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