Hook up the Evaluate button
[macgdbp.git] / Source / NetworkConnection.mm
1 /*
2 * MacGDBp
3 * Copyright (c) 2007 - 2011, 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 "NetworkConnection.h"
18 #import "NetworkConnectionPrivate.h"
19
20 #import "AppDelegate.h"
21 #import "LoggingController.h"
22 #include "NetworkCallbackController.h"
23
24 // Other Run Loop Callbacks ////////////////////////////////////////////////////
25
26 void PerformQuitSignal(void* info)
27 {
28 NetworkConnection* obj = (NetworkConnection*)info;
29 [obj performQuitSignal];
30 }
31
32 ////////////////////////////////////////////////////////////////////////////////
33
34 @implementation NetworkConnection
35
36 @synthesize port = port_;
37 @synthesize connected = connected_;
38 @synthesize delegate = delegate_;
39
40 @synthesize readStream = readStream_;
41 @synthesize lastReadTransaction = lastReadTransaction_;
42 @synthesize currentPacket = currentPacket_;
43 @synthesize writeStream = writeStream_;
44 @synthesize lastWrittenTransaction = lastWrittenTransaction_;
45 @synthesize queuedWrites = queuedWrites_;
46
47 - (id)initWithPort:(NSUInteger)aPort
48 {
49 if (self = [super init]) {
50 port_ = aPort;
51 }
52 return self;
53 }
54
55 - (void)dealloc
56 {
57 self.currentPacket = nil;
58 [super dealloc];
59 }
60
61 /**
62 * Kicks off the socket on another thread.
63 */
64 - (void)connect
65 {
66 if (thread_ && !connected_) {
67 // A thread has been detached but the socket has yet to connect. Do not
68 // spawn a new thread otherwise multiple threads will be blocked on the same
69 // socket.
70 return;
71 }
72 [NSThread detachNewThreadSelector:@selector(runNetworkThread) toTarget:self withObject:nil];
73 }
74
75 /**
76 * Creates, connects to, and schedules a CFSocket.
77 */
78 - (void)runNetworkThread
79 {
80 NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
81
82 thread_ = [NSThread currentThread];
83 runLoop_ = [NSRunLoop currentRunLoop];
84 callbackController_ = new NetworkCallbackController(self);
85
86 // Create a source that is used to quit.
87 CFRunLoopSourceContext quitContext = { 0 };
88 quitContext.info = self;
89 quitContext.perform = PerformQuitSignal;
90 quitSource_ = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &quitContext);
91 CFRunLoopAddSource([runLoop_ getCFRunLoop], quitSource_, kCFRunLoopCommonModes);
92
93 callbackController_->OpenConnection(port_);
94
95 CFRunLoopRun();
96
97 thread_ = nil;
98 runLoop_ = nil;
99 delete callbackController_;
100 callbackController_ = NULL;
101
102 CFRunLoopSourceInvalidate(quitSource_);
103 CFRelease(quitSource_);
104 quitSource_ = NULL;
105
106 [pool release];
107 }
108
109 /**
110 * Called by SocketWrapper after the connection is successful. This immediately calls
111 * -[SocketWrapper receive] to clear the way for communication, though the information
112 * could be useful server information that we don't use right now.
113 */
114 - (void)socketDidAccept
115 {
116 connected_ = YES;
117 transactionID = 1;
118 lastReadTransaction_ = 0;
119 lastWrittenTransaction_ = 0;
120 self.queuedWrites = [NSMutableArray array];
121 writeQueueLock_ = [NSRecursiveLock new];
122 if ([delegate_ respondsToSelector:@selector(connectionDidAccept:)])
123 [delegate_ performSelectorOnMainThread:@selector(connectionDidAccept:)
124 withObject:self
125 waitUntilDone:NO];
126 }
127
128 /**
129 * Closes a socket and releases the ref.
130 */
131 - (void)close
132 {
133 if (thread_) {
134 [thread_ cancel];
135 }
136 if (runLoop_ && quitSource_) {
137 CFRunLoopSourceSignal(quitSource_);
138 CFRunLoopWakeUp([runLoop_ getCFRunLoop]);
139 }
140 }
141
142 /**
143 * Quits the run loop and stops the thread.
144 */
145 - (void)performQuitSignal
146 {
147 self.queuedWrites = nil;
148 connected_ = NO;
149 [writeQueueLock_ release];
150
151 if (runLoop_) {
152 CFRunLoopStop([runLoop_ getCFRunLoop]);
153 }
154
155 callbackController_->CloseConnection();
156 }
157
158 /**
159 * Notification that the socket disconnected.
160 */
161 - (void)socketDisconnected
162 {
163 if ([delegate_ respondsToSelector:@selector(connectionDidClose:)])
164 [delegate_ connectionDidClose:self];
165 }
166
167 /**
168 * Writes a command into the write stream. If the stream is ready for writing,
169 * we do so immediately. If not, the command is queued and will be written
170 * when the stream is ready.
171 */
172 - (void)send:(NSString*)command
173 {
174 if (lastReadTransaction_ >= lastWrittenTransaction_ && CFWriteStreamCanAcceptBytes(writeStream_)) {
175 [self performSend:command];
176 } else {
177 [writeQueueLock_ lock];
178 [queuedWrites_ addObject:command];
179 [writeQueueLock_ unlock];
180 }
181 [self sendQueuedWrites];
182 }
183
184 /**
185 * This will send a command to the debugger engine. It will append the
186 * transaction ID automatically. It accepts a NSString command along with a
187 * a variable number of arguments to substitute into the command, a la
188 * +[NSString stringWithFormat:]. Returns the transaction ID as a NSNumber.
189 */
190 - (NSNumber*)sendCommandWithFormat:(NSString*)format, ...
191 {
192 // Collect varargs and format command.
193 va_list args;
194 va_start(args, format);
195 NSString* command = [[NSString alloc] initWithFormat:format arguments:args];
196 va_end(args);
197
198 NSNumber* callbackKey = [NSNumber numberWithInt:transactionID++];
199 NSString* taggedCommand = [NSString stringWithFormat:@"%@ -i %@", [command autorelease], callbackKey];
200 [self performSelector:@selector(send:)
201 onThread:thread_
202 withObject:taggedCommand
203 waitUntilDone:connected_];
204
205 return callbackKey;
206 }
207
208 /**
209 * Given a file path, this returns a file:// URI and escapes any spaces for the
210 * debugger engine.
211 */
212 - (NSString*)escapedURIPath:(NSString*)path
213 {
214 // Custon GDBp paths are fine.
215 if ([[path substringToIndex:4] isEqualToString:@"gdbp"])
216 return path;
217
218 // Create a temporary URL that will escape all the nasty characters.
219 NSURL* url = [NSURL fileURLWithPath:path];
220 NSString* urlString = [url absoluteString];
221
222 // Remove the host because this is a file:// URL;
223 urlString = [urlString stringByReplacingOccurrencesOfString:[url host] withString:@""];
224
225 // Escape % for use in printf-style NSString formatters.
226 urlString = [urlString stringByReplacingOccurrencesOfString:@"%" withString:@"%%"];
227 return urlString;
228 }
229
230 /**
231 * Returns the transaction_id from an NSXMLDocument.
232 */
233 - (NSInteger)transactionIDFromResponse:(NSXMLDocument*)response
234 {
235 return [[[[response rootElement] attributeForName:@"transaction_id"] stringValue] intValue];
236 }
237
238 /**
239 * Scans a command string for the transaction ID component. If it is not found,
240 * returns NSNotFound.
241 */
242 - (NSInteger)transactionIDFromCommand:(NSString*)command
243 {
244 NSRange occurrence = [command rangeOfString:@"-i "];
245 if (occurrence.location == NSNotFound)
246 return NSNotFound;
247 NSString* transaction = [command substringFromIndex:occurrence.location + occurrence.length];
248 return [transaction intValue];
249 }
250
251 // Private /////////////////////////////////////////////////////////////////////
252 #pragma mark Private
253
254 // Delegate Thread-Safe Wrappers ///////////////////////////////////////////////
255
256 /**
257 * Receives errors from the SocketWrapper and updates the display
258 */
259 - (void)errorEncountered:(NSString*)error
260 {
261 if (![delegate_ respondsToSelector:@selector(errorEncountered:)])
262 return;
263 [delegate_ performSelectorOnMainThread:@selector(errorEncountered:)
264 withObject:error
265 waitUntilDone:NO];
266 }
267
268 - (LogEntry*)recordSend:(NSString*)command
269 {
270 LoggingController* logger = [[AppDelegate instance] loggingController];
271 LogEntry* entry = [LogEntry newSendEntry:command];
272 entry.lastReadTransactionID = lastReadTransaction_;
273 entry.lastWrittenTransactionID = lastWrittenTransaction_;
274 [logger performSelectorOnMainThread:@selector(recordEntry:)
275 withObject:entry
276 waitUntilDone:NO];
277 return [entry autorelease];
278 }
279
280 - (LogEntry*)recordReceive:(NSString*)command
281 {
282 LoggingController* logger = [[AppDelegate instance] loggingController];
283 LogEntry* entry = [LogEntry newReceiveEntry:command];
284 entry.lastReadTransactionID = lastReadTransaction_;
285 entry.lastWrittenTransactionID = lastWrittenTransaction_;
286 [logger performSelectorOnMainThread:@selector(recordEntry:)
287 withObject:entry
288 waitUntilDone:NO];
289 return [entry autorelease];
290 }
291
292 // Stream Managers /////////////////////////////////////////////////////////////
293
294 /**
295 * Callback from the CFReadStream that there is data waiting to be read.
296 */
297 - (void)readStreamHasData
298 {
299 const NSUInteger kBufferSize = 1024;
300 UInt8 buffer[kBufferSize];
301 CFIndex bufferOffset = 0; // Starting point in |buffer| to work with.
302 CFIndex bytesRead = CFReadStreamRead(readStream_, buffer, kBufferSize);
303 const char* charBuffer = (const char*)buffer;
304
305 // The read loop works by going through the buffer until all the bytes have
306 // been processed.
307 while (bufferOffset < bytesRead) {
308 // Find the NULL separator, or the end of the string.
309 NSUInteger partLength = 0;
310 for (CFIndex i = bufferOffset; i < bytesRead && charBuffer[i] != '\0'; ++i, ++partLength) ;
311
312 // If there is not a current packet, set some state.
313 if (!self.currentPacket) {
314 // Read the message header: the size. This will be |partLength| bytes.
315 packetSize_ = atoi(charBuffer + bufferOffset);
316 currentPacketIndex_ = 0;
317 self.currentPacket = [NSMutableString stringWithCapacity:packetSize_];
318 bufferOffset += partLength + 1; // Pass over the NULL byte.
319 continue; // Spin the loop to begin reading actual data.
320 }
321
322 // Substring the byte stream and append it to the packet string.
323 CFStringRef bufferString = CFStringCreateWithBytes(kCFAllocatorDefault,
324 buffer + bufferOffset, // Byte pointer, offset by start index.
325 partLength, // Length.
326 kCFStringEncodingUTF8,
327 true);
328 [self.currentPacket appendString:(NSString*)bufferString];
329 CFRelease(bufferString);
330
331 // Advance counters.
332 currentPacketIndex_ += partLength;
333 bufferOffset += partLength + 1;
334
335 // If this read finished the packet, handle it and reset.
336 if (currentPacketIndex_ >= packetSize_) {
337 [self handlePacket:[[currentPacket_ retain] autorelease]];
338 self.currentPacket = nil;
339 packetSize_ = 0;
340 currentPacketIndex_ = 0;
341 }
342 }
343 }
344
345 /**
346 * Performs the packet handling of a raw string XML packet. From this point on,
347 * the packets are associated with a transaction and are then dispatched.
348 */
349 - (void)handlePacket:(NSString*)packet
350 {
351 // Test if we can convert it into an NSXMLDocument.
352 NSError* error = nil;
353 NSXMLDocument* xml = [[NSXMLDocument alloc] initWithXMLString:currentPacket_
354 options:NSXMLDocumentTidyXML
355 error:&error];
356 // TODO: Remove this assert before stable release. Flush out any possible
357 // issues during testing.
358 assert(xml);
359
360 // Validate the transaction.
361 NSInteger transaction = [self transactionIDFromResponse:xml];
362 if (transaction < lastReadTransaction_) {
363 NSLog(@"Transaction #%d is out of date (lastRead = %d). Dropping packet: %@",
364 transaction, lastReadTransaction_, packet);
365 return;
366 }
367 if (transaction != lastWrittenTransaction_) {
368 NSLog(@"Transaction #%d received out of order. lastRead = %d, lastWritten = %d. Continuing.",
369 transaction, lastReadTransaction_, lastWrittenTransaction_);
370 }
371
372 lastReadTransaction_ = transaction;
373
374 // Log this receive event.
375 LogEntry* log = [self recordReceive:currentPacket_];
376 log.error = error;
377
378 // Finally, dispatch the handler for this response.
379 [self handleResponse:[xml autorelease]];
380 }
381
382 - (void)handleResponse:(NSXMLDocument*)response
383 {
384 // Check and see if there's an error.
385 NSArray* error = [[response rootElement] elementsForName:@"error"];
386 if ([error count] > 0) {
387 NSLog(@"Xdebug error: %@", error);
388 NSString* errorMessage = [[[[error objectAtIndex:0] children] objectAtIndex:0] stringValue];
389 [self errorEncountered:errorMessage];
390 }
391
392 if ([[[response rootElement] name] isEqualToString:@"init"]) {
393 connected_ = YES;
394 [delegate_ performSelectorOnMainThread:@selector(handleInitialResponse:)
395 withObject:response
396 waitUntilDone:NO];
397 return;
398 }
399
400 if ([delegate_ respondsToSelector:@selector(handleResponse:)])
401 [delegate_ performSelectorOnMainThread:@selector(handleResponse:)
402 withObject:response
403 waitUntilDone:NO];
404
405 [self sendQueuedWrites];
406 }
407
408 /**
409 * This performs a blocking send. This should ONLY be called when we know we
410 * have write access to the stream. We will busy wait in case we don't do a full
411 * send.
412 */
413 - (void)performSend:(NSString*)command
414 {
415 // If this is an out-of-date transaction, do not bother sending it.
416 NSInteger transaction = [self transactionIDFromCommand:command];
417 if (transaction != NSNotFound && transaction < lastWrittenTransaction_)
418 return;
419
420 BOOL done = NO;
421
422 char* string = (char*)[command UTF8String];
423 size_t stringLength = strlen(string);
424
425 // Busy wait while writing. BAADD. Should background this operation.
426 while (!done) {
427 if (CFWriteStreamCanAcceptBytes(writeStream_)){
428 // Include the NULL byte in the string when we write.
429 CFIndex bytesWritten = CFWriteStreamWrite(writeStream_, (UInt8*)string, stringLength + 1);
430 if (bytesWritten < 0) {
431 CFErrorRef error = CFWriteStreamCopyError(writeStream_);
432 NSLog(@"Write stream error: %@", error);
433 CFRelease(error);
434 }
435 // Incomplete write.
436 else if (bytesWritten < static_cast<CFIndex>(strlen(string))) {
437 // Adjust the buffer and wait for another chance to write.
438 stringLength -= bytesWritten;
439 memmove(string, string + bytesWritten, stringLength);
440 }
441 else {
442 done = YES;
443 // We need to scan the string to find the transactionID.
444 if (transaction == NSNotFound) {
445 NSLog(@"sent %@ without a transaction ID", command);
446 continue;
447 }
448 lastWrittenTransaction_ = transaction;
449 }
450 }
451 }
452
453 // Log this trancation.
454 [self recordSend:command];
455 }
456
457 /**
458 * Checks if there are unsent commands in the |queuedWrites_| queue and sends
459 * them if it's OK to do so. This will not block.
460 */
461 - (void)sendQueuedWrites
462 {
463 if (!connected_)
464 return;
465
466 [writeQueueLock_ lock];
467 if (lastReadTransaction_ >= lastWrittenTransaction_ && [queuedWrites_ count] > 0) {
468 NSString* command = [queuedWrites_ objectAtIndex:0];
469
470 // We don't want to block because this is called from the main thread.
471 // |-performSend:| busy waits when the stream is not ready. Bail out
472 // before we do that becuase busy waiting is BAD.
473 if (CFWriteStreamCanAcceptBytes(writeStream_)) {
474 [self performSend:command];
475 [queuedWrites_ removeObjectAtIndex:0];
476 }
477 }
478 [writeQueueLock_ unlock];
479 }
480
481 @end