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)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 NSLog(@
"SocketAcceptCallback()");
125 DebuggerConnection
* connection
= (DebuggerConnection
*)connectionRaw
;
126 if (![connection inReconnectMode
])
129 CFReadStreamRef readStream
;
130 CFWriteStreamRef writeStream
;
132 // Create the streams on the socket.
133 CFStreamCreatePairWithSocket(kCFAllocatorDefault
,
134 *(CFSocketNativeHandle
*)data
, // Socket handle.
135 &readStream
, // Read stream in-pointer.
136 &writeStream
); // Write stream in-pointer.
138 // Create struct to register callbacks for the stream.
139 CFStreamClientContext context
;
141 context.info
= connection
;
142 context.retain
= NULL
;
143 context.release
= NULL
;
144 context.copyDescription
= NULL
;
146 // Set the client of the read stream.
147 CFOptionFlags readFlags
=
148 kCFStreamEventOpenCompleted |
149 kCFStreamEventHasBytesAvailable |
150 kCFStreamEventErrorOccurred |
151 kCFStreamEventEndEncountered
;
152 if (CFReadStreamSetClient(readStream
, readFlags
, ReadStreamCallback
, &context
))
153 // Schedule in run loop to do asynchronous communication with the engine.
154 CFReadStreamScheduleWithRunLoop(readStream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
158 // Open the stream now that it's scheduled on the run loop.
159 if (!CFReadStreamOpen(readStream
))
161 CFStreamError error
= CFReadStreamGetError(readStream
);
162 NSLog(@
"error! %@", error
);
166 // Set the client of the write stream.
167 CFOptionFlags writeFlags
=
168 kCFStreamEventOpenCompleted |
169 kCFStreamEventCanAcceptBytes |
170 kCFStreamEventErrorOccurred |
171 kCFStreamEventEndEncountered
;
172 if (CFWriteStreamSetClient(writeStream
, writeFlags
, WriteStreamCallback
, &context
))
173 // Schedule it in the run loop to receive error information.
174 CFWriteStreamScheduleWithRunLoop(writeStream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
178 // Open the write stream.
179 if (!CFWriteStreamOpen(writeStream
))
181 CFStreamError error
= CFWriteStreamGetError(writeStream
);
182 NSLog(@
"error! %@", error
);
186 connection.readStream
= readStream
;
187 connection.writeStream
= writeStream
;
188 [connection socketDidAccept
];
191 // Other Run Loop Callbacks ////////////////////////////////////////////////////
193 void PerformQuitSignal(void* info
)
195 DebuggerConnection
* obj
= (DebuggerConnection
*)info
;
196 [obj performQuitSignal
];
199 ////////////////////////////////////////////////////////////////////////////////
201 @implementation DebuggerConnection
203 @synthesize port
= port_
;
204 @synthesize connected
= connected_
;
205 @synthesize reconnect
= reconnect_
;
206 @synthesize delegate
= delegate_
;
208 @synthesize socket
= socket_
;
209 @synthesize readStream
= readStream_
;
210 @synthesize lastReadTransaction
= lastReadTransaction_
;
211 @synthesize currentPacket
= currentPacket_
;
212 @synthesize writeStream
= writeStream_
;
213 @synthesize lastWrittenTransaction
= lastWrittenTransaction_
;
214 @synthesize queuedWrites
= queuedWrites_
;
216 - (id)initWithPort
:(NSUInteger
)aPort
218 if (self = [super init
])
228 self.currentPacket
= nil;
239 * Kicks off the socket on another thread.
243 if (thread_
&& !connected_
) {
244 // A thread has been detached but the socket has yet to connect. Do not
245 // spawn a new thread otherwise multiple threads will be blocked on the same
249 [NSThread detachNewThreadSelector
:@selector(connectionThreadStart
) toTarget
:self withObject
:nil];
253 * Creates, connects to, and schedules a CFSocket.
255 - (void)connectionThreadStart
257 NSAutoreleasePool
* pool
= [[NSAutoreleasePool alloc
] init
];
259 thread_
= [NSThread currentThread
];
260 runLoop_
= [NSRunLoop currentRunLoop
];
262 // Pass ourselves to the callback so we don't have to use ugly globals.
263 CFSocketContext context
;
266 context.retain
= NULL
;
267 context.release
= NULL
;
268 context.copyDescription
= NULL
;
270 // Create the address structure.
271 struct sockaddr_in address
;
272 memset(&address
, 0, sizeof(address
));
273 address.sin_len
= sizeof(address
);
274 address.sin_family
= AF_INET
;
275 address.sin_port
= htons(port_
);
276 address.sin_addr.s_addr
= htonl(INADDR_ANY
);
278 // Create the socket signature.
279 CFSocketSignature signature
;
280 signature.protocolFamily
= PF_INET
;
281 signature.socketType
= SOCK_STREAM
;
282 signature.protocol
= IPPROTO_TCP
;
283 signature.address
= (CFDataRef
)[NSData dataWithBytes
:&address length
:sizeof(address
)];
286 socket_
= CFSocketCreateWithSocketSignature(kCFAllocatorDefault
,
287 &signature
, // Socket signature.
288 kCFSocketAcceptCallBack
, // Callback types.
289 SocketAcceptCallback
, // Callout function pointer.
290 &context
); // Context to pass to callout.
292 [self errorEncountered
:@
"Could not open socket."];
297 // Allow old, yet-to-be recycled sockets to be reused.
299 setsockopt(CFSocketGetNative(socket_
), SOL_SOCKET
, SO_REUSEADDR
, &yes
, sizeof(BOOL));
300 setsockopt(CFSocketGetNative(socket_
), SOL_SOCKET
, SO_REUSEPORT
, &yes
, sizeof(BOOL));
302 // Schedule the socket on the run loop.
303 CFRunLoopSourceRef source
= CFSocketCreateRunLoopSource(kCFAllocatorDefault
, socket_
, 0);
304 CFRunLoopAddSource([runLoop_ getCFRunLoop
], source
, kCFRunLoopCommonModes
);
307 // Create a source that is used to quit.
308 CFRunLoopSourceContext quitContext
= { 0 };
309 quitContext.version
= 0;
310 quitContext.info
= self;
311 quitContext.perform
= PerformQuitSignal
;
312 quitSource_
= CFRunLoopSourceCreate(kCFAllocatorDefault
, 0, &quitContext
);
313 CFRunLoopAddSource([runLoop_ getCFRunLoop
], quitSource_
, kCFRunLoopCommonModes
);
320 CFRunLoopSourceInvalidate(quitSource_
);
321 CFRelease(quitSource_
);
328 * Called by SocketWrapper after the connection is successful. This immediately calls
329 * -[SocketWrapper receive] to clear the way for communication, though the information
330 * could be useful server information that we don't use right now.
332 - (void)socketDidAccept
336 lastReadTransaction_
= 0;
337 lastWrittenTransaction_
= 0;
338 self.queuedWrites
= [NSMutableArray array
];
339 writeQueueLock_
= [NSRecursiveLock
new];
343 * Closes a socket and releases the ref.
350 if (runLoop_
&& quitSource_
) {
351 CFRunLoopSourceSignal(quitSource_
);
352 CFRunLoopWakeUp([runLoop_ getCFRunLoop
]);
357 * Quits the run loop and stops the thread.
359 - (void)performQuitSignal
361 self.queuedWrites
= nil;
363 [writeQueueLock_ release
];
366 CFRunLoopStop([runLoop_ getCFRunLoop
]);
369 // The socket goes down, so do the streams, which clean themselves up.
371 NSLog(@
"invalidating socket");
372 CFSocketInvalidate(socket_
);
379 * Notification that the socket disconnected.
381 - (void)socketDisconnected
384 // The state still is connected, which means that we did not get here
385 // through normal disconnected procedure (a call to |-close|, followed by
386 // the downing of the socket and the stream, which also produces this
387 // messsage). Instead, the stream callbacks encountered EOF unexpectedly.
390 if ([delegate_ respondsToSelector
:@selector(connectionDidClose
:)])
391 [delegate_ connectionDidClose
:self];
395 * Writes a command into the write stream. If the stream is ready for writing,
396 * we do so immediately. If not, the command is queued and will be written
397 * when the stream is ready.
399 - (void)send
:(NSString
*)command
401 if (lastReadTransaction_
>= lastWrittenTransaction_
&& CFWriteStreamCanAcceptBytes(writeStream_
)) {
402 [self performSend
:command
];
404 [writeQueueLock_ lock
];
405 [queuedWrites_ addObject
:command
];
406 [writeQueueLock_ unlock
];
408 [self sendQueuedWrites
];
412 * This will send a command to the debugger engine. It will append the
413 * transaction ID automatically. It accepts a NSString command along with a
414 * a variable number of arguments to substitute into the command, a la
415 * +[NSString stringWithFormat:]. Returns the transaction ID as a NSNumber.
417 - (NSNumber
*)sendCommandWithFormat
:(NSString
*)format
, ...
419 // Collect varargs and format command.
421 va_start(args
, format
);
422 NSString
* command
= [[NSString alloc
] initWithFormat
:format arguments
:args
];
425 NSNumber
* callbackKey
= [NSNumber numberWithInt
:transactionID
++];
426 NSString
* taggedCommand
= [NSString stringWithFormat
:@
"%@ -i %@", [command autorelease
], callbackKey
];
427 [self performSelector
:@selector(send
:)
429 withObject
:taggedCommand
430 waitUntilDone
:connected_
];
436 * Given a file path, this returns a file:// URI and escapes any spaces for the
439 - (NSString
*)escapedURIPath
:(NSString
*)path
441 // Custon GDBp paths are fine.
442 if ([[path substringToIndex
:4] isEqualToString
:@
"gdbp"])
445 // Create a temporary URL that will escape all the nasty characters.
446 NSURL
* url
= [NSURL fileURLWithPath
:path
];
447 NSString
* urlString
= [url absoluteString
];
449 // Remove the host because this is a file:// URL;
450 urlString
= [urlString stringByReplacingOccurrencesOfString
:[url host
] withString
:@
""];
452 // Escape % for use in printf-style NSString formatters.
453 urlString
= [urlString stringByReplacingOccurrencesOfString
:@
"%" withString
:@
"%%"];
458 * Returns the transaction_id from an NSXMLDocument.
460 - (NSInteger
)transactionIDFromResponse
:(NSXMLDocument
*)response
462 return [[[[response rootElement
] attributeForName
:@
"transaction_id"] stringValue
] intValue
];
466 * Scans a command string for the transaction ID component. If it is not found,
467 * returns NSNotFound.
469 - (NSInteger
)transactionIDFromCommand
:(NSString
*)command
471 NSRange occurrence
= [command rangeOfString
:@
"-i "];
472 if (occurrence.location
== NSNotFound
)
474 NSString
* transaction
= [command substringFromIndex
:occurrence.location
+ occurrence.length
];
475 return [transaction intValue
];
478 // Private /////////////////////////////////////////////////////////////////////
481 // Delegate Thread-Safe Wrappers ///////////////////////////////////////////////
484 * Receives errors from the SocketWrapper and updates the display
486 - (void)errorEncountered
:(NSString
*)error
488 if (![delegate_ respondsToSelector
:@selector(errorEncountered
:)])
490 [delegate_ performSelectorOnMainThread
:@selector(errorEncountered
:)
495 - (LogEntry
*)recordSend
:(NSString
*)command
497 LoggingController
* logger
= [[AppDelegate instance
] loggingController
];
498 LogEntry
* entry
= [LogEntry newSendEntry
:command
];
499 entry.lastReadTransactionID
= lastReadTransaction_
;
500 entry.lastWrittenTransactionID
= lastWrittenTransaction_
;
501 [logger performSelectorOnMainThread
:@selector(recordEntry
:)
504 return [entry autorelease
];
507 - (LogEntry
*)recordReceive
:(NSString
*)command
509 LoggingController
* logger
= [[AppDelegate instance
] loggingController
];
510 LogEntry
* entry
= [LogEntry newReceiveEntry
:command
];
511 entry.lastReadTransactionID
= lastReadTransaction_
;
512 entry.lastWrittenTransactionID
= lastWrittenTransaction_
;
513 [logger performSelectorOnMainThread
:@selector(recordEntry
:)
516 return [entry autorelease
];
519 // Stream Managers /////////////////////////////////////////////////////////////
522 * Callback from the CFReadStream that there is data waiting to be read.
524 - (void)readStreamHasData
526 const NSUInteger kBufferSize
= 1024;
527 UInt8 buffer
[kBufferSize
];
528 CFIndex bufferOffset
= 0; // Starting point in |buffer| to work with.
529 CFIndex bytesRead
= CFReadStreamRead(readStream_
, buffer
, kBufferSize
);
530 const char* charBuffer
= (const char*)buffer
;
532 // The read loop works by going through the buffer until all the bytes have
534 while (bufferOffset
< bytesRead
)
536 // Find the NULL separator, or the end of the string.
537 NSUInteger partLength
= 0;
538 for (NSUInteger i
= bufferOffset
; i
< bytesRead
&& charBuffer
[i
] != '\0'; ++i
, ++partLength
) ;
540 // If there is not a current packet, set some state.
541 if (!self.currentPacket
)
543 // Read the message header: the size. This will be |partLength| bytes.
544 packetSize_
= atoi(charBuffer
+ bufferOffset
);
545 currentPacketIndex_
= 0;
546 self.currentPacket
= [NSMutableString stringWithCapacity
:packetSize_
];
547 bufferOffset
+= partLength
+ 1; // Pass over the NULL byte.
548 continue; // Spin the loop to begin reading actual data.
551 // Substring the byte stream and append it to the packet string.
552 CFStringRef bufferString
= CFStringCreateWithBytes(kCFAllocatorDefault
,
553 buffer
+ bufferOffset
, // Byte pointer, offset by start index.
554 partLength
, // Length.
555 kCFStringEncodingUTF8
,
557 [self.currentPacket appendString
:(NSString
*)bufferString
];
558 CFRelease(bufferString
);
561 currentPacketIndex_
+= partLength
;
562 bufferOffset
+= partLength
+ 1;
564 // If this read finished the packet, handle it and reset.
565 if (currentPacketIndex_
>= packetSize_
)
567 [self handlePacket
:[[currentPacket_ retain
] autorelease
]];
568 self.currentPacket
= nil;
570 currentPacketIndex_
= 0;
576 * Performs the packet handling of a raw string XML packet. From this point on,
577 * the packets are associated with a transaction and are then dispatched.
579 - (void)handlePacket
:(NSString
*)packet
581 // Test if we can convert it into an NSXMLDocument.
582 NSError
* error
= nil;
583 NSXMLDocument
* xmlTest
= [[NSXMLDocument alloc
] initWithXMLString
:currentPacket_ options
:NSXMLDocumentTidyXML error
:&error
];
585 // Try to recover if we encountered an error.
588 // We do not want to starve the write queue, so manually parse out the
590 NSRange location
= [currentPacket_ rangeOfString
:@
"transaction_id"];
591 if (location.location
!= NSNotFound
)
593 NSUInteger start
= location.location
+ location.length
;
594 NSUInteger end
= start
;
596 NSCharacterSet
* numericSet
= [NSCharacterSet decimalDigitCharacterSet
];
598 // Loop over the characters after the attribute name to extract the ID.
599 while (end
< [currentPacket_ length
])
601 unichar c
= [currentPacket_ characterAtIndex
:end
];
602 if ([numericSet characterIsMember
:c
])
604 // If this character is numeric, extend the range to substring.
611 // If this character is nonnumeric and we have nothing in the
612 // range, skip this character.
618 // We've moved past the numeric ID so we should stop searching.
624 // If we were able to extract the transaction ID, update the last read.
625 NSRange substringRange
= NSMakeRange(start
, end
- start
);
626 NSString
* transactionStr
= [currentPacket_ substringWithRange
:substringRange
];
627 if ([transactionStr length
])
628 lastReadTransaction_
= [transactionStr intValue
];
631 // Otherwise, assume +1 and hope it works.
632 ++lastReadTransaction_
;
633 } else if (!reconnect_
) {
634 // See if the transaction can be parsed out.
635 NSInteger transaction
= [self transactionIDFromResponse
:xmlTest
];
636 if (transaction
< lastReadTransaction_
) {
637 NSLog(@
"tx = %d vs %d", transaction
, lastReadTransaction_
);
638 NSLog(@
"out of date transaction %@", packet
);
642 if (transaction
!= lastWrittenTransaction_
)
643 NSLog(@
"txn %d <> %d last written, %d last read", transaction
, lastWrittenTransaction_
, lastReadTransaction_
);
645 lastReadTransaction_
= transaction
;
648 // Log this receive event.
649 LogEntry
* log
= [self recordReceive
:currentPacket_
];
652 // Finally, dispatch the handler for this response.
653 [self handleResponse
:[xmlTest autorelease
]];
656 - (void)handleResponse
:(NSXMLDocument
*)response
658 // Check and see if there's an error.
659 NSArray
* error
= [[response rootElement
] elementsForName
:@
"error"];
660 if ([error count
] > 0)
662 NSLog(@
"Xdebug error: %@", error
);
663 NSString
* errorMessage
= [[[[error objectAtIndex
:0] children
] objectAtIndex
:0] stringValue
];
664 [self errorEncountered
:errorMessage
];
667 if ([[[response rootElement
] name
] isEqualToString
:@
"init"]) {
670 [delegate_ performSelectorOnMainThread
:@selector(handleInitialResponse
:)
676 if ([delegate_ respondsToSelector
:@selector(handleResponse
:)])
677 [delegate_ performSelectorOnMainThread
:@selector(handleResponse
:)
681 [self sendQueuedWrites
];
685 * This performs a blocking send. This should ONLY be called when we know we
686 * have write access to the stream. We will busy wait in case we don't do a full
689 - (void)performSend
:(NSString
*)command
691 // If this is an out-of-date transaction, do not bother sending it.
692 NSInteger transaction
= [self transactionIDFromCommand
:command
];
693 if (transaction
!= NSNotFound
&& transaction
< lastWrittenTransaction_
)
698 char* string
= (char*)[command UTF8String
];
699 int stringLength
= strlen(string
);
701 // Busy wait while writing. BAADD. Should background this operation.
704 if (CFWriteStreamCanAcceptBytes(writeStream_
))
706 // Include the NULL byte in the string when we write.
707 int bytesWritten
= CFWriteStreamWrite(writeStream_
, (UInt8
*)string
, stringLength
+ 1);
708 if (bytesWritten
< 0)
710 NSLog(@
"write error");
713 else if (bytesWritten
< strlen(string
))
715 // Adjust the buffer and wait for another chance to write.
716 stringLength
-= bytesWritten
;
717 memmove(string
, string
+ bytesWritten
, stringLength
);
723 // We need to scan the string to find the transactionID.
724 if (transaction
== NSNotFound
)
726 NSLog(@
"sent %@ without a transaction ID", command
);
729 lastWrittenTransaction_
= transaction
;
734 // Log this trancation.
735 [self recordSend
:command
];
739 * Checks if there are unsent commands in the |queuedWrites_| queue and sends
740 * them if it's OK to do so. This will not block.
742 - (void)sendQueuedWrites
747 [writeQueueLock_ lock
];
748 if (lastReadTransaction_
>= lastWrittenTransaction_
&& [queuedWrites_ count
] > 0)
750 NSString
* command
= [queuedWrites_ objectAtIndex
:0];
752 // We don't want to block because this is called from the main thread.
753 // |-performSend:| busy waits when the stream is not ready. Bail out
754 // before we do that becuase busy waiting is BAD.
755 if (CFWriteStreamCanAcceptBytes(writeStream_
))
757 [self performSend
:command
];
758 [queuedWrites_ removeObjectAtIndex
:0];
761 [writeQueueLock_ unlock
];