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