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"
24 // GDBpConnection (Private) ////////////////////////////////////////////////////
26 @interface DebuggerConnection ()
27 @property (readwrite
, copy
) NSString
* status
;
28 @property (assign
) CFSocketRef socket
;
29 @property (assign
) CFReadStreamRef readStream
;
30 @property NSUInteger lastReadTransaction
;
31 @property (retain
) NSMutableString
* currentPacket
;
32 @property (assign
) CFWriteStreamRef writeStream
;
33 @property NSUInteger lastWrittenTransaction
;
34 @property (retain
) NSMutableArray
* queuedWrites
;
38 - (void)socketDidAccept
;
39 - (void)socketDisconnected
;
40 - (void)readStreamHasData
;
41 - (void)send
:(NSString
*)command
;
42 - (void)performSend
:(NSString
*)command
;
43 - (void)errorEncountered
:(NSString
*)error
;
45 - (void)handleResponse
:(NSXMLDocument
*)response
;
46 - (void)initReceived
:(NSXMLDocument
*)response
;
47 - (void)updateStatus
:(NSXMLDocument
*)response
;
48 - (void)debuggerStep
:(NSXMLDocument
*)response
;
49 - (void)rebuildStack
:(NSXMLDocument
*)response
;
50 - (void)getStackFrame
:(NSXMLDocument
*)response
;
51 - (void)setSource
:(NSXMLDocument
*)response
;
52 - (void)contextsReceived
:(NSXMLDocument
*)response
;
53 - (void)variablesReceived
:(NSXMLDocument
*)response
;
55 - (NSNumber
*)sendCommandWithCallback
:(SEL)callback format
:(NSString
*)format
, ...
;
57 - (void)sendQueuedWrites
;
59 - (NSString
*)escapedURIPath
:(NSString
*)path
;
60 - (NSInteger
)transactionIDFromResponse
:(NSXMLDocument
*)response
;
63 // CFNetwork Callbacks /////////////////////////////////////////////////////////
65 void ReadStreamCallback(CFReadStreamRef stream
, CFStreamEventType eventType
, void* connectionRaw
)
67 DebuggerConnection
* connection
= (DebuggerConnection
*)connectionRaw
;
70 case kCFStreamEventHasBytesAvailable
:
71 NSLog(@
"About to read.");
72 [connection readStreamHasData
];
75 case kCFStreamEventErrorOccurred
:
77 CFErrorRef error
= CFReadStreamCopyError(stream
);
78 CFReadStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
79 CFReadStreamClose(stream
);
81 [connection errorEncountered
:[[(NSError
*)error autorelease
] description
]];
85 case kCFStreamEventEndEncountered
:
86 CFReadStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
87 CFReadStreamClose(stream
);
89 [connection socketDisconnected
];
94 void WriteStreamCallback(CFWriteStreamRef stream
, CFStreamEventType eventType
, void* connectionRaw
)
96 DebuggerConnection
* connection
= (DebuggerConnection
*)connectionRaw
;
99 case kCFStreamEventCanAcceptBytes
:
100 [connection sendQueuedWrites
];
103 case kCFStreamEventErrorOccurred
:
105 CFErrorRef error
= CFWriteStreamCopyError(stream
);
106 CFWriteStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
107 CFWriteStreamClose(stream
);
109 [connection errorEncountered
:[[(NSError
*)error autorelease
] description
]];
113 case kCFStreamEventEndEncountered
:
114 CFWriteStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
115 CFWriteStreamClose(stream
);
117 [connection socketDisconnected
];
122 void SocketAcceptCallback(CFSocketRef socket
,
123 CFSocketCallBackType callbackType
,
128 assert(callbackType
== kCFSocketAcceptCallBack
);
129 NSLog(@
"SocketAcceptCallback()");
131 DebuggerConnection
* connection
= (DebuggerConnection
*)connectionRaw
;
133 CFReadStreamRef readStream
;
134 CFWriteStreamRef writeStream
;
136 // Create the streams on the socket.
137 CFStreamCreatePairWithSocket(kCFAllocatorDefault
,
138 *(CFSocketNativeHandle
*)data
, // Socket handle.
139 &readStream
, // Read stream in-pointer.
140 &writeStream
); // Write stream in-pointer.
142 // Create struct to register callbacks for the stream.
143 CFStreamClientContext context
;
145 context.info
= connection
;
146 context.retain
= NULL
;
147 context.release
= NULL
;
148 context.copyDescription
= NULL
;
150 // Set the client of the read stream.
151 CFOptionFlags readFlags
=
152 kCFStreamEventOpenCompleted |
153 kCFStreamEventHasBytesAvailable |
154 kCFStreamEventErrorOccurred |
155 kCFStreamEventEndEncountered
;
156 if (CFReadStreamSetClient(readStream
, readFlags
, ReadStreamCallback
, &context
))
157 // Schedule in run loop to do asynchronous communication with the engine.
158 CFReadStreamScheduleWithRunLoop(readStream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
162 // Open the stream now that it's scheduled on the run loop.
163 if (!CFReadStreamOpen(readStream
))
165 CFStreamError error
= CFReadStreamGetError(readStream
);
166 NSLog(@
"error! %@", error
);
170 // Set the client of the write stream.
171 CFOptionFlags writeFlags
=
172 kCFStreamEventOpenCompleted |
173 kCFStreamEventCanAcceptBytes |
174 kCFStreamEventErrorOccurred |
175 kCFStreamEventEndEncountered
;
176 if (CFWriteStreamSetClient(writeStream
, writeFlags
, WriteStreamCallback
, &context
))
177 // Schedule it in the run loop to receive error information.
178 CFWriteStreamScheduleWithRunLoop(writeStream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
182 // Open the write stream.
183 if (!CFWriteStreamOpen(writeStream
))
185 CFStreamError error
= CFWriteStreamGetError(writeStream
);
186 NSLog(@
"error! %@", error
);
190 connection.readStream
= readStream
;
191 connection.writeStream
= writeStream
;
192 [connection socketDidAccept
];
195 // GDBpConnection //////////////////////////////////////////////////////////////
197 @implementation DebuggerConnection
198 @synthesize socket
= socket_
;
199 @synthesize readStream
= readStream_
;
200 @synthesize lastReadTransaction
= lastReadTransaction_
;
201 @synthesize currentPacket
= currentPacket_
;
202 @synthesize writeStream
= writeStream_
;
203 @synthesize lastWrittenTransaction
= lastWrittenTransaction_
;
204 @synthesize queuedWrites
= queuedWrites_
;
206 @synthesize delegate
;
209 * Creates a new DebuggerConnection and initializes the socket from the given connection
212 - (id)initWithPort
:(NSUInteger
)aPort
214 if (self = [super init
])
219 [[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 * Creates an entirely new stack and returns it as an array of StackFrame objects.
287 - (NSArray
*)getCurrentStack
289 NSMutableArray
* stack
= [NSMutableArray array
];
290 NSLog(@
"NOTIMPLEMENTED(): %s", _cmd
);
295 * Tells the debugger to continue running the script. Returns the current stack frame.
299 [self sendCommandWithCallback
:@selector(debuggerStep
:) format
:@
"run"];
303 * Tells the debugger to step into the current command.
307 [self sendCommandWithCallback
:@selector(debuggerStep
:) format
:@
"step_into"];
311 * Tells the debugger to step out of the current context
315 [self sendCommandWithCallback
:@selector(debuggerStep
:) format
:@
"step_out"];
319 * Tells the debugger to step over the current function
323 [self sendCommandWithCallback
:@selector(debuggerStep
:) format
:@
"step_over"];
327 * Tells the debugger engine to get a specifc property. This also takes in the NSXMLElement
328 * that requested it so that the child can be attached.
330 - (NSArray
*)getProperty
:(NSString
*)property
332 [socket send
:[self createCommand
:[NSString stringWithFormat
:@
"property_get -n \"%@\"", property
]]];
334 NSXMLDocument
* doc
= [self processData
:[socket receive
]];
338 <property> <!-- this is the one we requested -->
339 <property ... /> <!-- these are what we want -->
344 // we now have to detach all the children so we can insert them into another document
345 NSXMLElement
* parent
= (NSXMLElement
*)[[doc rootElement
] childAtIndex
:0];
346 NSArray
* children
= [parent children
];
347 [parent setChildren
:nil];
351 // Breakpoint Management ///////////////////////////////////////////////////////
352 #pragma mark Breakpoints
355 * Send an add breakpoint command
357 - (void)addBreakpoint
:(Breakpoint
*)bp
362 NSString
* file
= [self escapedURIPath
:[bp transformedPath
]];
363 NSNumber
* transaction
= [self sendCommandWithCallback
:@selector(breakpointReceived
:)
364 format
:@
"breakpoint_set -t line -f %@ -n %i", file
, [bp line
]];
365 [callbackContext_ setObject
:bp forKey
:transaction
];
369 * Removes a breakpoint
371 - (void)removeBreakpoint
:(Breakpoint
*)bp
378 [self sendCommandWithCallback
:nil format
:@
"breakpoint_remove -d %i", [bp debuggerId
]];
382 // Socket and Stream Callbacks /////////////////////////////////////////////////
383 #pragma mark Callbacks
386 * Called by SocketWrapper after the connection is successful. This immediately calls
387 * -[SocketWrapper receive] to clear the way for communication, though the information
388 * could be useful server information that we don't use right now.
390 - (void)socketDidAccept
394 stackFrames_
= [[NSMutableDictionary alloc
] init
];
395 self.queuedWrites
= [NSMutableArray array
];
396 writeQueueLock_
= [NSRecursiveLock
new];
397 callTable_
= [NSMutableDictionary
new];
398 callbackContext_
= [NSMutableDictionary
new];
402 * Receives errors from the SocketWrapper and updates the display
404 - (void)errorEncountered
:(NSString
*)error
406 [delegate errorEncountered
:error
];
410 * Creates, connects to, and schedules a CFSocket.
414 // Pass ourselves to the callback so we don't have to use ugly globals.
415 CFSocketContext context
;
418 context.retain
= NULL
;
419 context.release
= NULL
;
420 context.copyDescription
= NULL
;
422 // Create the address structure.
423 struct sockaddr_in address
;
424 memset(&address
, 0, sizeof(address
));
425 address.sin_len
= sizeof(address
);
426 address.sin_family
= AF_INET
;
427 address.sin_port
= htons(port
);
428 address.sin_addr.s_addr
= htonl(INADDR_ANY
);
430 // Create the socket signature.
431 CFSocketSignature signature
;
432 signature.protocolFamily
= PF_INET
;
433 signature.socketType
= SOCK_STREAM
;
434 signature.protocol
= IPPROTO_TCP
;
435 signature.address
= (CFDataRef
)[NSData dataWithBytes
:&address length
:sizeof(address
)];
437 socket_
= CFSocketCreateWithSocketSignature(kCFAllocatorDefault
,
438 &signature
, // Socket signature.
439 kCFSocketAcceptCallBack
, // Callback types.
440 SocketAcceptCallback
, // Callout function pointer.
441 &context
); // Context to pass to callout.
444 [self errorEncountered
:@
"Could not open socket."];
448 // Allow old, yet-to-be recycled sockets to be reused.
450 setsockopt(CFSocketGetNative(socket_
), SOL_SOCKET
, SO_REUSEADDR
, &yes
, sizeof(BOOL));
452 // Schedule the socket on the run loop.
453 CFRunLoopSourceRef source
= CFSocketCreateRunLoopSource(kCFAllocatorDefault
, socket_
, 0);
454 CFRunLoopAddSource(CFRunLoopGetCurrent(), source
, kCFRunLoopCommonModes
);
457 self.status
= @
"Connecting";
461 * Closes a socket and releases the ref.
465 // The socket goes down, so do the streams, which clean themselves up.
466 CFSocketInvalidate(socket_
);
468 [stackFrames_ release
];
469 self.queuedWrites
= nil;
470 [writeQueueLock_ release
];
471 [callTable_ release
];
472 [callbackContext_ release
];
476 * Notification that the socket disconnected.
478 - (void)socketDisconnected
481 [delegate debuggerDisconnected
];
485 * Callback from the CFReadStream that there is data waiting to be read.
487 - (void)readStreamHasData
490 CFIndex bytesRead
= CFReadStreamRead(readStream_
, buffer
, 1024);
491 const char* charBuffer
= (const char*)buffer
;
493 // We haven't finished reading a packet, so just read more data in.
494 if (currentPacketIndex_
< packetSize_
)
496 currentPacketIndex_
+= bytesRead
;
497 CFStringRef bufferString
= CFStringCreateWithBytes(kCFAllocatorDefault
,
500 kCFStringEncodingUTF8
,
502 [self.currentPacket appendString
:(NSString
*)bufferString
];
503 CFRelease(bufferString
);
505 // Time to read a new packet.
508 // Read the message header: the size.
509 packetSize_
= atoi(charBuffer
);
510 currentPacketIndex_
= bytesRead
- strlen(charBuffer
);
511 CFStringRef bufferString
= CFStringCreateWithBytes(kCFAllocatorDefault
,
512 buffer
+ strlen(charBuffer
) + 1,
513 bytesRead
- strlen(charBuffer
) - 1,
514 kCFStringEncodingUTF8
,
516 self.currentPacket
= [NSMutableString stringWithString
:(NSString
*)bufferString
];
517 CFRelease(bufferString
);
520 // We have finished reading the packet.
521 if (currentPacketIndex_
>= packetSize_
)
524 currentPacketIndex_
= 0;
526 // Test if we can convert it into an NSXMLDocument.
527 NSError
* error
= nil;
528 NSXMLDocument
* xmlTest
= [[NSXMLDocument alloc
] initWithXMLString
:currentPacket_ options
:NSXMLDocumentTidyXML error
:&error
];
531 NSLog(@
"Could not parse XML? --- %@", error
);
532 NSLog(@
"Error UserInfo: %@", [error userInfo
]);
533 NSLog(@
"This is the XML Document: %@", currentPacket_
);
536 [self handleResponse
:[xmlTest autorelease
]];
541 * Writes a command into the write stream. If the stream is ready for writing,
542 * we do so immediately. If not, the command is queued and will be written
543 * when the stream is ready.
545 - (void)send
:(NSString
*)command
547 if (lastReadTransaction_
>= lastWrittenTransaction_
&& CFWriteStreamCanAcceptBytes(writeStream_
))
548 [self performSend
:command
];
550 [queuedWrites_ addObject
:command
];
554 * This performs a blocking send. This should ONLY be called when we know we
555 * have write access to the stream. We will busy wait in case we don't do a full
558 - (void)performSend
:(NSString
*)command
562 char* string
= (char*)[command UTF8String
];
563 int stringLength
= strlen(string
);
565 // Log the command if TransportDebug is enabled.
566 if ([[[[NSProcessInfo processInfo
] environment
] objectForKey
:@
"TransportDebug"] boolValue
])
567 NSLog(@
"--> %@", command
);
569 // Busy wait while writing. BAADD. Should background this operation.
572 if (CFWriteStreamCanAcceptBytes(writeStream_
))
574 // Include the NULL byte in the string when we write.
575 int bytesWritten
= CFWriteStreamWrite(writeStream_
, (UInt8
*)string
, stringLength
+ 1);
576 if (bytesWritten
< 0)
578 NSLog(@
"write error");
581 else if (bytesWritten
< strlen(string
))
583 // Adjust the buffer and wait for another chance to write.
584 stringLength
-= bytesWritten
;
585 memmove(string
, string
+ bytesWritten
, stringLength
);
591 // We need to scan the string to find the transactionID.
592 NSRange occurrence
= [command rangeOfString
:@
"-i "];
593 if (occurrence.location
== NSNotFound
)
595 NSLog(@
"sent %@ without a transaction ID", command
);
598 NSString
* transaction
= [command substringFromIndex
:occurrence.location
+ occurrence.length
];
599 lastWrittenTransaction_
= [transaction intValue
];
600 NSLog(@
"command = %@", command
);
601 NSLog(@
"read=%d, write=%d", lastReadTransaction_
, lastWrittenTransaction_
);
607 - (void)handleResponse
:(NSXMLDocument
*)response
609 // Check and see if there's an error.
610 NSArray
* error
= [[response rootElement
] elementsForName
:@
"error"];
611 if ([error count
] > 0)
613 NSLog(@
"Xdebug error: %@", error
);
614 [delegate errorEncountered
:[[[[error objectAtIndex
:0] children
] objectAtIndex
:0] stringValue
]];
617 // If TransportDebug is enabled, log the response.
618 if ([[[[NSProcessInfo processInfo
] environment
] objectForKey
:@
"TransportDebug"] boolValue
])
619 NSLog(@
"<-- %@", response
);
621 // Get the name of the command from the engine's response.
622 NSInteger transaction
= [self transactionIDFromResponse
:response
];
623 if (transaction
< lastReadTransaction_
)
624 NSLog(@
"out of date transaction %@", response
);
626 if (transaction
!= lastWrittenTransaction_
)
627 NSLog(@
"txn doesn't match last written %@", response
);
629 lastReadTransaction_
= transaction
;
630 NSLog(@
"read=%d, write=%d", lastReadTransaction_
, lastWrittenTransaction_
);
632 if ([[[response rootElement
] name
] isEqualToString
:@
"init"])
634 [self initReceived
:response
];
638 NSString
* callbackStr
= [callTable_ objectForKey
:[NSNumber numberWithInt
:lastReadTransaction_
]];
641 SEL callback
= NSSelectorFromString(callbackStr
);
642 [self performSelector
:callback withObject
:response
];
645 [self sendQueuedWrites
];
648 // Specific Response Handlers //////////////////////////////////////////////////
649 #pragma mark Response Handlers
652 * Initial packet received. We've started a brand-new connection to the engine.
654 - (void)initReceived
:(NSXMLDocument
*)response
656 // Register any breakpoints that exist offline.
657 for (Breakpoint
* bp
in [[BreakpointManager sharedManager
] breakpoints
])
658 [self addBreakpoint
:bp
];
660 // Load the debugger to make it look active.
661 [delegate debuggerConnected
];
663 // TODO: update the status.
667 * Receiver for status updates. This just freshens up the UI.
669 - (void)updateStatus
:(NSXMLDocument
*)response
671 self.status
= [[[[response rootElement
] attributeForName
:@
"status"] stringValue
] capitalizedString
];
672 if (status
== nil ||
[status isEqualToString
:@
"Stopped"] ||
[status isEqualToString
:@
"Stopping"])
676 [delegate debuggerDisconnected
];
678 self.status
= @
"Stopped";
683 * Step in/out/over and run all take this path. We first get the status of the
684 * debugger and then request fresh stack information.
686 - (void)debuggerStep
:(NSXMLDocument
*)response
688 [self sendCommandWithCallback
:@selector(updateStatus
:) format
:@
"status"];
689 NSString
* command
= [[[response rootElement
] attributeForName
:@
"command"] stringValue
];
691 // If this is the run command, tell the delegate that a bunch of updates
692 // are coming. Also remove all existing stack routes and request a new stack.
693 // TODO: figure out if we can not clobber the stack every time.
694 if (YES ||
[command isEqualToString
:@
"run"])
696 if ([delegate respondsToSelector
:@selector(clobberStack
)])
697 [delegate clobberStack
];
698 [stackFrames_ removeAllObjects
];
699 stackFirstTransactionID_
= [[self sendCommandWithCallback
:@selector(rebuildStack
:) format
:@
"stack_depth"] intValue
];
704 * We ask for the stack_depth and now we clobber the stack and start rebuilding
707 - (void)rebuildStack
:(NSXMLDocument
*)response
709 NSInteger depth
= [[[[response rootElement
] attributeForName
:@
"depth"] stringValue
] intValue
];
711 if (stackFirstTransactionID_
== [self transactionIDFromResponse
:response
])
714 // We now need to alloc a bunch of stack frames and get the basic information
716 for (NSInteger i
= 0; i
< depth
; i
++)
718 // Use the transaction ID to create a routing path.
719 NSNumber
* routingID
= [self sendCommandWithCallback
:@selector(getStackFrame
:) format
:@
"stack_get -d %d", i
];
720 [stackFrames_ setObject
:[StackFrame alloc
] forKey
:routingID
];
725 * The initial rebuild of the stack frame. We now have enough to initialize
726 * a StackFrame object.
728 - (void)getStackFrame
:(NSXMLDocument
*)response
730 // Get the routing information.
731 NSInteger routingID
= [self transactionIDFromResponse
:response
];
732 if (routingID
< stackFirstTransactionID_
)
734 NSNumber
* routingNumber
= [NSNumber numberWithInt
:routingID
];
736 // Make sure we initialized this frame in our last |-rebuildStack:|.
737 StackFrame
* frame
= [stackFrames_ objectForKey
:routingNumber
];
741 NSXMLElement
* xmlframe
= [[[response rootElement
] children
] objectAtIndex
:0];
743 // Initialize the stack frame.
744 [frame initWithIndex
:[[[xmlframe attributeForName
:@
"level"] stringValue
] intValue
]
745 withFilename
:[[xmlframe attributeForName
:@
"filename"] stringValue
]
747 atLine
:[[[xmlframe attributeForName
:@
"lineno"] stringValue
] intValue
]
748 inFunction
:[[xmlframe attributeForName
:@
"where"] stringValue
]
751 // Get the source code of the file. Escape % in URL chars.
752 NSString
* escapedFilename
= [frame.filename stringByReplacingOccurrencesOfString
:@
"%" withString
:@
"%%"];
753 NSNumber
* transaction
= [self sendCommandWithCallback
:@selector(setSource
:) format
:@
"source -f %@", escapedFilename
];
754 [callbackContext_ setObject
:routingNumber forKey
:transaction
];
756 // Get the names of all the contexts.
757 transaction
= [self sendCommandWithCallback
:@selector(contextsReceived
:) format
:@
"context_names -d %d", frame.index
];
758 [callbackContext_ setObject
:routingNumber forKey
:transaction
];
760 if ([delegate respondsToSelector
:@selector(newStackFrame
:)])
761 [delegate newStackFrame
:frame
];
765 * Callback for setting the source of a file while rebuilding a specific stack
768 - (void)setSource
:(NSXMLDocument
*)response
770 NSNumber
* transaction
= [NSNumber numberWithInt
:[self transactionIDFromResponse
:response
]];
771 if ([transaction intValue
] < stackFirstTransactionID_
)
773 NSNumber
* routingNumber
= [callbackContext_ objectForKey
:transaction
];
777 [callbackContext_ removeObjectForKey
:transaction
];
778 StackFrame
* frame
= [stackFrames_ objectForKey
:routingNumber
];
782 frame.source
= [[response rootElement
] value
];
784 if ([delegate respondsToSelector
:@selector(sourceUpdated
:)])
785 [delegate sourceUpdated
:frame
];
789 * Enumerates all the contexts of a given stack frame. We then in turn get the
790 * contents of each one of these contexts.
792 - (void)contextsReceived
:(NSXMLDocument
*)response
794 // Get the stack frame's routing ID and use it again.
795 NSNumber
* receivedTransaction
= [NSNumber numberWithInt
:[self transactionIDFromResponse
:response
]];
796 if ([receivedTransaction intValue
] < stackFirstTransactionID_
)
798 NSNumber
* routingID
= [callbackContext_ objectForKey
:receivedTransaction
];
802 // Get the stack frame by the |routingID|.
803 StackFrame
* frame
= [stackFrames_ objectForKey
:routingID
];
805 NSXMLElement
* contextNames
= [response rootElement
];
806 for (NSXMLElement
* context
in [contextNames children
])
808 NSInteger cid
= [[[context attributeForName
:@
"id"] stringValue
] intValue
];
810 // Fetch each context's variables.
811 NSNumber
* transaction
= [self sendCommandWithCallback
:@selector(variablesReceived
:)
812 format
:@
"context_get -d %d -c %d", frame.index
, cid
];
813 [callbackContext_ setObject
:routingID forKey
:transaction
];
818 * Receives the variables from the context and attaches them to the stack frame.
820 - (void)variablesReceived
:(NSXMLDocument
*)response
822 // Get the stack frame's routing ID and use it again.
823 NSInteger transaction
= [self transactionIDFromResponse
:response
];
824 if (transaction
< stackFirstTransactionID_
)
826 NSNumber
* receivedTransaction
= [NSNumber numberWithInt
:transaction
];
827 NSNumber
* routingID
= [callbackContext_ objectForKey
:receivedTransaction
];
831 // Get the stack frame by the |routingID|.
832 StackFrame
* frame
= [stackFrames_ objectForKey
:routingID
];
834 NSMutableArray
* variables
= [NSMutableArray array
];
836 // Merge the frame's existing variables.
838 [variables addObjectsFromArray
:frame.variables
];
840 // Add these new variables.
841 NSArray
* addVariables
= [[response rootElement
] children
];
843 [variables addObjectsFromArray
:addVariables
];
845 frame.variables
= variables
;
849 * Callback for setting a breakpoint.
851 - (void)breakpointReceived
:(NSXMLDocument
*)response
853 NSNumber
* transaction
= [NSNumber numberWithInt
:[self transactionIDFromResponse
:response
]];
854 Breakpoint
* bp
= [callbackContext_ objectForKey
:transaction
];
858 [callbackContext_ removeObjectForKey
:callbackContext_
];
859 [bp setDebuggerId
:[[[[response rootElement
] attributeForName
:@
"id"] stringValue
] intValue
]];
865 * This will send a command to the debugger engine. It will append the
866 * transaction ID automatically. It accepts a NSString command along with a
867 * a variable number of arguments to substitute into the command, a la
868 * +[NSString stringWithFormat:]. Returns the transaction ID as a NSNumber.
870 - (NSNumber
*)sendCommandWithCallback
:(SEL)callback format
:(NSString
*)format
, ...
872 // Collect varargs and format command.
874 va_start(args
, format
);
875 NSString
* command
= [[NSString alloc
] initWithFormat
:format arguments
:args
];
878 NSNumber
* callbackKey
= [NSNumber numberWithInt
:transactionID
++];
880 [callTable_ setObject
:NSStringFromSelector(callback
) forKey
:callbackKey
];
882 [self send
:[NSString stringWithFormat
:@
"%@ -i %@", [command autorelease
], callbackKey
]];
888 * Checks if there are unsent commands in the |queuedWrites_| queue and sends
889 * them if it's OK to do so. This will not block.
891 - (void)sendQueuedWrites
893 [writeQueueLock_ lock
];
894 if (lastReadTransaction_
>= lastWrittenTransaction_
&& [queuedWrites_ count
] > 0)
896 NSString
* command
= [queuedWrites_ objectAtIndex
:0];
897 NSLog(@
"Sending queued write: %@", command
);
899 // We don't want to block because this is called from the main thread.
900 // |-performSend:| busy waits when the stream is not ready. Bail out
901 // before we do that becuase busy waiting is BAD.
902 if (CFWriteStreamCanAcceptBytes(writeStream_
))
904 [self performSend
:command
];
905 [queuedWrites_ removeObjectAtIndex
:0];
908 [writeQueueLock_ unlock
];
912 * Given a file path, this returns a file:// URI and escapes any spaces for the
915 - (NSString
*)escapedURIPath
:(NSString
*)path
917 // Custon GDBp paths are fine.
918 if ([[path substringToIndex
:4] isEqualToString
:@
"gdbp"])
921 // Create a temporary URL that will escape all the nasty characters.
922 NSURL
* url
= [NSURL fileURLWithPath
:path
];
923 NSString
* urlString
= [url absoluteString
];
925 // Remove the host because this is a file:// URL;
926 urlString
= [urlString stringByReplacingOccurrencesOfString
:[url host
] withString
:@
""];
928 // Escape % for use in printf-style NSString formatters.
929 urlString
= [urlString stringByReplacingOccurrencesOfString
:@
"%" withString
:@
"%%"];
934 * Returns the transaction_id from an NSXMLDocument.
936 - (NSInteger
)transactionIDFromResponse
:(NSXMLDocument
*)response
938 return [[[[response rootElement
] attributeForName
:@
"transaction_id"] stringValue
] intValue
];