Make the transport logging an environmental setting.
[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 if ([[[[NSProcessInfo processInfo] environment] objectForKey:@"TransportDebug"] boolValue])
272 NSLog(@"--> %@", cmd);
273
274 return [NSString stringWithFormat:@"%@ -i %@", [format autorelease], session];
275 }
276
277 /**
278 * Helper function to parse the NSData into an NSXMLDocument
279 */
280 - (NSXMLDocument*)processData:(NSString*)data
281 {
282 if (data == nil)
283 return nil;
284
285 NSError* parseError = nil;
286 NSXMLDocument* doc = [[NSXMLDocument alloc] initWithXMLString:data options:0 error:&parseError];
287 if (parseError)
288 {
289 NSLog(@"Could not parse XML? --- %@", parseError);
290 NSLog(@"Error UserInfo: %@", [parseError userInfo]);
291 NSLog(@"This is the XML Document: %@", data);
292 return nil;
293 }
294
295 // check and see if there's an error
296 NSArray* error = [[doc rootElement] elementsForName:@"error"];
297 if ([error count] > 0)
298 {
299 NSLog(@"Xdebug error: %@", error);
300 [delegate errorEncountered:[[[[error objectAtIndex:0] children] objectAtIndex:0] stringValue]];
301 return nil;
302 }
303
304 if ([[[[NSProcessInfo processInfo] environment] objectForKey:@"TransportDebug"] boolValue])
305 NSLog(@"<-- %@", doc);
306
307 return [doc autorelease];
308 }
309
310 /**
311 * Generates a stack frame for the given depth
312 */
313 - (StackFrame*)createStackFrame:(int)stackDepth
314 {
315 // get the stack frame
316 [socket send:[self createCommand:@"stack_get -d %d", stackDepth]];
317 NSXMLDocument* doc = [self processData:[socket receive]];
318 if (doc == nil)
319 return nil;
320
321 NSXMLElement* xmlframe = [[[doc rootElement] children] objectAtIndex:0];
322
323 // get the names of all the contexts
324 [socket send:[self createCommand:@"context_names -d 0"]];
325 NSXMLElement* contextNames = [[self processData:[socket receive]] rootElement];
326 NSMutableArray* variables = [NSMutableArray array];
327 for (NSXMLElement* context in [contextNames children])
328 {
329 NSString* name = [[context attributeForName:@"name"] stringValue];
330 int cid = [[[context attributeForName:@"id"] stringValue] intValue];
331
332 // fetch the contexts
333 [socket send:[self createCommand:[NSString stringWithFormat:@"context_get -d %d -c %d", stackDepth, cid]]];
334 NSArray* addVars = [[[self processData:[socket receive]] rootElement] children];
335 if (addVars != nil && name != nil)
336 [variables addObjectsFromArray:addVars];
337 }
338
339 // get the source
340 NSString* filename = [[xmlframe attributeForName:@"filename"] stringValue];
341 NSString* escapedFilename = [filename stringByReplacingOccurrencesOfString:@"%" withString:@"%%"]; // escape % in URL chars
342 [socket send:[self createCommand:[NSString stringWithFormat:@"source -f %@", escapedFilename]]];
343 NSString* source = [[[self processData:[socket receive]] rootElement] value]; // decode base64
344
345 // create stack frame
346 StackFrame* frame = [[StackFrame alloc]
347 initWithIndex:stackDepth
348 withFilename:filename
349 withSource:source
350 atLine:[[[xmlframe attributeForName:@"lineno"] stringValue] intValue]
351 inFunction:[[xmlframe attributeForName:@"where"] stringValue]
352 withVariables:variables
353 ];
354
355 return [frame autorelease];
356 }
357
358 /**
359 * Creates a StackFrame based on the current position in the debugger
360 */
361 - (StackFrame*)createCurrentStackFrame
362 {
363 return [self createStackFrame:0];
364 }
365
366 /**
367 * Fetches the value of and sets the status instance variable
368 */
369 - (void)updateStatus
370 {
371 [socket send:[self createCommand:@"status"]];
372 NSXMLDocument* doc = [self processData:[socket receive]];
373 self.status = [[[[doc rootElement] attributeForName:@"status"] stringValue] capitalizedString];
374
375 if (status == nil || [status isEqualToString:@"Stopped"] || [status isEqualToString:@"Stopping"])
376 {
377 connected = NO;
378 [socket close];
379
380 [delegate debuggerDisconnected];
381
382 self.status = @"Stopped";
383 }
384 }
385
386 /**
387 * Given a file path, this returns a file:// URI and escapes any spaces for the
388 * debugger engine.
389 */
390 - (NSString*)escapedURIPath:(NSString*)path
391 {
392 // Custon GDBp paths are fine.
393 if ([[path substringToIndex:4] isEqualToString:@"gdbp"])
394 return path;
395
396 // Create a temporary URL that will escape all the nasty characters.
397 NSURL* url = [NSURL fileURLWithPath:path];
398 NSString* urlString = [url absoluteString];
399
400 // Remove the host because this is a file:// URL;
401 urlString = [urlString stringByReplacingOccurrencesOfString:[url host] withString:@""];
402
403 // Escape % for use in printf-style NSString formatters.
404 urlString = [urlString stringByReplacingOccurrencesOfString:@"%" withString:@"%%"];
405 return urlString;
406 }
407
408 /**
409 * Helper method for |-socketDidAccept| to be called on the main thread.
410 */
411 - (void)doSocketAccept:_nil
412 {
413 connected = YES;
414 [socket receive];
415 [self updateStatus];
416
417 // register any breakpoints that exist offline
418 for (Breakpoint* bp in [[BreakpointManager sharedManager] breakpoints])
419 {
420 [self addBreakpoint:bp];
421 }
422
423 // Load the debugger to make it look active.
424 [delegate debuggerConnected];
425 }
426
427 @end