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 "Breakpoint.h"
21 #import "DebuggerModel.h"
23 #import "NSXMLElementAdditions.h"
24 #import "StackFrame.h"
26 @implementation DebuggerBackEnd
{
27 // The connection to the debugger engine.
29 ProtocolClient
* _client
;
32 - (instancetype
)initWithPort
:(NSUInteger
)aPort autoAttach
:(BOOL)doAttach
34 if (self = [super init
]) {
35 [[BreakpointManager sharedManager
] setConnection
:self];
37 _client
= [[ProtocolClient alloc
] initWithDelegate
:self];
39 _autoAttach
= doAttach
;
41 [_client connectOnPort
:_port
];
51 // Getters /////////////////////////////////////////////////////////////////////
55 * Gets the port number
62 * Sets the attached state of the debugger. This will open and close the
63 * connection as appropriate.
65 - (void)setAutoAttach
:(BOOL)flag
{
66 if (flag
== _autoAttach
)
72 [_client connectOnPort
:_port
];
77 // Commands ////////////////////////////////////////////////////////////////////
81 * Tells the debugger to continue running the script. Returns the current stack frame.
84 [_client sendCommandWithFormat
:@
"run" handler
:^
(NSXMLDocument
* message
) {
85 [self debuggerStep
:message
];
90 * Tells the debugger to step into the current command.
93 [_client sendCommandWithFormat
:@
"step_into" handler
:^
(NSXMLDocument
* message
) {
94 [self debuggerStep
:message
];
99 * Tells the debugger to step out of the current context
102 [_client sendCommandWithFormat
:@
"step_out" handler
:^
(NSXMLDocument
* message
) {
103 [self debuggerStep
:message
];
108 * Tells the debugger to step over the current function
111 [_client sendCommandWithFormat
:@
"step_over" handler
:^
(NSXMLDocument
* message
) {
112 [self debuggerStep
:message
];
117 * Halts execution of the script.
120 [_client disconnect
];
121 self.model.status
= @
"Stopped";
125 * Ends the current debugging session.
128 [_client sendCommandWithFormat
:@
"detach"];
129 self.model.status
= @
"Stopped";
132 - (void)loadStackFrame
:(StackFrame
*)frame
{
136 // Get the source code of the file. Escape % in URL chars.
137 if ([frame.filename length
]) {
138 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
139 frame.source
= [[message rootElement
] base64DecodedValue
];
141 [_client sendCommandWithFormat
:@
"source -f %@" handler
:handler
, frame.filename
];
144 // Get the names of all the contexts.
145 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
146 [self loadContexts
:message forFrame
:frame
];
148 [_client sendCommandWithFormat
:@
"context_names -d %d" handler
:handler
, frame.index
];
150 // This frame will be fully loaded.
154 - (void)loadVariableNode
:(VariableNode
*)variable
155 forStackFrame
:(StackFrame
*)frame
{
156 if (variable.children.count
== variable.childCount
)
159 [self loadVariableNode
:variable forStackFrame
:frame dataPage
:0 loadedData
:@
[]];
162 - (void)loadVariableNode
:(VariableNode
*)variable
163 forStackFrame
:(StackFrame
*)frame
164 dataPage
:(unsigned int)dataPage
165 loadedData
:(NSArray
*)loadedData
{
166 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
169 <property> <!-- this is the one we requested -->
170 <property ... /> <!-- these are what we want -->
175 // Detach all the children so we can insert them into another document.
176 NSXMLElement
* parent
= (NSXMLElement
*)[[message rootElement
] childAtIndex
:0];
177 NSArray
* children
= [parent children
];
178 [parent setChildren
:nil];
180 // Check to see if there are more children to load.
181 NSArray
* newLoadedData
= [loadedData arrayByAddingObjectsFromArray
:children
];
183 unsigned int totalChildren
= [[[parent attributeForName
:@
"numchildren"] stringValue
] integerValue
];
184 if ([newLoadedData count
] < totalChildren
) {
185 [self loadVariableNode
:variable
187 dataPage
:dataPage
+ 1
188 loadedData
:newLoadedData
];
190 [variable setChildrenFromXMLChildren
:newLoadedData
];
193 [_client sendCommandWithFormat
:@
"property_get -d %d -n %@ -p %u" handler
:handler
, frame.index
, variable.fullName
, dataPage
];
196 // Breakpoint Management ///////////////////////////////////////////////////////
197 #pragma mark Breakpoints
200 * Send an add breakpoint command
202 - (void)addBreakpoint
:(Breakpoint
*)bp
{
203 if (!self.model.connected
)
206 NSString
* file
= [ProtocolClient escapedFilePathURI
:[bp transformedPath
]];
207 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
208 [bp setDebuggerId
:[[[[message rootElement
] attributeForName
:@
"id"] stringValue
] intValue
]];
210 [_client sendCommandWithFormat
:@
"breakpoint_set -t line -f %@ -n %i" handler
:handler
, file
, [bp line
]];
214 * Removes a breakpoint
216 - (void)removeBreakpoint
:(Breakpoint
*)bp
{
217 if (!self.model.connected
)
220 [_client sendCommandWithFormat
:@
"breakpoint_remove -d %i", [bp debuggerId
]];
224 * Sends a string to be evaluated by the engine.
226 - (void)evalScript
:(NSString
*)str callback
:(void (^
)(NSString
*))callback
{
227 if (!self.model.connected
)
230 char* encodedString
= malloc(modp_b64_encode_len([str length
]));
231 modp_b64_encode(encodedString
, [str UTF8String
], [str length
]);
232 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
233 NSXMLElement
* parent
= (NSXMLElement
*)[[message rootElement
] childAtIndex
:0];
234 NSString
* value
= [parent base64DecodedValue
];
237 [_client sendCustomCommandWithFormat
:@
"eval -i {txn} -- %s" handler
:handler
, encodedString
];
241 // Protocol Client Delegate ////////////////////////////////////////////////////
242 #pragma mark Protocol Client Delegate
244 - (void)debuggerEngineConnected
:(ProtocolClient
*)client
{
245 [_model onNewConnection
];
249 * Called when the connection is finally closed. This will reopen the listening
250 * socket if the debugger remains attached.
252 - (void)debuggerEngineDisconnected
:(ProtocolClient
*)client
{
253 [_model onDisconnect
];
256 [_client connectOnPort
:_port
];
259 - (void)protocolClient
:(ProtocolClient
*)client receivedInitialMessage
:(NSXMLDocument
*)message
{
260 [self handleInitialResponse
:message
];
263 - (void)protocolClient
:(ProtocolClient
*)client receivedErrorMessage
:(NSXMLDocument
*)message
{
264 NSArray
* error
= [[message rootElement
] elementsForName
:@
"error"];
265 if ([error count
] > 0) {
266 NSLog(@
"Xdebug error: %@", error
);
267 NSString
* errorMessage
= [[[[error objectAtIndex
:0] children
] objectAtIndex
:0] stringValue
];
268 _model.lastError
= errorMessage
;
272 // Specific Response Handlers //////////////////////////////////////////////////
273 #pragma mark Response Handlers
276 * Initial packet received. We've started a brand-new connection to the engine.
278 - (void)handleInitialResponse
:(NSXMLDocument
*)response
{
279 if (!self.autoAttach
) {
280 [_client sendCommandWithFormat
:@
"detach"];
284 // Register any breakpoints that exist offline.
285 for (Breakpoint
* bp
in [[BreakpointManager sharedManager
] breakpoints
])
286 [self addBreakpoint
:bp
];
288 // TODO: update the status.
292 * Receiver for status updates. This just freshens up the UI.
294 - (void)updateStatus
:(NSXMLDocument
*)response
{
295 NSString
* status
= [[[[response rootElement
] attributeForName
:@
"status"] stringValue
] capitalizedString
];
296 self.model.status
= status
;
297 if (!status ||
[status isEqualToString
:@
"Stopped"]) {
298 [_model onDisconnect
];
299 } else if ([status isEqualToString
:@
"Stopping"]) {
300 [_client sendCommandWithFormat
:@
"stop"];
305 * Step in/out/over and run all take this path. We first get the status of the
306 * debugger and then request fresh stack information.
308 - (void)debuggerStep
:(NSXMLDocument
*)response
{
309 [self updateStatus
:response
];
310 if (!self.model.connected
)
313 [_client sendCommandWithFormat
:@
"stack_depth" handler
:^
(NSXMLDocument
* message
) {
314 [self rebuildStack
:message
];
319 * We ask for the stack_depth and now we clobber the stack and start rebuilding
322 - (void)rebuildStack
:(NSXMLDocument
*)response
{
323 NSUInteger depth
= [[[[response rootElement
] attributeForName
:@
"depth"] stringValue
] intValue
];
325 // Send a request to get each frame of the stack, which will be added to this
326 // array. When the final frame arrives, the |tempStack| is released.
327 __block NSMutableArray
* tempStack
= [[NSMutableArray alloc
] init
];
329 for (NSUInteger i
= 0; i
< depth
; ++i
) {
330 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
331 [tempStack addObject
:[self transformXMLToStackFrame
:message
]];
332 if (i
== depth
- 1) {
333 [self.model updateStack
:[tempStack autorelease
]];
336 [_client sendCommandWithFormat
:@
"stack_get -d %d" handler
:handler
, i
];
341 * Creates a StackFrame object from an NSXMLDocument response from the "stack_get"
344 - (StackFrame
*)transformXMLToStackFrame
:(NSXMLDocument
*)response
{
345 NSXMLElement
* xmlframe
= (NSXMLElement
*)[[[response rootElement
] children
] objectAtIndex
:0];
346 StackFrame
* frame
= [[[StackFrame alloc
] init
] autorelease
];
347 frame.index
= [[[xmlframe attributeForName
:@
"level"] stringValue
] intValue
];
348 frame.filename
= [[xmlframe attributeForName
:@
"filename"] stringValue
];
349 frame.lineNumber
= [[[xmlframe attributeForName
:@
"lineno"] stringValue
] intValue
];
350 frame.function
= [[xmlframe attributeForName
:@
"where"] stringValue
];
355 * Enumerates all the contexts of a given stack frame. We then in turn get the
356 * contents of each one of these contexts.
358 - (void)loadContexts
:(NSXMLDocument
*)response forFrame
:(StackFrame
*)frame
{
359 NSXMLElement
* contextNames
= [response rootElement
];
360 for (NSXMLElement
* context
in [contextNames children
]) {
361 NSInteger cid
= [[[context attributeForName
:@
"id"] stringValue
] intValue
];
363 // Fetch each context's variables.
364 ProtocolClientMessageHandler handler
= ^
(NSXMLDocument
* message
) {
365 NSMutableArray
* variables
= [NSMutableArray array
];
367 // Merge the frame's existing variables.
369 [variables addObjectsFromArray
:frame.variables
];
371 // Add these new variables.
372 NSArray
* addVariables
= [[message rootElement
] children
];
374 for (NSXMLElement
* elm
in addVariables
) {
375 VariableNode
* node
= [[VariableNode alloc
] initWithXMLNode
:elm
];
376 [variables addObject
:[node autorelease
]];
380 frame.variables
= variables
;
382 [_client sendCommandWithFormat
:@
"context_get -d %d -c %d" handler
:handler
, frame.index
, cid
];