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