Remove the |session| ivar from GDBpConnection. Use |transactionID| to keep
[macgdbp.git] / Source / GDBpConnection.m
1 /*
2 * MacGDBp
3 * Copyright (c) 2007 - 2009, 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 "GDBpConnection.h"
18 #import "AppDelegate.h"
19
20 @interface GDBpConnection()
21 @property(readwrite, copy) NSString* status;
22
23 - (NSString*)createCommand:(NSString*)cmd, ...;
24 - (NSXMLDocument*)processData:(NSString*)data;
25 - (StackFrame*)createStackFrame:(int)depth;
26 - (StackFrame*)createCurrentStackFrame;
27 - (void)updateStatus;
28 - (NSString*)escapedURIPath:(NSString*)path;
29 - (void)doSocketAccept:_nil;
30 @end
31
32 @implementation GDBpConnection
33 @synthesize socket;
34 @synthesize status;
35 @synthesize delegate;
36
37 /**
38 * Creates a new DebuggerConnection and initializes the socket from the given connection
39 * paramters.
40 */
41 - (id)initWithPort:(int)aPort
42 {
43 if (self = [super init])
44 {
45 port = aPort;
46 connected = NO;
47
48 // now that we have our host information, open the socket
49 socket = [[SocketWrapper alloc] initWithPort:port];
50 socket.delegate = self;
51 [socket connect];
52
53 self.status = @"Connecting";
54
55 [[BreakpointManager sharedManager] setConnection:self];
56 }
57 return self;
58 }
59
60 /**
61 * Deallocates the object
62 */
63 - (void)dealloc
64 {
65 [socket release];
66 [super dealloc];
67 }
68
69 /**
70 * Gets the port number
71 */
72 - (int)port
73 {
74 return port;
75 }
76
77 /**
78 * Returns the name of the remote host
79 */
80 - (NSString*)remoteHost
81 {
82 if (!connected)
83 {
84 return @"(DISCONNECTED)";
85 }
86 return [socket remoteHost];
87 }
88
89 /**
90 * Returns whether or not we have an active connection
91 */
92 - (BOOL)isConnected
93 {
94 return connected;
95 }
96
97 /**
98 * Called by SocketWrapper after the connection is successful. This immediately calls
99 * -[SocketWrapper receive] to clear the way for communication, though the information
100 * could be useful server information that we don't use right now.
101 */
102 - (void)socketDidAccept
103 {
104 [self performSelectorOnMainThread:@selector(doSocketAccept:) withObject:nil waitUntilDone:YES];
105 }
106
107 /**
108 * Receives errors from the SocketWrapper and updates the display
109 */
110 - (void)errorEncountered:(NSString*)error
111 {
112 [delegate errorEncountered:error];
113 }
114
115 /**
116 * Reestablishes communication with the remote debugger so that a new connection doesn't have to be
117 * created every time you want to debug a page
118 */
119 - (void)reconnect
120 {
121 [socket close];
122 self.status = @"Connecting";
123 [socket connect];
124 }
125
126 /**
127 * Creates an entirely new stack and returns it as an array of StackFrame objects.
128 */
129 - (NSArray*)getCurrentStack
130 {
131 // get the total stack depth
132 [socket send:[self createCommand:@"stack_depth"]];
133 NSXMLDocument* doc = [self processData:[socket receive]];
134 int depth = [[[[doc rootElement] attributeForName:@"depth"] stringValue] intValue];
135
136 // get all stack frames
137 NSMutableArray* stack = [NSMutableArray arrayWithCapacity:depth];
138 for (int i = 0; i < depth; i++)
139 {
140 StackFrame* frame = [self createStackFrame:i];
141 [stack insertObject:frame atIndex:i];
142 }
143
144 return stack;
145 }
146
147 /**
148 * Tells the debugger to continue running the script. Returns the current stack frame.
149 */
150 - (void)run
151 {
152 [socket send:[self createCommand:@"run"]];
153 [socket receive];
154
155 [self updateStatus];
156 }
157
158 /**
159 * Tells the debugger to step into the current command.
160 */
161 - (void)stepIn
162 {
163 [socket send:[self createCommand:@"step_into"]];
164 [socket receive];
165
166 [self updateStatus];
167 }
168
169 /**
170 * Tells the debugger to step out of the current context
171 */
172 - (void)stepOut
173 {
174 [socket send:[self createCommand:@"step_out"]];
175 [socket receive];
176
177 [self updateStatus];
178 }
179
180 /**
181 * Tells the debugger to step over the current function
182 */
183 - (void)stepOver
184 {
185 [socket send:[self createCommand:@"step_over"]];
186 [socket receive];
187
188 [self updateStatus];
189 }
190
191 /**
192 * Tells the debugger engine to get a specifc property. This also takes in the NSXMLElement
193 * that requested it so that the child can be attached.
194 */
195 - (NSArray*)getProperty:(NSString*)property
196 {
197 [socket send:[self createCommand:[NSString stringWithFormat:@"property_get -n \"%@\"", property]]];
198
199 NSXMLDocument* doc = [self processData:[socket receive]];
200
201 /*
202 <response>
203 <property> <!-- this is the one we requested -->
204 <property ... /> <!-- these are what we want -->
205 </property>
206 </repsonse>
207 */
208
209 // we now have to detach all the children so we can insert them into another document
210 NSXMLElement* parent = (NSXMLElement*)[[doc rootElement] childAtIndex:0];
211 NSArray* children = [parent children];
212 [parent setChildren:nil];
213 return children;
214 }
215
216 #pragma mark Breakpoints
217
218 /**
219 * Send an add breakpoint command
220 */
221 - (void)addBreakpoint:(Breakpoint*)bp
222 {
223 if (!connected)
224 return;
225
226 NSString* file = [self escapedURIPath:[bp transformedPath]];
227 NSString* cmd = [self createCommand:[NSString stringWithFormat:@"breakpoint_set -t line -f %@ -n %i", file, [bp line]]];
228 [socket send:cmd];
229 NSXMLDocument* info = [self processData:[socket receive]];
230 [bp setDebuggerId:[[[[info rootElement] attributeForName:@"id"] stringValue] intValue]];
231 }
232
233 /**
234 * Removes a breakpoint
235 */
236 - (void)removeBreakpoint:(Breakpoint*)bp
237 {
238 if (!connected)
239 {
240 return;
241 }
242
243 [socket send:[self createCommand:[NSString stringWithFormat:@"breakpoint_remove -d %i", [bp debuggerId]]]];
244 [socket receive];
245 }
246
247 #pragma mark Private
248
249 /**
250 * Helper method to create a string command with the -i <transaction id> automatically tacked on. Takes
251 * a variable number of arguments and parses the given command with +[NSString stringWithFormat:]
252 */
253 - (NSString*)createCommand:(NSString*)cmd, ...
254 {
255 // collect varargs
256 va_list argList;
257 va_start(argList, cmd);
258 NSString* format = [[NSString alloc] initWithFormat:cmd arguments:argList]; // format the command
259 va_end(argList);
260
261 if ([[[[NSProcessInfo processInfo] environment] objectForKey:@"TransportDebug"] boolValue])
262 NSLog(@"--> %@", cmd);
263
264 return [NSString stringWithFormat:@"%@ -i %d", [format autorelease], transactionID++];
265 }
266
267 /**
268 * Helper function to parse the NSData into an NSXMLDocument
269 */
270 - (NSXMLDocument*)processData:(NSString*)data
271 {
272 if (data == nil)
273 return nil;
274
275 NSError* parseError = nil;
276 NSXMLDocument* doc = [[NSXMLDocument alloc] initWithXMLString:data options:0 error:&parseError];
277 if (parseError)
278 {
279 NSLog(@"Could not parse XML? --- %@", parseError);
280 NSLog(@"Error UserInfo: %@", [parseError userInfo]);
281 NSLog(@"This is the XML Document: %@", data);
282 return nil;
283 }
284
285 // check and see if there's an error
286 NSArray* error = [[doc rootElement] elementsForName:@"error"];
287 if ([error count] > 0)
288 {
289 NSLog(@"Xdebug error: %@", error);
290 [delegate errorEncountered:[[[[error objectAtIndex:0] children] objectAtIndex:0] stringValue]];
291 return nil;
292 }
293
294 if ([[[[NSProcessInfo processInfo] environment] objectForKey:@"TransportDebug"] boolValue])
295 NSLog(@"<-- %@", doc);
296
297 return [doc autorelease];
298 }
299
300 /**
301 * Generates a stack frame for the given depth
302 */
303 - (StackFrame*)createStackFrame:(int)stackDepth
304 {
305 // get the stack frame
306 [socket send:[self createCommand:@"stack_get -d %d", stackDepth]];
307 NSXMLDocument* doc = [self processData:[socket receive]];
308 if (doc == nil)
309 return nil;
310
311 NSXMLElement* xmlframe = [[[doc rootElement] children] objectAtIndex:0];
312
313 // get the names of all the contexts
314 [socket send:[self createCommand:@"context_names -d 0"]];
315 NSXMLElement* contextNames = [[self processData:[socket receive]] rootElement];
316 NSMutableArray* variables = [NSMutableArray array];
317 for (NSXMLElement* context in [contextNames children])
318 {
319 NSString* name = [[context attributeForName:@"name"] stringValue];
320 int cid = [[[context attributeForName:@"id"] stringValue] intValue];
321
322 // fetch the contexts
323 [socket send:[self createCommand:[NSString stringWithFormat:@"context_get -d %d -c %d", stackDepth, cid]]];
324 NSArray* addVars = [[[self processData:[socket receive]] rootElement] children];
325 if (addVars != nil && name != nil)
326 [variables addObjectsFromArray:addVars];
327 }
328
329 // get the source
330 NSString* filename = [[xmlframe attributeForName:@"filename"] stringValue];
331 NSString* escapedFilename = [filename stringByReplacingOccurrencesOfString:@"%" withString:@"%%"]; // escape % in URL chars
332 [socket send:[self createCommand:[NSString stringWithFormat:@"source -f %@", escapedFilename]]];
333 NSString* source = [[[self processData:[socket receive]] rootElement] value]; // decode base64
334
335 // create stack frame
336 StackFrame* frame = [[StackFrame alloc]
337 initWithIndex:stackDepth
338 withFilename:filename
339 withSource:source
340 atLine:[[[xmlframe attributeForName:@"lineno"] stringValue] intValue]
341 inFunction:[[xmlframe attributeForName:@"where"] stringValue]
342 withVariables:variables
343 ];
344
345 return [frame autorelease];
346 }
347
348 /**
349 * Creates a StackFrame based on the current position in the debugger
350 */
351 - (StackFrame*)createCurrentStackFrame
352 {
353 return [self createStackFrame:0];
354 }
355
356 /**
357 * Fetches the value of and sets the status instance variable
358 */
359 - (void)updateStatus
360 {
361 [socket send:[self createCommand:@"status"]];
362 NSXMLDocument* doc = [self processData:[socket receive]];
363 self.status = [[[[doc rootElement] attributeForName:@"status"] stringValue] capitalizedString];
364
365 if (status == nil || [status isEqualToString:@"Stopped"] || [status isEqualToString:@"Stopping"])
366 {
367 connected = NO;
368 [socket close];
369
370 [delegate debuggerDisconnected];
371
372 self.status = @"Stopped";
373 }
374 }
375
376 /**
377 * Given a file path, this returns a file:// URI and escapes any spaces for the
378 * debugger engine.
379 */
380 - (NSString*)escapedURIPath:(NSString*)path
381 {
382 // Custon GDBp paths are fine.
383 if ([[path substringToIndex:4] isEqualToString:@"gdbp"])
384 return path;
385
386 // Create a temporary URL that will escape all the nasty characters.
387 NSURL* url = [NSURL fileURLWithPath:path];
388 NSString* urlString = [url absoluteString];
389
390 // Remove the host because this is a file:// URL;
391 urlString = [urlString stringByReplacingOccurrencesOfString:[url host] withString:@""];
392
393 // Escape % for use in printf-style NSString formatters.
394 urlString = [urlString stringByReplacingOccurrencesOfString:@"%" withString:@"%%"];
395 return urlString;
396 }
397
398 /**
399 * Helper method for |-socketDidAccept| to be called on the main thread.
400 */
401 - (void)doSocketAccept:_nil
402 {
403 connected = YES;
404 transactionID = 0;
405 [socket receive];
406 [self updateStatus];
407
408 // register any breakpoints that exist offline
409 for (Breakpoint* bp in [[BreakpointManager sharedManager] breakpoints])
410 {
411 [self addBreakpoint:bp];
412 }
413
414 // Load the debugger to make it look active.
415 [delegate debuggerConnected];
416 }
417
418 @end