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