TESTING -- override pthreads to fix gstreamer v5
[wine/multimedia.git] / dlls / ntdll / server.c
blob4775dece61a66c780b714d2648dc209d138a1adf
1 /*
2 * Wine server communication
4 * Copyright (C) 1998 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
22 #include "wine/port.h"
24 #include <assert.h>
25 #include <ctype.h>
26 #ifdef HAVE_DIRENT_H
27 # include <dirent.h>
28 #endif
29 #include <errno.h>
30 #include <fcntl.h>
31 #ifdef HAVE_LWP_H
32 #include <lwp.h>
33 #endif
34 #ifdef HAVE_PTHREAD_NP_H
35 # include <pthread_np.h>
36 #endif
37 #include <signal.h>
38 #include <stdarg.h>
39 #include <stdio.h>
40 #include <string.h>
41 #include <sys/types.h>
42 #ifdef HAVE_SYS_SOCKET_H
43 # include <sys/socket.h>
44 #endif
45 #ifdef HAVE_SYS_WAIT_H
46 #include <sys/wait.h>
47 #endif
48 #ifdef HAVE_SYS_UN_H
49 #include <sys/un.h>
50 #endif
51 #ifdef HAVE_SYS_MMAN_H
52 #include <sys/mman.h>
53 #endif
54 #ifdef HAVE_SYS_PRCTL_H
55 # include <sys/prctl.h>
56 #endif
57 #ifdef HAVE_SYS_STAT_H
58 # include <sys/stat.h>
59 #endif
60 #ifdef HAVE_SYS_SYSCALL_H
61 # include <sys/syscall.h>
62 #endif
63 #ifdef HAVE_SYS_UIO_H
64 #include <sys/uio.h>
65 #endif
66 #ifdef HAVE_SYS_UCONTEXT_H
67 # include <sys/ucontext.h>
68 #endif
69 #ifdef HAVE_SYS_THR_H
70 #include <sys/thr.h>
71 #endif
72 #ifdef HAVE_UNISTD_H
73 # include <unistd.h>
74 #endif
76 #include "ntstatus.h"
77 #define WIN32_NO_STATUS
78 #include "windef.h"
79 #include "winnt.h"
80 #include "wine/library.h"
81 #include "wine/server.h"
82 #include "wine/debug.h"
83 #include "ntdll_misc.h"
85 WINE_DEFAULT_DEBUG_CHANNEL(server);
86 WINE_DECLARE_DEBUG_CHANNEL(winediag);
87 WINE_DECLARE_DEBUG_CHANNEL(tid);
88 WINE_DECLARE_DEBUG_CHANNEL(timestamp);
90 /* Some versions of glibc don't define this */
91 #ifndef SCM_RIGHTS
92 #define SCM_RIGHTS 1
93 #endif
95 #ifndef MSG_CMSG_CLOEXEC
96 #define MSG_CMSG_CLOEXEC 0
97 #endif
99 #define SOCKETNAME "socket" /* name of the socket file */
100 #define LOCKNAME "lock" /* name of the lock file */
102 #ifdef __i386__
103 static const enum cpu_type client_cpu = CPU_x86;
104 #elif defined(__x86_64__)
105 static const enum cpu_type client_cpu = CPU_x86_64;
106 #elif defined(__powerpc__)
107 static const enum cpu_type client_cpu = CPU_POWERPC;
108 #elif defined(__arm__)
109 static const enum cpu_type client_cpu = CPU_ARM;
110 #elif defined(__aarch64__)
111 static const enum cpu_type client_cpu = CPU_ARM64;
112 #else
113 #error Unsupported CPU
114 #endif
116 unsigned int server_cpus = 0;
117 BOOL is_wow64 = FALSE;
119 timeout_t server_start_time = 0; /* time of server startup */
121 sigset_t server_block_set; /* signals to block during server calls */
122 static int fd_socket = -1; /* socket to exchange file descriptors with the server */
123 static pid_t server_pid;
125 static RTL_CRITICAL_SECTION fd_cache_section;
126 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
128 0, 0, &fd_cache_section,
129 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
130 0, 0, { (DWORD_PTR)(__FILE__ ": fd_cache_section") }
132 static RTL_CRITICAL_SECTION fd_cache_section = { &critsect_debug, -1, 0, 0, 0, 0 };
134 /* atomically exchange a 64-bit value */
135 static inline LONG64 interlocked_xchg64( LONG64 *dest, LONG64 val )
137 #ifdef _WIN64
138 return (LONG64)interlocked_xchg_ptr( (void **)dest, (void *)val );
139 #else
140 LONG64 tmp = *dest;
141 while (interlocked_cmpxchg64( dest, val, tmp ) != tmp) tmp = *dest;
142 return tmp;
143 #endif
146 #ifdef __GNUC__
147 static void fatal_error( const char *err, ... ) __attribute__((noreturn, format(printf,1,2)));
148 static void fatal_perror( const char *err, ... ) __attribute__((noreturn, format(printf,1,2)));
149 static void server_connect_error( const char *serverdir ) __attribute__((noreturn));
150 #endif
152 /* die on a fatal error; use only during initialization */
153 static void fatal_error( const char *err, ... )
155 va_list args;
157 va_start( args, err );
158 fprintf( stderr, "wine: " );
159 vfprintf( stderr, err, args );
160 va_end( args );
161 exit(1);
164 /* die on a fatal error; use only during initialization */
165 static void fatal_perror( const char *err, ... )
167 va_list args;
169 va_start( args, err );
170 fprintf( stderr, "wine: " );
171 vfprintf( stderr, err, args );
172 perror( " " );
173 va_end( args );
174 exit(1);
178 /***********************************************************************
179 * server_protocol_error
181 static DECLSPEC_NORETURN void server_protocol_error( const char *err, ... )
183 va_list args;
185 va_start( args, err );
186 fprintf( stderr, "wine client error:%x: ", GetCurrentThreadId() );
187 vfprintf( stderr, err, args );
188 va_end( args );
189 abort_thread(1);
193 /***********************************************************************
194 * server_protocol_perror
196 static DECLSPEC_NORETURN void server_protocol_perror( const char *err )
198 fprintf( stderr, "wine client error:%x: ", GetCurrentThreadId() );
199 perror( err );
200 abort_thread(1);
204 /***********************************************************************
205 * send_request
207 * Send a request to the server.
209 static unsigned int send_request( const struct __server_request_info *req )
211 unsigned int i;
212 int ret;
214 if (!req->u.req.request_header.request_size)
216 if ((ret = write( ntdll_get_thread_data()->request_fd, &req->u.req,
217 sizeof(req->u.req) )) == sizeof(req->u.req)) return STATUS_SUCCESS;
220 else
222 struct iovec vec[__SERVER_MAX_DATA+1];
224 vec[0].iov_base = (void *)&req->u.req;
225 vec[0].iov_len = sizeof(req->u.req);
226 for (i = 0; i < req->data_count; i++)
228 vec[i+1].iov_base = (void *)req->data[i].ptr;
229 vec[i+1].iov_len = req->data[i].size;
231 if ((ret = writev( ntdll_get_thread_data()->request_fd, vec, i+1 )) ==
232 req->u.req.request_header.request_size + sizeof(req->u.req)) return STATUS_SUCCESS;
235 if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
236 if (errno == EPIPE) abort_thread(0);
237 if (errno == EFAULT) return STATUS_ACCESS_VIOLATION;
238 server_protocol_perror( "write" );
242 /***********************************************************************
243 * read_reply_data
245 * Read data from the reply buffer; helper for wait_reply.
247 static void read_reply_data( void *buffer, size_t size )
249 int ret;
251 for (;;)
253 if ((ret = read( ntdll_get_thread_data()->reply_fd, buffer, size )) > 0)
255 if (!(size -= ret)) return;
256 buffer = (char *)buffer + ret;
257 continue;
259 if (!ret) break;
260 if (errno == EINTR) continue;
261 if (errno == EPIPE) break;
262 server_protocol_perror("read");
264 /* the server closed the connection; time to die... */
265 abort_thread(0);
269 /***********************************************************************
270 * wait_reply
272 * Wait for a reply from the server.
274 static inline unsigned int wait_reply( struct __server_request_info *req )
276 read_reply_data( &req->u.reply, sizeof(req->u.reply) );
277 if (req->u.reply.reply_header.reply_size)
278 read_reply_data( req->reply_data, req->u.reply.reply_header.reply_size );
279 return req->u.reply.reply_header.error;
283 /***********************************************************************
284 * wine_server_call (NTDLL.@)
286 * Perform a server call.
288 * PARAMS
289 * req_ptr [I/O] Function dependent data
291 * RETURNS
292 * Depends on server function being called, but usually an NTSTATUS code.
294 * NOTES
295 * Use the SERVER_START_REQ and SERVER_END_REQ to help you fill out the
296 * server request structure for the particular call. E.g:
297 *| SERVER_START_REQ( event_op )
298 *| {
299 *| req->handle = handle;
300 *| req->op = SET_EVENT;
301 *| ret = wine_server_call( req );
302 *| }
303 *| SERVER_END_REQ;
305 unsigned int wine_server_call( void *req_ptr )
307 struct __server_request_info * const req = req_ptr;
308 sigset_t old_set;
309 unsigned int ret;
311 pthread_sigmask( SIG_BLOCK, &server_block_set, &old_set );
312 ret = send_request( req );
313 if (!ret) ret = wait_reply( req );
314 pthread_sigmask( SIG_SETMASK, &old_set, NULL );
315 return ret;
319 /***********************************************************************
320 * server_enter_uninterrupted_section
322 void server_enter_uninterrupted_section( RTL_CRITICAL_SECTION *cs, sigset_t *sigset )
324 pthread_sigmask( SIG_BLOCK, &server_block_set, sigset );
325 RtlEnterCriticalSection( cs );
329 /***********************************************************************
330 * server_leave_uninterrupted_section
332 void server_leave_uninterrupted_section( RTL_CRITICAL_SECTION *cs, sigset_t *sigset )
334 RtlLeaveCriticalSection( cs );
335 pthread_sigmask( SIG_SETMASK, sigset, NULL );
339 /***********************************************************************
340 * wait_select_reply
342 * Wait for a reply on the waiting pipe of the current thread.
344 static int wait_select_reply( void *cookie )
346 int signaled;
347 struct wake_up_reply reply;
348 for (;;)
350 int ret;
351 ret = read( ntdll_get_thread_data()->wait_fd[0], &reply, sizeof(reply) );
352 if (ret == sizeof(reply))
354 if (!reply.cookie) abort_thread( reply.signaled ); /* thread got killed */
355 if (wine_server_get_ptr(reply.cookie) == cookie) return reply.signaled;
356 /* we stole another reply, wait for the real one */
357 signaled = wait_select_reply( cookie );
358 /* and now put the wrong one back in the pipe */
359 for (;;)
361 ret = write( ntdll_get_thread_data()->wait_fd[1], &reply, sizeof(reply) );
362 if (ret == sizeof(reply)) break;
363 if (ret >= 0) server_protocol_error( "partial wakeup write %d\n", ret );
364 if (errno == EINTR) continue;
365 server_protocol_perror("wakeup write");
367 return signaled;
369 if (ret >= 0) server_protocol_error( "partial wakeup read %d\n", ret );
370 if (errno == EINTR) continue;
371 server_protocol_perror("wakeup read");
376 /***********************************************************************
377 * invoke_apc
379 * Invoke a single APC. Return TRUE if a user APC has been run.
381 static BOOL invoke_apc( const apc_call_t *call, apc_result_t *result )
383 BOOL user_apc = FALSE;
384 SIZE_T size;
385 void *addr;
387 memset( result, 0, sizeof(*result) );
389 switch (call->type)
391 case APC_NONE:
392 break;
393 case APC_USER:
395 void (WINAPI *func)(ULONG_PTR,ULONG_PTR,ULONG_PTR) = wine_server_get_ptr( call->user.func );
396 func( call->user.args[0], call->user.args[1], call->user.args[2] );
397 user_apc = TRUE;
398 break;
400 case APC_TIMER:
402 void (WINAPI *func)(void*, unsigned int, unsigned int) = wine_server_get_ptr( call->timer.func );
403 func( wine_server_get_ptr( call->timer.arg ),
404 (DWORD)call->timer.time, (DWORD)(call->timer.time >> 32) );
405 user_apc = TRUE;
406 break;
408 case APC_ASYNC_IO:
410 void *apc = NULL, *arg = NULL;
411 IO_STATUS_BLOCK *iosb = wine_server_get_ptr( call->async_io.sb );
412 NTSTATUS (*func)(void *, IO_STATUS_BLOCK *, NTSTATUS, void **, void **) = wine_server_get_ptr( call->async_io.func );
413 result->type = call->type;
414 result->async_io.status = func( wine_server_get_ptr( call->async_io.user ),
415 iosb, call->async_io.status, &apc, &arg );
416 if (result->async_io.status != STATUS_PENDING)
418 result->async_io.total = iosb->Information;
419 result->async_io.apc = wine_server_client_ptr( apc );
420 result->async_io.arg = wine_server_client_ptr( arg );
422 break;
424 case APC_VIRTUAL_ALLOC:
425 result->type = call->type;
426 addr = wine_server_get_ptr( call->virtual_alloc.addr );
427 size = call->virtual_alloc.size;
428 if ((ULONG_PTR)addr == call->virtual_alloc.addr && size == call->virtual_alloc.size)
430 result->virtual_alloc.status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr,
431 call->virtual_alloc.zero_bits, &size,
432 call->virtual_alloc.op_type,
433 call->virtual_alloc.prot );
434 result->virtual_alloc.addr = wine_server_client_ptr( addr );
435 result->virtual_alloc.size = size;
437 else result->virtual_alloc.status = STATUS_WORKING_SET_LIMIT_RANGE;
438 break;
439 case APC_VIRTUAL_FREE:
440 result->type = call->type;
441 addr = wine_server_get_ptr( call->virtual_free.addr );
442 size = call->virtual_free.size;
443 if ((ULONG_PTR)addr == call->virtual_free.addr && size == call->virtual_free.size)
445 result->virtual_free.status = NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size,
446 call->virtual_free.op_type );
447 result->virtual_free.addr = wine_server_client_ptr( addr );
448 result->virtual_free.size = size;
450 else result->virtual_free.status = STATUS_INVALID_PARAMETER;
451 break;
452 case APC_VIRTUAL_QUERY:
454 MEMORY_BASIC_INFORMATION info;
455 result->type = call->type;
456 addr = wine_server_get_ptr( call->virtual_query.addr );
457 if ((ULONG_PTR)addr == call->virtual_query.addr)
458 result->virtual_query.status = NtQueryVirtualMemory( NtCurrentProcess(),
459 addr, MemoryBasicInformation, &info,
460 sizeof(info), NULL );
461 else
462 result->virtual_query.status = STATUS_WORKING_SET_LIMIT_RANGE;
464 if (result->virtual_query.status == STATUS_SUCCESS)
466 result->virtual_query.base = wine_server_client_ptr( info.BaseAddress );
467 result->virtual_query.alloc_base = wine_server_client_ptr( info.AllocationBase );
468 result->virtual_query.size = info.RegionSize;
469 result->virtual_query.prot = info.Protect;
470 result->virtual_query.alloc_prot = info.AllocationProtect;
471 result->virtual_query.state = info.State >> 12;
472 result->virtual_query.alloc_type = info.Type >> 16;
474 break;
476 case APC_VIRTUAL_PROTECT:
477 result->type = call->type;
478 addr = wine_server_get_ptr( call->virtual_protect.addr );
479 size = call->virtual_protect.size;
480 if ((ULONG_PTR)addr == call->virtual_protect.addr && size == call->virtual_protect.size)
482 result->virtual_protect.status = NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size,
483 call->virtual_protect.prot,
484 &result->virtual_protect.prot );
485 result->virtual_protect.addr = wine_server_client_ptr( addr );
486 result->virtual_protect.size = size;
488 else result->virtual_protect.status = STATUS_INVALID_PARAMETER;
489 break;
490 case APC_VIRTUAL_FLUSH:
491 result->type = call->type;
492 addr = wine_server_get_ptr( call->virtual_flush.addr );
493 size = call->virtual_flush.size;
494 if ((ULONG_PTR)addr == call->virtual_flush.addr && size == call->virtual_flush.size)
496 result->virtual_flush.status = NtFlushVirtualMemory( NtCurrentProcess(),
497 (const void **)&addr, &size, 0 );
498 result->virtual_flush.addr = wine_server_client_ptr( addr );
499 result->virtual_flush.size = size;
501 else result->virtual_flush.status = STATUS_INVALID_PARAMETER;
502 break;
503 case APC_VIRTUAL_LOCK:
504 result->type = call->type;
505 addr = wine_server_get_ptr( call->virtual_lock.addr );
506 size = call->virtual_lock.size;
507 if ((ULONG_PTR)addr == call->virtual_lock.addr && size == call->virtual_lock.size)
509 result->virtual_lock.status = NtLockVirtualMemory( NtCurrentProcess(), &addr, &size, 0 );
510 result->virtual_lock.addr = wine_server_client_ptr( addr );
511 result->virtual_lock.size = size;
513 else result->virtual_lock.status = STATUS_INVALID_PARAMETER;
514 break;
515 case APC_VIRTUAL_UNLOCK:
516 result->type = call->type;
517 addr = wine_server_get_ptr( call->virtual_unlock.addr );
518 size = call->virtual_unlock.size;
519 if ((ULONG_PTR)addr == call->virtual_unlock.addr && size == call->virtual_unlock.size)
521 result->virtual_unlock.status = NtUnlockVirtualMemory( NtCurrentProcess(), &addr, &size, 0 );
522 result->virtual_unlock.addr = wine_server_client_ptr( addr );
523 result->virtual_unlock.size = size;
525 else result->virtual_unlock.status = STATUS_INVALID_PARAMETER;
526 break;
527 case APC_MAP_VIEW:
528 result->type = call->type;
529 addr = wine_server_get_ptr( call->map_view.addr );
530 size = call->map_view.size;
531 if ((ULONG_PTR)addr == call->map_view.addr && size == call->map_view.size)
533 LARGE_INTEGER offset;
534 offset.QuadPart = call->map_view.offset;
535 result->map_view.status = NtMapViewOfSection( wine_server_ptr_handle(call->map_view.handle),
536 NtCurrentProcess(), &addr,
537 call->map_view.zero_bits, 0,
538 &offset, &size, ViewShare,
539 call->map_view.alloc_type, call->map_view.prot );
540 result->map_view.addr = wine_server_client_ptr( addr );
541 result->map_view.size = size;
543 else result->map_view.status = STATUS_INVALID_PARAMETER;
544 NtClose( wine_server_ptr_handle(call->map_view.handle) );
545 break;
546 case APC_UNMAP_VIEW:
547 result->type = call->type;
548 addr = wine_server_get_ptr( call->unmap_view.addr );
549 if ((ULONG_PTR)addr == call->unmap_view.addr)
550 result->unmap_view.status = NtUnmapViewOfSection( NtCurrentProcess(), addr );
551 else
552 result->unmap_view.status = STATUS_INVALID_PARAMETER;
553 break;
554 case APC_CREATE_THREAD:
556 CLIENT_ID id;
557 HANDLE handle;
558 SIZE_T reserve = call->create_thread.reserve;
559 SIZE_T commit = call->create_thread.commit;
560 void *func = wine_server_get_ptr( call->create_thread.func );
561 void *arg = wine_server_get_ptr( call->create_thread.arg );
563 result->type = call->type;
564 if (reserve == call->create_thread.reserve && commit == call->create_thread.commit &&
565 (ULONG_PTR)func == call->create_thread.func && (ULONG_PTR)arg == call->create_thread.arg)
567 result->create_thread.status = RtlCreateUserThread( NtCurrentProcess(), NULL,
568 call->create_thread.suspend, NULL,
569 reserve, commit, func, arg, &handle, &id );
570 result->create_thread.handle = wine_server_obj_handle( handle );
571 result->create_thread.tid = HandleToULong(id.UniqueThread);
573 else result->create_thread.status = STATUS_INVALID_PARAMETER;
574 break;
576 default:
577 server_protocol_error( "get_apc_request: bad type %d\n", call->type );
578 break;
580 return user_apc;
584 /***********************************************************************
585 * server_select
587 unsigned int server_select( const select_op_t *select_op, data_size_t size, UINT flags,
588 const LARGE_INTEGER *timeout )
590 unsigned int ret;
591 int cookie;
592 BOOL user_apc = FALSE;
593 obj_handle_t apc_handle = 0;
594 apc_call_t call;
595 apc_result_t result;
596 timeout_t abs_timeout = timeout ? timeout->QuadPart : TIMEOUT_INFINITE;
598 memset( &result, 0, sizeof(result) );
600 for (;;)
602 SERVER_START_REQ( select )
604 req->flags = flags;
605 req->cookie = wine_server_client_ptr( &cookie );
606 req->prev_apc = apc_handle;
607 req->timeout = abs_timeout;
608 wine_server_add_data( req, &result, sizeof(result) );
609 wine_server_add_data( req, select_op, size );
610 ret = wine_server_call( req );
611 abs_timeout = reply->timeout;
612 apc_handle = reply->apc_handle;
613 call = reply->call;
615 SERVER_END_REQ;
616 if (ret == STATUS_PENDING) ret = wait_select_reply( &cookie );
617 if (ret != STATUS_USER_APC) break;
618 if (invoke_apc( &call, &result ))
620 /* if we ran a user apc we have to check once more if additional apcs are queued,
621 * but we don't want to wait */
622 abs_timeout = 0;
623 user_apc = TRUE;
624 size = 0;
627 /* don't signal multiple times */
628 if (size >= sizeof(select_op->signal_and_wait) && select_op->op == SELECT_SIGNAL_AND_WAIT)
629 size = offsetof( select_op_t, signal_and_wait.signal );
632 if (ret == STATUS_TIMEOUT && user_apc) ret = STATUS_USER_APC;
634 /* A test on Windows 2000 shows that Windows always yields during
635 a wait, but a wait that is hit by an event gets a priority
636 boost as well. This seems to model that behavior the closest. */
637 if (ret == STATUS_TIMEOUT) NtYieldExecution();
639 return ret;
643 /***********************************************************************
644 * server_queue_process_apc
646 unsigned int server_queue_process_apc( HANDLE process, const apc_call_t *call, apc_result_t *result )
648 for (;;)
650 unsigned int ret;
651 HANDLE handle = 0;
652 BOOL self = FALSE;
654 SERVER_START_REQ( queue_apc )
656 req->handle = wine_server_obj_handle( process );
657 req->call = *call;
658 if (!(ret = wine_server_call( req )))
660 handle = wine_server_ptr_handle( reply->handle );
661 self = reply->self;
664 SERVER_END_REQ;
665 if (ret != STATUS_SUCCESS) return ret;
667 if (self)
669 invoke_apc( call, result );
671 else
673 NtWaitForSingleObject( handle, FALSE, NULL );
675 SERVER_START_REQ( get_apc_result )
677 req->handle = wine_server_obj_handle( handle );
678 if (!(ret = wine_server_call( req ))) *result = reply->result;
680 SERVER_END_REQ;
682 if (!ret && result->type == APC_NONE) continue; /* APC didn't run, try again */
684 return ret;
689 /***********************************************************************
690 * wine_server_send_fd (NTDLL.@)
692 * Send a file descriptor to the server.
694 * PARAMS
695 * fd [I] file descriptor to send
697 * RETURNS
698 * nothing
700 void CDECL wine_server_send_fd( int fd )
702 struct send_fd data;
703 struct msghdr msghdr;
704 struct iovec vec;
705 int ret;
707 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
708 msghdr.msg_accrights = (void *)&fd;
709 msghdr.msg_accrightslen = sizeof(fd);
710 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
711 char cmsg_buffer[256];
712 struct cmsghdr *cmsg;
713 msghdr.msg_control = cmsg_buffer;
714 msghdr.msg_controllen = sizeof(cmsg_buffer);
715 msghdr.msg_flags = 0;
716 cmsg = CMSG_FIRSTHDR( &msghdr );
717 cmsg->cmsg_len = CMSG_LEN( sizeof(fd) );
718 cmsg->cmsg_level = SOL_SOCKET;
719 cmsg->cmsg_type = SCM_RIGHTS;
720 *(int *)CMSG_DATA(cmsg) = fd;
721 msghdr.msg_controllen = cmsg->cmsg_len;
722 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
724 msghdr.msg_name = NULL;
725 msghdr.msg_namelen = 0;
726 msghdr.msg_iov = &vec;
727 msghdr.msg_iovlen = 1;
729 vec.iov_base = (void *)&data;
730 vec.iov_len = sizeof(data);
732 data.tid = GetCurrentThreadId();
733 data.fd = fd;
735 for (;;)
737 if ((ret = sendmsg( fd_socket, &msghdr, 0 )) == sizeof(data)) return;
738 if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
739 if (errno == EINTR) continue;
740 if (errno == EPIPE) abort_thread(0);
741 server_protocol_perror( "sendmsg" );
746 /***********************************************************************
747 * receive_fd
749 * Receive a file descriptor passed from the server.
751 static int receive_fd( obj_handle_t *handle )
753 struct iovec vec;
754 struct msghdr msghdr;
755 int ret, fd = -1;
757 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
758 msghdr.msg_accrights = (void *)&fd;
759 msghdr.msg_accrightslen = sizeof(fd);
760 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
761 char cmsg_buffer[256];
762 msghdr.msg_control = cmsg_buffer;
763 msghdr.msg_controllen = sizeof(cmsg_buffer);
764 msghdr.msg_flags = 0;
765 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
767 msghdr.msg_name = NULL;
768 msghdr.msg_namelen = 0;
769 msghdr.msg_iov = &vec;
770 msghdr.msg_iovlen = 1;
771 vec.iov_base = (void *)handle;
772 vec.iov_len = sizeof(*handle);
774 for (;;)
776 if ((ret = recvmsg( fd_socket, &msghdr, MSG_CMSG_CLOEXEC )) > 0)
778 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
779 struct cmsghdr *cmsg;
780 for (cmsg = CMSG_FIRSTHDR( &msghdr ); cmsg; cmsg = CMSG_NXTHDR( &msghdr, cmsg ))
782 if (cmsg->cmsg_level != SOL_SOCKET) continue;
783 if (cmsg->cmsg_type == SCM_RIGHTS) fd = *(int *)CMSG_DATA(cmsg);
784 #ifdef SCM_CREDENTIALS
785 else if (cmsg->cmsg_type == SCM_CREDENTIALS)
787 struct ucred *ucred = (struct ucred *)CMSG_DATA(cmsg);
788 server_pid = ucred->pid;
790 #endif
792 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
793 if (fd != -1) fcntl( fd, F_SETFD, FD_CLOEXEC ); /* in case MSG_CMSG_CLOEXEC is not supported */
794 return fd;
796 if (!ret) break;
797 if (errno == EINTR) continue;
798 if (errno == EPIPE) break;
799 server_protocol_perror("recvmsg");
801 /* the server closed the connection; time to die... */
802 abort_thread(0);
806 /***********************************************************************/
807 /* fd cache support */
809 #include "pshpack1.h"
810 union fd_cache_entry
812 LONG64 data;
813 struct
815 int fd;
816 enum server_fd_type type : 5;
817 unsigned int access : 3;
818 unsigned int options : 24;
819 } s;
821 #include "poppack.h"
823 C_ASSERT( sizeof(union fd_cache_entry) == sizeof(LONG64) );
825 #define FD_CACHE_BLOCK_SIZE (65536 / sizeof(union fd_cache_entry))
826 #define FD_CACHE_ENTRIES 128
828 static union fd_cache_entry *fd_cache[FD_CACHE_ENTRIES];
829 static union fd_cache_entry fd_cache_initial_block[FD_CACHE_BLOCK_SIZE];
831 static inline unsigned int handle_to_index( HANDLE handle, unsigned int *entry )
833 unsigned int idx = (wine_server_obj_handle(handle) >> 2) - 1;
834 *entry = idx / FD_CACHE_BLOCK_SIZE;
835 return idx % FD_CACHE_BLOCK_SIZE;
839 /***********************************************************************
840 * add_fd_to_cache
842 * Caller must hold fd_cache_section.
844 static BOOL add_fd_to_cache( HANDLE handle, int fd, enum server_fd_type type,
845 unsigned int access, unsigned int options )
847 unsigned int entry, idx = handle_to_index( handle, &entry );
848 union fd_cache_entry cache;
850 if (entry >= FD_CACHE_ENTRIES)
852 FIXME( "too many allocated handles, not caching %p\n", handle );
853 return FALSE;
856 if (!fd_cache[entry]) /* do we need to allocate a new block of entries? */
858 if (!entry) fd_cache[0] = fd_cache_initial_block;
859 else
861 void *ptr = wine_anon_mmap( NULL, FD_CACHE_BLOCK_SIZE * sizeof(union fd_cache_entry),
862 PROT_READ | PROT_WRITE, 0 );
863 if (ptr == MAP_FAILED) return FALSE;
864 fd_cache[entry] = ptr;
868 /* store fd+1 so that 0 can be used as the unset value */
869 cache.s.fd = fd + 1;
870 cache.s.type = type;
871 cache.s.access = access;
872 cache.s.options = options;
873 cache.data = interlocked_xchg64( &fd_cache[entry][idx].data, cache.data );
874 assert( !cache.s.fd );
875 return TRUE;
879 /***********************************************************************
880 * get_cached_fd
882 static inline int get_cached_fd( HANDLE handle, enum server_fd_type *type,
883 unsigned int *access, unsigned int *options )
885 unsigned int entry, idx = handle_to_index( handle, &entry );
886 int fd = -1;
888 if (entry < FD_CACHE_ENTRIES && fd_cache[entry])
890 union fd_cache_entry cache;
891 cache.data = interlocked_cmpxchg64( &fd_cache[entry][idx].data, 0, 0 );
892 fd = cache.s.fd - 1;
893 if (type) *type = cache.s.type;
894 if (access) *access = cache.s.access;
895 if (options) *options = cache.s.options;
897 return fd;
901 /***********************************************************************
902 * server_remove_fd_from_cache
904 int server_remove_fd_from_cache( HANDLE handle )
906 unsigned int entry, idx = handle_to_index( handle, &entry );
907 int fd = -1;
909 if (entry < FD_CACHE_ENTRIES && fd_cache[entry])
911 union fd_cache_entry cache;
912 cache.data = interlocked_xchg64( &fd_cache[entry][idx].data, 0 );
913 fd = cache.s.fd - 1;
916 return fd;
920 /***********************************************************************
921 * server_get_unix_fd
923 * The returned unix_fd should be closed iff needs_close is non-zero.
925 int server_get_unix_fd( HANDLE handle, unsigned int wanted_access, int *unix_fd,
926 int *needs_close, enum server_fd_type *type, unsigned int *options )
928 sigset_t sigset;
929 obj_handle_t fd_handle;
930 int ret = 0, fd;
931 unsigned int access = 0;
933 *unix_fd = -1;
934 *needs_close = 0;
935 wanted_access &= FILE_READ_DATA | FILE_WRITE_DATA | FILE_APPEND_DATA;
937 fd = get_cached_fd( handle, type, &access, options );
938 if (fd != -1) goto done;
940 server_enter_uninterrupted_section( &fd_cache_section, &sigset );
941 fd = get_cached_fd( handle, type, &access, options );
942 if (fd == -1)
944 SERVER_START_REQ( get_handle_fd )
946 req->handle = wine_server_obj_handle( handle );
947 if (!(ret = wine_server_call( req )))
949 if (type) *type = reply->type;
950 if (options) *options = reply->options;
951 access = reply->access;
952 if ((fd = receive_fd( &fd_handle )) != -1)
954 assert( wine_server_ptr_handle(fd_handle) == handle );
955 *needs_close = (!reply->cacheable ||
956 !add_fd_to_cache( handle, fd, reply->type,
957 reply->access, reply->options ));
959 else ret = STATUS_TOO_MANY_OPENED_FILES;
962 SERVER_END_REQ;
964 server_leave_uninterrupted_section( &fd_cache_section, &sigset );
966 done:
967 if (!ret && ((access & wanted_access) != wanted_access))
969 ret = STATUS_ACCESS_DENIED;
970 if (*needs_close) close( fd );
972 if (!ret) *unix_fd = fd;
973 return ret;
977 /***********************************************************************
978 * wine_server_fd_to_handle (NTDLL.@)
980 * Allocate a file handle for a Unix file descriptor.
982 * PARAMS
983 * fd [I] Unix file descriptor.
984 * access [I] Win32 access flags.
985 * attributes [I] Object attributes.
986 * handle [O] Address where Wine file handle will be stored.
988 * RETURNS
989 * NTSTATUS code
991 int CDECL wine_server_fd_to_handle( int fd, unsigned int access, unsigned int attributes, HANDLE *handle )
993 int ret;
995 *handle = 0;
996 wine_server_send_fd( fd );
998 SERVER_START_REQ( alloc_file_handle )
1000 req->access = access;
1001 req->attributes = attributes;
1002 req->fd = fd;
1003 if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
1005 SERVER_END_REQ;
1006 return ret;
1010 /***********************************************************************
1011 * wine_server_handle_to_fd (NTDLL.@)
1013 * Retrieve the file descriptor corresponding to a file handle.
1015 * PARAMS
1016 * handle [I] Wine file handle.
1017 * access [I] Win32 file access rights requested.
1018 * unix_fd [O] Address where Unix file descriptor will be stored.
1019 * options [O] Address where the file open options will be stored. Optional.
1021 * RETURNS
1022 * NTSTATUS code
1024 int CDECL wine_server_handle_to_fd( HANDLE handle, unsigned int access, int *unix_fd,
1025 unsigned int *options )
1027 int needs_close, ret = server_get_unix_fd( handle, access, unix_fd, &needs_close, NULL, options );
1029 if (!ret && !needs_close)
1031 if ((*unix_fd = dup(*unix_fd)) == -1) ret = FILE_GetNtStatus();
1033 return ret;
1037 /***********************************************************************
1038 * wine_server_release_fd (NTDLL.@)
1040 * Release the Unix file descriptor returned by wine_server_handle_to_fd.
1042 * PARAMS
1043 * handle [I] Wine file handle.
1044 * unix_fd [I] Unix file descriptor to release.
1046 * RETURNS
1047 * nothing
1049 void CDECL wine_server_release_fd( HANDLE handle, int unix_fd )
1051 close( unix_fd );
1055 /***********************************************************************
1056 * server_pipe
1058 * Create a pipe for communicating with the server.
1060 int server_pipe( int fd[2] )
1062 int ret;
1063 #ifdef HAVE_PIPE2
1064 static BOOL have_pipe2 = TRUE;
1066 if (have_pipe2)
1068 if (!(ret = pipe2( fd, O_CLOEXEC ))) return ret;
1069 if (errno == ENOSYS || errno == EINVAL) have_pipe2 = FALSE; /* don't try again */
1071 #endif
1072 if (!(ret = pipe( fd )))
1074 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1075 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1077 return ret;
1081 /***********************************************************************
1082 * start_server
1084 * Start a new wine server.
1086 static void start_server(void)
1088 static BOOL started; /* we only try once */
1089 char *argv[3];
1090 static char wineserver[] = "server/wineserver";
1091 static char debug[] = "-d";
1093 if (!started)
1095 int status;
1096 int pid = fork();
1097 if (pid == -1) fatal_perror( "fork" );
1098 if (!pid)
1100 argv[0] = wineserver;
1101 argv[1] = TRACE_ON(server) ? debug : NULL;
1102 argv[2] = NULL;
1103 wine_exec_wine_binary( argv[0], argv, getenv("WINESERVER") );
1104 fatal_error( "could not exec wineserver\n" );
1106 waitpid( pid, &status, 0 );
1107 status = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
1108 if (status == 2) return; /* server lock held by someone else, will retry later */
1109 if (status) exit(status); /* server failed */
1110 started = TRUE;
1115 /***********************************************************************
1116 * setup_config_dir
1118 * Setup the wine configuration dir.
1120 static void setup_config_dir(void)
1122 const char *p, *config_dir = wine_get_config_dir();
1124 if (chdir( config_dir ) == -1)
1126 if (errno != ENOENT) fatal_perror( "chdir to %s\n", config_dir );
1128 if ((p = strrchr( config_dir, '/' )) && p != config_dir)
1130 struct stat st;
1131 char *tmp_dir;
1133 if (!(tmp_dir = malloc( p + 1 - config_dir ))) fatal_error( "out of memory\n" );
1134 memcpy( tmp_dir, config_dir, p - config_dir );
1135 tmp_dir[p - config_dir] = 0;
1136 if (!stat( tmp_dir, &st ) && st.st_uid != getuid())
1137 fatal_error( "'%s' is not owned by you, refusing to create a configuration directory there\n",
1138 tmp_dir );
1139 free( tmp_dir );
1142 mkdir( config_dir, 0777 );
1143 if (chdir( config_dir ) == -1) fatal_perror( "chdir to %s\n", config_dir );
1145 if ((p = getenv( "WINEARCH" )) && !strcmp( p, "win32" ))
1147 /* force creation of a 32-bit prefix */
1148 int fd = open( "system.reg", O_WRONLY | O_CREAT | O_EXCL, 0666 );
1149 if (fd != -1)
1151 static const char regfile[] = "WINE REGISTRY Version 2\n\n#arch=win32\n";
1152 write( fd, regfile, sizeof(regfile) - 1 );
1153 close( fd );
1156 MESSAGE( "wine: created the configuration directory '%s'\n", config_dir );
1159 if (mkdir( "dosdevices", 0777 ) == -1)
1161 if (errno == EEXIST) return;
1162 fatal_perror( "cannot create %s/dosdevices\n", config_dir );
1165 /* create the drive symlinks */
1167 mkdir( "drive_c", 0777 );
1168 symlink( "../drive_c", "dosdevices/c:" );
1169 symlink( "/", "dosdevices/z:" );
1173 /***********************************************************************
1174 * server_connect_error
1176 * Try to display a meaningful explanation of why we couldn't connect
1177 * to the server.
1179 static void server_connect_error( const char *serverdir )
1181 int fd;
1182 struct flock fl;
1184 if ((fd = open( LOCKNAME, O_WRONLY )) == -1)
1185 fatal_error( "for some mysterious reason, the wine server never started.\n" );
1187 fl.l_type = F_WRLCK;
1188 fl.l_whence = SEEK_SET;
1189 fl.l_start = 0;
1190 fl.l_len = 1;
1191 if (fcntl( fd, F_GETLK, &fl ) != -1)
1193 if (fl.l_type == F_WRLCK) /* the file is locked */
1194 fatal_error( "a wine server seems to be running, but I cannot connect to it.\n"
1195 " You probably need to kill that process (it might be pid %d).\n",
1196 (int)fl.l_pid );
1197 fatal_error( "for some mysterious reason, the wine server failed to run.\n" );
1199 fatal_error( "the file system of '%s' doesn't support locks,\n"
1200 " and there is a 'socket' file in that directory that prevents wine from starting.\n"
1201 " You should make sure no wine server is running, remove that file and try again.\n",
1202 serverdir );
1206 /***********************************************************************
1207 * server_connect
1209 * Attempt to connect to an existing server socket.
1210 * We need to be in the server directory already.
1212 static int server_connect(void)
1214 const char *serverdir;
1215 struct sockaddr_un addr;
1216 struct stat st;
1217 int s, slen, retry, fd_cwd;
1219 /* retrieve the current directory */
1220 fd_cwd = open( ".", O_RDONLY );
1221 if (fd_cwd != -1) fcntl( fd_cwd, F_SETFD, 1 ); /* set close on exec flag */
1223 setup_config_dir();
1224 serverdir = wine_get_server_dir();
1226 /* chdir to the server directory */
1227 if (chdir( serverdir ) == -1)
1229 if (errno != ENOENT) fatal_perror( "chdir to %s", serverdir );
1230 start_server();
1231 if (chdir( serverdir ) == -1) fatal_perror( "chdir to %s", serverdir );
1234 /* make sure we are at the right place */
1235 if (stat( ".", &st ) == -1) fatal_perror( "stat %s", serverdir );
1236 if (st.st_uid != getuid()) fatal_error( "'%s' is not owned by you\n", serverdir );
1237 if (st.st_mode & 077) fatal_error( "'%s' must not be accessible by other users\n", serverdir );
1239 for (retry = 0; retry < 6; retry++)
1241 /* if not the first try, wait a bit to leave the previous server time to exit */
1242 if (retry)
1244 usleep( 100000 * retry * retry );
1245 start_server();
1246 if (lstat( SOCKETNAME, &st ) == -1) continue; /* still no socket, wait a bit more */
1248 else if (lstat( SOCKETNAME, &st ) == -1) /* check for an already existing socket */
1250 if (errno != ENOENT) fatal_perror( "lstat %s/%s", serverdir, SOCKETNAME );
1251 start_server();
1252 if (lstat( SOCKETNAME, &st ) == -1) continue; /* still no socket, wait a bit more */
1255 /* make sure the socket is sane (ISFIFO needed for Solaris) */
1256 if (!S_ISSOCK(st.st_mode) && !S_ISFIFO(st.st_mode))
1257 fatal_error( "'%s/%s' is not a socket\n", serverdir, SOCKETNAME );
1258 if (st.st_uid != getuid())
1259 fatal_error( "'%s/%s' is not owned by you\n", serverdir, SOCKETNAME );
1261 /* try to connect to it */
1262 addr.sun_family = AF_UNIX;
1263 strcpy( addr.sun_path, SOCKETNAME );
1264 slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
1265 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
1266 addr.sun_len = slen;
1267 #endif
1268 if ((s = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_perror( "socket" );
1269 #ifdef SO_PASSCRED
1270 else
1272 int enable = 1;
1273 setsockopt( s, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
1275 #endif
1276 if (connect( s, (struct sockaddr *)&addr, slen ) != -1)
1278 /* switch back to the starting directory */
1279 if (fd_cwd != -1)
1281 fchdir( fd_cwd );
1282 close( fd_cwd );
1284 fcntl( s, F_SETFD, 1 ); /* set close on exec flag */
1285 return s;
1287 close( s );
1289 server_connect_error( serverdir );
1293 #ifdef __APPLE__
1294 #include <mach/mach.h>
1295 #include <mach/mach_error.h>
1296 #include <servers/bootstrap.h>
1298 /* send our task port to the server */
1299 static void send_server_task_port(void)
1301 mach_port_t bootstrap_port, wineserver_port;
1302 kern_return_t kret;
1304 struct {
1305 mach_msg_header_t header;
1306 mach_msg_body_t body;
1307 mach_msg_port_descriptor_t task_port;
1308 } msg;
1310 if (task_get_bootstrap_port(mach_task_self(), &bootstrap_port) != KERN_SUCCESS) return;
1312 kret = bootstrap_look_up(bootstrap_port, (char*)wine_get_server_dir(), &wineserver_port);
1313 if (kret != KERN_SUCCESS)
1314 fatal_error( "cannot find the server port: 0x%08x\n", kret );
1316 mach_port_deallocate(mach_task_self(), bootstrap_port);
1318 msg.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0) | MACH_MSGH_BITS_COMPLEX;
1319 msg.header.msgh_size = sizeof(msg);
1320 msg.header.msgh_remote_port = wineserver_port;
1321 msg.header.msgh_local_port = MACH_PORT_NULL;
1323 msg.body.msgh_descriptor_count = 1;
1324 msg.task_port.name = mach_task_self();
1325 msg.task_port.disposition = MACH_MSG_TYPE_COPY_SEND;
1326 msg.task_port.type = MACH_MSG_PORT_DESCRIPTOR;
1328 kret = mach_msg_send(&msg.header);
1329 if (kret != KERN_SUCCESS)
1330 server_protocol_error( "mach_msg_send failed: 0x%08x\n", kret );
1332 mach_port_deallocate(mach_task_self(), wineserver_port);
1334 #endif /* __APPLE__ */
1337 /***********************************************************************
1338 * get_unix_tid
1340 * Retrieve the Unix tid to use on the server side for the current thread.
1342 static int get_unix_tid(void)
1344 int ret = -1;
1345 #ifdef HAVE_PTHREAD_GETTHREADID_NP
1346 ret = pthread_getthreadid_np();
1347 #elif defined(linux)
1348 ret = syscall( __NR_gettid );
1349 #elif defined(__sun)
1350 ret = pthread_self();
1351 #elif defined(__APPLE__)
1352 ret = mach_thread_self();
1353 mach_port_deallocate(mach_task_self(), ret);
1354 #elif defined(__NetBSD__)
1355 ret = _lwp_self();
1356 #elif defined(__FreeBSD__)
1357 long lwpid;
1358 thr_self( &lwpid );
1359 ret = lwpid;
1360 #elif defined(__DragonFly__)
1361 ret = lwp_gettid();
1362 #endif
1363 return ret;
1367 #ifdef SIGXCPU
1368 static int convert_tidtostr_r(char *s, unsigned hex)
1370 int i;
1371 char *start = s;
1373 for (i = 0; i < 8; ++i) {
1374 unsigned c = hex >> (28 - 4 * i);
1376 if (c || i >= 4)
1377 { /* last 4 digits always printed */
1378 c &= 0xf;
1380 if (c < 10)
1381 *s++ = '0' + c;
1382 else
1383 *s++ = 'a' + c - 10;
1387 *s++ = ':';
1388 return s - start;
1391 static int convert_stamptostr_r(char *s, unsigned stamp)
1393 unsigned high = stamp / 1000, low = stamp % 1000, i;
1394 char *start = s;
1396 for (i = 1000000; i; i /= 10) {
1397 if (high >= i)
1398 *s++ = '0' + (high / i) % 10;
1399 else if (i <= 100)
1400 *s++ = ' ';
1403 *s++ = '.';
1405 for (i = 100; i; i /= 10)
1406 *s++ = '0' + (low / i) % 10;
1408 *s++ = ':';
1410 return s - start;
1414 static const char throttle_str[] =
1415 "fixme:winediag:sigxcpu_handler realtime priority was throttled due to program exceeding time limit\n";
1417 static void sigxcpu_handler( int sig )
1419 char temp[16];
1420 int old_errno = errno, ret;
1422 if (server_pid > 0)
1423 kill(server_pid, SIGXCPU);
1424 else {
1425 /* uh oh, somehow init failed to get server_pid */
1426 struct sched_param parm;
1427 memset(&parm, 0, sizeof(parm));
1428 sched_setscheduler(0, SCHED_OTHER | SCHED_RESET_ON_FORK, &parm);
1431 if (FIXME_ON(winediag)) {
1432 if (TRACE_ON(timestamp)) {
1433 ret = convert_stamptostr_r(temp, NtGetTickCount());
1434 write(2, temp, ret);
1437 if (TRACE_ON(tid)) {
1438 ret = convert_tidtostr_r(temp, GetCurrentThreadId());
1439 write(2, temp, ret);
1442 write(2, throttle_str, sizeof(throttle_str)-1);
1445 errno = old_errno;
1447 #endif
1449 /***********************************************************************
1450 * server_init_process
1452 * Start the server and create the initial socket pair.
1454 void server_init_process(void)
1456 obj_handle_t version;
1457 const char *env_socket = getenv( "WINESERVERSOCKET" );
1458 #ifdef SIGXCPU
1459 struct sigaction sa;
1461 sa.sa_handler = sigxcpu_handler;
1462 sigemptyset(&sa.sa_mask);
1463 sa.sa_flags = 0;
1464 sigaction( SIGXCPU, &sa, NULL );
1465 #endif
1467 server_pid = -1;
1468 if (env_socket)
1470 fd_socket = atoi( env_socket );
1471 if (fcntl( fd_socket, F_SETFD, 1 ) == -1)
1472 fatal_perror( "Bad server socket %d", fd_socket );
1473 unsetenv( "WINESERVERSOCKET" );
1475 else fd_socket = server_connect();
1477 /* setup the signal mask */
1478 sigemptyset( &server_block_set );
1479 sigaddset( &server_block_set, SIGALRM );
1480 sigaddset( &server_block_set, SIGIO );
1481 sigaddset( &server_block_set, SIGINT );
1482 sigaddset( &server_block_set, SIGHUP );
1483 sigaddset( &server_block_set, SIGUSR1 );
1484 sigaddset( &server_block_set, SIGUSR2 );
1485 sigaddset( &server_block_set, SIGCHLD );
1486 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
1488 /* receive the first thread request fd on the main socket */
1489 ntdll_get_thread_data()->request_fd = receive_fd( &version );
1491 #ifdef SO_PASSCRED
1492 /* now that we hopefully received the server_pid, disable SO_PASSCRED */
1494 int enable = 0;
1495 setsockopt( fd_socket, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
1497 #endif
1499 if (version != SERVER_PROTOCOL_VERSION)
1500 server_protocol_error( "version mismatch %d/%d.\n"
1501 "Your %s binary was not upgraded correctly,\n"
1502 "or you have an older one somewhere in your PATH.\n"
1503 "Or maybe the wrong wineserver is still running?\n",
1504 version, SERVER_PROTOCOL_VERSION,
1505 (version > SERVER_PROTOCOL_VERSION) ? "wine" : "wineserver" );
1506 #ifdef __APPLE__
1507 send_server_task_port();
1508 #endif
1509 #if defined(__linux__) && defined(HAVE_PRCTL)
1510 /* work around Ubuntu's ptrace breakage */
1511 if (server_pid != -1) prctl( 0x59616d61 /* PR_SET_PTRACER */, server_pid );
1512 #endif
1516 /***********************************************************************
1517 * server_init_process_done
1519 NTSTATUS server_init_process_done(void)
1521 PEB *peb = NtCurrentTeb()->Peb;
1522 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
1523 NTSTATUS status;
1525 /* Install signal handlers; this cannot be done earlier, since we cannot
1526 * send exceptions to the debugger before the create process event that
1527 * is sent by REQ_INIT_PROCESS_DONE.
1528 * We do need the handlers in place by the time the request is over, so
1529 * we set them up here. If we segfault between here and the server call
1530 * something is very wrong... */
1531 signal_init_process();
1533 /* Signal the parent process to continue */
1534 SERVER_START_REQ( init_process_done )
1536 req->module = wine_server_client_ptr( peb->ImageBaseAddress );
1537 #ifdef __i386__
1538 req->ldt_copy = wine_server_client_ptr( &wine_ldt_copy );
1539 #endif
1540 req->entry = wine_server_client_ptr( (char *)peb->ImageBaseAddress + nt->OptionalHeader.AddressOfEntryPoint );
1541 req->gui = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
1542 status = wine_server_call( req );
1544 SERVER_END_REQ;
1546 return status;
1549 /***********************************************************************
1550 * server_init_thread
1552 * Send an init thread request. Return 0 if OK.
1554 size_t server_init_thread( void *entry_point )
1556 static const char *cpu_names[] = { "x86", "x86_64", "PowerPC", "ARM", "ARM64" };
1557 static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
1558 const char *arch = getenv( "WINEARCH" );
1559 int ret;
1560 int reply_pipe[2];
1561 struct sigaction sig_act;
1562 size_t info_size;
1564 sig_act.sa_handler = SIG_IGN;
1565 sig_act.sa_flags = 0;
1566 sigemptyset( &sig_act.sa_mask );
1568 /* ignore SIGPIPE so that we get an EPIPE error instead */
1569 sigaction( SIGPIPE, &sig_act, NULL );
1571 /* create the server->client communication pipes */
1572 if (server_pipe( reply_pipe ) == -1) server_protocol_perror( "pipe" );
1573 if (server_pipe( ntdll_get_thread_data()->wait_fd ) == -1) server_protocol_perror( "pipe" );
1574 wine_server_send_fd( reply_pipe[1] );
1575 wine_server_send_fd( ntdll_get_thread_data()->wait_fd[1] );
1576 ntdll_get_thread_data()->reply_fd = reply_pipe[0];
1577 close( reply_pipe[1] );
1579 SERVER_START_REQ( init_thread )
1581 req->unix_pid = getpid();
1582 req->unix_tid = get_unix_tid();
1583 req->teb = wine_server_client_ptr( NtCurrentTeb() );
1584 req->entry = wine_server_client_ptr( entry_point );
1585 req->reply_fd = reply_pipe[1];
1586 req->wait_fd = ntdll_get_thread_data()->wait_fd[1];
1587 req->debug_level = (TRACE_ON(server) != 0);
1588 req->cpu = client_cpu;
1589 ret = wine_server_call( req );
1590 NtCurrentTeb()->ClientId.UniqueProcess = ULongToHandle(reply->pid);
1591 NtCurrentTeb()->ClientId.UniqueThread = ULongToHandle(reply->tid);
1592 info_size = reply->info_size;
1593 server_start_time = reply->server_start;
1594 server_cpus = reply->all_cpus;
1596 SERVER_END_REQ;
1598 is_wow64 = !is_win64 && (server_cpus & ((1 << CPU_x86_64) | (1 << CPU_ARM64))) != 0;
1599 ntdll_get_thread_data()->wow64_redir = is_wow64;
1601 switch (ret)
1603 case STATUS_SUCCESS:
1604 if (arch)
1606 if (!strcmp( arch, "win32" ) && (is_win64 || is_wow64))
1607 fatal_error( "WINEARCH set to win32 but '%s' is a 64-bit installation.\n",
1608 wine_get_config_dir() );
1609 if (!strcmp( arch, "win64" ) && !is_win64 && !is_wow64)
1610 fatal_error( "WINEARCH set to win64 but '%s' is a 32-bit installation.\n",
1611 wine_get_config_dir() );
1613 return info_size;
1614 case STATUS_INVALID_IMAGE_WIN_64:
1615 fatal_error( "'%s' is a 32-bit installation, it cannot support 64-bit applications.\n",
1616 wine_get_config_dir() );
1617 case STATUS_NOT_SUPPORTED:
1618 fatal_error( "'%s' is a 64-bit installation, it cannot be used with a 32-bit wineserver.\n",
1619 wine_get_config_dir() );
1620 case STATUS_INVALID_IMAGE_FORMAT:
1621 fatal_error( "wineserver doesn't support the %s architecture\n", cpu_names[client_cpu] );
1622 default:
1623 server_protocol_error( "init_thread failed with status %x\n", ret );