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