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