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