-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNSConnection.m
More file actions
4039 lines (3582 loc) · 105 KB
/
NSConnection.m
File metadata and controls
4039 lines (3582 loc) · 105 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** Implementation of connection object for remote object messaging
Copyright (C) 1994-2017 Free Software Foundation, Inc.
Created by: Andrew Kachites McCallum <mccallum@gnu.ai.mit.edu>
Date: July 1994
Minor rewrite for OPENSTEP by: Richard Frith-Macdonald <rfm@gnu.org>
Date: August 1997
Major rewrite for MACOSX by: Richard Frith-Macdonald <rfm@gnu.org>
Date: 2000
This file is part of the GNUstep Base Library.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110 USA.
<title>NSConnection class reference</title>
$Date$ $Revision$
*/
#import "common.h"
#if !defined (__GNU_LIBOBJC__)
# include <objc/encoding.h>
#endif
#define GS_NSConnection_IVARS \
BOOL _isValid; \
BOOL _independentQueueing; \
BOOL _authenticateIn; \
BOOL _authenticateOut; \
BOOL _multipleThreads; \
BOOL _shuttingDown; \
BOOL _useKeepalive; \
BOOL _keepaliveWait; \
NSPort *_receivePort; \
NSPort *_sendPort; \
unsigned _requestDepth; \
unsigned _messageCount; \
unsigned _reqOutCount; \
unsigned _reqInCount; \
unsigned _repOutCount; \
unsigned _repInCount; \
GSIMapTable _localObjects; \
GSIMapTable _localTargets; \
GSIMapTable _remoteProxies; \
GSIMapTable _replyMap; \
NSTimeInterval _replyTimeout; \
NSTimeInterval _requestTimeout; \
NSMutableArray *_requestModes; \
NSMutableArray *_runLoops; \
NSMutableArray *_requestQueue; \
id _delegate; \
NSRecursiveLock *_refGate; \
NSMutableArray *_cachedDecoders; \
NSMutableArray *_cachedEncoders; \
NSString *_remoteName; \
NSString *_registeredName; \
NSPortNameServer *_nameServer; \
int _lastKeepalive
#define EXPOSE_NSDistantObject_IVARS 1
#ifdef HAVE_MALLOC_H
#if !defined(__OpenBSD__)
#include <malloc.h>
#endif
#endif
#ifdef HAVE_ALLOCA_H
#include <alloca.h>
#endif
#import "Foundation/NSEnumerator.h"
#import "GNUstepBase/GSLock.h"
/* Skip past an argument and also any offset information before the next.
*/
static inline const char *
skip_argspec(const char *ptr)
{
if (ptr != NULL)
{
ptr = NSGetSizeAndAlignment(ptr, NULL, NULL);
if (*ptr == '+') ptr++;
while (isdigit(*ptr)) ptr++;
}
return ptr;
}
/*
* Setup for inline operation of pointer map tables.
*/
#define GSI_MAP_KTYPES GSUNION_PTR | GSUNION_OBJ | GSUNION_NSINT
#define GSI_MAP_VTYPES GSUNION_PTR | GSUNION_OBJ
#define GSI_MAP_RETAIN_KEY(M, X)
#define GSI_MAP_RELEASE_KEY(M, X)
#define GSI_MAP_RETAIN_VAL(M, X)
#define GSI_MAP_RELEASE_VAL(M, X)
#define GSI_MAP_HASH(M, X) ((X).nsu ^ ((X).nsu >> 3))
#define GSI_MAP_EQUAL(M, X,Y) ((X).ptr == (Y).ptr)
#define GSI_MAP_NOCLEAN 1
#include "GNUstepBase/GSIMap.h"
#define _IN_CONNECTION_M
#import "Foundation/NSConnection.h"
#undef _IN_CONNECTION_M
#import "Foundation/NSPortCoder.h"
#import "GNUstepBase/DistributedObjects.h"
#import "Foundation/NSHashTable.h"
#import "Foundation/NSMapTable.h"
#import "Foundation/NSData.h"
#import "Foundation/NSRunLoop.h"
#import "Foundation/NSArray.h"
#import "Foundation/NSDictionary.h"
#import "Foundation/NSValue.h"
#import "Foundation/NSDate.h"
#import "Foundation/NSException.h"
#import "Foundation/NSLock.h"
#import "Foundation/NSThread.h"
#import "Foundation/NSPort.h"
#import "Foundation/NSPortMessage.h"
#import "Foundation/NSPortNameServer.h"
#import "Foundation/NSNotification.h"
#import "GSInvocation.h"
#import "GSPortPrivate.h"
#import "GSPrivate.h"
static inline NSRunLoop *
GSRunLoopForThread(NSThread *aThread)
{
GSRunLoopThreadInfo *info = GSRunLoopInfoForThread(aThread);
if (info == nil || info->loop == nil)
{
if (aThread == nil || aThread == GSCurrentThread())
{
return [NSRunLoop currentRunLoop];
}
return nil;
}
return info->loop;
}
@interface NSPortCoder (Private)
- (NSMutableArray*) _components;
@end
@interface NSPortMessage (Private)
- (NSMutableArray*) _components;
@end
@interface NSConnection (GNUstepExtensions)
- (void) finalize;
- (void) forwardInvocation: (NSInvocation *)inv
forProxy: (NSDistantObject*)object;
- (const char *) typeForSelector: (SEL)sel remoteTarget: (unsigned)target;
@end
#define GS_F_LOCK(X) \
{NSDebugFLLog(@"GSConnection",@"Lock %@",X);[X lock];}
#define GS_F_UNLOCK(X) \
{NSDebugFLLog(@"GSConnection",@"Unlock %@",X);[X unlock];}
#define GS_M_LOCK(X) \
{NSDebugMLLog(@"GSConnection",@"Lock %@",X);[X lock];}
#define GSM_UNLOCK(X) \
{NSDebugMLLog(@"GSConnection",@"Unlock %@",X);[X unlock];}
/*
* Cache various class pointers.
*/
static id dummyObject;
static Class connectionClass;
static Class dateClass;
static Class distantObjectClass;
static Class sendCoderClass;
static Class recvCoderClass;
static Class runLoopClass;
static NSString*
stringFromMsgType(int type)
{
switch (type)
{
case METHOD_REQUEST:
return @"method request";
case METHOD_REPLY:
return @"method reply";
case ROOTPROXY_REQUEST:
return @"root proxy request";
case ROOTPROXY_REPLY:
return @"root proxy reply";
case CONNECTION_SHUTDOWN:
return @"connection shutdown";
case METHODTYPE_REQUEST:
return @"methodtype request";
case METHODTYPE_REPLY:
return @"methodtype reply";
case PROXY_RELEASE:
return @"proxy release";
case PROXY_RETAIN:
return @"proxy retain";
case RETAIN_REPLY:
return @"retain replay";
default:
return @"unknown operation type!";
}
}
/*
* CachedLocalObject is a trivial class to keep track of local
* proxies which have been removed from their connections and
* need to persist a while in case another process needs them.
*/
@interface CachedLocalObject : NSObject
{
NSDistantObject *obj;
int time;
}
- (BOOL) countdown;
- (NSDistantObject*) obj;
+ (id) newWithObject: (NSDistantObject*)o time: (int)t;
@end
@implementation CachedLocalObject
+ (id) newWithObject: (NSDistantObject*)o time: (int)t
{
CachedLocalObject *item;
item = (CachedLocalObject*)NSAllocateObject(self, 0, NSDefaultMallocZone());
item->obj = RETAIN(o);
item->time = t;
return item;
}
- (void) dealloc
{
RELEASE(obj);
[super dealloc];
}
- (BOOL) countdown
{
if (time-- > 0)
return YES;
return NO;
}
- (NSDistantObject*) obj
{
return obj;
}
@end
/** <ignore> */
#define GSInternal NSConnectionInternal
#include "GSInternal.h"
GS_PRIVATE_INTERNAL(NSConnection)
#define IisValid (internal->_isValid)
#define IindependentQueueing (internal->_independentQueueing)
#define IauthenticateIn (internal->_authenticateIn)
#define IauthenticateOut (internal->_authenticateOut)
#define ImultipleThreads (internal->_multipleThreads)
#define IshuttingDown (internal->_shuttingDown)
#define IuseKeepalive (internal->_useKeepalive)
#define IkeepaliveWait (internal->_keepaliveWait)
#define IreceivePort (internal->_receivePort)
#define IsendPort (internal->_sendPort)
#define IrequestDepth (internal->_requestDepth)
#define ImessageCount (internal->_messageCount)
#define IreqOutCount (internal->_reqOutCount)
#define IreqInCount (internal->_reqInCount)
#define IrepOutCount (internal->_repOutCount)
#define IrepInCount (internal->_repInCount)
#define IlocalObjects (internal->_localObjects)
#define IlocalTargets (internal->_localTargets)
#define IremoteProxies (internal->_remoteProxies)
#define IreplyMap (internal->_replyMap)
#define IreplyTimeout (internal->_replyTimeout)
#define IrequestTimeout (internal->_requestTimeout)
#define IrequestModes (internal->_requestModes)
#define IrunLoops (internal->_runLoops)
#define IrequestQueue (internal->_requestQueue)
#define Idelegate (internal->_delegate)
#define IrefGate (internal->_refGate)
#define IcachedDecoders (internal->_cachedDecoders)
#define IcachedEncoders (internal->_cachedEncoders)
#define IremoteName (internal->_remoteName)
#define IregisteredName (internal->_registeredName)
#define InameServer (internal->_nameServer)
#define IlastKeepalive (internal->_lastKeepalive)
/** </ignore> */
@interface NSConnection(Private)
- (void) handlePortMessage: (NSPortMessage*)msg;
- (void) _runInNewThread;
+ (int) setDebug: (int)val;
- (void) _enableKeepalive;
- (void) addLocalObject: (NSDistantObject*)anObj;
- (void) removeLocalObject: (NSDistantObject*)anObj;
- (void) _doneInReply: (NSPortCoder*)c;
- (void) _doneInRmc: (NSPortCoder*) NS_CONSUMED c;
- (void) _failInRmc: (NSPortCoder*)c;
- (void) _failOutRmc: (NSPortCoder*)c;
- (NSPortCoder*) _getReplyRmc: (int)sn for: (const char*)request;
- (NSPortCoder*) _newInRmc: (NSMutableArray*)components;
- (NSPortCoder*) _newOutRmc: (int)sequence generate: (int*)sno reply: (BOOL)f;
- (void) _portIsInvalid: (NSNotification*)notification;
- (void) _sendOutRmc: (NSPortCoder*) NS_CONSUMED c
type: (int)msgid
sequence: (int)sno;
- (void) _service_forwardForProxy: (NSPortCoder*)rmc;
- (void) _service_release: (NSPortCoder*)rmc;
- (void) _service_retain: (NSPortCoder*)rmc;
- (void) _service_rootObject: (NSPortCoder*)rmc;
- (void) _service_shutdown: (NSPortCoder*)rmc;
- (void) _service_typeForSelector: (NSPortCoder*)rmc;
- (void) _shutdown;
+ (void) _threadWillExit: (NSNotification*)notification;
@end
/* class defaults */
static NSTimer *timer = nil;
static BOOL cacheCoders = NO;
static int debug_connection = 0;
static NSHashTable *connection_table;
static NSRecursiveLock *connection_table_gate = nil;
/*
* Locate an existing connection with the specified send and receive ports.
* nil ports act as wildcards and return the first match.
*/
static NSConnection*
existingConnection(NSPort *receivePort, NSPort *sendPort)
{
NSHashEnumerator enumerator;
NSConnection *c;
GS_F_LOCK(connection_table_gate);
enumerator = NSEnumerateHashTable(connection_table);
while ((c = (NSConnection*)NSNextHashEnumeratorItem(&enumerator)) != nil)
{
if ((sendPort == nil || [sendPort isEqual: [c sendPort]])
&& (receivePort == nil || [receivePort isEqual: [c receivePort]]))
{
/*
* We don't want this connection to be destroyed by another thread
* between now and when it's returned from this function and used!
*/
IF_NO_GC([[c retain] autorelease];)
break;
}
}
NSEndHashTableEnumeration(&enumerator);
GS_F_UNLOCK(connection_table_gate);
return c;
}
static NSMapTable *root_object_map;
static NSLock *root_object_map_gate = nil;
static id
rootObjectForInPort(NSPort *aPort)
{
id rootObject;
GS_F_LOCK(root_object_map_gate);
rootObject = (id)NSMapGet(root_object_map, (void*)(uintptr_t)aPort);
GS_F_UNLOCK(root_object_map_gate);
return rootObject;
}
/* Pass nil to remove any reference keyed by aPort. */
static void
setRootObjectForInPort(id anObj, NSPort *aPort)
{
id oldRootObject;
GS_F_LOCK(root_object_map_gate);
oldRootObject = (id)NSMapGet(root_object_map, (void*)(uintptr_t)aPort);
if (oldRootObject != anObj)
{
if (anObj != nil)
{
NSMapInsert(root_object_map, (void*)(uintptr_t)aPort,
(void*)(uintptr_t)anObj);
}
else /* anObj == nil && oldRootObject != nil */
{
NSMapRemove(root_object_map, (void*)(uintptr_t)aPort);
}
}
GS_F_UNLOCK(root_object_map_gate);
}
static NSMapTable *targetToCached = NULL;
static NSLock *cached_proxies_gate = nil;
/**
* NSConnection objects are used to manage communications between
* objects in different processes, in different machines, or in
* different threads.
*/
@implementation NSConnection
/**
* Returns an array containing all the NSConnection objects known to
* the system. These connections will be valid at the time that the
* array was created, but may be invalidated by other threads
* before you get to examine the array.
*/
+ (NSArray*) allConnections
{
NSArray *a;
GS_M_LOCK(connection_table_gate);
a = NSAllHashTableObjects(connection_table);
GSM_UNLOCK(connection_table_gate);
return a;
}
/**
* Returns a connection initialised using -initWithReceivePort:sendPort:<br />
* Both ports must be of the same type.
*/
+ (NSConnection*) connectionWithReceivePort: (NSPort*)r
sendPort: (NSPort*)s
{
NSConnection *c = existingConnection(r, s);
if (c == nil)
{
c = [self allocWithZone: NSDefaultMallocZone()];
c = [c initWithReceivePort: r sendPort: s];
IF_NO_GC([c autorelease];)
}
return c;
}
/**
* <p>Returns an NSConnection object whose send port is that of the
* NSConnection registered under the name n on the host h
* </p>
* <p>This method calls +connectionWithRegisteredName:host:usingNameServer:
* using the default system name server.
* </p>
* <p>Use [NSSocketPortNameServer] for connections to remote hosts.
* </p>
*/
+ (NSConnection*) connectionWithRegisteredName: (NSString*)n
host: (NSString*)h
{
NSPortNameServer *s;
s = [NSPortNameServer systemDefaultPortNameServer];
return [self connectionWithRegisteredName: n
host: h
usingNameServer: s];
}
/**
* <p>
* Returns an NSConnection object whose send port is that of the
* NSConnection registered under <em>name</em> on <em>host</em>.
* </p>
* <p>
* The nameserver <em>server</em> is used to look up the send
* port to be used for the connection.<br />
* Use [NSSocketPortNameServer+sharedInstance]
* for connections to remote hosts.
* </p>
* <p>
* If <em>host</em> is <code>nil</code> or an empty string,
* the host is taken to be the local machine.<br />
* If it is an asterisk ('*') then the nameserver checks all
* hosts on the local subnet (unless the nameserver is one
* that only manages local ports).<br />
* In the GNUstep implementation, the local host is searched before
* any other hosts.<br />
* NB. if the nameserver does not support connections to remote hosts
* (the default situation) the host argeument should be omitted.
* </p>
* <p>
* If no NSConnection can be found for <em>name</em> and
* <em>host</em>host, the method returns <code>nil</code>.
* </p>
* <p>
* The returned object has the default NSConnection of the
* current thread as its parent (it has the same receive port
* as the default connection).
* </p>
*/
+ (NSConnection*) connectionWithRegisteredName: (NSString*)n
host: (NSString*)h
usingNameServer: (NSPortNameServer*)s
{
NSConnection *con = nil;
if (s != nil)
{
NSPort *sendPort = [s portForName: n onHost: h];
if (sendPort != nil)
{
NSPort *recvPort;
recvPort = [[self defaultConnection] receivePort];
if (recvPort == sendPort)
{
/*
* If the receive and send port are the same, the server
* must be in this process - so we need to create a new
* connection to talk to it.
*/
recvPort = [NSPort port];
}
else if (![recvPort isMemberOfClass: [sendPort class]])
{
/*
We can only use the port of the default connection for
connections using the same port class. For other port classes,
we must use a receiving port of the same class as the sending
port, so we allocate one here.
*/
recvPort = [[sendPort class] port];
}
con = existingConnection(recvPort, sendPort);
if (con == nil)
{
con = [self connectionWithReceivePort: recvPort
sendPort: sendPort];
}
ASSIGNCOPY(GSIVar(con, _remoteName), n);
}
}
return con;
}
/**
* Return the current conversation ... not implemented in GNUstep
*/
+ (id) currentConversation
{
return nil;
}
/**
* Returns the default connection for a thread.<br />
* Creates a new instance if necessary.<br />
* The default connection has a single NSPort object used for
* both sending and receiving - this it can't be used to
* connect to a remote process, but can be used to vend objects.<br />
* Possible problem - if the connection is invalidated, it won't be
* cleaned up until this thread calls this method again. The connection
* and it's ports could hang around for a very long time.
*/
+ (NSConnection*) defaultConnection
{
static NSString *tkey = @"NSConnectionThreadKey";
NSConnection *c;
NSMutableDictionary *d;
d = GSCurrentThreadDictionary();
c = (NSConnection*)[d objectForKey: tkey];
if (c != nil && [c isValid] == NO)
{
/*
* If the default connection for this thread has been invalidated -
* release it and create a new one.
*/
[d removeObjectForKey: tkey];
c = nil;
}
if (c == nil)
{
NSPort *port;
c = [self alloc];
port = [NSPort port];
c = [c initWithReceivePort: port sendPort: nil];
if (c != nil)
{
[d setObject: c forKey: tkey];
RELEASE(c);
}
}
return c;
}
+ (void) initialize
{
if (connectionClass == nil)
{
NSNotificationCenter *nc;
GSMakeWeakPointer(self, "delegate");
connectionClass = self;
dateClass = [NSDate class];
distantObjectClass = [NSDistantObject class];
sendCoderClass = [NSPortCoder class];
recvCoderClass = [NSPortCoder class];
runLoopClass = [NSRunLoop class];
dummyObject = [NSObject new];
[[NSObject leakAt: &dummyObject] release];
connection_table =
NSCreateHashTable(NSNonRetainedObjectHashCallBacks, 0);
[[NSObject leakAt: &connection_table] release];
targetToCached =
NSCreateMapTable(NSIntegerMapKeyCallBacks,
NSObjectMapValueCallBacks, 0);
[[NSObject leakAt: &targetToCached] release];
root_object_map =
NSCreateMapTable(NSNonOwnedPointerMapKeyCallBacks,
NSObjectMapValueCallBacks, 0);
[[NSObject leakAt: &root_object_map] release];
if (connection_table_gate == nil)
{
connection_table_gate = [NSRecursiveLock new];
[[NSObject leakAt: &connection_table_gate] release];
}
if (cached_proxies_gate == nil)
{
cached_proxies_gate = [NSLock new];
[[NSObject leakAt: &cached_proxies_gate] release];
}
if (root_object_map_gate == nil)
{
root_object_map_gate = [NSLock new];
[[NSObject leakAt: &root_object_map_gate] release];
}
/*
* When any thread exits, we must check to see if we are using its
* runloop, and remove ourselves from it if necessary.
*/
nc = [NSNotificationCenter defaultCenter];
[nc addObserver: self
selector: @selector(_threadWillExit:)
name: NSThreadWillExitNotification
object: nil];
}
}
/**
* Undocumented feature for compatibility with OPENSTEP/MacOS-X
* +new returns the default connection.
*/
+ (id) new
{
return RETAIN([self defaultConnection]);
}
/**
* This method calls
* +rootProxyForConnectionWithRegisteredName:host:usingNameServer:
* to return a proxy for a root object on the remote connection with
* the send port registered under name n on host h.
*/
+ (NSDistantObject*) rootProxyForConnectionWithRegisteredName: (NSString*)n
host: (NSString*)h
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSConnection *connection;
NSDistantObject *proxy = nil;
connection = [self connectionWithRegisteredName: n host: h];
if (connection != nil)
{
proxy = [[connection rootProxy] retain];
}
[arp drain];
return [proxy autorelease];
}
/**
* This method calls
* +connectionWithRegisteredName:host:usingNameServer:
* to get a connection, then sends it a -rootProxy message to get
* a proxy for the root object being vended by the remote connection.
* Returns the proxy or nil if it couldn't find a connection or if
* the root object for the connection has not been set.<br />
* Use [NSSocketPortNameServer+sharedInstance]
* for connections to remote hosts.
*/
+ (NSDistantObject*) rootProxyForConnectionWithRegisteredName: (NSString*)n
host: (NSString*)h usingNameServer: (NSPortNameServer*)s
{
NSAutoreleasePool *arp = [NSAutoreleasePool new];
NSConnection *connection;
NSDistantObject *proxy = nil;
connection = [self connectionWithRegisteredName: n
host: h
usingNameServer: s];
if (connection != nil)
{
proxy = RETAIN([connection rootProxy]);
}
[arp drain];
return AUTORELEASE(proxy);
}
+ (id) serviceConnectionWithName: (NSString *)name
rootObject: (id)root
{
return [self serviceConnectionWithName: name
rootObject: root
usingNameServer: [NSPortNameServer systemDefaultPortNameServer]];
}
+ (id) serviceConnectionWithName: (NSString *)name
rootObject: (id)root
usingNameServer: (NSPortNameServer *)server
{
NSConnection *c;
NSPort *p;
if ([server isKindOfClass: [NSMessagePortNameServer class]] == YES)
{
p = [NSMessagePort port];
}
else if ([server isKindOfClass: [NSSocketPortNameServer class]] == YES)
{
p = [NSSocketPort port];
}
else
{
p = nil;
}
c = [[NSConnection alloc] initWithReceivePort: p sendPort: nil];
[c setRootObject: root];
if ([c registerName: name withNameServer: server] == NO)
{
DESTROY(c);
}
return AUTORELEASE(c);
}
+ (void) _timeout: (NSTimer*)t
{
NSArray *cached_locals;
int i;
GS_M_LOCK(cached_proxies_gate);
cached_locals = NSAllMapTableValues(targetToCached);
for (i = [cached_locals count]; i > 0; i--)
{
CachedLocalObject *item = [cached_locals objectAtIndex: i-1];
if ([item countdown] == NO)
{
NSDistantObject *obj = [item obj];
NSMapRemove(targetToCached,
(void*)(uintptr_t)obj->_handle);
}
}
if ([cached_locals count] == 0)
{
[t invalidate];
timer = nil;
}
GSM_UNLOCK(cached_proxies_gate);
}
/**
* Adds mode to the run loop modes that the NSConnection
* will listen to for incoming messages.
*/
- (void) addRequestMode: (NSString*)mode
{
GS_M_LOCK(IrefGate);
if ([self isValid] == YES)
{
if ([IrequestModes containsObject: mode] == NO)
{
NSUInteger c = [IrunLoops count];
while (c-- > 0)
{
NSRunLoop *loop = [IrunLoops objectAtIndex: c];
[IreceivePort addConnection: self toRunLoop: loop forMode: mode];
}
[IrequestModes addObject: mode];
}
}
GSM_UNLOCK(IrefGate);
}
/**
* Adds loop to the set of run loops that the NSConnection
* will listen to for incoming messages.
*/
- (void) addRunLoop: (NSRunLoop*)loop
{
GS_M_LOCK(IrefGate);
if ([self isValid] == YES)
{
if ([IrunLoops indexOfObjectIdenticalTo: loop] == NSNotFound)
{
NSUInteger c = [IrequestModes count];
while (c-- > 0)
{
NSString *mode = [IrequestModes objectAtIndex: c];
[IreceivePort addConnection: self toRunLoop: loop forMode: mode];
}
[IrunLoops addObject: loop];
}
}
GSM_UNLOCK(IrefGate);
}
- (void) dealloc
{
if (debug_connection)
NSLog(@"deallocating %@", self);
[self finalize];
if (internal != nil)
{
GS_DESTROY_INTERNAL(NSConnection);
}
[super dealloc];
}
/**
* Returns the delegate of the NSConnection.
*/
- (id) delegate
{
return Idelegate;
}
- (NSString*) description
{
return [NSString stringWithFormat: @"%@ local: '%@',%@ remote '%@',%@",
[super description],
IregisteredName ? (id)IregisteredName : (id)@"", [self receivePort],
IremoteName ? (id)IremoteName : (id)@"", [self sendPort]];
}
/**
* Sets the NSConnection configuration so that multiple threads may
* use the connection to send requests to the remote connection.<br />
* This option is inherited by child connections.<br />
* NB. A connection with multiple threads enabled will run slower than
* a normal connection.
*/
- (void) enableMultipleThreads
{
ImultipleThreads = YES;
}
/**
* Returns YES if the NSConnection is configured to
* handle remote messages atomically, NO otherwise.<br />
* This option is inherited by child connections.
*/
- (BOOL) independentConversationQueueing
{
return IindependentQueueing;
}
/**
* Return a connection able to act as a server receive incoming requests.
*/
- (id) init
{
NSPort *port = [NSPort port];
self = [self initWithReceivePort: port sendPort: nil];
return self;
}
/** <init />
* Initialises an NSConnection with the receive port r and the
* send port s.<br />
* Behavior varies with the port values as follows -
* <deflist>
* <term>r is <code>nil</code></term>
* <desc>
* The NSConnection is released and the method returns
* <code>nil</code>.
* </desc>
* <term>s is <code>nil</code></term>
* <desc>
* The NSConnection uses r as the send port as
* well as the receive port.
* </desc>
* <term>s is the same as r</term>
* <desc>
* The NSConnection is usable only for vending objects.
* </desc>
* <term>A connection with the same ports exists</term>
* <desc>
* The new connection is released and the old connection
* is retained and returned.
* </desc>
* <term>A connection with the same ports (swapped) exists</term>
* <desc>
* The new connection is initialised as normal, and will
* communicate with the old connection.
* </desc>
* </deflist>
* <p>
* If a connection exists whose send and receive ports are
* both the same as the new connections receive port, that
* existing connection is deemed to be the parent of the
* new connection. The new connection inherits configuration
* information from the parent, and the delegate of the
* parent has a chance to adjust the configuration of the
* new connection or veto its creation.
* <br/>
* NSConnectionDidInitializeNotification is posted once a new
* connection is initialised.
* </p>
*/
- (id) initWithReceivePort: (NSPort*)r
sendPort: (NSPort*)s
{
NSNotificationCenter *nCenter;
NSConnection *parent;
NSConnection *conn;
NSRunLoop *loop;
id del;
NSZone *z;
z = NSDefaultMallocZone();
/*
* If the receive port is nil, deallocate connection and return nil.
*/
if (r == nil)
{
if (debug_connection > 2)
{
NSLog(@"Asked to create connection with nil receive port");
}
DESTROY(self);
return self;
}
/*
* If the send port is nil, set it to the same as the receive port
* This connection will then only be useful to act as a server.
*/
if (s == nil)
{
s = r;
}
conn = existingConnection(r, s);
/*
* If the send and receive ports match an existing connection
* deallocate the new one and retain and return the old one.
*/