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;
315 [writeQueueLock_ release
];
319 * Notification that the socket disconnected.
321 - (void)socketDisconnected
324 [delegate_ connectionDidClose
:self];
328 * Writes a command into the write stream. If the stream is ready for writing,
329 * we do so immediately. If not, the command is queued and will be written
330 * when the stream is ready.
332 - (void)send
:(NSString
*)command
334 if (lastReadTransaction_
>= lastWrittenTransaction_
&& CFWriteStreamCanAcceptBytes(writeStream_
)) {
335 [self performSend
:command
];
337 [writeQueueLock_ lock
];
338 [queuedWrites_ addObject
:command
];
339 [writeQueueLock_ unlock
];
341 [self sendQueuedWrites
];
345 * This will send a command to the debugger engine. It will append the
346 * transaction ID automatically. It accepts a NSString command along with a
347 * a variable number of arguments to substitute into the command, a la
348 * +[NSString stringWithFormat:]. Returns the transaction ID as a NSNumber.
350 - (NSNumber
*)sendCommandWithFormat
:(NSString
*)format
, ...
352 // Collect varargs and format command.
354 va_start(args
, format
);
355 NSString
* command
= [[NSString alloc
] initWithFormat
:format arguments
:args
];
358 NSNumber
* callbackKey
= [NSNumber numberWithInt
:transactionID
++];
359 NSString
* taggedCommand
= [NSString stringWithFormat
:@
"%@ -i %@", [command autorelease
], callbackKey
];
360 [self performSelector
:@selector(send
:)
362 withObject
:taggedCommand
369 * Given a file path, this returns a file:// URI and escapes any spaces for the
372 - (NSString
*)escapedURIPath
:(NSString
*)path
374 // Custon GDBp paths are fine.
375 if ([[path substringToIndex
:4] isEqualToString
:@
"gdbp"])
378 // Create a temporary URL that will escape all the nasty characters.
379 NSURL
* url
= [NSURL fileURLWithPath
:path
];
380 NSString
* urlString
= [url absoluteString
];
382 // Remove the host because this is a file:// URL;
383 urlString
= [urlString stringByReplacingOccurrencesOfString
:[url host
] withString
:@
""];
385 // Escape % for use in printf-style NSString formatters.
386 urlString
= [urlString stringByReplacingOccurrencesOfString
:@
"%" withString
:@
"%%"];
391 * Returns the transaction_id from an NSXMLDocument.
393 - (NSInteger
)transactionIDFromResponse
:(NSXMLDocument
*)response
395 return [[[[response rootElement
] attributeForName
:@
"transaction_id"] stringValue
] intValue
];
399 * Scans a command string for the transaction ID component. If it is not found,
400 * returns NSNotFound.
402 - (NSInteger
)transactionIDFromCommand
:(NSString
*)command
404 NSRange occurrence
= [command rangeOfString
:@
"-i "];
405 if (occurrence.location
== NSNotFound
)
407 NSString
* transaction
= [command substringFromIndex
:occurrence.location
+ occurrence.length
];
408 return [transaction intValue
];
411 // Private /////////////////////////////////////////////////////////////////////
414 // Delegate Thread-Safe Wrappers ///////////////////////////////////////////////
417 * Receives errors from the SocketWrapper and updates the display
419 - (void)errorEncountered
:(NSString
*)error
421 [delegate_ performSelectorOnMainThread
:@selector(errorEncountered
:)
426 - (LogEntry
*)recordSend
:(NSString
*)command
428 LoggingController
* logger
= [[AppDelegate instance
] loggingController
];
429 LogEntry
* entry
= [LogEntry newSendEntry
:command
];
430 entry.lastReadTransactionID
= lastReadTransaction_
;
431 entry.lastWrittenTransactionID
= lastWrittenTransaction_
;
432 [logger performSelectorOnMainThread
:@selector(recordEntry
:)
435 return [entry autorelease
];
438 - (LogEntry
*)recordReceive
:(NSString
*)command
440 LoggingController
* logger
= [[AppDelegate instance
] loggingController
];
441 LogEntry
* entry
= [LogEntry newReceiveEntry
:command
];
442 entry.lastReadTransactionID
= lastReadTransaction_
;
443 entry.lastWrittenTransactionID
= lastWrittenTransaction_
;
444 [logger performSelectorOnMainThread
:@selector(recordEntry
:)
447 return [entry autorelease
];
450 // Stream Managers /////////////////////////////////////////////////////////////
453 * Callback from the CFReadStream that there is data waiting to be read.
455 - (void)readStreamHasData
457 const NSUInteger kBufferSize
= 1024;
458 UInt8 buffer
[kBufferSize
];
459 CFIndex bufferOffset
= 0; // Starting point in |buffer| to work with.
460 CFIndex bytesRead
= CFReadStreamRead(readStream_
, buffer
, kBufferSize
);
461 const char* charBuffer
= (const char*)buffer
;
463 // The read loop works by going through the buffer until all the bytes have
465 while (bufferOffset
< bytesRead
)
467 // Find the NULL separator, or the end of the string.
468 NSUInteger partLength
= 0;
469 for (NSUInteger i
= bufferOffset
; i
< bytesRead
&& charBuffer
[i
] != '\0'; ++i
, ++partLength
) ;
471 // If there is not a current packet, set some state.
472 if (!self.currentPacket
)
474 // Read the message header: the size. This will be |partLength| bytes.
475 packetSize_
= atoi(charBuffer
+ bufferOffset
);
476 currentPacketIndex_
= 0;
477 self.currentPacket
= [NSMutableString stringWithCapacity
:packetSize_
];
478 bufferOffset
+= partLength
+ 1; // Pass over the NULL byte.
479 continue; // Spin the loop to begin reading actual data.
482 // Substring the byte stream and append it to the packet string.
483 CFStringRef bufferString
= CFStringCreateWithBytes(kCFAllocatorDefault
,
484 buffer
+ bufferOffset
, // Byte pointer, offset by start index.
485 partLength
, // Length.
486 kCFStringEncodingUTF8
,
488 [self.currentPacket appendString
:(NSString
*)bufferString
];
489 CFRelease(bufferString
);
492 currentPacketIndex_
+= partLength
;
493 bufferOffset
+= partLength
+ 1;
495 // If this read finished the packet, handle it and reset.
496 if (currentPacketIndex_
>= packetSize_
)
498 [self handlePacket
:[[currentPacket_ retain
] autorelease
]];
499 self.currentPacket
= nil;
501 currentPacketIndex_
= 0;
507 * Performs the packet handling of a raw string XML packet. From this point on,
508 * the packets are associated with a transaction and are then dispatched.
510 - (void)handlePacket
:(NSString
*)packet
512 // Test if we can convert it into an NSXMLDocument.
513 NSError
* error
= nil;
514 NSXMLDocument
* xmlTest
= [[NSXMLDocument alloc
] initWithXMLString
:currentPacket_ options
:NSXMLDocumentTidyXML error
:&error
];
516 // Try to recover if we encountered an error.
519 // We do not want to starve the write queue, so manually parse out the
521 NSRange location
= [currentPacket_ rangeOfString
:@
"transaction_id"];
522 if (location.location
!= NSNotFound
)
524 NSUInteger start
= location.location
+ location.length
;
525 NSUInteger end
= start
;
527 NSCharacterSet
* numericSet
= [NSCharacterSet decimalDigitCharacterSet
];
529 // Loop over the characters after the attribute name to extract the ID.
530 while (end
< [currentPacket_ length
])
532 unichar c
= [currentPacket_ characterAtIndex
:end
];
533 if ([numericSet characterIsMember
:c
])
535 // If this character is numeric, extend the range to substring.
542 // If this character is nonnumeric and we have nothing in the
543 // range, skip this character.
549 // We've moved past the numeric ID so we should stop searching.
555 // If we were able to extract the transaction ID, update the last read.
556 NSRange substringRange
= NSMakeRange(start
, end
- start
);
557 NSString
* transactionStr
= [currentPacket_ substringWithRange
:substringRange
];
558 if ([transactionStr length
])
559 lastReadTransaction_
= [transactionStr intValue
];
562 // Otherwise, assume +1 and hope it works.
563 ++lastReadTransaction_
;
567 // See if the transaction can be parsed out.
568 NSInteger transaction
= [self transactionIDFromResponse
:xmlTest
];
569 if (transaction
< lastReadTransaction_
)
571 NSLog(@
"tx = %d vs %d", transaction
, lastReadTransaction_
);
572 NSLog(@
"out of date transaction %@", packet
);
576 if (transaction
!= lastWrittenTransaction_
)
577 NSLog(@
"txn %d <> %d last written, %d last read", transaction
, lastWrittenTransaction_
, lastReadTransaction_
);
579 lastReadTransaction_
= transaction
;
582 // Log this receive event.
583 LogEntry
* log
= [self recordReceive
:currentPacket_
];
586 // Finally, dispatch the handler for this response.
587 [self handleResponse
:[xmlTest autorelease
]];
590 - (void)handleResponse
:(NSXMLDocument
*)response
592 // Check and see if there's an error.
593 NSArray
* error
= [[response rootElement
] elementsForName
:@
"error"];
594 if ([error count
] > 0)
596 NSLog(@
"Xdebug error: %@", error
);
597 NSString
* errorMessage
= [[[[error objectAtIndex
:0] children
] objectAtIndex
:0] stringValue
];
598 [self errorEncountered
:errorMessage
];
601 if ([[[response rootElement
] name
] isEqualToString
:@
"init"])
603 [delegate_ performSelectorOnMainThread
:@selector(handleInitialResponse
:)
609 if ([delegate_ respondsToSelector
:@selector(handleResponse
:)])
610 [delegate_ performSelectorOnMainThread
:@selector(handleResponse
:)
614 [self sendQueuedWrites
];
618 * This performs a blocking send. This should ONLY be called when we know we
619 * have write access to the stream. We will busy wait in case we don't do a full
622 - (void)performSend
:(NSString
*)command
624 // If this is an out-of-date transaction, do not bother sending it.
625 NSInteger transaction
= [self transactionIDFromCommand
:command
];
626 if (transaction
!= NSNotFound
&& transaction
< lastWrittenTransaction_
)
631 char* string
= (char*)[command UTF8String
];
632 int stringLength
= strlen(string
);
634 // Busy wait while writing. BAADD. Should background this operation.
637 if (CFWriteStreamCanAcceptBytes(writeStream_
))
639 // Include the NULL byte in the string when we write.
640 int bytesWritten
= CFWriteStreamWrite(writeStream_
, (UInt8
*)string
, stringLength
+ 1);
641 if (bytesWritten
< 0)
643 NSLog(@
"write error");
646 else if (bytesWritten
< strlen(string
))
648 // Adjust the buffer and wait for another chance to write.
649 stringLength
-= bytesWritten
;
650 memmove(string
, string
+ bytesWritten
, stringLength
);
656 // We need to scan the string to find the transactionID.
657 if (transaction
== NSNotFound
)
659 NSLog(@
"sent %@ without a transaction ID", command
);
662 lastWrittenTransaction_
= transaction
;
667 // Log this trancation.
668 [self recordSend
:command
];
672 * Checks if there are unsent commands in the |queuedWrites_| queue and sends
673 * them if it's OK to do so. This will not block.
675 - (void)sendQueuedWrites
680 [writeQueueLock_ lock
];
681 if (lastReadTransaction_
>= lastWrittenTransaction_
&& [queuedWrites_ count
] > 0)
683 NSString
* command
= [queuedWrites_ objectAtIndex
:0];
685 // We don't want to block because this is called from the main thread.
686 // |-performSend:| busy waits when the stream is not ready. Bail out
687 // before we do that becuase busy waiting is BAD.
688 if (CFWriteStreamCanAcceptBytes(writeStream_
))
690 [self performSend
:command
];
691 [queuedWrites_ removeObjectAtIndex
:0];
694 [writeQueueLock_ unlock
];