PageRenderTime 43ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/Foundation/platform_windows/NSSelectSet_windows.m

https://code.google.com/p/cocotron/
Objective C | 442 lines | 326 code | 109 blank | 7 comment | 30 complexity | e67a0d8e0d0e13c71fea4a1dfa8cb4dd MD5 | raw file
  1. /* Copyright (c) 2007 Christopher J. W. Lloyd
  2. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  3. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  4. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  5. #import "NSSelectSet_windows.h"
  6. #import "NSSocket_windows.h"
  7. #import <Foundation/NSHandleMonitor_win32.h>
  8. #import <Foundation/NSError.h>
  9. #import <Foundation/NSSet.h>
  10. #import <Foundation/NSEnumerator.h>
  11. #import <Foundation/NSDate.h>
  12. #import <Foundation/NSArray.h>
  13. #import <Foundation/NSNotificationCenter.h>
  14. #import <Foundation/NSString.h>
  15. #import <Foundation/NSRunLoop.h>
  16. #include <pthread.h>
  17. @implementation NSSelectSet(windows)
  18. +allocWithZone:(NSZone *)zone {
  19. return NSAllocateObject([NSSelectSet_windows class],0,NULL);
  20. }
  21. @end
  22. @implementation NSSelectSet_windows
  23. typedef struct {
  24. unsigned max;
  25. fd_set *fdset;
  26. } native_set;
  27. native_set *native_set_new() {
  28. native_set *native=NSZoneCalloc(NULL, 1, sizeof(native_set));
  29. native->max=FD_SETSIZE;
  30. native->fdset=NSZoneCalloc(NULL, 1, sizeof(fd_set));
  31. return native;
  32. }
  33. void native_set_free(native_set *native){
  34. NSZoneFree(NULL,native->fdset);
  35. NSZoneFree(NULL,native);
  36. }
  37. void native_set_reset(native_set *native) {
  38. native->fdset->fd_count=0;
  39. }
  40. void native_set_set(native_set *native,SOCKET handle) {
  41. if(native->fdset->fd_count>=native->max){
  42. native->max*=2;
  43. native->fdset=NSZoneRealloc(NULL,native->fdset,sizeof(fd_set)+sizeof(SOCKET)*(native->max-FD_SETSIZE));
  44. }
  45. native->fdset->fd_array[native->fdset->fd_count++]=handle;
  46. }
  47. void native_set_clear(native_set *native,SOCKET handle){
  48. int i;
  49. for(i=0;i<native->fdset->fd_count;i++){
  50. if(native->fdset->fd_array[i]==handle){
  51. native->fdset->fd_count--;
  52. while(i<native->fdset->fd_count){
  53. native->fdset->fd_array[i]=native->fdset->fd_array[i+1];
  54. i++;
  55. }
  56. break;
  57. }
  58. }
  59. }
  60. void native_set_copy(native_set *native,native_set *copy){
  61. int i;
  62. while(copy->max<native->fdset->fd_count){
  63. copy->max*=2;
  64. copy->fdset=NSZoneRealloc(NULL,copy->fdset,sizeof(fd_set)+sizeof(SOCKET)*(copy->max-FD_SETSIZE));
  65. }
  66. for(i=0;i<native->fdset->fd_count;i++)
  67. copy->fdset->fd_array[i]=native->fdset->fd_array[i];
  68. copy->fdset->fd_count=i;
  69. }
  70. BOOL native_set_is_set(native_set *native,SOCKET handle) {
  71. int i;
  72. for(i=0;i<native->fdset->fd_count;i++)
  73. if(native->fdset->fd_array[i]==handle)
  74. return YES;
  75. return NO;
  76. }
  77. BOOL native_set_merge(native_set *native,native_set *merge){
  78. int i;
  79. for(i=0;i<native->fdset->fd_count;i++){
  80. SOCKET check=native->fdset->fd_array[i];
  81. if(!native_set_is_set(merge,check))
  82. native_set_set(merge,check);
  83. }
  84. return (i>0)?YES:NO;
  85. }
  86. void native_set_remove(native_set *native,native_set *remove){
  87. int i;
  88. for(i=0;i<native->fdset->fd_count;i++)
  89. native_set_clear(remove,native->fdset->fd_array[i]);
  90. }
  91. typedef struct NSSelectSetBackgroundInfo {
  92. HANDLE eventHandle;
  93. NSHandleMonitor_win32 *eventMonitor;
  94. NSMutableArray *eventMonitorModes;
  95. NSSocket_windows *pingRead;
  96. NSSocket_windows *pingWrite;
  97. SOCKET pingReadHandle;
  98. SOCKET pingWriteHandle;
  99. CRITICAL_SECTION *lock;
  100. BOOL shutdown;
  101. native_set *inputRead;
  102. native_set *inputWrite;
  103. native_set *inputExcept;
  104. native_set *outputRead;
  105. native_set *outputWrite;
  106. native_set *outputExcept;
  107. native_set *outputError;
  108. } NSSelectSetBackgroundInfo;
  109. static WINAPI DWORD selectThread(LPVOID arg){
  110. BOOL shutdown=NO;
  111. struct NSSelectSetBackgroundInfo *async=arg;
  112. native_set *activeRead;
  113. native_set *activeWrite;
  114. native_set *activeExcept;
  115. native_set *checkForErrors;
  116. native_set *gotErrors;
  117. activeRead=native_set_new();
  118. activeWrite=native_set_new();
  119. activeExcept=native_set_new();
  120. checkForErrors=native_set_new();
  121. gotErrors=native_set_new();
  122. while(!shutdown){
  123. BOOL setEvent;
  124. EnterCriticalSection(async->lock);
  125. native_set_copy(async->inputRead,activeRead);
  126. native_set_copy(async->inputWrite,activeWrite);
  127. native_set_copy(async->inputExcept,activeExcept);
  128. native_set_copy(async->inputRead,checkForErrors);
  129. native_set_merge(async->inputWrite,checkForErrors);
  130. native_set_merge(async->inputExcept,checkForErrors);
  131. LeaveCriticalSection(async->lock);
  132. native_set_set(activeRead,async->pingReadHandle);
  133. setEvent=NO;
  134. if(select(42,activeRead->fdset,activeWrite->fdset,activeExcept->fdset,NULL)<0){
  135. int i;
  136. native_set_reset(gotErrors);
  137. for(i=0;i<checkForErrors->fdset->fd_count;i++){
  138. SOCKET check=checkForErrors->fdset->fd_array[i];
  139. int ignore,ignoreLen=sizeof(ignore);
  140. if(getsockopt(check,IPPROTO_TCP,SO_TYPE,(void *)&ignore,&ignoreLen)<0)
  141. native_set_set(gotErrors,check);
  142. }
  143. EnterCriticalSection(async->lock);
  144. if(native_set_merge(gotErrors,async->outputError))
  145. setEvent=YES;
  146. native_set_remove(gotErrors,async->inputRead);
  147. native_set_remove(gotErrors,async->inputWrite);
  148. native_set_remove(gotErrors,async->inputExcept);
  149. LeaveCriticalSection(async->lock);
  150. }
  151. else {
  152. if(native_set_is_set(activeRead,async->pingReadHandle)){
  153. char buf[256];
  154. native_set_clear(activeRead,async->pingReadHandle);
  155. recv(async->pingReadHandle,buf,256,0);
  156. }
  157. EnterCriticalSection(async->lock);
  158. if(native_set_merge(activeRead,async->outputRead))
  159. setEvent=YES;
  160. if(native_set_merge(activeWrite,async->outputWrite))
  161. setEvent=YES;
  162. if(native_set_merge(activeExcept,async->outputExcept))
  163. setEvent=YES;
  164. native_set_remove(activeRead,async->inputRead);
  165. native_set_remove(activeWrite,async->inputWrite);
  166. native_set_remove(activeExcept,async->inputExcept);
  167. LeaveCriticalSection(async->lock);
  168. }
  169. if(setEvent)
  170. SetEvent(async->eventHandle);
  171. EnterCriticalSection(async->lock);
  172. shutdown=async->shutdown;
  173. LeaveCriticalSection(async->lock);
  174. }
  175. CloseHandle(async->eventHandle);
  176. [async->pingRead close];
  177. [async->pingRead release];
  178. [async->pingWrite close];
  179. [async->pingWrite release];
  180. native_set_free(async->inputRead);
  181. native_set_free(async->inputWrite);
  182. native_set_free(async->inputExcept);
  183. native_set_free(async->outputRead);
  184. native_set_free(async->outputWrite);
  185. native_set_free(async->outputExcept);
  186. native_set_free(async->outputError);
  187. NSZoneFree(NULL,async->lock);
  188. NSZoneFree(NULL,async);
  189. return 0;
  190. }
  191. static pthread_once_t asyncThreadKeyOnce=PTHREAD_ONCE_INIT;
  192. static pthread_key_t asyncThreadKey;
  193. static void asyncThreadInfoDealloc(void *asyncX){
  194. struct NSSelectSetBackgroundInfo *async=asyncX;
  195. }
  196. static void asyncThreadKeyInitialize(void) {
  197. pthread_key_create(&asyncThreadKey,(void(*)(void*))&asyncThreadInfoDealloc);
  198. }
  199. static struct NSSelectSetBackgroundInfo *asyncThreadInfo(){
  200. pthread_once(&asyncThreadKeyOnce,asyncThreadKeyInitialize);
  201. struct NSSelectSetBackgroundInfo *result=pthread_getspecific(asyncThreadKey);
  202. if (result == NULL){
  203. result=NSZoneMalloc(NULL,sizeof(struct NSSelectSetBackgroundInfo));
  204. result->eventHandle=CreateEvent(NULL,FALSE,FALSE,NULL);
  205. result->eventMonitor=[[NSHandleMonitor_win32 handleMonitorWithHandle:result->eventHandle] retain];
  206. [result->eventMonitor setDelegate:[NSSelectSet_windows class]];
  207. [result->eventMonitor setCurrentActivity:Win32HandleSignaled];
  208. result->eventMonitorModes=[NSMutableArray new];
  209. result->pingWrite=[[NSSocket alloc] initConnectedToSocket:&result->pingRead];
  210. [result->pingRead retain];
  211. result->pingWriteHandle=[result->pingWrite socketHandle];
  212. result->pingReadHandle=[result->pingRead socketHandle];
  213. result->lock=NSZoneMalloc(NULL,sizeof(CRITICAL_SECTION));
  214. InitializeCriticalSection(result->lock);
  215. result->shutdown=NO;
  216. result->inputRead=native_set_new();
  217. result->inputWrite=native_set_new();
  218. result->inputExcept=native_set_new();
  219. result->outputRead=native_set_new();
  220. result->outputWrite=native_set_new();
  221. result->outputExcept=native_set_new();
  222. result->outputError=native_set_new();
  223. pthread_setspecific(asyncThreadKey,result);
  224. DWORD threadID;
  225. CreateThread(NULL,0,selectThread,result,0,&threadID);
  226. }
  227. return result;
  228. }
  229. void NSSelectSetShutdownForCurrentThread() {
  230. pthread_once(&asyncThreadKeyOnce,asyncThreadKeyInitialize);
  231. struct NSSelectSetBackgroundInfo *async=pthread_getspecific(asyncThreadKey);
  232. if(async!=NULL){
  233. pthread_setspecific(asyncThreadKey,NULL);
  234. [async->eventMonitor invalidate];
  235. [async->eventMonitor release];
  236. async->eventMonitor=nil;
  237. [async->eventMonitorModes release];
  238. async->eventMonitorModes=nil;
  239. EnterCriticalSection(async->lock);
  240. async->shutdown=YES;
  241. uint8_t one[1]={ 42 };
  242. [async->pingWrite write:one maxLength:1];
  243. LeaveCriticalSection(async->lock);
  244. }
  245. }
  246. static void transferSetToNative(NSSet *set,native_set *native){
  247. NSEnumerator *state=[set objectEnumerator];
  248. NSSocket_windows *socket;
  249. while((socket=[state nextObject])!=nil)
  250. native_set_set(native,[socket socketHandle]);
  251. }
  252. static void transferNativeToSet(native_set *native,NSMutableSet *set){
  253. int i;
  254. for(i=0;i<native->fdset->fd_count;i++)
  255. [set addObject:[[[NSSocket_windows alloc] initWithSocketHandle:native->fdset->fd_array[i]] autorelease]];
  256. }
  257. static void transferNativeToSetWithOriginals(native_set *native,NSMutableSet *set,NSSet *original,NSSocket_windows *cheater){
  258. int i;
  259. for(i=0;i<native->fdset->fd_count;i++){
  260. [cheater setSocketHandle:native->fdset->fd_array[i]];
  261. [set addObject:[original member:cheater]];
  262. }
  263. }
  264. +(void)handleMonitorIndicatesSignaled:(NSHandleMonitor_win32 *)monitor {
  265. NSSelectSet_windows *outputSet=[[[NSSelectSet alloc] init] autorelease];
  266. NSSelectSetBackgroundInfo *async=asyncThreadInfo();
  267. EnterCriticalSection(async->lock);
  268. transferNativeToSet(async->outputRead,outputSet->_readSet);
  269. transferNativeToSet(async->outputWrite,outputSet->_writeSet);
  270. transferNativeToSet(async->outputExcept,outputSet->_exceptionSet);
  271. LeaveCriticalSection(async->lock);
  272. [[NSNotificationCenter defaultCenter] postNotificationName:NSSelectSetOutputNotification object:outputSet];
  273. }
  274. -(void)waitInBackgroundInMode:(NSString *)mode {
  275. BOOL pingElseThread=YES;
  276. if([self isEmpty])
  277. return;
  278. NSSelectSetBackgroundInfo *async=asyncThreadInfo();
  279. if(![async->eventMonitorModes containsObject:mode]){
  280. [async->eventMonitorModes addObject:mode];
  281. [[NSRunLoop currentRunLoop] addInputSource:async->eventMonitor forMode:mode];
  282. }
  283. EnterCriticalSection(async->lock);
  284. native_set_reset(async->inputRead);
  285. native_set_reset(async->inputWrite);
  286. native_set_reset(async->inputExcept);
  287. transferSetToNative(_readSet,async->inputRead);
  288. transferSetToNative(_writeSet,async->inputWrite);
  289. transferSetToNative(_exceptionSet,async->inputExcept);
  290. native_set_reset(async->outputRead);
  291. native_set_reset(async->outputWrite);
  292. native_set_reset(async->outputExcept);
  293. native_set_reset(async->outputError);
  294. LeaveCriticalSection(async->lock);
  295. uint8_t one[1]={ 42 };
  296. [async->pingWrite write:one maxLength:1];
  297. }
  298. -(NSError *)waitForSelectWithOutputSet:(NSSelectSet **)outputSetX beforeDate:(NSDate *)beforeDate {
  299. NSError *result=nil;
  300. NSSocket_windows *cheater=[NSSocket_windows socketWithSocketHandle:0];
  301. NSTimeInterval interval=[beforeDate timeIntervalSinceNow];
  302. native_set *activeRead=native_set_new();
  303. native_set *activeWrite=native_set_new();
  304. native_set *activeExcept=native_set_new();
  305. struct timeval timeval;
  306. transferSetToNative(_readSet,activeRead);
  307. transferSetToNative(_writeSet,activeWrite);
  308. transferSetToNative(_exceptionSet,activeExcept);
  309. if(interval>1000000)
  310. interval=1000000;
  311. if(interval<0)
  312. interval=0;
  313. timeval.tv_sec=interval;
  314. interval-=timeval.tv_sec;
  315. timeval.tv_usec=interval*1000;
  316. if(select(42,activeRead->fdset,activeWrite->fdset,activeExcept->fdset,&timeval)<0)
  317. result=[NSError errorWithDomain:NSWINSOCKErrorDomain code:WSAGetLastError() userInfo:nil];
  318. if(result==nil) {
  319. NSSelectSet_windows *outputSet=[[[NSSelectSet alloc] init] autorelease];
  320. transferNativeToSetWithOriginals(activeRead,outputSet->_readSet,_readSet,cheater);
  321. transferNativeToSetWithOriginals(activeWrite,outputSet->_writeSet,_writeSet,cheater);
  322. transferNativeToSetWithOriginals(activeExcept,outputSet->_exceptionSet,_exceptionSet,cheater);
  323. *outputSetX=outputSet;
  324. }
  325. native_set_free(activeRead);
  326. native_set_free(activeWrite);
  327. native_set_free(activeExcept);
  328. return result;
  329. }
  330. @end