Do not ever spawn more than 1 network thread.
[macgdbp.git] / Source / DebuggerConnection.m
1 /*
2 * MacGDBp
3 * Copyright (c) 2007 - 2010, Blue Static <http://www.bluestatic.org>
4 *
5 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU
6 * General Public License as published by the Free Software Foundation; either version 2 of the
7 * License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
10 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along with this program; if not,
14 * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
15 */
16
17 #import "DebuggerConnection.h"
18
19 #import <sys/socket.h>
20 #import <netinet/in.h>
21
22 #import "AppDelegate.h"
23 #import "LoggingController.h"
24
25 // DebuggerConnection (Private) ////////////////////////////////////////////////
26
27 @interface DebuggerConnection ()
28
29 @property (assign) CFSocketRef socket;
30 @property (assign) CFReadStreamRef readStream;
31 @property NSUInteger lastReadTransaction;
32 @property (retain) NSMutableString* currentPacket;
33 @property (assign) CFWriteStreamRef writeStream;
34 @property NSUInteger lastWrittenTransaction;
35 @property (retain) NSMutableArray* queuedWrites;
36
37 - (void)connectionThreadStart;
38
39 - (void)socketDidAccept;
40 - (void)socketDisconnected;
41 - (void)readStreamHasData;
42
43 - (void)performSend:(NSString*)command;
44 - (void)sendQueuedWrites;
45
46 - (void)performQuitSignal;
47
48 - (void)handleResponse:(NSXMLDocument*)response;
49 - (void)handlePacket:(NSString*)packet;
50
51 // Threadsafe wrappers for the delegate's methods.
52 - (void)errorEncountered:(NSString*)error;
53 - (LogEntry*)recordSend:(NSString*)command;
54 - (LogEntry*)recordReceive:(NSString*)command;
55
56 @end
57
58 // CFNetwork Callbacks /////////////////////////////////////////////////////////
59
60 void ReadStreamCallback(CFReadStreamRef stream, CFStreamEventType eventType, void* connectionRaw)
61 {
62 DebuggerConnection* connection = (DebuggerConnection*)connectionRaw;
63 switch (eventType)
64 {
65 case kCFStreamEventHasBytesAvailable:
66 [connection readStreamHasData];
67 break;
68
69 case kCFStreamEventErrorOccurred:
70 {
71 CFErrorRef error = CFReadStreamCopyError(stream);
72 CFReadStreamUnscheduleFromRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
73 CFReadStreamClose(stream);
74 CFRelease(stream);
75 [connection errorEncountered:[[(NSError*)error autorelease] description]];
76 break;
77 }
78
79 case kCFStreamEventEndEncountered:
80 CFReadStreamUnscheduleFromRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
81 CFReadStreamClose(stream);
82 CFRelease(stream);
83 [connection socketDisconnected];
84 break;
85 };
86 }
87
88 void WriteStreamCallback(CFWriteStreamRef stream, CFStreamEventType eventType, void* connectionRaw)
89 {
90 DebuggerConnection* connection = (DebuggerConnection*)connectionRaw;
91 switch (eventType)
92 {
93 case kCFStreamEventCanAcceptBytes:
94 [connection sendQueuedWrites];
95 break;
96
97 case kCFStreamEventErrorOccurred:
98 {
99 CFErrorRef error = CFWriteStreamCopyError(stream);
100 CFWriteStreamUnscheduleFromRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
101 CFWriteStreamClose(stream);
102 CFRelease(stream);
103 [connection errorEncountered:[[(NSError*)error autorelease] description]];
104 break;
105 }
106
107 case kCFStreamEventEndEncountered:
108 CFWriteStreamUnscheduleFromRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
109 CFWriteStreamClose(stream);
110 CFRelease(stream);
111 [connection socketDisconnected];
112 break;
113 }
114 }
115
116 void SocketAcceptCallback(CFSocketRef socket,
117 CFSocketCallBackType callbackType,
118 CFDataRef address,
119 const void* data,
120 void* connectionRaw)
121 {
122 assert(callbackType == kCFSocketAcceptCallBack);
123 NSLog(@"SocketAcceptCallback()");
124
125 DebuggerConnection* connection = (DebuggerConnection*)connectionRaw;
126
127 CFReadStreamRef readStream;
128 CFWriteStreamRef writeStream;
129
130 // Create the streams on the socket.
131 CFStreamCreatePairWithSocket(kCFAllocatorDefault,
132 *(CFSocketNativeHandle*)data, // Socket handle.
133 &readStream, // Read stream in-pointer.
134 &writeStream); // Write stream in-pointer.
135
136 // Create struct to register callbacks for the stream.
137 CFStreamClientContext context;
138 context.version = 0;
139 context.info = connection;
140 context.retain = NULL;
141 context.release = NULL;
142 context.copyDescription = NULL;
143
144 // Set the client of the read stream.
145 CFOptionFlags readFlags =
146 kCFStreamEventOpenCompleted |
147 kCFStreamEventHasBytesAvailable |
148 kCFStreamEventErrorOccurred |
149 kCFStreamEventEndEncountered;
150 if (CFReadStreamSetClient(readStream, readFlags, ReadStreamCallback, &context))
151 // Schedule in run loop to do asynchronous communication with the engine.
152 CFReadStreamScheduleWithRunLoop(readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
153 else
154 return;
155
156 // Open the stream now that it's scheduled on the run loop.
157 if (!CFReadStreamOpen(readStream))
158 {
159 CFStreamError error = CFReadStreamGetError(readStream);
160 NSLog(@"error! %@", error);
161 return;
162 }
163
164 // Set the client of the write stream.
165 CFOptionFlags writeFlags =
166 kCFStreamEventOpenCompleted |
167 kCFStreamEventCanAcceptBytes |
168 kCFStreamEventErrorOccurred |
169 kCFStreamEventEndEncountered;
170 if (CFWriteStreamSetClient(writeStream, writeFlags, WriteStreamCallback, &context))
171 // Schedule it in the run loop to receive error information.
172 CFWriteStreamScheduleWithRunLoop(writeStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
173 else
174 return;
175
176 // Open the write stream.
177 if (!CFWriteStreamOpen(writeStream))
178 {
179 CFStreamError error = CFWriteStreamGetError(writeStream);
180 NSLog(@"error! %@", error);
181 return;
182 }
183
184 connection.readStream = readStream;
185 connection.writeStream = writeStream;
186 [connection socketDidAccept];
187 }
188
189 // Other Run Loop Callbacks ////////////////////////////////////////////////////
190
191 void PerformQuitSignal(void* info)
192 {
193 DebuggerConnection* obj = (DebuggerConnection*)info;
194 [obj performQuitSignal];
195 }
196
197 ////////////////////////////////////////////////////////////////////////////////
198
199 @implementation DebuggerConnection
200
201 @synthesize port = port_;
202 @synthesize connected = connected_;
203 @synthesize delegate = delegate_;
204
205 @synthesize socket = socket_;
206 @synthesize readStream = readStream_;
207 @synthesize lastReadTransaction = lastReadTransaction_;
208 @synthesize currentPacket = currentPacket_;
209 @synthesize writeStream = writeStream_;
210 @synthesize lastWrittenTransaction = lastWrittenTransaction_;
211 @synthesize queuedWrites = queuedWrites_;
212
213 - (id)initWithPort:(NSUInteger)aPort
214 {
215 if (self = [super init])
216 {
217 port_ = aPort;
218 }
219 return self;
220 }
221
222 - (void)dealloc
223 {
224 self.currentPacket = nil;
225 [super dealloc];
226 }
227
228 /**
229 * Kicks off the socket on another thread.
230 */
231 - (void)connect
232 {
233 if (thread_ && !connected_) {
234 // A thread has been detached but the socket has yet to connect. Do not
235 // spawn a new thread otherwise multiple threads will be blocked on the same
236 // socket.
237 return;
238 }
239 [NSThread detachNewThreadSelector:@selector(connectionThreadStart) toTarget:self withObject:nil];
240 }
241
242 /**
243 * Creates, connects to, and schedules a CFSocket.
244 */
245 - (void)connectionThreadStart
246 {
247 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
248
249 thread_ = [NSThread currentThread];
250 runLoop_ = [NSRunLoop currentRunLoop];
251
252 // Pass ourselves to the callback so we don't have to use ugly globals.
253 CFSocketContext context;
254 context.version = 0;
255 context.info = self;
256 context.retain = NULL;
257 context.release = NULL;
258 context.copyDescription = NULL;
259
260 // Create the address structure.
261 struct sockaddr_in address;
262 memset(&address, 0, sizeof(address));
263 address.sin_len = sizeof(address);
264 address.sin_family = AF_INET;
265 address.sin_port = htons(port_);
266 address.sin_addr.s_addr = htonl(INADDR_ANY);
267
268 // Create the socket signature.
269 CFSocketSignature signature;
270 signature.protocolFamily = PF_INET;
271 signature.socketType = SOCK_STREAM;
272 signature.protocol = IPPROTO_TCP;
273 signature.address = (CFDataRef)[NSData dataWithBytes:&address length:sizeof(address)];
274
275 socket_ = CFSocketCreateWithSocketSignature(kCFAllocatorDefault,
276 &signature, // Socket signature.
277 kCFSocketAcceptCallBack, // Callback types.
278 SocketAcceptCallback, // Callout function pointer.
279 &context); // Context to pass to callout.
280 if (!socket_)
281 {
282 [self errorEncountered:@"Could not open socket."];
283 return;
284 }
285
286 // Allow old, yet-to-be recycled sockets to be reused.
287 BOOL yes = YES;
288 setsockopt(CFSocketGetNative(socket_), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(BOOL));
289
290 // Schedule the socket on the run loop.
291 CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket_, 0);
292 CFRunLoopAddSource([runLoop_ getCFRunLoop], source, kCFRunLoopCommonModes);
293 CFRelease(source);
294
295 // Create a source that is used to quit.
296 CFRunLoopSourceContext quitContext = { 0 };
297 quitContext.version = 0;
298 quitContext.info = self;
299 quitContext.perform = PerformQuitSignal;
300 quitSource_ = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &quitContext);
301 CFRunLoopAddSource([runLoop_ getCFRunLoop], quitSource_, kCFRunLoopCommonModes);
302
303 CFRunLoopRun();
304
305 thread_ = nil;
306 runLoop_ = nil;
307
308 CFRunLoopSourceInvalidate(quitSource_);
309 CFRelease(quitSource_);
310 quitSource_ = NULL;
311
312 [pool release];
313 }
314
315 /**
316 * Called by SocketWrapper after the connection is successful. This immediately calls
317 * -[SocketWrapper receive] to clear the way for communication, though the information
318 * could be useful server information that we don't use right now.
319 */
320 - (void)socketDidAccept
321 {
322 connected_ = YES;
323 transactionID = 1;
324 self.queuedWrites = [NSMutableArray array];
325 writeQueueLock_ = [NSRecursiveLock new];
326 }
327
328 /**
329 * Closes a socket and releases the ref.
330 */
331 - (void)close
332 {
333 if (thread_) {
334 [thread_ cancel];
335 }
336 if (runLoop_ && quitSource_) {
337 CFRunLoopSourceSignal(quitSource_);
338 CFRunLoopWakeUp([runLoop_ getCFRunLoop]);
339 }
340 }
341
342 /**
343 * Quits the run loop and stops the thread.
344 */
345 - (void)performQuitSignal
346 {
347 self.queuedWrites = nil;
348 connected_ = NO;
349 [writeQueueLock_ release];
350
351 if (runLoop_) {
352 CFRunLoopStop([runLoop_ getCFRunLoop]);
353 }
354
355 // The socket goes down, so do the streams, which clean themselves up.
356 if (socket_) {
357 CFSocketInvalidate(socket_);
358 CFRelease(socket_);
359 socket_ = NULL;
360 }
361 }
362
363 /**
364 * Notification that the socket disconnected.
365 */
366 - (void)socketDisconnected
367 {
368 if (connected_) {
369 // The state still is connected, which means that we did not get here
370 // through normal disconnected procedure (a call to |-close|, followed by
371 // the downing of the socket and the stream, which also produces this
372 // messsage). Instead, the stream callbacks encountered EOF unexpectedly.
373 [self close];
374 }
375 if ([delegate_ respondsToSelector:@selector(connectionDidClose:)])
376 [delegate_ connectionDidClose:self];
377 }
378
379 /**
380 * Writes a command into the write stream. If the stream is ready for writing,
381 * we do so immediately. If not, the command is queued and will be written
382 * when the stream is ready.
383 */
384 - (void)send:(NSString*)command
385 {
386 if (lastReadTransaction_ >= lastWrittenTransaction_ && CFWriteStreamCanAcceptBytes(writeStream_)) {
387 [self performSend:command];
388 } else {
389 [writeQueueLock_ lock];
390 [queuedWrites_ addObject:command];
391 [writeQueueLock_ unlock];
392 }
393 [self sendQueuedWrites];
394 }
395
396 /**
397 * This will send a command to the debugger engine. It will append the
398 * transaction ID automatically. It accepts a NSString command along with a
399 * a variable number of arguments to substitute into the command, a la
400 * +[NSString stringWithFormat:]. Returns the transaction ID as a NSNumber.
401 */
402 - (NSNumber*)sendCommandWithFormat:(NSString*)format, ...
403 {
404 // Collect varargs and format command.
405 va_list args;
406 va_start(args, format);
407 NSString* command = [[NSString alloc] initWithFormat:format arguments:args];
408 va_end(args);
409
410 NSNumber* callbackKey = [NSNumber numberWithInt:transactionID++];
411 NSString* taggedCommand = [NSString stringWithFormat:@"%@ -i %@", [command autorelease], callbackKey];
412 [self performSelector:@selector(send:)
413 onThread:thread_
414 withObject:taggedCommand
415 waitUntilDone:YES];
416
417 return callbackKey;
418 }
419
420 /**
421 * Given a file path, this returns a file:// URI and escapes any spaces for the
422 * debugger engine.
423 */
424 - (NSString*)escapedURIPath:(NSString*)path
425 {
426 // Custon GDBp paths are fine.
427 if ([[path substringToIndex:4] isEqualToString:@"gdbp"])
428 return path;
429
430 // Create a temporary URL that will escape all the nasty characters.
431 NSURL* url = [NSURL fileURLWithPath:path];
432 NSString* urlString = [url absoluteString];
433
434 // Remove the host because this is a file:// URL;
435 urlString = [urlString stringByReplacingOccurrencesOfString:[url host] withString:@""];
436
437 // Escape % for use in printf-style NSString formatters.
438 urlString = [urlString stringByReplacingOccurrencesOfString:@"%" withString:@"%%"];
439 return urlString;
440 }
441
442 /**
443 * Returns the transaction_id from an NSXMLDocument.
444 */
445 - (NSInteger)transactionIDFromResponse:(NSXMLDocument*)response
446 {
447 return [[[[response rootElement] attributeForName:@"transaction_id"] stringValue] intValue];
448 }
449
450 /**
451 * Scans a command string for the transaction ID component. If it is not found,
452 * returns NSNotFound.
453 */
454 - (NSInteger)transactionIDFromCommand:(NSString*)command
455 {
456 NSRange occurrence = [command rangeOfString:@"-i "];
457 if (occurrence.location == NSNotFound)
458 return NSNotFound;
459 NSString* transaction = [command substringFromIndex:occurrence.location + occurrence.length];
460 return [transaction intValue];
461 }
462
463 // Private /////////////////////////////////////////////////////////////////////
464 #pragma mark Private
465
466 // Delegate Thread-Safe Wrappers ///////////////////////////////////////////////
467
468 /**
469 * Receives errors from the SocketWrapper and updates the display
470 */
471 - (void)errorEncountered:(NSString*)error
472 {
473 if (![delegate_ respondsToSelector:@selector(errorEncountered:)])
474 return;
475 [delegate_ performSelectorOnMainThread:@selector(errorEncountered:)
476 withObject:error
477 waitUntilDone:NO];
478 }
479
480 - (LogEntry*)recordSend:(NSString*)command
481 {
482 LoggingController* logger = [[AppDelegate instance] loggingController];
483 LogEntry* entry = [LogEntry newSendEntry:command];
484 entry.lastReadTransactionID = lastReadTransaction_;
485 entry.lastWrittenTransactionID = lastWrittenTransaction_;
486 [logger performSelectorOnMainThread:@selector(recordEntry:)
487 withObject:entry
488 waitUntilDone:NO];
489 return [entry autorelease];
490 }
491
492 - (LogEntry*)recordReceive:(NSString*)command
493 {
494 LoggingController* logger = [[AppDelegate instance] loggingController];
495 LogEntry* entry = [LogEntry newReceiveEntry:command];
496 entry.lastReadTransactionID = lastReadTransaction_;
497 entry.lastWrittenTransactionID = lastWrittenTransaction_;
498 [logger performSelectorOnMainThread:@selector(recordEntry:)
499 withObject:entry
500 waitUntilDone:NO];
501 return [entry autorelease];
502 }
503
504 // Stream Managers /////////////////////////////////////////////////////////////
505
506 /**
507 * Callback from the CFReadStream that there is data waiting to be read.
508 */
509 - (void)readStreamHasData
510 {
511 const NSUInteger kBufferSize = 1024;
512 UInt8 buffer[kBufferSize];
513 CFIndex bufferOffset = 0; // Starting point in |buffer| to work with.
514 CFIndex bytesRead = CFReadStreamRead(readStream_, buffer, kBufferSize);
515 const char* charBuffer = (const char*)buffer;
516
517 // The read loop works by going through the buffer until all the bytes have
518 // been processed.
519 while (bufferOffset < bytesRead)
520 {
521 // Find the NULL separator, or the end of the string.
522 NSUInteger partLength = 0;
523 for (NSUInteger i = bufferOffset; i < bytesRead && charBuffer[i] != '\0'; ++i, ++partLength) ;
524
525 // If there is not a current packet, set some state.
526 if (!self.currentPacket)
527 {
528 // Read the message header: the size. This will be |partLength| bytes.
529 packetSize_ = atoi(charBuffer + bufferOffset);
530 currentPacketIndex_ = 0;
531 self.currentPacket = [NSMutableString stringWithCapacity:packetSize_];
532 bufferOffset += partLength + 1; // Pass over the NULL byte.
533 continue; // Spin the loop to begin reading actual data.
534 }
535
536 // Substring the byte stream and append it to the packet string.
537 CFStringRef bufferString = CFStringCreateWithBytes(kCFAllocatorDefault,
538 buffer + bufferOffset, // Byte pointer, offset by start index.
539 partLength, // Length.
540 kCFStringEncodingUTF8,
541 true);
542 [self.currentPacket appendString:(NSString*)bufferString];
543 CFRelease(bufferString);
544
545 // Advance counters.
546 currentPacketIndex_ += partLength;
547 bufferOffset += partLength + 1;
548
549 // If this read finished the packet, handle it and reset.
550 if (currentPacketIndex_ >= packetSize_)
551 {
552 [self handlePacket:[[currentPacket_ retain] autorelease]];
553 self.currentPacket = nil;
554 packetSize_ = 0;
555 currentPacketIndex_ = 0;
556 }
557 }
558 }
559
560 /**
561 * Performs the packet handling of a raw string XML packet. From this point on,
562 * the packets are associated with a transaction and are then dispatched.
563 */
564 - (void)handlePacket:(NSString*)packet
565 {
566 // Test if we can convert it into an NSXMLDocument.
567 NSError* error = nil;
568 NSXMLDocument* xmlTest = [[NSXMLDocument alloc] initWithXMLString:currentPacket_ options:NSXMLDocumentTidyXML error:&error];
569
570 // Try to recover if we encountered an error.
571 if (!xmlTest)
572 {
573 // We do not want to starve the write queue, so manually parse out the
574 // transaction ID.
575 NSRange location = [currentPacket_ rangeOfString:@"transaction_id"];
576 if (location.location != NSNotFound)
577 {
578 NSUInteger start = location.location + location.length;
579 NSUInteger end = start;
580
581 NSCharacterSet* numericSet = [NSCharacterSet decimalDigitCharacterSet];
582
583 // Loop over the characters after the attribute name to extract the ID.
584 while (end < [currentPacket_ length])
585 {
586 unichar c = [currentPacket_ characterAtIndex:end];
587 if ([numericSet characterIsMember:c])
588 {
589 // If this character is numeric, extend the range to substring.
590 ++end;
591 }
592 else
593 {
594 if (start == end)
595 {
596 // If this character is nonnumeric and we have nothing in the
597 // range, skip this character.
598 ++start;
599 ++end;
600 }
601 else
602 {
603 // We've moved past the numeric ID so we should stop searching.
604 break;
605 }
606 }
607 }
608
609 // If we were able to extract the transaction ID, update the last read.
610 NSRange substringRange = NSMakeRange(start, end - start);
611 NSString* transactionStr = [currentPacket_ substringWithRange:substringRange];
612 if ([transactionStr length])
613 lastReadTransaction_ = [transactionStr intValue];
614 }
615
616 // Otherwise, assume +1 and hope it works.
617 ++lastReadTransaction_;
618 }
619 else
620 {
621 // See if the transaction can be parsed out.
622 NSInteger transaction = [self transactionIDFromResponse:xmlTest];
623 if (transaction < lastReadTransaction_)
624 {
625 NSLog(@"tx = %d vs %d", transaction, lastReadTransaction_);
626 NSLog(@"out of date transaction %@", packet);
627 return;
628 }
629
630 if (transaction != lastWrittenTransaction_)
631 NSLog(@"txn %d <> %d last written, %d last read", transaction, lastWrittenTransaction_, lastReadTransaction_);
632
633 lastReadTransaction_ = transaction;
634 }
635
636 // Log this receive event.
637 LogEntry* log = [self recordReceive:currentPacket_];
638 log.error = error;
639
640 // Finally, dispatch the handler for this response.
641 [self handleResponse:[xmlTest autorelease]];
642 }
643
644 - (void)handleResponse:(NSXMLDocument*)response
645 {
646 // Check and see if there's an error.
647 NSArray* error = [[response rootElement] elementsForName:@"error"];
648 if ([error count] > 0)
649 {
650 NSLog(@"Xdebug error: %@", error);
651 NSString* errorMessage = [[[[error objectAtIndex:0] children] objectAtIndex:0] stringValue];
652 [self errorEncountered:errorMessage];
653 }
654
655 if ([[[response rootElement] name] isEqualToString:@"init"])
656 {
657 [delegate_ performSelectorOnMainThread:@selector(handleInitialResponse:)
658 withObject:response
659 waitUntilDone:NO];
660 return;
661 }
662
663 if ([delegate_ respondsToSelector:@selector(handleResponse:)])
664 [delegate_ performSelectorOnMainThread:@selector(handleResponse:)
665 withObject:response
666 waitUntilDone:NO];
667
668 [self sendQueuedWrites];
669 }
670
671 /**
672 * This performs a blocking send. This should ONLY be called when we know we
673 * have write access to the stream. We will busy wait in case we don't do a full
674 * send.
675 */
676 - (void)performSend:(NSString*)command
677 {
678 // If this is an out-of-date transaction, do not bother sending it.
679 NSInteger transaction = [self transactionIDFromCommand:command];
680 if (transaction != NSNotFound && transaction < lastWrittenTransaction_)
681 return;
682
683 BOOL done = NO;
684
685 char* string = (char*)[command UTF8String];
686 int stringLength = strlen(string);
687
688 // Busy wait while writing. BAADD. Should background this operation.
689 while (!done)
690 {
691 if (CFWriteStreamCanAcceptBytes(writeStream_))
692 {
693 // Include the NULL byte in the string when we write.
694 int bytesWritten = CFWriteStreamWrite(writeStream_, (UInt8*)string, stringLength + 1);
695 if (bytesWritten < 0)
696 {
697 NSLog(@"write error");
698 }
699 // Incomplete write.
700 else if (bytesWritten < strlen(string))
701 {
702 // Adjust the buffer and wait for another chance to write.
703 stringLength -= bytesWritten;
704 memmove(string, string + bytesWritten, stringLength);
705 }
706 else
707 {
708 done = YES;
709
710 // We need to scan the string to find the transactionID.
711 if (transaction == NSNotFound)
712 {
713 NSLog(@"sent %@ without a transaction ID", command);
714 continue;
715 }
716 lastWrittenTransaction_ = transaction;
717 }
718 }
719 }
720
721 // Log this trancation.
722 [self recordSend:command];
723 }
724
725 /**
726 * Checks if there are unsent commands in the |queuedWrites_| queue and sends
727 * them if it's OK to do so. This will not block.
728 */
729 - (void)sendQueuedWrites
730 {
731 if (!connected_)
732 return;
733
734 [writeQueueLock_ lock];
735 if (lastReadTransaction_ >= lastWrittenTransaction_ && [queuedWrites_ count] > 0)
736 {
737 NSString* command = [queuedWrites_ objectAtIndex:0];
738
739 // We don't want to block because this is called from the main thread.
740 // |-performSend:| busy waits when the stream is not ready. Bail out
741 // before we do that becuase busy waiting is BAD.
742 if (CFWriteStreamCanAcceptBytes(writeStream_))
743 {
744 [self performSend:command];
745 [queuedWrites_ removeObjectAtIndex:0];
746 }
747 }
748 [writeQueueLock_ unlock];
749 }
750
751 @end