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