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