Do not double-percent-escape the filename.
[macgdbp.git] / Source / DebuggerBackEnd.m
1 /*
2 * MacGDBp
3 * Copyright (c) 2007 - 2011, Blue Static <http://www.bluestatic.org>
4 *
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.
8 *
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.
12 *
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
15 */
16
17 #import "DebuggerBackEnd.h"
18
19 #import "AppDelegate.h"
20 #import "modp_b64.h"
21 #import "NSXMLElementAdditions.h"
22
23 // GDBpConnection (Private) ////////////////////////////////////////////////////
24
25 @interface DebuggerBackEnd ()
26 @property (readwrite, copy) NSString* status;
27
28 - (void)recordCallback:(SEL)callback forTransaction:(NSNumber*)txn;
29
30 - (void)updateStatus:(NSXMLDocument*)response;
31 - (void)debuggerStep:(NSXMLDocument*)response;
32 - (void)rebuildStack:(NSXMLDocument*)response;
33 - (void)getStackFrame:(NSXMLDocument*)response;
34 - (void)setSource:(NSXMLDocument*)response;
35 - (void)contextsReceived:(NSXMLDocument*)response;
36 - (void)variablesReceived:(NSXMLDocument*)response;
37 - (void)propertiesReceived:(NSXMLDocument*)response;
38 - (void)evalScriptReceived:(NSXMLDocument*)response;
39
40 @end
41
42 // GDBpConnection //////////////////////////////////////////////////////////////
43
44 @implementation DebuggerBackEnd
45
46 @synthesize status;
47 @synthesize attached = attached_;
48 @synthesize delegate;
49
50 /**
51 * Creates a new DebuggerBackEnd and initializes the socket from the given connection
52 * paramters.
53 */
54 - (id)initWithPort:(NSUInteger)aPort
55 {
56 if (self = [super init])
57 {
58 stackFrames_ = [[NSMutableDictionary alloc] init];
59 callbackContext_ = [NSMutableDictionary new];
60 callTable_ = [NSMutableDictionary new];
61
62 [[BreakpointManager sharedManager] setConnection:self];
63 port_ = aPort;
64 client_ = [[ProtocolClient alloc] initWithDelegate:self];
65
66 attached_ = [[NSUserDefaults standardUserDefaults] boolForKey:@"DebuggerAttached"];
67
68 if (self.attached)
69 [client_ connectOnPort:port_];
70 }
71 return self;
72 }
73
74 /**
75 * Deallocates the object
76 */
77 - (void)dealloc
78 {
79 [client_ release];
80 [stackFrames_ release];
81 [callTable_ release];
82 [callbackContext_ release];
83 [super dealloc];
84 }
85
86
87 // Getters /////////////////////////////////////////////////////////////////////
88 #pragma mark Getters
89
90 /**
91 * Gets the port number
92 */
93 - (NSUInteger)port
94 {
95 return port_;
96 }
97
98 /**
99 * Returns whether or not we have an active connection
100 */
101 - (BOOL)isConnected
102 {
103 return active_;
104 }
105
106 /**
107 * Sets the attached state of the debugger. This will open and close the
108 * connection as appropriate.
109 */
110 - (void)setAttached:(BOOL)attached {
111 if (attached != attached_) {
112 if (!attached)
113 [client_ connectOnPort:port_];
114 else
115 [client_ disconnect];
116 }
117 attached_ = attached;
118 }
119
120 // Commands ////////////////////////////////////////////////////////////////////
121 #pragma mark Commands
122
123 /**
124 * Tells the debugger to continue running the script. Returns the current stack frame.
125 */
126 - (void)run
127 {
128 NSNumber* tx = [client_ sendCommandWithFormat:@"run"];
129 [self recordCallback:@selector(debuggerStep:) forTransaction:tx];
130 }
131
132 /**
133 * Tells the debugger to step into the current command.
134 */
135 - (void)stepIn
136 {
137 NSNumber* tx = [client_ sendCommandWithFormat:@"step_into"];
138 [self recordCallback:@selector(debuggerStep:) forTransaction:tx];
139 }
140
141 /**
142 * Tells the debugger to step out of the current context
143 */
144 - (void)stepOut
145 {
146 NSNumber* tx = [client_ sendCommandWithFormat:@"step_out"];
147 [self recordCallback:@selector(debuggerStep:) forTransaction:tx];
148 }
149
150 /**
151 * Tells the debugger to step over the current function
152 */
153 - (void)stepOver
154 {
155 NSNumber* tx = [client_ sendCommandWithFormat:@"step_over"];
156 [self recordCallback:@selector(debuggerStep:) forTransaction:tx];
157 }
158
159 /**
160 * Halts execution of the script.
161 */
162 - (void)stop
163 {
164 [client_ disconnect];
165 active_ = NO;
166 self.status = @"Stopped";
167 }
168
169 /**
170 * Ends the current debugging session.
171 */
172 - (void)detach
173 {
174 [client_ sendCommandWithFormat:@"detach"];
175 active_ = NO;
176 self.status = @"Stopped";
177 }
178
179 /**
180 * Tells the debugger engine to get a specifc property. This also takes in the NSXMLElement
181 * that requested it so that the child can be attached.
182 */
183 - (NSInteger)getChildrenOfProperty:(VariableNode*)property atDepth:(NSInteger)depth;
184 {
185 NSNumber* tx = [client_ sendCommandWithFormat:@"property_get -d %d -n %@", depth, [property fullName]];
186 [self recordCallback:@selector(propertiesReceived:) forTransaction:tx];
187 return [tx intValue];
188 }
189
190 - (void)loadStackFrame:(StackFrame*)frame
191 {
192 if (frame.loaded)
193 return;
194
195 NSNumber* routingNumber = [NSNumber numberWithInt:frame.routingID];
196 NSNumber* transaction = nil;
197
198 // Get the source code of the file. Escape % in URL chars.
199 if ([frame.filename length]) {
200 transaction = [client_ sendCommandWithFormat:@"source -f %@", frame.filename];
201 [self recordCallback:@selector(setSource:) forTransaction:transaction];
202 [callbackContext_ setObject:routingNumber forKey:transaction];
203 }
204
205 // Get the names of all the contexts.
206 transaction = [client_ sendCommandWithFormat:@"context_names -d %d", frame.index];
207 [self recordCallback:@selector(contextsReceived:) forTransaction:transaction];
208 [callbackContext_ setObject:routingNumber forKey:transaction];
209
210 // This frame will be fully loaded.
211 frame.loaded = YES;
212 }
213
214 // Breakpoint Management ///////////////////////////////////////////////////////
215 #pragma mark Breakpoints
216
217 /**
218 * Send an add breakpoint command
219 */
220 - (void)addBreakpoint:(Breakpoint*)bp
221 {
222 if (!active_)
223 return;
224
225 NSString* file = [ProtocolClient escapedFilePathURI:[bp transformedPath]];
226 NSNumber* tx = [client_ sendCommandWithFormat:@"breakpoint_set -t line -f %@ -n %i", file, [bp line]];
227 [self recordCallback:@selector(breakpointReceived:) forTransaction:tx];
228 [callbackContext_ setObject:bp forKey:tx];
229 }
230
231 /**
232 * Removes a breakpoint
233 */
234 - (void)removeBreakpoint:(Breakpoint*)bp
235 {
236 if (!active_)
237 return;
238
239 [client_ sendCommandWithFormat:@"breakpoint_remove -d %i", [bp debuggerId]];
240 }
241
242 /**
243 * Sends a string to be evaluated by the engine.
244 */
245 - (void)evalScript:(NSString*)str
246 {
247 if (!active_)
248 return;
249
250 char* encodedString = malloc(modp_b64_encode_len([str length]));
251 modp_b64_encode(encodedString, [str UTF8String], [str length]);
252 NSNumber* tx = [client_ sendCustomCommandWithFormat:@"eval -i {txn} -- %s", encodedString];
253 free(encodedString);
254
255 [self recordCallback:@selector(evalScriptReceived:) forTransaction:tx];
256 }
257
258 // Protocol Client Delegate ////////////////////////////////////////////////////
259 #pragma mark Protocol Client Delegate
260
261 - (void)debuggerEngineConnected:(ProtocolClient*)client
262 {
263 active_ = YES;
264 }
265
266 /**
267 * Called when the connection is finally closed. This will reopen the listening
268 * socket if the debugger remains attached.
269 */
270 - (void)debuggerEngineDisconnected:(ProtocolClient*)client
271 {
272 active_ = NO;
273
274 if ([delegate respondsToSelector:@selector(debuggerDisconnected)])
275 [delegate debuggerDisconnected];
276
277 if (self.attached)
278 [client_ connectOnPort:port_];
279 }
280
281 - (void)debuggerEngine:(ProtocolClient*)client receivedMessage:(NSXMLDocument*)message
282 {
283 // Check and see if there's an error.
284 NSArray* error = [[message rootElement] elementsForName:@"error"];
285 if ([error count] > 0) {
286 NSLog(@"Xdebug error: %@", error);
287 NSString* errorMessage = [[[[error objectAtIndex:0] children] objectAtIndex:0] stringValue];
288 [self errorEncountered:errorMessage];
289 }
290
291 if ([[[message rootElement] name] isEqualToString:@"init"]) {
292 [self handleInitialResponse:message];
293 return;
294 }
295
296 [self handleResponse:message];
297 }
298
299 // Specific Response Handlers //////////////////////////////////////////////////
300 #pragma mark Response Handlers
301
302 - (void)errorEncountered:(NSString*)error
303 {
304 [delegate errorEncountered:error];
305 }
306
307 /**
308 * Initial packet received. We've started a brand-new connection to the engine.
309 */
310 - (void)handleInitialResponse:(NSXMLDocument*)response
311 {
312 if (!self.attached) {
313 [client_ sendCommandWithFormat:@"detach"];
314 return;
315 }
316
317 active_ = YES;
318
319 // Register any breakpoints that exist offline.
320 for (Breakpoint* bp in [[BreakpointManager sharedManager] breakpoints])
321 [self addBreakpoint:bp];
322
323 // Load the debugger to make it look active.
324 [delegate debuggerConnected];
325
326 // TODO: update the status.
327 }
328
329 - (void)handleResponse:(NSXMLDocument*)response
330 {
331 NSInteger transactionID = [client_ transactionIDFromResponse:response];
332 NSNumber* key = [NSNumber numberWithInt:transactionID];
333 NSString* callbackStr = [callTable_ objectForKey:key];
334 if (callbackStr)
335 {
336 SEL callback = NSSelectorFromString(callbackStr);
337 [self performSelector:callback withObject:response];
338 }
339 [callTable_ removeObjectForKey:key];
340 }
341
342 /**
343 * Receiver for status updates. This just freshens up the UI.
344 */
345 - (void)updateStatus:(NSXMLDocument*)response
346 {
347 self.status = [[[[response rootElement] attributeForName:@"status"] stringValue] capitalizedString];
348 active_ = YES;
349 if (!status || [status isEqualToString:@"Stopped"]) {
350 [delegate debuggerDisconnected];
351 active_ = NO;
352 } else if ([status isEqualToString:@"Stopping"]) {
353 [client_ sendCommandWithFormat:@"stop"];
354 active_ = NO;
355 }
356 }
357
358 /**
359 * Step in/out/over and run all take this path. We first get the status of the
360 * debugger and then request fresh stack information.
361 */
362 - (void)debuggerStep:(NSXMLDocument*)response
363 {
364 [self updateStatus:response];
365 if (![self isConnected])
366 return;
367
368 // If this is the run command, tell the delegate that a bunch of updates
369 // are coming. Also remove all existing stack routes and request a new stack.
370 if ([delegate respondsToSelector:@selector(clobberStack)])
371 [delegate clobberStack];
372 [stackFrames_ removeAllObjects];
373 NSNumber* tx = [client_ sendCommandWithFormat:@"stack_depth"];
374 [self recordCallback:@selector(rebuildStack:) forTransaction:tx];
375 stackFirstTransactionID_ = [tx intValue];
376 }
377
378 /**
379 * We ask for the stack_depth and now we clobber the stack and start rebuilding
380 * it.
381 */
382 - (void)rebuildStack:(NSXMLDocument*)response
383 {
384 NSInteger depth = [[[[response rootElement] attributeForName:@"depth"] stringValue] intValue];
385
386 if (stackFirstTransactionID_ == [client_ transactionIDFromResponse:response])
387 stackDepth_ = depth;
388
389 // We now need to alloc a bunch of stack frames and get the basic information
390 // for them.
391 for (NSInteger i = 0; i < depth; i++)
392 {
393 // Use the transaction ID to create a routing path.
394 NSNumber* routingID = [client_ sendCommandWithFormat:@"stack_get -d %d", i];
395 [self recordCallback:@selector(getStackFrame:) forTransaction:routingID];
396 [stackFrames_ setObject:[[StackFrame new] autorelease] forKey:routingID];
397 }
398 }
399
400 /**
401 * The initial rebuild of the stack frame. We now have enough to initialize
402 * a StackFrame object.
403 */
404 - (void)getStackFrame:(NSXMLDocument*)response
405 {
406 // Get the routing information.
407 NSInteger routingID = [client_ transactionIDFromResponse:response];
408 if (routingID < stackFirstTransactionID_)
409 return;
410 NSNumber* routingNumber = [NSNumber numberWithInt:routingID];
411
412 // Make sure we initialized this frame in our last |-rebuildStack:|.
413 StackFrame* frame = [stackFrames_ objectForKey:routingNumber];
414 if (!frame)
415 return;
416
417 NSXMLElement* xmlframe = [[[response rootElement] children] objectAtIndex:0];
418
419 // Initialize the stack frame.
420 frame.index = [[[xmlframe attributeForName:@"level"] stringValue] intValue];
421 frame.filename = [[xmlframe attributeForName:@"filename"] stringValue];
422 frame.lineNumber = [[[xmlframe attributeForName:@"lineno"] stringValue] intValue];
423 frame.function = [[xmlframe attributeForName:@"where"] stringValue];
424 frame.routingID = routingID;
425
426 // Only get the complete frame for the first level. The other frames will get
427 // information loaded lazily when the user clicks on one.
428 if (frame.index == 0) {
429 [self loadStackFrame:frame];
430 }
431
432 if ([delegate respondsToSelector:@selector(newStackFrame:)])
433 [delegate newStackFrame:frame];
434 }
435
436 /**
437 * Callback for setting the source of a file while rebuilding a specific stack
438 * frame.
439 */
440 - (void)setSource:(NSXMLDocument*)response
441 {
442 NSNumber* transaction = [NSNumber numberWithInt:[client_ transactionIDFromResponse:response]];
443 if ([transaction intValue] < stackFirstTransactionID_)
444 return;
445 NSNumber* routingNumber = [callbackContext_ objectForKey:transaction];
446 if (!routingNumber)
447 return;
448
449 [callbackContext_ removeObjectForKey:transaction];
450 StackFrame* frame = [stackFrames_ objectForKey:routingNumber];
451 if (!frame)
452 return;
453
454 frame.source = [[response rootElement] base64DecodedValue];
455
456 if ([delegate respondsToSelector:@selector(sourceUpdated:)])
457 [delegate sourceUpdated:frame];
458 }
459
460 /**
461 * Enumerates all the contexts of a given stack frame. We then in turn get the
462 * contents of each one of these contexts.
463 */
464 - (void)contextsReceived:(NSXMLDocument*)response
465 {
466 // Get the stack frame's routing ID and use it again.
467 NSNumber* receivedTransaction = [NSNumber numberWithInt:[client_ transactionIDFromResponse:response]];
468 if ([receivedTransaction intValue] < stackFirstTransactionID_)
469 return;
470 NSNumber* routingID = [callbackContext_ objectForKey:receivedTransaction];
471 if (!routingID)
472 return;
473
474 // Get the stack frame by the |routingID|.
475 StackFrame* frame = [stackFrames_ objectForKey:routingID];
476
477 NSXMLElement* contextNames = [response rootElement];
478 for (NSXMLElement* context in [contextNames children])
479 {
480 NSInteger cid = [[[context attributeForName:@"id"] stringValue] intValue];
481
482 // Fetch each context's variables.
483 NSNumber* tx = [client_ sendCommandWithFormat:@"context_get -d %d -c %d", frame.index, cid];
484 [self recordCallback:@selector(variablesReceived:) forTransaction:tx];
485 [callbackContext_ setObject:routingID forKey:tx];
486 }
487 }
488
489 /**
490 * Receives the variables from the context and attaches them to the stack frame.
491 */
492 - (void)variablesReceived:(NSXMLDocument*)response
493 {
494 // Get the stack frame's routing ID and use it again.
495 NSInteger transaction = [client_ transactionIDFromResponse:response];
496 if (transaction < stackFirstTransactionID_)
497 return;
498 NSNumber* receivedTransaction = [NSNumber numberWithInt:transaction];
499 NSNumber* routingID = [callbackContext_ objectForKey:receivedTransaction];
500 if (!routingID)
501 return;
502
503 // Get the stack frame by the |routingID|.
504 StackFrame* frame = [stackFrames_ objectForKey:routingID];
505
506 NSMutableArray* variables = [NSMutableArray array];
507
508 // Merge the frame's existing variables.
509 if (frame.variables)
510 [variables addObjectsFromArray:frame.variables];
511
512 // Add these new variables.
513 NSArray* addVariables = [[response rootElement] children];
514 if (addVariables) {
515 for (NSXMLElement* elm in addVariables) {
516 VariableNode* node = [[VariableNode alloc] initWithXMLNode:elm];
517 [variables addObject:[node autorelease]];
518 }
519 }
520
521 frame.variables = variables;
522 }
523
524 /**
525 * Callback from a |-getProperty:| request.
526 */
527 - (void)propertiesReceived:(NSXMLDocument*)response
528 {
529 NSInteger transaction = [client_ transactionIDFromResponse:response];
530
531 /*
532 <response>
533 <property> <!-- this is the one we requested -->
534 <property ... /> <!-- these are what we want -->
535 </property>
536 </repsonse>
537 */
538
539 // Detach all the children so we can insert them into another document.
540 NSXMLElement* parent = (NSXMLElement*)[[response rootElement] childAtIndex:0];
541 NSArray* children = [parent children];
542 [parent setChildren:nil];
543
544 [delegate receivedProperties:children forTransaction:transaction];
545 }
546
547 /**
548 * Callback from a |-evalScript:| request.
549 */
550 - (void)evalScriptReceived:(NSXMLDocument*)response
551 {
552 NSXMLElement* parent = (NSXMLElement*)[[response rootElement] childAtIndex:0];
553 NSString* value = [parent base64DecodedValue];
554 [delegate scriptWasEvaluatedWithResult:value];
555 }
556
557 /**
558 * Callback for setting a breakpoint.
559 */
560 - (void)breakpointReceived:(NSXMLDocument*)response
561 {
562 NSNumber* transaction = [NSNumber numberWithInt:[client_ transactionIDFromResponse:response]];
563 Breakpoint* bp = [callbackContext_ objectForKey:transaction];
564 if (!bp)
565 return;
566
567 [callbackContext_ removeObjectForKey:callbackContext_];
568 [bp setDebuggerId:[[[[response rootElement] attributeForName:@"id"] stringValue] intValue]];
569 }
570
571 // Private /////////////////////////////////////////////////////////////////////
572
573 - (void)recordCallback:(SEL)callback forTransaction:(NSNumber*)txn
574 {
575 [callTable_ setObject:NSStringFromSelector(callback) forKey:txn];
576 }
577
578 @end