mshtml: Removed no longer used attr_name from event_info_t.
[wine.git] / dlls / ntdll / server.c
blobec517fcf40823a75580b6eefea7b53ad0b847b24
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 * wine_server_call (NTDLL.@)
283 * Perform a server call.
285 * PARAMS
286 * req_ptr [I/O] Function dependent data
288 * RETURNS
289 * Depends on server function being called, but usually an NTSTATUS code.
291 * NOTES
292 * Use the SERVER_START_REQ and SERVER_END_REQ to help you fill out the
293 * server request structure for the particular call. E.g:
294 *| SERVER_START_REQ( event_op )
295 *| {
296 *| req->handle = handle;
297 *| req->op = SET_EVENT;
298 *| ret = wine_server_call( req );
299 *| }
300 *| SERVER_END_REQ;
302 unsigned int wine_server_call( void *req_ptr )
304 struct __server_request_info * const req = req_ptr;
305 sigset_t old_set;
306 unsigned int ret;
308 pthread_sigmask( SIG_BLOCK, &server_block_set, &old_set );
309 ret = send_request( req );
310 if (!ret) ret = wait_reply( req );
311 pthread_sigmask( SIG_SETMASK, &old_set, NULL );
312 return ret;
316 /***********************************************************************
317 * server_enter_uninterrupted_section
319 void server_enter_uninterrupted_section( RTL_CRITICAL_SECTION *cs, sigset_t *sigset )
321 pthread_sigmask( SIG_BLOCK, &server_block_set, sigset );
322 RtlEnterCriticalSection( cs );
326 /***********************************************************************
327 * server_leave_uninterrupted_section
329 void server_leave_uninterrupted_section( RTL_CRITICAL_SECTION *cs, sigset_t *sigset )
331 RtlLeaveCriticalSection( cs );
332 pthread_sigmask( SIG_SETMASK, sigset, NULL );
336 /***********************************************************************
337 * wait_select_reply
339 * Wait for a reply on the waiting pipe of the current thread.
341 static int wait_select_reply( void *cookie )
343 int signaled;
344 struct wake_up_reply reply;
345 for (;;)
347 int ret;
348 ret = read( ntdll_get_thread_data()->wait_fd[0], &reply, sizeof(reply) );
349 if (ret == sizeof(reply))
351 if (!reply.cookie) abort_thread( reply.signaled ); /* thread got killed */
352 if (wine_server_get_ptr(reply.cookie) == cookie) return reply.signaled;
353 /* we stole another reply, wait for the real one */
354 signaled = wait_select_reply( cookie );
355 /* and now put the wrong one back in the pipe */
356 for (;;)
358 ret = write( ntdll_get_thread_data()->wait_fd[1], &reply, sizeof(reply) );
359 if (ret == sizeof(reply)) break;
360 if (ret >= 0) server_protocol_error( "partial wakeup write %d\n", ret );
361 if (errno == EINTR) continue;
362 server_protocol_perror("wakeup write");
364 return signaled;
366 if (ret >= 0) server_protocol_error( "partial wakeup read %d\n", ret );
367 if (errno == EINTR) continue;
368 server_protocol_perror("wakeup read");
373 /***********************************************************************
374 * invoke_apc
376 * Invoke a single APC. Return TRUE if a user APC has been run.
378 static BOOL invoke_apc( const apc_call_t *call, apc_result_t *result )
380 BOOL user_apc = FALSE;
381 SIZE_T size;
382 void *addr;
384 memset( result, 0, sizeof(*result) );
386 switch (call->type)
388 case APC_NONE:
389 break;
390 case APC_USER:
392 void (WINAPI *func)(ULONG_PTR,ULONG_PTR,ULONG_PTR) = wine_server_get_ptr( call->user.func );
393 func( call->user.args[0], call->user.args[1], call->user.args[2] );
394 user_apc = TRUE;
395 break;
397 case APC_TIMER:
399 void (WINAPI *func)(void*, unsigned int, unsigned int) = wine_server_get_ptr( call->timer.func );
400 func( wine_server_get_ptr( call->timer.arg ),
401 (DWORD)call->timer.time, (DWORD)(call->timer.time >> 32) );
402 user_apc = TRUE;
403 break;
405 case APC_ASYNC_IO:
407 void *apc = NULL, *arg = NULL;
408 IO_STATUS_BLOCK *iosb = wine_server_get_ptr( call->async_io.sb );
409 NTSTATUS (*func)(void *, IO_STATUS_BLOCK *, NTSTATUS, void **, void **) = wine_server_get_ptr( call->async_io.func );
410 result->type = call->type;
411 result->async_io.status = func( wine_server_get_ptr( call->async_io.user ),
412 iosb, call->async_io.status, &apc, &arg );
413 if (result->async_io.status != STATUS_PENDING)
415 result->async_io.total = iosb->Information;
416 result->async_io.apc = wine_server_client_ptr( apc );
417 result->async_io.arg = wine_server_client_ptr( arg );
419 break;
421 case APC_VIRTUAL_ALLOC:
422 result->type = call->type;
423 addr = wine_server_get_ptr( call->virtual_alloc.addr );
424 size = call->virtual_alloc.size;
425 if ((ULONG_PTR)addr == call->virtual_alloc.addr && size == call->virtual_alloc.size)
427 result->virtual_alloc.status = NtAllocateVirtualMemory( NtCurrentProcess(), &addr,
428 call->virtual_alloc.zero_bits, &size,
429 call->virtual_alloc.op_type,
430 call->virtual_alloc.prot );
431 result->virtual_alloc.addr = wine_server_client_ptr( addr );
432 result->virtual_alloc.size = size;
434 else result->virtual_alloc.status = STATUS_WORKING_SET_LIMIT_RANGE;
435 break;
436 case APC_VIRTUAL_FREE:
437 result->type = call->type;
438 addr = wine_server_get_ptr( call->virtual_free.addr );
439 size = call->virtual_free.size;
440 if ((ULONG_PTR)addr == call->virtual_free.addr && size == call->virtual_free.size)
442 result->virtual_free.status = NtFreeVirtualMemory( NtCurrentProcess(), &addr, &size,
443 call->virtual_free.op_type );
444 result->virtual_free.addr = wine_server_client_ptr( addr );
445 result->virtual_free.size = size;
447 else result->virtual_free.status = STATUS_INVALID_PARAMETER;
448 break;
449 case APC_VIRTUAL_QUERY:
451 MEMORY_BASIC_INFORMATION info;
452 result->type = call->type;
453 addr = wine_server_get_ptr( call->virtual_query.addr );
454 if ((ULONG_PTR)addr == call->virtual_query.addr)
455 result->virtual_query.status = NtQueryVirtualMemory( NtCurrentProcess(),
456 addr, MemoryBasicInformation, &info,
457 sizeof(info), NULL );
458 else
459 result->virtual_query.status = STATUS_WORKING_SET_LIMIT_RANGE;
461 if (result->virtual_query.status == STATUS_SUCCESS)
463 result->virtual_query.base = wine_server_client_ptr( info.BaseAddress );
464 result->virtual_query.alloc_base = wine_server_client_ptr( info.AllocationBase );
465 result->virtual_query.size = info.RegionSize;
466 result->virtual_query.prot = info.Protect;
467 result->virtual_query.alloc_prot = info.AllocationProtect;
468 result->virtual_query.state = info.State >> 12;
469 result->virtual_query.alloc_type = info.Type >> 16;
471 break;
473 case APC_VIRTUAL_PROTECT:
474 result->type = call->type;
475 addr = wine_server_get_ptr( call->virtual_protect.addr );
476 size = call->virtual_protect.size;
477 if ((ULONG_PTR)addr == call->virtual_protect.addr && size == call->virtual_protect.size)
479 result->virtual_protect.status = NtProtectVirtualMemory( NtCurrentProcess(), &addr, &size,
480 call->virtual_protect.prot,
481 &result->virtual_protect.prot );
482 result->virtual_protect.addr = wine_server_client_ptr( addr );
483 result->virtual_protect.size = size;
485 else result->virtual_protect.status = STATUS_INVALID_PARAMETER;
486 break;
487 case APC_VIRTUAL_FLUSH:
488 result->type = call->type;
489 addr = wine_server_get_ptr( call->virtual_flush.addr );
490 size = call->virtual_flush.size;
491 if ((ULONG_PTR)addr == call->virtual_flush.addr && size == call->virtual_flush.size)
493 result->virtual_flush.status = NtFlushVirtualMemory( NtCurrentProcess(),
494 (const void **)&addr, &size, 0 );
495 result->virtual_flush.addr = wine_server_client_ptr( addr );
496 result->virtual_flush.size = size;
498 else result->virtual_flush.status = STATUS_INVALID_PARAMETER;
499 break;
500 case APC_VIRTUAL_LOCK:
501 result->type = call->type;
502 addr = wine_server_get_ptr( call->virtual_lock.addr );
503 size = call->virtual_lock.size;
504 if ((ULONG_PTR)addr == call->virtual_lock.addr && size == call->virtual_lock.size)
506 result->virtual_lock.status = NtLockVirtualMemory( NtCurrentProcess(), &addr, &size, 0 );
507 result->virtual_lock.addr = wine_server_client_ptr( addr );
508 result->virtual_lock.size = size;
510 else result->virtual_lock.status = STATUS_INVALID_PARAMETER;
511 break;
512 case APC_VIRTUAL_UNLOCK:
513 result->type = call->type;
514 addr = wine_server_get_ptr( call->virtual_unlock.addr );
515 size = call->virtual_unlock.size;
516 if ((ULONG_PTR)addr == call->virtual_unlock.addr && size == call->virtual_unlock.size)
518 result->virtual_unlock.status = NtUnlockVirtualMemory( NtCurrentProcess(), &addr, &size, 0 );
519 result->virtual_unlock.addr = wine_server_client_ptr( addr );
520 result->virtual_unlock.size = size;
522 else result->virtual_unlock.status = STATUS_INVALID_PARAMETER;
523 break;
524 case APC_MAP_VIEW:
525 result->type = call->type;
526 addr = wine_server_get_ptr( call->map_view.addr );
527 size = call->map_view.size;
528 if ((ULONG_PTR)addr == call->map_view.addr && size == call->map_view.size)
530 LARGE_INTEGER offset;
531 offset.QuadPart = call->map_view.offset;
532 result->map_view.status = NtMapViewOfSection( wine_server_ptr_handle(call->map_view.handle),
533 NtCurrentProcess(), &addr,
534 call->map_view.zero_bits, 0,
535 &offset, &size, ViewShare,
536 call->map_view.alloc_type, call->map_view.prot );
537 result->map_view.addr = wine_server_client_ptr( addr );
538 result->map_view.size = size;
540 else result->map_view.status = STATUS_INVALID_PARAMETER;
541 NtClose( wine_server_ptr_handle(call->map_view.handle) );
542 break;
543 case APC_UNMAP_VIEW:
544 result->type = call->type;
545 addr = wine_server_get_ptr( call->unmap_view.addr );
546 if ((ULONG_PTR)addr == call->unmap_view.addr)
547 result->unmap_view.status = NtUnmapViewOfSection( NtCurrentProcess(), addr );
548 else
549 result->unmap_view.status = STATUS_INVALID_PARAMETER;
550 break;
551 case APC_CREATE_THREAD:
553 CLIENT_ID id;
554 HANDLE handle;
555 SIZE_T reserve = call->create_thread.reserve;
556 SIZE_T commit = call->create_thread.commit;
557 void *func = wine_server_get_ptr( call->create_thread.func );
558 void *arg = wine_server_get_ptr( call->create_thread.arg );
560 result->type = call->type;
561 if (reserve == call->create_thread.reserve && commit == call->create_thread.commit &&
562 (ULONG_PTR)func == call->create_thread.func && (ULONG_PTR)arg == call->create_thread.arg)
564 result->create_thread.status = RtlCreateUserThread( NtCurrentProcess(), NULL,
565 call->create_thread.suspend, NULL,
566 reserve, commit, func, arg, &handle, &id );
567 result->create_thread.handle = wine_server_obj_handle( handle );
568 result->create_thread.tid = HandleToULong(id.UniqueThread);
570 else result->create_thread.status = STATUS_INVALID_PARAMETER;
571 break;
573 default:
574 server_protocol_error( "get_apc_request: bad type %d\n", call->type );
575 break;
577 return user_apc;
581 /***********************************************************************
582 * server_select
584 unsigned int server_select( const select_op_t *select_op, data_size_t size, UINT flags,
585 const LARGE_INTEGER *timeout )
587 unsigned int ret;
588 int cookie;
589 BOOL user_apc = FALSE;
590 obj_handle_t apc_handle = 0;
591 apc_call_t call;
592 apc_result_t result;
593 timeout_t abs_timeout = timeout ? timeout->QuadPart : TIMEOUT_INFINITE;
595 memset( &result, 0, sizeof(result) );
597 for (;;)
599 SERVER_START_REQ( select )
601 req->flags = flags;
602 req->cookie = wine_server_client_ptr( &cookie );
603 req->prev_apc = apc_handle;
604 req->timeout = abs_timeout;
605 wine_server_add_data( req, &result, sizeof(result) );
606 wine_server_add_data( req, select_op, size );
607 ret = wine_server_call( req );
608 abs_timeout = reply->timeout;
609 apc_handle = reply->apc_handle;
610 call = reply->call;
612 SERVER_END_REQ;
613 if (ret == STATUS_PENDING) ret = wait_select_reply( &cookie );
614 if (ret != STATUS_USER_APC) break;
615 if (invoke_apc( &call, &result ))
617 /* if we ran a user apc we have to check once more if additional apcs are queued,
618 * but we don't want to wait */
619 abs_timeout = 0;
620 user_apc = TRUE;
621 size = 0;
624 /* don't signal multiple times */
625 if (size >= sizeof(select_op->signal_and_wait) && select_op->op == SELECT_SIGNAL_AND_WAIT)
626 size = offsetof( select_op_t, signal_and_wait.signal );
629 if (ret == STATUS_TIMEOUT && user_apc) ret = STATUS_USER_APC;
631 /* A test on Windows 2000 shows that Windows always yields during
632 a wait, but a wait that is hit by an event gets a priority
633 boost as well. This seems to model that behavior the closest. */
634 if (ret == STATUS_TIMEOUT) NtYieldExecution();
636 return ret;
640 /***********************************************************************
641 * server_queue_process_apc
643 unsigned int server_queue_process_apc( HANDLE process, const apc_call_t *call, apc_result_t *result )
645 for (;;)
647 unsigned int ret;
648 HANDLE handle = 0;
649 BOOL self = FALSE;
651 SERVER_START_REQ( queue_apc )
653 req->handle = wine_server_obj_handle( process );
654 req->call = *call;
655 if (!(ret = wine_server_call( req )))
657 handle = wine_server_ptr_handle( reply->handle );
658 self = reply->self;
661 SERVER_END_REQ;
662 if (ret != STATUS_SUCCESS) return ret;
664 if (self)
666 invoke_apc( call, result );
668 else
670 NtWaitForSingleObject( handle, FALSE, NULL );
672 SERVER_START_REQ( get_apc_result )
674 req->handle = wine_server_obj_handle( handle );
675 if (!(ret = wine_server_call( req ))) *result = reply->result;
677 SERVER_END_REQ;
679 if (!ret && result->type == APC_NONE) continue; /* APC didn't run, try again */
681 return ret;
686 /***********************************************************************
687 * wine_server_send_fd (NTDLL.@)
689 * Send a file descriptor to the server.
691 * PARAMS
692 * fd [I] file descriptor to send
694 * RETURNS
695 * nothing
697 void CDECL wine_server_send_fd( int fd )
699 struct send_fd data;
700 struct msghdr msghdr;
701 struct iovec vec;
702 int ret;
704 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
705 msghdr.msg_accrights = (void *)&fd;
706 msghdr.msg_accrightslen = sizeof(fd);
707 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
708 char cmsg_buffer[256];
709 struct cmsghdr *cmsg;
710 msghdr.msg_control = cmsg_buffer;
711 msghdr.msg_controllen = sizeof(cmsg_buffer);
712 msghdr.msg_flags = 0;
713 cmsg = CMSG_FIRSTHDR( &msghdr );
714 cmsg->cmsg_len = CMSG_LEN( sizeof(fd) );
715 cmsg->cmsg_level = SOL_SOCKET;
716 cmsg->cmsg_type = SCM_RIGHTS;
717 *(int *)CMSG_DATA(cmsg) = fd;
718 msghdr.msg_controllen = cmsg->cmsg_len;
719 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
721 msghdr.msg_name = NULL;
722 msghdr.msg_namelen = 0;
723 msghdr.msg_iov = &vec;
724 msghdr.msg_iovlen = 1;
726 vec.iov_base = (void *)&data;
727 vec.iov_len = sizeof(data);
729 data.tid = GetCurrentThreadId();
730 data.fd = fd;
732 for (;;)
734 if ((ret = sendmsg( fd_socket, &msghdr, 0 )) == sizeof(data)) return;
735 if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
736 if (errno == EINTR) continue;
737 if (errno == EPIPE) abort_thread(0);
738 server_protocol_perror( "sendmsg" );
743 /***********************************************************************
744 * receive_fd
746 * Receive a file descriptor passed from the server.
748 static int receive_fd( obj_handle_t *handle )
750 struct iovec vec;
751 struct msghdr msghdr;
752 int ret, fd = -1;
754 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
755 msghdr.msg_accrights = (void *)&fd;
756 msghdr.msg_accrightslen = sizeof(fd);
757 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
758 char cmsg_buffer[256];
759 msghdr.msg_control = cmsg_buffer;
760 msghdr.msg_controllen = sizeof(cmsg_buffer);
761 msghdr.msg_flags = 0;
762 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
764 msghdr.msg_name = NULL;
765 msghdr.msg_namelen = 0;
766 msghdr.msg_iov = &vec;
767 msghdr.msg_iovlen = 1;
768 vec.iov_base = (void *)handle;
769 vec.iov_len = sizeof(*handle);
771 for (;;)
773 if ((ret = recvmsg( fd_socket, &msghdr, MSG_CMSG_CLOEXEC )) > 0)
775 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
776 struct cmsghdr *cmsg;
777 for (cmsg = CMSG_FIRSTHDR( &msghdr ); cmsg; cmsg = CMSG_NXTHDR( &msghdr, cmsg ))
779 if (cmsg->cmsg_level != SOL_SOCKET) continue;
780 if (cmsg->cmsg_type == SCM_RIGHTS) fd = *(int *)CMSG_DATA(cmsg);
781 #ifdef SCM_CREDENTIALS
782 else if (cmsg->cmsg_type == SCM_CREDENTIALS)
784 struct ucred *ucred = (struct ucred *)CMSG_DATA(cmsg);
785 server_pid = ucred->pid;
787 #endif
789 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
790 if (fd != -1) fcntl( fd, F_SETFD, FD_CLOEXEC ); /* in case MSG_CMSG_CLOEXEC is not supported */
791 return fd;
793 if (!ret) break;
794 if (errno == EINTR) continue;
795 if (errno == EPIPE) break;
796 server_protocol_perror("recvmsg");
798 /* the server closed the connection; time to die... */
799 abort_thread(0);
803 /***********************************************************************/
804 /* fd cache support */
806 #include "pshpack1.h"
807 union fd_cache_entry
809 LONG64 data;
810 struct
812 int fd;
813 enum server_fd_type type : 5;
814 unsigned int access : 3;
815 unsigned int options : 24;
816 } s;
818 #include "poppack.h"
820 C_ASSERT( sizeof(union fd_cache_entry) == sizeof(LONG64) );
822 #define FD_CACHE_BLOCK_SIZE (65536 / sizeof(union fd_cache_entry))
823 #define FD_CACHE_ENTRIES 128
825 static union fd_cache_entry *fd_cache[FD_CACHE_ENTRIES];
826 static union fd_cache_entry fd_cache_initial_block[FD_CACHE_BLOCK_SIZE];
828 static inline unsigned int handle_to_index( HANDLE handle, unsigned int *entry )
830 unsigned int idx = (wine_server_obj_handle(handle) >> 2) - 1;
831 *entry = idx / FD_CACHE_BLOCK_SIZE;
832 return idx % FD_CACHE_BLOCK_SIZE;
836 /***********************************************************************
837 * add_fd_to_cache
839 * Caller must hold fd_cache_section.
841 static BOOL add_fd_to_cache( HANDLE handle, int fd, enum server_fd_type type,
842 unsigned int access, unsigned int options )
844 unsigned int entry, idx = handle_to_index( handle, &entry );
845 union fd_cache_entry cache;
847 if (entry >= FD_CACHE_ENTRIES)
849 FIXME( "too many allocated handles, not caching %p\n", handle );
850 return FALSE;
853 if (!fd_cache[entry]) /* do we need to allocate a new block of entries? */
855 if (!entry) fd_cache[0] = fd_cache_initial_block;
856 else
858 void *ptr = wine_anon_mmap( NULL, FD_CACHE_BLOCK_SIZE * sizeof(union fd_cache_entry),
859 PROT_READ | PROT_WRITE, 0 );
860 if (ptr == MAP_FAILED) return FALSE;
861 fd_cache[entry] = ptr;
865 /* store fd+1 so that 0 can be used as the unset value */
866 cache.s.fd = fd + 1;
867 cache.s.type = type;
868 cache.s.access = access;
869 cache.s.options = options;
870 cache.data = interlocked_xchg64( &fd_cache[entry][idx].data, cache.data );
871 assert( !cache.s.fd );
872 return TRUE;
876 /***********************************************************************
877 * get_cached_fd
879 static inline NTSTATUS get_cached_fd( HANDLE handle, int *fd, enum server_fd_type *type,
880 unsigned int *access, unsigned int *options )
882 unsigned int entry, idx = handle_to_index( handle, &entry );
883 union fd_cache_entry cache;
885 if (entry >= FD_CACHE_ENTRIES || !fd_cache[entry]) return STATUS_INVALID_HANDLE;
887 cache.data = interlocked_cmpxchg64( &fd_cache[entry][idx].data, 0, 0 );
888 if (!cache.data) return STATUS_INVALID_HANDLE;
890 /* if fd type is invalid, fd stores an error value */
891 if (cache.s.type == FD_TYPE_INVALID) return cache.s.fd - 1;
893 *fd = cache.s.fd - 1;
894 if (type) *type = cache.s.type;
895 if (access) *access = cache.s.access;
896 if (options) *options = cache.s.options;
897 return STATUS_SUCCESS;
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 if (cache.s.type != FD_TYPE_INVALID) 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, fd = -1;
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 ret = get_cached_fd( handle, &fd, type, &access, options );
938 if (ret != STATUS_INVALID_HANDLE) goto done;
940 server_enter_uninterrupted_section( &fd_cache_section, &sigset );
941 ret = get_cached_fd( handle, &fd, type, &access, options );
942 if (ret == STATUS_INVALID_HANDLE)
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;
961 else if (reply->cacheable)
963 add_fd_to_cache( handle, ret, FD_TYPE_INVALID, 0, 0 );
966 SERVER_END_REQ;
968 server_leave_uninterrupted_section( &fd_cache_section, &sigset );
970 done:
971 if (!ret && ((access & wanted_access) != wanted_access))
973 ret = STATUS_ACCESS_DENIED;
974 if (*needs_close) close( fd );
976 if (!ret) *unix_fd = fd;
977 return ret;
981 /***********************************************************************
982 * wine_server_fd_to_handle (NTDLL.@)
984 * Allocate a file handle for a Unix file descriptor.
986 * PARAMS
987 * fd [I] Unix file descriptor.
988 * access [I] Win32 access flags.
989 * attributes [I] Object attributes.
990 * handle [O] Address where Wine file handle will be stored.
992 * RETURNS
993 * NTSTATUS code
995 int CDECL wine_server_fd_to_handle( int fd, unsigned int access, unsigned int attributes, HANDLE *handle )
997 int ret;
999 *handle = 0;
1000 wine_server_send_fd( fd );
1002 SERVER_START_REQ( alloc_file_handle )
1004 req->access = access;
1005 req->attributes = attributes;
1006 req->fd = fd;
1007 if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
1009 SERVER_END_REQ;
1010 return ret;
1014 /***********************************************************************
1015 * wine_server_handle_to_fd (NTDLL.@)
1017 * Retrieve the file descriptor corresponding to a file handle.
1019 * PARAMS
1020 * handle [I] Wine file handle.
1021 * access [I] Win32 file access rights requested.
1022 * unix_fd [O] Address where Unix file descriptor will be stored.
1023 * options [O] Address where the file open options will be stored. Optional.
1025 * RETURNS
1026 * NTSTATUS code
1028 int CDECL wine_server_handle_to_fd( HANDLE handle, unsigned int access, int *unix_fd,
1029 unsigned int *options )
1031 int needs_close, ret = server_get_unix_fd( handle, access, unix_fd, &needs_close, NULL, options );
1033 if (!ret && !needs_close)
1035 if ((*unix_fd = dup(*unix_fd)) == -1) ret = FILE_GetNtStatus();
1037 return ret;
1041 /***********************************************************************
1042 * wine_server_release_fd (NTDLL.@)
1044 * Release the Unix file descriptor returned by wine_server_handle_to_fd.
1046 * PARAMS
1047 * handle [I] Wine file handle.
1048 * unix_fd [I] Unix file descriptor to release.
1050 * RETURNS
1051 * nothing
1053 void CDECL wine_server_release_fd( HANDLE handle, int unix_fd )
1055 close( unix_fd );
1059 /***********************************************************************
1060 * server_pipe
1062 * Create a pipe for communicating with the server.
1064 int server_pipe( int fd[2] )
1066 int ret;
1067 #ifdef HAVE_PIPE2
1068 static BOOL have_pipe2 = TRUE;
1070 if (have_pipe2)
1072 if (!(ret = pipe2( fd, O_CLOEXEC ))) return ret;
1073 if (errno == ENOSYS || errno == EINVAL) have_pipe2 = FALSE; /* don't try again */
1075 #endif
1076 if (!(ret = pipe( fd )))
1078 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
1079 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
1081 return ret;
1085 /***********************************************************************
1086 * start_server
1088 * Start a new wine server.
1090 static void start_server(void)
1092 static BOOL started; /* we only try once */
1093 char *argv[3];
1094 static char wineserver[] = "server/wineserver";
1095 static char debug[] = "-d";
1097 if (!started)
1099 int status;
1100 int pid = fork();
1101 if (pid == -1) fatal_perror( "fork" );
1102 if (!pid)
1104 argv[0] = wineserver;
1105 argv[1] = TRACE_ON(server) ? debug : NULL;
1106 argv[2] = NULL;
1107 wine_exec_wine_binary( argv[0], argv, getenv("WINESERVER") );
1108 fatal_error( "could not exec wineserver\n" );
1110 waitpid( pid, &status, 0 );
1111 status = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
1112 if (status == 2) return; /* server lock held by someone else, will retry later */
1113 if (status) exit(status); /* server failed */
1114 started = TRUE;
1119 /***********************************************************************
1120 * setup_config_dir
1122 * Setup the wine configuration dir.
1124 static void setup_config_dir(void)
1126 const char *p, *config_dir = wine_get_config_dir();
1128 if (chdir( config_dir ) == -1)
1130 if (errno != ENOENT) fatal_perror( "chdir to %s\n", config_dir );
1132 if ((p = strrchr( config_dir, '/' )) && p != config_dir)
1134 struct stat st;
1135 char *tmp_dir;
1137 if (!(tmp_dir = malloc( p + 1 - config_dir ))) fatal_error( "out of memory\n" );
1138 memcpy( tmp_dir, config_dir, p - config_dir );
1139 tmp_dir[p - config_dir] = 0;
1140 if (!stat( tmp_dir, &st ) && st.st_uid != getuid())
1141 fatal_error( "'%s' is not owned by you, refusing to create a configuration directory there\n",
1142 tmp_dir );
1143 free( tmp_dir );
1146 mkdir( config_dir, 0777 );
1147 if (chdir( config_dir ) == -1) fatal_perror( "chdir to %s\n", config_dir );
1149 MESSAGE( "wine: created the configuration directory '%s'\n", config_dir );
1152 if (mkdir( "dosdevices", 0777 ) == -1)
1154 if (errno == EEXIST) return;
1155 fatal_perror( "cannot create %s/dosdevices\n", config_dir );
1158 /* create the drive symlinks */
1160 mkdir( "drive_c", 0777 );
1161 symlink( "../drive_c", "dosdevices/c:" );
1162 symlink( "/", "dosdevices/z:" );
1166 /***********************************************************************
1167 * server_connect_error
1169 * Try to display a meaningful explanation of why we couldn't connect
1170 * to the server.
1172 static void server_connect_error( const char *serverdir )
1174 int fd;
1175 struct flock fl;
1177 if ((fd = open( LOCKNAME, O_WRONLY )) == -1)
1178 fatal_error( "for some mysterious reason, the wine server never started.\n" );
1180 fl.l_type = F_WRLCK;
1181 fl.l_whence = SEEK_SET;
1182 fl.l_start = 0;
1183 fl.l_len = 1;
1184 if (fcntl( fd, F_GETLK, &fl ) != -1)
1186 if (fl.l_type == F_WRLCK) /* the file is locked */
1187 fatal_error( "a wine server seems to be running, but I cannot connect to it.\n"
1188 " You probably need to kill that process (it might be pid %d).\n",
1189 (int)fl.l_pid );
1190 fatal_error( "for some mysterious reason, the wine server failed to run.\n" );
1192 fatal_error( "the file system of '%s' doesn't support locks,\n"
1193 " and there is a 'socket' file in that directory that prevents wine from starting.\n"
1194 " You should make sure no wine server is running, remove that file and try again.\n",
1195 serverdir );
1199 /***********************************************************************
1200 * server_connect
1202 * Attempt to connect to an existing server socket.
1203 * We need to be in the server directory already.
1205 static int server_connect(void)
1207 const char *serverdir;
1208 struct sockaddr_un addr;
1209 struct stat st;
1210 int s, slen, retry, fd_cwd;
1212 /* retrieve the current directory */
1213 fd_cwd = open( ".", O_RDONLY );
1214 if (fd_cwd != -1) fcntl( fd_cwd, F_SETFD, 1 ); /* set close on exec flag */
1216 setup_config_dir();
1217 serverdir = wine_get_server_dir();
1219 /* chdir to the server directory */
1220 if (chdir( serverdir ) == -1)
1222 if (errno != ENOENT) fatal_perror( "chdir to %s", serverdir );
1223 start_server();
1224 if (chdir( serverdir ) == -1) fatal_perror( "chdir to %s", serverdir );
1227 /* make sure we are at the right place */
1228 if (stat( ".", &st ) == -1) fatal_perror( "stat %s", serverdir );
1229 if (st.st_uid != getuid()) fatal_error( "'%s' is not owned by you\n", serverdir );
1230 if (st.st_mode & 077) fatal_error( "'%s' must not be accessible by other users\n", serverdir );
1232 for (retry = 0; retry < 6; retry++)
1234 /* if not the first try, wait a bit to leave the previous server time to exit */
1235 if (retry)
1237 usleep( 100000 * retry * retry );
1238 start_server();
1239 if (lstat( SOCKETNAME, &st ) == -1) continue; /* still no socket, wait a bit more */
1241 else if (lstat( SOCKETNAME, &st ) == -1) /* check for an already existing socket */
1243 if (errno != ENOENT) fatal_perror( "lstat %s/%s", serverdir, SOCKETNAME );
1244 start_server();
1245 if (lstat( SOCKETNAME, &st ) == -1) continue; /* still no socket, wait a bit more */
1248 /* make sure the socket is sane (ISFIFO needed for Solaris) */
1249 if (!S_ISSOCK(st.st_mode) && !S_ISFIFO(st.st_mode))
1250 fatal_error( "'%s/%s' is not a socket\n", serverdir, SOCKETNAME );
1251 if (st.st_uid != getuid())
1252 fatal_error( "'%s/%s' is not owned by you\n", serverdir, SOCKETNAME );
1254 /* try to connect to it */
1255 addr.sun_family = AF_UNIX;
1256 strcpy( addr.sun_path, SOCKETNAME );
1257 slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
1258 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
1259 addr.sun_len = slen;
1260 #endif
1261 if ((s = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_perror( "socket" );
1262 #ifdef SO_PASSCRED
1263 else
1265 int enable = 1;
1266 setsockopt( s, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
1268 #endif
1269 if (connect( s, (struct sockaddr *)&addr, slen ) != -1)
1271 /* switch back to the starting directory */
1272 if (fd_cwd != -1)
1274 fchdir( fd_cwd );
1275 close( fd_cwd );
1277 fcntl( s, F_SETFD, 1 ); /* set close on exec flag */
1278 return s;
1280 close( s );
1282 server_connect_error( serverdir );
1286 #ifdef __APPLE__
1287 #include <mach/mach.h>
1288 #include <mach/mach_error.h>
1289 #include <servers/bootstrap.h>
1291 /* send our task port to the server */
1292 static void send_server_task_port(void)
1294 mach_port_t bootstrap_port, wineserver_port;
1295 kern_return_t kret;
1297 struct {
1298 mach_msg_header_t header;
1299 mach_msg_body_t body;
1300 mach_msg_port_descriptor_t task_port;
1301 } msg;
1303 if (task_get_bootstrap_port(mach_task_self(), &bootstrap_port) != KERN_SUCCESS) return;
1305 kret = bootstrap_look_up(bootstrap_port, (char*)wine_get_server_dir(), &wineserver_port);
1306 if (kret != KERN_SUCCESS)
1307 fatal_error( "cannot find the server port: 0x%08x\n", kret );
1309 mach_port_deallocate(mach_task_self(), bootstrap_port);
1311 msg.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0) | MACH_MSGH_BITS_COMPLEX;
1312 msg.header.msgh_size = sizeof(msg);
1313 msg.header.msgh_remote_port = wineserver_port;
1314 msg.header.msgh_local_port = MACH_PORT_NULL;
1316 msg.body.msgh_descriptor_count = 1;
1317 msg.task_port.name = mach_task_self();
1318 msg.task_port.disposition = MACH_MSG_TYPE_COPY_SEND;
1319 msg.task_port.type = MACH_MSG_PORT_DESCRIPTOR;
1321 kret = mach_msg_send(&msg.header);
1322 if (kret != KERN_SUCCESS)
1323 server_protocol_error( "mach_msg_send failed: 0x%08x\n", kret );
1325 mach_port_deallocate(mach_task_self(), wineserver_port);
1327 #endif /* __APPLE__ */
1330 /***********************************************************************
1331 * get_unix_tid
1333 * Retrieve the Unix tid to use on the server side for the current thread.
1335 static int get_unix_tid(void)
1337 int ret = -1;
1338 #ifdef HAVE_PTHREAD_GETTHREADID_NP
1339 ret = pthread_getthreadid_np();
1340 #elif defined(linux)
1341 ret = syscall( __NR_gettid );
1342 #elif defined(__sun)
1343 ret = pthread_self();
1344 #elif defined(__APPLE__)
1345 ret = mach_thread_self();
1346 mach_port_deallocate(mach_task_self(), ret);
1347 #elif defined(__NetBSD__)
1348 ret = _lwp_self();
1349 #elif defined(__FreeBSD__)
1350 long lwpid;
1351 thr_self( &lwpid );
1352 ret = lwpid;
1353 #elif defined(__DragonFly__)
1354 ret = lwp_gettid();
1355 #endif
1356 return ret;
1360 /***********************************************************************
1361 * server_init_process
1363 * Start the server and create the initial socket pair.
1365 void server_init_process(void)
1367 obj_handle_t version;
1368 const char *env_socket = getenv( "WINESERVERSOCKET" );
1370 server_pid = -1;
1371 if (env_socket)
1373 fd_socket = atoi( env_socket );
1374 if (fcntl( fd_socket, F_SETFD, 1 ) == -1)
1375 fatal_perror( "Bad server socket %d", fd_socket );
1376 unsetenv( "WINESERVERSOCKET" );
1378 else
1380 const char *arch = getenv( "WINEARCH" );
1382 if (arch && strcmp( arch, "win32" ) && strcmp( arch, "win64" ))
1383 fatal_error( "WINEARCH set to invalid value '%s', it must be either win32 or win64.\n", arch );
1385 fd_socket = server_connect();
1388 /* setup the signal mask */
1389 sigemptyset( &server_block_set );
1390 sigaddset( &server_block_set, SIGALRM );
1391 sigaddset( &server_block_set, SIGIO );
1392 sigaddset( &server_block_set, SIGINT );
1393 sigaddset( &server_block_set, SIGHUP );
1394 sigaddset( &server_block_set, SIGUSR1 );
1395 sigaddset( &server_block_set, SIGUSR2 );
1396 sigaddset( &server_block_set, SIGCHLD );
1397 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
1399 /* receive the first thread request fd on the main socket */
1400 ntdll_get_thread_data()->request_fd = receive_fd( &version );
1402 #ifdef SO_PASSCRED
1403 /* now that we hopefully received the server_pid, disable SO_PASSCRED */
1405 int enable = 0;
1406 setsockopt( fd_socket, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
1408 #endif
1410 if (version != SERVER_PROTOCOL_VERSION)
1411 server_protocol_error( "version mismatch %d/%d.\n"
1412 "Your %s binary was not upgraded correctly,\n"
1413 "or you have an older one somewhere in your PATH.\n"
1414 "Or maybe the wrong wineserver is still running?\n",
1415 version, SERVER_PROTOCOL_VERSION,
1416 (version > SERVER_PROTOCOL_VERSION) ? "wine" : "wineserver" );
1417 #ifdef __APPLE__
1418 send_server_task_port();
1419 #endif
1420 #if defined(__linux__) && defined(HAVE_PRCTL)
1421 /* work around Ubuntu's ptrace breakage */
1422 if (server_pid != -1) prctl( 0x59616d61 /* PR_SET_PTRACER */, server_pid );
1423 #endif
1427 /***********************************************************************
1428 * server_init_process_done
1430 NTSTATUS server_init_process_done(void)
1432 PEB *peb = NtCurrentTeb()->Peb;
1433 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
1434 NTSTATUS status;
1436 /* Install signal handlers; this cannot be done earlier, since we cannot
1437 * send exceptions to the debugger before the create process event that
1438 * is sent by REQ_INIT_PROCESS_DONE.
1439 * We do need the handlers in place by the time the request is over, so
1440 * we set them up here. If we segfault between here and the server call
1441 * something is very wrong... */
1442 signal_init_process();
1444 /* Signal the parent process to continue */
1445 SERVER_START_REQ( init_process_done )
1447 req->module = wine_server_client_ptr( peb->ImageBaseAddress );
1448 #ifdef __i386__
1449 req->ldt_copy = wine_server_client_ptr( &wine_ldt_copy );
1450 #endif
1451 req->entry = wine_server_client_ptr( (char *)peb->ImageBaseAddress + nt->OptionalHeader.AddressOfEntryPoint );
1452 req->gui = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
1453 status = wine_server_call( req );
1455 SERVER_END_REQ;
1457 return status;
1461 /***********************************************************************
1462 * server_init_thread
1464 * Send an init thread request. Return 0 if OK.
1466 size_t server_init_thread( void *entry_point )
1468 static const char *cpu_names[] = { "x86", "x86_64", "PowerPC", "ARM", "ARM64" };
1469 static const BOOL is_win64 = (sizeof(void *) > sizeof(int));
1470 const char *arch = getenv( "WINEARCH" );
1471 int ret;
1472 int reply_pipe[2];
1473 struct sigaction sig_act;
1474 size_t info_size;
1476 sig_act.sa_handler = SIG_IGN;
1477 sig_act.sa_flags = 0;
1478 sigemptyset( &sig_act.sa_mask );
1480 /* ignore SIGPIPE so that we get an EPIPE error instead */
1481 sigaction( SIGPIPE, &sig_act, NULL );
1483 /* create the server->client communication pipes */
1484 if (server_pipe( reply_pipe ) == -1) server_protocol_perror( "pipe" );
1485 if (server_pipe( ntdll_get_thread_data()->wait_fd ) == -1) server_protocol_perror( "pipe" );
1486 wine_server_send_fd( reply_pipe[1] );
1487 wine_server_send_fd( ntdll_get_thread_data()->wait_fd[1] );
1488 ntdll_get_thread_data()->reply_fd = reply_pipe[0];
1489 close( reply_pipe[1] );
1491 SERVER_START_REQ( init_thread )
1493 req->unix_pid = getpid();
1494 req->unix_tid = get_unix_tid();
1495 req->teb = wine_server_client_ptr( NtCurrentTeb() );
1496 req->entry = wine_server_client_ptr( entry_point );
1497 req->reply_fd = reply_pipe[1];
1498 req->wait_fd = ntdll_get_thread_data()->wait_fd[1];
1499 req->debug_level = (TRACE_ON(server) != 0);
1500 req->cpu = client_cpu;
1501 ret = wine_server_call( req );
1502 NtCurrentTeb()->ClientId.UniqueProcess = ULongToHandle(reply->pid);
1503 NtCurrentTeb()->ClientId.UniqueThread = ULongToHandle(reply->tid);
1504 info_size = reply->info_size;
1505 server_start_time = reply->server_start;
1506 server_cpus = reply->all_cpus;
1508 SERVER_END_REQ;
1510 is_wow64 = !is_win64 && (server_cpus & ((1 << CPU_x86_64) | (1 << CPU_ARM64))) != 0;
1511 ntdll_get_thread_data()->wow64_redir = is_wow64;
1513 switch (ret)
1515 case STATUS_SUCCESS:
1516 if (arch)
1518 if (!strcmp( arch, "win32" ) && (is_win64 || is_wow64))
1519 fatal_error( "WINEARCH set to win32 but '%s' is a 64-bit installation.\n",
1520 wine_get_config_dir() );
1521 if (!strcmp( arch, "win64" ) && !is_win64 && !is_wow64)
1522 fatal_error( "WINEARCH set to win64 but '%s' is a 32-bit installation.\n",
1523 wine_get_config_dir() );
1525 return info_size;
1526 case STATUS_INVALID_IMAGE_WIN_64:
1527 fatal_error( "'%s' is a 32-bit installation, it cannot support 64-bit applications.\n",
1528 wine_get_config_dir() );
1529 case STATUS_NOT_SUPPORTED:
1530 fatal_error( "'%s' is a 64-bit installation, it cannot be used with a 32-bit wineserver.\n",
1531 wine_get_config_dir() );
1532 case STATUS_INVALID_IMAGE_FORMAT:
1533 fatal_error( "wineserver doesn't support the %s architecture\n", cpu_names[client_cpu] );
1534 default:
1535 server_protocol_error( "init_thread failed with status %x\n", ret );