Don't crash after pressing the "run" button or at end of script.
[macgdbp.git] / Source / DebuggerConnection.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 <sys/socket.h>
18 #import <netinet/in.h>
19
20 #import "DebuggerConnection.h"
21
22 #import "AppDelegate.h"
23
24 // GDBpConnection (Private) ////////////////////////////////////////////////////
25
26 @interface DebuggerConnection ()
27 @property (readwrite, copy) NSString* status;
28 @property (assign) CFSocketRef socket;
29 @property (assign) CFReadStreamRef readStream;
30 @property NSUInteger lastReadTransaction;
31 @property (retain) NSMutableString* currentPacket;
32 @property (assign) CFWriteStreamRef writeStream;
33 @property NSUInteger lastWrittenTransaction;
34 @property (retain) NSMutableArray* queuedWrites;
35
36 - (void)connect;
37 - (void)close;
38 - (void)socketDidAccept;
39 - (void)socketDisconnected;
40 - (void)readStreamHasData;
41 - (void)send:(NSString*)command;
42 - (void)performSend:(NSString*)command;
43 - (void)errorEncountered:(NSString*)error;
44
45 - (void)handleResponse:(NSXMLDocument*)response;
46 - (void)initReceived:(NSXMLDocument*)response;
47 - (void)updateStatus:(NSXMLDocument*)response;
48 - (void)debuggerStep:(NSXMLDocument*)response;
49 - (void)rebuildStack:(NSXMLDocument*)response;
50 - (void)getStackFrame:(NSXMLDocument*)response;
51 - (void)setSource:(NSXMLDocument*)response;
52 - (void)contextsReceived:(NSXMLDocument*)response;
53 - (void)variablesReceived:(NSXMLDocument*)response;
54 - (void)propertiesReceived:(NSXMLDocument*)response;
55
56 - (NSNumber*)sendCommandWithCallback:(SEL)callback format:(NSString*)format, ...;
57
58 - (void)sendQueuedWrites;
59
60 - (NSString*)escapedURIPath:(NSString*)path;
61 - (NSInteger)transactionIDFromResponse:(NSXMLDocument*)response;
62 @end
63
64 // CFNetwork Callbacks /////////////////////////////////////////////////////////
65
66 void ReadStreamCallback(CFReadStreamRef stream, CFStreamEventType eventType, void* connectionRaw)
67 {
68 DebuggerConnection* connection = (DebuggerConnection*)connectionRaw;
69 switch (eventType)
70 {
71 case kCFStreamEventHasBytesAvailable:
72 NSLog(@"About to read.");
73 [connection readStreamHasData];
74 break;
75
76 case kCFStreamEventErrorOccurred:
77 {
78 CFErrorRef error = CFReadStreamCopyError(stream);
79 CFReadStreamUnscheduleFromRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
80 CFReadStreamClose(stream);
81 CFRelease(stream);
82 [connection errorEncountered:[[(NSError*)error autorelease] description]];
83 break;
84 }
85
86 case kCFStreamEventEndEncountered:
87 CFReadStreamUnscheduleFromRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
88 CFReadStreamClose(stream);
89 CFRelease(stream);
90 [connection socketDisconnected];
91 break;
92 };
93 }
94
95 void WriteStreamCallback(CFWriteStreamRef stream, CFStreamEventType eventType, void* connectionRaw)
96 {
97 DebuggerConnection* connection = (DebuggerConnection*)connectionRaw;
98 switch (eventType)
99 {
100 case kCFStreamEventCanAcceptBytes:
101 [connection sendQueuedWrites];
102 break;
103
104 case kCFStreamEventErrorOccurred:
105 {
106 CFErrorRef error = CFWriteStreamCopyError(stream);
107 CFWriteStreamUnscheduleFromRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
108 CFWriteStreamClose(stream);
109 CFRelease(stream);
110 [connection errorEncountered:[[(NSError*)error autorelease] description]];
111 break;
112 }
113
114 case kCFStreamEventEndEncountered:
115 CFWriteStreamUnscheduleFromRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
116 CFWriteStreamClose(stream);
117 CFRelease(stream);
118 [connection socketDisconnected];
119 break;
120 }
121 }
122
123 void SocketAcceptCallback(CFSocketRef socket,
124 CFSocketCallBackType callbackType,
125 CFDataRef address,
126 const void* data,
127 void* connectionRaw)
128 {
129 assert(callbackType == kCFSocketAcceptCallBack);
130 NSLog(@"SocketAcceptCallback()");
131
132 DebuggerConnection* connection = (DebuggerConnection*)connectionRaw;
133
134 CFReadStreamRef readStream;
135 CFWriteStreamRef writeStream;
136
137 // Create the streams on the socket.
138 CFStreamCreatePairWithSocket(kCFAllocatorDefault,
139 *(CFSocketNativeHandle*)data, // Socket handle.
140 &readStream, // Read stream in-pointer.
141 &writeStream); // Write stream in-pointer.
142
143 // Create struct to register callbacks for the stream.
144 CFStreamClientContext context;
145 context.version = 0;
146 context.info = connection;
147 context.retain = NULL;
148 context.release = NULL;
149 context.copyDescription = NULL;
150
151 // Set the client of the read stream.
152 CFOptionFlags readFlags =
153 kCFStreamEventOpenCompleted |
154 kCFStreamEventHasBytesAvailable |
155 kCFStreamEventErrorOccurred |
156 kCFStreamEventEndEncountered;
157 if (CFReadStreamSetClient(readStream, readFlags, ReadStreamCallback, &context))
158 // Schedule in run loop to do asynchronous communication with the engine.
159 CFReadStreamScheduleWithRunLoop(readStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
160 else
161 return;
162
163 // Open the stream now that it's scheduled on the run loop.
164 if (!CFReadStreamOpen(readStream))
165 {
166 CFStreamError error = CFReadStreamGetError(readStream);
167 NSLog(@"error! %@", error);
168 return;
169 }
170
171 // Set the client of the write stream.
172 CFOptionFlags writeFlags =
173 kCFStreamEventOpenCompleted |
174 kCFStreamEventCanAcceptBytes |
175 kCFStreamEventErrorOccurred |
176 kCFStreamEventEndEncountered;
177 if (CFWriteStreamSetClient(writeStream, writeFlags, WriteStreamCallback, &context))
178 // Schedule it in the run loop to receive error information.
179 CFWriteStreamScheduleWithRunLoop(writeStream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
180 else
181 return;
182
183 // Open the write stream.
184 if (!CFWriteStreamOpen(writeStream))
185 {
186 CFStreamError error = CFWriteStreamGetError(writeStream);
187 NSLog(@"error! %@", error);
188 return;
189 }
190
191 connection.readStream = readStream;
192 connection.writeStream = writeStream;
193 [connection socketDidAccept];
194 }
195
196 // GDBpConnection //////////////////////////////////////////////////////////////
197
198 @implementation DebuggerConnection
199 @synthesize socket = socket_;
200 @synthesize readStream = readStream_;
201 @synthesize lastReadTransaction = lastReadTransaction_;
202 @synthesize currentPacket = currentPacket_;
203 @synthesize writeStream = writeStream_;
204 @synthesize lastWrittenTransaction = lastWrittenTransaction_;
205 @synthesize queuedWrites = queuedWrites_;
206 @synthesize status;
207 @synthesize delegate;
208
209 /**
210 * Creates a new DebuggerConnection and initializes the socket from the given connection
211 * paramters.
212 */
213 - (id)initWithPort:(NSUInteger)aPort
214 {
215 if (self = [super init])
216 {
217 port = aPort;
218 connected = NO;
219
220 [[BreakpointManager sharedManager] setConnection:self];
221
222 [self connect];
223 }
224 return self;
225 }
226
227 /**
228 * Deallocates the object
229 */
230 - (void)dealloc
231 {
232 [self close];
233 self.currentPacket = nil;
234
235 [super dealloc];
236 }
237
238
239 // Getters /////////////////////////////////////////////////////////////////////
240 #pragma mark Getters
241
242 /**
243 * Gets the port number
244 */
245 - (NSUInteger)port
246 {
247 return port;
248 }
249
250 /**
251 * Returns the name of the remote host
252 */
253 - (NSString*)remoteHost
254 {
255 if (!connected)
256 {
257 return @"(DISCONNECTED)";
258 }
259 // TODO: Either impl or remove.
260 return @"";
261 }
262
263 /**
264 * Returns whether or not we have an active connection
265 */
266 - (BOOL)isConnected
267 {
268 return connected;
269 }
270
271 // Commands ////////////////////////////////////////////////////////////////////
272 #pragma mark Commands
273
274 /**
275 * Reestablishes communication with the remote debugger so that a new connection doesn't have to be
276 * created every time you want to debug a page
277 */
278 - (void)reconnect
279 {
280 [self close];
281 self.status = @"Connecting";
282 [self connect];
283 }
284
285 /**
286 * Tells the debugger to continue running the script. Returns the current stack frame.
287 */
288 - (void)run
289 {
290 [self sendCommandWithCallback:@selector(debuggerStep:) format:@"run"];
291 }
292
293 /**
294 * Tells the debugger to step into the current command.
295 */
296 - (void)stepIn
297 {
298 [self sendCommandWithCallback:@selector(debuggerStep:) format:@"step_into"];
299 }
300
301 /**
302 * Tells the debugger to step out of the current context
303 */
304 - (void)stepOut
305 {
306 [self sendCommandWithCallback:@selector(debuggerStep:) format:@"step_out"];
307 }
308
309 /**
310 * Tells the debugger to step over the current function
311 */
312 - (void)stepOver
313 {
314 [self sendCommandWithCallback:@selector(debuggerStep:) format:@"step_over"];
315 }
316
317 /**
318 * Tells the debugger engine to get a specifc property. This also takes in the NSXMLElement
319 * that requested it so that the child can be attached.
320 */
321 - (NSInteger)getProperty:(NSString*)property
322 {
323 [self sendCommandWithCallback:@selector(propertiesReceived:) format:@"property_get -n \"%@\"", property];
324 }
325
326 // Breakpoint Management ///////////////////////////////////////////////////////
327 #pragma mark Breakpoints
328
329 /**
330 * Send an add breakpoint command
331 */
332 - (void)addBreakpoint:(Breakpoint*)bp
333 {
334 if (!connected)
335 return;
336
337 NSString* file = [self escapedURIPath:[bp transformedPath]];
338 NSNumber* transaction = [self sendCommandWithCallback:@selector(breakpointReceived:)
339 format:@"breakpoint_set -t line -f %@ -n %i", file, [bp line]];
340 [callbackContext_ setObject:bp forKey:transaction];
341 }
342
343 /**
344 * Removes a breakpoint
345 */
346 - (void)removeBreakpoint:(Breakpoint*)bp
347 {
348 if (!connected)
349 {
350 return;
351 }
352
353 [self sendCommandWithCallback:nil format:@"breakpoint_remove -d %i", [bp debuggerId]];
354 }
355
356
357 // Socket and Stream Callbacks /////////////////////////////////////////////////
358 #pragma mark Callbacks
359
360 /**
361 * Called by SocketWrapper after the connection is successful. This immediately calls
362 * -[SocketWrapper receive] to clear the way for communication, though the information
363 * could be useful server information that we don't use right now.
364 */
365 - (void)socketDidAccept
366 {
367 connected = YES;
368 transactionID = 1;
369 stackFrames_ = [[NSMutableDictionary alloc] init];
370 self.queuedWrites = [NSMutableArray array];
371 writeQueueLock_ = [NSRecursiveLock new];
372 callTable_ = [NSMutableDictionary new];
373 callbackContext_ = [NSMutableDictionary new];
374 }
375
376 /**
377 * Receives errors from the SocketWrapper and updates the display
378 */
379 - (void)errorEncountered:(NSString*)error
380 {
381 [delegate errorEncountered:error];
382 }
383
384 /**
385 * Creates, connects to, and schedules a CFSocket.
386 */
387 - (void)connect
388 {
389 // Pass ourselves to the callback so we don't have to use ugly globals.
390 CFSocketContext context;
391 context.version = 0;
392 context.info = self;
393 context.retain = NULL;
394 context.release = NULL;
395 context.copyDescription = NULL;
396
397 // Create the address structure.
398 struct sockaddr_in address;
399 memset(&address, 0, sizeof(address));
400 address.sin_len = sizeof(address);
401 address.sin_family = AF_INET;
402 address.sin_port = htons(port);
403 address.sin_addr.s_addr = htonl(INADDR_ANY);
404
405 // Create the socket signature.
406 CFSocketSignature signature;
407 signature.protocolFamily = PF_INET;
408 signature.socketType = SOCK_STREAM;
409 signature.protocol = IPPROTO_TCP;
410 signature.address = (CFDataRef)[NSData dataWithBytes:&address length:sizeof(address)];
411
412 socket_ = CFSocketCreateWithSocketSignature(kCFAllocatorDefault,
413 &signature, // Socket signature.
414 kCFSocketAcceptCallBack, // Callback types.
415 SocketAcceptCallback, // Callout function pointer.
416 &context); // Context to pass to callout.
417 if (!socket_)
418 {
419 [self errorEncountered:@"Could not open socket."];
420 return;
421 }
422
423 // Allow old, yet-to-be recycled sockets to be reused.
424 BOOL yes = YES;
425 setsockopt(CFSocketGetNative(socket_), SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(BOOL));
426
427 // Schedule the socket on the run loop.
428 CFRunLoopSourceRef source = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket_, 0);
429 CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes);
430 CFRelease(source);
431
432 self.status = @"Connecting";
433 }
434
435 /**
436 * Closes a socket and releases the ref.
437 */
438 - (void)close
439 {
440 // The socket goes down, so do the streams, which clean themselves up.
441 CFSocketInvalidate(socket_);
442 CFRelease(socket_);
443 [stackFrames_ release];
444 self.queuedWrites = nil;
445 [writeQueueLock_ release];
446 [callTable_ release];
447 [callbackContext_ release];
448 }
449
450 /**
451 * Notification that the socket disconnected.
452 */
453 - (void)socketDisconnected
454 {
455 [self close];
456 [delegate debuggerDisconnected];
457 }
458
459 /**
460 * Callback from the CFReadStream that there is data waiting to be read.
461 */
462 - (void)readStreamHasData
463 {
464 UInt8 buffer[1024];
465 CFIndex bytesRead = CFReadStreamRead(readStream_, buffer, 1024);
466 const char* charBuffer = (const char*)buffer;
467
468 // We haven't finished reading a packet, so just read more data in.
469 if (currentPacketIndex_ < packetSize_)
470 {
471 currentPacketIndex_ += bytesRead;
472 CFStringRef bufferString = CFStringCreateWithBytes(kCFAllocatorDefault,
473 buffer,
474 bytesRead,
475 kCFStringEncodingUTF8,
476 true);
477 [self.currentPacket appendString:(NSString*)bufferString];
478 CFRelease(bufferString);
479 }
480 // Time to read a new packet.
481 else
482 {
483 // Read the message header: the size.
484 packetSize_ = atoi(charBuffer);
485 currentPacketIndex_ = bytesRead - strlen(charBuffer);
486 CFStringRef bufferString = CFStringCreateWithBytes(kCFAllocatorDefault,
487 buffer + strlen(charBuffer) + 1,
488 bytesRead - strlen(charBuffer) - 1,
489 kCFStringEncodingUTF8,
490 true);
491 self.currentPacket = [NSMutableString stringWithString:(NSString*)bufferString];
492 CFRelease(bufferString);
493 }
494
495 // We have finished reading the packet.
496 if (currentPacketIndex_ >= packetSize_)
497 {
498 packetSize_ = 0;
499 currentPacketIndex_ = 0;
500
501 // Test if we can convert it into an NSXMLDocument.
502 NSError* error = nil;
503 NSXMLDocument* xmlTest = [[NSXMLDocument alloc] initWithXMLString:currentPacket_ options:NSXMLDocumentTidyXML error:&error];
504 if (error)
505 {
506 NSLog(@"Could not parse XML? --- %@", error);
507 NSLog(@"Error UserInfo: %@", [error userInfo]);
508 NSLog(@"This is the XML Document: %@", currentPacket_);
509
510 // We do not want to starve the write queue, so manually parse out the
511 // transaction ID.
512 NSRange location = [currentPacket_ rangeOfString:@"transaction_id"];
513 if (location.location != NSNotFound)
514 {
515 NSUInteger start = location.location + location.length;
516 NSUInteger end = start;
517
518 NSCharacterSet* numericSet = [NSCharacterSet decimalDigitCharacterSet];
519
520 // Loop over the characters after the attribute name to extract the ID.
521 while (end < [currentPacket_ length])
522 {
523 unichar c = [currentPacket_ characterAtIndex:end];
524 if ([numericSet characterIsMember:c])
525 {
526 // If this character is numeric, extend the range to substring.
527 ++end;
528 }
529 else
530 {
531 if (start == end)
532 {
533 // If this character is nonnumeric and we have nothing in the
534 // range, skip this character.
535 ++start;
536 ++end;
537 }
538 else
539 {
540 // We've moved past the numeric ID so we should stop searching.
541 break;
542 }
543 }
544 }
545
546 // If we were able to extract the transaction ID, update the last read.
547 NSRange substringRange = NSMakeRange(start, end - start);
548 NSString* transaction = [currentPacket_ substringWithRange:substringRange];
549 if ([transaction length])
550 {
551 lastReadTransaction_ = [transaction intValue];
552 return;
553 }
554 }
555
556 // Otherwise, assume +1 and hope it works.
557 ++lastReadTransaction_;
558 return;
559 }
560 [self handleResponse:[xmlTest autorelease]];
561 }
562 }
563
564 /**
565 * Writes a command into the write stream. If the stream is ready for writing,
566 * we do so immediately. If not, the command is queued and will be written
567 * when the stream is ready.
568 */
569 - (void)send:(NSString*)command
570 {
571 if (lastReadTransaction_ >= lastWrittenTransaction_ && CFWriteStreamCanAcceptBytes(writeStream_))
572 [self performSend:command];
573 else
574 [queuedWrites_ addObject:command];
575 }
576
577 /**
578 * This performs a blocking send. This should ONLY be called when we know we
579 * have write access to the stream. We will busy wait in case we don't do a full
580 * send.
581 */
582 - (void)performSend:(NSString*)command
583 {
584 BOOL done = NO;
585
586 char* string = (char*)[command UTF8String];
587 int stringLength = strlen(string);
588
589 // Log the command if TransportDebug is enabled.
590 if ([[[[NSProcessInfo processInfo] environment] objectForKey:@"TransportDebug"] boolValue])
591 NSLog(@"--> %@", command);
592
593 // Busy wait while writing. BAADD. Should background this operation.
594 while (!done)
595 {
596 if (CFWriteStreamCanAcceptBytes(writeStream_))
597 {
598 // Include the NULL byte in the string when we write.
599 int bytesWritten = CFWriteStreamWrite(writeStream_, (UInt8*)string, stringLength + 1);
600 if (bytesWritten < 0)
601 {
602 NSLog(@"write error");
603 }
604 // Incomplete write.
605 else if (bytesWritten < strlen(string))
606 {
607 // Adjust the buffer and wait for another chance to write.
608 stringLength -= bytesWritten;
609 memmove(string, string + bytesWritten, stringLength);
610 }
611 else
612 {
613 done = YES;
614
615 // We need to scan the string to find the transactionID.
616 NSRange occurrence = [command rangeOfString:@"-i "];
617 if (occurrence.location == NSNotFound)
618 {
619 NSLog(@"sent %@ without a transaction ID", command);
620 continue;
621 }
622 NSString* transaction = [command substringFromIndex:occurrence.location + occurrence.length];
623 lastWrittenTransaction_ = [transaction intValue];
624 NSLog(@"command = %@", command);
625 NSLog(@"read=%d, write=%d", lastReadTransaction_, lastWrittenTransaction_);
626 }
627 }
628 }
629 }
630
631 - (void)handleResponse:(NSXMLDocument*)response
632 {
633 // Check and see if there's an error.
634 NSArray* error = [[response rootElement] elementsForName:@"error"];
635 if ([error count] > 0)
636 {
637 NSLog(@"Xdebug error: %@", error);
638 [delegate errorEncountered:[[[[error objectAtIndex:0] children] objectAtIndex:0] stringValue]];
639 }
640
641 // If TransportDebug is enabled, log the response.
642 if ([[[[NSProcessInfo processInfo] environment] objectForKey:@"TransportDebug"] boolValue])
643 NSLog(@"<-- %@", response);
644
645 // Get the name of the command from the engine's response.
646 NSInteger transaction = [self transactionIDFromResponse:response];
647 if (transaction < lastReadTransaction_)
648 NSLog(@"out of date transaction %@", response);
649
650 if (transaction != lastWrittenTransaction_)
651 NSLog(@"txn doesn't match last written %@", response);
652
653 lastReadTransaction_ = transaction;
654 NSLog(@"read=%d, write=%d", lastReadTransaction_, lastWrittenTransaction_);
655
656 if ([[[response rootElement] name] isEqualToString:@"init"])
657 {
658 [self initReceived:response];
659 return;
660 }
661
662 NSString* callbackStr = [callTable_ objectForKey:[NSNumber numberWithInt:lastReadTransaction_]];
663 if (callbackStr)
664 {
665 SEL callback = NSSelectorFromString(callbackStr);
666 [self performSelector:callback withObject:response];
667 }
668
669 [self sendQueuedWrites];
670 }
671
672 // Specific Response Handlers //////////////////////////////////////////////////
673 #pragma mark Response Handlers
674
675 /**
676 * Initial packet received. We've started a brand-new connection to the engine.
677 */
678 - (void)initReceived:(NSXMLDocument*)response
679 {
680 // Register any breakpoints that exist offline.
681 for (Breakpoint* bp in [[BreakpointManager sharedManager] breakpoints])
682 [self addBreakpoint:bp];
683
684 // Load the debugger to make it look active.
685 [delegate debuggerConnected];
686
687 // TODO: update the status.
688 }
689
690 /**
691 * Receiver for status updates. This just freshens up the UI.
692 */
693 - (void)updateStatus:(NSXMLDocument*)response
694 {
695 self.status = [[[[response rootElement] attributeForName:@"status"] stringValue] capitalizedString];
696 if (status == nil || [status isEqualToString:@"Stopped"] || [status isEqualToString:@"Stopping"])
697 {
698 connected = NO;
699 [self close];
700 [delegate debuggerDisconnected];
701
702 self.status = @"Stopped";
703 }
704 }
705
706 /**
707 * Step in/out/over and run all take this path. We first get the status of the
708 * debugger and then request fresh stack information.
709 */
710 - (void)debuggerStep:(NSXMLDocument*)response
711 {
712 [self updateStatus:response];
713 if (!connected)
714 return;
715
716 // If this is the run command, tell the delegate that a bunch of updates
717 // are coming. Also remove all existing stack routes and request a new stack.
718 // TODO: figure out if we can not clobber the stack every time.
719 NSString* command = [[[response rootElement] attributeForName:@"command"] stringValue];
720 if (YES || [command isEqualToString:@"run"])
721 {
722 if ([delegate respondsToSelector:@selector(clobberStack)])
723 [delegate clobberStack];
724 [stackFrames_ removeAllObjects];
725 stackFirstTransactionID_ = [[self sendCommandWithCallback:@selector(rebuildStack:) format:@"stack_depth"] intValue];
726 }
727 }
728
729 /**
730 * We ask for the stack_depth and now we clobber the stack and start rebuilding
731 * it.
732 */
733 - (void)rebuildStack:(NSXMLDocument*)response
734 {
735 NSInteger depth = [[[[response rootElement] attributeForName:@"depth"] stringValue] intValue];
736
737 if (stackFirstTransactionID_ == [self transactionIDFromResponse:response])
738 stackDepth_ = depth;
739
740 // We now need to alloc a bunch of stack frames and get the basic information
741 // for them.
742 for (NSInteger i = 0; i < depth; i++)
743 {
744 // Use the transaction ID to create a routing path.
745 NSNumber* routingID = [self sendCommandWithCallback:@selector(getStackFrame:) format:@"stack_get -d %d", i];
746 [stackFrames_ setObject:[StackFrame alloc] forKey:routingID];
747 }
748 }
749
750 /**
751 * The initial rebuild of the stack frame. We now have enough to initialize
752 * a StackFrame object.
753 */
754 - (void)getStackFrame:(NSXMLDocument*)response
755 {
756 // Get the routing information.
757 NSInteger routingID = [self transactionIDFromResponse:response];
758 if (routingID < stackFirstTransactionID_)
759 return;
760 NSNumber* routingNumber = [NSNumber numberWithInt:routingID];
761
762 // Make sure we initialized this frame in our last |-rebuildStack:|.
763 StackFrame* frame = [stackFrames_ objectForKey:routingNumber];
764 if (!frame)
765 return;
766
767 NSXMLElement* xmlframe = [[[response rootElement] children] objectAtIndex:0];
768
769 // Initialize the stack frame.
770 [frame initWithIndex:[[[xmlframe attributeForName:@"level"] stringValue] intValue]
771 withFilename:[[xmlframe attributeForName:@"filename"] stringValue]
772 withSource:nil
773 atLine:[[[xmlframe attributeForName:@"lineno"] stringValue] intValue]
774 inFunction:[[xmlframe attributeForName:@"where"] stringValue]
775 withVariables:nil];
776
777 // Get the source code of the file. Escape % in URL chars.
778 NSString* escapedFilename = [frame.filename stringByReplacingOccurrencesOfString:@"%" withString:@"%%"];
779 NSNumber* transaction = [self sendCommandWithCallback:@selector(setSource:) format:@"source -f %@", escapedFilename];
780 [callbackContext_ setObject:routingNumber forKey:transaction];
781
782 // Get the names of all the contexts.
783 transaction = [self sendCommandWithCallback:@selector(contextsReceived:) format:@"context_names -d %d", frame.index];
784 [callbackContext_ setObject:routingNumber forKey:transaction];
785
786 if ([delegate respondsToSelector:@selector(newStackFrame:)])
787 [delegate newStackFrame:frame];
788 }
789
790 /**
791 * Callback for setting the source of a file while rebuilding a specific stack
792 * frame.
793 */
794 - (void)setSource:(NSXMLDocument*)response
795 {
796 NSNumber* transaction = [NSNumber numberWithInt:[self transactionIDFromResponse:response]];
797 if ([transaction intValue] < stackFirstTransactionID_)
798 return;
799 NSNumber* routingNumber = [callbackContext_ objectForKey:transaction];
800 if (!routingNumber)
801 return;
802
803 [callbackContext_ removeObjectForKey:transaction];
804 StackFrame* frame = [stackFrames_ objectForKey:routingNumber];
805 if (!frame)
806 return;
807
808 frame.source = [[response rootElement] value];
809
810 if ([delegate respondsToSelector:@selector(sourceUpdated:)])
811 [delegate sourceUpdated:frame];
812 }
813
814 /**
815 * Enumerates all the contexts of a given stack frame. We then in turn get the
816 * contents of each one of these contexts.
817 */
818 - (void)contextsReceived:(NSXMLDocument*)response
819 {
820 // Get the stack frame's routing ID and use it again.
821 NSNumber* receivedTransaction = [NSNumber numberWithInt:[self transactionIDFromResponse:response]];
822 if ([receivedTransaction intValue] < stackFirstTransactionID_)
823 return;
824 NSNumber* routingID = [callbackContext_ objectForKey:receivedTransaction];
825 if (!routingID)
826 return;
827
828 // Get the stack frame by the |routingID|.
829 StackFrame* frame = [stackFrames_ objectForKey:routingID];
830
831 NSXMLElement* contextNames = [response rootElement];
832 for (NSXMLElement* context in [contextNames children])
833 {
834 NSInteger cid = [[[context attributeForName:@"id"] stringValue] intValue];
835
836 // Fetch each context's variables.
837 NSNumber* transaction = [self sendCommandWithCallback:@selector(variablesReceived:)
838 format:@"context_get -d %d -c %d", frame.index, cid];
839 [callbackContext_ setObject:routingID forKey:transaction];
840 }
841 }
842
843 /**
844 * Receives the variables from the context and attaches them to the stack frame.
845 */
846 - (void)variablesReceived:(NSXMLDocument*)response
847 {
848 // Get the stack frame's routing ID and use it again.
849 NSInteger transaction = [self transactionIDFromResponse:response];
850 if (transaction < stackFirstTransactionID_)
851 return;
852 NSNumber* receivedTransaction = [NSNumber numberWithInt:transaction];
853 NSNumber* routingID = [callbackContext_ objectForKey:receivedTransaction];
854 if (!routingID)
855 return;
856
857 // Get the stack frame by the |routingID|.
858 StackFrame* frame = [stackFrames_ objectForKey:routingID];
859
860 NSMutableArray* variables = [NSMutableArray array];
861
862 // Merge the frame's existing variables.
863 if (frame.variables)
864 [variables addObjectsFromArray:frame.variables];
865
866 // Add these new variables.
867 NSArray* addVariables = [[response rootElement] children];
868 if (addVariables)
869 [variables addObjectsFromArray:addVariables];
870
871 frame.variables = variables;
872 }
873
874 /**
875 * Callback from a |-getProperty:| request.
876 */
877 - (void)propertiesReceived:(NSXMLDocument*)response
878 {
879 NSInteger transaction = [self transactionIDFromResponse:response];
880
881 /*
882 <response>
883 <property> <!-- this is the one we requested -->
884 <property ... /> <!-- these are what we want -->
885 </property>
886 </repsonse>
887 */
888
889 // Detach all the children so we can insert them into another document.
890 NSXMLElement* parent = (NSXMLElement*)[[response rootElement] childAtIndex:0];
891 NSArray* children = [parent children];
892 [parent setChildren:nil];
893
894 [delegate receivedProperties:children forTransaction:transaction];
895 }
896
897 /**
898 * Callback for setting a breakpoint.
899 */
900 - (void)breakpointReceived:(NSXMLDocument*)response
901 {
902 NSNumber* transaction = [NSNumber numberWithInt:[self transactionIDFromResponse:response]];
903 Breakpoint* bp = [callbackContext_ objectForKey:transaction];
904 if (!bp)
905 return;
906
907 [callbackContext_ removeObjectForKey:callbackContext_];
908 [bp setDebuggerId:[[[[response rootElement] attributeForName:@"id"] stringValue] intValue]];
909 }
910
911 #pragma mark Private
912
913 /**
914 * This will send a command to the debugger engine. It will append the
915 * transaction ID automatically. It accepts a NSString command along with a
916 * a variable number of arguments to substitute into the command, a la
917 * +[NSString stringWithFormat:]. Returns the transaction ID as a NSNumber.
918 */
919 - (NSNumber*)sendCommandWithCallback:(SEL)callback format:(NSString*)format, ...
920 {
921 // Collect varargs and format command.
922 va_list args;
923 va_start(args, format);
924 NSString* command = [[NSString alloc] initWithFormat:format arguments:args];
925 va_end(args);
926
927 NSNumber* callbackKey = [NSNumber numberWithInt:transactionID++];
928 if (callback)
929 [callTable_ setObject:NSStringFromSelector(callback) forKey:callbackKey];
930
931 [self send:[NSString stringWithFormat:@"%@ -i %@", [command autorelease], callbackKey]];
932
933 return callbackKey;
934 }
935
936 /**
937 * Checks if there are unsent commands in the |queuedWrites_| queue and sends
938 * them if it's OK to do so. This will not block.
939 */
940 - (void)sendQueuedWrites
941 {
942 if (!connected)
943 return;
944
945 [writeQueueLock_ lock];
946 if (lastReadTransaction_ >= lastWrittenTransaction_ && [queuedWrites_ count] > 0)
947 {
948 NSString* command = [queuedWrites_ objectAtIndex:0];
949 NSLog(@"Sending queued write: %@", command);
950
951 // We don't want to block because this is called from the main thread.
952 // |-performSend:| busy waits when the stream is not ready. Bail out
953 // before we do that becuase busy waiting is BAD.
954 if (CFWriteStreamCanAcceptBytes(writeStream_))
955 {
956 [self performSend:command];
957 [queuedWrites_ removeObjectAtIndex:0];
958 }
959 }
960 [writeQueueLock_ unlock];
961 }
962
963 /**
964 * Given a file path, this returns a file:// URI and escapes any spaces for the
965 * debugger engine.
966 */
967 - (NSString*)escapedURIPath:(NSString*)path
968 {
969 // Custon GDBp paths are fine.
970 if ([[path substringToIndex:4] isEqualToString:@"gdbp"])
971 return path;
972
973 // Create a temporary URL that will escape all the nasty characters.
974 NSURL* url = [NSURL fileURLWithPath:path];
975 NSString* urlString = [url absoluteString];
976
977 // Remove the host because this is a file:// URL;
978 urlString = [urlString stringByReplacingOccurrencesOfString:[url host] withString:@""];
979
980 // Escape % for use in printf-style NSString formatters.
981 urlString = [urlString stringByReplacingOccurrencesOfString:@"%" withString:@"%%"];
982 return urlString;
983 }
984
985 /**
986 * Returns the transaction_id from an NSXMLDocument.
987 */
988 - (NSInteger)transactionIDFromResponse:(NSXMLDocument*)response
989 {
990 return [[[[response rootElement] attributeForName:@"transaction_id"] stringValue] intValue];
991 }
992
993 @end