Add a quit source to the DebuggerConnection's run loop to properly handle closing.
[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 [NSThread detachNewThreadSelector:@selector(connectionThreadStart) toTarget:self withObject:nil];
234 }
235
236 /**
237 * Creates, connects to, and schedules a CFSocket.
238 */
239 - (void)connectionThreadStart
240 {
241 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
242
243 thread_ = [NSThread currentThread];
244 runLoop_ = [NSRunLoop currentRunLoop];
245
246 // Pass ourselves to the callback so we don't have to use ugly globals.
247 CFSocketContext context;
248 context.version = 0;
249 context.info = self;
250 context.retain = NULL;
251 context.release = NULL;
252 context.copyDescription = NULL;
253
254 // Create the address structure.
255 struct sockaddr_in address;
256 memset(&address, 0, sizeof(address));
257 address.sin_len = sizeof(address);
258 address.sin_family = AF_INET;
259 address.sin_port = htons(port_);
260 address.sin_addr.s_addr = htonl(INADDR_ANY);
261
262 // Create the socket signature.
263 CFSocketSignature signature;
264 signature.protocolFamily = PF_INET;
265 signature.socketType = SOCK_STREAM;
266 signature.protocol = IPPROTO_TCP;
267 signature.address = (CFDataRef)[NSData dataWithBytes:&address length:sizeof(address)];
268
269 socket_ = CFSocketCreateWithSocketSignature(kCFAllocatorDefault,
270 &signature, // Socket signature.
271 kCFSocketAcceptCallBack, // Callback types.
272 SocketAcceptCallback, // Callout function pointer.
273 &context); // Context to pass to callout.
274 if (!socket_)
275 {
276 [self errorEncountered:@"Could not open socket."];
277 return;
278 }
279
280 // Allow old, yet-to-be recycled sockets to be reused.
281 BOOL yes = YES;
282 setsockopt(CFSocketGetNative(socket_), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(BOOL));
283
284 // Schedule the socket on the run loop.
285 CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket_, 0);
286 CFRunLoopAddSource([runLoop_ getCFRunLoop], source, kCFRunLoopCommonModes);
287 CFRelease(source);
288
289 // Create a source that is used to quit.
290 CFRunLoopSourceContext quitContext = { 0 };
291 quitContext.version = 0;
292 quitContext.info = self;
293 quitContext.perform = PerformQuitSignal;
294 quitSource_ = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &quitContext);
295 CFRunLoopAddSource([runLoop_ getCFRunLoop], quitSource_, kCFRunLoopCommonModes);
296
297 [runLoop_ run];
298
299 thread_ = nil;
300 runLoop_ = nil;
301
302 CFRunLoopSourceInvalidate(quitSource_);
303 CFRelease(quitSource_);
304 quitSource_ = NULL;
305
306 [pool release];
307 }
308
309 /**
310 * Called by SocketWrapper after the connection is successful. This immediately calls
311 * -[SocketWrapper receive] to clear the way for communication, though the information
312 * could be useful server information that we don't use right now.
313 */
314 - (void)socketDidAccept
315 {
316 connected_ = YES;
317 transactionID = 1;
318 self.queuedWrites = [NSMutableArray array];
319 writeQueueLock_ = [NSRecursiveLock new];
320 }
321
322 /**
323 * Closes a socket and releases the ref.
324 */
325 - (void)close
326 {
327 if (runLoop_ && quitSource_) {
328 CFRunLoopSourceSignal(quitSource_);
329 CFRunLoopWakeUp([runLoop_ getCFRunLoop]);
330 }
331 }
332
333 /**
334 * Quits the run loop and stops the thread.
335 */
336 - (void)performQuitSignal
337 {
338 if (runLoop_) {
339 CFRunLoopStop([runLoop_ getCFRunLoop]);
340 }
341
342 // The socket goes down, so do the streams, which clean themselves up.
343 if (socket_) {
344 CFSocketInvalidate(socket_);
345 CFRelease(socket_);
346 socket_ = NULL;
347 }
348
349 self.queuedWrites = nil;
350 connected_ = NO;
351 [writeQueueLock_ release];
352 }
353
354 /**
355 * Notification that the socket disconnected.
356 */
357 - (void)socketDisconnected
358 {
359 if (connected_) {
360 // The state still is connected, which means that we did not get here
361 // through normal disconnected procedure (a call to |-close|, followed by
362 // the downing of the socket and the stream, which also produces this
363 // messsage). Instead, the stream callbacks encountered EOF unexpectedly.
364 [self close];
365 }
366 if ([delegate_ respondsToSelector:@selector(connectionDidClose:)])
367 [delegate_ connectionDidClose:self];
368 }
369
370 /**
371 * Writes a command into the write stream. If the stream is ready for writing,
372 * we do so immediately. If not, the command is queued and will be written
373 * when the stream is ready.
374 */
375 - (void)send:(NSString*)command
376 {
377 if (lastReadTransaction_ >= lastWrittenTransaction_ && CFWriteStreamCanAcceptBytes(writeStream_)) {
378 [self performSend:command];
379 } else {
380 [writeQueueLock_ lock];
381 [queuedWrites_ addObject:command];
382 [writeQueueLock_ unlock];
383 }
384 [self sendQueuedWrites];
385 }
386
387 /**
388 * This will send a command to the debugger engine. It will append the
389 * transaction ID automatically. It accepts a NSString command along with a
390 * a variable number of arguments to substitute into the command, a la
391 * +[NSString stringWithFormat:]. Returns the transaction ID as a NSNumber.
392 */
393 - (NSNumber*)sendCommandWithFormat:(NSString*)format, ...
394 {
395 // Collect varargs and format command.
396 va_list args;
397 va_start(args, format);
398 NSString* command = [[NSString alloc] initWithFormat:format arguments:args];
399 va_end(args);
400
401 NSNumber* callbackKey = [NSNumber numberWithInt:transactionID++];
402 NSString* taggedCommand = [NSString stringWithFormat:@"%@ -i %@", [command autorelease], callbackKey];
403 [self performSelector:@selector(send:)
404 onThread:thread_
405 withObject:taggedCommand
406 waitUntilDone:YES];
407
408 return callbackKey;
409 }
410
411 /**
412 * Given a file path, this returns a file:// URI and escapes any spaces for the
413 * debugger engine.
414 */
415 - (NSString*)escapedURIPath:(NSString*)path
416 {
417 // Custon GDBp paths are fine.
418 if ([[path substringToIndex:4] isEqualToString:@"gdbp"])
419 return path;
420
421 // Create a temporary URL that will escape all the nasty characters.
422 NSURL* url = [NSURL fileURLWithPath:path];
423 NSString* urlString = [url absoluteString];
424
425 // Remove the host because this is a file:// URL;
426 urlString = [urlString stringByReplacingOccurrencesOfString:[url host] withString:@""];
427
428 // Escape % for use in printf-style NSString formatters.
429 urlString = [urlString stringByReplacingOccurrencesOfString:@"%" withString:@"%%"];
430 return urlString;
431 }
432
433 /**
434 * Returns the transaction_id from an NSXMLDocument.
435 */
436 - (NSInteger)transactionIDFromResponse:(NSXMLDocument*)response
437 {
438 return [[[[response rootElement] attributeForName:@"transaction_id"] stringValue] intValue];
439 }
440
441 /**
442 * Scans a command string for the transaction ID component. If it is not found,
443 * returns NSNotFound.
444 */
445 - (NSInteger)transactionIDFromCommand:(NSString*)command
446 {
447 NSRange occurrence = [command rangeOfString:@"-i "];
448 if (occurrence.location == NSNotFound)
449 return NSNotFound;
450 NSString* transaction = [command substringFromIndex:occurrence.location + occurrence.length];
451 return [transaction intValue];
452 }
453
454 // Private /////////////////////////////////////////////////////////////////////
455 #pragma mark Private
456
457 // Delegate Thread-Safe Wrappers ///////////////////////////////////////////////
458
459 /**
460 * Receives errors from the SocketWrapper and updates the display
461 */
462 - (void)errorEncountered:(NSString*)error
463 {
464 if (![delegate_ respondsToSelector:@selector(errorEncountered:)])
465 return;
466 [delegate_ performSelectorOnMainThread:@selector(errorEncountered:)
467 withObject:error
468 waitUntilDone:NO];
469 }
470
471 - (LogEntry*)recordSend:(NSString*)command
472 {
473 LoggingController* logger = [[AppDelegate instance] loggingController];
474 LogEntry* entry = [LogEntry newSendEntry:command];
475 entry.lastReadTransactionID = lastReadTransaction_;
476 entry.lastWrittenTransactionID = lastWrittenTransaction_;
477 [logger performSelectorOnMainThread:@selector(recordEntry:)
478 withObject:entry
479 waitUntilDone:NO];
480 return [entry autorelease];
481 }
482
483 - (LogEntry*)recordReceive:(NSString*)command
484 {
485 LoggingController* logger = [[AppDelegate instance] loggingController];
486 LogEntry* entry = [LogEntry newReceiveEntry:command];
487 entry.lastReadTransactionID = lastReadTransaction_;
488 entry.lastWrittenTransactionID = lastWrittenTransaction_;
489 [logger performSelectorOnMainThread:@selector(recordEntry:)
490 withObject:entry
491 waitUntilDone:NO];
492 return [entry autorelease];
493 }
494
495 // Stream Managers /////////////////////////////////////////////////////////////
496
497 /**
498 * Callback from the CFReadStream that there is data waiting to be read.
499 */
500 - (void)readStreamHasData
501 {
502 const NSUInteger kBufferSize = 1024;
503 UInt8 buffer[kBufferSize];
504 CFIndex bufferOffset = 0; // Starting point in |buffer| to work with.
505 CFIndex bytesRead = CFReadStreamRead(readStream_, buffer, kBufferSize);
506 const char* charBuffer = (const char*)buffer;
507
508 // The read loop works by going through the buffer until all the bytes have
509 // been processed.
510 while (bufferOffset < bytesRead)
511 {
512 // Find the NULL separator, or the end of the string.
513 NSUInteger partLength = 0;
514 for (NSUInteger i = bufferOffset; i < bytesRead && charBuffer[i] != '\0'; ++i, ++partLength) ;
515
516 // If there is not a current packet, set some state.
517 if (!self.currentPacket)
518 {
519 // Read the message header: the size. This will be |partLength| bytes.
520 packetSize_ = atoi(charBuffer + bufferOffset);
521 currentPacketIndex_ = 0;
522 self.currentPacket = [NSMutableString stringWithCapacity:packetSize_];
523 bufferOffset += partLength + 1; // Pass over the NULL byte.
524 continue; // Spin the loop to begin reading actual data.
525 }
526
527 // Substring the byte stream and append it to the packet string.
528 CFStringRef bufferString = CFStringCreateWithBytes(kCFAllocatorDefault,
529 buffer + bufferOffset, // Byte pointer, offset by start index.
530 partLength, // Length.
531 kCFStringEncodingUTF8,
532 true);
533 [self.currentPacket appendString:(NSString*)bufferString];
534 CFRelease(bufferString);
535
536 // Advance counters.
537 currentPacketIndex_ += partLength;
538 bufferOffset += partLength + 1;
539
540 // If this read finished the packet, handle it and reset.
541 if (currentPacketIndex_ >= packetSize_)
542 {
543 [self handlePacket:[[currentPacket_ retain] autorelease]];
544 self.currentPacket = nil;
545 packetSize_ = 0;
546 currentPacketIndex_ = 0;
547 }
548 }
549 }
550
551 /**
552 * Performs the packet handling of a raw string XML packet. From this point on,
553 * the packets are associated with a transaction and are then dispatched.
554 */
555 - (void)handlePacket:(NSString*)packet
556 {
557 // Test if we can convert it into an NSXMLDocument.
558 NSError* error = nil;
559 NSXMLDocument* xmlTest = [[NSXMLDocument alloc] initWithXMLString:currentPacket_ options:NSXMLDocumentTidyXML error:&error];
560
561 // Try to recover if we encountered an error.
562 if (!xmlTest)
563 {
564 // We do not want to starve the write queue, so manually parse out the
565 // transaction ID.
566 NSRange location = [currentPacket_ rangeOfString:@"transaction_id"];
567 if (location.location != NSNotFound)
568 {
569 NSUInteger start = location.location + location.length;
570 NSUInteger end = start;
571
572 NSCharacterSet* numericSet = [NSCharacterSet decimalDigitCharacterSet];
573
574 // Loop over the characters after the attribute name to extract the ID.
575 while (end < [currentPacket_ length])
576 {
577 unichar c = [currentPacket_ characterAtIndex:end];
578 if ([numericSet characterIsMember:c])
579 {
580 // If this character is numeric, extend the range to substring.
581 ++end;
582 }
583 else
584 {
585 if (start == end)
586 {
587 // If this character is nonnumeric and we have nothing in the
588 // range, skip this character.
589 ++start;
590 ++end;
591 }
592 else
593 {
594 // We've moved past the numeric ID so we should stop searching.
595 break;
596 }
597 }
598 }
599
600 // If we were able to extract the transaction ID, update the last read.
601 NSRange substringRange = NSMakeRange(start, end - start);
602 NSString* transactionStr = [currentPacket_ substringWithRange:substringRange];
603 if ([transactionStr length])
604 lastReadTransaction_ = [transactionStr intValue];
605 }
606
607 // Otherwise, assume +1 and hope it works.
608 ++lastReadTransaction_;
609 }
610 else
611 {
612 // See if the transaction can be parsed out.
613 NSInteger transaction = [self transactionIDFromResponse:xmlTest];
614 if (transaction < lastReadTransaction_)
615 {
616 NSLog(@"tx = %d vs %d", transaction, lastReadTransaction_);
617 NSLog(@"out of date transaction %@", packet);
618 return;
619 }
620
621 if (transaction != lastWrittenTransaction_)
622 NSLog(@"txn %d <> %d last written, %d last read", transaction, lastWrittenTransaction_, lastReadTransaction_);
623
624 lastReadTransaction_ = transaction;
625 }
626
627 // Log this receive event.
628 LogEntry* log = [self recordReceive:currentPacket_];
629 log.error = error;
630
631 // Finally, dispatch the handler for this response.
632 [self handleResponse:[xmlTest autorelease]];
633 }
634
635 - (void)handleResponse:(NSXMLDocument*)response
636 {
637 // Check and see if there's an error.
638 NSArray* error = [[response rootElement] elementsForName:@"error"];
639 if ([error count] > 0)
640 {
641 NSLog(@"Xdebug error: %@", error);
642 NSString* errorMessage = [[[[error objectAtIndex:0] children] objectAtIndex:0] stringValue];
643 [self errorEncountered:errorMessage];
644 }
645
646 if ([[[response rootElement] name] isEqualToString:@"init"])
647 {
648 [delegate_ performSelectorOnMainThread:@selector(handleInitialResponse:)
649 withObject:response
650 waitUntilDone:NO];
651 return;
652 }
653
654 if ([delegate_ respondsToSelector:@selector(handleResponse:)])
655 [delegate_ performSelectorOnMainThread:@selector(handleResponse:)
656 withObject:response
657 waitUntilDone:NO];
658
659 [self sendQueuedWrites];
660 }
661
662 /**
663 * This performs a blocking send. This should ONLY be called when we know we
664 * have write access to the stream. We will busy wait in case we don't do a full
665 * send.
666 */
667 - (void)performSend:(NSString*)command
668 {
669 // If this is an out-of-date transaction, do not bother sending it.
670 NSInteger transaction = [self transactionIDFromCommand:command];
671 if (transaction != NSNotFound && transaction < lastWrittenTransaction_)
672 return;
673
674 BOOL done = NO;
675
676 char* string = (char*)[command UTF8String];
677 int stringLength = strlen(string);
678
679 // Busy wait while writing. BAADD. Should background this operation.
680 while (!done)
681 {
682 if (CFWriteStreamCanAcceptBytes(writeStream_))
683 {
684 // Include the NULL byte in the string when we write.
685 int bytesWritten = CFWriteStreamWrite(writeStream_, (UInt8*)string, stringLength + 1);
686 if (bytesWritten < 0)
687 {
688 NSLog(@"write error");
689 }
690 // Incomplete write.
691 else if (bytesWritten < strlen(string))
692 {
693 // Adjust the buffer and wait for another chance to write.
694 stringLength -= bytesWritten;
695 memmove(string, string + bytesWritten, stringLength);
696 }
697 else
698 {
699 done = YES;
700
701 // We need to scan the string to find the transactionID.
702 if (transaction == NSNotFound)
703 {
704 NSLog(@"sent %@ without a transaction ID", command);
705 continue;
706 }
707 lastWrittenTransaction_ = transaction;
708 }
709 }
710 }
711
712 // Log this trancation.
713 [self recordSend:command];
714 }
715
716 /**
717 * Checks if there are unsent commands in the |queuedWrites_| queue and sends
718 * them if it's OK to do so. This will not block.
719 */
720 - (void)sendQueuedWrites
721 {
722 if (!connected_)
723 return;
724
725 [writeQueueLock_ lock];
726 if (lastReadTransaction_ >= lastWrittenTransaction_ && [queuedWrites_ count] > 0)
727 {
728 NSString* command = [queuedWrites_ objectAtIndex:0];
729
730 // We don't want to block because this is called from the main thread.
731 // |-performSend:| busy waits when the stream is not ready. Bail out
732 // before we do that becuase busy waiting is BAD.
733 if (CFWriteStreamCanAcceptBytes(writeStream_))
734 {
735 [self performSend:command];
736 [queuedWrites_ removeObjectAtIndex:0];
737 }
738 }
739 [writeQueueLock_ unlock];
740 }
741
742 @end