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
;
41 - (id)initWithPort
:(NSUInteger
)aPort
43 if (self = [super init
]) {
44 [[BreakpointManager sharedManager
] setConnection
:self];
46 _client
= [[ProtocolClient alloc
] initWithDelegate
:self];
48 _autoAttach
= [[NSUserDefaults standardUserDefaults
] boolForKey
:@
"DebuggerAttached"];
51 [_client connectOnPort
:_port
];
61 // Getters /////////////////////////////////////////////////////////////////////
65 * Gets the port number
72 * Returns whether or not we have an active connection
79 * Sets the attached state of the debugger. This will open and close the
80 * connection as appropriate.
82 - (void)setAutoAttach
:(BOOL)flag
{
83 if (flag
== _autoAttach
)
89 [_client connectOnPort
:_port
];
94 // Commands ////////////////////////////////////////////////////////////////////
98 * Tells the debugger to continue running the script. Returns the current stack frame.
101 [_client sendCommandWithFormat
:@
"run" handler
:^
(NSXMLDocument
* message
) {
102 [self debuggerStep
:message
];
107 * Tells the debugger to step into the current command.
110 [_client sendCommandWithFormat
:@
"step_into" handler
:^
(NSXMLDocument
* message
) {
111 [self debuggerStep
:message
];
116 * Tells the debugger to step out of the current context
119 [_client sendCommandWithFormat
:@
"step_out" handler
:^
(NSXMLDocument
* message
) {
120 [self debuggerStep
:message
];
125 * Tells the debugger to step over the current function
128 [_client sendCommandWithFormat
:@
"step_over" handler
:^
(NSXMLDocument
* message
) {
129 [self debuggerStep
:message
];
134 * Halts execution of the script.
137 [_client disconnect
];
139 self.status
= @
"Stopped";
143 * Ends the current debugging session.
146 [_client sendCommandWithFormat
:@
"detach"];
148 self.status
= @
"Stopped";
151 - (void)loadStackFrame
:(StackFrame
*)frame
{
155 // Get the source code of the file. Escape % in URL chars.
156 if ([frame.filename length
]) {
157 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
158 frame.source
= [[message rootElement
] base64DecodedValue
];
160 [_client sendCommandWithFormat
:@
"source -f %@" handler
:handler
, frame.filename
];
163 // Get the names of all the contexts.
164 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
165 [self loadContexts
:message forFrame
:frame
];
167 [_client sendCommandWithFormat
:@
"context_names -d %d" handler
:handler
, frame.index
];
169 // This frame will be fully loaded.
173 - (void)loadVariableNode
:(VariableNode
*)variable
174 forStackFrame
:(StackFrame
*)frame
{
175 if (variable.children.count
== variable.childCount
)
178 [self loadVariableNode
:variable forStackFrame
:frame dataPage
:0 loadedData
:@
[]];
181 - (void)loadVariableNode
:(VariableNode
*)variable
182 forStackFrame
:(StackFrame
*)frame
183 dataPage
:(unsigned int)dataPage
184 loadedData
:(NSArray
*)loadedData
{
185 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
188 <property> <!-- this is the one we requested -->
189 <property ... /> <!-- these are what we want -->
194 // Detach all the children so we can insert them into another document.
195 NSXMLElement
* parent
= (NSXMLElement
*)[[message rootElement
] childAtIndex
:0];
196 NSArray
* children
= [parent children
];
197 [parent setChildren
:nil];
199 // Check to see if there are more children to load.
200 NSArray
* newLoadedData
= [loadedData arrayByAddingObjectsFromArray
:children
];
202 unsigned int totalChildren
= [[[parent attributeForName
:@
"numchildren"] stringValue
] integerValue
];
203 if ([newLoadedData count
] < totalChildren
) {
204 [self loadVariableNode
:variable
206 dataPage
:dataPage
+ 1
207 loadedData
:newLoadedData
];
209 [variable setChildrenFromXMLChildren
:newLoadedData
];
212 [_client sendCommandWithFormat
:@
"property_get -d %d -n %@ -p %u" handler
:handler
, frame.index
, variable.fullName
, dataPage
];
215 // Breakpoint Management ///////////////////////////////////////////////////////
216 #pragma mark Breakpoints
219 * Send an add breakpoint command
221 - (void)addBreakpoint
:(Breakpoint
*)bp
{
225 NSString
* file
= [ProtocolClient escapedFilePathURI
:[bp transformedPath
]];
226 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
227 [bp setDebuggerId
:[[[[message rootElement
] attributeForName
:@
"id"] stringValue
] intValue
]];
229 [_client sendCommandWithFormat
:@
"breakpoint_set -t line -f %@ -n %i" handler
:handler
, file
, [bp line
]];
233 * Removes a breakpoint
235 - (void)removeBreakpoint
:(Breakpoint
*)bp
{
239 [_client sendCommandWithFormat
:@
"breakpoint_remove -d %i", [bp debuggerId
]];
243 * Sends a string to be evaluated by the engine.
245 - (void)evalScript
:(NSString
*)str callback
:(void (^
)(NSString
*))callback
{
249 char* encodedString
= malloc(modp_b64_encode_len([str length
]));
250 modp_b64_encode(encodedString
, [str UTF8String
], [str length
]);
251 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
252 NSXMLElement
* parent
= (NSXMLElement
*)[[message rootElement
] childAtIndex
:0];
253 NSString
* value
= [parent base64DecodedValue
];
256 [_client sendCustomCommandWithFormat
:@
"eval -i {txn} -- %s" handler
:handler
, encodedString
];
260 // Protocol Client Delegate ////////////////////////////////////////////////////
261 #pragma mark Protocol Client Delegate
263 - (void)debuggerEngineConnected
:(ProtocolClient
*)client
{
265 [_model onNewConnection
];
269 * Called when the connection is finally closed. This will reopen the listening
270 * socket if the debugger remains attached.
272 - (void)debuggerEngineDisconnected
:(ProtocolClient
*)client
{
275 [_model onDisconnect
];
278 [_client connectOnPort
:_port
];
281 - (void)protocolClient
:(ProtocolClient
*)client receivedInitialMessage
:(NSXMLDocument
*)message
{
282 [self handleInitialResponse
:message
];
285 - (void)protocolClient
:(ProtocolClient
*)client receivedErrorMessage
:(NSXMLDocument
*)message
{
286 NSArray
* error
= [[message rootElement
] elementsForName
:@
"error"];
287 if ([error count
] > 0) {
288 NSLog(@
"Xdebug error: %@", error
);
289 NSString
* errorMessage
= [[[[error objectAtIndex
:0] children
] objectAtIndex
:0] stringValue
];
290 _model.lastError
= errorMessage
;
294 // Specific Response Handlers //////////////////////////////////////////////////
295 #pragma mark Response Handlers
298 * Initial packet received. We've started a brand-new connection to the engine.
300 - (void)handleInitialResponse
:(NSXMLDocument
*)response
{
301 if (!self.autoAttach
) {
302 [_client sendCommandWithFormat
:@
"detach"];
308 // Register any breakpoints that exist offline.
309 for (Breakpoint
* bp
in [[BreakpointManager sharedManager
] breakpoints
])
310 [self addBreakpoint
:bp
];
312 // TODO: update the status.
316 * Receiver for status updates. This just freshens up the UI.
318 - (void)updateStatus
:(NSXMLDocument
*)response
{
319 self.status
= [[[[response rootElement
] attributeForName
:@
"status"] stringValue
] capitalizedString
];
320 self.model.status
= self.status
;
322 if (!_status ||
[_status isEqualToString
:@
"Stopped"]) {
323 [_model onDisconnect
];
325 } else if ([_status isEqualToString
:@
"Stopping"]) {
326 [_client sendCommandWithFormat
:@
"stop"];
332 * Step in/out/over and run all take this path. We first get the status of the
333 * debugger and then request fresh stack information.
335 - (void)debuggerStep
:(NSXMLDocument
*)response
{
336 [self updateStatus
:response
];
337 if (![self isConnected
])
340 [_client sendCommandWithFormat
:@
"stack_depth" handler
:^
(NSXMLDocument
* message
) {
341 [self rebuildStack
:message
];
346 * We ask for the stack_depth and now we clobber the stack and start rebuilding
349 - (void)rebuildStack
:(NSXMLDocument
*)response
{
350 NSUInteger depth
= [[[[response rootElement
] attributeForName
:@
"depth"] stringValue
] intValue
];
352 // Start with frame 0. If this is a shifted frame, then only it needs to be
353 // re-loaded. If it is not shifted, see if another frame on the stack is equal
354 // to it; if so, then the frames up to that must be discarded. If not, this is
355 // a new stack frame that should be inserted at the top of the stack. Finally,
356 // the sice of the stack is trimmed to |depth| from the bottom.
358 __block NSMutableArray
* tempStack
= [[NSMutableArray alloc
] init
];
360 for (NSUInteger i
= 0; i
< depth
; ++i
) {
361 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
362 [tempStack addObject
:[self transformXMLToStackFrame
:message
]];
363 if (i
== depth
- 1) {
364 [self.model updateStack
:[tempStack autorelease
]];
367 [_client sendCommandWithFormat
:@
"stack_get -d %d" handler
:handler
, i
];
372 * Creates a StackFrame object from an NSXMLDocument response from the "stack_get"
375 - (StackFrame
*)transformXMLToStackFrame
:(NSXMLDocument
*)response
{
376 NSXMLElement
* xmlframe
= (NSXMLElement
*)[[[response rootElement
] children
] objectAtIndex
:0];
377 StackFrame
* frame
= [[[StackFrame alloc
] init
] autorelease
];
378 frame.index
= [[[xmlframe attributeForName
:@
"level"] stringValue
] intValue
];
379 frame.filename
= [[xmlframe attributeForName
:@
"filename"] stringValue
];
380 frame.lineNumber
= [[[xmlframe attributeForName
:@
"lineno"] stringValue
] intValue
];
381 frame.function
= [[xmlframe attributeForName
:@
"where"] stringValue
];
386 * Enumerates all the contexts of a given stack frame. We then in turn get the
387 * contents of each one of these contexts.
389 - (void)loadContexts
:(NSXMLDocument
*)response forFrame
:(StackFrame
*)frame
{
390 NSXMLElement
* contextNames
= [response rootElement
];
391 for (NSXMLElement
* context
in [contextNames children
]) {
392 NSInteger cid
= [[[context attributeForName
:@
"id"] stringValue
] intValue
];
394 // Fetch each context's variables.
395 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
396 NSMutableArray
* variables
= [NSMutableArray array
];
398 // Merge the frame's existing variables.
400 [variables addObjectsFromArray
:frame.variables
];
402 // Add these new variables.
403 NSArray
* addVariables
= [[message rootElement
] children
];
405 for (NSXMLElement
* elm
in addVariables
) {
406 VariableNode
* node
= [[VariableNode alloc
] initWithXMLNode
:elm
];
407 [variables addObject
:[node autorelease
]];
411 frame.variables
= variables
;
413 [_client sendCommandWithFormat
:@
"context_get -d %d -c %d" handler
:handler
, frame.index
, cid
];