Get the base64-decoded value of the when showing evaluated script responses
[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 connection_ = [[NetworkConnection alloc] initWithPort:aPort];
64 connection_.delegate = self;
65
66 attached_ = [[NSUserDefaults standardUserDefaults] boolForKey:@"DebuggerAttached"];
67
68 if (self.attached)
69 [connection_ connect];
70 }
71 return self;
72 }
73
74 /**
75 * Deallocates the object
76 */
77 - (void)dealloc
78 {
79 [connection_ close];
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 [connection_ port];
96 }
97
98 /**
99 * Returns whether or not we have an active connection
100 */
101 - (BOOL)isConnected
102 {
103 return [connection_ connected] && 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 [connection_ close];
114 else
115 [connection_ connect];
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 = [connection_ 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 = [connection_ 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 = [connection_ 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 = [connection_ 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 [connection_ close];
165 active_ = NO;
166 self.status = @"Stopped";
167 if ([delegate respondsToSelector:@selector(debuggerDisconnected)])
168 [delegate debuggerDisconnected];
169 }
170
171 /**
172 * Ends the current debugging session.
173 */
174 - (void)detach
175 {
176 [connection_ sendCommandWithFormat:@"detach"];
177 active_ = NO;
178 self.status = @"Stopped";
179 if ([delegate respondsToSelector:@selector(debuggerDisconnected)])
180 [delegate debuggerDisconnected];
181 }
182
183 /**
184 * Tells the debugger engine to get a specifc property. This also takes in the NSXMLElement
185 * that requested it so that the child can be attached.
186 */
187 - (NSInteger)getChildrenOfProperty:(VariableNode*)property atDepth:(NSInteger)depth;
188 {
189 NSNumber* tx = [connection_ sendCommandWithFormat:@"property_get -d %d -n %@", depth, [property fullName]];
190 [self recordCallback:@selector(propertiesReceived:) forTransaction:tx];
191 return [tx intValue];
192 }
193
194 - (void)loadStackFrame:(StackFrame*)frame
195 {
196 if (frame.loaded)
197 return;
198
199 NSNumber* routingNumber = [NSNumber numberWithInt:frame.routingID];
200 NSNumber* transaction = nil;
201
202 // Get the source code of the file. Escape % in URL chars.
203 if ([frame.filename length]) {
204 NSString* escapedFilename = [frame.filename stringByReplacingOccurrencesOfString:@"%" withString:@"%%"];
205 transaction = [connection_ sendCommandWithFormat:@"source -f %@", escapedFilename];
206 [self recordCallback:@selector(setSource:) forTransaction:transaction];
207 [callbackContext_ setObject:routingNumber forKey:transaction];
208 }
209
210 // Get the names of all the contexts.
211 transaction = [connection_ sendCommandWithFormat:@"context_names -d %d", frame.index];
212 [self recordCallback:@selector(contextsReceived:) forTransaction:transaction];
213 [callbackContext_ setObject:routingNumber forKey:transaction];
214
215 // This frame will be fully loaded.
216 frame.loaded = YES;
217 }
218
219 // Breakpoint Management ///////////////////////////////////////////////////////
220 #pragma mark Breakpoints
221
222 /**
223 * Send an add breakpoint command
224 */
225 - (void)addBreakpoint:(Breakpoint*)bp
226 {
227 if (![connection_ connected])
228 return;
229
230 NSString* file = [connection_ escapedURIPath:[bp transformedPath]];
231 NSNumber* tx = [connection_ sendCommandWithFormat:@"breakpoint_set -t line -f %@ -n %i", file, [bp line]];
232 [self recordCallback:@selector(breakpointReceived:) forTransaction:tx];
233 [callbackContext_ setObject:bp forKey:tx];
234 }
235
236 /**
237 * Removes a breakpoint
238 */
239 - (void)removeBreakpoint:(Breakpoint*)bp
240 {
241 if (![connection_ connected])
242 return;
243
244 [connection_ sendCommandWithFormat:@"breakpoint_remove -d %i", [bp debuggerId]];
245 }
246
247 /**
248 * Sends a string to be evaluated by the engine.
249 */
250 - (void)evalScript:(NSString*)str
251 {
252 if (![connection_ connected])
253 return;
254
255 char* encodedString = malloc(modp_b64_encode_len([str length]));
256 modp_b64_encode(encodedString, [str UTF8String], [str length]);
257 NSNumber* tx = [connection_ sendCustomCommandWithFormat:@"eval -i {txn} -- %s", encodedString];
258 free(encodedString);
259
260 [self recordCallback:@selector(evalScriptReceived:) forTransaction:tx];
261 }
262
263 // Specific Response Handlers //////////////////////////////////////////////////
264 #pragma mark Response Handlers
265
266 - (void)errorEncountered:(NSString*)error
267 {
268 [delegate errorEncountered:error];
269 }
270
271 /**
272 * Initial packet received. We've started a brand-new connection to the engine.
273 */
274 - (void)handleInitialResponse:(NSXMLDocument*)response
275 {
276 if (!self.attached) {
277 [connection_ sendCommandWithFormat:@"detach"];
278 return;
279 }
280
281 active_ = YES;
282
283 // Register any breakpoints that exist offline.
284 for (Breakpoint* bp in [[BreakpointManager sharedManager] breakpoints])
285 [self addBreakpoint:bp];
286
287 // Load the debugger to make it look active.
288 [delegate debuggerConnected];
289
290 // TODO: update the status.
291 }
292
293 - (void)handleResponse:(NSXMLDocument*)response
294 {
295 NSInteger transactionID = [connection_ transactionIDFromResponse:response];
296 NSNumber* key = [NSNumber numberWithInt:transactionID];
297 NSString* callbackStr = [callTable_ objectForKey:key];
298 if (callbackStr)
299 {
300 SEL callback = NSSelectorFromString(callbackStr);
301 [self performSelector:callback withObject:response];
302 }
303 [callTable_ removeObjectForKey:key];
304 }
305
306 /**
307 * Receiver for status updates. This just freshens up the UI.
308 */
309 - (void)updateStatus:(NSXMLDocument*)response
310 {
311 self.status = [[[[response rootElement] attributeForName:@"status"] stringValue] capitalizedString];
312 active_ = YES;
313 if (!status || [status isEqualToString:@"Stopped"]) {
314 [delegate debuggerDisconnected];
315 active_ = NO;
316 } else if ([status isEqualToString:@"Stopping"]) {
317 [connection_ sendCommandWithFormat:@"stop"];
318 active_ = NO;
319 }
320 }
321
322 /**
323 * Step in/out/over and run all take this path. We first get the status of the
324 * debugger and then request fresh stack information.
325 */
326 - (void)debuggerStep:(NSXMLDocument*)response
327 {
328 [self updateStatus:response];
329 if (![self isConnected])
330 return;
331
332 // If this is the run command, tell the delegate that a bunch of updates
333 // are coming. Also remove all existing stack routes and request a new stack.
334 if ([delegate respondsToSelector:@selector(clobberStack)])
335 [delegate clobberStack];
336 [stackFrames_ removeAllObjects];
337 NSNumber* tx = [connection_ sendCommandWithFormat:@"stack_depth"];
338 [self recordCallback:@selector(rebuildStack:) forTransaction:tx];
339 stackFirstTransactionID_ = [tx intValue];
340 }
341
342 /**
343 * We ask for the stack_depth and now we clobber the stack and start rebuilding
344 * it.
345 */
346 - (void)rebuildStack:(NSXMLDocument*)response
347 {
348 NSInteger depth = [[[[response rootElement] attributeForName:@"depth"] stringValue] intValue];
349
350 if (stackFirstTransactionID_ == [connection_ transactionIDFromResponse:response])
351 stackDepth_ = depth;
352
353 // We now need to alloc a bunch of stack frames and get the basic information
354 // for them.
355 for (NSInteger i = 0; i < depth; i++)
356 {
357 // Use the transaction ID to create a routing path.
358 NSNumber* routingID = [connection_ sendCommandWithFormat:@"stack_get -d %d", i];
359 [self recordCallback:@selector(getStackFrame:) forTransaction:routingID];
360 [stackFrames_ setObject:[[StackFrame new] autorelease] forKey:routingID];
361 }
362 }
363
364 /**
365 * The initial rebuild of the stack frame. We now have enough to initialize
366 * a StackFrame object.
367 */
368 - (void)getStackFrame:(NSXMLDocument*)response
369 {
370 // Get the routing information.
371 NSInteger routingID = [connection_ transactionIDFromResponse:response];
372 if (routingID < stackFirstTransactionID_)
373 return;
374 NSNumber* routingNumber = [NSNumber numberWithInt:routingID];
375
376 // Make sure we initialized this frame in our last |-rebuildStack:|.
377 StackFrame* frame = [stackFrames_ objectForKey:routingNumber];
378 if (!frame)
379 return;
380
381 NSXMLElement* xmlframe = [[[response rootElement] children] objectAtIndex:0];
382
383 // Initialize the stack frame.
384 frame.index = [[[xmlframe attributeForName:@"level"] stringValue] intValue];
385 frame.filename = [[xmlframe attributeForName:@"filename"] stringValue];
386 frame.lineNumber = [[[xmlframe attributeForName:@"lineno"] stringValue] intValue];
387 frame.function = [[xmlframe attributeForName:@"where"] stringValue];
388 frame.routingID = routingID;
389
390 // Only get the complete frame for the first level. The other frames will get
391 // information loaded lazily when the user clicks on one.
392 if (frame.index == 0) {
393 [self loadStackFrame:frame];
394 }
395
396 if ([delegate respondsToSelector:@selector(newStackFrame:)])
397 [delegate newStackFrame:frame];
398 }
399
400 /**
401 * Callback for setting the source of a file while rebuilding a specific stack
402 * frame.
403 */
404 - (void)setSource:(NSXMLDocument*)response
405 {
406 NSNumber* transaction = [NSNumber numberWithInt:[connection_ transactionIDFromResponse:response]];
407 if ([transaction intValue] < stackFirstTransactionID_)
408 return;
409 NSNumber* routingNumber = [callbackContext_ objectForKey:transaction];
410 if (!routingNumber)
411 return;
412
413 [callbackContext_ removeObjectForKey:transaction];
414 StackFrame* frame = [stackFrames_ objectForKey:routingNumber];
415 if (!frame)
416 return;
417
418 frame.source = [[response rootElement] base64DecodedValue];
419
420 if ([delegate respondsToSelector:@selector(sourceUpdated:)])
421 [delegate sourceUpdated:frame];
422 }
423
424 /**
425 * Enumerates all the contexts of a given stack frame. We then in turn get the
426 * contents of each one of these contexts.
427 */
428 - (void)contextsReceived:(NSXMLDocument*)response
429 {
430 // Get the stack frame's routing ID and use it again.
431 NSNumber* receivedTransaction = [NSNumber numberWithInt:[connection_ transactionIDFromResponse:response]];
432 if ([receivedTransaction intValue] < stackFirstTransactionID_)
433 return;
434 NSNumber* routingID = [callbackContext_ objectForKey:receivedTransaction];
435 if (!routingID)
436 return;
437
438 // Get the stack frame by the |routingID|.
439 StackFrame* frame = [stackFrames_ objectForKey:routingID];
440
441 NSXMLElement* contextNames = [response rootElement];
442 for (NSXMLElement* context in [contextNames children])
443 {
444 NSInteger cid = [[[context attributeForName:@"id"] stringValue] intValue];
445
446 // Fetch each context's variables.
447 NSNumber* tx = [connection_ sendCommandWithFormat:@"context_get -d %d -c %d", frame.index, cid];
448 [self recordCallback:@selector(variablesReceived:) forTransaction:tx];
449 [callbackContext_ setObject:routingID forKey:tx];
450 }
451 }
452
453 /**
454 * Receives the variables from the context and attaches them to the stack frame.
455 */
456 - (void)variablesReceived:(NSXMLDocument*)response
457 {
458 // Get the stack frame's routing ID and use it again.
459 NSInteger transaction = [connection_ transactionIDFromResponse:response];
460 if (transaction < stackFirstTransactionID_)
461 return;
462 NSNumber* receivedTransaction = [NSNumber numberWithInt:transaction];
463 NSNumber* routingID = [callbackContext_ objectForKey:receivedTransaction];
464 if (!routingID)
465 return;
466
467 // Get the stack frame by the |routingID|.
468 StackFrame* frame = [stackFrames_ objectForKey:routingID];
469
470 NSMutableArray* variables = [NSMutableArray array];
471
472 // Merge the frame's existing variables.
473 if (frame.variables)
474 [variables addObjectsFromArray:frame.variables];
475
476 // Add these new variables.
477 NSArray* addVariables = [[response rootElement] children];
478 if (addVariables) {
479 for (NSXMLElement* elm in addVariables) {
480 VariableNode* node = [[VariableNode alloc] initWithXMLNode:elm];
481 [variables addObject:[node autorelease]];
482 }
483 }
484
485 frame.variables = variables;
486 }
487
488 /**
489 * Callback from a |-getProperty:| request.
490 */
491 - (void)propertiesReceived:(NSXMLDocument*)response
492 {
493 NSInteger transaction = [connection_ transactionIDFromResponse:response];
494
495 /*
496 <response>
497 <property> <!-- this is the one we requested -->
498 <property ... /> <!-- these are what we want -->
499 </property>
500 </repsonse>
501 */
502
503 // Detach all the children so we can insert them into another document.
504 NSXMLElement* parent = (NSXMLElement*)[[response rootElement] childAtIndex:0];
505 NSArray* children = [parent children];
506 [parent setChildren:nil];
507
508 [delegate receivedProperties:children forTransaction:transaction];
509 }
510
511 /**
512 * Callback from a |-evalScript:| request.
513 */
514 - (void)evalScriptReceived:(NSXMLDocument*)response
515 {
516 NSXMLElement* parent = (NSXMLElement*)[[response rootElement] childAtIndex:0];
517 NSString* value = [parent base64DecodedValue];
518 [delegate scriptWasEvaluatedWithResult:value];
519 }
520
521 /**
522 * Callback for setting a breakpoint.
523 */
524 - (void)breakpointReceived:(NSXMLDocument*)response
525 {
526 NSNumber* transaction = [NSNumber numberWithInt:[connection_ transactionIDFromResponse:response]];
527 Breakpoint* bp = [callbackContext_ objectForKey:transaction];
528 if (!bp)
529 return;
530
531 [callbackContext_ removeObjectForKey:callbackContext_];
532 [bp setDebuggerId:[[[[response rootElement] attributeForName:@"id"] stringValue] intValue]];
533 }
534
535 // Private /////////////////////////////////////////////////////////////////////
536
537 - (void)recordCallback:(SEL)callback forTransaction:(NSNumber*)txn
538 {
539 [callTable_ setObject:NSStringFromSelector(callback) forKey:txn];
540 }
541
542 @end