3 * Copyright (c) 2007 - 2010, Blue Static <http://www.bluestatic.org>
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.
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.
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
17 #import <sys/socket.h>
18 #import <netinet/in.h>
20 #import "GDBpConnection.h"
22 #import "AppDelegate.h"
24 // GDBpConnection (Private) ////////////////////////////////////////////////////
26 @interface GDBpConnection ()
27 @property (readwrite
, copy
) NSString
* status
;
28 @property (assign
) CFSocketRef socket
;
29 @property (assign
) CFReadStreamRef readStream
;
30 @property int lastReadTransaction
;
31 @property (retain
) NSMutableString
* currentPacket
;
32 @property (assign
) CFWriteStreamRef writeStream
;
33 @property int lastWrittenTransaction
;
34 @property (retain
) NSMutableArray
* queuedWrites
;
38 - (void)socketDidAccept
;
39 - (void)socketDisconnected
;
40 - (void)readStreamHasData
;
41 - (void)send
:(NSString
*)command
;
42 - (void)performSend
:(NSString
*)command
;
43 - (void)errorEncountered
:(NSString
*)error
;
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
;
55 - (NSNumber
*)sendCommandWithCallback
:(SEL)callback format
:(NSString
*)format
, ...
;
57 - (void)sendQueuedWrites
;
59 - (NSString
*)escapedURIPath
:(NSString
*)path
;
60 - (NSInteger
)transactionIDFromResponse
:(NSXMLDocument
*)response
;
63 // CFNetwork Callbacks /////////////////////////////////////////////////////////
65 void ReadStreamCallback(CFReadStreamRef stream
, CFStreamEventType eventType
, void* connectionRaw
)
67 GDBpConnection
* connection
= (GDBpConnection
*)connectionRaw
;
70 case kCFStreamEventHasBytesAvailable
:
71 NSLog(@
"About to read.");
72 [connection readStreamHasData
];
75 case kCFStreamEventErrorOccurred
:
77 CFErrorRef error
= CFReadStreamCopyError(stream
);
78 CFReadStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
79 CFReadStreamClose(stream
);
81 [connection errorEncountered
:[[(NSError
*)error autorelease
] description
]];
85 case kCFStreamEventEndEncountered
:
86 CFReadStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
87 CFReadStreamClose(stream
);
89 [connection socketDisconnected
];
94 void WriteStreamCallback(CFWriteStreamRef stream
, CFStreamEventType eventType
, void* connectionRaw
)
96 GDBpConnection
* connection
= (GDBpConnection
*)connectionRaw
;
99 case kCFStreamEventCanAcceptBytes
:
100 [connection sendQueuedWrites
];
103 case kCFStreamEventErrorOccurred
:
105 CFErrorRef error
= CFWriteStreamCopyError(stream
);
106 CFWriteStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
107 CFWriteStreamClose(stream
);
109 [connection errorEncountered
:[[(NSError
*)error autorelease
] description
]];
113 case kCFStreamEventEndEncountered
:
114 CFWriteStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
115 CFWriteStreamClose(stream
);
117 [connection socketDisconnected
];
122 void SocketAcceptCallback(CFSocketRef socket
,
123 CFSocketCallBackType callbackType
,
128 assert(callbackType
== kCFSocketAcceptCallBack
);
129 NSLog(@
"SocketAcceptCallback()");
131 GDBpConnection
* connection
= (GDBpConnection
*)connectionRaw
;
133 CFReadStreamRef readStream
;
134 CFWriteStreamRef writeStream
;
136 // Create the streams on the socket.
137 CFStreamCreatePairWithSocket(kCFAllocatorDefault
,
138 *(CFSocketNativeHandle
*)data
, // Socket handle.
139 &readStream
, // Read stream in-pointer.
140 &writeStream
); // Write stream in-pointer.
142 // Create struct to register callbacks for the stream.
143 CFStreamClientContext context
;
145 context.info
= connection
;
146 context.retain
= NULL
;
147 context.release
= NULL
;
148 context.copyDescription
= NULL
;
150 // Set the client of the read stream.
151 CFOptionFlags readFlags
=
152 kCFStreamEventOpenCompleted |
153 kCFStreamEventHasBytesAvailable |
154 kCFStreamEventErrorOccurred |
155 kCFStreamEventEndEncountered
;
156 if (CFReadStreamSetClient(readStream
, readFlags
, ReadStreamCallback
, &context
))
157 // Schedule in run loop to do asynchronous communication with the engine.
158 CFReadStreamScheduleWithRunLoop(readStream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
162 // Open the stream now that it's scheduled on the run loop.
163 if (!CFReadStreamOpen(readStream
))
165 CFStreamError error
= CFReadStreamGetError(readStream
);
166 NSLog(@
"error! %@", error
);
170 // Set the client of the write stream.
171 CFOptionFlags writeFlags
=
172 kCFStreamEventOpenCompleted |
173 kCFStreamEventCanAcceptBytes |
174 kCFStreamEventErrorOccurred |
175 kCFStreamEventEndEncountered
;
176 if (CFWriteStreamSetClient(writeStream
, writeFlags
, WriteStreamCallback
, &context
))
177 // Schedule it in the run loop to receive error information.
178 CFWriteStreamScheduleWithRunLoop(writeStream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
182 // Open the write stream.
183 if (!CFWriteStreamOpen(writeStream
))
185 CFStreamError error
= CFWriteStreamGetError(writeStream
);
186 NSLog(@
"error! %@", error
);
190 connection.readStream
= readStream
;
191 connection.writeStream
= writeStream
;
192 [connection socketDidAccept
];
195 // GDBpConnection //////////////////////////////////////////////////////////////
197 @implementation GDBpConnection
198 @synthesize socket
= socket_
;
199 @synthesize readStream
= readStream_
;
200 @synthesize lastReadTransaction
= lastReadTransaction_
;
201 @synthesize currentPacket
= currentPacket_
;
202 @synthesize writeStream
= writeStream_
;
203 @synthesize lastWrittenTransaction
= lastWrittenTransaction_
;
204 @synthesize queuedWrites
= queuedWrites_
;
206 @synthesize delegate
;
209 * Creates a new DebuggerConnection and initializes the socket from the given connection
212 - (id)initWithPort
:(int)aPort
214 if (self = [super init
])
219 [[BreakpointManager sharedManager
] setConnection
:self];
227 * Deallocates the object
232 self.currentPacket
= nil;
238 * Gets the port number
246 * Returns the name of the remote host
248 - (NSString
*)remoteHost
252 return @
"(DISCONNECTED)";
254 // TODO: Either impl or remove.
259 * Returns whether or not we have an active connection
267 * Called by SocketWrapper after the connection is successful. This immediately calls
268 * -[SocketWrapper receive] to clear the way for communication, though the information
269 * could be useful server information that we don't use right now.
271 - (void)socketDidAccept
275 stackFrames_
= [[NSMutableDictionary alloc
] init
];
276 self.queuedWrites
= [NSMutableArray array
];
277 writeQueueLock_
= [NSRecursiveLock
new];
278 callTable_
= [NSMutableDictionary
new];
279 callbackContext_
= [NSMutableDictionary
new];
283 * Receives errors from the SocketWrapper and updates the display
285 - (void)errorEncountered
:(NSString
*)error
287 [delegate errorEncountered
:error
];
291 * Reestablishes communication with the remote debugger so that a new connection doesn't have to be
292 * created every time you want to debug a page
297 self.status
= @
"Connecting";
302 * Creates an entirely new stack and returns it as an array of StackFrame objects.
304 - (NSArray
*)getCurrentStack
306 NSMutableArray
* stack
= [NSMutableArray array
];
307 NSLog(@
"NOTIMPLEMENTED(): %s", _cmd
);
312 * Tells the debugger to continue running the script. Returns the current stack frame.
316 [self sendCommandWithCallback
:@selector(debuggerStep
:) format
:@
"run"];
320 * Tells the debugger to step into the current command.
324 [self sendCommandWithCallback
:@selector(debuggerStep
:) format
:@
"step_into"];
328 * Tells the debugger to step out of the current context
332 [self sendCommandWithCallback
:@selector(debuggerStep
:) format
:@
"step_out"];
336 * Tells the debugger to step over the current function
340 [self sendCommandWithCallback
:@selector(debuggerStep
:) format
:@
"step_over"];
344 * Tells the debugger engine to get a specifc property. This also takes in the NSXMLElement
345 * that requested it so that the child can be attached.
347 - (NSArray
*)getProperty
:(NSString
*)property
349 [socket send
:[self createCommand
:[NSString stringWithFormat
:@
"property_get -n \"%@\"", property
]]];
351 NSXMLDocument
* doc
= [self processData
:[socket receive
]];
355 <property> <!-- this is the one we requested -->
356 <property ... /> <!-- these are what we want -->
361 // we now have to detach all the children so we can insert them into another document
362 NSXMLElement
* parent
= (NSXMLElement
*)[[doc rootElement
] childAtIndex
:0];
363 NSArray
* children
= [parent children
];
364 [parent setChildren
:nil];
368 #pragma mark Breakpoints
371 * Send an add breakpoint command
373 - (void)addBreakpoint
:(Breakpoint
*)bp
378 NSString
* file
= [self escapedURIPath
:[bp transformedPath
]];
379 NSNumber
* transaction
= [self sendCommandWithCallback
:@selector(breakpointReceived
:)
380 format
:@
"breakpoint_set -t line -f %@ -n %i", file
, [bp line
]];
381 [callbackContext_ setObject
:bp forKey
:transaction
];
385 * Callback for setting a breakpoint.
387 - (void)breakpointReceived
:(NSXMLDocument
*)response
389 NSNumber
* transaction
= [NSNumber numberWithInt
:[self transactionIDFromResponse
:response
]];
390 Breakpoint
* bp
= [callbackContext_ objectForKey
:transaction
];
394 [callbackContext_ removeObjectForKey
:callbackContext_
];
395 [bp setDebuggerId
:[[[[response rootElement
] attributeForName
:@
"id"] stringValue
] intValue
]];
399 * Removes a breakpoint
401 - (void)removeBreakpoint
:(Breakpoint
*)bp
408 [self sendCommandWithCallback
:nil format
:@
"breakpoint_remove -d %i", [bp debuggerId
]];
411 #pragma mark Socket and Stream Callbacks
414 * Creates, connects to, and schedules a CFSocket.
418 // Pass ourselves to the callback so we don't have to use ugly globals.
419 CFSocketContext context
;
422 context.retain
= NULL
;
423 context.release
= NULL
;
424 context.copyDescription
= NULL
;
426 // Create the address structure.
427 struct sockaddr_in address
;
428 memset(&address
, 0, sizeof(address
));
429 address.sin_len
= sizeof(address
);
430 address.sin_family
= AF_INET
;
431 address.sin_port
= htons(port
);
432 address.sin_addr.s_addr
= htonl(INADDR_ANY
);
434 // Create the socket signature.
435 CFSocketSignature signature
;
436 signature.protocolFamily
= PF_INET
;
437 signature.socketType
= SOCK_STREAM
;
438 signature.protocol
= IPPROTO_TCP
;
439 signature.address
= (CFDataRef
)[NSData dataWithBytes
:&address length
:sizeof(address
)];
441 socket_
= CFSocketCreateWithSocketSignature(kCFAllocatorDefault
,
442 &signature
, // Socket signature.
443 kCFSocketAcceptCallBack
, // Callback types.
444 SocketAcceptCallback
, // Callout function pointer.
445 &context
); // Context to pass to callout.
448 [self errorEncountered
:@
"Could not open socket."];
452 // Allow old, yet-to-be recycled sockets to be reused.
454 setsockopt(CFSocketGetNative(socket_
), SOL_SOCKET
, SO_REUSEADDR
, &yes
, sizeof(BOOL));
456 // Schedule the socket on the run loop.
457 CFRunLoopSourceRef source
= CFSocketCreateRunLoopSource(kCFAllocatorDefault
, socket_
, 0);
458 CFRunLoopAddSource(CFRunLoopGetCurrent(), source
, kCFRunLoopCommonModes
);
461 self.status
= @
"Connecting";
465 * Closes a socket and releases the ref.
469 // The socket goes down, so do the streams, which clean themselves up.
470 CFSocketInvalidate(socket_
);
472 [stackFrames_ release
];
473 self.queuedWrites
= nil;
474 [writeQueueLock_ release
];
475 [callTable_ release
];
476 [callbackContext_ release
];
480 * Notification that the socket disconnected.
482 - (void)socketDisconnected
485 [delegate debuggerDisconnected
];
489 * Callback from the CFReadStream that there is data waiting to be read.
491 - (void)readStreamHasData
494 CFIndex bytesRead
= CFReadStreamRead(readStream_
, buffer
, 1024);
495 const char* charBuffer
= (const char*)buffer
;
497 // We haven't finished reading a packet, so just read more data in.
498 if (currentPacketIndex_
< packetSize_
)
500 currentPacketIndex_
+= bytesRead
;
501 CFStringRef bufferString
= CFStringCreateWithBytes(kCFAllocatorDefault
,
504 kCFStringEncodingUTF8
,
506 [self.currentPacket appendString
:(NSString
*)bufferString
];
507 CFRelease(bufferString
);
509 // Time to read a new packet.
512 // Read the message header: the size.
513 packetSize_
= atoi(charBuffer
);
514 currentPacketIndex_
= bytesRead
- strlen(charBuffer
);
515 CFStringRef bufferString
= CFStringCreateWithBytes(kCFAllocatorDefault
,
516 buffer
+ strlen(charBuffer
) + 1,
517 bytesRead
- strlen(charBuffer
) - 1,
518 kCFStringEncodingUTF8
,
520 self.currentPacket
= [NSMutableString stringWithString
:(NSString
*)bufferString
];
521 CFRelease(bufferString
);
524 // We have finished reading the packet.
525 if (currentPacketIndex_
>= packetSize_
)
528 currentPacketIndex_
= 0;
530 // Test if we can convert it into an NSXMLDocument.
531 NSError
* error
= nil;
532 NSXMLDocument
* xmlTest
= [[NSXMLDocument alloc
] initWithXMLString
:currentPacket_ options
:NSXMLDocumentTidyXML error
:&error
];
535 NSLog(@
"Could not parse XML? --- %@", error
);
536 NSLog(@
"Error UserInfo: %@", [error userInfo
]);
537 NSLog(@
"This is the XML Document: %@", currentPacket_
);
540 [self handleResponse
:[xmlTest autorelease
]];
545 * Writes a command into the write stream. If the stream is ready for writing,
546 * we do so immediately. If not, the command is queued and will be written
547 * when the stream is ready.
549 - (void)send
:(NSString
*)command
551 if (lastReadTransaction_
>= lastWrittenTransaction_
&& CFWriteStreamCanAcceptBytes(writeStream_
))
552 [self performSend
:command
];
554 [queuedWrites_ addObject
:command
];
558 * This performs a blocking send. This should ONLY be called when we know we
559 * have write access to the stream. We will busy wait in case we don't do a full
562 - (void)performSend
:(NSString
*)command
566 char* string
= (char*)[command UTF8String
];
567 int stringLength
= strlen(string
);
569 // Log the command if TransportDebug is enabled.
570 if ([[[[NSProcessInfo processInfo
] environment
] objectForKey
:@
"TransportDebug"] boolValue
])
571 NSLog(@
"--> %@", command
);
573 // Busy wait while writing. BAADD. Should background this operation.
576 if (CFWriteStreamCanAcceptBytes(writeStream_
))
578 // Include the NULL byte in the string when we write.
579 int bytesWritten
= CFWriteStreamWrite(writeStream_
, (UInt8
*)string
, stringLength
+ 1);
580 if (bytesWritten
< 0)
582 NSLog(@
"write error");
585 else if (bytesWritten
< strlen(string
))
587 // Adjust the buffer and wait for another chance to write.
588 stringLength
-= bytesWritten
;
589 memmove(string
, string
+ bytesWritten
, stringLength
);
595 // We need to scan the string to find the transactionID.
596 NSRange occurrence
= [command rangeOfString
:@
"-i "];
597 if (occurrence.location
== NSNotFound
)
599 NSLog(@
"sent %@ without a transaction ID", command
);
602 NSString
* transaction
= [command substringFromIndex
:occurrence.location
+ occurrence.length
];
603 lastWrittenTransaction_
= [transaction intValue
];
604 NSLog(@
"command = %@", command
);
605 NSLog(@
"read=%d, write=%d", lastReadTransaction_
, lastWrittenTransaction_
);
611 #pragma mark Response Handlers
613 - (void)handleResponse
:(NSXMLDocument
*)response
615 // Check and see if there's an error.
616 NSArray
* error
= [[response rootElement
] elementsForName
:@
"error"];
617 if ([error count
] > 0)
619 NSLog(@
"Xdebug error: %@", error
);
620 [delegate errorEncountered
:[[[[error objectAtIndex
:0] children
] objectAtIndex
:0] stringValue
]];
623 // If TransportDebug is enabled, log the response.
624 if ([[[[NSProcessInfo processInfo
] environment
] objectForKey
:@
"TransportDebug"] boolValue
])
625 NSLog(@
"<-- %@", response
);
627 // Get the name of the command from the engine's response.
628 NSInteger transaction
= [self transactionIDFromResponse
:response
];
629 if (transaction
< lastReadTransaction_
)
630 NSLog(@
"out of date transaction %@", response
);
632 if (transaction
!= lastWrittenTransaction_
)
633 NSLog(@
"txn doesn't match last written %@", response
);
635 lastReadTransaction_
= transaction
;
636 NSLog(@
"read=%d, write=%d", lastReadTransaction_
, lastWrittenTransaction_
);
638 if ([[[response rootElement
] name
] isEqualToString
:@
"init"])
640 [self initReceived
:response
];
644 NSString
* callbackStr
= [callTable_ objectForKey
:[NSNumber numberWithInt
:lastReadTransaction_
]];
647 SEL callback
= NSSelectorFromString(callbackStr
);
648 [self performSelector
:callback withObject
:response
];
651 [self sendQueuedWrites
];
655 * Initial packet received. We've started a brand-new connection to the engine.
657 - (void)initReceived
:(NSXMLDocument
*)response
659 // Register any breakpoints that exist offline.
660 for (Breakpoint
* bp
in [[BreakpointManager sharedManager
] breakpoints
])
661 [self addBreakpoint
:bp
];
663 // Load the debugger to make it look active.
664 [delegate debuggerConnected
];
666 // TODO: update the status.
670 * Receiver for status updates. This just freshens up the UI.
672 - (void)updateStatus
:(NSXMLDocument
*)response
674 self.status
= [[[[response rootElement
] attributeForName
:@
"status"] stringValue
] capitalizedString
];
675 if (status
== nil ||
[status isEqualToString
:@
"Stopped"] ||
[status isEqualToString
:@
"Stopping"])
679 [delegate debuggerDisconnected
];
681 self.status
= @
"Stopped";
686 * Step in/out/over and run all take this path. We first get the status of the
687 * debugger and then request fresh stack information.
689 - (void)debuggerStep
:(NSXMLDocument
*)response
691 [self sendCommandWithCallback
:@selector(updateStatus
:) format
:@
"status"];
692 NSString
* command
= [[[response rootElement
] attributeForName
:@
"command"] stringValue
];
694 // If this is the run command, tell the delegate that a bunch of updates
695 // are coming. Also remove all existing stack routes and request a new stack.
696 // TODO: figure out if we can not clobber the stack every time.
697 if (YES ||
[command isEqualToString
:@
"run"])
699 if ([delegate respondsToSelector
:@selector(clobberStack
)])
700 [delegate clobberStack
];
701 [stackFrames_ removeAllObjects
];
702 stackFirstTransactionID_
= [[self sendCommandWithCallback
:@selector(rebuildStack
:) format
:@
"stack_depth"] intValue
];
707 * We ask for the stack_depth and now we clobber the stack and start rebuilding
710 - (void)rebuildStack
:(NSXMLDocument
*)response
712 NSInteger depth
= [[[[response rootElement
] attributeForName
:@
"depth"] stringValue
] intValue
];
714 if (stackFirstTransactionID_
== [self transactionIDFromResponse
:response
])
717 // We now need to alloc a bunch of stack frames and get the basic information
719 for (NSInteger i
= 0; i
< depth
; i
++)
721 // Use the transaction ID to create a routing path.
722 NSNumber
* routingID
= [self sendCommandWithCallback
:@selector(getStackFrame
:) format
:@
"stack_get -d %d", i
];
723 [stackFrames_ setObject
:[StackFrame alloc
] forKey
:routingID
];
728 * The initial rebuild of the stack frame. We now have enough to initialize
729 * a StackFrame object.
731 - (void)getStackFrame
:(NSXMLDocument
*)response
733 // Get the routing information.
734 NSInteger routingID
= [self transactionIDFromResponse
:response
];
735 if (routingID
< stackFirstTransactionID_
)
737 NSNumber
* routingNumber
= [NSNumber numberWithInt
:routingID
];
739 // Make sure we initialized this frame in our last |-rebuildStack:|.
740 StackFrame
* frame
= [stackFrames_ objectForKey
:routingNumber
];
744 NSXMLElement
* xmlframe
= [[[response rootElement
] children
] objectAtIndex
:0];
746 // Initialize the stack frame.
747 [frame initWithIndex
:[[[xmlframe attributeForName
:@
"level"] stringValue
] intValue
]
748 withFilename
:[[xmlframe attributeForName
:@
"filename"] stringValue
]
750 atLine
:[[[xmlframe attributeForName
:@
"lineno"] stringValue
] intValue
]
751 inFunction
:[[xmlframe attributeForName
:@
"where"] stringValue
]
754 // Get the source code of the file. Escape % in URL chars.
755 NSString
* escapedFilename
= [frame.filename stringByReplacingOccurrencesOfString
:@
"%" withString
:@
"%%"];
756 NSNumber
* transaction
= [self sendCommandWithCallback
:@selector(setSource
:) format
:@
"source -f %@", escapedFilename
];
757 [callbackContext_ setObject
:routingNumber forKey
:transaction
];
759 // Get the names of all the contexts.
760 transaction
= [self sendCommandWithCallback
:@selector(contextsReceived
:) format
:@
"context_names -d %d", frame.index
];
761 [callbackContext_ setObject
:routingNumber forKey
:transaction
];
763 if ([delegate respondsToSelector
:@selector(newStackFrame
:)])
764 [delegate newStackFrame
:frame
];
768 * Callback for setting the source of a file while rebuilding a specific stack
771 - (void)setSource
:(NSXMLDocument
*)response
773 NSNumber
* transaction
= [NSNumber numberWithInt
:[self transactionIDFromResponse
:response
]];
774 if ([transaction intValue
] < stackFirstTransactionID_
)
776 NSNumber
* routingNumber
= [callbackContext_ objectForKey
:transaction
];
780 [callbackContext_ removeObjectForKey
:transaction
];
781 StackFrame
* frame
= [stackFrames_ objectForKey
:routingNumber
];
785 frame.source
= [[response rootElement
] value
];
787 if ([delegate respondsToSelector
:@selector(sourceUpdated
:)])
788 [delegate sourceUpdated
:frame
];
792 * Enumerates all the contexts of a given stack frame. We then in turn get the
793 * contents of each one of these contexts.
795 - (void)contextsReceived
:(NSXMLDocument
*)response
797 // Get the stack frame's routing ID and use it again.
798 NSNumber
* receivedTransaction
= [NSNumber numberWithInt
:[self transactionIDFromResponse
:response
]];
799 if ([receivedTransaction intValue
] < stackFirstTransactionID_
)
801 NSNumber
* routingID
= [callbackContext_ objectForKey
:receivedTransaction
];
805 // Get the stack frame by the |routingID|.
806 StackFrame
* frame
= [stackFrames_ objectForKey
:routingID
];
808 NSXMLElement
* contextNames
= [response rootElement
];
809 for (NSXMLElement
* context
in [contextNames children
])
811 NSInteger cid
= [[[context attributeForName
:@
"id"] stringValue
] intValue
];
813 // Fetch each context's variables.
814 NSNumber
* transaction
= [self sendCommandWithCallback
:@selector(variablesReceived
:)
815 format
:@
"context_get -d %d -c %d", frame.index
, cid
];
816 [callbackContext_ setObject
:routingID forKey
:transaction
];
821 * Receives the variables from the context and attaches them to the stack frame.
823 - (void)variablesReceived
:(NSXMLDocument
*)response
825 // Get the stack frame's routing ID and use it again.
826 NSInteger transaction
= [self transactionIDFromResponse
:response
];
827 if (transaction
< stackFirstTransactionID_
)
829 NSNumber
* receivedTransaction
= [NSNumber numberWithInt
:transaction
];
830 NSNumber
* routingID
= [callbackContext_ objectForKey
:receivedTransaction
];
834 // Get the stack frame by the |routingID|.
835 StackFrame
* frame
= [stackFrames_ objectForKey
:routingID
];
837 NSMutableArray
* variables
= [NSMutableArray array
];
839 // Merge the frame's existing variables.
841 [variables addObjectsFromArray
:frame.variables
];
843 // Add these new variables.
844 NSArray
* addVariables
= [[response rootElement
] children
];
846 [variables addObjectsFromArray
:addVariables
];
848 frame.variables
= variables
;
854 * This will send a command to the debugger engine. It will append the
855 * transaction ID automatically. It accepts a NSString command along with a
856 * a variable number of arguments to substitute into the command, a la
857 * +[NSString stringWithFormat:]. Returns the transaction ID as a NSNumber.
859 - (NSNumber
*)sendCommandWithCallback
:(SEL)callback format
:(NSString
*)format
, ...
861 // Collect varargs and format command.
863 va_start(args
, format
);
864 NSString
* command
= [[NSString alloc
] initWithFormat
:format arguments
:args
];
867 NSNumber
* callbackKey
= [NSNumber numberWithInt
:transactionID
++];
869 [callTable_ setObject
:NSStringFromSelector(callback
) forKey
:callbackKey
];
871 [self send
:[NSString stringWithFormat
:@
"%@ -i %@", [command autorelease
], callbackKey
]];
877 * Checks if there are unsent commands in the |queuedWrites_| queue and sends
878 * them if it's OK to do so. This will not block.
880 - (void)sendQueuedWrites
882 [writeQueueLock_ lock
];
883 if (lastReadTransaction_
>= lastWrittenTransaction_
&& [queuedWrites_ count
] > 0)
885 NSString
* command
= [queuedWrites_ objectAtIndex
:0];
886 NSLog(@
"Sending queued write: %@", command
);
888 // We don't want to block because this is called from the main thread.
889 // |-performSend:| busy waits when the stream is not ready. Bail out
890 // before we do that becuase busy waiting is BAD.
891 if (CFWriteStreamCanAcceptBytes(writeStream_
))
893 [self performSend
:command
];
894 [queuedWrites_ removeObjectAtIndex
:0];
897 [writeQueueLock_ unlock
];
901 * Given a file path, this returns a file:// URI and escapes any spaces for the
904 - (NSString
*)escapedURIPath
:(NSString
*)path
906 // Custon GDBp paths are fine.
907 if ([[path substringToIndex
:4] isEqualToString
:@
"gdbp"])
910 // Create a temporary URL that will escape all the nasty characters.
911 NSURL
* url
= [NSURL fileURLWithPath
:path
];
912 NSString
* urlString
= [url absoluteString
];
914 // Remove the host because this is a file:// URL;
915 urlString
= [urlString stringByReplacingOccurrencesOfString
:[url host
] withString
:@
""];
917 // Escape % for use in printf-style NSString formatters.
918 urlString
= [urlString stringByReplacingOccurrencesOfString
:@
"%" withString
:@
"%%"];
923 * Returns the transaction_id from an NSXMLDocument.
925 - (NSInteger
)transactionIDFromResponse
:(NSXMLDocument
*)response
927 return [[[[response rootElement
] attributeForName
:@
"transaction_id"] stringValue
] intValue
];