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;
63 [connection_ connect
];
69 * Deallocates the object
74 [stackFrames_ release
];
76 [callbackContext_ release
];
81 // Getters /////////////////////////////////////////////////////////////////////
85 * Gets the port number
89 return [connection_ port
];
93 * Returns whether or not we have an active connection
97 return [connection_ connected
] && active_
;
100 // Commands ////////////////////////////////////////////////////////////////////
101 #pragma mark Commands
104 * Tells the debugger to continue running the script. Returns the current stack frame.
108 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"run"];
109 [self recordCallback
:@selector(debuggerStep
:) forTransaction
:tx
];
113 * Tells the debugger to step into the current command.
117 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"step_into"];
118 [self recordCallback
:@selector(debuggerStep
:) forTransaction
:tx
];
122 * Tells the debugger to step out of the current context
126 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"step_out"];
127 [self recordCallback
:@selector(debuggerStep
:) forTransaction
:tx
];
131 * Tells the debugger to step over the current function
135 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"step_over"];
136 [self recordCallback
:@selector(debuggerStep
:) forTransaction
:tx
];
140 * Ends the current debugging session.
144 [connection_ sendCommandWithFormat
:@
"detach"];
146 self.status
= @
"Stopped";
147 if ([delegate respondsToSelector
:@selector(debuggerDisconnected
)])
148 [delegate debuggerDisconnected
];
152 * Tells the debugger engine to get a specifc property. This also takes in the NSXMLElement
153 * that requested it so that the child can be attached.
155 - (NSInteger
)getChildrenOfProperty
:(VariableNode
*)property atDepth
:(NSInteger
)depth
;
157 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"property_get -d %d -n %@", depth
, [property fullName
]];
158 [self recordCallback
:@selector(propertiesReceived
:) forTransaction
:tx
];
159 return [tx intValue
];
162 - (void)loadStackFrame
:(StackFrame
*)frame
167 NSNumber
* routingNumber
= [NSNumber numberWithInt
:frame.routingID
];
168 NSNumber
* transaction
= nil;
170 // Get the source code of the file. Escape % in URL chars.
171 if ([frame.filename length
]) {
172 NSString
* escapedFilename
= [frame.filename stringByReplacingOccurrencesOfString
:@
"%" withString
:@
"%%"];
173 transaction
= [connection_ sendCommandWithFormat
:@
"source -f %@", escapedFilename
];
174 [self recordCallback
:@selector(setSource
:) forTransaction
:transaction
];
175 [callbackContext_ setObject
:routingNumber forKey
:transaction
];
178 // Get the names of all the contexts.
179 transaction
= [connection_ sendCommandWithFormat
:@
"context_names -d %d", frame.index
];
180 [self recordCallback
:@selector(contextsReceived
:) forTransaction
:transaction
];
181 [callbackContext_ setObject
:routingNumber forKey
:transaction
];
183 // This frame will be fully loaded.
187 // Breakpoint Management ///////////////////////////////////////////////////////
188 #pragma mark Breakpoints
191 * Send an add breakpoint command
193 - (void)addBreakpoint
:(Breakpoint
*)bp
195 if (![connection_ connected
])
198 NSString
* file
= [connection_ escapedURIPath
:[bp transformedPath
]];
199 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"breakpoint_set -t line -f %@ -n %i", file
, [bp line
]];
200 [self recordCallback
:@selector(breakpointReceived
:) forTransaction
:tx
];
201 [callbackContext_ setObject
:bp forKey
:tx
];
205 * Removes a breakpoint
207 - (void)removeBreakpoint
:(Breakpoint
*)bp
209 if (![connection_ connected
])
212 [connection_ sendCommandWithFormat
:@
"breakpoint_remove -d %i", [bp debuggerId
]];
215 // Specific Response Handlers //////////////////////////////////////////////////
216 #pragma mark Response Handlers
218 - (void)connectionDidAccept
:(NetworkConnection
*)cx
221 [connection_ sendCommandWithFormat
:@
"detach"];
224 - (void)errorEncountered
:(NSString
*)error
226 [delegate errorEncountered
:error
];
230 * Initial packet received. We've started a brand-new connection to the engine.
232 - (void)handleInitialResponse
:(NSXMLDocument
*)response
236 // Register any breakpoints that exist offline.
237 for (Breakpoint
* bp
in [[BreakpointManager sharedManager
] breakpoints
])
238 [self addBreakpoint
:bp
];
240 // Load the debugger to make it look active.
241 [delegate debuggerConnected
];
243 // TODO: update the status.
246 - (void)handleResponse
:(NSXMLDocument
*)response
248 NSInteger transactionID
= [connection_ transactionIDFromResponse
:response
];
249 NSNumber
* key
= [NSNumber numberWithInt
:transactionID
];
250 NSString
* callbackStr
= [callTable_ objectForKey
:key
];
253 SEL callback
= NSSelectorFromString(callbackStr
);
254 [self performSelector
:callback withObject
:response
];
256 [callTable_ removeObjectForKey
:key
];
260 * Receiver for status updates. This just freshens up the UI.
262 - (void)updateStatus
:(NSXMLDocument
*)response
264 self.status
= [[[[response rootElement
] attributeForName
:@
"status"] stringValue
] capitalizedString
];
266 if (!status ||
[status isEqualToString
:@
"Stopped"]) {
267 [delegate debuggerDisconnected
];
269 } else if ([status isEqualToString
:@
"Stopping"]) {
270 [connection_ sendCommandWithFormat
:@
"stop"];
276 * Step in/out/over and run all take this path. We first get the status of the
277 * debugger and then request fresh stack information.
279 - (void)debuggerStep
:(NSXMLDocument
*)response
281 [self updateStatus
:response
];
282 if (![self isConnected
])
285 // If this is the run command, tell the delegate that a bunch of updates
286 // are coming. Also remove all existing stack routes and request a new stack.
287 if ([delegate respondsToSelector
:@selector(clobberStack
)])
288 [delegate clobberStack
];
289 [stackFrames_ removeAllObjects
];
290 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"stack_depth"];
291 [self recordCallback
:@selector(rebuildStack
:) forTransaction
:tx
];
292 stackFirstTransactionID_
= [tx intValue
];
296 * We ask for the stack_depth and now we clobber the stack and start rebuilding
299 - (void)rebuildStack
:(NSXMLDocument
*)response
301 NSInteger depth
= [[[[response rootElement
] attributeForName
:@
"depth"] stringValue
] intValue
];
303 if (stackFirstTransactionID_
== [connection_ transactionIDFromResponse
:response
])
306 // We now need to alloc a bunch of stack frames and get the basic information
308 for (NSInteger i
= 0; i
< depth
; i
++)
310 // Use the transaction ID to create a routing path.
311 NSNumber
* routingID
= [connection_ sendCommandWithFormat
:@
"stack_get -d %d", i
];
312 [self recordCallback
:@selector(getStackFrame
:) forTransaction
:routingID
];
313 [stackFrames_ setObject
:[[StackFrame
new] autorelease
] forKey
:routingID
];
318 * The initial rebuild of the stack frame. We now have enough to initialize
319 * a StackFrame object.
321 - (void)getStackFrame
:(NSXMLDocument
*)response
323 // Get the routing information.
324 NSInteger routingID
= [connection_ transactionIDFromResponse
:response
];
325 if (routingID
< stackFirstTransactionID_
)
327 NSNumber
* routingNumber
= [NSNumber numberWithInt
:routingID
];
329 // Make sure we initialized this frame in our last |-rebuildStack:|.
330 StackFrame
* frame
= [stackFrames_ objectForKey
:routingNumber
];
334 NSXMLElement
* xmlframe
= [[[response rootElement
] children
] objectAtIndex
:0];
336 // Initialize the stack frame.
337 frame.index
= [[[xmlframe attributeForName
:@
"level"] stringValue
] intValue
];
338 frame.filename
= [[xmlframe attributeForName
:@
"filename"] stringValue
];
339 frame.lineNumber
= [[[xmlframe attributeForName
:@
"lineno"] stringValue
] intValue
];
340 frame.function
= [[xmlframe attributeForName
:@
"where"] stringValue
];
341 frame.routingID
= routingID
;
343 // Only get the complete frame for the first level. The other frames will get
344 // information loaded lazily when the user clicks on one.
345 if (frame.index
== 0) {
346 [self loadStackFrame
:frame
];
349 if ([delegate respondsToSelector
:@selector(newStackFrame
:)])
350 [delegate newStackFrame
:frame
];
354 * Callback for setting the source of a file while rebuilding a specific stack
357 - (void)setSource
:(NSXMLDocument
*)response
359 NSNumber
* transaction
= [NSNumber numberWithInt
:[connection_ transactionIDFromResponse
:response
]];
360 if ([transaction intValue
] < stackFirstTransactionID_
)
362 NSNumber
* routingNumber
= [callbackContext_ objectForKey
:transaction
];
366 [callbackContext_ removeObjectForKey
:transaction
];
367 StackFrame
* frame
= [stackFrames_ objectForKey
:routingNumber
];
371 frame.source
= [[response rootElement
] base64DecodedValue
];
373 if ([delegate respondsToSelector
:@selector(sourceUpdated
:)])
374 [delegate sourceUpdated
:frame
];
378 * Enumerates all the contexts of a given stack frame. We then in turn get the
379 * contents of each one of these contexts.
381 - (void)contextsReceived
:(NSXMLDocument
*)response
383 // Get the stack frame's routing ID and use it again.
384 NSNumber
* receivedTransaction
= [NSNumber numberWithInt
:[connection_ transactionIDFromResponse
:response
]];
385 if ([receivedTransaction intValue
] < stackFirstTransactionID_
)
387 NSNumber
* routingID
= [callbackContext_ objectForKey
:receivedTransaction
];
391 // Get the stack frame by the |routingID|.
392 StackFrame
* frame
= [stackFrames_ objectForKey
:routingID
];
394 NSXMLElement
* contextNames
= [response rootElement
];
395 for (NSXMLElement
* context
in [contextNames children
])
397 NSInteger cid
= [[[context attributeForName
:@
"id"] stringValue
] intValue
];
399 // Fetch each context's variables.
400 NSNumber
* tx
= [connection_ sendCommandWithFormat
:@
"context_get -d %d -c %d", frame.index
, cid
];
401 [self recordCallback
:@selector(variablesReceived
:) forTransaction
:tx
];
402 [callbackContext_ setObject
:routingID forKey
:tx
];
407 * Receives the variables from the context and attaches them to the stack frame.
409 - (void)variablesReceived
:(NSXMLDocument
*)response
411 // Get the stack frame's routing ID and use it again.
412 NSInteger transaction
= [connection_ transactionIDFromResponse
:response
];
413 if (transaction
< stackFirstTransactionID_
)
415 NSNumber
* receivedTransaction
= [NSNumber numberWithInt
:transaction
];
416 NSNumber
* routingID
= [callbackContext_ objectForKey
:receivedTransaction
];
420 // Get the stack frame by the |routingID|.
421 StackFrame
* frame
= [stackFrames_ objectForKey
:routingID
];
423 NSMutableArray
* variables
= [NSMutableArray array
];
425 // Merge the frame's existing variables.
427 [variables addObjectsFromArray
:frame.variables
];
429 // Add these new variables.
430 NSArray
* addVariables
= [[response rootElement
] children
];
432 for (NSXMLElement
* elm
in addVariables
) {
433 VariableNode
* node
= [[VariableNode alloc
] initWithXMLNode
:elm
];
434 [variables addObject
:[node autorelease
]];
438 frame.variables
= variables
;
442 * Callback from a |-getProperty:| request.
444 - (void)propertiesReceived
:(NSXMLDocument
*)response
446 NSInteger transaction
= [connection_ transactionIDFromResponse
:response
];
450 <property> <!-- this is the one we requested -->
451 <property ... /> <!-- these are what we want -->
456 // Detach all the children so we can insert them into another document.
457 NSXMLElement
* parent
= (NSXMLElement
*)[[response rootElement
] childAtIndex
:0];
458 NSArray
* children
= [parent children
];
459 [parent setChildren
:nil];
461 [delegate receivedProperties
:children forTransaction
:transaction
];
465 * Callback for setting a breakpoint.
467 - (void)breakpointReceived
:(NSXMLDocument
*)response
469 NSNumber
* transaction
= [NSNumber numberWithInt
:[connection_ transactionIDFromResponse
:response
]];
470 Breakpoint
* bp
= [callbackContext_ objectForKey
:transaction
];
474 [callbackContext_ removeObjectForKey
:callbackContext_
];
475 [bp setDebuggerId
:[[[[response rootElement
] attributeForName
:@
"id"] stringValue
] intValue
]];
478 // Private /////////////////////////////////////////////////////////////////////
480 - (void)recordCallback
:(SEL)callback forTransaction
:(NSNumber
*)txn
482 [callTable_ setObject
:NSStringFromSelector(callback
) forKey
:txn
];