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