3 * Copyright (c) 2007 - 2010, Blue Static <http://www.bluestatic.org>
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.
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.
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
17 #import "DebuggerConnection.h"
19 #import <sys/socket.h>
20 #import <netinet/in.h>
22 #import "AppDelegate.h"
23 #import "LoggingController.h"
25 // DebuggerConnection (Private) ////////////////////////////////////////////////
27 @interface DebuggerConnection ()
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
;
37 - (void)runNetworkThread
;
39 - (void)socketDidAccept
;
40 - (void)socketDisconnected
;
41 - (void)readStreamHasData
;
43 - (void)performSend
:(NSString
*)command
;
44 - (void)sendQueuedWrites
;
46 - (void)performQuitSignal
;
48 - (void)handleResponse
:(NSXMLDocument
*)response
;
49 - (void)handlePacket
:(NSString
*)packet
;
51 // Threadsafe wrappers for the delegate's methods.
52 - (void)errorEncountered
:(NSString
*)error
;
53 - (LogEntry
*)recordSend
:(NSString
*)command
;
54 - (LogEntry
*)recordReceive
:(NSString
*)command
;
58 // CFNetwork Callbacks /////////////////////////////////////////////////////////
60 void ReadStreamCallback(CFReadStreamRef stream
, CFStreamEventType eventType
, void* connectionRaw
)
62 DebuggerConnection
* connection
= (DebuggerConnection
*)connectionRaw
;
65 case kCFStreamEventHasBytesAvailable
:
66 [connection readStreamHasData
];
69 case kCFStreamEventErrorOccurred
:
71 CFErrorRef error
= CFReadStreamCopyError(stream
);
72 CFReadStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
73 CFReadStreamClose(stream
);
75 [connection errorEncountered
:[[(NSError
*)error autorelease
] description
]];
79 case kCFStreamEventEndEncountered
:
80 CFReadStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
81 CFReadStreamClose(stream
);
83 [connection socketDisconnected
];
88 void WriteStreamCallback(CFWriteStreamRef stream
, CFStreamEventType eventType
, void* connectionRaw
)
90 DebuggerConnection
* connection
= (DebuggerConnection
*)connectionRaw
;
93 case kCFStreamEventCanAcceptBytes
:
94 [connection sendQueuedWrites
];
97 case kCFStreamEventErrorOccurred
:
99 CFErrorRef error
= CFWriteStreamCopyError(stream
);
100 CFWriteStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
101 CFWriteStreamClose(stream
);
103 [connection errorEncountered
:[[(NSError
*)error autorelease
] description
]];
107 case kCFStreamEventEndEncountered
:
108 CFWriteStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
109 CFWriteStreamClose(stream
);
111 [connection socketDisconnected
];
116 void SocketAcceptCallback(CFSocketRef socket
,
117 CFSocketCallBackType callbackType
,
122 assert(callbackType
== kCFSocketAcceptCallBack
);
123 DebuggerConnection
* connection
= (DebuggerConnection
*)connectionRaw
;
125 CFReadStreamRef readStream
;
126 CFWriteStreamRef writeStream
;
128 // Create the streams on the socket.
129 CFStreamCreatePairWithSocket(kCFAllocatorDefault
,
130 *(CFSocketNativeHandle
*)data
, // Socket handle.
131 &readStream
, // Read stream in-pointer.
132 &writeStream
); // Write stream in-pointer.
134 // Create struct to register callbacks for the stream.
135 CFStreamClientContext context
;
137 context.info
= connection
;
138 context.retain
= NULL
;
139 context.release
= NULL
;
140 context.copyDescription
= NULL
;
142 // Set the client of the read stream.
143 CFOptionFlags readFlags
=
144 kCFStreamEventOpenCompleted |
145 kCFStreamEventHasBytesAvailable |
146 kCFStreamEventErrorOccurred |
147 kCFStreamEventEndEncountered
;
148 if (CFReadStreamSetClient(readStream
, readFlags
, ReadStreamCallback
, &context
))
149 // Schedule in run loop to do asynchronous communication with the engine.
150 CFReadStreamScheduleWithRunLoop(readStream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
154 // Open the stream now that it's scheduled on the run loop.
155 if (!CFReadStreamOpen(readStream
))
157 CFStreamError error
= CFReadStreamGetError(readStream
);
158 NSLog(@
"error! %@", error
);
162 // Set the client of the write stream.
163 CFOptionFlags writeFlags
=
164 kCFStreamEventOpenCompleted |
165 kCFStreamEventCanAcceptBytes |
166 kCFStreamEventErrorOccurred |
167 kCFStreamEventEndEncountered
;
168 if (CFWriteStreamSetClient(writeStream
, writeFlags
, WriteStreamCallback
, &context
))
169 // Schedule it in the run loop to receive error information.
170 CFWriteStreamScheduleWithRunLoop(writeStream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
174 // Open the write stream.
175 if (!CFWriteStreamOpen(writeStream
))
177 CFStreamError error
= CFWriteStreamGetError(writeStream
);
178 NSLog(@
"error! %@", error
);
182 connection.readStream
= readStream
;
183 connection.writeStream
= writeStream
;
184 [connection socketDidAccept
];
187 // Other Run Loop Callbacks ////////////////////////////////////////////////////
189 void PerformQuitSignal(void* info
)
191 DebuggerConnection
* obj
= (DebuggerConnection
*)info
;
192 [obj performQuitSignal
];
195 ////////////////////////////////////////////////////////////////////////////////
197 @implementation DebuggerConnection
199 @synthesize port
= port_
;
200 @synthesize connected
= connected_
;
201 @synthesize delegate
= delegate_
;
203 @synthesize socket
= socket_
;
204 @synthesize readStream
= readStream_
;
205 @synthesize lastReadTransaction
= lastReadTransaction_
;
206 @synthesize currentPacket
= currentPacket_
;
207 @synthesize writeStream
= writeStream_
;
208 @synthesize lastWrittenTransaction
= lastWrittenTransaction_
;
209 @synthesize queuedWrites
= queuedWrites_
;
211 - (id)initWithPort
:(NSUInteger
)aPort
213 if (self = [super init
])
222 self.currentPacket
= nil;
227 * Kicks off the socket on another thread.
231 if (thread_
&& !connected_
) {
232 // A thread has been detached but the socket has yet to connect. Do not
233 // spawn a new thread otherwise multiple threads will be blocked on the same
237 [NSThread detachNewThreadSelector
:@selector(runNetworkThread
) toTarget
:self withObject
:nil];
241 * Creates, connects to, and schedules a CFSocket.
243 - (void)runNetworkThread
245 NSAutoreleasePool
* pool
= [[NSAutoreleasePool alloc
] init
];
247 thread_
= [NSThread currentThread
];
248 runLoop_
= [NSRunLoop currentRunLoop
];
250 // Pass ourselves to the callback so we don't have to use ugly globals.
251 CFSocketContext context
;
254 context.retain
= NULL
;
255 context.release
= NULL
;
256 context.copyDescription
= NULL
;
258 // Create the address structure.
259 struct sockaddr_in address
;
260 memset(&address
, 0, sizeof(address
));
261 address.sin_len
= sizeof(address
);
262 address.sin_family
= AF_INET
;
263 address.sin_port
= htons(port_
);
264 address.sin_addr.s_addr
= htonl(INADDR_ANY
);
266 // Create the socket signature.
267 CFSocketSignature signature
;
268 signature.protocolFamily
= PF_INET
;
269 signature.socketType
= SOCK_STREAM
;
270 signature.protocol
= IPPROTO_TCP
;
271 signature.address
= (CFDataRef
)[NSData dataWithBytes
:&address length
:sizeof(address
)];
274 socket_
= CFSocketCreateWithSocketSignature(kCFAllocatorDefault
,
275 &signature
, // Socket signature.
276 kCFSocketAcceptCallBack
, // Callback types.
277 SocketAcceptCallback
, // Callout function pointer.
278 &context
); // Context to pass to callout.
280 [self errorEncountered
:@
"Could not open socket."];
285 // Allow old, yet-to-be recycled sockets to be reused.
287 setsockopt(CFSocketGetNative(socket_
), SOL_SOCKET
, SO_REUSEADDR
, &yes
, sizeof(BOOL));
288 setsockopt(CFSocketGetNative(socket_
), SOL_SOCKET
, SO_REUSEPORT
, &yes
, sizeof(BOOL));
290 // Schedule the socket on the run loop.
291 CFRunLoopSourceRef source
= CFSocketCreateRunLoopSource(kCFAllocatorDefault
, socket_
, 0);
292 CFRunLoopAddSource([runLoop_ getCFRunLoop
], source
, kCFRunLoopCommonModes
);
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
);
308 CFRunLoopSourceInvalidate(quitSource_
);
309 CFRelease(quitSource_
);
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.
320 - (void)socketDidAccept
324 lastReadTransaction_
= 0;
325 lastWrittenTransaction_
= 0;
326 self.queuedWrites
= [NSMutableArray array
];
327 writeQueueLock_
= [NSRecursiveLock
new];
328 if ([delegate_ respondsToSelector
:@selector(connectionDidAccept
:)])
329 [delegate_ performSelectorOnMainThread
:@selector(connectionDidAccept
:)
335 * Closes a socket and releases the ref.
342 if (runLoop_
&& quitSource_
) {
343 CFRunLoopSourceSignal(quitSource_
);
344 CFRunLoopWakeUp([runLoop_ getCFRunLoop
]);
349 * Quits the run loop and stops the thread.
351 - (void)performQuitSignal
353 self.queuedWrites
= nil;
355 [writeQueueLock_ release
];
358 CFRunLoopStop([runLoop_ getCFRunLoop
]);
361 // The socket goes down, so do the streams, which clean themselves up.
363 NSLog(@
"invalidating socket");
364 CFSocketInvalidate(socket_
);
371 * Notification that the socket disconnected.
373 - (void)socketDisconnected
376 // The state still is connected, which means that we did not get here
377 // through normal disconnected procedure (a call to |-close|, followed by
378 // the downing of the socket and the stream, which also produces this
379 // messsage). Instead, the stream callbacks encountered EOF unexpectedly.
382 if ([delegate_ respondsToSelector
:@selector(connectionDidClose
:)])
383 [delegate_ connectionDidClose
:self];
387 * Writes a command into the write stream. If the stream is ready for writing,
388 * we do so immediately. If not, the command is queued and will be written
389 * when the stream is ready.
391 - (void)send
:(NSString
*)command
393 if (lastReadTransaction_
>= lastWrittenTransaction_
&& CFWriteStreamCanAcceptBytes(writeStream_
)) {
394 [self performSend
:command
];
396 [writeQueueLock_ lock
];
397 [queuedWrites_ addObject
:command
];
398 [writeQueueLock_ unlock
];
400 [self sendQueuedWrites
];
404 * This will send a command to the debugger engine. It will append the
405 * transaction ID automatically. It accepts a NSString command along with a
406 * a variable number of arguments to substitute into the command, a la
407 * +[NSString stringWithFormat:]. Returns the transaction ID as a NSNumber.
409 - (NSNumber
*)sendCommandWithFormat
:(NSString
*)format
, ...
411 // Collect varargs and format command.
413 va_start(args
, format
);
414 NSString
* command
= [[NSString alloc
] initWithFormat
:format arguments
:args
];
417 NSNumber
* callbackKey
= [NSNumber numberWithInt
:transactionID
++];
418 NSString
* taggedCommand
= [NSString stringWithFormat
:@
"%@ -i %@", [command autorelease
], callbackKey
];
419 [self performSelector
:@selector(send
:)
421 withObject
:taggedCommand
422 waitUntilDone
:connected_
];
428 * Given a file path, this returns a file:// URI and escapes any spaces for the
431 - (NSString
*)escapedURIPath
:(NSString
*)path
433 // Custon GDBp paths are fine.
434 if ([[path substringToIndex
:4] isEqualToString
:@
"gdbp"])
437 // Create a temporary URL that will escape all the nasty characters.
438 NSURL
* url
= [NSURL fileURLWithPath
:path
];
439 NSString
* urlString
= [url absoluteString
];
441 // Remove the host because this is a file:// URL;
442 urlString
= [urlString stringByReplacingOccurrencesOfString
:[url host
] withString
:@
""];
444 // Escape % for use in printf-style NSString formatters.
445 urlString
= [urlString stringByReplacingOccurrencesOfString
:@
"%" withString
:@
"%%"];
450 * Returns the transaction_id from an NSXMLDocument.
452 - (NSInteger
)transactionIDFromResponse
:(NSXMLDocument
*)response
454 return [[[[response rootElement
] attributeForName
:@
"transaction_id"] stringValue
] intValue
];
458 * Scans a command string for the transaction ID component. If it is not found,
459 * returns NSNotFound.
461 - (NSInteger
)transactionIDFromCommand
:(NSString
*)command
463 NSRange occurrence
= [command rangeOfString
:@
"-i "];
464 if (occurrence.location
== NSNotFound
)
466 NSString
* transaction
= [command substringFromIndex
:occurrence.location
+ occurrence.length
];
467 return [transaction intValue
];
470 // Private /////////////////////////////////////////////////////////////////////
473 // Delegate Thread-Safe Wrappers ///////////////////////////////////////////////
476 * Receives errors from the SocketWrapper and updates the display
478 - (void)errorEncountered
:(NSString
*)error
480 if (![delegate_ respondsToSelector
:@selector(errorEncountered
:)])
482 [delegate_ performSelectorOnMainThread
:@selector(errorEncountered
:)
487 - (LogEntry
*)recordSend
:(NSString
*)command
489 LoggingController
* logger
= [[AppDelegate instance
] loggingController
];
490 LogEntry
* entry
= [LogEntry newSendEntry
:command
];
491 entry.lastReadTransactionID
= lastReadTransaction_
;
492 entry.lastWrittenTransactionID
= lastWrittenTransaction_
;
493 [logger performSelectorOnMainThread
:@selector(recordEntry
:)
496 return [entry autorelease
];
499 - (LogEntry
*)recordReceive
:(NSString
*)command
501 LoggingController
* logger
= [[AppDelegate instance
] loggingController
];
502 LogEntry
* entry
= [LogEntry newReceiveEntry
:command
];
503 entry.lastReadTransactionID
= lastReadTransaction_
;
504 entry.lastWrittenTransactionID
= lastWrittenTransaction_
;
505 [logger performSelectorOnMainThread
:@selector(recordEntry
:)
508 return [entry autorelease
];
511 // Stream Managers /////////////////////////////////////////////////////////////
514 * Callback from the CFReadStream that there is data waiting to be read.
516 - (void)readStreamHasData
518 const NSUInteger kBufferSize
= 1024;
519 UInt8 buffer
[kBufferSize
];
520 CFIndex bufferOffset
= 0; // Starting point in |buffer| to work with.
521 CFIndex bytesRead
= CFReadStreamRead(readStream_
, buffer
, kBufferSize
);
522 const char* charBuffer
= (const char*)buffer
;
524 // The read loop works by going through the buffer until all the bytes have
526 while (bufferOffset
< bytesRead
)
528 // Find the NULL separator, or the end of the string.
529 NSUInteger partLength
= 0;
530 for (NSUInteger i
= bufferOffset
; i
< bytesRead
&& charBuffer
[i
] != '\0'; ++i
, ++partLength
) ;
532 // If there is not a current packet, set some state.
533 if (!self.currentPacket
)
535 // Read the message header: the size. This will be |partLength| bytes.
536 packetSize_
= atoi(charBuffer
+ bufferOffset
);
537 currentPacketIndex_
= 0;
538 self.currentPacket
= [NSMutableString stringWithCapacity
:packetSize_
];
539 bufferOffset
+= partLength
+ 1; // Pass over the NULL byte.
540 continue; // Spin the loop to begin reading actual data.
543 // Substring the byte stream and append it to the packet string.
544 CFStringRef bufferString
= CFStringCreateWithBytes(kCFAllocatorDefault
,
545 buffer
+ bufferOffset
, // Byte pointer, offset by start index.
546 partLength
, // Length.
547 kCFStringEncodingUTF8
,
549 [self.currentPacket appendString
:(NSString
*)bufferString
];
550 CFRelease(bufferString
);
553 currentPacketIndex_
+= partLength
;
554 bufferOffset
+= partLength
+ 1;
556 // If this read finished the packet, handle it and reset.
557 if (currentPacketIndex_
>= packetSize_
)
559 [self handlePacket
:[[currentPacket_ retain
] autorelease
]];
560 self.currentPacket
= nil;
562 currentPacketIndex_
= 0;
568 * Performs the packet handling of a raw string XML packet. From this point on,
569 * the packets are associated with a transaction and are then dispatched.
571 - (void)handlePacket
:(NSString
*)packet
573 // Test if we can convert it into an NSXMLDocument.
574 NSError
* error
= nil;
575 NSXMLDocument
* xmlTest
= [[NSXMLDocument alloc
] initWithXMLString
:currentPacket_ options
:NSXMLDocumentTidyXML error
:&error
];
577 // Try to recover if we encountered an error.
580 // We do not want to starve the write queue, so manually parse out the
582 NSRange location
= [currentPacket_ rangeOfString
:@
"transaction_id"];
583 if (location.location
!= NSNotFound
)
585 NSUInteger start
= location.location
+ location.length
;
586 NSUInteger end
= start
;
588 NSCharacterSet
* numericSet
= [NSCharacterSet decimalDigitCharacterSet
];
590 // Loop over the characters after the attribute name to extract the ID.
591 while (end
< [currentPacket_ length
])
593 unichar c
= [currentPacket_ characterAtIndex
:end
];
594 if ([numericSet characterIsMember
:c
])
596 // If this character is numeric, extend the range to substring.
603 // If this character is nonnumeric and we have nothing in the
604 // range, skip this character.
610 // We've moved past the numeric ID so we should stop searching.
616 // If we were able to extract the transaction ID, update the last read.
617 NSRange substringRange
= NSMakeRange(start
, end
- start
);
618 NSString
* transactionStr
= [currentPacket_ substringWithRange
:substringRange
];
619 if ([transactionStr length
])
620 lastReadTransaction_
= [transactionStr intValue
];
623 // Otherwise, assume +1 and hope it works.
624 ++lastReadTransaction_
;
625 } else /*if (!reconnect_)*/ {
626 // See if the transaction can be parsed out.
627 NSInteger transaction
= [self transactionIDFromResponse
:xmlTest
];
628 if (transaction
< lastReadTransaction_
) {
629 NSLog(@
"tx = %d vs %d", transaction
, lastReadTransaction_
);
630 NSLog(@
"out of date transaction %@", packet
);
634 if (transaction
!= lastWrittenTransaction_
)
635 NSLog(@
"txn %d <> %d last written, %d last read", transaction
, lastWrittenTransaction_
, lastReadTransaction_
);
637 lastReadTransaction_
= transaction
;
640 // Log this receive event.
641 LogEntry
* log
= [self recordReceive
:currentPacket_
];
644 // Finally, dispatch the handler for this response.
645 [self handleResponse
:[xmlTest autorelease
]];
648 - (void)handleResponse
:(NSXMLDocument
*)response
650 // Check and see if there's an error.
651 NSArray
* error
= [[response rootElement
] elementsForName
:@
"error"];
652 if ([error count
] > 0)
654 NSLog(@
"Xdebug error: %@", error
);
655 NSString
* errorMessage
= [[[[error objectAtIndex
:0] children
] objectAtIndex
:0] stringValue
];
656 [self errorEncountered
:errorMessage
];
659 if ([[[response rootElement
] name
] isEqualToString
:@
"init"]) {
661 [delegate_ performSelectorOnMainThread
:@selector(handleInitialResponse
:)
667 if ([delegate_ respondsToSelector
:@selector(handleResponse
:)])
668 [delegate_ performSelectorOnMainThread
:@selector(handleResponse
:)
672 [self sendQueuedWrites
];
676 * This performs a blocking send. This should ONLY be called when we know we
677 * have write access to the stream. We will busy wait in case we don't do a full
680 - (void)performSend
:(NSString
*)command
682 // If this is an out-of-date transaction, do not bother sending it.
683 NSInteger transaction
= [self transactionIDFromCommand
:command
];
684 if (transaction
!= NSNotFound
&& transaction
< lastWrittenTransaction_
)
689 char* string
= (char*)[command UTF8String
];
690 int stringLength
= strlen(string
);
692 // Busy wait while writing. BAADD. Should background this operation.
695 if (CFWriteStreamCanAcceptBytes(writeStream_
))
697 // Include the NULL byte in the string when we write.
698 int bytesWritten
= CFWriteStreamWrite(writeStream_
, (UInt8
*)string
, stringLength
+ 1);
699 if (bytesWritten
< 0)
701 NSLog(@
"write error");
704 else if (bytesWritten
< strlen(string
))
706 // Adjust the buffer and wait for another chance to write.
707 stringLength
-= bytesWritten
;
708 memmove(string
, string
+ bytesWritten
, stringLength
);
714 // We need to scan the string to find the transactionID.
715 if (transaction
== NSNotFound
)
717 NSLog(@
"sent %@ without a transaction ID", command
);
720 lastWrittenTransaction_
= transaction
;
725 // Log this trancation.
726 [self recordSend
:command
];
730 * Checks if there are unsent commands in the |queuedWrites_| queue and sends
731 * them if it's OK to do so. This will not block.
733 - (void)sendQueuedWrites
738 [writeQueueLock_ lock
];
739 if (lastReadTransaction_
>= lastWrittenTransaction_
&& [queuedWrites_ count
] > 0)
741 NSString
* command
= [queuedWrites_ objectAtIndex
:0];
743 // We don't want to block because this is called from the main thread.
744 // |-performSend:| busy waits when the stream is not ready. Bail out
745 // before we do that becuase busy waiting is BAD.
746 if (CFWriteStreamCanAcceptBytes(writeStream_
))
748 [self performSend
:command
];
749 [queuedWrites_ removeObjectAtIndex
:0];
752 [writeQueueLock_ unlock
];