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 "DebuggerModel.h"
22 #import "NSXMLElementAdditions.h"
24 @interface DebuggerBackEnd ()
25 @property(readwrite
, copy
, nonatomic
) NSString
* status
;
28 @implementation DebuggerBackEnd
{
29 // The connection to the debugger engine.
31 ProtocolClient
* _client
;
33 // Whether or not a debugging session is currently active.
37 @synthesize status
= _status
;
38 @synthesize autoAttach
= _autoAttach
;
39 @synthesize model
= _model
;
40 @synthesize delegate
= _delegate
;
42 - (id)initWithPort
:(NSUInteger
)aPort
44 if (self = [super init
]) {
45 [[BreakpointManager sharedManager
] setConnection
:self];
47 _client
= [[ProtocolClient alloc
] initWithDelegate
:self];
49 _autoAttach
= [[NSUserDefaults standardUserDefaults
] boolForKey
:@
"DebuggerAttached"];
52 [_client connectOnPort
:_port
];
62 // Getters /////////////////////////////////////////////////////////////////////
66 * Gets the port number
73 * Returns whether or not we have an active connection
80 * Sets the attached state of the debugger. This will open and close the
81 * connection as appropriate.
83 - (void)setAutoAttach
:(BOOL)flag
{
84 if (flag
== _autoAttach
)
90 [_client connectOnPort
:_port
];
95 // Commands ////////////////////////////////////////////////////////////////////
99 * Tells the debugger to continue running the script. Returns the current stack frame.
102 [_client sendCommandWithFormat
:@
"run" handler
:^
(NSXMLDocument
* message
) {
103 [self debuggerStep
:message
];
108 * Tells the debugger to step into the current command.
111 [_client sendCommandWithFormat
:@
"step_into" handler
:^
(NSXMLDocument
* message
) {
112 [self debuggerStep
:message
];
117 * Tells the debugger to step out of the current context
120 [_client sendCommandWithFormat
:@
"step_out" handler
:^
(NSXMLDocument
* message
) {
121 [self debuggerStep
:message
];
126 * Tells the debugger to step over the current function
129 [_client sendCommandWithFormat
:@
"step_over" handler
:^
(NSXMLDocument
* message
) {
130 [self debuggerStep
:message
];
135 * Halts execution of the script.
138 [_client disconnect
];
140 self.status
= @
"Stopped";
144 * Ends the current debugging session.
147 [_client sendCommandWithFormat
:@
"detach"];
149 self.status
= @
"Stopped";
152 - (void)loadStackFrame
:(StackFrame
*)frame
{
156 // Get the source code of the file. Escape % in URL chars.
157 if ([frame.filename length
]) {
158 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
159 frame.source
= [[message rootElement
] base64DecodedValue
];
161 [_client sendCommandWithFormat
:@
"source -f %@" handler
:handler
, frame.filename
];
164 // Get the names of all the contexts.
165 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
166 [self loadContexts
:message forFrame
:frame
];
168 [_client sendCommandWithFormat
:@
"context_names -d %d" handler
:handler
, frame.index
];
170 // This frame will be fully loaded.
174 - (void)loadVariableNode
:(VariableNode
*)variable
175 forStackFrame
:(StackFrame
*)frame
{
176 if (variable.children.count
== variable.childCount
)
179 [self loadVariableNode
:variable forStackFrame
:frame dataPage
:0 loadedData
:@
[]];
182 - (void)loadVariableNode
:(VariableNode
*)variable
183 forStackFrame
:(StackFrame
*)frame
184 dataPage
:(unsigned int)dataPage
185 loadedData
:(NSArray
*)loadedData
{
186 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
189 <property> <!-- this is the one we requested -->
190 <property ... /> <!-- these are what we want -->
195 // Detach all the children so we can insert them into another document.
196 NSXMLElement
* parent
= (NSXMLElement
*)[[message rootElement
] childAtIndex
:0];
197 NSArray
* children
= [parent children
];
198 [parent setChildren
:nil];
200 // Check to see if there are more children to load.
201 NSArray
* newLoadedData
= [loadedData arrayByAddingObjectsFromArray
:children
];
203 unsigned int totalChildren
= [[[parent attributeForName
:@
"numchildren"] stringValue
] integerValue
];
204 if ([newLoadedData count
] < totalChildren
) {
205 [self loadVariableNode
:variable
207 dataPage
:dataPage
+ 1
208 loadedData
:newLoadedData
];
210 [variable setChildrenFromXMLChildren
:newLoadedData
];
213 [_client sendCommandWithFormat
:@
"property_get -d %d -n %@ -p %u" handler
:handler
, frame.index
, variable.fullName
, dataPage
];
216 // Breakpoint Management ///////////////////////////////////////////////////////
217 #pragma mark Breakpoints
220 * Send an add breakpoint command
222 - (void)addBreakpoint
:(Breakpoint
*)bp
{
226 NSString
* file
= [ProtocolClient escapedFilePathURI
:[bp transformedPath
]];
227 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
228 [bp setDebuggerId
:[[[[message rootElement
] attributeForName
:@
"id"] stringValue
] intValue
]];
230 [_client sendCommandWithFormat
:@
"breakpoint_set -t line -f %@ -n %i" handler
:handler
, file
, [bp line
]];
234 * Removes a breakpoint
236 - (void)removeBreakpoint
:(Breakpoint
*)bp
{
240 [_client sendCommandWithFormat
:@
"breakpoint_remove -d %i", [bp debuggerId
]];
244 * Sends a string to be evaluated by the engine.
246 - (void)evalScript
:(NSString
*)str callback
:(void (^
)(NSString
*))callback
{
250 char* encodedString
= malloc(modp_b64_encode_len([str length
]));
251 modp_b64_encode(encodedString
, [str UTF8String
], [str length
]);
252 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
253 NSXMLElement
* parent
= (NSXMLElement
*)[[message rootElement
] childAtIndex
:0];
254 NSString
* value
= [parent base64DecodedValue
];
257 [_client sendCustomCommandWithFormat
:@
"eval -i {txn} -- %s" handler
:handler
, encodedString
];
261 // Protocol Client Delegate ////////////////////////////////////////////////////
262 #pragma mark Protocol Client Delegate
264 - (void)debuggerEngineConnected
:(ProtocolClient
*)client
{
266 [_model onNewConnection
];
270 * Called when the connection is finally closed. This will reopen the listening
271 * socket if the debugger remains attached.
273 - (void)debuggerEngineDisconnected
:(ProtocolClient
*)client
{
276 if ([self.delegate respondsToSelector
:@selector(debuggerDisconnected
)])
277 [self.delegate debuggerDisconnected
];
279 [_model onDisconnect
];
282 [_client connectOnPort
:_port
];
285 - (void)protocolClient
:(ProtocolClient
*)client receivedInitialMessage
:(NSXMLDocument
*)message
{
286 [self handleInitialResponse
:message
];
289 - (void)protocolClient
:(ProtocolClient
*)client receivedErrorMessage
:(NSXMLDocument
*)message
{
290 NSArray
* error
= [[message rootElement
] elementsForName
:@
"error"];
291 if ([error count
] > 0) {
292 NSLog(@
"Xdebug error: %@", error
);
293 NSString
* errorMessage
= [[[[error objectAtIndex
:0] children
] objectAtIndex
:0] stringValue
];
294 _model.lastError
= errorMessage
;
298 // Specific Response Handlers //////////////////////////////////////////////////
299 #pragma mark Response Handlers
302 * Initial packet received. We've started a brand-new connection to the engine.
304 - (void)handleInitialResponse
:(NSXMLDocument
*)response
{
305 if (!self.autoAttach
) {
306 [_client sendCommandWithFormat
:@
"detach"];
312 // Register any breakpoints that exist offline.
313 for (Breakpoint
* bp
in [[BreakpointManager sharedManager
] breakpoints
])
314 [self addBreakpoint
:bp
];
316 // Load the debugger to make it look active.
317 [self.delegate debuggerConnected
];
319 // TODO: update the status.
323 * Receiver for status updates. This just freshens up the UI.
325 - (void)updateStatus
:(NSXMLDocument
*)response
{
326 self.status
= [[[[response rootElement
] attributeForName
:@
"status"] stringValue
] capitalizedString
];
328 if (!_status ||
[_status isEqualToString
:@
"Stopped"]) {
329 [_delegate debuggerDisconnected
];
331 } else if ([_status isEqualToString
:@
"Stopping"]) {
332 [_client sendCommandWithFormat
:@
"stop"];
335 self.model.status
= self.status
;
339 * Step in/out/over and run all take this path. We first get the status of the
340 * debugger and then request fresh stack information.
342 - (void)debuggerStep
:(NSXMLDocument
*)response
{
343 [self updateStatus
:response
];
344 if (![self isConnected
])
347 [_client sendCommandWithFormat
:@
"stack_depth" handler
:^
(NSXMLDocument
* message
) {
348 [self rebuildStack
:message
];
353 * We ask for the stack_depth and now we clobber the stack and start rebuilding
356 - (void)rebuildStack
:(NSXMLDocument
*)response
{
357 NSUInteger depth
= [[[[response rootElement
] attributeForName
:@
"depth"] stringValue
] intValue
];
359 // Start with frame 0. If this is a shifted frame, then only it needs to be
360 // re-loaded. If it is not shifted, see if another frame on the stack is equal
361 // to it; if so, then the frames up to that must be discarded. If not, this is
362 // a new stack frame that should be inserted at the top of the stack. Finally,
363 // the sice of the stack is trimmed to |depth| from the bottom.
365 __block NSMutableArray
* tempStack
= [[NSMutableArray alloc
] init
];
367 for (NSUInteger i
= 0; i
< depth
; ++i
) {
368 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
369 [tempStack addObject
:[self transformXMLToStackFrame
:message
]];
370 if (i
== depth
- 1) {
371 [self.model updateStack
:[tempStack autorelease
]];
374 [_client sendCommandWithFormat
:@
"stack_get -d %d" handler
:handler
, i
];
379 * Creates a StackFrame object from an NSXMLDocument response from the "stack_get"
382 - (StackFrame
*)transformXMLToStackFrame
:(NSXMLDocument
*)response
{
383 NSXMLElement
* xmlframe
= (NSXMLElement
*)[[[response rootElement
] children
] objectAtIndex
:0];
384 StackFrame
* frame
= [[[StackFrame alloc
] init
] autorelease
];
385 frame.index
= [[[xmlframe attributeForName
:@
"level"] stringValue
] intValue
];
386 frame.filename
= [[xmlframe attributeForName
:@
"filename"] stringValue
];
387 frame.lineNumber
= [[[xmlframe attributeForName
:@
"lineno"] stringValue
] intValue
];
388 frame.function
= [[xmlframe attributeForName
:@
"where"] stringValue
];
393 * Enumerates all the contexts of a given stack frame. We then in turn get the
394 * contents of each one of these contexts.
396 - (void)loadContexts
:(NSXMLDocument
*)response forFrame
:(StackFrame
*)frame
{
397 NSXMLElement
* contextNames
= [response rootElement
];
398 for (NSXMLElement
* context
in [contextNames children
]) {
399 NSInteger cid
= [[[context attributeForName
:@
"id"] stringValue
] intValue
];
401 // Fetch each context's variables.
402 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
403 NSMutableArray
* variables
= [NSMutableArray array
];
405 // Merge the frame's existing variables.
407 [variables addObjectsFromArray
:frame.variables
];
409 // Add these new variables.
410 NSArray
* addVariables
= [[message rootElement
] children
];
412 for (NSXMLElement
* elm
in addVariables
) {
413 VariableNode
* node
= [[VariableNode alloc
] initWithXMLNode
:elm
];
414 [variables addObject
:[node autorelease
]];
418 frame.variables
= variables
;
420 [_client sendCommandWithFormat
:@
"context_get -d %d -c %d" handler
:handler
, frame.index
, cid
];