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 <sys/socket.h>
18 #import <netinet/in.h>
20 #import "DebuggerConnection.h"
22 #import "AppDelegate.h"
23 #import "LoggingController.h"
25 // GDBpConnection (Private) ////////////////////////////////////////////////////
27 @interface DebuggerConnection ()
28 @property (readwrite
, copy
) NSString
* status
;
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
;
39 - (void)socketDidAccept
;
40 - (void)socketDisconnected
;
41 - (void)readStreamHasData
;
42 - (void)send
:(NSString
*)command
;
43 - (void)performSend
:(NSString
*)command
;
44 - (void)errorEncountered
:(NSString
*)error
;
46 - (void)handleResponse
:(NSXMLDocument
*)response
;
47 - (void)initReceived
:(NSXMLDocument
*)response
;
48 - (void)updateStatus
:(NSXMLDocument
*)response
;
49 - (void)debuggerStep
:(NSXMLDocument
*)response
;
50 - (void)rebuildStack
:(NSXMLDocument
*)response
;
51 - (void)getStackFrame
:(NSXMLDocument
*)response
;
52 - (void)setSource
:(NSXMLDocument
*)response
;
53 - (void)contextsReceived
:(NSXMLDocument
*)response
;
54 - (void)variablesReceived
:(NSXMLDocument
*)response
;
55 - (void)propertiesReceived
:(NSXMLDocument
*)response
;
57 - (NSNumber
*)sendCommandWithCallback
:(SEL)callback format
:(NSString
*)format
, ...
;
59 - (void)sendQueuedWrites
;
61 - (NSString
*)escapedURIPath
:(NSString
*)path
;
62 - (NSInteger
)transactionIDFromResponse
:(NSXMLDocument
*)response
;
65 // CFNetwork Callbacks /////////////////////////////////////////////////////////
67 void ReadStreamCallback(CFReadStreamRef stream
, CFStreamEventType eventType
, void* connectionRaw
)
69 DebuggerConnection
* connection
= (DebuggerConnection
*)connectionRaw
;
72 case kCFStreamEventHasBytesAvailable
:
73 [connection readStreamHasData
];
76 case kCFStreamEventErrorOccurred
:
78 CFErrorRef error
= CFReadStreamCopyError(stream
);
79 CFReadStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
80 CFReadStreamClose(stream
);
82 [connection errorEncountered
:[[(NSError
*)error autorelease
] description
]];
86 case kCFStreamEventEndEncountered
:
87 CFReadStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
88 CFReadStreamClose(stream
);
90 [connection socketDisconnected
];
95 void WriteStreamCallback(CFWriteStreamRef stream
, CFStreamEventType eventType
, void* connectionRaw
)
97 DebuggerConnection
* connection
= (DebuggerConnection
*)connectionRaw
;
100 case kCFStreamEventCanAcceptBytes
:
101 [connection sendQueuedWrites
];
104 case kCFStreamEventErrorOccurred
:
106 CFErrorRef error
= CFWriteStreamCopyError(stream
);
107 CFWriteStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
108 CFWriteStreamClose(stream
);
110 [connection errorEncountered
:[[(NSError
*)error autorelease
] description
]];
114 case kCFStreamEventEndEncountered
:
115 CFWriteStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
116 CFWriteStreamClose(stream
);
118 [connection socketDisconnected
];
123 void SocketAcceptCallback(CFSocketRef socket
,
124 CFSocketCallBackType callbackType
,
129 assert(callbackType
== kCFSocketAcceptCallBack
);
130 NSLog(@
"SocketAcceptCallback()");
132 DebuggerConnection
* connection
= (DebuggerConnection
*)connectionRaw
;
134 CFReadStreamRef readStream
;
135 CFWriteStreamRef writeStream
;
137 // Create the streams on the socket.
138 CFStreamCreatePairWithSocket(kCFAllocatorDefault
,
139 *(CFSocketNativeHandle
*)data
, // Socket handle.
140 &readStream
, // Read stream in-pointer.
141 &writeStream
); // Write stream in-pointer.
143 // Create struct to register callbacks for the stream.
144 CFStreamClientContext context
;
146 context.info
= connection
;
147 context.retain
= NULL
;
148 context.release
= NULL
;
149 context.copyDescription
= NULL
;
151 // Set the client of the read stream.
152 CFOptionFlags readFlags
=
153 kCFStreamEventOpenCompleted |
154 kCFStreamEventHasBytesAvailable |
155 kCFStreamEventErrorOccurred |
156 kCFStreamEventEndEncountered
;
157 if (CFReadStreamSetClient(readStream
, readFlags
, ReadStreamCallback
, &context
))
158 // Schedule in run loop to do asynchronous communication with the engine.
159 CFReadStreamScheduleWithRunLoop(readStream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
163 // Open the stream now that it's scheduled on the run loop.
164 if (!CFReadStreamOpen(readStream
))
166 CFStreamError error
= CFReadStreamGetError(readStream
);
167 NSLog(@
"error! %@", error
);
171 // Set the client of the write stream.
172 CFOptionFlags writeFlags
=
173 kCFStreamEventOpenCompleted |
174 kCFStreamEventCanAcceptBytes |
175 kCFStreamEventErrorOccurred |
176 kCFStreamEventEndEncountered
;
177 if (CFWriteStreamSetClient(writeStream
, writeFlags
, WriteStreamCallback
, &context
))
178 // Schedule it in the run loop to receive error information.
179 CFWriteStreamScheduleWithRunLoop(writeStream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
183 // Open the write stream.
184 if (!CFWriteStreamOpen(writeStream
))
186 CFStreamError error
= CFWriteStreamGetError(writeStream
);
187 NSLog(@
"error! %@", error
);
191 connection.readStream
= readStream
;
192 connection.writeStream
= writeStream
;
193 [connection socketDidAccept
];
196 // GDBpConnection //////////////////////////////////////////////////////////////
198 @implementation DebuggerConnection
199 @synthesize socket
= socket_
;
200 @synthesize readStream
= readStream_
;
201 @synthesize lastReadTransaction
= lastReadTransaction_
;
202 @synthesize currentPacket
= currentPacket_
;
203 @synthesize writeStream
= writeStream_
;
204 @synthesize lastWrittenTransaction
= lastWrittenTransaction_
;
205 @synthesize queuedWrites
= queuedWrites_
;
207 @synthesize delegate
;
210 * Creates a new DebuggerConnection and initializes the socket from the given connection
213 - (id)initWithPort
:(NSUInteger
)aPort
215 if (self = [super init
])
220 [[BreakpointManager sharedManager
] setConnection
:self];
227 * Deallocates the object
232 self.currentPacket
= nil;
238 // Getters /////////////////////////////////////////////////////////////////////
242 * Gets the port number
250 * Returns the name of the remote host
252 - (NSString
*)remoteHost
256 return @
"(DISCONNECTED)";
258 // TODO: Either impl or remove.
263 * Returns whether or not we have an active connection
270 // Commands ////////////////////////////////////////////////////////////////////
271 #pragma mark Commands
274 * Reestablishes communication with the remote debugger so that a new connection doesn't have to be
275 * created every time you want to debug a page
280 self.status
= @
"Connecting";
285 * Tells the debugger to continue running the script. Returns the current stack frame.
289 [self sendCommandWithCallback
:@selector(debuggerStep
:) format
:@
"run"];
293 * Tells the debugger to step into the current command.
297 [self sendCommandWithCallback
:@selector(debuggerStep
:) format
:@
"step_into"];
301 * Tells the debugger to step out of the current context
305 [self sendCommandWithCallback
:@selector(debuggerStep
:) format
:@
"step_out"];
309 * Tells the debugger to step over the current function
313 [self sendCommandWithCallback
:@selector(debuggerStep
:) format
:@
"step_over"];
317 * Tells the debugger engine to get a specifc property. This also takes in the NSXMLElement
318 * that requested it so that the child can be attached.
320 - (NSInteger
)getProperty
:(NSString
*)property
322 [self sendCommandWithCallback
:@selector(propertiesReceived
:) format
:@
"property_get -n \"%@\"", property
];
325 // Breakpoint Management ///////////////////////////////////////////////////////
326 #pragma mark Breakpoints
329 * Send an add breakpoint command
331 - (void)addBreakpoint
:(Breakpoint
*)bp
336 NSString
* file
= [self escapedURIPath
:[bp transformedPath
]];
337 NSNumber
* transaction
= [self sendCommandWithCallback
:@selector(breakpointReceived
:)
338 format
:@
"breakpoint_set -t line -f %@ -n %i", file
, [bp line
]];
339 [callbackContext_ setObject
:bp forKey
:transaction
];
343 * Removes a breakpoint
345 - (void)removeBreakpoint
:(Breakpoint
*)bp
352 [self sendCommandWithCallback
:nil format
:@
"breakpoint_remove -d %i", [bp debuggerId
]];
356 // Socket and Stream Callbacks /////////////////////////////////////////////////
357 #pragma mark Callbacks
360 * Called by SocketWrapper after the connection is successful. This immediately calls
361 * -[SocketWrapper receive] to clear the way for communication, though the information
362 * could be useful server information that we don't use right now.
364 - (void)socketDidAccept
368 stackFrames_
= [[NSMutableDictionary alloc
] init
];
369 self.queuedWrites
= [NSMutableArray array
];
370 writeQueueLock_
= [NSRecursiveLock
new];
371 callTable_
= [NSMutableDictionary
new];
372 callbackContext_
= [NSMutableDictionary
new];
376 * Receives errors from the SocketWrapper and updates the display
378 - (void)errorEncountered
:(NSString
*)error
380 [delegate errorEncountered
:error
];
384 * Creates, connects to, and schedules a CFSocket.
388 // Pass ourselves to the callback so we don't have to use ugly globals.
389 CFSocketContext context
;
392 context.retain
= NULL
;
393 context.release
= NULL
;
394 context.copyDescription
= NULL
;
396 // Create the address structure.
397 struct sockaddr_in address
;
398 memset(&address
, 0, sizeof(address
));
399 address.sin_len
= sizeof(address
);
400 address.sin_family
= AF_INET
;
401 address.sin_port
= htons(port
);
402 address.sin_addr.s_addr
= htonl(INADDR_ANY
);
404 // Create the socket signature.
405 CFSocketSignature signature
;
406 signature.protocolFamily
= PF_INET
;
407 signature.socketType
= SOCK_STREAM
;
408 signature.protocol
= IPPROTO_TCP
;
409 signature.address
= (CFDataRef
)[NSData dataWithBytes
:&address length
:sizeof(address
)];
411 socket_
= CFSocketCreateWithSocketSignature(kCFAllocatorDefault
,
412 &signature
, // Socket signature.
413 kCFSocketAcceptCallBack
, // Callback types.
414 SocketAcceptCallback
, // Callout function pointer.
415 &context
); // Context to pass to callout.
418 [self errorEncountered
:@
"Could not open socket."];
422 // Allow old, yet-to-be recycled sockets to be reused.
424 setsockopt(CFSocketGetNative(socket_
), SOL_SOCKET
, SO_REUSEADDR
, &yes
, sizeof(BOOL));
426 // Schedule the socket on the run loop.
427 CFRunLoopSourceRef source
= CFSocketCreateRunLoopSource(kCFAllocatorDefault
, socket_
, 0);
428 CFRunLoopAddSource(CFRunLoopGetCurrent(), source
, kCFRunLoopCommonModes
);
431 self.status
= @
"Connecting";
435 * Closes a socket and releases the ref.
439 // The socket goes down, so do the streams, which clean themselves up.
440 CFSocketInvalidate(socket_
);
442 [stackFrames_ release
];
443 self.queuedWrites
= nil;
444 [writeQueueLock_ release
];
445 [callTable_ release
];
446 [callbackContext_ release
];
450 * Notification that the socket disconnected.
452 - (void)socketDisconnected
455 [delegate debuggerDisconnected
];
459 * Callback from the CFReadStream that there is data waiting to be read.
461 - (void)readStreamHasData
464 CFIndex bytesRead
= CFReadStreamRead(readStream_
, buffer
, 1024);
465 const char* charBuffer
= (const char*)buffer
;
467 // We haven't finished reading a packet, so just read more data in.
468 if (currentPacketIndex_
< packetSize_
)
470 currentPacketIndex_
+= bytesRead
;
471 CFStringRef bufferString
= CFStringCreateWithBytes(kCFAllocatorDefault
,
474 kCFStringEncodingUTF8
,
476 [self.currentPacket appendString
:(NSString
*)bufferString
];
477 CFRelease(bufferString
);
479 // Time to read a new packet.
482 // Read the message header: the size.
483 packetSize_
= atoi(charBuffer
);
484 currentPacketIndex_
= bytesRead
- strlen(charBuffer
);
485 CFStringRef bufferString
= CFStringCreateWithBytes(kCFAllocatorDefault
,
486 buffer
+ strlen(charBuffer
) + 1,
487 bytesRead
- strlen(charBuffer
) - 1,
488 kCFStringEncodingUTF8
,
490 self.currentPacket
= [NSMutableString stringWithString
:(NSString
*)bufferString
];
491 CFRelease(bufferString
);
494 // We have finished reading the packet.
495 if (currentPacketIndex_
>= packetSize_
)
498 currentPacketIndex_
= 0;
500 // Test if we can convert it into an NSXMLDocument.
501 NSError
* error
= nil;
502 NSXMLDocument
* xmlTest
= [[NSXMLDocument alloc
] initWithXMLString
:currentPacket_ options
:NSXMLDocumentTidyXML error
:&error
];
504 // Try to recover if we encountered an error.
507 // We do not want to starve the write queue, so manually parse out the
509 NSRange location
= [currentPacket_ rangeOfString
:@
"transaction_id"];
510 if (location.location
!= NSNotFound
)
512 NSUInteger start
= location.location
+ location.length
;
513 NSUInteger end
= start
;
515 NSCharacterSet
* numericSet
= [NSCharacterSet decimalDigitCharacterSet
];
517 // Loop over the characters after the attribute name to extract the ID.
518 while (end
< [currentPacket_ length
])
520 unichar c
= [currentPacket_ characterAtIndex
:end
];
521 if ([numericSet characterIsMember
:c
])
523 // If this character is numeric, extend the range to substring.
530 // If this character is nonnumeric and we have nothing in the
531 // range, skip this character.
537 // We've moved past the numeric ID so we should stop searching.
543 // If we were able to extract the transaction ID, update the last read.
544 NSRange substringRange
= NSMakeRange(start
, end
- start
);
545 NSString
* transaction
= [currentPacket_ substringWithRange
:substringRange
];
546 if ([transaction length
])
547 lastReadTransaction_
= [transaction intValue
];
550 // Otherwise, assume +1 and hope it works.
551 ++lastReadTransaction_
;
555 // See if the transaction can be parsed out.
556 NSInteger transaction
= [self transactionIDFromResponse
:xmlTest
];
557 if (transaction
< lastReadTransaction_ || transaction
!= lastWrittenTransaction_
)
559 NSLog(@
"tx = %d vs %d", transaction
, lastReadTransaction_
);
560 NSLog(@
"out of date transaction %@", xmlTest
);
564 if (transaction
!= lastWrittenTransaction_
)
565 NSLog(@
"txn doesn't match last written %@", xmlTest
);
567 lastReadTransaction_
= transaction
;
570 // Log this receive event.
571 LoggingController
* logger
= [(AppDelegate
*)[NSApp delegate
] loggingController
];
572 LogEntry
* log
= [logger recordReceive
:currentPacket_
];
574 log.lastWrittenTransactionID
= lastWrittenTransaction_
;
575 log.lastReadTransactionID
= lastReadTransaction_
;
577 // Finally, dispatch the handler for this response.
578 [self handleResponse
:[xmlTest autorelease
]];
583 * Writes a command into the write stream. If the stream is ready for writing,
584 * we do so immediately. If not, the command is queued and will be written
585 * when the stream is ready.
587 - (void)send
:(NSString
*)command
589 if (lastReadTransaction_
>= lastWrittenTransaction_
&& CFWriteStreamCanAcceptBytes(writeStream_
))
590 [self performSend
:command
];
592 [queuedWrites_ addObject
:command
];
593 [self sendQueuedWrites
];
597 * This performs a blocking send. This should ONLY be called when we know we
598 * have write access to the stream. We will busy wait in case we don't do a full
601 - (void)performSend
:(NSString
*)command
605 char* string
= (char*)[command UTF8String
];
606 int stringLength
= strlen(string
);
608 // Busy wait while writing. BAADD. Should background this operation.
611 if (CFWriteStreamCanAcceptBytes(writeStream_
))
613 // Include the NULL byte in the string when we write.
614 int bytesWritten
= CFWriteStreamWrite(writeStream_
, (UInt8
*)string
, stringLength
+ 1);
615 if (bytesWritten
< 0)
617 NSLog(@
"write error");
620 else if (bytesWritten
< strlen(string
))
622 // Adjust the buffer and wait for another chance to write.
623 stringLength
-= bytesWritten
;
624 memmove(string
, string
+ bytesWritten
, stringLength
);
630 // We need to scan the string to find the transactionID.
631 NSRange occurrence
= [command rangeOfString
:@
"-i "];
632 if (occurrence.location
== NSNotFound
)
634 NSLog(@
"sent %@ without a transaction ID", command
);
637 NSString
* transaction
= [command substringFromIndex
:occurrence.location
+ occurrence.length
];
638 lastWrittenTransaction_
= [transaction intValue
];
643 // Log this trancation.
644 LoggingController
* logger
= [(AppDelegate
*)[NSApp delegate
] loggingController
];
645 LogEntry
* log
= [logger recordSend
:command
];
646 log.lastWrittenTransactionID
= lastWrittenTransaction_
;
647 log.lastReadTransactionID
= lastReadTransaction_
;
650 - (void)handleResponse
:(NSXMLDocument
*)response
652 // Check and see if there's an error.
653 NSArray
* error
= [[response rootElement
] elementsForName
:@
"error"];
654 if ([error count
] > 0)
656 NSLog(@
"Xdebug error: %@", error
);
657 [delegate errorEncountered
:[[[[error objectAtIndex
:0] children
] objectAtIndex
:0] stringValue
]];
660 if ([[[response rootElement
] name
] isEqualToString
:@
"init"])
662 [self initReceived
:response
];
666 NSString
* callbackStr
= [callTable_ objectForKey
:[NSNumber numberWithInt
:lastReadTransaction_
]];
669 SEL callback
= NSSelectorFromString(callbackStr
);
670 [self performSelector
:callback withObject
:response
];
673 [self sendQueuedWrites
];
676 // Specific Response Handlers //////////////////////////////////////////////////
677 #pragma mark Response Handlers
680 * Initial packet received. We've started a brand-new connection to the engine.
682 - (void)initReceived
:(NSXMLDocument
*)response
684 // Register any breakpoints that exist offline.
685 for (Breakpoint
* bp
in [[BreakpointManager sharedManager
] breakpoints
])
686 [self addBreakpoint
:bp
];
688 // Load the debugger to make it look active.
689 [delegate debuggerConnected
];
691 // TODO: update the status.
695 * Receiver for status updates. This just freshens up the UI.
697 - (void)updateStatus
:(NSXMLDocument
*)response
699 self.status
= [[[[response rootElement
] attributeForName
:@
"status"] stringValue
] capitalizedString
];
700 if (status
== nil ||
[status isEqualToString
:@
"Stopped"] ||
[status isEqualToString
:@
"Stopping"])
704 [delegate debuggerDisconnected
];
706 self.status
= @
"Stopped";
711 * Step in/out/over and run all take this path. We first get the status of the
712 * debugger and then request fresh stack information.
714 - (void)debuggerStep
:(NSXMLDocument
*)response
716 [self updateStatus
:response
];
720 // If this is the run command, tell the delegate that a bunch of updates
721 // are coming. Also remove all existing stack routes and request a new stack.
722 // TODO: figure out if we can not clobber the stack every time.
723 NSString
* command
= [[[response rootElement
] attributeForName
:@
"command"] stringValue
];
724 if (YES ||
[command isEqualToString
:@
"run"])
726 if ([delegate respondsToSelector
:@selector(clobberStack
)])
727 [delegate clobberStack
];
728 [stackFrames_ removeAllObjects
];
729 stackFirstTransactionID_
= [[self sendCommandWithCallback
:@selector(rebuildStack
:) format
:@
"stack_depth"] intValue
];
734 * We ask for the stack_depth and now we clobber the stack and start rebuilding
737 - (void)rebuildStack
:(NSXMLDocument
*)response
739 NSInteger depth
= [[[[response rootElement
] attributeForName
:@
"depth"] stringValue
] intValue
];
741 if (stackFirstTransactionID_
== [self transactionIDFromResponse
:response
])
744 // We now need to alloc a bunch of stack frames and get the basic information
746 for (NSInteger i
= 0; i
< depth
; i
++)
748 // Use the transaction ID to create a routing path.
749 NSNumber
* routingID
= [self sendCommandWithCallback
:@selector(getStackFrame
:) format
:@
"stack_get -d %d", i
];
750 [stackFrames_ setObject
:[StackFrame alloc
] forKey
:routingID
];
755 * The initial rebuild of the stack frame. We now have enough to initialize
756 * a StackFrame object.
758 - (void)getStackFrame
:(NSXMLDocument
*)response
760 // Get the routing information.
761 NSInteger routingID
= [self transactionIDFromResponse
:response
];
762 if (routingID
< stackFirstTransactionID_
)
764 NSNumber
* routingNumber
= [NSNumber numberWithInt
:routingID
];
766 // Make sure we initialized this frame in our last |-rebuildStack:|.
767 StackFrame
* frame
= [stackFrames_ objectForKey
:routingNumber
];
771 NSXMLElement
* xmlframe
= [[[response rootElement
] children
] objectAtIndex
:0];
773 // Initialize the stack frame.
774 [frame initWithIndex
:[[[xmlframe attributeForName
:@
"level"] stringValue
] intValue
]
775 withFilename
:[[xmlframe attributeForName
:@
"filename"] stringValue
]
777 atLine
:[[[xmlframe attributeForName
:@
"lineno"] stringValue
] intValue
]
778 inFunction
:[[xmlframe attributeForName
:@
"where"] stringValue
]
781 // Get the source code of the file. Escape % in URL chars.
782 NSString
* escapedFilename
= [frame.filename stringByReplacingOccurrencesOfString
:@
"%" withString
:@
"%%"];
783 NSNumber
* transaction
= [self sendCommandWithCallback
:@selector(setSource
:) format
:@
"source -f %@", escapedFilename
];
784 [callbackContext_ setObject
:routingNumber forKey
:transaction
];
786 // Get the names of all the contexts.
787 transaction
= [self sendCommandWithCallback
:@selector(contextsReceived
:) format
:@
"context_names -d %d", frame.index
];
788 [callbackContext_ setObject
:routingNumber forKey
:transaction
];
790 if ([delegate respondsToSelector
:@selector(newStackFrame
:)])
791 [delegate newStackFrame
:frame
];
795 * Callback for setting the source of a file while rebuilding a specific stack
798 - (void)setSource
:(NSXMLDocument
*)response
800 NSNumber
* transaction
= [NSNumber numberWithInt
:[self transactionIDFromResponse
:response
]];
801 if ([transaction intValue
] < stackFirstTransactionID_
)
803 NSNumber
* routingNumber
= [callbackContext_ objectForKey
:transaction
];
807 [callbackContext_ removeObjectForKey
:transaction
];
808 StackFrame
* frame
= [stackFrames_ objectForKey
:routingNumber
];
812 frame.source
= [[response rootElement
] value
];
814 if ([delegate respondsToSelector
:@selector(sourceUpdated
:)])
815 [delegate sourceUpdated
:frame
];
819 * Enumerates all the contexts of a given stack frame. We then in turn get the
820 * contents of each one of these contexts.
822 - (void)contextsReceived
:(NSXMLDocument
*)response
824 // Get the stack frame's routing ID and use it again.
825 NSNumber
* receivedTransaction
= [NSNumber numberWithInt
:[self transactionIDFromResponse
:response
]];
826 if ([receivedTransaction intValue
] < stackFirstTransactionID_
)
828 NSNumber
* routingID
= [callbackContext_ objectForKey
:receivedTransaction
];
832 // Get the stack frame by the |routingID|.
833 StackFrame
* frame
= [stackFrames_ objectForKey
:routingID
];
835 NSXMLElement
* contextNames
= [response rootElement
];
836 for (NSXMLElement
* context
in [contextNames children
])
838 NSInteger cid
= [[[context attributeForName
:@
"id"] stringValue
] intValue
];
840 // Fetch each context's variables.
841 NSNumber
* transaction
= [self sendCommandWithCallback
:@selector(variablesReceived
:)
842 format
:@
"context_get -d %d -c %d", frame.index
, cid
];
843 [callbackContext_ setObject
:routingID forKey
:transaction
];
848 * Receives the variables from the context and attaches them to the stack frame.
850 - (void)variablesReceived
:(NSXMLDocument
*)response
852 // Get the stack frame's routing ID and use it again.
853 NSInteger transaction
= [self transactionIDFromResponse
:response
];
854 if (transaction
< stackFirstTransactionID_
)
856 NSNumber
* receivedTransaction
= [NSNumber numberWithInt
:transaction
];
857 NSNumber
* routingID
= [callbackContext_ objectForKey
:receivedTransaction
];
861 // Get the stack frame by the |routingID|.
862 StackFrame
* frame
= [stackFrames_ objectForKey
:routingID
];
864 NSMutableArray
* variables
= [NSMutableArray array
];
866 // Merge the frame's existing variables.
868 [variables addObjectsFromArray
:frame.variables
];
870 // Add these new variables.
871 NSArray
* addVariables
= [[response rootElement
] children
];
873 [variables addObjectsFromArray
:addVariables
];
875 frame.variables
= variables
;
879 * Callback from a |-getProperty:| request.
881 - (void)propertiesReceived
:(NSXMLDocument
*)response
883 NSInteger transaction
= [self transactionIDFromResponse
:response
];
887 <property> <!-- this is the one we requested -->
888 <property ... /> <!-- these are what we want -->
893 // Detach all the children so we can insert them into another document.
894 NSXMLElement
* parent
= (NSXMLElement
*)[[response rootElement
] childAtIndex
:0];
895 NSArray
* children
= [parent children
];
896 [parent setChildren
:nil];
898 [delegate receivedProperties
:children forTransaction
:transaction
];
902 * Callback for setting a breakpoint.
904 - (void)breakpointReceived
:(NSXMLDocument
*)response
906 NSNumber
* transaction
= [NSNumber numberWithInt
:[self transactionIDFromResponse
:response
]];
907 Breakpoint
* bp
= [callbackContext_ objectForKey
:transaction
];
911 [callbackContext_ removeObjectForKey
:callbackContext_
];
912 [bp setDebuggerId
:[[[[response rootElement
] attributeForName
:@
"id"] stringValue
] intValue
]];
918 * This will send a command to the debugger engine. It will append the
919 * transaction ID automatically. It accepts a NSString command along with a
920 * a variable number of arguments to substitute into the command, a la
921 * +[NSString stringWithFormat:]. Returns the transaction ID as a NSNumber.
923 - (NSNumber
*)sendCommandWithCallback
:(SEL)callback format
:(NSString
*)format
, ...
925 // Collect varargs and format command.
927 va_start(args
, format
);
928 NSString
* command
= [[NSString alloc
] initWithFormat
:format arguments
:args
];
931 NSNumber
* callbackKey
= [NSNumber numberWithInt
:transactionID
++];
933 [callTable_ setObject
:NSStringFromSelector(callback
) forKey
:callbackKey
];
935 [self send
:[NSString stringWithFormat
:@
"%@ -i %@", [command autorelease
], callbackKey
]];
941 * Checks if there are unsent commands in the |queuedWrites_| queue and sends
942 * them if it's OK to do so. This will not block.
944 - (void)sendQueuedWrites
949 [writeQueueLock_ lock
];
950 if (lastReadTransaction_
>= lastWrittenTransaction_
&& [queuedWrites_ count
] > 0)
952 NSString
* command
= [queuedWrites_ objectAtIndex
:0];
954 // We don't want to block because this is called from the main thread.
955 // |-performSend:| busy waits when the stream is not ready. Bail out
956 // before we do that becuase busy waiting is BAD.
957 if (CFWriteStreamCanAcceptBytes(writeStream_
))
959 [self performSend
:command
];
960 [queuedWrites_ removeObjectAtIndex
:0];
963 [writeQueueLock_ unlock
];
967 * Given a file path, this returns a file:// URI and escapes any spaces for the
970 - (NSString
*)escapedURIPath
:(NSString
*)path
972 // Custon GDBp paths are fine.
973 if ([[path substringToIndex
:4] isEqualToString
:@
"gdbp"])
976 // Create a temporary URL that will escape all the nasty characters.
977 NSURL
* url
= [NSURL fileURLWithPath
:path
];
978 NSString
* urlString
= [url absoluteString
];
980 // Remove the host because this is a file:// URL;
981 urlString
= [urlString stringByReplacingOccurrencesOfString
:[url host
] withString
:@
""];
983 // Escape % for use in printf-style NSString formatters.
984 urlString
= [urlString stringByReplacingOccurrencesOfString
:@
"%" withString
:@
"%%"];
989 * Returns the transaction_id from an NSXMLDocument.
991 - (NSInteger
)transactionIDFromResponse
:(NSXMLDocument
*)response
993 return [[[[response rootElement
] attributeForName
:@
"transaction_id"] stringValue
] intValue
];