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
22 #include "wine/port.h"
35 #include <sys/types.h>
36 #ifdef HAVE_SYS_SOCKET_H
37 # include <sys/socket.h>
39 #ifdef HAVE_SYS_WAIT_H
45 #ifdef HAVE_SYS_MMAN_H
48 #ifdef HAVE_SYS_PRCTL_H
49 # include <sys/prctl.h>
51 #ifdef HAVE_SYS_STAT_H
52 # include <sys/stat.h>
54 #ifdef HAVE_SYS_SYSCALL_H
55 # include <sys/syscall.h>
61 #include <sys/ucontext.h>
69 #define WIN32_NO_STATUS
70 #include "wine/library.h"
71 #include "wine/server.h"
72 #include "wine/debug.h"
73 #include "ntdll_misc.h"
75 WINE_DEFAULT_DEBUG_CHANNEL(server);
77 /* Some versions of glibc don't define this */
82 #ifndef MSG_CMSG_CLOEXEC
83 #define MSG_CMSG_CLOEXEC 0
86 #define SOCKETNAME "socket" /* name of the socket file */
87 #define LOCKNAME "lock" /* name of the lock file */
90 static const enum cpu_type client_cpu = CPU_x86;
91 #elif defined(__x86_64__)
92 static const enum cpu_type client_cpu = CPU_x86_64;
93 #elif defined(__ALPHA__)
94 static const enum cpu_type client_cpu = CPU_ALPHA;
95 #elif defined(__powerpc__)
96 static const enum cpu_type client_cpu = CPU_POWERPC;
97 #elif defined(__sparc__)
98 static const enum cpu_type client_cpu = CPU_SPARC;
99 #elif defined(__arm__)
100 static const enum cpu_type client_cpu = CPU_ARM;
102 #error Unsupported CPU
105 unsigned int server_cpus = 0;
106 int is_wow64 = FALSE;
108 timeout_t server_start_time = 0; /* time of server startup */
110 sigset_t server_block_set; /* signals to block during server calls */
111 static int fd_socket = -1; /* socket to exchange file descriptors with the server */
112 static pid_t server_pid;
114 static RTL_CRITICAL_SECTION fd_cache_section;
115 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
117 0, 0, &fd_cache_section,
118 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
119 0, 0, { (DWORD_PTR)(__FILE__ ": fd_cache_section") }
121 static RTL_CRITICAL_SECTION fd_cache_section = { &critsect_debug, -1, 0, 0, 0, 0 };
125 static void fatal_error( const char *err, ... ) __attribute__((noreturn, format(printf,1,2)));
126 static void fatal_perror( const char *err, ... ) __attribute__((noreturn, format(printf,1,2)));
127 static void server_connect_error( const char *serverdir ) __attribute__((noreturn));
130 /* die on a fatal error; use only during initialization */
131 static void fatal_error( const char *err, ... )
135 va_start( args, err );
136 fprintf( stderr, "wine: " );
137 vfprintf( stderr, err, args );
142 /* die on a fatal error; use only during initialization */
143 static void fatal_perror( const char *err, ... )
147 va_start( args, err );
148 fprintf( stderr, "wine: " );
149 vfprintf( stderr, err, args );
156 /***********************************************************************
157 * server_protocol_error
159 void server_protocol_error( const char *err, ... )
163 va_start( args, err );
164 fprintf( stderr, "wine client error:%x: ", GetCurrentThreadId() );
165 vfprintf( stderr, err, args );
171 /***********************************************************************
172 * server_protocol_perror
174 void server_protocol_perror( const char *err )
176 fprintf( stderr, "wine client error:%x: ", GetCurrentThreadId() );
182 /***********************************************************************
185 * Send a request to the server.
187 static unsigned int send_request( const struct __server_request_info *req )
192 if (!req->u.req.request_header.request_size)
194 if ((ret = write( ntdll_get_thread_data()->request_fd, &req->u.req,
195 sizeof(req->u.req) )) == sizeof(req->u.req)) return STATUS_SUCCESS;
200 struct iovec vec[__SERVER_MAX_DATA+1];
202 vec[0].iov_base = (void *)&req->u.req;
203 vec[0].iov_len = sizeof(req->u.req);
204 for (i = 0; i < req->data_count; i++)
206 vec[i+1].iov_base = (void *)req->data[i].ptr;
207 vec[i+1].iov_len = req->data[i].size;
209 if ((ret = writev( ntdll_get_thread_data()->request_fd, vec, i+1 )) ==
210 req->u.req.request_header.request_size + sizeof(req->u.req)) return STATUS_SUCCESS;
213 if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
214 if (errno == EPIPE) abort_thread(0);
215 if (errno == EFAULT) return STATUS_ACCESS_VIOLATION;
216 server_protocol_perror( "write" );
220 /***********************************************************************
223 * Read data from the reply buffer; helper for wait_reply.
225 static void read_reply_data( void *buffer, size_t size )
231 if ((ret = read( ntdll_get_thread_data()->reply_fd, buffer, size )) > 0)
233 if (!(size -= ret)) return;
234 buffer = (char *)buffer + ret;
238 if (errno == EINTR) continue;
239 if (errno == EPIPE) break;
240 server_protocol_perror("read");
242 /* the server closed the connection; time to die... */
247 /***********************************************************************
250 * Wait for a reply from the server.
252 static inline unsigned int wait_reply( struct __server_request_info *req )
254 read_reply_data( &req->u.reply, sizeof(req->u.reply) );
255 if (req->u.reply.reply_header.reply_size)
256 read_reply_data( req->reply_data, req->u.reply.reply_header.reply_size );
257 return req->u.reply.reply_header.error;
261 /***********************************************************************
262 * wine_server_call (NTDLL.@)
264 * Perform a server call.
267 * req_ptr [I/O] Function dependent data
270 * Depends on server function being called, but usually an NTSTATUS code.
273 * Use the SERVER_START_REQ and SERVER_END_REQ to help you fill out the
274 * server request structure for the particular call. E.g:
275 *| SERVER_START_REQ( event_op )
277 *| req->handle = handle;
278 *| req->op = SET_EVENT;
279 *| ret = wine_server_call( req );
283 unsigned int wine_server_call( void *req_ptr )
285 struct __server_request_info * const req = req_ptr;
289 pthread_sigmask( SIG_BLOCK, &server_block_set, &old_set );
290 ret = send_request( req );
291 if (!ret) ret = wait_reply( req );
292 pthread_sigmask( SIG_SETMASK, &old_set, NULL );
297 /***********************************************************************
298 * server_enter_uninterrupted_section
300 void server_enter_uninterrupted_section( RTL_CRITICAL_SECTION *cs, sigset_t *sigset )
302 pthread_sigmask( SIG_BLOCK, &server_block_set, sigset );
303 RtlEnterCriticalSection( cs );
307 /***********************************************************************
308 * server_leave_uninterrupted_section
310 void server_leave_uninterrupted_section( RTL_CRITICAL_SECTION *cs, sigset_t *sigset )
312 RtlLeaveCriticalSection( cs );
313 pthread_sigmask( SIG_SETMASK, sigset, NULL );
317 /***********************************************************************
318 * wine_server_send_fd (NTDLL.@)
320 * Send a file descriptor to the server.
323 * fd [I] file descriptor to send
328 void CDECL wine_server_send_fd( int fd )
331 struct msghdr msghdr;
335 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
336 msghdr.msg_accrights = (void *)&fd;
337 msghdr.msg_accrightslen = sizeof(fd);
338 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
339 char cmsg_buffer[256];
340 struct cmsghdr *cmsg;
341 msghdr.msg_control = cmsg_buffer;
342 msghdr.msg_controllen = sizeof(cmsg_buffer);
343 msghdr.msg_flags = 0;
344 cmsg = CMSG_FIRSTHDR( &msghdr );
345 cmsg->cmsg_len = CMSG_LEN( sizeof(fd) );
346 cmsg->cmsg_level = SOL_SOCKET;
347 cmsg->cmsg_type = SCM_RIGHTS;
348 *(int *)CMSG_DATA(cmsg) = fd;
349 msghdr.msg_controllen = cmsg->cmsg_len;
350 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
352 msghdr.msg_name = NULL;
353 msghdr.msg_namelen = 0;
354 msghdr.msg_iov = &vec;
355 msghdr.msg_iovlen = 1;
357 vec.iov_base = (void *)&data;
358 vec.iov_len = sizeof(data);
360 data.tid = GetCurrentThreadId();
365 if ((ret = sendmsg( fd_socket, &msghdr, 0 )) == sizeof(data)) return;
366 if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
367 if (errno == EINTR) continue;
368 if (errno == EPIPE) abort_thread(0);
369 server_protocol_perror( "sendmsg" );
374 /***********************************************************************
377 * Receive a file descriptor passed from the server.
379 static int receive_fd( obj_handle_t *handle )
382 struct msghdr msghdr;
385 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
386 msghdr.msg_accrights = (void *)&fd;
387 msghdr.msg_accrightslen = sizeof(fd);
388 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
389 char cmsg_buffer[256];
390 msghdr.msg_control = cmsg_buffer;
391 msghdr.msg_controllen = sizeof(cmsg_buffer);
392 msghdr.msg_flags = 0;
393 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
395 msghdr.msg_name = NULL;
396 msghdr.msg_namelen = 0;
397 msghdr.msg_iov = &vec;
398 msghdr.msg_iovlen = 1;
399 vec.iov_base = (void *)handle;
400 vec.iov_len = sizeof(*handle);
404 if ((ret = recvmsg( fd_socket, &msghdr, MSG_CMSG_CLOEXEC )) > 0)
406 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
407 struct cmsghdr *cmsg;
408 for (cmsg = CMSG_FIRSTHDR( &msghdr ); cmsg; cmsg = CMSG_NXTHDR( &msghdr, cmsg ))
410 if (cmsg->cmsg_level != SOL_SOCKET) continue;
411 if (cmsg->cmsg_type == SCM_RIGHTS) fd = *(int *)CMSG_DATA(cmsg);
412 #ifdef SCM_CREDENTIALS
413 else if (cmsg->cmsg_type == SCM_CREDENTIALS)
415 struct ucred *ucred = (struct ucred *)CMSG_DATA(cmsg);
416 server_pid = ucred->pid;
420 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
421 if (fd != -1) fcntl( fd, F_SETFD, FD_CLOEXEC ); /* in case MSG_CMSG_CLOEXEC is not supported */
425 if (errno == EINTR) continue;
426 if (errno == EPIPE) break;
427 server_protocol_perror("recvmsg");
429 /* the server closed the connection; time to die... */
434 /***********************************************************************/
435 /* fd cache support */
437 struct fd_cache_entry
440 enum server_fd_type type : 6;
441 unsigned int access : 2;
442 unsigned int options : 24;
445 #define FD_CACHE_BLOCK_SIZE (65536 / sizeof(struct fd_cache_entry))
446 #define FD_CACHE_ENTRIES 128
448 static struct fd_cache_entry *fd_cache[FD_CACHE_ENTRIES];
449 static struct fd_cache_entry fd_cache_initial_block[FD_CACHE_BLOCK_SIZE];
451 static inline unsigned int handle_to_index( HANDLE handle, unsigned int *entry )
453 unsigned int idx = (wine_server_obj_handle(handle) >> 2) - 1;
454 *entry = idx / FD_CACHE_BLOCK_SIZE;
455 return idx % FD_CACHE_BLOCK_SIZE;
459 /***********************************************************************
462 * Caller must hold fd_cache_section.
464 static int add_fd_to_cache( HANDLE handle, int fd, enum server_fd_type type,
465 unsigned int access, unsigned int options )
467 unsigned int entry, idx = handle_to_index( handle, &entry );
470 if (entry >= FD_CACHE_ENTRIES)
472 FIXME( "too many allocated handles, not caching %p\n", handle );
476 if (!fd_cache[entry]) /* do we need to allocate a new block of entries? */
478 if (!entry) fd_cache[0] = fd_cache_initial_block;
481 void *ptr = wine_anon_mmap( NULL, FD_CACHE_BLOCK_SIZE * sizeof(struct fd_cache_entry),
482 PROT_READ | PROT_WRITE, 0 );
483 if (ptr == MAP_FAILED) return 0;
484 fd_cache[entry] = ptr;
487 /* store fd+1 so that 0 can be used as the unset value */
488 prev_fd = interlocked_xchg( &fd_cache[entry][idx].fd, fd + 1 ) - 1;
489 fd_cache[entry][idx].type = type;
490 fd_cache[entry][idx].access = access;
491 fd_cache[entry][idx].options = options;
492 if (prev_fd != -1) close( prev_fd );
497 /***********************************************************************
500 * Caller must hold fd_cache_section.
502 static inline int get_cached_fd( HANDLE handle, enum server_fd_type *type,
503 unsigned int *access, unsigned int *options )
505 unsigned int entry, idx = handle_to_index( handle, &entry );
508 if (entry < FD_CACHE_ENTRIES && fd_cache[entry])
510 fd = fd_cache[entry][idx].fd - 1;
511 if (type) *type = fd_cache[entry][idx].type;
512 if (access) *access = fd_cache[entry][idx].access;
513 if (options) *options = fd_cache[entry][idx].options;
519 /***********************************************************************
520 * server_remove_fd_from_cache
522 int server_remove_fd_from_cache( HANDLE handle )
524 unsigned int entry, idx = handle_to_index( handle, &entry );
527 if (entry < FD_CACHE_ENTRIES && fd_cache[entry])
528 fd = interlocked_xchg( &fd_cache[entry][idx].fd, 0 ) - 1;
534 /***********************************************************************
537 * The returned unix_fd should be closed iff needs_close is non-zero.
539 int server_get_unix_fd( HANDLE handle, unsigned int wanted_access, int *unix_fd,
540 int *needs_close, enum server_fd_type *type, unsigned int *options )
543 obj_handle_t fd_handle;
545 unsigned int access = 0;
549 wanted_access &= FILE_READ_DATA | FILE_WRITE_DATA;
551 server_enter_uninterrupted_section( &fd_cache_section, &sigset );
553 fd = get_cached_fd( handle, type, &access, options );
554 if (fd != -1) goto done;
556 SERVER_START_REQ( get_handle_fd )
558 req->handle = wine_server_obj_handle( handle );
559 if (!(ret = wine_server_call( req )))
561 if (type) *type = reply->type;
562 if (options) *options = reply->options;
563 access = reply->access;
564 if ((fd = receive_fd( &fd_handle )) != -1)
566 assert( wine_server_ptr_handle(fd_handle) == handle );
567 *needs_close = (!reply->cacheable ||
568 !add_fd_to_cache( handle, fd, reply->type,
569 reply->access, reply->options ));
571 else ret = STATUS_TOO_MANY_OPENED_FILES;
577 server_leave_uninterrupted_section( &fd_cache_section, &sigset );
578 if (!ret && ((access & wanted_access) != wanted_access))
580 ret = STATUS_ACCESS_DENIED;
581 if (*needs_close) close( fd );
583 if (!ret) *unix_fd = fd;
588 /***********************************************************************
589 * wine_server_fd_to_handle (NTDLL.@)
591 * Allocate a file handle for a Unix file descriptor.
594 * fd [I] Unix file descriptor.
595 * access [I] Win32 access flags.
596 * attributes [I] Object attributes.
597 * handle [O] Address where Wine file handle will be stored.
602 int CDECL wine_server_fd_to_handle( int fd, unsigned int access, unsigned int attributes, HANDLE *handle )
607 wine_server_send_fd( fd );
609 SERVER_START_REQ( alloc_file_handle )
611 req->access = access;
612 req->attributes = attributes;
614 if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
621 /***********************************************************************
622 * wine_server_handle_to_fd (NTDLL.@)
624 * Retrieve the file descriptor corresponding to a file handle.
627 * handle [I] Wine file handle.
628 * access [I] Win32 file access rights requested.
629 * unix_fd [O] Address where Unix file descriptor will be stored.
630 * options [O] Address where the file open options will be stored. Optional.
635 int CDECL wine_server_handle_to_fd( HANDLE handle, unsigned int access, int *unix_fd,
636 unsigned int *options )
638 int needs_close, ret = server_get_unix_fd( handle, access, unix_fd, &needs_close, NULL, options );
640 if (!ret && !needs_close)
642 if ((*unix_fd = dup(*unix_fd)) == -1) ret = FILE_GetNtStatus();
648 /***********************************************************************
649 * wine_server_release_fd (NTDLL.@)
651 * Release the Unix file descriptor returned by wine_server_handle_to_fd.
654 * handle [I] Wine file handle.
655 * unix_fd [I] Unix file descriptor to release.
660 void CDECL wine_server_release_fd( HANDLE handle, int unix_fd )
666 /***********************************************************************
669 * Create a pipe for communicating with the server.
671 int server_pipe( int fd[2] )
675 static int have_pipe2 = 1;
679 if (!(ret = pipe2( fd, O_CLOEXEC ))) return ret;
680 if (errno == ENOSYS || errno == EINVAL) have_pipe2 = 0; /* don't try again */
683 if (!(ret = pipe( fd )))
685 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
686 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
692 /***********************************************************************
695 * Start a new wine server.
697 static void start_server(void)
699 static int started; /* we only try once */
701 static char wineserver[] = "server/wineserver";
702 static char debug[] = "-d";
708 if (pid == -1) fatal_perror( "fork" );
711 argv[0] = wineserver;
712 argv[1] = TRACE_ON(server) ? debug : NULL;
714 wine_exec_wine_binary( argv[0], argv, getenv("WINESERVER") );
715 fatal_error( "could not exec wineserver\n" );
717 waitpid( pid, &status, 0 );
718 status = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
719 if (status == 2) return; /* server lock held by someone else, will retry later */
720 if (status) exit(status); /* server failed */
726 /***********************************************************************
729 * Setup the wine configuration dir.
731 static void setup_config_dir(void)
733 const char *p, *config_dir = wine_get_config_dir();
735 if (chdir( config_dir ) == -1)
737 if (errno != ENOENT) fatal_perror( "chdir to %s\n", config_dir );
739 if ((p = strrchr( config_dir, '/' )) && p != config_dir)
744 if (!(tmp_dir = malloc( p + 1 - config_dir ))) fatal_error( "out of memory\n" );
745 memcpy( tmp_dir, config_dir, p - config_dir );
746 tmp_dir[p - config_dir] = 0;
747 if (!stat( tmp_dir, &st ) && st.st_uid != getuid())
748 fatal_error( "'%s' is not owned by you, refusing to create a configuration directory there\n",
753 mkdir( config_dir, 0777 );
754 if (chdir( config_dir ) == -1) fatal_perror( "chdir to %s\n", config_dir );
756 if ((p = getenv( "WINEARCH" )) && !strcmp( p, "win32" ))
758 /* force creation of a 32-bit prefix */
759 int fd = open( "system.reg", O_WRONLY | O_CREAT | O_EXCL, 0666 );
762 static const char regfile[] = "WINE REGISTRY Version 2\n\n#arch=win32\n";
763 write( fd, regfile, sizeof(regfile) - 1 );
767 MESSAGE( "wine: created the configuration directory '%s'\n", config_dir );
770 if (mkdir( "dosdevices", 0777 ) == -1)
772 if (errno == EEXIST) return;
773 fatal_perror( "cannot create %s/dosdevices\n", config_dir );
776 /* create the drive symlinks */
778 mkdir( "drive_c", 0777 );
779 symlink( "../drive_c", "dosdevices/c:" );
780 symlink( "/", "dosdevices/z:" );
784 /***********************************************************************
785 * server_connect_error
787 * Try to display a meaningful explanation of why we couldn't connect
790 static void server_connect_error( const char *serverdir )
795 if ((fd = open( LOCKNAME, O_WRONLY )) == -1)
796 fatal_error( "for some mysterious reason, the wine server never started.\n" );
799 fl.l_whence = SEEK_SET;
802 if (fcntl( fd, F_GETLK, &fl ) != -1)
804 if (fl.l_type == F_WRLCK) /* the file is locked */
805 fatal_error( "a wine server seems to be running, but I cannot connect to it.\n"
806 " You probably need to kill that process (it might be pid %d).\n",
808 fatal_error( "for some mysterious reason, the wine server failed to run.\n" );
810 fatal_error( "the file system of '%s' doesn't support locks,\n"
811 " and there is a 'socket' file in that directory that prevents wine from starting.\n"
812 " You should make sure no wine server is running, remove that file and try again.\n",
817 /***********************************************************************
820 * Attempt to connect to an existing server socket.
821 * We need to be in the server directory already.
823 static int server_connect(void)
825 const char *serverdir;
826 struct sockaddr_un addr;
828 int s, slen, retry, fd_cwd;
830 /* retrieve the current directory */
831 fd_cwd = open( ".", O_RDONLY );
832 if (fd_cwd != -1) fcntl( fd_cwd, F_SETFD, 1 ); /* set close on exec flag */
835 serverdir = wine_get_server_dir();
837 /* chdir to the server directory */
838 if (chdir( serverdir ) == -1)
840 if (errno != ENOENT) fatal_perror( "chdir to %s", serverdir );
842 if (chdir( serverdir ) == -1) fatal_perror( "chdir to %s", serverdir );
845 /* make sure we are at the right place */
846 if (stat( ".", &st ) == -1) fatal_perror( "stat %s", serverdir );
847 if (st.st_uid != getuid()) fatal_error( "'%s' is not owned by you\n", serverdir );
848 if (st.st_mode & 077) fatal_error( "'%s' must not be accessible by other users\n", serverdir );
850 for (retry = 0; retry < 6; retry++)
852 /* if not the first try, wait a bit to leave the previous server time to exit */
855 usleep( 100000 * retry * retry );
857 if (lstat( SOCKETNAME, &st ) == -1) continue; /* still no socket, wait a bit more */
859 else if (lstat( SOCKETNAME, &st ) == -1) /* check for an already existing socket */
861 if (errno != ENOENT) fatal_perror( "lstat %s/%s", serverdir, SOCKETNAME );
863 if (lstat( SOCKETNAME, &st ) == -1) continue; /* still no socket, wait a bit more */
866 /* make sure the socket is sane (ISFIFO needed for Solaris) */
867 if (!S_ISSOCK(st.st_mode) && !S_ISFIFO(st.st_mode))
868 fatal_error( "'%s/%s' is not a socket\n", serverdir, SOCKETNAME );
869 if (st.st_uid != getuid())
870 fatal_error( "'%s/%s' is not owned by you\n", serverdir, SOCKETNAME );
872 /* try to connect to it */
873 addr.sun_family = AF_UNIX;
874 strcpy( addr.sun_path, SOCKETNAME );
875 slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
876 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
879 if ((s = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_perror( "socket" );
880 if (connect( s, (struct sockaddr *)&addr, slen ) != -1)
882 /* switch back to the starting directory */
888 fcntl( s, F_SETFD, 1 ); /* set close on exec flag */
893 server_connect_error( serverdir );
898 #include <mach/mach.h>
899 #include <mach/mach_error.h>
900 #include <servers/bootstrap.h>
902 /* send our task port to the server */
903 static void send_server_task_port(void)
905 mach_port_t bootstrap_port, wineserver_port;
909 mach_msg_header_t header;
910 mach_msg_body_t body;
911 mach_msg_port_descriptor_t task_port;
914 if (task_get_bootstrap_port(mach_task_self(), &bootstrap_port) != KERN_SUCCESS) return;
916 kret = bootstrap_look_up(bootstrap_port, (char*)wine_get_server_dir(), &wineserver_port);
917 if (kret != KERN_SUCCESS)
918 fatal_error( "cannot find the server port: 0x%08x\n", kret );
920 mach_port_deallocate(mach_task_self(), bootstrap_port);
922 msg.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0) | MACH_MSGH_BITS_COMPLEX;
923 msg.header.msgh_size = sizeof(msg);
924 msg.header.msgh_remote_port = wineserver_port;
925 msg.header.msgh_local_port = MACH_PORT_NULL;
927 msg.body.msgh_descriptor_count = 1;
928 msg.task_port.name = mach_task_self();
929 msg.task_port.disposition = MACH_MSG_TYPE_COPY_SEND;
930 msg.task_port.type = MACH_MSG_PORT_DESCRIPTOR;
932 kret = mach_msg_send(&msg.header);
933 if (kret != KERN_SUCCESS)
934 server_protocol_error( "mach_msg_send failed: 0x%08x\n", kret );
936 mach_port_deallocate(mach_task_self(), wineserver_port);
938 #endif /* __APPLE__ */
941 /***********************************************************************
944 * Retrieve the Unix tid to use on the server side for the current thread.
946 static int get_unix_tid(void)
950 ret = syscall( SYS_gettid );
952 ret = pthread_self();
953 #elif defined(__APPLE__)
954 ret = mach_thread_self();
955 mach_port_deallocate(mach_task_self(), ret);
956 #elif defined(__FreeBSD__)
965 /***********************************************************************
966 * server_init_process
968 * Start the server and create the initial socket pair.
970 void server_init_process(void)
972 obj_handle_t version;
973 const char *env_socket = getenv( "WINESERVERSOCKET" );
978 fd_socket = atoi( env_socket );
979 if (fcntl( fd_socket, F_SETFD, 1 ) == -1)
980 fatal_perror( "Bad server socket %d", fd_socket );
981 unsetenv( "WINESERVERSOCKET" );
983 else fd_socket = server_connect();
985 /* setup the signal mask */
986 sigemptyset( &server_block_set );
987 sigaddset( &server_block_set, SIGALRM );
988 sigaddset( &server_block_set, SIGIO );
989 sigaddset( &server_block_set, SIGINT );
990 sigaddset( &server_block_set, SIGHUP );
991 sigaddset( &server_block_set, SIGUSR1 );
992 sigaddset( &server_block_set, SIGUSR2 );
993 sigaddset( &server_block_set, SIGCHLD );
994 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
996 /* receive the first thread request fd on the main socket */
998 if (server_pid == -1)
1001 setsockopt( fd_socket, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
1002 ntdll_get_thread_data()->request_fd = receive_fd( &version );
1004 setsockopt( fd_socket, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
1008 ntdll_get_thread_data()->request_fd = receive_fd( &version );
1010 if (version != SERVER_PROTOCOL_VERSION)
1011 server_protocol_error( "version mismatch %d/%d.\n"
1012 "Your %s binary was not upgraded correctly,\n"
1013 "or you have an older one somewhere in your PATH.\n"
1014 "Or maybe the wrong wineserver is still running?\n",
1015 version, SERVER_PROTOCOL_VERSION,
1016 (version > SERVER_PROTOCOL_VERSION) ? "wine" : "wineserver" );
1018 send_server_task_port();
1020 #if defined(__linux__) && defined(HAVE_PRCTL)
1021 /* work around Ubuntu's ptrace breakage */
1022 if (server_pid != -1) prctl( 0x59616d61 /* PR_SET_PTRACER */, server_pid );
1027 /***********************************************************************
1028 * server_init_process_done
1030 NTSTATUS server_init_process_done(void)
1032 PEB *peb = NtCurrentTeb()->Peb;
1033 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
1036 /* Install signal handlers; this cannot be done earlier, since we cannot
1037 * send exceptions to the debugger before the create process event that
1038 * is sent by REQ_INIT_PROCESS_DONE.
1039 * We do need the handlers in place by the time the request is over, so
1040 * we set them up here. If we segfault between here and the server call
1041 * something is very wrong... */
1042 signal_init_process();
1044 /* Signal the parent process to continue */
1045 SERVER_START_REQ( init_process_done )
1047 req->module = wine_server_client_ptr( peb->ImageBaseAddress );
1049 req->ldt_copy = wine_server_client_ptr( &wine_ldt_copy );
1051 req->entry = wine_server_client_ptr( (char *)peb->ImageBaseAddress + nt->OptionalHeader.AddressOfEntryPoint );
1052 req->gui = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
1053 status = wine_server_call( req );
1061 /***********************************************************************
1062 * server_init_thread
1064 * Send an init thread request. Return 0 if OK.
1066 size_t server_init_thread( void *entry_point )
1068 static const int is_win64 = (sizeof(void *) > sizeof(int));
1069 const char *arch = getenv( "WINEARCH" );
1072 struct sigaction sig_act;
1075 sig_act.sa_handler = SIG_IGN;
1076 sig_act.sa_flags = 0;
1077 sigemptyset( &sig_act.sa_mask );
1079 /* ignore SIGPIPE so that we get an EPIPE error instead */
1080 sigaction( SIGPIPE, &sig_act, NULL );
1081 /* automatic child reaping to avoid zombies */
1083 sig_act.sa_flags |= SA_NOCLDWAIT;
1085 sigaction( SIGCHLD, &sig_act, NULL );
1087 /* create the server->client communication pipes */
1088 if (server_pipe( reply_pipe ) == -1) server_protocol_perror( "pipe" );
1089 if (server_pipe( ntdll_get_thread_data()->wait_fd ) == -1) server_protocol_perror( "pipe" );
1090 wine_server_send_fd( reply_pipe[1] );
1091 wine_server_send_fd( ntdll_get_thread_data()->wait_fd[1] );
1092 ntdll_get_thread_data()->reply_fd = reply_pipe[0];
1093 close( reply_pipe[1] );
1095 SERVER_START_REQ( init_thread )
1097 req->unix_pid = getpid();
1098 req->unix_tid = get_unix_tid();
1099 req->teb = wine_server_client_ptr( NtCurrentTeb() );
1100 req->entry = wine_server_client_ptr( entry_point );
1101 req->reply_fd = reply_pipe[1];
1102 req->wait_fd = ntdll_get_thread_data()->wait_fd[1];
1103 req->debug_level = (TRACE_ON(server) != 0);
1104 req->cpu = client_cpu;
1105 ret = wine_server_call( req );
1106 NtCurrentTeb()->ClientId.UniqueProcess = ULongToHandle(reply->pid);
1107 NtCurrentTeb()->ClientId.UniqueThread = ULongToHandle(reply->tid);
1108 info_size = reply->info_size;
1109 server_start_time = reply->server_start;
1110 server_cpus = reply->all_cpus;
1114 is_wow64 = !is_win64 && (server_cpus & (1 << CPU_x86_64)) != 0;
1115 ntdll_get_thread_data()->wow64_redir = is_wow64;
1119 case STATUS_SUCCESS:
1122 if (!strcmp( arch, "win32" ) && (is_win64 || is_wow64))
1123 fatal_error( "WINEARCH set to win32 but '%s' is a 64-bit installation.\n",
1124 wine_get_config_dir() );
1125 if (!strcmp( arch, "win64" ) && !is_wow64)
1126 fatal_error( "WINEARCH set to win64 but '%s' is a 32-bit installation.\n",
1127 wine_get_config_dir() );
1130 case STATUS_NOT_REGISTRY_FILE:
1131 fatal_error( "'%s' is a 32-bit installation, it cannot support 64-bit applications.\n",
1132 wine_get_config_dir() );
1133 case STATUS_NOT_SUPPORTED:
1135 fatal_error( "wineserver is 32-bit, it cannot support 64-bit applications.\n" );
1137 fatal_error( "'%s' is a 64-bit installation, it cannot be used with a 32-bit wineserver.\n",
1138 wine_get_config_dir() );
1140 server_protocol_error( "init_thread failed with status %x\n", ret );