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];
64 client_
= [[ProtocolClient alloc
] initWithDelegate
:self];
66 attached_
= [[NSUserDefaults standardUserDefaults
] boolForKey
:@
"DebuggerAttached"];
69 [client_ connectOnPort
:port_
];
75 * Deallocates the object
80 [stackFrames_ release
];
82 [callbackContext_ release
];
87 // Getters /////////////////////////////////////////////////////////////////////
91 * Gets the port number
99 * Returns whether or not we have an active connection
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 [client_ disconnect
];
117 [client_ connectOnPort
:port_
];
119 attached_
= attached
;
122 // Commands ////////////////////////////////////////////////////////////////////
123 #pragma mark Commands
126 * Tells the debugger to continue running the script. Returns the current stack frame.
130 NSNumber
* tx
= [client_ sendCommandWithFormat
:@
"run"];
131 [self recordCallback
:@selector(debuggerStep
:) forTransaction
:tx
];
135 * Tells the debugger to step into the current command.
139 NSNumber
* tx
= [client_ sendCommandWithFormat
:@
"step_into"];
140 [self recordCallback
:@selector(debuggerStep
:) forTransaction
:tx
];
144 * Tells the debugger to step out of the current context
148 NSNumber
* tx
= [client_ sendCommandWithFormat
:@
"step_out"];
149 [self recordCallback
:@selector(debuggerStep
:) forTransaction
:tx
];
153 * Tells the debugger to step over the current function
157 NSNumber
* tx
= [client_ sendCommandWithFormat
:@
"step_over"];
158 [self recordCallback
:@selector(debuggerStep
:) forTransaction
:tx
];
162 * Halts execution of the script.
166 [client_ disconnect
];
168 self.status
= @
"Stopped";
172 * Ends the current debugging session.
176 [client_ sendCommandWithFormat
:@
"detach"];
178 self.status
= @
"Stopped";
182 * Tells the debugger engine to get a specifc property. This also takes in the NSXMLElement
183 * that requested it so that the child can be attached.
185 - (NSInteger
)getChildrenOfProperty
:(VariableNode
*)property atDepth
:(NSInteger
)depth
;
187 NSNumber
* tx
= [client_ sendCommandWithFormat
:@
"property_get -d %d -n %@", depth
, [property fullName
]];
188 [self recordCallback
:@selector(propertiesReceived
:) forTransaction
:tx
];
189 return [tx intValue
];
192 - (void)loadStackFrame
:(StackFrame
*)frame
197 NSNumber
* routingNumber
= [NSNumber numberWithInt
:frame.routingID
];
198 NSNumber
* transaction
= nil;
200 // Get the source code of the file. Escape % in URL chars.
201 if ([frame.filename length
]) {
202 transaction
= [client_ sendCommandWithFormat
:@
"source -f %@", frame.filename
];
203 [self recordCallback
:@selector(setSource
:) forTransaction
:transaction
];
204 [callbackContext_ setObject
:routingNumber forKey
:transaction
];
207 // Get the names of all the contexts.
208 transaction
= [client_ sendCommandWithFormat
:@
"context_names -d %d", frame.index
];
209 [self recordCallback
:@selector(contextsReceived
:) forTransaction
:transaction
];
210 [callbackContext_ setObject
:routingNumber forKey
:transaction
];
212 // This frame will be fully loaded.
216 // Breakpoint Management ///////////////////////////////////////////////////////
217 #pragma mark Breakpoints
220 * Send an add breakpoint command
222 - (void)addBreakpoint
:(Breakpoint
*)bp
227 NSString
* file
= [ProtocolClient escapedFilePathURI
:[bp transformedPath
]];
228 NSNumber
* tx
= [client_ sendCommandWithFormat
:@
"breakpoint_set -t line -f %@ -n %i", file
, [bp line
]];
229 [self recordCallback
:@selector(breakpointReceived
:) forTransaction
:tx
];
230 [callbackContext_ setObject
:bp forKey
:tx
];
234 * Removes a breakpoint
236 - (void)removeBreakpoint
:(Breakpoint
*)bp
241 [client_ sendCommandWithFormat
:@
"breakpoint_remove -d %i", [bp debuggerId
]];
245 * Sends a string to be evaluated by the engine.
247 - (void)evalScript
:(NSString
*)str
252 char* encodedString
= malloc(modp_b64_encode_len([str length
]));
253 modp_b64_encode(encodedString
, [str UTF8String
], [str length
]);
254 NSNumber
* tx
= [client_ sendCustomCommandWithFormat
:@
"eval -i {txn} -- %s", encodedString
];
257 [self recordCallback
:@selector(evalScriptReceived
:) forTransaction
:tx
];
260 // Protocol Client Delegate ////////////////////////////////////////////////////
261 #pragma mark Protocol Client Delegate
263 - (void)debuggerEngineConnected
:(ProtocolClient
*)client
269 * Called when the connection is finally closed. This will reopen the listening
270 * socket if the debugger remains attached.
272 - (void)debuggerEngineDisconnected
:(ProtocolClient
*)client
276 if ([delegate respondsToSelector
:@selector(debuggerDisconnected
)])
277 [delegate debuggerDisconnected
];
280 [client_ connectOnPort
:port_
];
283 - (void)debuggerEngine
:(ProtocolClient
*)client receivedMessage
:(NSXMLDocument
*)message
285 // Check and see if there's an error.
286 NSArray
* error
= [[message rootElement
] elementsForName
:@
"error"];
287 if ([error count
] > 0) {
288 NSLog(@
"Xdebug error: %@", error
);
289 NSString
* errorMessage
= [[[[error objectAtIndex
:0] children
] objectAtIndex
:0] stringValue
];
290 [self errorEncountered
:errorMessage
];
293 if ([[[message rootElement
] name
] isEqualToString
:@
"init"]) {
294 [self handleInitialResponse
:message
];
298 [self handleResponse
:message
];
301 // Specific Response Handlers //////////////////////////////////////////////////
302 #pragma mark Response Handlers
304 - (void)errorEncountered
:(NSString
*)error
306 [delegate errorEncountered
:error
];
310 * Initial packet received. We've started a brand-new connection to the engine.
312 - (void)handleInitialResponse
:(NSXMLDocument
*)response
314 if (!self.attached
) {
315 [client_ sendCommandWithFormat
:@
"detach"];
321 // Register any breakpoints that exist offline.
322 for (Breakpoint
* bp
in [[BreakpointManager sharedManager
] breakpoints
])
323 [self addBreakpoint
:bp
];
325 // Load the debugger to make it look active.
326 [delegate debuggerConnected
];
328 // TODO: update the status.
331 - (void)handleResponse
:(NSXMLDocument
*)response
333 NSInteger transactionID
= [client_ transactionIDFromResponse
:response
];
334 NSNumber
* key
= [NSNumber numberWithInt
:transactionID
];
335 NSString
* callbackStr
= [callTable_ objectForKey
:key
];
338 SEL callback
= NSSelectorFromString(callbackStr
);
339 [self performSelector
:callback withObject
:response
];
341 [callTable_ removeObjectForKey
:key
];
345 * Receiver for status updates. This just freshens up the UI.
347 - (void)updateStatus
:(NSXMLDocument
*)response
349 self.status
= [[[[response rootElement
] attributeForName
:@
"status"] stringValue
] capitalizedString
];
351 if (!status ||
[status isEqualToString
:@
"Stopped"]) {
352 [delegate debuggerDisconnected
];
354 } else if ([status isEqualToString
:@
"Stopping"]) {
355 [client_ sendCommandWithFormat
:@
"stop"];
361 * Step in/out/over and run all take this path. We first get the status of the
362 * debugger and then request fresh stack information.
364 - (void)debuggerStep
:(NSXMLDocument
*)response
366 [self updateStatus
:response
];
367 if (![self isConnected
])
370 // If this is the run command, tell the delegate that a bunch of updates
371 // are coming. Also remove all existing stack routes and request a new stack.
372 if ([delegate respondsToSelector
:@selector(clobberStack
)])
373 [delegate clobberStack
];
374 [stackFrames_ removeAllObjects
];
375 NSNumber
* tx
= [client_ sendCommandWithFormat
:@
"stack_depth"];
376 [self recordCallback
:@selector(rebuildStack
:) forTransaction
:tx
];
377 stackFirstTransactionID_
= [tx intValue
];
381 * We ask for the stack_depth and now we clobber the stack and start rebuilding
384 - (void)rebuildStack
:(NSXMLDocument
*)response
386 NSInteger depth
= [[[[response rootElement
] attributeForName
:@
"depth"] stringValue
] intValue
];
388 if (stackFirstTransactionID_
== [client_ transactionIDFromResponse
:response
])
391 // We now need to alloc a bunch of stack frames and get the basic information
393 for (NSInteger i
= 0; i
< depth
; i
++)
395 // Use the transaction ID to create a routing path.
396 NSNumber
* routingID
= [client_ sendCommandWithFormat
:@
"stack_get -d %d", i
];
397 [self recordCallback
:@selector(getStackFrame
:) forTransaction
:routingID
];
398 [stackFrames_ setObject
:[[StackFrame
new] autorelease
] forKey
:routingID
];
403 * The initial rebuild of the stack frame. We now have enough to initialize
404 * a StackFrame object.
406 - (void)getStackFrame
:(NSXMLDocument
*)response
408 // Get the routing information.
409 NSInteger routingID
= [client_ transactionIDFromResponse
:response
];
410 if (routingID
< stackFirstTransactionID_
)
412 NSNumber
* routingNumber
= [NSNumber numberWithInt
:routingID
];
414 // Make sure we initialized this frame in our last |-rebuildStack:|.
415 StackFrame
* frame
= [stackFrames_ objectForKey
:routingNumber
];
419 NSXMLElement
* xmlframe
= [[[response rootElement
] children
] objectAtIndex
:0];
421 // Initialize the stack frame.
422 frame.index
= [[[xmlframe attributeForName
:@
"level"] stringValue
] intValue
];
423 frame.filename
= [[xmlframe attributeForName
:@
"filename"] stringValue
];
424 frame.lineNumber
= [[[xmlframe attributeForName
:@
"lineno"] stringValue
] intValue
];
425 frame.function
= [[xmlframe attributeForName
:@
"where"] stringValue
];
426 frame.routingID
= routingID
;
428 // Only get the complete frame for the first level. The other frames will get
429 // information loaded lazily when the user clicks on one.
430 if (frame.index
== 0) {
431 [self loadStackFrame
:frame
];
434 if ([delegate respondsToSelector
:@selector(newStackFrame
:)])
435 [delegate newStackFrame
:frame
];
439 * Callback for setting the source of a file while rebuilding a specific stack
442 - (void)setSource
:(NSXMLDocument
*)response
444 NSNumber
* transaction
= [NSNumber numberWithInt
:[client_ transactionIDFromResponse
:response
]];
445 if ([transaction intValue
] < stackFirstTransactionID_
)
447 NSNumber
* routingNumber
= [callbackContext_ objectForKey
:transaction
];
451 [callbackContext_ removeObjectForKey
:transaction
];
452 StackFrame
* frame
= [stackFrames_ objectForKey
:routingNumber
];
456 frame.source
= [[response rootElement
] base64DecodedValue
];
458 if ([delegate respondsToSelector
:@selector(sourceUpdated
:)])
459 [delegate sourceUpdated
:frame
];
463 * Enumerates all the contexts of a given stack frame. We then in turn get the
464 * contents of each one of these contexts.
466 - (void)contextsReceived
:(NSXMLDocument
*)response
468 // Get the stack frame's routing ID and use it again.
469 NSNumber
* receivedTransaction
= [NSNumber numberWithInt
:[client_ transactionIDFromResponse
:response
]];
470 if ([receivedTransaction intValue
] < stackFirstTransactionID_
)
472 NSNumber
* routingID
= [callbackContext_ objectForKey
:receivedTransaction
];
476 // Get the stack frame by the |routingID|.
477 StackFrame
* frame
= [stackFrames_ objectForKey
:routingID
];
479 NSXMLElement
* contextNames
= [response rootElement
];
480 for (NSXMLElement
* context
in [contextNames children
])
482 NSInteger cid
= [[[context attributeForName
:@
"id"] stringValue
] intValue
];
484 // Fetch each context's variables.
485 NSNumber
* tx
= [client_ sendCommandWithFormat
:@
"context_get -d %d -c %d", frame.index
, cid
];
486 [self recordCallback
:@selector(variablesReceived
:) forTransaction
:tx
];
487 [callbackContext_ setObject
:routingID forKey
:tx
];
492 * Receives the variables from the context and attaches them to the stack frame.
494 - (void)variablesReceived
:(NSXMLDocument
*)response
496 // Get the stack frame's routing ID and use it again.
497 NSInteger transaction
= [client_ transactionIDFromResponse
:response
];
498 if (transaction
< stackFirstTransactionID_
)
500 NSNumber
* receivedTransaction
= [NSNumber numberWithInt
:transaction
];
501 NSNumber
* routingID
= [callbackContext_ objectForKey
:receivedTransaction
];
505 // Get the stack frame by the |routingID|.
506 StackFrame
* frame
= [stackFrames_ objectForKey
:routingID
];
508 NSMutableArray
* variables
= [NSMutableArray array
];
510 // Merge the frame's existing variables.
512 [variables addObjectsFromArray
:frame.variables
];
514 // Add these new variables.
515 NSArray
* addVariables
= [[response rootElement
] children
];
517 for (NSXMLElement
* elm
in addVariables
) {
518 VariableNode
* node
= [[VariableNode alloc
] initWithXMLNode
:elm
];
519 [variables addObject
:[node autorelease
]];
523 frame.variables
= variables
;
527 * Callback from a |-getProperty:| request.
529 - (void)propertiesReceived
:(NSXMLDocument
*)response
531 NSInteger transaction
= [client_ transactionIDFromResponse
:response
];
535 <property> <!-- this is the one we requested -->
536 <property ... /> <!-- these are what we want -->
541 // Detach all the children so we can insert them into another document.
542 NSXMLElement
* parent
= (NSXMLElement
*)[[response rootElement
] childAtIndex
:0];
543 NSArray
* children
= [parent children
];
544 [parent setChildren
:nil];
546 [delegate receivedProperties
:children forTransaction
:transaction
];
550 * Callback from a |-evalScript:| request.
552 - (void)evalScriptReceived
:(NSXMLDocument
*)response
554 NSXMLElement
* parent
= (NSXMLElement
*)[[response rootElement
] childAtIndex
:0];
555 NSString
* value
= [parent base64DecodedValue
];
556 [delegate scriptWasEvaluatedWithResult
:value
];
560 * Callback for setting a breakpoint.
562 - (void)breakpointReceived
:(NSXMLDocument
*)response
564 NSNumber
* transaction
= [NSNumber numberWithInt
:[client_ transactionIDFromResponse
:response
]];
565 Breakpoint
* bp
= [callbackContext_ objectForKey
:transaction
];
569 [callbackContext_ removeObjectForKey
:callbackContext_
];
570 [bp setDebuggerId
:[[[[response rootElement
] attributeForName
:@
"id"] stringValue
] intValue
]];
573 // Private /////////////////////////////////////////////////////////////////////
575 - (void)recordCallback
:(SEL)callback forTransaction
:(NSNumber
*)txn
577 [callTable_ setObject
:NSStringFromSelector(callback
) forKey
:txn
];