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