3 * Copyright (c) 2007 - 2011, 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 "DebuggerBackEnd.h"
19 #import "AppDelegate.h"
21 #import "NSXMLElementAdditions.h"
23 // GDBpConnection (Private) ////////////////////////////////////////////////////
25 @interface DebuggerBackEnd ()
26 @property (readwrite
, copy
) NSString
* status
;
28 - (void)recordCallback
:(SEL)callback forTransaction
:(NSNumber
*)txn
;
30 - (void)updateStatus
:(NSXMLDocument
*)response
;
31 - (void)debuggerStep
:(NSXMLDocument
*)response
;
32 - (void)rebuildStack
:(NSXMLDocument
*)response
;
33 - (void)getStackFrame
:(NSXMLDocument
*)response
;
34 - (void)setSource
:(NSXMLDocument
*)response
;
35 - (void)contextsReceived
:(NSXMLDocument
*)response
;
36 - (void)variablesReceived
:(NSXMLDocument
*)response
;
37 - (void)propertiesReceived
:(NSXMLDocument
*)response
;
38 - (void)evalScriptReceived
:(NSXMLDocument
*)response
;
42 // GDBpConnection //////////////////////////////////////////////////////////////
44 @implementation DebuggerBackEnd
47 @synthesize attached
= attached_
;
51 * Creates a new DebuggerBackEnd and initializes the socket from the given connection
54 - (id)initWithPort
:(NSUInteger
)aPort
56 if (self = [super init
])
58 stackFrames_
= [[NSMutableDictionary alloc
] init
];
59 callbackContext_
= [NSMutableDictionary
new];
60 callTable_
= [NSMutableDictionary
new];
62 [[BreakpointManager sharedManager
] setConnection
:self];
63 connection_
= [[NetworkConnection alloc
] initWithPort
:aPort
];
64 connection_.delegate
= self;
66 attached_
= [[NSUserDefaults standardUserDefaults
] boolForKey
:@
"DebuggerAttached"];
69 [connection_ connect
];
75 * Deallocates the object
80 [stackFrames_ release
];
82 [callbackContext_ release
];
87 // Getters /////////////////////////////////////////////////////////////////////
91 * Gets the port number
95 return [connection_ port
];
99 * Returns whether or not we have an active connection
103 return [connection_ connected
] && active_
;
107 * Sets the attached state of the debugger. This will open and close the
108 * connection as appropriate.
110 - (void)setAttached
:(BOOL)attached
{
111 if (attached
!= attached_
) {
115 [connection_ connect
];
117 attached_
= attached
;
120 // Commands ////////////////////////////////////////////////////////////////////
121 #pragma mark Commands
124 * Tells the debugger to continue running the script. Returns the current stack frame.
128 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"run"];
129 [self recordCallback
:@selector(debuggerStep
:) forTransaction
:tx
];
133 * Tells the debugger to step into the current command.
137 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"step_into"];
138 [self recordCallback
:@selector(debuggerStep
:) forTransaction
:tx
];
142 * Tells the debugger to step out of the current context
146 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"step_out"];
147 [self recordCallback
:@selector(debuggerStep
:) forTransaction
:tx
];
151 * Tells the debugger to step over the current function
155 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"step_over"];
156 [self recordCallback
:@selector(debuggerStep
:) forTransaction
:tx
];
160 * Halts execution of the script.
166 self.status
= @
"Stopped";
167 if ([delegate respondsToSelector
:@selector(debuggerDisconnected
)])
168 [delegate debuggerDisconnected
];
172 * Ends the current debugging session.
176 [connection_ sendCommandWithFormat
:@
"detach"];
178 self.status
= @
"Stopped";
179 if ([delegate respondsToSelector
:@selector(debuggerDisconnected
)])
180 [delegate debuggerDisconnected
];
184 * Tells the debugger engine to get a specifc property. This also takes in the NSXMLElement
185 * that requested it so that the child can be attached.
187 - (NSInteger
)getChildrenOfProperty
:(VariableNode
*)property atDepth
:(NSInteger
)depth
;
189 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"property_get -d %d -n %@", depth
, [property fullName
]];
190 [self recordCallback
:@selector(propertiesReceived
:) forTransaction
:tx
];
191 return [tx intValue
];
194 - (void)loadStackFrame
:(StackFrame
*)frame
199 NSNumber
* routingNumber
= [NSNumber numberWithInt
:frame.routingID
];
200 NSNumber
* transaction
= nil;
202 // Get the source code of the file. Escape % in URL chars.
203 if ([frame.filename length
]) {
204 NSString
* escapedFilename
= [frame.filename stringByReplacingOccurrencesOfString
:@
"%" withString
:@
"%%"];
205 transaction
= [connection_ sendCommandWithFormat
:@
"source -f %@", escapedFilename
];
206 [self recordCallback
:@selector(setSource
:) forTransaction
:transaction
];
207 [callbackContext_ setObject
:routingNumber forKey
:transaction
];
210 // Get the names of all the contexts.
211 transaction
= [connection_ sendCommandWithFormat
:@
"context_names -d %d", frame.index
];
212 [self recordCallback
:@selector(contextsReceived
:) forTransaction
:transaction
];
213 [callbackContext_ setObject
:routingNumber forKey
:transaction
];
215 // This frame will be fully loaded.
219 // Breakpoint Management ///////////////////////////////////////////////////////
220 #pragma mark Breakpoints
223 * Send an add breakpoint command
225 - (void)addBreakpoint
:(Breakpoint
*)bp
227 if (![connection_ connected
])
230 NSString
* file
= [connection_ escapedURIPath
:[bp transformedPath
]];
231 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"breakpoint_set -t line -f %@ -n %i", file
, [bp line
]];
232 [self recordCallback
:@selector(breakpointReceived
:) forTransaction
:tx
];
233 [callbackContext_ setObject
:bp forKey
:tx
];
237 * Removes a breakpoint
239 - (void)removeBreakpoint
:(Breakpoint
*)bp
241 if (![connection_ connected
])
244 [connection_ sendCommandWithFormat
:@
"breakpoint_remove -d %i", [bp debuggerId
]];
248 * Sends a string to be evaluated by the engine.
250 - (void)evalScript
:(NSString
*)str
252 if (![connection_ connected
])
255 char* encodedString
= malloc(modp_b64_encode_len([str length
]));
256 modp_b64_encode(encodedString
, [str UTF8String
], [str length
]);
257 NSNumber
* tx
= [connection_ sendCustomCommandWithFormat
:@
"eval -i {txn} -- %s", encodedString
];
260 [self recordCallback
:@selector(evalScriptReceived
:) forTransaction
:tx
];
263 // Specific Response Handlers //////////////////////////////////////////////////
264 #pragma mark Response Handlers
266 - (void)errorEncountered
:(NSString
*)error
268 [delegate errorEncountered
:error
];
272 * Initial packet received. We've started a brand-new connection to the engine.
274 - (void)handleInitialResponse
:(NSXMLDocument
*)response
276 if (!self.attached
) {
277 [connection_ sendCommandWithFormat
:@
"detach"];
283 // Register any breakpoints that exist offline.
284 for (Breakpoint
* bp
in [[BreakpointManager sharedManager
] breakpoints
])
285 [self addBreakpoint
:bp
];
287 // Load the debugger to make it look active.
288 [delegate debuggerConnected
];
290 // TODO: update the status.
294 * Called when the connection is finally closed. This will reopen the listening
295 * socket if the debugger remains attached.
297 - (void)connectionDidClose
:(NetworkConnection
*)connection
299 if ([delegate respondsToSelector
:@selector(debuggerDisconnected
)])
300 [delegate debuggerDisconnected
];
303 [connection_ connect
];
306 - (void)handleResponse
:(NSXMLDocument
*)response
308 NSInteger transactionID
= [connection_ transactionIDFromResponse
:response
];
309 NSNumber
* key
= [NSNumber numberWithInt
:transactionID
];
310 NSString
* callbackStr
= [callTable_ objectForKey
:key
];
313 SEL callback
= NSSelectorFromString(callbackStr
);
314 [self performSelector
:callback withObject
:response
];
316 [callTable_ removeObjectForKey
:key
];
320 * Receiver for status updates. This just freshens up the UI.
322 - (void)updateStatus
:(NSXMLDocument
*)response
324 self.status
= [[[[response rootElement
] attributeForName
:@
"status"] stringValue
] capitalizedString
];
326 if (!status ||
[status isEqualToString
:@
"Stopped"]) {
327 [delegate debuggerDisconnected
];
329 } else if ([status isEqualToString
:@
"Stopping"]) {
330 [connection_ sendCommandWithFormat
:@
"stop"];
336 * Step in/out/over and run all take this path. We first get the status of the
337 * debugger and then request fresh stack information.
339 - (void)debuggerStep
:(NSXMLDocument
*)response
341 [self updateStatus
:response
];
342 if (![self isConnected
])
345 // If this is the run command, tell the delegate that a bunch of updates
346 // are coming. Also remove all existing stack routes and request a new stack.
347 if ([delegate respondsToSelector
:@selector(clobberStack
)])
348 [delegate clobberStack
];
349 [stackFrames_ removeAllObjects
];
350 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"stack_depth"];
351 [self recordCallback
:@selector(rebuildStack
:) forTransaction
:tx
];
352 stackFirstTransactionID_
= [tx intValue
];
356 * We ask for the stack_depth and now we clobber the stack and start rebuilding
359 - (void)rebuildStack
:(NSXMLDocument
*)response
361 NSInteger depth
= [[[[response rootElement
] attributeForName
:@
"depth"] stringValue
] intValue
];
363 if (stackFirstTransactionID_
== [connection_ transactionIDFromResponse
:response
])
366 // We now need to alloc a bunch of stack frames and get the basic information
368 for (NSInteger i
= 0; i
< depth
; i
++)
370 // Use the transaction ID to create a routing path.
371 NSNumber
* routingID
= [connection_ sendCommandWithFormat
:@
"stack_get -d %d", i
];
372 [self recordCallback
:@selector(getStackFrame
:) forTransaction
:routingID
];
373 [stackFrames_ setObject
:[[StackFrame
new] autorelease
] forKey
:routingID
];
378 * The initial rebuild of the stack frame. We now have enough to initialize
379 * a StackFrame object.
381 - (void)getStackFrame
:(NSXMLDocument
*)response
383 // Get the routing information.
384 NSInteger routingID
= [connection_ transactionIDFromResponse
:response
];
385 if (routingID
< stackFirstTransactionID_
)
387 NSNumber
* routingNumber
= [NSNumber numberWithInt
:routingID
];
389 // Make sure we initialized this frame in our last |-rebuildStack:|.
390 StackFrame
* frame
= [stackFrames_ objectForKey
:routingNumber
];
394 NSXMLElement
* xmlframe
= [[[response rootElement
] children
] objectAtIndex
:0];
396 // Initialize the stack frame.
397 frame.index
= [[[xmlframe attributeForName
:@
"level"] stringValue
] intValue
];
398 frame.filename
= [[xmlframe attributeForName
:@
"filename"] stringValue
];
399 frame.lineNumber
= [[[xmlframe attributeForName
:@
"lineno"] stringValue
] intValue
];
400 frame.function
= [[xmlframe attributeForName
:@
"where"] stringValue
];
401 frame.routingID
= routingID
;
403 // Only get the complete frame for the first level. The other frames will get
404 // information loaded lazily when the user clicks on one.
405 if (frame.index
== 0) {
406 [self loadStackFrame
:frame
];
409 if ([delegate respondsToSelector
:@selector(newStackFrame
:)])
410 [delegate newStackFrame
:frame
];
414 * Callback for setting the source of a file while rebuilding a specific stack
417 - (void)setSource
:(NSXMLDocument
*)response
419 NSNumber
* transaction
= [NSNumber numberWithInt
:[connection_ transactionIDFromResponse
:response
]];
420 if ([transaction intValue
] < stackFirstTransactionID_
)
422 NSNumber
* routingNumber
= [callbackContext_ objectForKey
:transaction
];
426 [callbackContext_ removeObjectForKey
:transaction
];
427 StackFrame
* frame
= [stackFrames_ objectForKey
:routingNumber
];
431 frame.source
= [[response rootElement
] base64DecodedValue
];
433 if ([delegate respondsToSelector
:@selector(sourceUpdated
:)])
434 [delegate sourceUpdated
:frame
];
438 * Enumerates all the contexts of a given stack frame. We then in turn get the
439 * contents of each one of these contexts.
441 - (void)contextsReceived
:(NSXMLDocument
*)response
443 // Get the stack frame's routing ID and use it again.
444 NSNumber
* receivedTransaction
= [NSNumber numberWithInt
:[connection_ transactionIDFromResponse
:response
]];
445 if ([receivedTransaction intValue
] < stackFirstTransactionID_
)
447 NSNumber
* routingID
= [callbackContext_ objectForKey
:receivedTransaction
];
451 // Get the stack frame by the |routingID|.
452 StackFrame
* frame
= [stackFrames_ objectForKey
:routingID
];
454 NSXMLElement
* contextNames
= [response rootElement
];
455 for (NSXMLElement
* context
in [contextNames children
])
457 NSInteger cid
= [[[context attributeForName
:@
"id"] stringValue
] intValue
];
459 // Fetch each context's variables.
460 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"context_get -d %d -c %d", frame.index
, cid
];
461 [self recordCallback
:@selector(variablesReceived
:) forTransaction
:tx
];
462 [callbackContext_ setObject
:routingID forKey
:tx
];
467 * Receives the variables from the context and attaches them to the stack frame.
469 - (void)variablesReceived
:(NSXMLDocument
*)response
471 // Get the stack frame's routing ID and use it again.
472 NSInteger transaction
= [connection_ transactionIDFromResponse
:response
];
473 if (transaction
< stackFirstTransactionID_
)
475 NSNumber
* receivedTransaction
= [NSNumber numberWithInt
:transaction
];
476 NSNumber
* routingID
= [callbackContext_ objectForKey
:receivedTransaction
];
480 // Get the stack frame by the |routingID|.
481 StackFrame
* frame
= [stackFrames_ objectForKey
:routingID
];
483 NSMutableArray
* variables
= [NSMutableArray array
];
485 // Merge the frame's existing variables.
487 [variables addObjectsFromArray
:frame.variables
];
489 // Add these new variables.
490 NSArray
* addVariables
= [[response rootElement
] children
];
492 for (NSXMLElement
* elm
in addVariables
) {
493 VariableNode
* node
= [[VariableNode alloc
] initWithXMLNode
:elm
];
494 [variables addObject
:[node autorelease
]];
498 frame.variables
= variables
;
502 * Callback from a |-getProperty:| request.
504 - (void)propertiesReceived
:(NSXMLDocument
*)response
506 NSInteger transaction
= [connection_ transactionIDFromResponse
:response
];
510 <property> <!-- this is the one we requested -->
511 <property ... /> <!-- these are what we want -->
516 // Detach all the children so we can insert them into another document.
517 NSXMLElement
* parent
= (NSXMLElement
*)[[response rootElement
] childAtIndex
:0];
518 NSArray
* children
= [parent children
];
519 [parent setChildren
:nil];
521 [delegate receivedProperties
:children forTransaction
:transaction
];
525 * Callback from a |-evalScript:| request.
527 - (void)evalScriptReceived
:(NSXMLDocument
*)response
529 NSXMLElement
* parent
= (NSXMLElement
*)[[response rootElement
] childAtIndex
:0];
530 NSString
* value
= [parent base64DecodedValue
];
531 [delegate scriptWasEvaluatedWithResult
:value
];
535 * Callback for setting a breakpoint.
537 - (void)breakpointReceived
:(NSXMLDocument
*)response
539 NSNumber
* transaction
= [NSNumber numberWithInt
:[connection_ transactionIDFromResponse
:response
]];
540 Breakpoint
* bp
= [callbackContext_ objectForKey
:transaction
];
544 [callbackContext_ removeObjectForKey
:callbackContext_
];
545 [bp setDebuggerId
:[[[[response rootElement
] attributeForName
:@
"id"] stringValue
] intValue
]];
548 // Private /////////////////////////////////////////////////////////////////////
550 - (void)recordCallback
:(SEL)callback forTransaction
:(NSNumber
*)txn
552 [callTable_ setObject
:NSStringFromSelector(callback
) forKey
:txn
];