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
;
37 // GDBpConnection //////////////////////////////////////////////////////////////
39 @implementation DebuggerBackEnd
42 @synthesize attached
= attached_
;
46 * Creates a new DebuggerBackEnd and initializes the socket from the given connection
49 - (id)initWithPort
:(NSUInteger
)aPort
51 if (self = [super init
])
53 stackFrames_
= [[NSMutableDictionary alloc
] init
];
54 callTable_
= [NSMutableDictionary
new];
56 [[BreakpointManager sharedManager
] setConnection
:self];
58 client_
= [[ProtocolClient alloc
] initWithDelegate
:self];
60 attached_
= [[NSUserDefaults standardUserDefaults
] boolForKey
:@
"DebuggerAttached"];
63 [client_ connectOnPort
:port_
];
69 * Deallocates the object
74 [stackFrames_ release
];
80 // Getters /////////////////////////////////////////////////////////////////////
84 * Gets the port number
92 * Returns whether or not we have an active connection
100 * Sets the attached state of the debugger. This will open and close the
101 * connection as appropriate.
103 - (void)setAttached
:(BOOL)attached
{
104 if (attached
== attached_
)
108 [client_ disconnect
];
110 [client_ connectOnPort
:port_
];
112 attached_
= attached
;
115 // Commands ////////////////////////////////////////////////////////////////////
116 #pragma mark Commands
119 * Tells the debugger to continue running the script. Returns the current stack frame.
122 [client_ sendCommandWithFormat
:@
"run" handler
:^
(NSXMLDocument
* message
) {
123 [self debuggerStep
:message
];
128 * Tells the debugger to step into the current command.
131 [client_ sendCommandWithFormat
:@
"step_into" handler
:^
(NSXMLDocument
* message
) {
132 [self debuggerStep
:message
];
137 * Tells the debugger to step out of the current context
140 [client_ sendCommandWithFormat
:@
"step_out" handler
:^
(NSXMLDocument
* message
) {
141 [self debuggerStep
:message
];
146 * Tells the debugger to step over the current function
149 [client_ sendCommandWithFormat
:@
"step_over" handler
:^
(NSXMLDocument
* message
) {
150 [self debuggerStep
:message
];
155 * Halts execution of the script.
159 [client_ disconnect
];
161 self.status
= @
"Stopped";
165 * Ends the current debugging session.
169 [client_ sendCommandWithFormat
:@
"detach"];
171 self.status
= @
"Stopped";
175 * Tells the debugger engine to get a specifc property. This also takes in the NSXMLElement
176 * that requested it so that the child can be attached.
178 - (void)getChildrenOfProperty
:(VariableNode
*)property
179 atDepth
:(NSInteger
)depth
180 callback
:(void (^
)(NSArray
*))callback
182 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
185 <property> <!-- this is the one we requested -->
186 <property ... /> <!-- these are what we want -->
191 // Detach all the children so we can insert them into another document.
192 NSXMLElement
* parent
= (NSXMLElement
*)[[message rootElement
] childAtIndex
:0];
193 NSArray
* children
= [parent children
];
194 [parent setChildren
:nil];
198 [client_ sendCommandWithFormat
:@
"property_get -d %d -n %@" handler
:handler
, depth
, [property fullName
]];
201 - (void)loadStackFrame
:(StackFrame
*)frame
206 // Get the source code of the file. Escape % in URL chars.
207 if ([frame.filename length
]) {
208 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
209 int receivedTransaction
= [client_ transactionIDFromResponse
:message
];
210 if (receivedTransaction
< stackFirstTransactionID_
)
213 frame.source
= [[message rootElement
] base64DecodedValue
];
214 if ([self.delegate respondsToSelector
:@selector(sourceUpdated
:)])
215 [self.delegate sourceUpdated
:frame
];
217 [client_ sendCommandWithFormat
:@
"source -f %@" handler
:handler
, frame.filename
];
220 // Get the names of all the contexts.
221 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
222 [self loadContexts
:message forFrame
:frame
];
224 [client_ sendCommandWithFormat
:@
"context_names -d %d" handler
:handler
, frame.index
];
226 // This frame will be fully loaded.
230 // Breakpoint Management ///////////////////////////////////////////////////////
231 #pragma mark Breakpoints
234 * Send an add breakpoint command
236 - (void)addBreakpoint
:(Breakpoint
*)bp
241 NSString
* file
= [ProtocolClient escapedFilePathURI
:[bp transformedPath
]];
242 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
243 [bp setDebuggerId
:[[[[message rootElement
] attributeForName
:@
"id"] stringValue
] intValue
]];
245 [client_ sendCommandWithFormat
:@
"breakpoint_set -t line -f %@ -n %i" handler
:handler
, file
, [bp line
]];
249 * Removes a breakpoint
251 - (void)removeBreakpoint
:(Breakpoint
*)bp
256 [client_ sendCommandWithFormat
:@
"breakpoint_remove -d %i", [bp debuggerId
]];
260 * Sends a string to be evaluated by the engine.
262 - (void)evalScript
:(NSString
*)str
267 char* encodedString
= malloc(modp_b64_encode_len([str length
]));
268 modp_b64_encode(encodedString
, [str UTF8String
], [str length
]);
269 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
270 NSXMLElement
* parent
= (NSXMLElement
*)[[message rootElement
] childAtIndex
:0];
271 NSString
* value
= [parent base64DecodedValue
];
272 [self.delegate scriptWasEvaluatedWithResult
:value
];
274 [client_ sendCustomCommandWithFormat
:@
"eval -i {txn} -- %s" handler
:handler
, encodedString
];
278 // Protocol Client Delegate ////////////////////////////////////////////////////
279 #pragma mark Protocol Client Delegate
281 - (void)debuggerEngineConnected
:(ProtocolClient
*)client
287 * Called when the connection is finally closed. This will reopen the listening
288 * socket if the debugger remains attached.
290 - (void)debuggerEngineDisconnected
:(ProtocolClient
*)client
294 if ([delegate respondsToSelector
:@selector(debuggerDisconnected
)])
295 [delegate debuggerDisconnected
];
298 [client_ connectOnPort
:port_
];
301 - (void)protocolClient
:(ProtocolClient
*)client receivedInitialMessage
:(NSXMLDocument
*)message
{
302 [self handleInitialResponse
:message
];
305 - (void)protocolClient
:(ProtocolClient
*)client receivedErrorMessage
:(NSXMLDocument
*)message
{
306 NSArray
* error
= [[message rootElement
] elementsForName
:@
"error"];
307 if ([error count
] > 0) {
308 NSLog(@
"Xdebug error: %@", error
);
309 NSString
* errorMessage
= [[[[error objectAtIndex
:0] children
] objectAtIndex
:0] stringValue
];
310 [self errorEncountered
:errorMessage
];
314 - (void)debuggerEngine
:(ProtocolClient
*)client receivedMessage
:(NSXMLDocument
*)message
{
315 [self handleResponse
:message
];
318 // Specific Response Handlers //////////////////////////////////////////////////
319 #pragma mark Response Handlers
321 - (void)errorEncountered
:(NSString
*)error
323 [delegate errorEncountered
:error
];
327 * Initial packet received. We've started a brand-new connection to the engine.
329 - (void)handleInitialResponse
:(NSXMLDocument
*)response
331 if (!self.attached
) {
332 [client_ sendCommandWithFormat
:@
"detach"];
338 // Register any breakpoints that exist offline.
339 for (Breakpoint
* bp
in [[BreakpointManager sharedManager
] breakpoints
])
340 [self addBreakpoint
:bp
];
342 // Load the debugger to make it look active.
343 [delegate debuggerConnected
];
345 // TODO: update the status.
348 - (void)handleResponse
:(NSXMLDocument
*)response
350 NSInteger transactionID
= [client_ transactionIDFromResponse
:response
];
351 NSNumber
* key
= [NSNumber numberWithInt
:transactionID
];
352 NSString
* callbackStr
= [callTable_ objectForKey
:key
];
355 SEL callback
= NSSelectorFromString(callbackStr
);
356 [self performSelector
:callback withObject
:response
];
358 [callTable_ removeObjectForKey
:key
];
362 * Receiver for status updates. This just freshens up the UI.
364 - (void)updateStatus
:(NSXMLDocument
*)response
366 self.status
= [[[[response rootElement
] attributeForName
:@
"status"] stringValue
] capitalizedString
];
368 if (!status ||
[status isEqualToString
:@
"Stopped"]) {
369 [delegate debuggerDisconnected
];
371 } else if ([status isEqualToString
:@
"Stopping"]) {
372 [client_ sendCommandWithFormat
:@
"stop"];
378 * Step in/out/over and run all take this path. We first get the status of the
379 * debugger and then request fresh stack information.
381 - (void)debuggerStep
:(NSXMLDocument
*)response
383 [self updateStatus
:response
];
384 if (![self isConnected
])
387 // If this is the run command, tell the delegate that a bunch of updates
388 // are coming. Also remove all existing stack routes and request a new stack.
389 if ([delegate respondsToSelector
:@selector(clobberStack
)])
390 [delegate clobberStack
];
391 [stackFrames_ removeAllObjects
];
392 NSNumber
* tx
= [client_ sendCommandWithFormat
:@
"stack_depth"];
393 [self recordCallback
:@selector(rebuildStack
:) forTransaction
:tx
];
394 stackFirstTransactionID_
= [tx intValue
];
398 * We ask for the stack_depth and now we clobber the stack and start rebuilding
401 - (void)rebuildStack
:(NSXMLDocument
*)response
403 NSInteger depth
= [[[[response rootElement
] attributeForName
:@
"depth"] stringValue
] intValue
];
405 if (stackFirstTransactionID_
== [client_ transactionIDFromResponse
:response
])
408 // We now need to alloc a bunch of stack frames and get the basic information
410 for (NSInteger i
= 0; i
< depth
; i
++)
412 // Use the transaction ID to create a routing path.
413 NSNumber
* routingID
= [client_ sendCommandWithFormat
:@
"stack_get -d %d", i
];
414 [self recordCallback
:@selector(getStackFrame
:) forTransaction
:routingID
];
415 [stackFrames_ setObject
:[[StackFrame
new] autorelease
] forKey
:routingID
];
420 * The initial rebuild of the stack frame. We now have enough to initialize
421 * a StackFrame object.
423 - (void)getStackFrame
:(NSXMLDocument
*)response
425 // Get the routing information.
426 NSInteger routingID
= [client_ transactionIDFromResponse
:response
];
427 if (routingID
< stackFirstTransactionID_
)
429 NSNumber
* routingNumber
= [NSNumber numberWithInt
:routingID
];
431 // Make sure we initialized this frame in our last |-rebuildStack:|.
432 StackFrame
* frame
= [stackFrames_ objectForKey
:routingNumber
];
436 NSXMLElement
* xmlframe
= [[[response rootElement
] children
] objectAtIndex
:0];
438 // Initialize the stack frame.
439 frame.index
= [[[xmlframe attributeForName
:@
"level"] stringValue
] intValue
];
440 frame.filename
= [[xmlframe attributeForName
:@
"filename"] stringValue
];
441 frame.lineNumber
= [[[xmlframe attributeForName
:@
"lineno"] stringValue
] intValue
];
442 frame.function
= [[xmlframe attributeForName
:@
"where"] stringValue
];
443 frame.routingID
= routingID
;
445 // Only get the complete frame for the first level. The other frames will get
446 // information loaded lazily when the user clicks on one.
447 if (frame.index
== 0) {
448 [self loadStackFrame
:frame
];
451 if ([delegate respondsToSelector
:@selector(newStackFrame
:)])
452 [delegate newStackFrame
:frame
];
456 * Enumerates all the contexts of a given stack frame. We then in turn get the
457 * contents of each one of these contexts.
459 - (void)loadContexts
:(NSXMLDocument
*)response forFrame
:(StackFrame
*)frame
{
460 int receivedTransaction
= [client_ transactionIDFromResponse
:response
];
461 if (receivedTransaction
< stackFirstTransactionID_
)
464 NSXMLElement
* contextNames
= [response rootElement
];
465 for (NSXMLElement
* context
in [contextNames children
]) {
466 NSInteger cid
= [[[context attributeForName
:@
"id"] stringValue
] intValue
];
468 // Fetch each context's variables.
469 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
470 NSMutableArray
* variables
= [NSMutableArray array
];
472 // Merge the frame's existing variables.
474 [variables addObjectsFromArray
:frame.variables
];
476 // Add these new variables.
477 NSArray
* addVariables
= [[message rootElement
] children
];
479 for (NSXMLElement
* elm
in addVariables
) {
480 VariableNode
* node
= [[VariableNode alloc
] initWithXMLNode
:elm
];
481 [variables addObject
:[node autorelease
]];
485 frame.variables
= variables
;
487 [client_ sendCommandWithFormat
:@
"context_get -d %d -c %d" handler
:handler
, frame.index
, cid
];
491 // Private /////////////////////////////////////////////////////////////////////
493 - (void)recordCallback
:(SEL)callback forTransaction
:(NSNumber
*)txn
495 [callTable_ setObject
:NSStringFromSelector(callback
) forKey
:txn
];