3 * Copyright (c) 2007 - 2009, 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 (retain
) NSMutableString
* currentPacket
;
31 @property (assign
) CFWriteStreamRef writeStream
;
35 - (void)socketDidAccept
;
36 - (void)socketDisconnected
;
37 - (void)readStreamHasData
;
38 - (void)send
:(NSString
*)command
;
39 - (void)errorEncountered
:(NSString
*)error
;
41 - (NSString
*)createCommand
:(NSString
*)cmd
, ...
;
42 - (NSXMLDocument
*)processData
:(NSString
*)data
;
43 - (StackFrame
*)createStackFrame
:(int)depth
;
44 - (StackFrame
*)createCurrentStackFrame
;
46 - (NSString
*)escapedURIPath
:(NSString
*)path
;
47 - (void)doSocketAccept
:_nil
;
50 // CFNetwork Callbacks /////////////////////////////////////////////////////////
52 void ReadStreamCallback(CFReadStreamRef stream
, CFStreamEventType eventType
, void* connectionRaw
)
54 NSLog(@
"ReadStreamCallback()");
55 GDBpConnection
* connection
= (GDBpConnection
*)connectionRaw
;
58 case kCFStreamEventHasBytesAvailable
:
59 [connection readStreamHasData
];
62 case kCFStreamEventErrorOccurred
:
64 CFErrorRef error
= CFReadStreamCopyError(stream
);
65 CFReadStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
66 CFReadStreamClose(stream
);
68 [connection errorEncountered
:[[(NSError
*)error autorelease
] description
]];
72 case kCFStreamEventEndEncountered
:
73 CFReadStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
74 CFReadStreamClose(stream
);
76 [connection socketDisconnected
];
81 void WriteStreamCallback(CFWriteStreamRef stream
, CFStreamEventType eventType
, void* connectionRaw
)
83 NSLog(@
"WriteStreamCallback()");
84 GDBpConnection
* connection
= (GDBpConnection
*)connectionRaw
;
87 case kCFStreamEventErrorOccurred
:
89 CFErrorRef error
= CFWriteStreamCopyError(stream
);
90 CFWriteStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
91 CFWriteStreamClose(stream
);
93 [connection errorEncountered
:[[(NSError
*)error autorelease
] description
]];
97 case kCFStreamEventEndEncountered
:
98 CFWriteStreamUnscheduleFromRunLoop(stream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
99 CFWriteStreamClose(stream
);
101 [connection socketDisconnected
];
106 void SocketAcceptCallback(CFSocketRef socket
,
107 CFSocketCallBackType callbackType
,
112 assert(callbackType
== kCFSocketAcceptCallBack
);
113 NSLog(@
"SocketAcceptCallback()");
115 GDBpConnection
* connection
= (GDBpConnection
*)connectionRaw
;
117 CFReadStreamRef readStream
;
118 CFWriteStreamRef writeStream
;
120 // Create the streams on the socket.
121 CFStreamCreatePairWithSocket(kCFAllocatorDefault
,
122 *(CFSocketNativeHandle
*)data
, // Socket handle.
123 &readStream
, // Read stream in-pointer.
124 &writeStream
); // Write stream in-pointer.
126 // Create struct to register callbacks for the stream.
127 CFStreamClientContext context
;
129 context.info
= connection
;
130 context.retain
= NULL
;
131 context.release
= NULL
;
132 context.copyDescription
= NULL
;
134 // Set the client of the read stream.
135 CFOptionFlags readFlags
=
136 kCFStreamEventOpenCompleted |
137 kCFStreamEventHasBytesAvailable |
138 kCFStreamEventErrorOccurred |
139 kCFStreamEventEndEncountered
;
140 if (CFReadStreamSetClient(readStream
, readFlags
, ReadStreamCallback
, &context
))
141 // Schedule in run loop to do asynchronous communication with the engine.
142 CFReadStreamScheduleWithRunLoop(readStream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
146 NSLog(@
"Read stream scheduled");
148 // Open the stream now that it's scheduled on the run loop.
149 if (!CFReadStreamOpen(readStream
))
151 CFStreamError error
= CFReadStreamGetError(readStream
);
152 NSLog(@
"error! %@", error
);
156 NSLog(@
"Read stream opened");
158 // Set the client of the write stream.
159 CFOptionFlags writeFlags
=
160 kCFStreamEventOpenCompleted |
161 kCFStreamEventErrorOccurred |
162 kCFStreamEventEndEncountered
;
163 if (CFWriteStreamSetClient(writeStream
, writeFlags
, WriteStreamCallback
, &context
))
164 // Schedule it in the run loop to receive error information.
165 CFWriteStreamScheduleWithRunLoop(writeStream
, CFRunLoopGetCurrent(), kCFRunLoopCommonModes
);
169 NSLog(@
"Write stream scheduled");
171 // Open the write stream.
172 if (!CFWriteStreamOpen(writeStream
))
174 CFStreamError error
= CFWriteStreamGetError(writeStream
);
175 NSLog(@
"error! %@", error
);
179 NSLog(@
"Write stream opened");
181 connection.readStream
= readStream
;
182 connection.writeStream
= writeStream
;
183 [connection socketDidAccept
];
186 // GDBpConnection //////////////////////////////////////////////////////////////
188 @implementation GDBpConnection
189 @synthesize socket
= socket_
;
190 @synthesize readStream
= readStream_
;
191 @synthesize currentPacket
= currentPacket_
;
192 @synthesize writeStream
= writeStream_
;
194 @synthesize delegate
;
197 * Creates a new DebuggerConnection and initializes the socket from the given connection
200 - (id)initWithPort
:(int)aPort
202 if (self = [super init
])
207 [[BreakpointManager sharedManager
] setConnection
:self];
215 * Deallocates the object
220 self.currentPacket
= nil;
226 * Gets the port number
234 * Returns the name of the remote host
236 - (NSString
*)remoteHost
240 return @
"(DISCONNECTED)";
242 // TODO: Either impl or remove.
247 * Returns whether or not we have an active connection
255 * Called by SocketWrapper after the connection is successful. This immediately calls
256 * -[SocketWrapper receive] to clear the way for communication, though the information
257 * could be useful server information that we don't use right now.
259 - (void)socketDidAccept
261 [self performSelectorOnMainThread
:@selector(doSocketAccept
:) withObject
:nil waitUntilDone
:YES
];
265 * Receives errors from the SocketWrapper and updates the display
267 - (void)errorEncountered
:(NSString
*)error
269 [delegate errorEncountered
:error
];
273 * Reestablishes communication with the remote debugger so that a new connection doesn't have to be
274 * created every time you want to debug a page
279 self.status
= @
"Connecting";
284 * Creates an entirely new stack and returns it as an array of StackFrame objects.
286 - (NSArray
*)getCurrentStack
288 // get the total stack depth
289 [socket send
:[self createCommand
:@
"stack_depth"]];
290 NSXMLDocument
* doc
= [self processData
:[socket receive
]];
291 int depth
= [[[[doc rootElement
] attributeForName
:@
"depth"] stringValue
] intValue
];
293 // get all stack frames
294 NSMutableArray
* stack
= [NSMutableArray arrayWithCapacity
:depth
];
295 for (int i
= 0; i
< depth
; i
++)
297 StackFrame
* frame
= [self createStackFrame
:i
];
298 [stack insertObject
:frame atIndex
:i
];
305 * Tells the debugger to continue running the script. Returns the current stack frame.
309 [socket send
:[self createCommand
:@
"run"]];
316 * Tells the debugger to step into the current command.
320 [socket send
:[self createCommand
:@
"step_into"]];
327 * Tells the debugger to step out of the current context
331 [socket send
:[self createCommand
:@
"step_out"]];
338 * Tells the debugger to step over the current function
342 [socket send
:[self createCommand
:@
"step_over"]];
349 * Tells the debugger engine to get a specifc property. This also takes in the NSXMLElement
350 * that requested it so that the child can be attached.
352 - (NSArray
*)getProperty
:(NSString
*)property
354 [socket send
:[self createCommand
:[NSString stringWithFormat
:@
"property_get -n \"%@\"", property
]]];
356 NSXMLDocument
* doc
= [self processData
:[socket receive
]];
360 <property> <!-- this is the one we requested -->
361 <property ... /> <!-- these are what we want -->
366 // we now have to detach all the children so we can insert them into another document
367 NSXMLElement
* parent
= (NSXMLElement
*)[[doc rootElement
] childAtIndex
:0];
368 NSArray
* children
= [parent children
];
369 [parent setChildren
:nil];
373 #pragma mark Breakpoints
376 * Send an add breakpoint command
378 - (void)addBreakpoint
:(Breakpoint
*)bp
383 NSString
* file
= [self escapedURIPath
:[bp transformedPath
]];
384 NSString
* cmd
= [self createCommand
:[NSString stringWithFormat
:@
"breakpoint_set -t line -f %@ -n %i", file
, [bp line
]]];
386 NSXMLDocument
* info
= [self processData
:[socket receive
]];
387 [bp setDebuggerId
:[[[[info rootElement
] attributeForName
:@
"id"] stringValue
] intValue
]];
391 * Removes a breakpoint
393 - (void)removeBreakpoint
:(Breakpoint
*)bp
400 [socket send
:[self createCommand
:[NSString stringWithFormat
:@
"breakpoint_remove -d %i", [bp debuggerId
]]]];
407 * Creates, connects to, and schedules a CFSocket.
411 // Pass ourselves to the callback so we don't have to use ugly globals.
412 CFSocketContext context
;
415 context.retain
= NULL
;
416 context.release
= NULL
;
417 context.copyDescription
= NULL
;
419 // Create the address structure.
420 struct sockaddr_in address
;
421 memset(&address
, 0, sizeof(address
));
422 address.sin_len
= sizeof(address
);
423 address.sin_family
= AF_INET
;
424 address.sin_port
= htons(port
);
425 address.sin_addr.s_addr
= htonl(INADDR_ANY
);
427 // Create the socket signature.
428 CFSocketSignature signature
;
429 signature.protocolFamily
= PF_INET
;
430 signature.socketType
= SOCK_STREAM
;
431 signature.protocol
= IPPROTO_TCP
;
432 signature.address
= (CFDataRef
)[NSData dataWithBytes
:&address length
:sizeof(address
)];
434 socket_
= CFSocketCreateWithSocketSignature(kCFAllocatorDefault
,
435 &signature
, // Socket signature.
436 kCFSocketAcceptCallBack
, // Callback types.
437 SocketAcceptCallback
, // Callout function pointer.
438 &context
); // Context to pass to callout.
441 [self errorEncountered
:@
"Could not open socket."];
445 // Allow old, yet-to-be recycled sockets to be reused.
447 setsockopt(CFSocketGetNative(socket_
), SOL_SOCKET
, SO_REUSEADDR
, &yes
, sizeof(BOOL));
449 // Schedule the socket on the run loop.
450 CFRunLoopSourceRef source
= CFSocketCreateRunLoopSource(kCFAllocatorDefault
, socket_
, 0);
451 CFRunLoopAddSource(CFRunLoopGetCurrent(), source
, kCFRunLoopCommonModes
);
454 self.status
= @
"Connecting";
458 * Closes a socket and releases the ref.
462 // The socket goes down, so do the streams, which clean themselves up.
463 CFSocketInvalidate(socket_
);
468 * Notification that the socket disconnected.
470 - (void)socketDisconnected
473 [delegate debuggerDisconnected
];
477 * Callback from the CFReadStream that there is data waiting to be read.
479 - (void)readStreamHasData
482 CFIndex bytesRead
= CFReadStreamRead(readStream_
, buffer
, 1024);
483 const char* charBuffer
= (const char*)buffer
;
485 // We haven't finished reading a packet, so just read more data in.
486 if (currentPacketIndex_
< packetSize_
)
488 [currentPacket_ appendFormat
:@
"%s", buffer
];
489 currentPacketIndex_
+= bytesRead
;
491 // Time to read a new packet.
494 // Read the message header: the size.
495 packetSize_
= atoi(charBuffer
);
496 currentPacketIndex_
= bytesRead
- strlen(charBuffer
);
497 self.currentPacket
= [NSMutableString stringWithFormat
:@
"%s", buffer
+ strlen(charBuffer
) + 1];
500 // We have finished reading the packet.
501 if (currentPacketIndex_
>= packetSize_
)
504 currentPacketIndex_
= 0;
506 // Test if we can convert it into an NSXMLDocument.
507 NSError
* error
= nil;
508 NSXMLDocument
* xmlTest
= [[NSXMLDocument alloc
] initWithXMLString
:currentPacket_ options
:NSXMLDocumentTidyXML error
:&error
];
510 NSLog(@
"FAILED XML TEST: %@", error
);
516 * Writes a command into the write stream. This does use blocking IO.
518 - (void)send
:(NSString
*)command
522 char* string
= (char*)[command UTF8String
];
523 int stringLength
= strlen(string
);
525 // Busy wait while writing. BAADD. Should background this operation.
528 if (CFWriteStreamCanAcceptBytes(writeStream_
))
530 // Include the NULL byte in the string when we write.
531 int bytesWritten
= CFWriteStreamWrite(writeStream_
, (UInt8
*)string
, stringLength
+ 1);
532 if (bytesWritten
< 0)
534 NSLog(@
"write error");
537 else if (bytesWritten
< strlen(string
))
539 // Adjust the buffer and wait for another chance to write.
540 stringLength
-= bytesWritten
;
541 memmove(string
, string
+ bytesWritten
, stringLength
);
552 * Helper method to create a string command with the -i <transaction id> automatically tacked on. Takes
553 * a variable number of arguments and parses the given command with +[NSString stringWithFormat:]
555 - (NSString
*)createCommand
:(NSString
*)cmd
, ...
559 va_start(argList
, cmd
);
560 NSString
* format
= [[NSString alloc
] initWithFormat
:cmd arguments
:argList
]; // format the command
563 if ([[[[NSProcessInfo processInfo
] environment
] objectForKey
:@
"TransportDebug"] boolValue
])
564 NSLog(@
"--> %@", cmd
);
566 return [NSString stringWithFormat
:@
"%@ -i %d", [format autorelease
], transactionID
++];
570 * Helper function to parse the NSData into an NSXMLDocument
572 - (NSXMLDocument
*)processData
:(NSString
*)data
577 NSError
* parseError
= nil;
578 NSXMLDocument
* doc
= [[NSXMLDocument alloc
] initWithXMLString
:data options
:0 error
:&parseError
];
581 NSLog(@
"Could not parse XML? --- %@", parseError
);
582 NSLog(@
"Error UserInfo: %@", [parseError userInfo
]);
583 NSLog(@
"This is the XML Document: %@", data
);
587 // check and see if there's an error
588 NSArray
* error
= [[doc rootElement
] elementsForName
:@
"error"];
589 if ([error count
] > 0)
591 NSLog(@
"Xdebug error: %@", error
);
592 [delegate errorEncountered
:[[[[error objectAtIndex
:0] children
] objectAtIndex
:0] stringValue
]];
596 if ([[[[NSProcessInfo processInfo
] environment
] objectForKey
:@
"TransportDebug"] boolValue
])
597 NSLog(@
"<-- %@", doc
);
599 return [doc autorelease
];
603 * Generates a stack frame for the given depth
605 - (StackFrame
*)createStackFrame
:(int)stackDepth
607 // get the stack frame
608 [socket send
:[self createCommand
:@
"stack_get -d %d", stackDepth
]];
609 NSXMLDocument
* doc
= [self processData
:[socket receive
]];
613 NSXMLElement
* xmlframe
= [[[doc rootElement
] children
] objectAtIndex
:0];
615 // get the names of all the contexts
616 [socket send
:[self createCommand
:@
"context_names -d 0"]];
617 NSXMLElement
* contextNames
= [[self processData
:[socket receive
]] rootElement
];
618 NSMutableArray
* variables
= [NSMutableArray array
];
619 for (NSXMLElement
* context
in [contextNames children
])
621 NSString
* name
= [[context attributeForName
:@
"name"] stringValue
];
622 int cid
= [[[context attributeForName
:@
"id"] stringValue
] intValue
];
624 // fetch the contexts
625 [socket send
:[self createCommand
:[NSString stringWithFormat
:@
"context_get -d %d -c %d", stackDepth
, cid
]]];
626 NSArray
* addVars
= [[[self processData
:[socket receive
]] rootElement
] children
];
627 if (addVars
!= nil && name
!= nil)
628 [variables addObjectsFromArray
:addVars
];
632 NSString
* filename
= [[xmlframe attributeForName
:@
"filename"] stringValue
];
633 NSString
* escapedFilename
= [filename stringByReplacingOccurrencesOfString
:@
"%" withString
:@
"%%"]; // escape % in URL chars
634 [socket send
:[self createCommand
:[NSString stringWithFormat
:@
"source -f %@", escapedFilename
]]];
635 NSString
* source
= [[[self processData
:[socket receive
]] rootElement
] value
]; // decode base64
637 // create stack frame
638 StackFrame
* frame
= [[StackFrame alloc
]
639 initWithIndex
:stackDepth
640 withFilename
:filename
642 atLine
:[[[xmlframe attributeForName
:@
"lineno"] stringValue
] intValue
]
643 inFunction
:[[xmlframe attributeForName
:@
"where"] stringValue
]
644 withVariables
:variables
647 return [frame autorelease
];
651 * Creates a StackFrame based on the current position in the debugger
653 - (StackFrame
*)createCurrentStackFrame
655 return [self createStackFrame
:0];
659 * Fetches the value of and sets the status instance variable
663 [socket send
:[self createCommand
:@
"status"]];
664 NSXMLDocument
* doc
= [self processData
:[socket receive
]];
665 self.status
= [[[[doc rootElement
] attributeForName
:@
"status"] stringValue
] capitalizedString
];
667 if (status
== nil ||
[status isEqualToString
:@
"Stopped"] ||
[status isEqualToString
:@
"Stopping"])
672 [delegate debuggerDisconnected
];
674 self.status
= @
"Stopped";
679 * Given a file path, this returns a file:// URI and escapes any spaces for the
682 - (NSString
*)escapedURIPath
:(NSString
*)path
684 // Custon GDBp paths are fine.
685 if ([[path substringToIndex
:4] isEqualToString
:@
"gdbp"])
688 // Create a temporary URL that will escape all the nasty characters.
689 NSURL
* url
= [NSURL fileURLWithPath
:path
];
690 NSString
* urlString
= [url absoluteString
];
692 // Remove the host because this is a file:// URL;
693 urlString
= [urlString stringByReplacingOccurrencesOfString
:[url host
] withString
:@
""];
695 // Escape % for use in printf-style NSString formatters.
696 urlString
= [urlString stringByReplacingOccurrencesOfString
:@
"%" withString
:@
"%%"];
701 * Helper method for |-socketDidAccept| to be called on the main thread.
703 - (void)doSocketAccept
:_nil
710 // register any breakpoints that exist offline
711 for (Breakpoint
* bp
in [[BreakpointManager sharedManager
] breakpoints
])
713 [self addBreakpoint
:bp
];
716 // Load the debugger to make it look active.
717 [delegate debuggerConnected
];