More fixes for paths with spaces. We can't use single quotes to pass path names,...
[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 NSString* kErrorOccurredNotif = @"GDBpConnection_ErrorOccured_Notification";
21
22 @interface GDBpConnection()
23 @property(readwrite, copy) NSString* status;
24
25 - (NSString*)createCommand:(NSString*)cmd, ...;
26 - (NSXMLDocument*)processData:(NSString*)data;
27 - (StackFrame*)createStackFrame:(int)depth;
28 - (StackFrame*)createCurrentStackFrame;
29 - (void)updateStatus;
30 - (NSString*)escapedURIPath:(NSString*)path;
31 @end
32
33 @implementation GDBpConnection
34
35 @synthesize socket, status;
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] initWithConnection:self];
51 [socket setDelegate: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:(id)obj
113 {
114 connected = YES;
115 [socket receive];
116 [self updateStatus];
117
118 // register any breakpoints that exist offline
119 for (Breakpoint* bp in [[BreakpointManager sharedManager] breakpoints])
120 {
121 [self addBreakpoint:bp];
122 }
123
124 [[[NSApp delegate] debugger] startDebugger]; // this will just load the debugger to make it look active
125 }
126
127 /**
128 * Receives errors from the SocketWrapper and updates the display
129 */
130 - (void)errorEncountered:(NSString*)error
131 {
132 [[NSNotificationCenter defaultCenter]
133 postNotificationName:kErrorOccurredNotif
134 object:self
135 userInfo:[NSDictionary
136 dictionaryWithObject:error
137 forKey:@"NSString"
138 ]
139 ];
140 }
141
142 /**
143 * Reestablishes communication with the remote debugger so that a new connection doesn't have to be
144 * created every time you want to debug a page
145 */
146 - (void)reconnect
147 {
148 [socket close];
149 self.status = @"Connecting";
150 [socket connect];
151 }
152
153 /**
154 * Creates an entirely new stack and returns it as an array of StackFrame objects.
155 */
156 - (NSArray*)getCurrentStack
157 {
158 // get the total stack depth
159 [socket send:[self createCommand:@"stack_depth"]];
160 NSXMLDocument* doc = [self processData:[socket receive]];
161 int depth = [[[[doc rootElement] attributeForName:@"depth"] stringValue] intValue];
162
163 // get all stack frames
164 NSMutableArray* stack = [NSMutableArray arrayWithCapacity:depth];
165 for (int i = 0; i < depth; i++)
166 {
167 StackFrame* frame = [self createStackFrame:i];
168 [stack insertObject:frame atIndex:i];
169 }
170
171 return stack;
172 }
173
174 /**
175 * Tells the debugger to continue running the script. Returns the current stack frame.
176 */
177 - (void)run
178 {
179 [socket send:[self createCommand:@"run"]];
180 [socket receive];
181
182 [self updateStatus];
183 }
184
185 /**
186 * Tells the debugger to step into the current command.
187 */
188 - (void)stepIn
189 {
190 [socket send:[self createCommand:@"step_into"]];
191 [socket receive];
192
193 [self updateStatus];
194
195 }
196
197 /**
198 * Tells the debugger to step out of the current context
199 */
200 - (void)stepOut
201 {
202 [socket send:[self createCommand:@"step_out"]];
203 [socket receive];
204
205 [self updateStatus];
206 }
207
208 /**
209 * Tells the debugger to step over the current function
210 */
211 - (void)stepOver
212 {
213 [socket send:[self createCommand:@"step_over"]];
214 [socket receive];
215
216 [self updateStatus];
217 }
218
219 /**
220 * Tells the debugger engine to get a specifc property. This also takes in the NSXMLElement
221 * that requested it so that the child can be attached.
222 */
223 - (NSArray*)getProperty:(NSString*)property
224 {
225 [socket send:[self createCommand:[NSString stringWithFormat:@"property_get -n \"%@\"", property]]];
226
227 NSXMLDocument* doc = [self processData:[socket receive]];
228
229 /*
230 <response>
231 <property> <!-- this is the one we requested -->
232 <property ... /> <!-- these are what we want -->
233 </property>
234 </repsonse>
235 */
236
237 // we now have to detach all the children so we can insert them into another document
238 NSXMLElement* parent = (NSXMLElement*)[[doc rootElement] childAtIndex:0];
239 NSArray* children = [parent children];
240 [parent setChildren:nil];
241 return children;
242 }
243
244 #pragma mark Breakpoints
245
246 /**
247 * Send an add breakpoint command
248 */
249 - (void)addBreakpoint:(Breakpoint*)bp
250 {
251 if (!connected)
252 return;
253
254 NSString* file = [self escapedURIPath:[bp transformedPath]];
255 NSString* cmd = [self createCommand:[NSString stringWithFormat:@"breakpoint_set -t line -f %@ -n %i", file, [bp line]]];
256 [socket send:cmd];
257 NSXMLDocument* info = [self processData:[socket receive]];
258 [bp setDebuggerId:[[[[info rootElement] attributeForName:@"id"] stringValue] intValue]];
259 }
260
261 /**
262 * Removes a breakpoint
263 */
264 - (void)removeBreakpoint:(Breakpoint*)bp
265 {
266 if (!connected)
267 {
268 return;
269 }
270
271 [socket send:[self createCommand:[NSString stringWithFormat:@"breakpoint_remove -d %i", [bp debuggerId]]]];
272 [socket receive];
273 }
274
275 #pragma mark Private
276
277 /**
278 * Helper method to create a string command with the -i <session> automatically tacked on. Takes
279 * a variable number of arguments and parses the given command with +[NSString stringWithFormat:]
280 */
281 - (NSString*)createCommand:(NSString*)cmd, ...
282 {
283 // collect varargs
284 va_list argList;
285 va_start(argList, cmd);
286 NSString* format = [[NSString alloc] initWithFormat:cmd arguments:argList]; // format the command
287 va_end(argList);
288
289 #ifdef BLU_DEBUG
290 NSLog(@"--> %@", format);
291 #endif
292
293 return [NSString stringWithFormat:@"%@ -i %@", [format autorelease], session];
294 }
295
296 /**
297 * Helper function to parse the NSData into an NSXMLDocument
298 */
299 - (NSXMLDocument*)processData:(NSString*)data
300 {
301 if (data == nil)
302 return nil;
303
304 NSError* parseError = nil;
305 NSXMLDocument* doc = [[NSXMLDocument alloc] initWithXMLString:data options:0 error:&parseError];
306 if (parseError)
307 {
308 NSLog(@"Could not parse XML? --- %@", parseError);
309 NSLog(@"Error UserInfo: %@", [parseError userInfo]);
310 NSLog(@"This is the XML Document: %@", data);
311 return nil;
312 }
313
314 // check and see if there's an error
315 NSArray* error = [[doc rootElement] elementsForName:@"error"];
316 if ([error count] > 0)
317 {
318 NSLog(@"Xdebug error: %@", error);
319 [self errorEncountered:[[[[error objectAtIndex:0] children] objectAtIndex:0] stringValue]];
320 return nil;
321 }
322
323 #ifdef BLU_DEBUG
324 NSLog(@"<-- %@", doc);
325 #endif
326
327 return [doc autorelease];
328 }
329
330 /**
331 * Generates a stack frame for the given depth
332 */
333 - (StackFrame*)createStackFrame:(int)stackDepth
334 {
335 // get the stack frame
336 [socket send:[self createCommand:@"stack_get -d %d", stackDepth]];
337 NSXMLDocument* doc = [self processData:[socket receive]];
338 if (doc == nil)
339 return nil;
340
341 NSXMLElement* xmlframe = [[[doc rootElement] children] objectAtIndex:0];
342
343 // get the names of all the contexts
344 [socket send:[self createCommand:@"context_names -d 0"]];
345 NSXMLElement* contextNames = [[self processData:[socket receive]] rootElement];
346 NSMutableArray* variables = [NSMutableArray array];
347 for (NSXMLElement* context in [contextNames children])
348 {
349 NSString* name = [[context attributeForName:@"name"] stringValue];
350 int cid = [[[context attributeForName:@"id"] stringValue] intValue];
351
352 // fetch the contexts
353 [socket send:[self createCommand:[NSString stringWithFormat:@"context_get -d %d -c %d", stackDepth, cid]]];
354 NSArray* addVars = [[[self processData:[socket receive]] rootElement] children];
355 if (addVars != nil && name != nil)
356 [variables addObjectsFromArray:addVars];
357 }
358
359 // get the source
360 NSString* filename = [[xmlframe attributeForName:@"filename"] stringValue];
361 NSString* escapedFilename = [filename stringByReplacingOccurrencesOfString:@"%" withString:@"%%"]; // escape % in URL chars
362 [socket send:[self createCommand:[NSString stringWithFormat:@"source -f %@", escapedFilename]]];
363 NSString* source = [[[self processData:[socket receive]] rootElement] value]; // decode base64
364
365 // create stack frame
366 StackFrame* frame = [[StackFrame alloc]
367 initWithIndex:stackDepth
368 withFilename:filename
369 withSource:source
370 atLine:[[[xmlframe attributeForName:@"lineno"] stringValue] intValue]
371 inFunction:[[xmlframe attributeForName:@"where"] stringValue]
372 withVariables:variables
373 ];
374
375 return [frame autorelease];
376 }
377
378 /**
379 * Creates a StackFrame based on the current position in the debugger
380 */
381 - (StackFrame*)createCurrentStackFrame
382 {
383 return [self createStackFrame:0];
384 }
385
386 /**
387 * Fetches the value of and sets the status instance variable
388 */
389 - (void)updateStatus
390 {
391 [socket send:[self createCommand:@"status"]];
392 NSXMLDocument* doc = [self processData:[socket receive]];
393 self.status = [[[[doc rootElement] attributeForName:@"status"] stringValue] capitalizedString];
394
395 if (status == nil || [status isEqualToString:@"Stopped"] || [status isEqualToString:@"Stopping"])
396 {
397 connected = NO;
398 [socket close];
399 self.status = @"Stopped";
400 }
401 }
402
403 /**
404 * Given a file path, this returns a file:// URI and escapes any spaces for the
405 * debugger engine.
406 */
407 - (NSString*)escapedURIPath:(NSString*)path
408 {
409 // Custon GDBp paths are fine.
410 if ([[path substringToIndex:4] isEqualToString:@"gdbp"])
411 return path;
412
413 // Create a temporary URL that will escape all the nasty characters.
414 NSURL* url = [NSURL fileURLWithPath:path];
415 NSString* urlString = [url absoluteString];
416
417 // Remove the host because this is a file:// URL;
418 urlString = [urlString stringByReplacingOccurrencesOfString:[url host] withString:@""];
419
420 // Escape % for use in printf-style NSString formatters.
421 urlString = [urlString stringByReplacingOccurrencesOfString:@"%" withString:@"%%"];
422 return urlString;
423 }
424
425 @end