wined3d: Return void from wined3d_device_set_light_enable().
[wine.git] / dlls / ntdll / server.c
blob4facdc08a72e2ace4fce28482962221b24e13d33
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);
87 /* Some versions of glibc don't define this */
88 #ifndef SCM_RIGHTS
89 #define SCM_RIGHTS 1
90 #endif
92 #ifndef MSG_CMSG_CLOEXEC
93 #define MSG_CMSG_CLOEXEC 0
94 #endif
96 #define SOCKETNAME "socket" /* name of the socket file */
97 #define LOCKNAME "lock" /* name of the lock file */
99 #ifdef __i386__
100 static const enum cpu_type client_cpu = CPU_x86;
101 #elif defined(__x86_64__)
102 static const enum cpu_type client_cpu = CPU_x86_64;
103 #elif defined(__powerpc__)
104 static const enum cpu_type client_cpu = CPU_POWERPC;
105 #elif defined(__arm__)
106 static const enum cpu_type client_cpu = CPU_ARM;
107 #elif defined(__aarch64__)
108 static const enum cpu_type client_cpu = CPU_ARM64;
109 #else
110 #error Unsupported CPU
111 #endif
113 unsigned int server_cpus = 0;
114 BOOL is_wow64 = FALSE;
116 timeout_t server_start_time = 0; /* time of server startup */
118 sigset_t server_block_set; /* signals to block during server calls */
119 static int fd_socket = -1; /* socket to exchange file descriptors with the server */
120 static pid_t server_pid;
122 static RTL_CRITICAL_SECTION fd_cache_section;
123 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
125 0, 0, &fd_cache_section,
126 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
127 0, 0, { (DWORD_PTR)(__FILE__ ": fd_cache_section") }
129 static RTL_CRITICAL_SECTION fd_cache_section = { &critsect_debug, -1, 0, 0, 0, 0 };
131 /* atomically exchange a 64-bit value */
132 static inline LONG64 interlocked_xchg64( LONG64 *dest, LONG64 val )
134 #ifdef _WIN64
135 return (LONG64)interlocked_xchg_ptr( (void **)dest, (void *)val );
136 #else
137 LONG64 tmp = *dest;
138 while (interlocked_cmpxchg64( dest, val, tmp ) != tmp) tmp = *dest;
139 return tmp;
140 #endif
143 #ifdef __GNUC__
144 static void fatal_error( const char *err, ... ) __attribute__((noreturn, format(printf,1,2)));
145 static void fatal_perror( const char *err, ... ) __attribute__((noreturn, format(printf,1,2)));
146 static void server_connect_error( const char *serverdir ) __attribute__((noreturn));
147 #endif
149 /* die on a fatal error; use only during initialization */
150 static void fatal_error( const char *err, ... )
152 va_list args;
154 va_start( args, err );
155 fprintf( stderr, "wine: " );
156 vfprintf( stderr, err, args );
157 va_end( args );
158 exit(1);
161 /* die on a fatal error; use only during initialization */
162 static void fatal_perror( const char *err, ... )
164 va_list args;
166 va_start( args, err );
167 fprintf( stderr, "wine: " );
168 vfprintf( stderr, err, args );
169 perror( " " );
170 va_end( args );
171 exit(1);
175 /***********************************************************************
176 * server_protocol_error
178 static DECLSPEC_NORETURN void server_protocol_error( const char *err, ... )
180 va_list args;
182 va_start( args, err );
183 fprintf( stderr, "wine client error:%x: ", GetCurrentThreadId() );
184 vfprintf( stderr, err, args );
185 va_end( args );
186 abort_thread(1);
190 /***********************************************************************
191 * server_protocol_perror
193 static DECLSPEC_NORETURN void server_protocol_perror( const char *err )
195 fprintf( stderr, "wine client error:%x: ", GetCurrentThreadId() );
196 perror( err );
197 abort_thread(1);
201 /***********************************************************************
202 * send_request
204 * Send a request to the server.
206 static unsigned int send_request( const struct __server_request_info *req )
208 unsigned int i;
209 int ret;
211 if (!req->u.req.request_header.request_size)
213 if ((ret = write( ntdll_get_thread_data()->request_fd, &req->u.req,
214 sizeof(req->u.req) )) == sizeof(req->u.req)) return STATUS_SUCCESS;
217 else
219 struct iovec vec[__SERVER_MAX_DATA+1];
221 vec[0].iov_base = (void *)&req->u.req;
222 vec[0].iov_len = sizeof(req->u.req);
223 for (i = 0; i < req->data_count; i++)
225 vec[i+1].iov_base = (void *)req->data[i].ptr;
226 vec[i+1].iov_len = req->data[i].size;
228 if ((ret = writev( ntdll_get_thread_data()->request_fd, vec, i+1 )) ==
229 req->u.req.request_header.request_size + sizeof(req->u.req)) return STATUS_SUCCESS;
232 if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
233 if (errno == EPIPE) abort_thread(0);
234 if (errno == EFAULT) return STATUS_ACCESS_VIOLATION;
235 server_protocol_perror( "write" );
239 /***********************************************************************
240 * read_reply_data
242 * Read data from the reply buffer; helper for wait_reply.
244 static void read_reply_data( void *buffer, size_t size )
246 int ret;
248 for (;;)
250 if ((ret = read( ntdll_get_thread_data()->reply_fd, buffer, size )) > 0)
252 if (!(size -= ret)) return;
253 buffer = (char *)buffer + ret;
254 continue;
256 if (!ret) break;
257 if (errno == EINTR) continue;
258 if (errno == EPIPE) break;
259 server_protocol_perror("read");
261 /* the server closed the connection; time to die... */
262 abort_thread(0);
266 /***********************************************************************
267 * wait_reply
269 * Wait for a reply from the server.
271 static inline unsigned int wait_reply( struct __server_request_info *req )
273 read_reply_data( &req->u.reply, sizeof(req->u.reply) );
274 if (req->u.reply.reply_header.reply_size)
275 read_reply_data( req->reply_data, req->u.reply.reply_header.reply_size );
276 return req->u.reply.reply_header.error;
280 /***********************************************************************
281 * server_call_unlocked
283 unsigned int server_call_unlocked( void *req_ptr )
285 struct __server_request_info * const req = req_ptr;
286 unsigned int ret;
288 if ((ret = send_request( req ))) return ret;
289 return wait_reply( req );
293 /***********************************************************************
294 * wine_server_call (NTDLL.@)
296 * Perform a server call.
298 * PARAMS
299 * req_ptr [I/O] Function dependent data
301 * RETURNS
302 * Depends on server function being called, but usually an NTSTATUS code.
304 * NOTES
305 * Use the SERVER_START_REQ and SERVER_END_REQ to help you fill out the
306 * server request structure for the particular call. E.g:
307 *| SERVER_START_REQ( event_op )
308 *| {
309 *| req->handle = handle;
310 *| req->op = SET_EVENT;
311 *| ret = wine_server_call( req );
312 *| }
313 *| SERVER_END_REQ;
315 unsigned int CDECL wine_server_call( void *req_ptr )
317 sigset_t old_set;
318 unsigned int ret;
320 pthread_sigmask( SIG_BLOCK, &server_block_set, &old_set );
321 ret = server_call_unlocked( req_ptr );
322 pthread_sigmask( SIG_SETMASK, &old_set, NULL );
323 return ret;
327 /***********************************************************************
328 * server_enter_uninterrupted_section
330 void server_enter_uninterrupted_section( RTL_CRITICAL_SECTION *cs, sigset_t *sigset )
332 pthread_sigmask( SIG_BLOCK, &server_block_set, sigset );
333 RtlEnterCriticalSection( cs );
337 /***********************************************************************
338 * server_leave_uninterrupted_section
340 void server_leave_uninterrupted_section( RTL_CRITICAL_SECTION *cs, sigset_t *sigset )
342 RtlLeaveCriticalSection( cs );
343 pthread_sigmask( SIG_SETMASK, sigset, NULL );
347 /***********************************************************************
348 * wait_select_reply
350 * Wait for a reply on the waiting pipe of the current thread.
352 int wait_select_reply( void *cookie )
354 int signaled;
355 struct wake_up_reply reply;
356 for (;;)
358 int ret;
359 ret = read( ntdll_get_thread_data()->wait_fd[0], &reply, sizeof(reply) );
360 if (ret == sizeof(reply))
362 if (!reply.cookie) abort_thread( reply.signaled ); /* thread got killed */
363 if (wine_server_get_ptr(reply.cookie) == cookie) return reply.signaled;
364 /* we stole another reply, wait for the real one */
365 signaled = wait_select_reply( cookie );
366 /* and now put the wrong one back in the pipe */
367 for (;;)
369 ret = write( ntdll_get_thread_data()->wait_fd[1], &reply, sizeof(reply) );
370 if (ret == sizeof(reply)) break;
371 if (ret >= 0) server_protocol_error( "partial wakeup write %d\n", ret );
372 if (errno == EINTR) continue;
373 server_protocol_perror("wakeup write");
375 return signaled;
377 if (ret >= 0) server_protocol_error( "partial wakeup read %d\n", ret );
378 if (errno == EINTR) continue;
379 server_protocol_perror("wakeup read");
384 /***********************************************************************
385 * invoke_apc
387 * Invoke a single APC.
390 void invoke_apc( const apc_call_t *call, apc_result_t *result )
392 SIZE_T size;
393 void *addr;
394 pe_image_info_t image_info;
396 memset( result, 0, sizeof(*result) );
398 switch (call->type)
400 case APC_NONE:
401 break;
402 case APC_USER:
404 void (WINAPI *func)(ULONG_PTR,ULONG_PTR,ULONG_PTR) = wine_server_get_ptr( call->user.func );
405 func( call->user.args[0], call->user.args[1], call->user.args[2] );
406 break;
408 case APC_TIMER:
410 void (WINAPI *func)(void*, unsigned int, unsigned int) = wine_server_get_ptr( call->timer.func );
411 func( wine_server_get_ptr( call->timer.arg ),
412 (DWORD)call->timer.time, (DWORD)(call->timer.time >> 32) );
413 break;
415 case APC_ASYNC_IO:
417 IO_STATUS_BLOCK *iosb = wine_server_get_ptr( call->async_io.sb );
418 NTSTATUS (**user)(void *, IO_STATUS_BLOCK *, NTSTATUS) = wine_server_get_ptr( call->async_io.user );
419 result->type = call->type;
420 result->async_io.status = (*user)( user, iosb, call->async_io.status );
421 if (result->async_io.status != STATUS_PENDING)
422 result->async_io.total = iosb->Information;
423 break;
425 case APC_VIRTUAL_ALLOC:
426 result->type = call->type;
427 addr = wine_server_get_ptr( call->virtual_alloc.addr );
428 size = call->virtual_alloc.size;
429 if ((ULONG_PTR)addr == call->virtual_alloc.addr && size == call->virtual_alloc.size)
431 result->virtual_alloc.status = virtual_alloc_aligned( &addr,
432 call->virtual_alloc.zero_bits_64, &size,
433 call->virtual_alloc.op_type,
434 call->virtual_alloc.prot,
435 0 );
436 result->virtual_alloc.addr = wine_server_client_ptr( addr );
437 result->virtual_alloc.size = size;
439 else result->virtual_alloc.status = STATUS_WORKING_SET_LIMIT_RANGE;
440 break;
441 case APC_VIRTUAL_FREE:
442 result->type = call->type;
443 addr = wine_server_get_ptr( call->virtual_free.addr );
444 size = call->virtual_free.size;
445 if ((ULONG_PTR)addr == call->virtual_free.addr && size == call->virtual_free.size)
447 result->virtual_free.status = NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size,
448 call->virtual_free.op_type );
449 result->virtual_free.addr = wine_server_client_ptr( addr );
450 result->virtual_free.size = size;
452 else result->virtual_free.status = STATUS_INVALID_PARAMETER;
453 break;
454 case APC_VIRTUAL_QUERY:
456 MEMORY_BASIC_INFORMATION info;
457 result->type = call->type;
458 addr = wine_server_get_ptr( call->virtual_query.addr );
459 if ((ULONG_PTR)addr == call->virtual_query.addr)
460 result->virtual_query.status = NtQueryVirtualMemory( NtCurrentProcess(),
461 addr, MemoryBasicInformation, &info,
462 sizeof(info), NULL );
463 else
464 result->virtual_query.status = STATUS_WORKING_SET_LIMIT_RANGE;
466 if (result->virtual_query.status == STATUS_SUCCESS)
468 result->virtual_query.base = wine_server_client_ptr( info.BaseAddress );
469 result->virtual_query.alloc_base = wine_server_client_ptr( info.AllocationBase );
470 result->virtual_query.size = info.RegionSize;
471 result->virtual_query.prot = info.Protect;
472 result->virtual_query.alloc_prot = info.AllocationProtect;
473 result->virtual_query.state = info.State >> 12;
474 result->virtual_query.alloc_type = info.Type >> 16;
476 break;
478 case APC_VIRTUAL_PROTECT:
479 result->type = call->type;
480 addr = wine_server_get_ptr( call->virtual_protect.addr );
481 size = call->virtual_protect.size;
482 if ((ULONG_PTR)addr == call->virtual_protect.addr && size == call->virtual_protect.size)
484 result->virtual_protect.status = NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size,
485 call->virtual_protect.prot,
486 &result->virtual_protect.prot );
487 result->virtual_protect.addr = wine_server_client_ptr( addr );
488 result->virtual_protect.size = size;
490 else result->virtual_protect.status = STATUS_INVALID_PARAMETER;
491 break;
492 case APC_VIRTUAL_FLUSH:
493 result->type = call->type;
494 addr = wine_server_get_ptr( call->virtual_flush.addr );
495 size = call->virtual_flush.size;
496 if ((ULONG_PTR)addr == call->virtual_flush.addr && size == call->virtual_flush.size)
498 result->virtual_flush.status = NtFlushVirtualMemory( NtCurrentProcess(),
499 (const void **)&addr, &size, 0 );
500 result->virtual_flush.addr = wine_server_client_ptr( addr );
501 result->virtual_flush.size = size;
503 else result->virtual_flush.status = STATUS_INVALID_PARAMETER;
504 break;
505 case APC_VIRTUAL_LOCK:
506 result->type = call->type;
507 addr = wine_server_get_ptr( call->virtual_lock.addr );
508 size = call->virtual_lock.size;
509 if ((ULONG_PTR)addr == call->virtual_lock.addr && size == call->virtual_lock.size)
511 result->virtual_lock.status = NtLockVirtualMemory( NtCurrentProcess(), &addr, &size, 0 );
512 result->virtual_lock.addr = wine_server_client_ptr( addr );
513 result->virtual_lock.size = size;
515 else result->virtual_lock.status = STATUS_INVALID_PARAMETER;
516 break;
517 case APC_VIRTUAL_UNLOCK:
518 result->type = call->type;
519 addr = wine_server_get_ptr( call->virtual_unlock.addr );
520 size = call->virtual_unlock.size;
521 if ((ULONG_PTR)addr == call->virtual_unlock.addr && size == call->virtual_unlock.size)
523 result->virtual_unlock.status = NtUnlockVirtualMemory( NtCurrentProcess(), &addr, &size, 0 );
524 result->virtual_unlock.addr = wine_server_client_ptr( addr );
525 result->virtual_unlock.size = size;
527 else result->virtual_unlock.status = STATUS_INVALID_PARAMETER;
528 break;
529 case APC_MAP_VIEW:
530 result->type = call->type;
531 addr = wine_server_get_ptr( call->map_view.addr );
532 size = call->map_view.size;
533 if ((ULONG_PTR)addr == call->map_view.addr && size == call->map_view.size)
535 LARGE_INTEGER offset;
536 offset.QuadPart = call->map_view.offset;
537 result->map_view.status = virtual_map_section( wine_server_ptr_handle(call->map_view.handle),
538 &addr,
539 call->map_view.zero_bits_64, 0,
540 &offset, &size,
541 call->map_view.alloc_type, call->map_view.prot,
542 &image_info );
543 result->map_view.addr = wine_server_client_ptr( addr );
544 result->map_view.size = size;
546 else result->map_view.status = STATUS_INVALID_PARAMETER;
547 NtClose( wine_server_ptr_handle(call->map_view.handle) );
548 break;
549 case APC_UNMAP_VIEW:
550 result->type = call->type;
551 addr = wine_server_get_ptr( call->unmap_view.addr );
552 if ((ULONG_PTR)addr == call->unmap_view.addr)
553 result->unmap_view.status = NtUnmapViewOfSection( NtCurrentProcess(), addr );
554 else
555 result->unmap_view.status = STATUS_INVALID_PARAMETER;
556 break;
557 case APC_CREATE_THREAD:
559 CLIENT_ID id;
560 HANDLE handle;
561 SIZE_T reserve = call->create_thread.reserve;
562 SIZE_T commit = call->create_thread.commit;
563 void *func = wine_server_get_ptr( call->create_thread.func );
564 void *arg = wine_server_get_ptr( call->create_thread.arg );
566 result->type = call->type;
567 if (reserve == call->create_thread.reserve && commit == call->create_thread.commit &&
568 (ULONG_PTR)func == call->create_thread.func && (ULONG_PTR)arg == call->create_thread.arg)
570 result->create_thread.status = RtlCreateUserThread( NtCurrentProcess(), NULL,
571 call->create_thread.suspend, NULL,
572 reserve, commit, func, arg, &handle, &id );
573 result->create_thread.handle = wine_server_obj_handle( handle );
574 result->create_thread.tid = HandleToULong(id.UniqueThread);
576 else result->create_thread.status = STATUS_INVALID_PARAMETER;
577 break;
579 case APC_BREAK_PROCESS:
580 result->type = APC_BREAK_PROCESS;
581 result->break_process.status = RtlCreateUserThread( NtCurrentProcess(), NULL, FALSE, NULL, 0, 0,
582 DbgUiRemoteBreakin, NULL, NULL, NULL );
583 break;
584 default:
585 server_protocol_error( "get_apc_request: bad type %d\n", call->type );
586 break;
591 /***********************************************************************
592 * server_select
594 unsigned int server_select( const select_op_t *select_op, data_size_t size, UINT flags,
595 const LARGE_INTEGER *timeout )
597 unsigned int ret;
598 int cookie;
599 BOOL user_apc = FALSE;
600 obj_handle_t apc_handle = 0;
601 apc_call_t call;
602 apc_result_t result;
603 timeout_t abs_timeout = timeout ? timeout->QuadPart : TIMEOUT_INFINITE;
604 sigset_t old_set;
606 memset( &result, 0, sizeof(result) );
610 pthread_sigmask( SIG_BLOCK, &server_block_set, &old_set );
611 for (;;)
613 SERVER_START_REQ( select )
615 req->flags = flags;
616 req->cookie = wine_server_client_ptr( &cookie );
617 req->prev_apc = apc_handle;
618 req->timeout = abs_timeout;
619 wine_server_add_data( req, &result, sizeof(result) );
620 wine_server_add_data( req, select_op, size );
621 ret = server_call_unlocked( req );
622 abs_timeout = reply->timeout;
623 apc_handle = reply->apc_handle;
624 call = reply->call;
626 SERVER_END_REQ;
628 /* don't signal multiple times */
629 if (size >= sizeof(select_op->signal_and_wait) && select_op->op == SELECT_SIGNAL_AND_WAIT)
630 size = offsetof( select_op_t, signal_and_wait.signal );
632 if (ret != STATUS_KERNEL_APC) break;
633 invoke_apc( &call, &result );
635 pthread_sigmask( SIG_SETMASK, &old_set, NULL );
637 if (ret == STATUS_USER_APC)
639 invoke_apc( &call, &result );
640 /* if we ran a user apc we have to check once more if additional apcs are queued,
641 * but we don't want to wait */
642 abs_timeout = 0;
643 user_apc = TRUE;
644 size = 0;
647 if (ret == STATUS_PENDING) ret = wait_select_reply( &cookie );
649 while (ret == STATUS_USER_APC || ret == STATUS_KERNEL_APC);
651 if (ret == STATUS_TIMEOUT && user_apc) ret = STATUS_USER_APC;
653 /* A test on Windows 2000 shows that Windows always yields during
654 a wait, but a wait that is hit by an event gets a priority
655 boost as well. This seems to model that behavior the closest. */
656 if (ret == STATUS_TIMEOUT) NtYieldExecution();
658 return ret;
662 /***********************************************************************
663 * server_queue_process_apc
665 unsigned int server_queue_process_apc( HANDLE process, const apc_call_t *call, apc_result_t *result )
667 for (;;)
669 unsigned int ret;
670 HANDLE handle = 0;
671 BOOL self = FALSE;
673 SERVER_START_REQ( queue_apc )
675 req->handle = wine_server_obj_handle( process );
676 req->call = *call;
677 if (!(ret = wine_server_call( req )))
679 handle = wine_server_ptr_handle( reply->handle );
680 self = reply->self;
683 SERVER_END_REQ;
684 if (ret != STATUS_SUCCESS) return ret;
686 if (self)
688 invoke_apc( call, result );
690 else
692 NtWaitForSingleObject( handle, FALSE, NULL );
694 SERVER_START_REQ( get_apc_result )
696 req->handle = wine_server_obj_handle( handle );
697 if (!(ret = wine_server_call( req ))) *result = reply->result;
699 SERVER_END_REQ;
701 if (!ret && result->type == APC_NONE) continue; /* APC didn't run, try again */
703 return ret;
708 /***********************************************************************
709 * wine_server_send_fd (NTDLL.@)
711 * Send a file descriptor to the server.
713 * PARAMS
714 * fd [I] file descriptor to send
716 * RETURNS
717 * nothing
719 void CDECL wine_server_send_fd( int fd )
721 struct send_fd data;
722 struct msghdr msghdr;
723 struct iovec vec;
724 int ret;
726 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
727 msghdr.msg_accrights = (void *)&fd;
728 msghdr.msg_accrightslen = sizeof(fd);
729 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
730 char cmsg_buffer[256];
731 struct cmsghdr *cmsg;
732 msghdr.msg_control = cmsg_buffer;
733 msghdr.msg_controllen = sizeof(cmsg_buffer);
734 msghdr.msg_flags = 0;
735 cmsg = CMSG_FIRSTHDR( &msghdr );
736 cmsg->cmsg_len = CMSG_LEN( sizeof(fd) );
737 cmsg->cmsg_level = SOL_SOCKET;
738 cmsg->cmsg_type = SCM_RIGHTS;
739 *(int *)CMSG_DATA(cmsg) = fd;
740 msghdr.msg_controllen = cmsg->cmsg_len;
741 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
743 msghdr.msg_name = NULL;
744 msghdr.msg_namelen = 0;
745 msghdr.msg_iov = &vec;
746 msghdr.msg_iovlen = 1;
748 vec.iov_base = (void *)&data;
749 vec.iov_len = sizeof(data);
751 data.tid = GetCurrentThreadId();
752 data.fd = fd;
754 for (;;)
756 if ((ret = sendmsg( fd_socket, &msghdr, 0 )) == sizeof(data)) return;
757 if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
758 if (errno == EINTR) continue;
759 if (errno == EPIPE) abort_thread(0);
760 server_protocol_perror( "sendmsg" );
765 /***********************************************************************
766 * receive_fd
768 * Receive a file descriptor passed from the server.
770 static int receive_fd( obj_handle_t *handle )
772 struct iovec vec;
773 struct msghdr msghdr;
774 int ret, fd = -1;
776 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
777 msghdr.msg_accrights = (void *)&fd;
778 msghdr.msg_accrightslen = sizeof(fd);
779 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
780 char cmsg_buffer[256];
781 msghdr.msg_control = cmsg_buffer;
782 msghdr.msg_controllen = sizeof(cmsg_buffer);
783 msghdr.msg_flags = 0;
784 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
786 msghdr.msg_name = NULL;
787 msghdr.msg_namelen = 0;
788 msghdr.msg_iov = &vec;
789 msghdr.msg_iovlen = 1;
790 vec.iov_base = (void *)handle;
791 vec.iov_len = sizeof(*handle);
793 for (;;)
795 if ((ret = recvmsg( fd_socket, &msghdr, MSG_CMSG_CLOEXEC )) > 0)
797 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
798 struct cmsghdr *cmsg;
799 for (cmsg = CMSG_FIRSTHDR( &msghdr ); cmsg; cmsg = CMSG_NXTHDR( &msghdr, cmsg ))
801 if (cmsg->cmsg_level != SOL_SOCKET) continue;
802 if (cmsg->cmsg_type == SCM_RIGHTS) fd = *(int *)CMSG_DATA(cmsg);
803 #ifdef SCM_CREDENTIALS
804 else if (cmsg->cmsg_type == SCM_CREDENTIALS)
806 struct ucred *ucred = (struct ucred *)CMSG_DATA(cmsg);
807 server_pid = ucred->pid;
809 #endif
811 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
812 if (fd != -1) fcntl( fd, F_SETFD, FD_CLOEXEC ); /* in case MSG_CMSG_CLOEXEC is not supported */
813 return fd;
815 if (!ret) break;
816 if (errno == EINTR) continue;
817 if (errno == EPIPE) break;
818 server_protocol_perror("recvmsg");
820 /* the server closed the connection; time to die... */
821 abort_thread(0);
825 /***********************************************************************/
826 /* fd cache support */
828 union fd_cache_entry
830 LONG64 data;
831 struct
833 int fd;
834 enum server_fd_type type : 5;
835 unsigned int access : 3;
836 unsigned int options : 24;
837 } s;
840 C_ASSERT( sizeof(union fd_cache_entry) == sizeof(LONG64) );
842 #define FD_CACHE_BLOCK_SIZE (65536 / sizeof(union fd_cache_entry))
843 #define FD_CACHE_ENTRIES 128
845 static union fd_cache_entry *fd_cache[FD_CACHE_ENTRIES];
846 static union fd_cache_entry fd_cache_initial_block[FD_CACHE_BLOCK_SIZE];
848 static inline unsigned int handle_to_index( HANDLE handle, unsigned int *entry )
850 unsigned int idx = (wine_server_obj_handle(handle) >> 2) - 1;
851 *entry = idx / FD_CACHE_BLOCK_SIZE;
852 return idx % FD_CACHE_BLOCK_SIZE;
856 /***********************************************************************
857 * add_fd_to_cache
859 * Caller must hold fd_cache_section.
861 static BOOL add_fd_to_cache( HANDLE handle, int fd, enum server_fd_type type,
862 unsigned int access, unsigned int options )
864 unsigned int entry, idx = handle_to_index( handle, &entry );
865 union fd_cache_entry cache;
867 if (entry >= FD_CACHE_ENTRIES)
869 FIXME( "too many allocated handles, not caching %p\n", handle );
870 return FALSE;
873 if (!fd_cache[entry]) /* do we need to allocate a new block of entries? */
875 if (!entry) fd_cache[0] = fd_cache_initial_block;
876 else
878 void *ptr = wine_anon_mmap( NULL, FD_CACHE_BLOCK_SIZE * sizeof(union fd_cache_entry),
879 PROT_READ | PROT_WRITE, 0 );
880 if (ptr == MAP_FAILED) return FALSE;
881 fd_cache[entry] = ptr;
885 /* store fd+1 so that 0 can be used as the unset value */
886 cache.s.fd = fd + 1;
887 cache.s.type = type;
888 cache.s.access = access;
889 cache.s.options = options;
890 cache.data = interlocked_xchg64( &fd_cache[entry][idx].data, cache.data );
891 assert( !cache.s.fd );
892 return TRUE;
896 /***********************************************************************
897 * get_cached_fd
899 static inline NTSTATUS get_cached_fd( HANDLE handle, int *fd, enum server_fd_type *type,
900 unsigned int *access, unsigned int *options )
902 unsigned int entry, idx = handle_to_index( handle, &entry );
903 union fd_cache_entry cache;
905 if (entry >= FD_CACHE_ENTRIES || !fd_cache[entry]) return STATUS_INVALID_HANDLE;
907 cache.data = interlocked_cmpxchg64( &fd_cache[entry][idx].data, 0, 0 );
908 if (!cache.data) return STATUS_INVALID_HANDLE;
910 /* if fd type is invalid, fd stores an error value */
911 if (cache.s.type == FD_TYPE_INVALID) return cache.s.fd - 1;
913 *fd = cache.s.fd - 1;
914 if (type) *type = cache.s.type;
915 if (access) *access = cache.s.access;
916 if (options) *options = cache.s.options;
917 return STATUS_SUCCESS;
921 /***********************************************************************
922 * server_remove_fd_from_cache
924 int server_remove_fd_from_cache( HANDLE handle )
926 unsigned int entry, idx = handle_to_index( handle, &entry );
927 int fd = -1;
929 if (entry < FD_CACHE_ENTRIES && fd_cache[entry])
931 union fd_cache_entry cache;
932 cache.data = interlocked_xchg64( &fd_cache[entry][idx].data, 0 );
933 if (cache.s.type != FD_TYPE_INVALID) fd = cache.s.fd - 1;
936 return fd;
940 /***********************************************************************
941 * server_get_unix_fd
943 * The returned unix_fd should be closed iff needs_close is non-zero.
945 int server_get_unix_fd( HANDLE handle, unsigned int wanted_access, int *unix_fd,
946 int *needs_close, enum server_fd_type *type, unsigned int *options )
948 sigset_t sigset;
949 obj_handle_t fd_handle;
950 int ret, fd = -1;
951 unsigned int access = 0;
953 *unix_fd = -1;
954 *needs_close = 0;
955 wanted_access &= FILE_READ_DATA | FILE_WRITE_DATA | FILE_APPEND_DATA;
957 ret = get_cached_fd( handle, &fd, type, &access, options );
958 if (ret != STATUS_INVALID_HANDLE) goto done;
960 server_enter_uninterrupted_section( &fd_cache_section, &sigset );
961 ret = get_cached_fd( handle, &fd, type, &access, options );
962 if (ret == STATUS_INVALID_HANDLE)
964 SERVER_START_REQ( get_handle_fd )
966 req->handle = wine_server_obj_handle( handle );
967 if (!(ret = wine_server_call( req )))
969 if (type) *type = reply->type;
970 if (options) *options = reply->options;
971 access = reply->access;
972 if ((fd = receive_fd( &fd_handle )) != -1)
974 assert( wine_server_ptr_handle(fd_handle) == handle );
975 *needs_close = (!reply->cacheable ||
976 !add_fd_to_cache( handle, fd, reply->type,
977 reply->access, reply->options ));
979 else ret = STATUS_TOO_MANY_OPENED_FILES;
981 else if (reply->cacheable)
983 add_fd_to_cache( handle, ret, FD_TYPE_INVALID, 0, 0 );
986 SERVER_END_REQ;
988 server_leave_uninterrupted_section( &fd_cache_section, &sigset );
990 done:
991 if (!ret && ((access & wanted_access) != wanted_access))
993 ret = STATUS_ACCESS_DENIED;
994 if (*needs_close) close( fd );
996 if (!ret) *unix_fd = fd;
997 return ret;
1001 /***********************************************************************
1002 * wine_server_fd_to_handle (NTDLL.@)
1004 * Allocate a file handle for a Unix file descriptor.
1006 * PARAMS
1007 * fd [I] Unix file descriptor.
1008 * access [I] Win32 access flags.
1009 * attributes [I] Object attributes.
1010 * handle [O] Address where Wine file handle will be stored.
1012 * RETURNS
1013 * NTSTATUS code
1015 int CDECL wine_server_fd_to_handle( int fd, unsigned int access, unsigned int attributes, HANDLE *handle )
1017 int ret;
1019 *handle = 0;
1020 wine_server_send_fd( fd );
1022 SERVER_START_REQ( alloc_file_handle )
1024 req->access = access;
1025 req->attributes = attributes;
1026 req->fd = fd;
1027 if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
1029 SERVER_END_REQ;
1030 return ret;
1034 /***********************************************************************
1035 * wine_server_handle_to_fd (NTDLL.@)
1037 * Retrieve the file descriptor corresponding to a file handle.
1039 * PARAMS
1040 * handle [I] Wine file handle.
1041 * access [I] Win32 file access rights requested.
1042 * unix_fd [O] Address where Unix file descriptor will be stored.
1043 * options [O] Address where the file open options will be stored. Optional.
1045 * RETURNS
1046 * NTSTATUS code
1048 int CDECL wine_server_handle_to_fd( HANDLE handle, unsigned int access, int *unix_fd,
1049 unsigned int *options )
1051 int needs_close, ret = server_get_unix_fd( handle, access, unix_fd, &needs_close, NULL, options );
1053 if (!ret && !needs_close)
1055 if ((*unix_fd = dup(*unix_fd)) == -1) ret = FILE_GetNtStatus();
1057 return ret;
1061 /***********************************************************************
1062 * wine_server_release_fd (NTDLL.@)
1064 * Release the Unix file descriptor returned by wine_server_handle_to_fd.
1066 * PARAMS
1067 * handle [I] Wine file handle.
1068 * unix_fd [I] Unix file descriptor to release.
1070 * RETURNS
1071 * nothing
1073 void CDECL wine_server_release_fd( HANDLE handle, int unix_fd )
1075 close( unix_fd );
1079 /***********************************************************************
1080 * server_pipe
1082 * Create a pipe for communicating with the server.
1084 int server_pipe( int fd[2] )
1086 int ret;
1087 #ifdef HAVE_PIPE2
1088 static BOOL have_pipe2 = TRUE;
1090 if (have_pipe2)
1092 if (!(ret = pipe2( fd, O_CLOEXEC ))) return ret;
1093 if (errno == ENOSYS || errno == EINVAL) have_pipe2 = FALSE; /* don't try again */
1095 #endif
1096 if (!(ret = pipe( fd )))
1098 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1099 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1101 return ret;
1105 /***********************************************************************
1106 * start_server
1108 * Start a new wine server.
1110 static void start_server(void)
1112 static BOOL started; /* we only try once */
1113 char *argv[3];
1114 static char wineserver[] = "server/wineserver";
1115 static char debug[] = "-d";
1117 if (!started)
1119 int status;
1120 int pid = fork();
1121 if (pid == -1) fatal_perror( "fork" );
1122 if (!pid)
1124 argv[0] = wineserver;
1125 argv[1] = TRACE_ON(server) ? debug : NULL;
1126 argv[2] = NULL;
1127 wine_exec_wine_binary( argv[0], argv, getenv("WINESERVER") );
1128 fatal_error( "could not exec wineserver\n" );
1130 waitpid( pid, &status, 0 );
1131 status = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
1132 if (status == 2) return; /* server lock held by someone else, will retry later */
1133 if (status) exit(status); /* server failed */
1134 started = TRUE;
1139 /***********************************************************************
1140 * setup_config_dir
1142 * Setup the wine configuration dir.
1144 static int setup_config_dir(void)
1146 const char *p, *config_dir = wine_get_config_dir();
1147 int fd_cwd = open( ".", O_RDONLY );
1149 if (chdir( config_dir ) == -1)
1151 if (errno != ENOENT) fatal_perror( "chdir to %s", config_dir );
1153 if ((p = strrchr( config_dir, '/' )) && p != config_dir)
1155 struct stat st;
1156 char *tmp_dir;
1158 if (!(tmp_dir = malloc( p + 1 - config_dir ))) fatal_error( "out of memory\n" );
1159 memcpy( tmp_dir, config_dir, p - config_dir );
1160 tmp_dir[p - config_dir] = 0;
1161 if (!stat( tmp_dir, &st ) && st.st_uid != getuid())
1162 fatal_error( "'%s' is not owned by you, refusing to create a configuration directory there\n",
1163 tmp_dir );
1164 free( tmp_dir );
1167 mkdir( config_dir, 0777 );
1168 if (chdir( config_dir ) == -1) fatal_perror( "chdir to %s", config_dir );
1170 MESSAGE( "wine: created the configuration directory '%s'\n", config_dir );
1173 if (mkdir( "dosdevices", 0777 ) == -1)
1175 if (errno == EEXIST) goto done;
1176 fatal_perror( "cannot create %s/dosdevices", config_dir );
1179 /* create the drive symlinks */
1181 mkdir( "drive_c", 0777 );
1182 symlink( "../drive_c", "dosdevices/c:" );
1183 symlink( "/", "dosdevices/z:" );
1185 done:
1186 if (fd_cwd == -1) fd_cwd = open( "dosdevices/c:", O_RDONLY );
1187 fcntl( fd_cwd, F_SETFD, FD_CLOEXEC );
1188 return fd_cwd;
1192 /***********************************************************************
1193 * server_connect_error
1195 * Try to display a meaningful explanation of why we couldn't connect
1196 * to the server.
1198 static void server_connect_error( const char *serverdir )
1200 int fd;
1201 struct flock fl;
1203 if ((fd = open( LOCKNAME, O_WRONLY )) == -1)
1204 fatal_error( "for some mysterious reason, the wine server never started.\n" );
1206 fl.l_type = F_WRLCK;
1207 fl.l_whence = SEEK_SET;
1208 fl.l_start = 0;
1209 fl.l_len = 1;
1210 if (fcntl( fd, F_GETLK, &fl ) != -1)
1212 if (fl.l_type == F_WRLCK) /* the file is locked */
1213 fatal_error( "a wine server seems to be running, but I cannot connect to it.\n"
1214 " You probably need to kill that process (it might be pid %d).\n",
1215 (int)fl.l_pid );
1216 fatal_error( "for some mysterious reason, the wine server failed to run.\n" );
1218 fatal_error( "the file system of '%s' doesn't support locks,\n"
1219 " and there is a 'socket' file in that directory that prevents wine from starting.\n"
1220 " You should make sure no wine server is running, remove that file and try again.\n",
1221 serverdir );
1225 /***********************************************************************
1226 * server_connect
1228 * Attempt to connect to an existing server socket.
1229 * We need to be in the server directory already.
1231 static int server_connect(void)
1233 const char *serverdir;
1234 struct sockaddr_un addr;
1235 struct stat st;
1236 int s, slen, retry, fd_cwd;
1238 fd_cwd = setup_config_dir();
1239 serverdir = wine_get_server_dir();
1241 /* chdir to the server directory */
1242 if (chdir( serverdir ) == -1)
1244 if (errno != ENOENT) fatal_perror( "chdir to %s", serverdir );
1245 start_server();
1246 if (chdir( serverdir ) == -1) fatal_perror( "chdir to %s", serverdir );
1249 /* make sure we are at the right place */
1250 if (stat( ".", &st ) == -1) fatal_perror( "stat %s", serverdir );
1251 if (st.st_uid != getuid()) fatal_error( "'%s' is not owned by you\n", serverdir );
1252 if (st.st_mode & 077) fatal_error( "'%s' must not be accessible by other users\n", serverdir );
1254 for (retry = 0; retry < 6; retry++)
1256 /* if not the first try, wait a bit to leave the previous server time to exit */
1257 if (retry)
1259 usleep( 100000 * retry * retry );
1260 start_server();
1261 if (lstat( SOCKETNAME, &st ) == -1) continue; /* still no socket, wait a bit more */
1263 else if (lstat( SOCKETNAME, &st ) == -1) /* check for an already existing socket */
1265 if (errno != ENOENT) fatal_perror( "lstat %s/%s", serverdir, SOCKETNAME );
1266 start_server();
1267 if (lstat( SOCKETNAME, &st ) == -1) continue; /* still no socket, wait a bit more */
1270 /* make sure the socket is sane (ISFIFO needed for Solaris) */
1271 if (!S_ISSOCK(st.st_mode) && !S_ISFIFO(st.st_mode))
1272 fatal_error( "'%s/%s' is not a socket\n", serverdir, SOCKETNAME );
1273 if (st.st_uid != getuid())
1274 fatal_error( "'%s/%s' is not owned by you\n", serverdir, SOCKETNAME );
1276 /* try to connect to it */
1277 addr.sun_family = AF_UNIX;
1278 strcpy( addr.sun_path, SOCKETNAME );
1279 slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
1280 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
1281 addr.sun_len = slen;
1282 #endif
1283 if ((s = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_perror( "socket" );
1284 #ifdef SO_PASSCRED
1285 else
1287 int enable = 1;
1288 setsockopt( s, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
1290 #endif
1291 if (connect( s, (struct sockaddr *)&addr, slen ) != -1)
1293 /* switch back to the starting directory */
1294 if (fd_cwd != -1)
1296 fchdir( fd_cwd );
1297 close( fd_cwd );
1299 fcntl( s, F_SETFD, FD_CLOEXEC );
1300 return s;
1302 close( s );
1304 server_connect_error( serverdir );
1308 #ifdef __APPLE__
1309 #include <mach/mach.h>
1310 #include <mach/mach_error.h>
1311 #include <servers/bootstrap.h>
1313 /* send our task port to the server */
1314 static void send_server_task_port(void)
1316 mach_port_t bootstrap_port, wineserver_port;
1317 kern_return_t kret;
1319 struct {
1320 mach_msg_header_t header;
1321 mach_msg_body_t body;
1322 mach_msg_port_descriptor_t task_port;
1323 } msg;
1325 if (task_get_bootstrap_port(mach_task_self(), &bootstrap_port) != KERN_SUCCESS) return;
1327 kret = bootstrap_look_up(bootstrap_port, (char*)wine_get_server_dir(), &wineserver_port);
1328 if (kret != KERN_SUCCESS)
1329 fatal_error( "cannot find the server port: 0x%08x\n", kret );
1331 mach_port_deallocate(mach_task_self(), bootstrap_port);
1333 msg.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0) | MACH_MSGH_BITS_COMPLEX;
1334 msg.header.msgh_size = sizeof(msg);
1335 msg.header.msgh_remote_port = wineserver_port;
1336 msg.header.msgh_local_port = MACH_PORT_NULL;
1338 msg.body.msgh_descriptor_count = 1;
1339 msg.task_port.name = mach_task_self();
1340 msg.task_port.disposition = MACH_MSG_TYPE_COPY_SEND;
1341 msg.task_port.type = MACH_MSG_PORT_DESCRIPTOR;
1343 kret = mach_msg_send(&msg.header);
1344 if (kret != KERN_SUCCESS)
1345 server_protocol_error( "mach_msg_send failed: 0x%08x\n", kret );
1347 mach_port_deallocate(mach_task_self(), wineserver_port);
1349 #endif /* __APPLE__ */
1352 /***********************************************************************
1353 * get_unix_tid
1355 * Retrieve the Unix tid to use on the server side for the current thread.
1357 static int get_unix_tid(void)
1359 int ret = -1;
1360 #ifdef HAVE_PTHREAD_GETTHREADID_NP
1361 ret = pthread_getthreadid_np();
1362 #elif defined(linux)
1363 ret = syscall( __NR_gettid );
1364 #elif defined(__sun)
1365 ret = pthread_self();
1366 #elif defined(__APPLE__)
1367 ret = mach_thread_self();
1368 mach_port_deallocate(mach_task_self(), ret);
1369 #elif defined(__NetBSD__)
1370 ret = _lwp_self();
1371 #elif defined(__FreeBSD__)
1372 long lwpid;
1373 thr_self( &lwpid );
1374 ret = lwpid;
1375 #elif defined(__DragonFly__)
1376 ret = lwp_gettid();
1377 #endif
1378 return ret;
1382 /***********************************************************************
1383 * server_init_process
1385 * Start the server and create the initial socket pair.
1387 void server_init_process(void)
1389 obj_handle_t version;
1390 const char *env_socket = getenv( "WINESERVERSOCKET" );
1392 server_pid = -1;
1393 if (env_socket)
1395 fd_socket = atoi( env_socket );
1396 if (fcntl( fd_socket, F_SETFD, FD_CLOEXEC ) == -1)
1397 fatal_perror( "Bad server socket %d", fd_socket );
1398 unsetenv( "WINESERVERSOCKET" );
1400 else
1402 const char *arch = getenv( "WINEARCH" );
1404 if (arch && strcmp( arch, "win32" ) && strcmp( arch, "win64" ))
1405 fatal_error( "WINEARCH set to invalid value '%s', it must be either win32 or win64.\n", arch );
1407 fd_socket = server_connect();
1410 /* setup the signal mask */
1411 sigemptyset( &server_block_set );
1412 sigaddset( &server_block_set, SIGALRM );
1413 sigaddset( &server_block_set, SIGIO );
1414 sigaddset( &server_block_set, SIGINT );
1415 sigaddset( &server_block_set, SIGHUP );
1416 sigaddset( &server_block_set, SIGUSR1 );
1417 sigaddset( &server_block_set, SIGUSR2 );
1418 sigaddset( &server_block_set, SIGCHLD );
1419 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
1421 /* receive the first thread request fd on the main socket */
1422 ntdll_get_thread_data()->request_fd = receive_fd( &version );
1424 #ifdef SO_PASSCRED
1425 /* now that we hopefully received the server_pid, disable SO_PASSCRED */
1427 int enable = 0;
1428 setsockopt( fd_socket, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
1430 #endif
1432 if (version != SERVER_PROTOCOL_VERSION)
1433 server_protocol_error( "version mismatch %d/%d.\n"
1434 "Your %s binary was not upgraded correctly,\n"
1435 "or you have an older one somewhere in your PATH.\n"
1436 "Or maybe the wrong wineserver is still running?\n",
1437 version, SERVER_PROTOCOL_VERSION,
1438 (version > SERVER_PROTOCOL_VERSION) ? "wine" : "wineserver" );
1439 #if defined(__linux__) && defined(HAVE_PRCTL)
1440 /* work around Ubuntu's ptrace breakage */
1441 if (server_pid != -1) prctl( 0x59616d61 /* PR_SET_PTRACER */, server_pid );
1442 #endif
1446 /***********************************************************************
1447 * server_init_process_done
1449 void server_init_process_done(void)
1451 PEB *peb = NtCurrentTeb()->Peb;
1452 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
1453 void *entry = (char *)peb->ImageBaseAddress + nt->OptionalHeader.AddressOfEntryPoint;
1454 NTSTATUS status;
1455 int suspend;
1457 #ifdef __APPLE__
1458 send_server_task_port();
1459 #endif
1461 /* Install signal handlers; this cannot be done earlier, since we cannot
1462 * send exceptions to the debugger before the create process event that
1463 * is sent by REQ_INIT_PROCESS_DONE.
1464 * We do need the handlers in place by the time the request is over, so
1465 * we set them up here. If we segfault between here and the server call
1466 * something is very wrong... */
1467 signal_init_process();
1469 /* Signal the parent process to continue */
1470 SERVER_START_REQ( init_process_done )
1472 req->module = wine_server_client_ptr( peb->ImageBaseAddress );
1473 #ifdef __i386__
1474 req->ldt_copy = wine_server_client_ptr( &wine_ldt_copy );
1475 #endif
1476 req->entry = wine_server_client_ptr( entry );
1477 req->gui = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
1478 status = wine_server_call( req );
1479 suspend = reply->suspend;
1481 SERVER_END_REQ;
1483 assert( !status );
1484 signal_start_process( entry, suspend );
1488 /***********************************************************************
1489 * server_init_thread
1491 * Send an init thread request. Return 0 if OK.
1493 size_t server_init_thread( void *entry_point, BOOL *suspend )
1495 static const char *cpu_names[] = { "x86", "x86_64", "PowerPC", "ARM", "ARM64" };
1496 static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
1497 const char *arch = getenv( "WINEARCH" );
1498 int ret;
1499 int reply_pipe[2];
1500 struct sigaction sig_act;
1501 size_t info_size;
1503 sig_act.sa_handler = SIG_IGN;
1504 sig_act.sa_flags = 0;
1505 sigemptyset( &sig_act.sa_mask );
1507 /* ignore SIGPIPE so that we get an EPIPE error instead */
1508 sigaction( SIGPIPE, &sig_act, NULL );
1510 /* create the server->client communication pipes */
1511 if (server_pipe( reply_pipe ) == -1) server_protocol_perror( "pipe" );
1512 if (server_pipe( ntdll_get_thread_data()->wait_fd ) == -1) server_protocol_perror( "pipe" );
1513 wine_server_send_fd( reply_pipe[1] );
1514 wine_server_send_fd( ntdll_get_thread_data()->wait_fd[1] );
1515 ntdll_get_thread_data()->reply_fd = reply_pipe[0];
1516 close( reply_pipe[1] );
1518 SERVER_START_REQ( init_thread )
1520 req->unix_pid = getpid();
1521 req->unix_tid = get_unix_tid();
1522 req->teb = wine_server_client_ptr( NtCurrentTeb() );
1523 req->entry = wine_server_client_ptr( entry_point );
1524 req->reply_fd = reply_pipe[1];
1525 req->wait_fd = ntdll_get_thread_data()->wait_fd[1];
1526 req->debug_level = (TRACE_ON(server) != 0);
1527 req->cpu = client_cpu;
1528 ret = wine_server_call( req );
1529 NtCurrentTeb()->ClientId.UniqueProcess = ULongToHandle(reply->pid);
1530 NtCurrentTeb()->ClientId.UniqueThread = ULongToHandle(reply->tid);
1531 info_size = reply->info_size;
1532 server_start_time = reply->server_start;
1533 server_cpus = reply->all_cpus;
1534 *suspend = reply->suspend;
1536 SERVER_END_REQ;
1538 is_wow64 = !is_win64 && (server_cpus & ((1 << CPU_x86_64) | (1 << CPU_ARM64))) != 0;
1539 ntdll_get_thread_data()->wow64_redir = is_wow64;
1541 switch (ret)
1543 case STATUS_SUCCESS:
1544 if (arch)
1546 if (!strcmp( arch, "win32" ) && (is_win64 || is_wow64))
1547 fatal_error( "WINEARCH set to win32 but '%s' is a 64-bit installation.\n",
1548 wine_get_config_dir() );
1549 if (!strcmp( arch, "win64" ) && !is_win64 && !is_wow64)
1550 fatal_error( "WINEARCH set to win64 but '%s' is a 32-bit installation.\n",
1551 wine_get_config_dir() );
1553 return info_size;
1554 case STATUS_INVALID_IMAGE_WIN_64:
1555 fatal_error( "'%s' is a 32-bit installation, it cannot support 64-bit applications.\n",
1556 wine_get_config_dir() );
1557 case STATUS_NOT_SUPPORTED:
1558 fatal_error( "'%s' is a 64-bit installation, it cannot be used with a 32-bit wineserver.\n",
1559 wine_get_config_dir() );
1560 case STATUS_INVALID_IMAGE_FORMAT:
1561 fatal_error( "wineserver doesn't support the %s architecture\n", cpu_names[client_cpu] );
1562 default:
1563 server_protocol_error( "init_thread failed with status %x\n", ret );