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)connectionThreadStart
;
39 - (void)socketDidAccept
;
40 - (void)socketDisconnected
;
41 - (void)readStreamHasData
;
43 - (void)performSend
:(NSString
*)command
;
44 - (void)sendQueuedWrites
;
46 - (void)handleResponse
:(NSXMLDocument
*)response
;
47 - (void)handlePacket
:(NSString
*)packet
;
49 // Threadsafe wrappers for the delegate's methods.
50 - (void)errorEncountered
:(NSString
*)error
;
51 - (LogEntry
*)recordSend
:(NSString
*)command
;
52 - (LogEntry
*)recordReceive
:(NSString
*)command
;
56 // CFNetwork Callbacks /////////////////////////////////////////////////////////
58 void ReadStreamCallback(CFReadStreamRef stream
, CFStreamEventType eventType
, void* connectionRaw
)
60 DebuggerConnection
* connection
= (DebuggerConnection
*)connectionRaw
;
63 case kCFStreamEventHasBytesAvailable
:
64 [connection readStreamHasData
];
67 case kCFStreamEventErrorOccurred
:
69 CFErrorRef error
= CFReadStreamCopyError(stream
);
70 CFReadStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
71 CFReadStreamClose(stream
);
73 [connection errorEncountered
:[[(NSError
*)error autorelease
] description
]];
77 case kCFStreamEventEndEncountered
:
78 CFReadStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
79 CFReadStreamClose(stream
);
81 [connection socketDisconnected
];
86 void WriteStreamCallback(CFWriteStreamRef stream
, CFStreamEventType eventType
, void* connectionRaw
)
88 DebuggerConnection
* connection
= (DebuggerConnection
*)connectionRaw
;
91 case kCFStreamEventCanAcceptBytes
:
92 [connection sendQueuedWrites
];
95 case kCFStreamEventErrorOccurred
:
97 CFErrorRef error
= CFWriteStreamCopyError(stream
);
98 CFWriteStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
99 CFWriteStreamClose(stream
);
101 [connection errorEncountered
:[[(NSError
*)error autorelease
] description
]];
105 case kCFStreamEventEndEncountered
:
106 CFWriteStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
107 CFWriteStreamClose(stream
);
109 [connection socketDisconnected
];
114 void SocketAcceptCallback(CFSocketRef socket
,
115 CFSocketCallBackType callbackType
,
120 assert(callbackType
== kCFSocketAcceptCallBack
);
121 NSLog(@
"SocketAcceptCallback()");
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 ////////////////////////////////////////////////////////////////////////////////
189 @implementation DebuggerConnection
191 @synthesize port
= port_
;
192 @synthesize connected
= connected_
;
193 @synthesize delegate
= delegate_
;
195 @synthesize socket
= socket_
;
196 @synthesize readStream
= readStream_
;
197 @synthesize lastReadTransaction
= lastReadTransaction_
;
198 @synthesize currentPacket
= currentPacket_
;
199 @synthesize writeStream
= writeStream_
;
200 @synthesize lastWrittenTransaction
= lastWrittenTransaction_
;
201 @synthesize queuedWrites
= queuedWrites_
;
203 - (id)initWithPort
:(NSUInteger
)aPort
205 if (self = [super init
])
214 self.currentPacket
= nil;
219 * Kicks off the socket on another thread.
223 [NSThread detachNewThreadSelector
:@selector(connectionThreadStart
) toTarget
:self withObject
:nil];
227 * Creates, connects to, and schedules a CFSocket.
229 - (void)connectionThreadStart
231 NSAutoreleasePool
* pool
= [[NSAutoreleasePool alloc
] init
];
233 thread_
= [NSThread currentThread
];
234 runLoop_
= [NSRunLoop currentRunLoop
];
236 // Pass ourselves to the callback so we don't have to use ugly globals.
237 CFSocketContext context
;
240 context.retain
= NULL
;
241 context.release
= NULL
;
242 context.copyDescription
= NULL
;
244 // Create the address structure.
245 struct sockaddr_in address
;
246 memset(&address
, 0, sizeof(address
));
247 address.sin_len
= sizeof(address
);
248 address.sin_family
= AF_INET
;
249 address.sin_port
= htons(port_
);
250 address.sin_addr.s_addr
= htonl(INADDR_ANY
);
252 // Create the socket signature.
253 CFSocketSignature signature
;
254 signature.protocolFamily
= PF_INET
;
255 signature.socketType
= SOCK_STREAM
;
256 signature.protocol
= IPPROTO_TCP
;
257 signature.address
= (CFDataRef
)[NSData dataWithBytes
:&address length
:sizeof(address
)];
259 socket_
= CFSocketCreateWithSocketSignature(kCFAllocatorDefault
,
260 &signature
, // Socket signature.
261 kCFSocketAcceptCallBack
, // Callback types.
262 SocketAcceptCallback
, // Callout function pointer.
263 &context
); // Context to pass to callout.
266 [self errorEncountered
:@
"Could not open socket."];
270 // Allow old, yet-to-be recycled sockets to be reused.
272 setsockopt(CFSocketGetNative(socket_
), SOL_SOCKET
, SO_REUSEADDR
, &yes
, sizeof(BOOL));
274 // Schedule the socket on the run loop.
275 CFRunLoopSourceRef source
= CFSocketCreateRunLoopSource(kCFAllocatorDefault
, socket_
, 0);
276 CFRunLoopAddSource([runLoop_ getCFRunLoop
], source
, kCFRunLoopCommonModes
);
288 * Called by SocketWrapper after the connection is successful. This immediately calls
289 * -[SocketWrapper receive] to clear the way for communication, though the information
290 * could be useful server information that we don't use right now.
292 - (void)socketDidAccept
296 self.queuedWrites
= [NSMutableArray array
];
297 writeQueueLock_
= [NSRecursiveLock
new];
301 * Closes a socket and releases the ref.
306 CFRunLoopStop([runLoop_ getCFRunLoop
]);
309 // The socket goes down, so do the streams, which clean themselves up.
311 CFSocketInvalidate(socket_
);
314 self.queuedWrites
= nil;
316 [writeQueueLock_ release
];
320 * Notification that the socket disconnected.
322 - (void)socketDisconnected
325 [delegate_ connectionDidClose
:self];
329 * Writes a command into the write stream. If the stream is ready for writing,
330 * we do so immediately. If not, the command is queued and will be written
331 * when the stream is ready.
333 - (void)send
:(NSString
*)command
335 if (lastReadTransaction_
>= lastWrittenTransaction_
&& CFWriteStreamCanAcceptBytes(writeStream_
)) {
336 [self performSend
:command
];
338 [writeQueueLock_ lock
];
339 [queuedWrites_ addObject
:command
];
340 [writeQueueLock_ unlock
];
342 [self sendQueuedWrites
];
346 * This will send a command to the debugger engine. It will append the
347 * transaction ID automatically. It accepts a NSString command along with a
348 * a variable number of arguments to substitute into the command, a la
349 * +[NSString stringWithFormat:]. Returns the transaction ID as a NSNumber.
351 - (NSNumber
*)sendCommandWithFormat
:(NSString
*)format
, ...
353 // Collect varargs and format command.
355 va_start(args
, format
);
356 NSString
* command
= [[NSString alloc
] initWithFormat
:format arguments
:args
];
359 NSNumber
* callbackKey
= [NSNumber numberWithInt
:transactionID
++];
360 NSString
* taggedCommand
= [NSString stringWithFormat
:@
"%@ -i %@", [command autorelease
], callbackKey
];
361 [self performSelector
:@selector(send
:)
363 withObject
:taggedCommand
370 * Given a file path, this returns a file:// URI and escapes any spaces for the
373 - (NSString
*)escapedURIPath
:(NSString
*)path
375 // Custon GDBp paths are fine.
376 if ([[path substringToIndex
:4] isEqualToString
:@
"gdbp"])
379 // Create a temporary URL that will escape all the nasty characters.
380 NSURL
* url
= [NSURL fileURLWithPath
:path
];
381 NSString
* urlString
= [url absoluteString
];
383 // Remove the host because this is a file:// URL;
384 urlString
= [urlString stringByReplacingOccurrencesOfString
:[url host
] withString
:@
""];
386 // Escape % for use in printf-style NSString formatters.
387 urlString
= [urlString stringByReplacingOccurrencesOfString
:@
"%" withString
:@
"%%"];
392 * Returns the transaction_id from an NSXMLDocument.
394 - (NSInteger
)transactionIDFromResponse
:(NSXMLDocument
*)response
396 return [[[[response rootElement
] attributeForName
:@
"transaction_id"] stringValue
] intValue
];
400 * Scans a command string for the transaction ID component. If it is not found,
401 * returns NSNotFound.
403 - (NSInteger
)transactionIDFromCommand
:(NSString
*)command
405 NSRange occurrence
= [command rangeOfString
:@
"-i "];
406 if (occurrence.location
== NSNotFound
)
408 NSString
* transaction
= [command substringFromIndex
:occurrence.location
+ occurrence.length
];
409 return [transaction intValue
];
412 // Private /////////////////////////////////////////////////////////////////////
415 // Delegate Thread-Safe Wrappers ///////////////////////////////////////////////
418 * Receives errors from the SocketWrapper and updates the display
420 - (void)errorEncountered
:(NSString
*)error
422 [delegate_ performSelectorOnMainThread
:@selector(errorEncountered
:)
427 - (LogEntry
*)recordSend
:(NSString
*)command
429 LoggingController
* logger
= [[AppDelegate instance
] loggingController
];
430 LogEntry
* entry
= [LogEntry newSendEntry
:command
];
431 entry.lastReadTransactionID
= lastReadTransaction_
;
432 entry.lastWrittenTransactionID
= lastWrittenTransaction_
;
433 [logger performSelectorOnMainThread
:@selector(recordEntry
:)
436 return [entry autorelease
];
439 - (LogEntry
*)recordReceive
:(NSString
*)command
441 LoggingController
* logger
= [[AppDelegate instance
] loggingController
];
442 LogEntry
* entry
= [LogEntry newReceiveEntry
:command
];
443 entry.lastReadTransactionID
= lastReadTransaction_
;
444 entry.lastWrittenTransactionID
= lastWrittenTransaction_
;
445 [logger performSelectorOnMainThread
:@selector(recordEntry
:)
448 return [entry autorelease
];
451 // Stream Managers /////////////////////////////////////////////////////////////
454 * Callback from the CFReadStream that there is data waiting to be read.
456 - (void)readStreamHasData
458 const NSUInteger kBufferSize
= 1024;
459 UInt8 buffer
[kBufferSize
];
460 CFIndex bufferOffset
= 0; // Starting point in |buffer| to work with.
461 CFIndex bytesRead
= CFReadStreamRead(readStream_
, buffer
, kBufferSize
);
462 const char* charBuffer
= (const char*)buffer
;
464 // The read loop works by going through the buffer until all the bytes have
466 while (bufferOffset
< bytesRead
)
468 // Find the NULL separator, or the end of the string.
469 NSUInteger partLength
= 0;
470 for (NSUInteger i
= bufferOffset
; i
< bytesRead
&& charBuffer
[i
] != '\0'; ++i
, ++partLength
) ;
472 // If there is not a current packet, set some state.
473 if (!self.currentPacket
)
475 // Read the message header: the size. This will be |partLength| bytes.
476 packetSize_
= atoi(charBuffer
+ bufferOffset
);
477 currentPacketIndex_
= 0;
478 self.currentPacket
= [NSMutableString stringWithCapacity
:packetSize_
];
479 bufferOffset
+= partLength
+ 1; // Pass over the NULL byte.
480 continue; // Spin the loop to begin reading actual data.
483 // Substring the byte stream and append it to the packet string.
484 CFStringRef bufferString
= CFStringCreateWithBytes(kCFAllocatorDefault
,
485 buffer
+ bufferOffset
, // Byte pointer, offset by start index.
486 partLength
, // Length.
487 kCFStringEncodingUTF8
,
489 [self.currentPacket appendString
:(NSString
*)bufferString
];
490 CFRelease(bufferString
);
493 currentPacketIndex_
+= partLength
;
494 bufferOffset
+= partLength
+ 1;
496 // If this read finished the packet, handle it and reset.
497 if (currentPacketIndex_
>= packetSize_
)
499 [self handlePacket
:[[currentPacket_ retain
] autorelease
]];
500 self.currentPacket
= nil;
502 currentPacketIndex_
= 0;
508 * Performs the packet handling of a raw string XML packet. From this point on,
509 * the packets are associated with a transaction and are then dispatched.
511 - (void)handlePacket
:(NSString
*)packet
513 // Test if we can convert it into an NSXMLDocument.
514 NSError
* error
= nil;
515 NSXMLDocument
* xmlTest
= [[NSXMLDocument alloc
] initWithXMLString
:currentPacket_ options
:NSXMLDocumentTidyXML error
:&error
];
517 // Try to recover if we encountered an error.
520 // We do not want to starve the write queue, so manually parse out the
522 NSRange location
= [currentPacket_ rangeOfString
:@
"transaction_id"];
523 if (location.location
!= NSNotFound
)
525 NSUInteger start
= location.location
+ location.length
;
526 NSUInteger end
= start
;
528 NSCharacterSet
* numericSet
= [NSCharacterSet decimalDigitCharacterSet
];
530 // Loop over the characters after the attribute name to extract the ID.
531 while (end
< [currentPacket_ length
])
533 unichar c
= [currentPacket_ characterAtIndex
:end
];
534 if ([numericSet characterIsMember
:c
])
536 // If this character is numeric, extend the range to substring.
543 // If this character is nonnumeric and we have nothing in the
544 // range, skip this character.
550 // We've moved past the numeric ID so we should stop searching.
556 // If we were able to extract the transaction ID, update the last read.
557 NSRange substringRange
= NSMakeRange(start
, end
- start
);
558 NSString
* transactionStr
= [currentPacket_ substringWithRange
:substringRange
];
559 if ([transactionStr length
])
560 lastReadTransaction_
= [transactionStr intValue
];
563 // Otherwise, assume +1 and hope it works.
564 ++lastReadTransaction_
;
568 // See if the transaction can be parsed out.
569 NSInteger transaction
= [self transactionIDFromResponse
:xmlTest
];
570 if (transaction
< lastReadTransaction_
)
572 NSLog(@
"tx = %d vs %d", transaction
, lastReadTransaction_
);
573 NSLog(@
"out of date transaction %@", packet
);
577 if (transaction
!= lastWrittenTransaction_
)
578 NSLog(@
"txn %d <> %d last written, %d last read", transaction
, lastWrittenTransaction_
, lastReadTransaction_
);
580 lastReadTransaction_
= transaction
;
583 // Log this receive event.
584 LogEntry
* log
= [self recordReceive
:currentPacket_
];
587 // Finally, dispatch the handler for this response.
588 [self handleResponse
:[xmlTest autorelease
]];
591 - (void)handleResponse
:(NSXMLDocument
*)response
593 // Check and see if there's an error.
594 NSArray
* error
= [[response rootElement
] elementsForName
:@
"error"];
595 if ([error count
] > 0)
597 NSLog(@
"Xdebug error: %@", error
);
598 NSString
* errorMessage
= [[[[error objectAtIndex
:0] children
] objectAtIndex
:0] stringValue
];
599 [self errorEncountered
:errorMessage
];
602 if ([[[response rootElement
] name
] isEqualToString
:@
"init"])
604 [delegate_ performSelectorOnMainThread
:@selector(handleInitialResponse
:)
610 if ([delegate_ respondsToSelector
:@selector(handleResponse
:)])
611 [delegate_ performSelectorOnMainThread
:@selector(handleResponse
:)
615 [self sendQueuedWrites
];
619 * This performs a blocking send. This should ONLY be called when we know we
620 * have write access to the stream. We will busy wait in case we don't do a full
623 - (void)performSend
:(NSString
*)command
625 // If this is an out-of-date transaction, do not bother sending it.
626 NSInteger transaction
= [self transactionIDFromCommand
:command
];
627 if (transaction
!= NSNotFound
&& transaction
< lastWrittenTransaction_
)
632 char* string
= (char*)[command UTF8String
];
633 int stringLength
= strlen(string
);
635 // Busy wait while writing. BAADD. Should background this operation.
638 if (CFWriteStreamCanAcceptBytes(writeStream_
))
640 // Include the NULL byte in the string when we write.
641 int bytesWritten
= CFWriteStreamWrite(writeStream_
, (UInt8
*)string
, stringLength
+ 1);
642 if (bytesWritten
< 0)
644 NSLog(@
"write error");
647 else if (bytesWritten
< strlen(string
))
649 // Adjust the buffer and wait for another chance to write.
650 stringLength
-= bytesWritten
;
651 memmove(string
, string
+ bytesWritten
, stringLength
);
657 // We need to scan the string to find the transactionID.
658 if (transaction
== NSNotFound
)
660 NSLog(@
"sent %@ without a transaction ID", command
);
663 lastWrittenTransaction_
= transaction
;
668 // Log this trancation.
669 [self recordSend
:command
];
673 * Checks if there are unsent commands in the |queuedWrites_| queue and sends
674 * them if it's OK to do so. This will not block.
676 - (void)sendQueuedWrites
681 [writeQueueLock_ lock
];
682 if (lastReadTransaction_
>= lastWrittenTransaction_
&& [queuedWrites_ count
] > 0)
684 NSString
* command
= [queuedWrites_ objectAtIndex
:0];
686 // We don't want to block because this is called from the main thread.
687 // |-performSend:| busy waits when the stream is not ready. Bail out
688 // before we do that becuase busy waiting is BAD.
689 if (CFWriteStreamCanAcceptBytes(writeStream_
))
691 [self performSend
:command
];
692 [queuedWrites_ removeObjectAtIndex
:0];
695 [writeQueueLock_ unlock
];