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 @implementation DebuggerBackEnd
{
25 // The connection to the debugger engine.
27 ProtocolClient
* _client
;
30 @synthesize autoAttach
= _autoAttach
;
31 @synthesize model
= _model
;
33 - (instancetype
)initWithPort
:(NSUInteger
)aPort autoAttach
:(BOOL)doAttach
35 if (self = [super init
]) {
36 [[BreakpointManager sharedManager
] setConnection
:self];
38 _client
= [[ProtocolClient alloc
] initWithDelegate
:self];
40 _autoAttach
= doAttach
;
42 [_client connectOnPort
:_port
];
52 // Getters /////////////////////////////////////////////////////////////////////
56 * Gets the port number
63 * Sets the attached state of the debugger. This will open and close the
64 * connection as appropriate.
66 - (void)setAutoAttach
:(BOOL)flag
{
67 if (flag
== _autoAttach
)
73 [_client connectOnPort
:_port
];
78 // Commands ////////////////////////////////////////////////////////////////////
82 * Tells the debugger to continue running the script. Returns the current stack frame.
85 [_client sendCommandWithFormat
:@
"run" handler
:^
(NSXMLDocument
* message
) {
86 [self debuggerStep
:message
];
91 * Tells the debugger to step into the current command.
94 [_client sendCommandWithFormat
:@
"step_into" handler
:^
(NSXMLDocument
* message
) {
95 [self debuggerStep
:message
];
100 * Tells the debugger to step out of the current context
103 [_client sendCommandWithFormat
:@
"step_out" handler
:^
(NSXMLDocument
* message
) {
104 [self debuggerStep
:message
];
109 * Tells the debugger to step over the current function
112 [_client sendCommandWithFormat
:@
"step_over" handler
:^
(NSXMLDocument
* message
) {
113 [self debuggerStep
:message
];
118 * Halts execution of the script.
121 [_client disconnect
];
122 self.model.status
= @
"Stopped";
126 * Ends the current debugging session.
129 [_client sendCommandWithFormat
:@
"detach"];
130 self.model.status
= @
"Stopped";
133 - (void)loadStackFrame
:(StackFrame
*)frame
{
137 // Get the source code of the file. Escape % in URL chars.
138 if ([frame.filename length
]) {
139 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
140 frame.source
= [[message rootElement
] base64DecodedValue
];
142 [_client sendCommandWithFormat
:@
"source -f %@" handler
:handler
, frame.filename
];
145 // Get the names of all the contexts.
146 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
147 [self loadContexts
:message forFrame
:frame
];
149 [_client sendCommandWithFormat
:@
"context_names -d %d" handler
:handler
, frame.index
];
151 // This frame will be fully loaded.
155 - (void)loadVariableNode
:(VariableNode
*)variable
156 forStackFrame
:(StackFrame
*)frame
{
157 if (variable.children.count
== variable.childCount
)
160 [self loadVariableNode
:variable forStackFrame
:frame dataPage
:0 loadedData
:@
[]];
163 - (void)loadVariableNode
:(VariableNode
*)variable
164 forStackFrame
:(StackFrame
*)frame
165 dataPage
:(unsigned int)dataPage
166 loadedData
:(NSArray
*)loadedData
{
167 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
170 <property> <!-- this is the one we requested -->
171 <property ... /> <!-- these are what we want -->
176 // Detach all the children so we can insert them into another document.
177 NSXMLElement
* parent
= (NSXMLElement
*)[[message rootElement
] childAtIndex
:0];
178 NSArray
* children
= [parent children
];
179 [parent setChildren
:nil];
181 // Check to see if there are more children to load.
182 NSArray
* newLoadedData
= [loadedData arrayByAddingObjectsFromArray
:children
];
184 unsigned int totalChildren
= [[[parent attributeForName
:@
"numchildren"] stringValue
] integerValue
];
185 if ([newLoadedData count
] < totalChildren
) {
186 [self loadVariableNode
:variable
188 dataPage
:dataPage
+ 1
189 loadedData
:newLoadedData
];
191 [variable setChildrenFromXMLChildren
:newLoadedData
];
194 [_client sendCommandWithFormat
:@
"property_get -d %d -n %@ -p %u" handler
:handler
, frame.index
, variable.fullName
, dataPage
];
197 // Breakpoint Management ///////////////////////////////////////////////////////
198 #pragma mark Breakpoints
201 * Send an add breakpoint command
203 - (void)addBreakpoint
:(Breakpoint
*)bp
{
204 if (!self.model.connected
)
207 NSString
* file
= [ProtocolClient escapedFilePathURI
:[bp transformedPath
]];
208 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
209 [bp setDebuggerId
:[[[[message rootElement
] attributeForName
:@
"id"] stringValue
] intValue
]];
211 [_client sendCommandWithFormat
:@
"breakpoint_set -t line -f %@ -n %i" handler
:handler
, file
, [bp line
]];
215 * Removes a breakpoint
217 - (void)removeBreakpoint
:(Breakpoint
*)bp
{
218 if (!self.model.connected
)
221 [_client sendCommandWithFormat
:@
"breakpoint_remove -d %i", [bp debuggerId
]];
225 * Sends a string to be evaluated by the engine.
227 - (void)evalScript
:(NSString
*)str callback
:(void (^
)(NSString
*))callback
{
228 if (!self.model.connected
)
231 char* encodedString
= malloc(modp_b64_encode_len([str length
]));
232 modp_b64_encode(encodedString
, [str UTF8String
], [str length
]);
233 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
234 NSXMLElement
* parent
= (NSXMLElement
*)[[message rootElement
] childAtIndex
:0];
235 NSString
* value
= [parent base64DecodedValue
];
238 [_client sendCustomCommandWithFormat
:@
"eval -i {txn} -- %s" handler
:handler
, encodedString
];
242 // Protocol Client Delegate ////////////////////////////////////////////////////
243 #pragma mark Protocol Client Delegate
245 - (void)debuggerEngineConnected
:(ProtocolClient
*)client
{
246 [_model onNewConnection
];
250 * Called when the connection is finally closed. This will reopen the listening
251 * socket if the debugger remains attached.
253 - (void)debuggerEngineDisconnected
:(ProtocolClient
*)client
{
254 [_model onDisconnect
];
257 [_client connectOnPort
:_port
];
260 - (void)protocolClient
:(ProtocolClient
*)client receivedInitialMessage
:(NSXMLDocument
*)message
{
261 [self handleInitialResponse
:message
];
264 - (void)protocolClient
:(ProtocolClient
*)client receivedErrorMessage
:(NSXMLDocument
*)message
{
265 NSArray
* error
= [[message rootElement
] elementsForName
:@
"error"];
266 if ([error count
] > 0) {
267 NSLog(@
"Xdebug error: %@", error
);
268 NSString
* errorMessage
= [[[[error objectAtIndex
:0] children
] objectAtIndex
:0] stringValue
];
269 _model.lastError
= errorMessage
;
273 // Specific Response Handlers //////////////////////////////////////////////////
274 #pragma mark Response Handlers
277 * Initial packet received. We've started a brand-new connection to the engine.
279 - (void)handleInitialResponse
:(NSXMLDocument
*)response
{
280 if (!self.autoAttach
) {
281 [_client sendCommandWithFormat
:@
"detach"];
285 // Register any breakpoints that exist offline.
286 for (Breakpoint
* bp
in [[BreakpointManager sharedManager
] breakpoints
])
287 [self addBreakpoint
:bp
];
289 // TODO: update the status.
293 * Receiver for status updates. This just freshens up the UI.
295 - (void)updateStatus
:(NSXMLDocument
*)response
{
296 NSString
* status
= [[[[response rootElement
] attributeForName
:@
"status"] stringValue
] capitalizedString
];
297 self.model.status
= status
;
298 if (!status ||
[status isEqualToString
:@
"Stopped"]) {
299 [_model onDisconnect
];
300 } else if ([status isEqualToString
:@
"Stopping"]) {
301 [_client sendCommandWithFormat
:@
"stop"];
306 * Step in/out/over and run all take this path. We first get the status of the
307 * debugger and then request fresh stack information.
309 - (void)debuggerStep
:(NSXMLDocument
*)response
{
310 [self updateStatus
:response
];
311 if (!self.model.connected
)
314 [_client sendCommandWithFormat
:@
"stack_depth" handler
:^
(NSXMLDocument
* message
) {
315 [self rebuildStack
:message
];
320 * We ask for the stack_depth and now we clobber the stack and start rebuilding
323 - (void)rebuildStack
:(NSXMLDocument
*)response
{
324 NSUInteger depth
= [[[[response rootElement
] attributeForName
:@
"depth"] stringValue
] intValue
];
326 // Send a request to get each frame of the stack, which will be added to this
327 // array. When the final frame arrives, the |tempStack| is released.
328 __block NSMutableArray
* tempStack
= [[NSMutableArray alloc
] init
];
330 for (NSUInteger i
= 0; i
< depth
; ++i
) {
331 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
332 [tempStack addObject
:[self transformXMLToStackFrame
:message
]];
333 if (i
== depth
- 1) {
334 [self.model updateStack
:[tempStack autorelease
]];
337 [_client sendCommandWithFormat
:@
"stack_get -d %d" handler
:handler
, i
];
342 * Creates a StackFrame object from an NSXMLDocument response from the "stack_get"
345 - (StackFrame
*)transformXMLToStackFrame
:(NSXMLDocument
*)response
{
346 NSXMLElement
* xmlframe
= (NSXMLElement
*)[[[response rootElement
] children
] objectAtIndex
:0];
347 StackFrame
* frame
= [[[StackFrame alloc
] init
] autorelease
];
348 frame.index
= [[[xmlframe attributeForName
:@
"level"] stringValue
] intValue
];
349 frame.filename
= [[xmlframe attributeForName
:@
"filename"] stringValue
];
350 frame.lineNumber
= [[[xmlframe attributeForName
:@
"lineno"] stringValue
] intValue
];
351 frame.function
= [[xmlframe attributeForName
:@
"where"] stringValue
];
356 * Enumerates all the contexts of a given stack frame. We then in turn get the
357 * contents of each one of these contexts.
359 - (void)loadContexts
:(NSXMLDocument
*)response forFrame
:(StackFrame
*)frame
{
360 NSXMLElement
* contextNames
= [response rootElement
];
361 for (NSXMLElement
* context
in [contextNames children
]) {
362 NSInteger cid
= [[[context attributeForName
:@
"id"] stringValue
] intValue
];
364 // Fetch each context's variables.
365 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
366 NSMutableArray
* variables
= [NSMutableArray array
];
368 // Merge the frame's existing variables.
370 [variables addObjectsFromArray
:frame.variables
];
372 // Add these new variables.
373 NSArray
* addVariables
= [[message rootElement
] children
];
375 for (NSXMLElement
* elm
in addVariables
) {
376 VariableNode
* node
= [[VariableNode alloc
] initWithXMLNode
:elm
];
377 [variables addObject
:[node autorelease
]];
381 frame.variables
= variables
;
383 [_client sendCommandWithFormat
:@
"context_get -d %d -c %d" handler
:handler
, frame.index
, cid
];