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