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"
20 #import "NSXMLElementAdditions.h"
22 // GDBpConnection (Private) ////////////////////////////////////////////////////
24 @interface DebuggerBackEnd ()
25 @property (readwrite
, copy
) NSString
* status
;
27 - (void)recordCallback
:(SEL)callback forTransaction
:(NSNumber
*)txn
;
29 - (void)updateStatus
:(NSXMLDocument
*)response
;
30 - (void)debuggerStep
:(NSXMLDocument
*)response
;
31 - (void)rebuildStack
:(NSXMLDocument
*)response
;
32 - (void)getStackFrame
:(NSXMLDocument
*)response
;
33 - (void)setSource
:(NSXMLDocument
*)response
;
34 - (void)contextsReceived
:(NSXMLDocument
*)response
;
35 - (void)variablesReceived
:(NSXMLDocument
*)response
;
36 - (void)propertiesReceived
:(NSXMLDocument
*)response
;
40 // GDBpConnection //////////////////////////////////////////////////////////////
42 @implementation DebuggerBackEnd
45 @synthesize attached
= attached_
;
49 * Creates a new DebuggerBackEnd and initializes the socket from the given connection
52 - (id)initWithPort
:(NSUInteger
)aPort
54 if (self = [super init
])
56 stackFrames_
= [[NSMutableDictionary alloc
] init
];
57 callbackContext_
= [NSMutableDictionary
new];
58 callTable_
= [NSMutableDictionary
new];
60 [[BreakpointManager sharedManager
] setConnection
:self];
61 connection_
= [[NetworkConnection alloc
] initWithPort
:aPort
];
62 connection_.delegate
= self;
64 attached_
= [[NSUserDefaults standardUserDefaults
] boolForKey
:@
"DebuggerAttached"];
67 [connection_ connect
];
73 * Deallocates the object
78 [stackFrames_ release
];
80 [callbackContext_ release
];
85 // Getters /////////////////////////////////////////////////////////////////////
89 * Gets the port number
93 return [connection_ port
];
97 * Returns whether or not we have an active connection
101 return [connection_ connected
] && active_
;
105 * Sets the attached state of the debugger. This will open and close the
106 * connection as appropriate.
108 - (void)setAttached
:(BOOL)attached
{
109 if (attached
!= attached_
) {
113 [connection_ connect
];
115 attached_
= attached
;
118 // Commands ////////////////////////////////////////////////////////////////////
119 #pragma mark Commands
122 * Tells the debugger to continue running the script. Returns the current stack frame.
126 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"run"];
127 [self recordCallback
:@selector(debuggerStep
:) forTransaction
:tx
];
131 * Tells the debugger to step into the current command.
135 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"step_into"];
136 [self recordCallback
:@selector(debuggerStep
:) forTransaction
:tx
];
140 * Tells the debugger to step out of the current context
144 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"step_out"];
145 [self recordCallback
:@selector(debuggerStep
:) forTransaction
:tx
];
149 * Tells the debugger to step over the current function
153 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"step_over"];
154 [self recordCallback
:@selector(debuggerStep
:) forTransaction
:tx
];
158 * Halts execution of the script.
164 self.status
= @
"Stopped";
165 if ([delegate respondsToSelector
:@selector(debuggerDisconnected
)])
166 [delegate debuggerDisconnected
];
170 * Ends the current debugging session.
174 [connection_ sendCommandWithFormat
:@
"detach"];
176 self.status
= @
"Stopped";
177 if ([delegate respondsToSelector
:@selector(debuggerDisconnected
)])
178 [delegate debuggerDisconnected
];
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
= [connection_ 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 NSString
* escapedFilename
= [frame.filename stringByReplacingOccurrencesOfString
:@
"%" withString
:@
"%%"];
203 transaction
= [connection_ sendCommandWithFormat
:@
"source -f %@", escapedFilename
];
204 [self recordCallback
:@selector(setSource
:) forTransaction
:transaction
];
205 [callbackContext_ setObject
:routingNumber forKey
:transaction
];
208 // Get the names of all the contexts.
209 transaction
= [connection_ sendCommandWithFormat
:@
"context_names -d %d", frame.index
];
210 [self recordCallback
:@selector(contextsReceived
:) forTransaction
:transaction
];
211 [callbackContext_ setObject
:routingNumber forKey
:transaction
];
213 // This frame will be fully loaded.
217 // Breakpoint Management ///////////////////////////////////////////////////////
218 #pragma mark Breakpoints
221 * Send an add breakpoint command
223 - (void)addBreakpoint
:(Breakpoint
*)bp
225 if (![connection_ connected
])
228 NSString
* file
= [connection_ escapedURIPath
:[bp transformedPath
]];
229 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"breakpoint_set -t line -f %@ -n %i", file
, [bp line
]];
230 [self recordCallback
:@selector(breakpointReceived
:) forTransaction
:tx
];
231 [callbackContext_ setObject
:bp forKey
:tx
];
235 * Removes a breakpoint
237 - (void)removeBreakpoint
:(Breakpoint
*)bp
239 if (![connection_ connected
])
242 [connection_ sendCommandWithFormat
:@
"breakpoint_remove -d %i", [bp debuggerId
]];
245 // Specific Response Handlers //////////////////////////////////////////////////
246 #pragma mark Response Handlers
248 - (void)errorEncountered
:(NSString
*)error
250 [delegate errorEncountered
:error
];
254 * Initial packet received. We've started a brand-new connection to the engine.
256 - (void)handleInitialResponse
:(NSXMLDocument
*)response
258 if (!self.attached
) {
259 [connection_ sendCommandWithFormat
:@
"detach"];
265 // Register any breakpoints that exist offline.
266 for (Breakpoint
* bp
in [[BreakpointManager sharedManager
] breakpoints
])
267 [self addBreakpoint
:bp
];
269 // Load the debugger to make it look active.
270 [delegate debuggerConnected
];
272 // TODO: update the status.
275 - (void)handleResponse
:(NSXMLDocument
*)response
277 NSInteger transactionID
= [connection_ transactionIDFromResponse
:response
];
278 NSNumber
* key
= [NSNumber numberWithInt
:transactionID
];
279 NSString
* callbackStr
= [callTable_ objectForKey
:key
];
282 SEL callback
= NSSelectorFromString(callbackStr
);
283 [self performSelector
:callback withObject
:response
];
285 [callTable_ removeObjectForKey
:key
];
289 * Receiver for status updates. This just freshens up the UI.
291 - (void)updateStatus
:(NSXMLDocument
*)response
293 self.status
= [[[[response rootElement
] attributeForName
:@
"status"] stringValue
] capitalizedString
];
295 if (!status ||
[status isEqualToString
:@
"Stopped"]) {
296 [delegate debuggerDisconnected
];
298 } else if ([status isEqualToString
:@
"Stopping"]) {
299 [connection_ sendCommandWithFormat
:@
"stop"];
305 * Step in/out/over and run all take this path. We first get the status of the
306 * debugger and then request fresh stack information.
308 - (void)debuggerStep
:(NSXMLDocument
*)response
310 [self updateStatus
:response
];
311 if (![self isConnected
])
314 // If this is the run command, tell the delegate that a bunch of updates
315 // are coming. Also remove all existing stack routes and request a new stack.
316 if ([delegate respondsToSelector
:@selector(clobberStack
)])
317 [delegate clobberStack
];
318 [stackFrames_ removeAllObjects
];
319 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"stack_depth"];
320 [self recordCallback
:@selector(rebuildStack
:) forTransaction
:tx
];
321 stackFirstTransactionID_
= [tx intValue
];
325 * We ask for the stack_depth and now we clobber the stack and start rebuilding
328 - (void)rebuildStack
:(NSXMLDocument
*)response
330 NSInteger depth
= [[[[response rootElement
] attributeForName
:@
"depth"] stringValue
] intValue
];
332 if (stackFirstTransactionID_
== [connection_ transactionIDFromResponse
:response
])
335 // We now need to alloc a bunch of stack frames and get the basic information
337 for (NSInteger i
= 0; i
< depth
; i
++)
339 // Use the transaction ID to create a routing path.
340 NSNumber
* routingID
= [connection_ sendCommandWithFormat
:@
"stack_get -d %d", i
];
341 [self recordCallback
:@selector(getStackFrame
:) forTransaction
:routingID
];
342 [stackFrames_ setObject
:[[StackFrame
new] autorelease
] forKey
:routingID
];
347 * The initial rebuild of the stack frame. We now have enough to initialize
348 * a StackFrame object.
350 - (void)getStackFrame
:(NSXMLDocument
*)response
352 // Get the routing information.
353 NSInteger routingID
= [connection_ transactionIDFromResponse
:response
];
354 if (routingID
< stackFirstTransactionID_
)
356 NSNumber
* routingNumber
= [NSNumber numberWithInt
:routingID
];
358 // Make sure we initialized this frame in our last |-rebuildStack:|.
359 StackFrame
* frame
= [stackFrames_ objectForKey
:routingNumber
];
363 NSXMLElement
* xmlframe
= [[[response rootElement
] children
] objectAtIndex
:0];
365 // Initialize the stack frame.
366 frame.index
= [[[xmlframe attributeForName
:@
"level"] stringValue
] intValue
];
367 frame.filename
= [[xmlframe attributeForName
:@
"filename"] stringValue
];
368 frame.lineNumber
= [[[xmlframe attributeForName
:@
"lineno"] stringValue
] intValue
];
369 frame.function
= [[xmlframe attributeForName
:@
"where"] stringValue
];
370 frame.routingID
= routingID
;
372 // Only get the complete frame for the first level. The other frames will get
373 // information loaded lazily when the user clicks on one.
374 if (frame.index
== 0) {
375 [self loadStackFrame
:frame
];
378 if ([delegate respondsToSelector
:@selector(newStackFrame
:)])
379 [delegate newStackFrame
:frame
];
383 * Callback for setting the source of a file while rebuilding a specific stack
386 - (void)setSource
:(NSXMLDocument
*)response
388 NSNumber
* transaction
= [NSNumber numberWithInt
:[connection_ transactionIDFromResponse
:response
]];
389 if ([transaction intValue
] < stackFirstTransactionID_
)
391 NSNumber
* routingNumber
= [callbackContext_ objectForKey
:transaction
];
395 [callbackContext_ removeObjectForKey
:transaction
];
396 StackFrame
* frame
= [stackFrames_ objectForKey
:routingNumber
];
400 frame.source
= [[response rootElement
] base64DecodedValue
];
402 if ([delegate respondsToSelector
:@selector(sourceUpdated
:)])
403 [delegate sourceUpdated
:frame
];
407 * Enumerates all the contexts of a given stack frame. We then in turn get the
408 * contents of each one of these contexts.
410 - (void)contextsReceived
:(NSXMLDocument
*)response
412 // Get the stack frame's routing ID and use it again.
413 NSNumber
* receivedTransaction
= [NSNumber numberWithInt
:[connection_ transactionIDFromResponse
:response
]];
414 if ([receivedTransaction intValue
] < stackFirstTransactionID_
)
416 NSNumber
* routingID
= [callbackContext_ objectForKey
:receivedTransaction
];
420 // Get the stack frame by the |routingID|.
421 StackFrame
* frame
= [stackFrames_ objectForKey
:routingID
];
423 NSXMLElement
* contextNames
= [response rootElement
];
424 for (NSXMLElement
* context
in [contextNames children
])
426 NSInteger cid
= [[[context attributeForName
:@
"id"] stringValue
] intValue
];
428 // Fetch each context's variables.
429 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"context_get -d %d -c %d", frame.index
, cid
];
430 [self recordCallback
:@selector(variablesReceived
:) forTransaction
:tx
];
431 [callbackContext_ setObject
:routingID forKey
:tx
];
436 * Receives the variables from the context and attaches them to the stack frame.
438 - (void)variablesReceived
:(NSXMLDocument
*)response
440 // Get the stack frame's routing ID and use it again.
441 NSInteger transaction
= [connection_ transactionIDFromResponse
:response
];
442 if (transaction
< stackFirstTransactionID_
)
444 NSNumber
* receivedTransaction
= [NSNumber numberWithInt
:transaction
];
445 NSNumber
* routingID
= [callbackContext_ objectForKey
:receivedTransaction
];
449 // Get the stack frame by the |routingID|.
450 StackFrame
* frame
= [stackFrames_ objectForKey
:routingID
];
452 NSMutableArray
* variables
= [NSMutableArray array
];
454 // Merge the frame's existing variables.
456 [variables addObjectsFromArray
:frame.variables
];
458 // Add these new variables.
459 NSArray
* addVariables
= [[response rootElement
] children
];
461 for (NSXMLElement
* elm
in addVariables
) {
462 VariableNode
* node
= [[VariableNode alloc
] initWithXMLNode
:elm
];
463 [variables addObject
:[node autorelease
]];
467 frame.variables
= variables
;
471 * Callback from a |-getProperty:| request.
473 - (void)propertiesReceived
:(NSXMLDocument
*)response
475 NSInteger transaction
= [connection_ transactionIDFromResponse
:response
];
479 <property> <!-- this is the one we requested -->
480 <property ... /> <!-- these are what we want -->
485 // Detach all the children so we can insert them into another document.
486 NSXMLElement
* parent
= (NSXMLElement
*)[[response rootElement
] childAtIndex
:0];
487 NSArray
* children
= [parent children
];
488 [parent setChildren
:nil];
490 [delegate receivedProperties
:children forTransaction
:transaction
];
494 * Callback for setting a breakpoint.
496 - (void)breakpointReceived
:(NSXMLDocument
*)response
498 NSNumber
* transaction
= [NSNumber numberWithInt
:[connection_ transactionIDFromResponse
:response
]];
499 Breakpoint
* bp
= [callbackContext_ objectForKey
:transaction
];
503 [callbackContext_ removeObjectForKey
:callbackContext_
];
504 [bp setDebuggerId
:[[[[response rootElement
] attributeForName
:@
"id"] stringValue
] intValue
]];
507 // Private /////////////////////////////////////////////////////////////////////
509 - (void)recordCallback
:(SEL)callback forTransaction
:(NSNumber
*)txn
511 [callTable_ setObject
:NSStringFromSelector(callback
) forKey
:txn
];