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 @interface DebuggerBackEnd ()
24 @property(readwrite
, copy
, nonatomic
) NSString
* status
;
27 @implementation DebuggerBackEnd
{
28 // The connection to the debugger engine.
30 ProtocolClient
* _client
;
32 // Whether or not a debugging session is currently active.
35 // The earliest transaction ID for the current build of |stackFrames_|.
36 NSInteger stackFirstTransactionID_
;
39 @synthesize status
= _status
;
40 @synthesize autoAttach
= _autoAttach
;
41 @synthesize delegate
= _delegate
;
43 - (id)initWithPort
:(NSUInteger
)aPort
45 if (self = [super init
]) {
46 [[BreakpointManager sharedManager
] setConnection
:self];
48 _client
= [[ProtocolClient alloc
] initWithDelegate
:self];
50 _autoAttach
= [[NSUserDefaults standardUserDefaults
] boolForKey
:@
"DebuggerAttached"];
53 [_client connectOnPort
:_port
];
63 // Getters /////////////////////////////////////////////////////////////////////
67 * Gets the port number
74 * Returns whether or not we have an active connection
81 * Sets the attached state of the debugger. This will open and close the
82 * connection as appropriate.
84 - (void)setAutoAttach
:(BOOL)flag
{
85 if (flag
== _autoAttach
)
91 [_client connectOnPort
:_port
];
96 // Commands ////////////////////////////////////////////////////////////////////
100 * Tells the debugger to continue running the script. Returns the current stack frame.
103 [_client sendCommandWithFormat
:@
"run" handler
:^
(NSXMLDocument
* message
) {
104 [self debuggerStep
:message
];
109 * Tells the debugger to step into the current command.
112 [_client sendCommandWithFormat
:@
"step_into" handler
:^
(NSXMLDocument
* message
) {
113 [self debuggerStep
:message
];
118 * Tells the debugger to step out of the current context
121 [_client sendCommandWithFormat
:@
"step_out" handler
:^
(NSXMLDocument
* message
) {
122 [self debuggerStep
:message
];
127 * Tells the debugger to step over the current function
130 [_client sendCommandWithFormat
:@
"step_over" handler
:^
(NSXMLDocument
* message
) {
131 [self debuggerStep
:message
];
136 * Halts execution of the script.
139 [_client disconnect
];
141 self.status
= @
"Stopped";
145 * Ends the current debugging session.
148 [_client sendCommandWithFormat
:@
"detach"];
150 self.status
= @
"Stopped";
154 * Tells the debugger engine to get a specifc property. This also takes in the NSXMLElement
155 * that requested it so that the child can be attached.
157 - (void)getChildrenOfProperty
:(VariableNode
*)property
158 atDepth
:(NSInteger
)depth
159 callback
:(void (^
)(NSArray
*))callback
{
160 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
163 <property> <!-- this is the one we requested -->
164 <property ... /> <!-- these are what we want -->
169 // Detach all the children so we can insert them into another document.
170 NSXMLElement
* parent
= (NSXMLElement
*)[[message rootElement
] childAtIndex
:0];
171 NSArray
* children
= [parent children
];
172 [parent setChildren
:nil];
176 [_client sendCommandWithFormat
:@
"property_get -d %d -n %@" handler
:handler
, depth
, [property fullName
]];
179 - (void)loadStackFrame
:(StackFrame
*)frame
{
183 // Get the source code of the file. Escape % in URL chars.
184 if ([frame.filename length
]) {
185 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
186 int receivedTransaction
= [_client transactionIDFromResponse
:message
];
187 if (receivedTransaction
< stackFirstTransactionID_
)
190 frame.source
= [[message rootElement
] base64DecodedValue
];
191 if ([self.delegate respondsToSelector
:@selector(sourceUpdated
:)])
192 [self.delegate sourceUpdated
:frame
];
194 [_client sendCommandWithFormat
:@
"source -f %@" handler
:handler
, frame.filename
];
197 // Get the names of all the contexts.
198 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
199 [self loadContexts
:message forFrame
:frame
];
201 [_client sendCommandWithFormat
:@
"context_names -d %d" handler
:handler
, frame.index
];
203 // This frame will be fully loaded.
207 // Breakpoint Management ///////////////////////////////////////////////////////
208 #pragma mark Breakpoints
211 * Send an add breakpoint command
213 - (void)addBreakpoint
:(Breakpoint
*)bp
{
217 NSString
* file
= [ProtocolClient escapedFilePathURI
:[bp transformedPath
]];
218 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
219 [bp setDebuggerId
:[[[[message rootElement
] attributeForName
:@
"id"] stringValue
] intValue
]];
221 [_client sendCommandWithFormat
:@
"breakpoint_set -t line -f %@ -n %i" handler
:handler
, file
, [bp line
]];
225 * Removes a breakpoint
227 - (void)removeBreakpoint
:(Breakpoint
*)bp
{
231 [_client sendCommandWithFormat
:@
"breakpoint_remove -d %i", [bp debuggerId
]];
235 * Sends a string to be evaluated by the engine.
237 - (void)evalScript
:(NSString
*)str callback
:(void (^
)(NSString
*))callback
{
241 char* encodedString
= malloc(modp_b64_encode_len([str length
]));
242 modp_b64_encode(encodedString
, [str UTF8String
], [str length
]);
243 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
244 NSXMLElement
* parent
= (NSXMLElement
*)[[message rootElement
] childAtIndex
:0];
245 NSString
* value
= [parent base64DecodedValue
];
248 [_client sendCustomCommandWithFormat
:@
"eval -i {txn} -- %s" handler
:handler
, encodedString
];
252 // Protocol Client Delegate ////////////////////////////////////////////////////
253 #pragma mark Protocol Client Delegate
255 - (void)debuggerEngineConnected
:(ProtocolClient
*)client
{
260 * Called when the connection is finally closed. This will reopen the listening
261 * socket if the debugger remains attached.
263 - (void)debuggerEngineDisconnected
:(ProtocolClient
*)client
{
266 if ([self.delegate respondsToSelector
:@selector(debuggerDisconnected
)])
267 [self.delegate debuggerDisconnected
];
270 [_client connectOnPort
:_port
];
273 - (void)protocolClient
:(ProtocolClient
*)client receivedInitialMessage
:(NSXMLDocument
*)message
{
274 [self handleInitialResponse
:message
];
277 - (void)protocolClient
:(ProtocolClient
*)client receivedErrorMessage
:(NSXMLDocument
*)message
{
278 NSArray
* error
= [[message rootElement
] elementsForName
:@
"error"];
279 if ([error count
] > 0) {
280 NSLog(@
"Xdebug error: %@", error
);
281 NSString
* errorMessage
= [[[[error objectAtIndex
:0] children
] objectAtIndex
:0] stringValue
];
282 [self errorEncountered
:errorMessage
];
286 // Specific Response Handlers //////////////////////////////////////////////////
287 #pragma mark Response Handlers
289 - (void)errorEncountered
:(NSString
*)error
{
290 [self.delegate errorEncountered
:error
];
294 * Initial packet received. We've started a brand-new connection to the engine.
296 - (void)handleInitialResponse
:(NSXMLDocument
*)response
{
297 if (!self.autoAttach
) {
298 [_client sendCommandWithFormat
:@
"detach"];
304 // Register any breakpoints that exist offline.
305 for (Breakpoint
* bp
in [[BreakpointManager sharedManager
] breakpoints
])
306 [self addBreakpoint
:bp
];
308 // Load the debugger to make it look active.
309 [self.delegate debuggerConnected
];
311 // TODO: update the status.
315 * Receiver for status updates. This just freshens up the UI.
317 - (void)updateStatus
:(NSXMLDocument
*)response
{
318 self.status
= [[[[response rootElement
] attributeForName
:@
"status"] stringValue
] capitalizedString
];
320 if (!_status ||
[_status isEqualToString
:@
"Stopped"]) {
321 [_delegate debuggerDisconnected
];
323 } else if ([_status isEqualToString
:@
"Stopping"]) {
324 [_client sendCommandWithFormat
:@
"stop"];
330 * Step in/out/over and run all take this path. We first get the status of the
331 * debugger and then request fresh stack information.
333 - (void)debuggerStep
:(NSXMLDocument
*)response
{
334 [self updateStatus
:response
];
335 if (![self isConnected
])
338 // If this is the run command, tell the delegate that a bunch of updates
339 // are coming. Also remove all existing stack routes and request a new stack.
340 if ([self.delegate respondsToSelector
:@selector(clobberStack
)])
341 [self.delegate clobberStack
];
343 [_client sendCommandWithFormat
:@
"stack_depth" handler
:^
(NSXMLDocument
* message
) {
344 stackFirstTransactionID_
= [_client transactionIDFromResponse
:message
];
345 [self rebuildStack
:message
];
350 * We ask for the stack_depth and now we clobber the stack and start rebuilding
353 - (void)rebuildStack
:(NSXMLDocument
*)response
{
354 NSInteger depth
= [[[[response rootElement
] attributeForName
:@
"depth"] stringValue
] intValue
];
356 // We now need to alloc a bunch of stack frames and get the basic information
358 for (NSInteger i
= 0; i
< depth
; i
++) {
359 // Use the transaction ID to create a routing path.
360 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
361 NSInteger receivedTransaction
= [_client transactionIDFromResponse
:message
];
362 if (receivedTransaction
< stackFirstTransactionID_
)
365 StackFrame
* frame
= [[[StackFrame alloc
] init
] autorelease
];
366 NSXMLElement
* xmlframe
= (NSXMLElement
*)[[[message rootElement
] children
] objectAtIndex
:0];
368 // Initialize the stack frame.
369 frame.index
= [[[xmlframe attributeForName
:@
"level"] stringValue
] intValue
];
370 frame.filename
= [[xmlframe attributeForName
:@
"filename"] stringValue
];
371 frame.lineNumber
= [[[xmlframe attributeForName
:@
"lineno"] stringValue
] intValue
];
372 frame.function
= [[xmlframe attributeForName
:@
"where"] stringValue
];
374 // Only get the complete frame for the first level. The other frames will get
375 // information loaded lazily when the user clicks on one.
376 if (frame.index
== 0) {
377 [self loadStackFrame
:frame
];
380 if ([self.delegate respondsToSelector
:@selector(newStackFrame
:)])
381 [self.delegate newStackFrame
:frame
];
383 [_client sendCommandWithFormat
:@
"stack_get -d %d" handler
:handler
, i
];
388 * Enumerates all the contexts of a given stack frame. We then in turn get the
389 * contents of each one of these contexts.
391 - (void)loadContexts
:(NSXMLDocument
*)response forFrame
:(StackFrame
*)frame
{
392 int receivedTransaction
= [_client transactionIDFromResponse
:response
];
393 if (receivedTransaction
< stackFirstTransactionID_
)
396 NSXMLElement
* contextNames
= [response rootElement
];
397 for (NSXMLElement
* context
in [contextNames children
]) {
398 NSInteger cid
= [[[context attributeForName
:@
"id"] stringValue
] intValue
];
400 // Fetch each context's variables.
401 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
402 NSMutableArray
* variables
= [NSMutableArray array
];
404 // Merge the frame's existing variables.
406 [variables addObjectsFromArray
:frame.variables
];
408 // Add these new variables.
409 NSArray
* addVariables
= [[message rootElement
] children
];
411 for (NSXMLElement
* elm
in addVariables
) {
412 VariableNode
* node
= [[VariableNode alloc
] initWithXMLNode
:elm
];
413 [variables addObject
:[node autorelease
]];
417 frame.variables
= variables
;
419 [_client sendCommandWithFormat
:@
"context_get -d %d -c %d" handler
:handler
, frame.index
, cid
];