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
;
127 CFReadStreamRef readStream
;
128 CFWriteStreamRef writeStream
;
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.
136 // Create struct to register callbacks for the stream.
137 CFStreamClientContext context
;
139 context.info
= connection
;
140 context.retain
= NULL
;
141 context.release
= NULL
;
142 context.copyDescription
= NULL
;
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
);
156 // Open the stream now that it's scheduled on the run loop.
157 if (!CFReadStreamOpen(readStream
))
159 CFStreamError error
= CFReadStreamGetError(readStream
);
160 NSLog(@
"error! %@", error
);
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
);
176 // Open the write stream.
177 if (!CFWriteStreamOpen(writeStream
))
179 CFStreamError error
= CFWriteStreamGetError(writeStream
);
180 NSLog(@
"error! %@", error
);
184 connection.readStream
= readStream
;
185 connection.writeStream
= writeStream
;
186 [connection socketDidAccept
];
189 // Other Run Loop Callbacks ////////////////////////////////////////////////////
191 void PerformQuitSignal(void* info
)
193 DebuggerConnection
* obj
= (DebuggerConnection
*)info
;
194 [obj performQuitSignal
];
197 ////////////////////////////////////////////////////////////////////////////////
199 @implementation DebuggerConnection
201 @synthesize port
= port_
;
202 @synthesize connected
= connected_
;
203 @synthesize delegate
= delegate_
;
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_
;
213 - (id)initWithPort
:(NSUInteger
)aPort
215 if (self = [super init
])
224 self.currentPacket
= nil;
229 * Kicks off the socket on another thread.
233 [NSThread detachNewThreadSelector
:@selector(connectionThreadStart
) toTarget
:self withObject
:nil];
237 * Creates, connects to, and schedules a CFSocket.
239 - (void)connectionThreadStart
241 NSAutoreleasePool
* pool
= [[NSAutoreleasePool alloc
] init
];
243 thread_
= [NSThread currentThread
];
244 runLoop_
= [NSRunLoop currentRunLoop
];
246 // Pass ourselves to the callback so we don't have to use ugly globals.
247 CFSocketContext context
;
250 context.retain
= NULL
;
251 context.release
= NULL
;
252 context.copyDescription
= NULL
;
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
);
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
)];
269 socket_
= CFSocketCreateWithSocketSignature(kCFAllocatorDefault
,
270 &signature
, // Socket signature.
271 kCFSocketAcceptCallBack
, // Callback types.
272 SocketAcceptCallback
, // Callout function pointer.
273 &context
); // Context to pass to callout.
276 [self errorEncountered
:@
"Could not open socket."];
280 // Allow old, yet-to-be recycled sockets to be reused.
282 setsockopt(CFSocketGetNative(socket_
), SOL_SOCKET
, SO_REUSEADDR
, &yes
, sizeof(BOOL));
284 // Schedule the socket on the run loop.
285 CFRunLoopSourceRef source
= CFSocketCreateRunLoopSource(kCFAllocatorDefault
, socket_
, 0);
286 CFRunLoopAddSource([runLoop_ getCFRunLoop
], source
, kCFRunLoopCommonModes
);
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
);
302 CFRunLoopSourceInvalidate(quitSource_
);
303 CFRelease(quitSource_
);
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.
314 - (void)socketDidAccept
318 self.queuedWrites
= [NSMutableArray array
];
319 writeQueueLock_
= [NSRecursiveLock
new];
323 * Closes a socket and releases the ref.
327 if (runLoop_
&& quitSource_
) {
328 CFRunLoopSourceSignal(quitSource_
);
329 CFRunLoopWakeUp([runLoop_ getCFRunLoop
]);
334 * Quits the run loop and stops the thread.
336 - (void)performQuitSignal
339 CFRunLoopStop([runLoop_ getCFRunLoop
]);
342 // The socket goes down, so do the streams, which clean themselves up.
344 CFSocketInvalidate(socket_
);
349 self.queuedWrites
= nil;
351 [writeQueueLock_ release
];
355 * Notification that the socket disconnected.
357 - (void)socketDisconnected
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.
366 if ([delegate_ respondsToSelector
:@selector(connectionDidClose
:)])
367 [delegate_ connectionDidClose
:self];
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.
375 - (void)send
:(NSString
*)command
377 if (lastReadTransaction_
>= lastWrittenTransaction_
&& CFWriteStreamCanAcceptBytes(writeStream_
)) {
378 [self performSend
:command
];
380 [writeQueueLock_ lock
];
381 [queuedWrites_ addObject
:command
];
382 [writeQueueLock_ unlock
];
384 [self sendQueuedWrites
];
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.
393 - (NSNumber
*)sendCommandWithFormat
:(NSString
*)format
, ...
395 // Collect varargs and format command.
397 va_start(args
, format
);
398 NSString
* command
= [[NSString alloc
] initWithFormat
:format arguments
:args
];
401 NSNumber
* callbackKey
= [NSNumber numberWithInt
:transactionID
++];
402 NSString
* taggedCommand
= [NSString stringWithFormat
:@
"%@ -i %@", [command autorelease
], callbackKey
];
403 [self performSelector
:@selector(send
:)
405 withObject
:taggedCommand
412 * Given a file path, this returns a file:// URI and escapes any spaces for the
415 - (NSString
*)escapedURIPath
:(NSString
*)path
417 // Custon GDBp paths are fine.
418 if ([[path substringToIndex
:4] isEqualToString
:@
"gdbp"])
421 // Create a temporary URL that will escape all the nasty characters.
422 NSURL
* url
= [NSURL fileURLWithPath
:path
];
423 NSString
* urlString
= [url absoluteString
];
425 // Remove the host because this is a file:// URL;
426 urlString
= [urlString stringByReplacingOccurrencesOfString
:[url host
] withString
:@
""];
428 // Escape % for use in printf-style NSString formatters.
429 urlString
= [urlString stringByReplacingOccurrencesOfString
:@
"%" withString
:@
"%%"];
434 * Returns the transaction_id from an NSXMLDocument.
436 - (NSInteger
)transactionIDFromResponse
:(NSXMLDocument
*)response
438 return [[[[response rootElement
] attributeForName
:@
"transaction_id"] stringValue
] intValue
];
442 * Scans a command string for the transaction ID component. If it is not found,
443 * returns NSNotFound.
445 - (NSInteger
)transactionIDFromCommand
:(NSString
*)command
447 NSRange occurrence
= [command rangeOfString
:@
"-i "];
448 if (occurrence.location
== NSNotFound
)
450 NSString
* transaction
= [command substringFromIndex
:occurrence.location
+ occurrence.length
];
451 return [transaction intValue
];
454 // Private /////////////////////////////////////////////////////////////////////
457 // Delegate Thread-Safe Wrappers ///////////////////////////////////////////////
460 * Receives errors from the SocketWrapper and updates the display
462 - (void)errorEncountered
:(NSString
*)error
464 if (![delegate_ respondsToSelector
:@selector(errorEncountered
:)])
466 [delegate_ performSelectorOnMainThread
:@selector(errorEncountered
:)
471 - (LogEntry
*)recordSend
:(NSString
*)command
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
:)
480 return [entry autorelease
];
483 - (LogEntry
*)recordReceive
:(NSString
*)command
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
:)
492 return [entry autorelease
];
495 // Stream Managers /////////////////////////////////////////////////////////////
498 * Callback from the CFReadStream that there is data waiting to be read.
500 - (void)readStreamHasData
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
;
508 // The read loop works by going through the buffer until all the bytes have
510 while (bufferOffset
< bytesRead
)
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
) ;
516 // If there is not a current packet, set some state.
517 if (!self.currentPacket
)
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.
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
,
533 [self.currentPacket appendString
:(NSString
*)bufferString
];
534 CFRelease(bufferString
);
537 currentPacketIndex_
+= partLength
;
538 bufferOffset
+= partLength
+ 1;
540 // If this read finished the packet, handle it and reset.
541 if (currentPacketIndex_
>= packetSize_
)
543 [self handlePacket
:[[currentPacket_ retain
] autorelease
]];
544 self.currentPacket
= nil;
546 currentPacketIndex_
= 0;
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.
555 - (void)handlePacket
:(NSString
*)packet
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
];
561 // Try to recover if we encountered an error.
564 // We do not want to starve the write queue, so manually parse out the
566 NSRange location
= [currentPacket_ rangeOfString
:@
"transaction_id"];
567 if (location.location
!= NSNotFound
)
569 NSUInteger start
= location.location
+ location.length
;
570 NSUInteger end
= start
;
572 NSCharacterSet
* numericSet
= [NSCharacterSet decimalDigitCharacterSet
];
574 // Loop over the characters after the attribute name to extract the ID.
575 while (end
< [currentPacket_ length
])
577 unichar c
= [currentPacket_ characterAtIndex
:end
];
578 if ([numericSet characterIsMember
:c
])
580 // If this character is numeric, extend the range to substring.
587 // If this character is nonnumeric and we have nothing in the
588 // range, skip this character.
594 // We've moved past the numeric ID so we should stop searching.
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
];
607 // Otherwise, assume +1 and hope it works.
608 ++lastReadTransaction_
;
612 // See if the transaction can be parsed out.
613 NSInteger transaction
= [self transactionIDFromResponse
:xmlTest
];
614 if (transaction
< lastReadTransaction_
)
616 NSLog(@
"tx = %d vs %d", transaction
, lastReadTransaction_
);
617 NSLog(@
"out of date transaction %@", packet
);
621 if (transaction
!= lastWrittenTransaction_
)
622 NSLog(@
"txn %d <> %d last written, %d last read", transaction
, lastWrittenTransaction_
, lastReadTransaction_
);
624 lastReadTransaction_
= transaction
;
627 // Log this receive event.
628 LogEntry
* log
= [self recordReceive
:currentPacket_
];
631 // Finally, dispatch the handler for this response.
632 [self handleResponse
:[xmlTest autorelease
]];
635 - (void)handleResponse
:(NSXMLDocument
*)response
637 // Check and see if there's an error.
638 NSArray
* error
= [[response rootElement
] elementsForName
:@
"error"];
639 if ([error count
] > 0)
641 NSLog(@
"Xdebug error: %@", error
);
642 NSString
* errorMessage
= [[[[error objectAtIndex
:0] children
] objectAtIndex
:0] stringValue
];
643 [self errorEncountered
:errorMessage
];
646 if ([[[response rootElement
] name
] isEqualToString
:@
"init"])
648 [delegate_ performSelectorOnMainThread
:@selector(handleInitialResponse
:)
654 if ([delegate_ respondsToSelector
:@selector(handleResponse
:)])
655 [delegate_ performSelectorOnMainThread
:@selector(handleResponse
:)
659 [self sendQueuedWrites
];
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
667 - (void)performSend
:(NSString
*)command
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_
)
676 char* string
= (char*)[command UTF8String
];
677 int stringLength
= strlen(string
);
679 // Busy wait while writing. BAADD. Should background this operation.
682 if (CFWriteStreamCanAcceptBytes(writeStream_
))
684 // Include the NULL byte in the string when we write.
685 int bytesWritten
= CFWriteStreamWrite(writeStream_
, (UInt8
*)string
, stringLength
+ 1);
686 if (bytesWritten
< 0)
688 NSLog(@
"write error");
691 else if (bytesWritten
< strlen(string
))
693 // Adjust the buffer and wait for another chance to write.
694 stringLength
-= bytesWritten
;
695 memmove(string
, string
+ bytesWritten
, stringLength
);
701 // We need to scan the string to find the transactionID.
702 if (transaction
== NSNotFound
)
704 NSLog(@
"sent %@ without a transaction ID", command
);
707 lastWrittenTransaction_
= transaction
;
712 // Log this trancation.
713 [self recordSend
:command
];
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.
720 - (void)sendQueuedWrites
725 [writeQueueLock_ lock
];
726 if (lastReadTransaction_
>= lastWrittenTransaction_
&& [queuedWrites_ count
] > 0)
728 NSString
* command
= [queuedWrites_ objectAtIndex
:0];
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_
))
735 [self performSend
:command
];
736 [queuedWrites_ removeObjectAtIndex
:0];
739 [writeQueueLock_ unlock
];