Remove the thin layer around ProtocolClient that is NetworkConnection.
[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 port_ = aPort;
64 client_ = [[ProtocolClient alloc] initWithDelegate:self];
65
66 attached_ = [[NSUserDefaults standardUserDefaults] boolForKey:@"DebuggerAttached"];
67
68 if (self.attached)
69 [client_ connectOnPort:port_];
70 }
71 return self;
72 }
73
74 /**
75 * Deallocates the object
76 */
77 - (void)dealloc
78 {
79 [client_ release];
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 port_;
96 }
97
98 /**
99 * Returns whether or not we have an active connection
100 */
101 - (BOOL)isConnected
102 {
103 return 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 [client_ connectOnPort:port_];
114 else
115 [client_ disconnect];
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 = [client_ 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 = [client_ 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 = [client_ 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 = [client_ 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 [client_ disconnect];
165 active_ = NO;
166 self.status = @"Stopped";
167 }
168
169 /**
170 * Ends the current debugging session.
171 */
172 - (void)detach
173 {
174 [client_ 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 = [client_ 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 = [client_ 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 = [client_ 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 (!active_)
224 return;
225
226 NSString* file = [ProtocolClient escapedFilePathURI:[bp transformedPath]];
227 NSNumber* tx = [client_ 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 (!active_)
238 return;
239
240 [client_ 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 (!active_)
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 = [client_ sendCustomCommandWithFormat:@"eval -i {txn} -- %s", encodedString];
254 free(encodedString);
255
256 [self recordCallback:@selector(evalScriptReceived:) forTransaction:tx];
257 }
258
259 // Protocol Client Delegate ////////////////////////////////////////////////////
260 #pragma mark Protocol Client Delegate
261
262 - (void)debuggerEngineConnected:(ProtocolClient*)client
263 {
264 active_ = YES;
265 }
266
267 /**
268 * Called when the connection is finally closed. This will reopen the listening
269 * socket if the debugger remains attached.
270 */
271 - (void)debuggerEngineDisconnected:(ProtocolClient*)client
272 {
273 active_ = NO;
274
275 if ([delegate respondsToSelector:@selector(debuggerDisconnected)])
276 [delegate debuggerDisconnected];
277
278 if (self.attached)
279 [client_ connectOnPort:port_];
280 }
281
282 - (void)debuggerEngine:(ProtocolClient*)client receivedMessage:(NSXMLDocument*)message
283 {
284 // Check and see if there's an error.
285 NSArray* error = [[message rootElement] elementsForName:@"error"];
286 if ([error count] > 0) {
287 NSLog(@"Xdebug error: %@", error);
288 NSString* errorMessage = [[[[error objectAtIndex:0] children] objectAtIndex:0] stringValue];
289 [self errorEncountered:errorMessage];
290 }
291
292 if ([[[message rootElement] name] isEqualToString:@"init"]) {
293 [self handleInitialResponse:message];
294 return;
295 }
296
297 [self handleResponse:message];
298 }
299
300 // Specific Response Handlers //////////////////////////////////////////////////
301 #pragma mark Response Handlers
302
303 - (void)errorEncountered:(NSString*)error
304 {
305 [delegate errorEncountered:error];
306 }
307
308 /**
309 * Initial packet received. We've started a brand-new connection to the engine.
310 */
311 - (void)handleInitialResponse:(NSXMLDocument*)response
312 {
313 if (!self.attached) {
314 [client_ sendCommandWithFormat:@"detach"];
315 return;
316 }
317
318 active_ = YES;
319
320 // Register any breakpoints that exist offline.
321 for (Breakpoint* bp in [[BreakpointManager sharedManager] breakpoints])
322 [self addBreakpoint:bp];
323
324 // Load the debugger to make it look active.
325 [delegate debuggerConnected];
326
327 // TODO: update the status.
328 }
329
330 - (void)handleResponse:(NSXMLDocument*)response
331 {
332 NSInteger transactionID = [client_ transactionIDFromResponse:response];
333 NSNumber* key = [NSNumber numberWithInt:transactionID];
334 NSString* callbackStr = [callTable_ objectForKey:key];
335 if (callbackStr)
336 {
337 SEL callback = NSSelectorFromString(callbackStr);
338 [self performSelector:callback withObject:response];
339 }
340 [callTable_ removeObjectForKey:key];
341 }
342
343 /**
344 * Receiver for status updates. This just freshens up the UI.
345 */
346 - (void)updateStatus:(NSXMLDocument*)response
347 {
348 self.status = [[[[response rootElement] attributeForName:@"status"] stringValue] capitalizedString];
349 active_ = YES;
350 if (!status || [status isEqualToString:@"Stopped"]) {
351 [delegate debuggerDisconnected];
352 active_ = NO;
353 } else if ([status isEqualToString:@"Stopping"]) {
354 [client_ sendCommandWithFormat:@"stop"];
355 active_ = NO;
356 }
357 }
358
359 /**
360 * Step in/out/over and run all take this path. We first get the status of the
361 * debugger and then request fresh stack information.
362 */
363 - (void)debuggerStep:(NSXMLDocument*)response
364 {
365 [self updateStatus:response];
366 if (![self isConnected])
367 return;
368
369 // If this is the run command, tell the delegate that a bunch of updates
370 // are coming. Also remove all existing stack routes and request a new stack.
371 if ([delegate respondsToSelector:@selector(clobberStack)])
372 [delegate clobberStack];
373 [stackFrames_ removeAllObjects];
374 NSNumber* tx = [client_ sendCommandWithFormat:@"stack_depth"];
375 [self recordCallback:@selector(rebuildStack:) forTransaction:tx];
376 stackFirstTransactionID_ = [tx intValue];
377 }
378
379 /**
380 * We ask for the stack_depth and now we clobber the stack and start rebuilding
381 * it.
382 */
383 - (void)rebuildStack:(NSXMLDocument*)response
384 {
385 NSInteger depth = [[[[response rootElement] attributeForName:@"depth"] stringValue] intValue];
386
387 if (stackFirstTransactionID_ == [client_ transactionIDFromResponse:response])
388 stackDepth_ = depth;
389
390 // We now need to alloc a bunch of stack frames and get the basic information
391 // for them.
392 for (NSInteger i = 0; i < depth; i++)
393 {
394 // Use the transaction ID to create a routing path.
395 NSNumber* routingID = [client_ sendCommandWithFormat:@"stack_get -d %d", i];
396 [self recordCallback:@selector(getStackFrame:) forTransaction:routingID];
397 [stackFrames_ setObject:[[StackFrame new] autorelease] forKey:routingID];
398 }
399 }
400
401 /**
402 * The initial rebuild of the stack frame. We now have enough to initialize
403 * a StackFrame object.
404 */
405 - (void)getStackFrame:(NSXMLDocument*)response
406 {
407 // Get the routing information.
408 NSInteger routingID = [client_ transactionIDFromResponse:response];
409 if (routingID < stackFirstTransactionID_)
410 return;
411 NSNumber* routingNumber = [NSNumber numberWithInt:routingID];
412
413 // Make sure we initialized this frame in our last |-rebuildStack:|.
414 StackFrame* frame = [stackFrames_ objectForKey:routingNumber];
415 if (!frame)
416 return;
417
418 NSXMLElement* xmlframe = [[[response rootElement] children] objectAtIndex:0];
419
420 // Initialize the stack frame.
421 frame.index = [[[xmlframe attributeForName:@"level"] stringValue] intValue];
422 frame.filename = [[xmlframe attributeForName:@"filename"] stringValue];
423 frame.lineNumber = [[[xmlframe attributeForName:@"lineno"] stringValue] intValue];
424 frame.function = [[xmlframe attributeForName:@"where"] stringValue];
425 frame.routingID = routingID;
426
427 // Only get the complete frame for the first level. The other frames will get
428 // information loaded lazily when the user clicks on one.
429 if (frame.index == 0) {
430 [self loadStackFrame:frame];
431 }
432
433 if ([delegate respondsToSelector:@selector(newStackFrame:)])
434 [delegate newStackFrame:frame];
435 }
436
437 /**
438 * Callback for setting the source of a file while rebuilding a specific stack
439 * frame.
440 */
441 - (void)setSource:(NSXMLDocument*)response
442 {
443 NSNumber* transaction = [NSNumber numberWithInt:[client_ transactionIDFromResponse:response]];
444 if ([transaction intValue] < stackFirstTransactionID_)
445 return;
446 NSNumber* routingNumber = [callbackContext_ objectForKey:transaction];
447 if (!routingNumber)
448 return;
449
450 [callbackContext_ removeObjectForKey:transaction];
451 StackFrame* frame = [stackFrames_ objectForKey:routingNumber];
452 if (!frame)
453 return;
454
455 frame.source = [[response rootElement] base64DecodedValue];
456
457 if ([delegate respondsToSelector:@selector(sourceUpdated:)])
458 [delegate sourceUpdated:frame];
459 }
460
461 /**
462 * Enumerates all the contexts of a given stack frame. We then in turn get the
463 * contents of each one of these contexts.
464 */
465 - (void)contextsReceived:(NSXMLDocument*)response
466 {
467 // Get the stack frame's routing ID and use it again.
468 NSNumber* receivedTransaction = [NSNumber numberWithInt:[client_ transactionIDFromResponse:response]];
469 if ([receivedTransaction intValue] < stackFirstTransactionID_)
470 return;
471 NSNumber* routingID = [callbackContext_ objectForKey:receivedTransaction];
472 if (!routingID)
473 return;
474
475 // Get the stack frame by the |routingID|.
476 StackFrame* frame = [stackFrames_ objectForKey:routingID];
477
478 NSXMLElement* contextNames = [response rootElement];
479 for (NSXMLElement* context in [contextNames children])
480 {
481 NSInteger cid = [[[context attributeForName:@"id"] stringValue] intValue];
482
483 // Fetch each context's variables.
484 NSNumber* tx = [client_ sendCommandWithFormat:@"context_get -d %d -c %d", frame.index, cid];
485 [self recordCallback:@selector(variablesReceived:) forTransaction:tx];
486 [callbackContext_ setObject:routingID forKey:tx];
487 }
488 }
489
490 /**
491 * Receives the variables from the context and attaches them to the stack frame.
492 */
493 - (void)variablesReceived:(NSXMLDocument*)response
494 {
495 // Get the stack frame's routing ID and use it again.
496 NSInteger transaction = [client_ transactionIDFromResponse:response];
497 if (transaction < stackFirstTransactionID_)
498 return;
499 NSNumber* receivedTransaction = [NSNumber numberWithInt:transaction];
500 NSNumber* routingID = [callbackContext_ objectForKey:receivedTransaction];
501 if (!routingID)
502 return;
503
504 // Get the stack frame by the |routingID|.
505 StackFrame* frame = [stackFrames_ objectForKey:routingID];
506
507 NSMutableArray* variables = [NSMutableArray array];
508
509 // Merge the frame's existing variables.
510 if (frame.variables)
511 [variables addObjectsFromArray:frame.variables];
512
513 // Add these new variables.
514 NSArray* addVariables = [[response rootElement] children];
515 if (addVariables) {
516 for (NSXMLElement* elm in addVariables) {
517 VariableNode* node = [[VariableNode alloc] initWithXMLNode:elm];
518 [variables addObject:[node autorelease]];
519 }
520 }
521
522 frame.variables = variables;
523 }
524
525 /**
526 * Callback from a |-getProperty:| request.
527 */
528 - (void)propertiesReceived:(NSXMLDocument*)response
529 {
530 NSInteger transaction = [client_ transactionIDFromResponse:response];
531
532 /*
533 <response>
534 <property> <!-- this is the one we requested -->
535 <property ... /> <!-- these are what we want -->
536 </property>
537 </repsonse>
538 */
539
540 // Detach all the children so we can insert them into another document.
541 NSXMLElement* parent = (NSXMLElement*)[[response rootElement] childAtIndex:0];
542 NSArray* children = [parent children];
543 [parent setChildren:nil];
544
545 [delegate receivedProperties:children forTransaction:transaction];
546 }
547
548 /**
549 * Callback from a |-evalScript:| request.
550 */
551 - (void)evalScriptReceived:(NSXMLDocument*)response
552 {
553 NSXMLElement* parent = (NSXMLElement*)[[response rootElement] childAtIndex:0];
554 NSString* value = [parent base64DecodedValue];
555 [delegate scriptWasEvaluatedWithResult:value];
556 }
557
558 /**
559 * Callback for setting a breakpoint.
560 */
561 - (void)breakpointReceived:(NSXMLDocument*)response
562 {
563 NSNumber* transaction = [NSNumber numberWithInt:[client_ transactionIDFromResponse:response]];
564 Breakpoint* bp = [callbackContext_ objectForKey:transaction];
565 if (!bp)
566 return;
567
568 [callbackContext_ removeObjectForKey:callbackContext_];
569 [bp setDebuggerId:[[[[response rootElement] attributeForName:@"id"] stringValue] intValue]];
570 }
571
572 // Private /////////////////////////////////////////////////////////////////////
573
574 - (void)recordCallback:(SEL)callback forTransaction:(NSNumber*)txn
575 {
576 [callTable_ setObject:NSStringFromSelector(callback) forKey:txn];
577 }
578
579 @end