Move -[DebuggerConnection send:] to the private interface because it isn't threadsafe.
[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 attached = attached_;
46 @synthesize delegate;
47
48 /**
49 * Creates a new DebuggerConnection 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_ = [[DebuggerConnection 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
157 // Get the source code of the file. Escape % in URL chars.
158 NSString* escapedFilename = [frame.filename stringByReplacingOccurrencesOfString:@"%" withString:@"%%"];
159 NSNumber* transaction = [connection_ sendCommandWithFormat:@"source -f %@", escapedFilename];
160 [self recordCallback:@selector(setSource:) forTransaction:transaction];
161 [callbackContext_ setObject:routingNumber forKey:transaction];
162
163 // Get the names of all the contexts.
164 transaction = [connection_ sendCommandWithFormat:@"context_names -d %d", frame.index];
165 [self recordCallback:@selector(contextsReceived:) forTransaction:transaction];
166 [callbackContext_ setObject:routingNumber forKey:transaction];
167
168 // This frame will be fully loaded.
169 frame.loaded = YES;
170 }
171
172 // Breakpoint Management ///////////////////////////////////////////////////////
173 #pragma mark Breakpoints
174
175 /**
176 * Send an add breakpoint command
177 */
178 - (void)addBreakpoint:(Breakpoint*)bp
179 {
180 if (![connection_ connected])
181 return;
182
183 NSString* file = [connection_ escapedURIPath:[bp transformedPath]];
184 NSNumber* tx = [connection_ sendCommandWithFormat:@"breakpoint_set -t line -f %@ -n %i", file, [bp line]];
185 [self recordCallback:@selector(breakpointReceived:) forTransaction:tx];
186 [callbackContext_ setObject:bp forKey:tx];
187 }
188
189 /**
190 * Removes a breakpoint
191 */
192 - (void)removeBreakpoint:(Breakpoint*)bp
193 {
194 if (![connection_ connected])
195 return;
196
197 [connection_ sendCommandWithFormat:@"breakpoint_remove -d %i", [bp debuggerId]];
198 }
199
200 // Specific Response Handlers //////////////////////////////////////////////////
201 #pragma mark Response Handlers
202
203 - (void)connectionDidAccept:(DebuggerConnection*)cx
204 {
205 if (!self.attached)
206 [connection_ sendCommandWithFormat:@"detach"];
207 }
208
209 - (void)errorEncountered:(NSString*)error
210 {
211 [delegate errorEncountered:error];
212 }
213
214 /**
215 * Initial packet received. We've started a brand-new connection to the engine.
216 */
217 - (void)handleInitialResponse:(NSXMLDocument*)response
218 {
219 active_ = YES;
220
221 // Register any breakpoints that exist offline.
222 for (Breakpoint* bp in [[BreakpointManager sharedManager] breakpoints])
223 [self addBreakpoint:bp];
224
225 // Load the debugger to make it look active.
226 [delegate debuggerConnected];
227
228 // TODO: update the status.
229 }
230
231 - (void)handleResponse:(NSXMLDocument*)response
232 {
233 NSInteger transactionID = [connection_ transactionIDFromResponse:response];
234 NSNumber* key = [NSNumber numberWithInt:transactionID];
235 NSString* callbackStr = [callTable_ objectForKey:key];
236 if (callbackStr)
237 {
238 SEL callback = NSSelectorFromString(callbackStr);
239 [self performSelector:callback withObject:response];
240 }
241 [callTable_ removeObjectForKey:key];
242 }
243
244 /**
245 * Receiver for status updates. This just freshens up the UI.
246 */
247 - (void)updateStatus:(NSXMLDocument*)response
248 {
249 self.status = [[[[response rootElement] attributeForName:@"status"] stringValue] capitalizedString];
250 active_ = YES;
251 if (!status || [status isEqualToString:@"Stopped"]) {
252 [delegate debuggerDisconnected];
253 active_ = NO;
254 } else if ([status isEqualToString:@"Stopping"]) {
255 [connection_ sendCommandWithFormat:@"stop"];
256 active_ = NO;
257 }
258 }
259
260 /**
261 * Step in/out/over and run all take this path. We first get the status of the
262 * debugger and then request fresh stack information.
263 */
264 - (void)debuggerStep:(NSXMLDocument*)response
265 {
266 [self updateStatus:response];
267 if (![self isConnected])
268 return;
269
270 // If this is the run command, tell the delegate that a bunch of updates
271 // are coming. Also remove all existing stack routes and request a new stack.
272 if ([delegate respondsToSelector:@selector(clobberStack)])
273 [delegate clobberStack];
274 [stackFrames_ removeAllObjects];
275 NSNumber* tx = [connection_ sendCommandWithFormat:@"stack_depth"];
276 [self recordCallback:@selector(rebuildStack:) forTransaction:tx];
277 stackFirstTransactionID_ = [tx intValue];
278 }
279
280 /**
281 * We ask for the stack_depth and now we clobber the stack and start rebuilding
282 * it.
283 */
284 - (void)rebuildStack:(NSXMLDocument*)response
285 {
286 NSInteger depth = [[[[response rootElement] attributeForName:@"depth"] stringValue] intValue];
287
288 if (stackFirstTransactionID_ == [connection_ transactionIDFromResponse:response])
289 stackDepth_ = depth;
290
291 // We now need to alloc a bunch of stack frames and get the basic information
292 // for them.
293 for (NSInteger i = 0; i < depth; i++)
294 {
295 // Use the transaction ID to create a routing path.
296 NSNumber* routingID = [connection_ sendCommandWithFormat:@"stack_get -d %d", i];
297 [self recordCallback:@selector(getStackFrame:) forTransaction:routingID];
298 [stackFrames_ setObject:[[StackFrame new] autorelease] forKey:routingID];
299 }
300 }
301
302 /**
303 * The initial rebuild of the stack frame. We now have enough to initialize
304 * a StackFrame object.
305 */
306 - (void)getStackFrame:(NSXMLDocument*)response
307 {
308 // Get the routing information.
309 NSInteger routingID = [connection_ transactionIDFromResponse:response];
310 if (routingID < stackFirstTransactionID_)
311 return;
312 NSNumber* routingNumber = [NSNumber numberWithInt:routingID];
313
314 // Make sure we initialized this frame in our last |-rebuildStack:|.
315 StackFrame* frame = [stackFrames_ objectForKey:routingNumber];
316 if (!frame)
317 return;
318
319 NSXMLElement* xmlframe = [[[response rootElement] children] objectAtIndex:0];
320
321 // Initialize the stack frame.
322 frame.index = [[[xmlframe attributeForName:@"level"] stringValue] intValue];
323 frame.filename = [[xmlframe attributeForName:@"filename"] stringValue];
324 frame.lineNumber = [[[xmlframe attributeForName:@"lineno"] stringValue] intValue];
325 frame.function = [[xmlframe attributeForName:@"where"] stringValue];
326 frame.routingID = routingID;
327
328 // Only get the complete frame for the first level. The other frames will get
329 // information loaded lazily when the user clicks on one.
330 if (frame.index == 0) {
331 [self loadStackFrame:frame];
332 }
333
334 if ([delegate respondsToSelector:@selector(newStackFrame:)])
335 [delegate newStackFrame:frame];
336 }
337
338 /**
339 * Callback for setting the source of a file while rebuilding a specific stack
340 * frame.
341 */
342 - (void)setSource:(NSXMLDocument*)response
343 {
344 NSNumber* transaction = [NSNumber numberWithInt:[connection_ transactionIDFromResponse:response]];
345 if ([transaction intValue] < stackFirstTransactionID_)
346 return;
347 NSNumber* routingNumber = [callbackContext_ objectForKey:transaction];
348 if (!routingNumber)
349 return;
350
351 [callbackContext_ removeObjectForKey:transaction];
352 StackFrame* frame = [stackFrames_ objectForKey:routingNumber];
353 if (!frame)
354 return;
355
356 frame.source = [[response rootElement] base64DecodedValue];
357
358 if ([delegate respondsToSelector:@selector(sourceUpdated:)])
359 [delegate sourceUpdated:frame];
360 }
361
362 /**
363 * Enumerates all the contexts of a given stack frame. We then in turn get the
364 * contents of each one of these contexts.
365 */
366 - (void)contextsReceived:(NSXMLDocument*)response
367 {
368 // Get the stack frame's routing ID and use it again.
369 NSNumber* receivedTransaction = [NSNumber numberWithInt:[connection_ transactionIDFromResponse:response]];
370 if ([receivedTransaction intValue] < stackFirstTransactionID_)
371 return;
372 NSNumber* routingID = [callbackContext_ objectForKey:receivedTransaction];
373 if (!routingID)
374 return;
375
376 // Get the stack frame by the |routingID|.
377 StackFrame* frame = [stackFrames_ objectForKey:routingID];
378
379 NSXMLElement* contextNames = [response rootElement];
380 for (NSXMLElement* context in [contextNames children])
381 {
382 NSInteger cid = [[[context attributeForName:@"id"] stringValue] intValue];
383
384 // Fetch each context's variables.
385 NSNumber* tx = [connection_ sendCommandWithFormat:@"context_get -d %d -c %d", frame.index, cid];
386 [self recordCallback:@selector(variablesReceived:) forTransaction:tx];
387 [callbackContext_ setObject:routingID forKey:tx];
388 }
389 }
390
391 /**
392 * Receives the variables from the context and attaches them to the stack frame.
393 */
394 - (void)variablesReceived:(NSXMLDocument*)response
395 {
396 // Get the stack frame's routing ID and use it again.
397 NSInteger transaction = [connection_ transactionIDFromResponse:response];
398 if (transaction < stackFirstTransactionID_)
399 return;
400 NSNumber* receivedTransaction = [NSNumber numberWithInt:transaction];
401 NSNumber* routingID = [callbackContext_ objectForKey:receivedTransaction];
402 if (!routingID)
403 return;
404
405 // Get the stack frame by the |routingID|.
406 StackFrame* frame = [stackFrames_ objectForKey:routingID];
407
408 NSMutableArray* variables = [NSMutableArray array];
409
410 // Merge the frame's existing variables.
411 if (frame.variables)
412 [variables addObjectsFromArray:frame.variables];
413
414 // Add these new variables.
415 NSArray* addVariables = [[response rootElement] children];
416 if (addVariables) {
417 for (NSXMLElement* elm in addVariables) {
418 VariableNode* node = [[VariableNode alloc] initWithXMLNode:elm];
419 [variables addObject:[node autorelease]];
420 }
421 }
422
423 frame.variables = variables;
424 }
425
426 /**
427 * Callback from a |-getProperty:| request.
428 */
429 - (void)propertiesReceived:(NSXMLDocument*)response
430 {
431 NSInteger transaction = [connection_ transactionIDFromResponse:response];
432
433 /*
434 <response>
435 <property> <!-- this is the one we requested -->
436 <property ... /> <!-- these are what we want -->
437 </property>
438 </repsonse>
439 */
440
441 // Detach all the children so we can insert them into another document.
442 NSXMLElement* parent = (NSXMLElement*)[[response rootElement] childAtIndex:0];
443 NSArray* children = [parent children];
444 [parent setChildren:nil];
445
446 [delegate receivedProperties:children forTransaction:transaction];
447 }
448
449 /**
450 * Callback for setting a breakpoint.
451 */
452 - (void)breakpointReceived:(NSXMLDocument*)response
453 {
454 NSNumber* transaction = [NSNumber numberWithInt:[connection_ transactionIDFromResponse:response]];
455 Breakpoint* bp = [callbackContext_ objectForKey:transaction];
456 if (!bp)
457 return;
458
459 [callbackContext_ removeObjectForKey:callbackContext_];
460 [bp setDebuggerId:[[[[response rootElement] attributeForName:@"id"] stringValue] intValue]];
461 }
462
463 // Private /////////////////////////////////////////////////////////////////////
464
465 - (void)recordCallback:(SEL)callback forTransaction:(NSNumber*)txn
466 {
467 [callTable_ setObject:NSStringFromSelector(callback) forKey:txn];
468 }
469
470 @end