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_STAT_H
49 # include <sys/stat.h>
55 #include <sys/ucontext.h>
63 #define WIN32_NO_STATUS
64 #include "wine/library.h"
65 #include "wine/server.h"
66 #include "wine/debug.h"
67 #include "ntdll_misc.h"
69 WINE_DEFAULT_DEBUG_CHANNEL(server);
71 /* Some versions of glibc don't define this */
76 #ifndef MSG_CMSG_CLOEXEC
77 #define MSG_CMSG_CLOEXEC 0
80 #define SOCKETNAME "socket" /* name of the socket file */
81 #define LOCKNAME "lock" /* name of the lock file */
84 static const enum cpu_type client_cpu = CPU_x86;
85 #elif defined(__x86_64__)
86 static const enum cpu_type client_cpu = CPU_x86_64;
87 #elif defined(__ALPHA__)
88 static const enum cpu_type client_cpu = CPU_ALPHA;
89 #elif defined(__powerpc__)
90 static const enum cpu_type client_cpu = CPU_POWERPC;
91 #elif defined(__sparc__)
92 static const enum cpu_type client_cpu = CPU_SPARC;
93 #elif defined(__arm__)
94 static const enum cpu_type client_cpu = CPU_ARM;
96 #error Unsupported CPU
99 unsigned int server_cpus = 0;
100 int is_wow64 = FALSE;
102 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
103 /* data structure used to pass an fd with sendmsg/recvmsg */
108 size_t len; /* size of structure */
109 int level; /* SOL_SOCKET */
110 int type; /* SCM_RIGHTS */
112 int fd; /* fd to pass */
114 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
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 */
121 static RTL_CRITICAL_SECTION fd_cache_section;
122 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
124 0, 0, &fd_cache_section,
125 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
126 0, 0, { (DWORD_PTR)(__FILE__ ": fd_cache_section") }
128 static RTL_CRITICAL_SECTION fd_cache_section = { &critsect_debug, -1, 0, 0, 0, 0 };
132 static void fatal_error( const char *err, ... ) __attribute__((noreturn, format(printf,1,2)));
133 static void fatal_perror( const char *err, ... ) __attribute__((noreturn, format(printf,1,2)));
134 static void server_connect_error( const char *serverdir ) __attribute__((noreturn));
137 /* die on a fatal error; use only during initialization */
138 static void fatal_error( const char *err, ... )
142 va_start( args, err );
143 fprintf( stderr, "wine: " );
144 vfprintf( stderr, err, args );
149 /* die on a fatal error; use only during initialization */
150 static void fatal_perror( const char *err, ... )
154 va_start( args, err );
155 fprintf( stderr, "wine: " );
156 vfprintf( stderr, err, args );
163 /***********************************************************************
164 * server_protocol_error
166 void server_protocol_error( const char *err, ... )
170 va_start( args, err );
171 fprintf( stderr, "wine client error:%x: ", GetCurrentThreadId() );
172 vfprintf( stderr, err, args );
178 /***********************************************************************
179 * server_protocol_perror
181 void server_protocol_perror( const char *err )
183 fprintf( stderr, "wine client error:%x: ", GetCurrentThreadId() );
189 /***********************************************************************
192 * Send a request to the server.
194 static unsigned int send_request( const struct __server_request_info *req )
199 if (!req->u.req.request_header.request_size)
201 if ((ret = write( ntdll_get_thread_data()->request_fd, &req->u.req,
202 sizeof(req->u.req) )) == sizeof(req->u.req)) return STATUS_SUCCESS;
207 struct iovec vec[__SERVER_MAX_DATA+1];
209 vec[0].iov_base = (void *)&req->u.req;
210 vec[0].iov_len = sizeof(req->u.req);
211 for (i = 0; i < req->data_count; i++)
213 vec[i+1].iov_base = (void *)req->data[i].ptr;
214 vec[i+1].iov_len = req->data[i].size;
216 if ((ret = writev( ntdll_get_thread_data()->request_fd, vec, i+1 )) ==
217 req->u.req.request_header.request_size + sizeof(req->u.req)) return STATUS_SUCCESS;
220 if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
221 if (errno == EPIPE) abort_thread(0);
222 if (errno == EFAULT) return STATUS_ACCESS_VIOLATION;
223 server_protocol_perror( "write" );
227 /***********************************************************************
230 * Read data from the reply buffer; helper for wait_reply.
232 static void read_reply_data( void *buffer, size_t size )
238 if ((ret = read( ntdll_get_thread_data()->reply_fd, buffer, size )) > 0)
240 if (!(size -= ret)) return;
241 buffer = (char *)buffer + ret;
245 if (errno == EINTR) continue;
246 if (errno == EPIPE) break;
247 server_protocol_perror("read");
249 /* the server closed the connection; time to die... */
254 /***********************************************************************
257 * Wait for a reply from the server.
259 static inline unsigned int wait_reply( struct __server_request_info *req )
261 read_reply_data( &req->u.reply, sizeof(req->u.reply) );
262 if (req->u.reply.reply_header.reply_size)
263 read_reply_data( req->reply_data, req->u.reply.reply_header.reply_size );
264 return req->u.reply.reply_header.error;
268 /***********************************************************************
269 * wine_server_call (NTDLL.@)
271 * Perform a server call.
274 * req_ptr [I/O] Function dependent data
277 * Depends on server function being called, but usually an NTSTATUS code.
280 * Use the SERVER_START_REQ and SERVER_END_REQ to help you fill out the
281 * server request structure for the particular call. E.g:
282 *| SERVER_START_REQ( event_op )
284 *| req->handle = handle;
285 *| req->op = SET_EVENT;
286 *| ret = wine_server_call( req );
290 unsigned int wine_server_call( void *req_ptr )
292 struct __server_request_info * const req = req_ptr;
296 pthread_sigmask( SIG_BLOCK, &server_block_set, &old_set );
297 ret = send_request( req );
298 if (!ret) ret = wait_reply( req );
299 pthread_sigmask( SIG_SETMASK, &old_set, NULL );
304 /***********************************************************************
305 * server_enter_uninterrupted_section
307 void server_enter_uninterrupted_section( RTL_CRITICAL_SECTION *cs, sigset_t *sigset )
309 pthread_sigmask( SIG_BLOCK, &server_block_set, sigset );
310 RtlEnterCriticalSection( cs );
314 /***********************************************************************
315 * server_leave_uninterrupted_section
317 void server_leave_uninterrupted_section( RTL_CRITICAL_SECTION *cs, sigset_t *sigset )
319 RtlLeaveCriticalSection( cs );
320 pthread_sigmask( SIG_SETMASK, sigset, NULL );
324 /***********************************************************************
325 * wine_server_send_fd (NTDLL.@)
327 * Send a file descriptor to the server.
330 * fd [I] file descriptor to send
335 void CDECL wine_server_send_fd( int fd )
337 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
341 struct msghdr msghdr;
345 vec.iov_base = (void *)&data;
346 vec.iov_len = sizeof(data);
348 msghdr.msg_name = NULL;
349 msghdr.msg_namelen = 0;
350 msghdr.msg_iov = &vec;
351 msghdr.msg_iovlen = 1;
353 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
354 msghdr.msg_accrights = (void *)&fd;
355 msghdr.msg_accrightslen = sizeof(fd);
356 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
357 cmsg.header.len = sizeof(cmsg.header) + sizeof(fd);
358 cmsg.header.level = SOL_SOCKET;
359 cmsg.header.type = SCM_RIGHTS;
361 msghdr.msg_control = &cmsg;
362 msghdr.msg_controllen = sizeof(cmsg.header) + sizeof(fd);
363 msghdr.msg_flags = 0;
364 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
366 data.tid = GetCurrentThreadId();
371 if ((ret = sendmsg( fd_socket, &msghdr, 0 )) == sizeof(data)) return;
372 if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
373 if (errno == EINTR) continue;
374 if (errno == EPIPE) abort_thread(0);
375 server_protocol_perror( "sendmsg" );
380 /***********************************************************************
383 * Receive a file descriptor passed from the server.
385 static int receive_fd( obj_handle_t *handle )
390 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
391 struct msghdr msghdr;
394 msghdr.msg_accrights = (void *)&fd;
395 msghdr.msg_accrightslen = sizeof(fd);
396 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
397 struct msghdr msghdr;
400 cmsg.header.len = sizeof(cmsg.header) + sizeof(fd);
401 cmsg.header.level = SOL_SOCKET;
402 cmsg.header.type = SCM_RIGHTS;
404 msghdr.msg_control = &cmsg;
405 msghdr.msg_controllen = sizeof(cmsg.header) + sizeof(fd);
406 msghdr.msg_flags = 0;
407 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
409 msghdr.msg_name = NULL;
410 msghdr.msg_namelen = 0;
411 msghdr.msg_iov = &vec;
412 msghdr.msg_iovlen = 1;
413 vec.iov_base = (void *)handle;
414 vec.iov_len = sizeof(*handle);
418 if ((ret = recvmsg( fd_socket, &msghdr, MSG_CMSG_CLOEXEC )) > 0)
420 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
423 if (fd != -1) fcntl( fd, F_SETFD, FD_CLOEXEC ); /* in case MSG_CMSG_CLOEXEC is not supported */
427 if (errno == EINTR) continue;
428 if (errno == EPIPE) break;
429 server_protocol_perror("recvmsg");
431 /* the server closed the connection; time to die... */
436 /***********************************************************************/
437 /* fd cache support */
439 struct fd_cache_entry
442 enum server_fd_type type : 6;
443 unsigned int access : 2;
444 unsigned int options : 24;
447 #define FD_CACHE_BLOCK_SIZE (65536 / sizeof(struct fd_cache_entry))
448 #define FD_CACHE_ENTRIES 128
450 static struct fd_cache_entry *fd_cache[FD_CACHE_ENTRIES];
451 static struct fd_cache_entry fd_cache_initial_block[FD_CACHE_BLOCK_SIZE];
453 static inline unsigned int handle_to_index( HANDLE handle, unsigned int *entry )
455 unsigned int idx = (wine_server_obj_handle(handle) >> 2) - 1;
456 *entry = idx / FD_CACHE_BLOCK_SIZE;
457 return idx % FD_CACHE_BLOCK_SIZE;
461 /***********************************************************************
464 * Caller must hold fd_cache_section.
466 static int add_fd_to_cache( HANDLE handle, int fd, enum server_fd_type type,
467 unsigned int access, unsigned int options )
469 unsigned int entry, idx = handle_to_index( handle, &entry );
472 if (entry >= FD_CACHE_ENTRIES)
474 FIXME( "too many allocated handles, not caching %p\n", handle );
478 if (!fd_cache[entry]) /* do we need to allocate a new block of entries? */
480 if (!entry) fd_cache[0] = fd_cache_initial_block;
483 void *ptr = wine_anon_mmap( NULL, FD_CACHE_BLOCK_SIZE * sizeof(struct fd_cache_entry),
484 PROT_READ | PROT_WRITE, 0 );
485 if (ptr == MAP_FAILED) return 0;
486 fd_cache[entry] = ptr;
489 /* store fd+1 so that 0 can be used as the unset value */
490 prev_fd = interlocked_xchg( &fd_cache[entry][idx].fd, fd + 1 ) - 1;
491 fd_cache[entry][idx].type = type;
492 fd_cache[entry][idx].access = access;
493 fd_cache[entry][idx].options = options;
494 if (prev_fd != -1) close( prev_fd );
499 /***********************************************************************
502 * Caller must hold fd_cache_section.
504 static inline int get_cached_fd( HANDLE handle, enum server_fd_type *type,
505 unsigned int *access, unsigned int *options )
507 unsigned int entry, idx = handle_to_index( handle, &entry );
510 if (entry < FD_CACHE_ENTRIES && fd_cache[entry])
512 fd = fd_cache[entry][idx].fd - 1;
513 if (type) *type = fd_cache[entry][idx].type;
514 if (access) *access = fd_cache[entry][idx].access;
515 if (options) *options = fd_cache[entry][idx].options;
521 /***********************************************************************
522 * server_remove_fd_from_cache
524 int server_remove_fd_from_cache( HANDLE handle )
526 unsigned int entry, idx = handle_to_index( handle, &entry );
529 if (entry < FD_CACHE_ENTRIES && fd_cache[entry])
530 fd = interlocked_xchg( &fd_cache[entry][idx].fd, 0 ) - 1;
536 /***********************************************************************
539 * The returned unix_fd should be closed iff needs_close is non-zero.
541 int server_get_unix_fd( HANDLE handle, unsigned int wanted_access, int *unix_fd,
542 int *needs_close, enum server_fd_type *type, unsigned int *options )
545 obj_handle_t fd_handle;
547 unsigned int access = 0;
551 wanted_access &= FILE_READ_DATA | FILE_WRITE_DATA;
553 server_enter_uninterrupted_section( &fd_cache_section, &sigset );
555 fd = get_cached_fd( handle, type, &access, options );
556 if (fd != -1) goto done;
558 SERVER_START_REQ( get_handle_fd )
560 req->handle = wine_server_obj_handle( handle );
561 if (!(ret = wine_server_call( req )))
563 if (type) *type = reply->type;
564 if (options) *options = reply->options;
565 access = reply->access;
566 if ((fd = receive_fd( &fd_handle )) != -1)
568 assert( wine_server_ptr_handle(fd_handle) == handle );
569 *needs_close = (!reply->cacheable ||
570 !add_fd_to_cache( handle, fd, reply->type,
571 reply->access, reply->options ));
573 else ret = STATUS_TOO_MANY_OPENED_FILES;
579 server_leave_uninterrupted_section( &fd_cache_section, &sigset );
580 if (!ret && ((access & wanted_access) != wanted_access))
582 ret = STATUS_ACCESS_DENIED;
583 if (*needs_close) close( fd );
585 if (!ret) *unix_fd = fd;
590 /***********************************************************************
591 * wine_server_fd_to_handle (NTDLL.@)
593 * Allocate a file handle for a Unix file descriptor.
596 * fd [I] Unix file descriptor.
597 * access [I] Win32 access flags.
598 * attributes [I] Object attributes.
599 * handle [O] Address where Wine file handle will be stored.
604 int CDECL wine_server_fd_to_handle( int fd, unsigned int access, unsigned int attributes, HANDLE *handle )
609 wine_server_send_fd( fd );
611 SERVER_START_REQ( alloc_file_handle )
613 req->access = access;
614 req->attributes = attributes;
616 if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
623 /***********************************************************************
624 * wine_server_handle_to_fd (NTDLL.@)
626 * Retrieve the file descriptor corresponding to a file handle.
629 * handle [I] Wine file handle.
630 * access [I] Win32 file access rights requested.
631 * unix_fd [O] Address where Unix file descriptor will be stored.
632 * options [O] Address where the file open options will be stored. Optional.
637 int CDECL wine_server_handle_to_fd( HANDLE handle, unsigned int access, int *unix_fd,
638 unsigned int *options )
640 int needs_close, ret = server_get_unix_fd( handle, access, unix_fd, &needs_close, NULL, options );
642 if (!ret && !needs_close)
644 if ((*unix_fd = dup(*unix_fd)) == -1) ret = FILE_GetNtStatus();
650 /***********************************************************************
651 * wine_server_release_fd (NTDLL.@)
653 * Release the Unix file descriptor returned by wine_server_handle_to_fd.
656 * handle [I] Wine file handle.
657 * unix_fd [I] Unix file descriptor to release.
662 void CDECL wine_server_release_fd( HANDLE handle, int unix_fd )
668 /***********************************************************************
671 * Create a pipe for communicating with the server.
673 int server_pipe( int fd[2] )
677 static int have_pipe2 = 1;
681 if (!(ret = pipe2( fd, O_CLOEXEC ))) return ret;
682 if (errno == ENOSYS || errno == EINVAL) have_pipe2 = 0; /* don't try again */
685 if (!(ret = pipe( fd )))
687 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
688 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
694 /***********************************************************************
697 * Start a new wine server.
699 static void start_server(void)
701 static int started; /* we only try once */
703 static char wineserver[] = "server/wineserver";
704 static char debug[] = "-d";
710 if (pid == -1) fatal_perror( "fork" );
713 argv[0] = wineserver;
714 argv[1] = TRACE_ON(server) ? debug : NULL;
716 wine_exec_wine_binary( argv[0], argv, getenv("WINESERVER") );
717 fatal_error( "could not exec wineserver\n" );
719 waitpid( pid, &status, 0 );
720 status = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
721 if (status == 2) return; /* server lock held by someone else, will retry later */
722 if (status) exit(status); /* server failed */
728 /***********************************************************************
731 * Setup the wine configuration dir.
733 static void setup_config_dir(void)
735 const char *p, *config_dir = wine_get_config_dir();
737 if (chdir( config_dir ) == -1)
739 if (errno != ENOENT) fatal_perror( "chdir to %s\n", config_dir );
741 if ((p = strrchr( config_dir, '/' )) && p != config_dir)
746 if (!(tmp_dir = malloc( p + 1 - config_dir ))) fatal_error( "out of memory\n" );
747 memcpy( tmp_dir, config_dir, p - config_dir );
748 tmp_dir[p - config_dir] = 0;
749 if (!stat( tmp_dir, &st ) && st.st_uid != getuid())
750 fatal_error( "'%s' is not owned by you, refusing to create a configuration directory there\n",
755 mkdir( config_dir, 0777 );
756 if (chdir( config_dir ) == -1) fatal_perror( "chdir to %s\n", config_dir );
758 if ((p = getenv( "WINEARCH" )) && !strcmp( p, "win32" ))
760 /* force creation of a 32-bit prefix */
761 int fd = open( "system.reg", O_WRONLY | O_CREAT | O_EXCL, 0666 );
764 static const char regfile[] = "WINE REGISTRY Version 2\n\n#arch=win32\n";
765 write( fd, regfile, sizeof(regfile) - 1 );
769 MESSAGE( "wine: created the configuration directory '%s'\n", config_dir );
772 if (mkdir( "dosdevices", 0777 ) == -1)
774 if (errno == EEXIST) return;
775 fatal_perror( "cannot create %s/dosdevices\n", config_dir );
778 /* create the drive symlinks */
780 mkdir( "drive_c", 0777 );
781 symlink( "../drive_c", "dosdevices/c:" );
782 symlink( "/", "dosdevices/z:" );
786 /***********************************************************************
787 * server_connect_error
789 * Try to display a meaningful explanation of why we couldn't connect
792 static void server_connect_error( const char *serverdir )
797 if ((fd = open( LOCKNAME, O_WRONLY )) == -1)
798 fatal_error( "for some mysterious reason, the wine server never started.\n" );
801 fl.l_whence = SEEK_SET;
804 if (fcntl( fd, F_GETLK, &fl ) != -1)
806 if (fl.l_type == F_WRLCK) /* the file is locked */
807 fatal_error( "a wine server seems to be running, but I cannot connect to it.\n"
808 " You probably need to kill that process (it might be pid %d).\n",
810 fatal_error( "for some mysterious reason, the wine server failed to run.\n" );
812 fatal_error( "the file system of '%s' doesn't support locks,\n"
813 " and there is a 'socket' file in that directory that prevents wine from starting.\n"
814 " You should make sure no wine server is running, remove that file and try again.\n",
819 /***********************************************************************
822 * Attempt to connect to an existing server socket.
823 * We need to be in the server directory already.
825 static int server_connect(void)
827 const char *serverdir;
828 struct sockaddr_un addr;
830 int s, slen, retry, fd_cwd;
832 /* retrieve the current directory */
833 fd_cwd = open( ".", O_RDONLY );
834 if (fd_cwd != -1) fcntl( fd_cwd, F_SETFD, 1 ); /* set close on exec flag */
837 serverdir = wine_get_server_dir();
839 /* chdir to the server directory */
840 if (chdir( serverdir ) == -1)
842 if (errno != ENOENT) fatal_perror( "chdir to %s", serverdir );
844 if (chdir( serverdir ) == -1) fatal_perror( "chdir to %s", serverdir );
847 /* make sure we are at the right place */
848 if (stat( ".", &st ) == -1) fatal_perror( "stat %s", serverdir );
849 if (st.st_uid != getuid()) fatal_error( "'%s' is not owned by you\n", serverdir );
850 if (st.st_mode & 077) fatal_error( "'%s' must not be accessible by other users\n", serverdir );
852 for (retry = 0; retry < 6; retry++)
854 /* if not the first try, wait a bit to leave the previous server time to exit */
857 usleep( 100000 * retry * retry );
859 if (lstat( SOCKETNAME, &st ) == -1) continue; /* still no socket, wait a bit more */
861 else if (lstat( SOCKETNAME, &st ) == -1) /* check for an already existing socket */
863 if (errno != ENOENT) fatal_perror( "lstat %s/%s", serverdir, SOCKETNAME );
865 if (lstat( SOCKETNAME, &st ) == -1) continue; /* still no socket, wait a bit more */
868 /* make sure the socket is sane (ISFIFO needed for Solaris) */
869 if (!S_ISSOCK(st.st_mode) && !S_ISFIFO(st.st_mode))
870 fatal_error( "'%s/%s' is not a socket\n", serverdir, SOCKETNAME );
871 if (st.st_uid != getuid())
872 fatal_error( "'%s/%s' is not owned by you\n", serverdir, SOCKETNAME );
874 /* try to connect to it */
875 addr.sun_family = AF_UNIX;
876 strcpy( addr.sun_path, SOCKETNAME );
877 slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
878 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
881 if ((s = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_perror( "socket" );
882 if (connect( s, (struct sockaddr *)&addr, slen ) != -1)
884 /* switch back to the starting directory */
890 fcntl( s, F_SETFD, 1 ); /* set close on exec flag */
895 server_connect_error( serverdir );
900 #include <mach/mach.h>
901 #include <mach/mach_error.h>
902 #include <servers/bootstrap.h>
904 /* send our task port to the server */
905 static void send_server_task_port(void)
907 mach_port_t bootstrap_port, wineserver_port;
911 mach_msg_header_t header;
912 mach_msg_body_t body;
913 mach_msg_port_descriptor_t task_port;
916 if (task_get_bootstrap_port(mach_task_self(), &bootstrap_port) != KERN_SUCCESS) return;
918 kret = bootstrap_look_up(bootstrap_port, (char*)wine_get_server_dir(), &wineserver_port);
919 if (kret != KERN_SUCCESS)
920 fatal_error( "cannot find the server port: 0x%08x\n", kret );
922 mach_port_deallocate(mach_task_self(), bootstrap_port);
924 msg.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0) | MACH_MSGH_BITS_COMPLEX;
925 msg.header.msgh_size = sizeof(msg);
926 msg.header.msgh_remote_port = wineserver_port;
927 msg.header.msgh_local_port = MACH_PORT_NULL;
929 msg.body.msgh_descriptor_count = 1;
930 msg.task_port.name = mach_task_self();
931 msg.task_port.disposition = MACH_MSG_TYPE_COPY_SEND;
932 msg.task_port.type = MACH_MSG_PORT_DESCRIPTOR;
934 kret = mach_msg_send(&msg.header);
935 if (kret != KERN_SUCCESS)
936 server_protocol_error( "mach_msg_send failed: 0x%08x\n", kret );
938 mach_port_deallocate(mach_task_self(), wineserver_port);
940 #endif /* __APPLE__ */
943 /***********************************************************************
946 * Retrieve the Unix tid to use on the server side for the current thread.
948 static int get_unix_tid(void)
951 #if defined(linux) && defined(__i386__)
952 ret = syscall(224 /*SYS_gettid*/);
953 #elif defined(linux) && defined(__x86_64__)
954 ret = syscall(186 /*SYS_gettid*/);
956 ret = pthread_self();
957 #elif defined(__APPLE__)
958 ret = mach_thread_self();
959 mach_port_deallocate(mach_task_self(), ret);
960 #elif defined(__FreeBSD__)
969 /***********************************************************************
970 * server_init_process
972 * Start the server and create the initial socket pair.
974 void server_init_process(void)
976 obj_handle_t version;
977 const char *env_socket = getenv( "WINESERVERSOCKET" );
981 fd_socket = atoi( env_socket );
982 if (fcntl( fd_socket, F_SETFD, 1 ) == -1)
983 fatal_perror( "Bad server socket %d", fd_socket );
984 unsetenv( "WINESERVERSOCKET" );
986 else fd_socket = server_connect();
988 /* setup the signal mask */
989 sigemptyset( &server_block_set );
990 sigaddset( &server_block_set, SIGALRM );
991 sigaddset( &server_block_set, SIGIO );
992 sigaddset( &server_block_set, SIGINT );
993 sigaddset( &server_block_set, SIGHUP );
994 sigaddset( &server_block_set, SIGUSR1 );
995 sigaddset( &server_block_set, SIGUSR2 );
996 sigaddset( &server_block_set, SIGCHLD );
997 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
999 /* receive the first thread request fd on the main socket */
1000 ntdll_get_thread_data()->request_fd = receive_fd( &version );
1002 if (version != SERVER_PROTOCOL_VERSION)
1003 server_protocol_error( "version mismatch %d/%d.\n"
1004 "Your %s binary was not upgraded correctly,\n"
1005 "or you have an older one somewhere in your PATH.\n"
1006 "Or maybe the wrong wineserver is still running?\n",
1007 version, SERVER_PROTOCOL_VERSION,
1008 (version > SERVER_PROTOCOL_VERSION) ? "wine" : "wineserver" );
1010 send_server_task_port();
1015 /***********************************************************************
1016 * server_init_process_done
1018 NTSTATUS server_init_process_done(void)
1020 PEB *peb = NtCurrentTeb()->Peb;
1021 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
1024 /* Install signal handlers; this cannot be done earlier, since we cannot
1025 * send exceptions to the debugger before the create process event that
1026 * is sent by REQ_INIT_PROCESS_DONE.
1027 * We do need the handlers in place by the time the request is over, so
1028 * we set them up here. If we segfault between here and the server call
1029 * something is very wrong... */
1030 signal_init_process();
1032 /* Signal the parent process to continue */
1033 SERVER_START_REQ( init_process_done )
1035 req->module = wine_server_client_ptr( peb->ImageBaseAddress );
1037 req->ldt_copy = wine_server_client_ptr( &wine_ldt_copy );
1039 req->entry = wine_server_client_ptr( (char *)peb->ImageBaseAddress + nt->OptionalHeader.AddressOfEntryPoint );
1040 req->gui = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
1041 status = wine_server_call( req );
1049 /***********************************************************************
1050 * server_init_thread
1052 * Send an init thread request. Return 0 if OK.
1054 size_t server_init_thread( void *entry_point )
1056 static const int is_win64 = (sizeof(void *) > sizeof(int));
1057 const char *arch = getenv( "WINEARCH" );
1060 struct sigaction sig_act;
1063 sig_act.sa_handler = SIG_IGN;
1064 sig_act.sa_flags = 0;
1065 sigemptyset( &sig_act.sa_mask );
1067 /* ignore SIGPIPE so that we get an EPIPE error instead */
1068 sigaction( SIGPIPE, &sig_act, NULL );
1069 /* automatic child reaping to avoid zombies */
1071 sig_act.sa_flags |= SA_NOCLDWAIT;
1073 sigaction( SIGCHLD, &sig_act, NULL );
1075 /* create the server->client communication pipes */
1076 if (server_pipe( reply_pipe ) == -1) server_protocol_perror( "pipe" );
1077 if (server_pipe( ntdll_get_thread_data()->wait_fd ) == -1) server_protocol_perror( "pipe" );
1078 wine_server_send_fd( reply_pipe[1] );
1079 wine_server_send_fd( ntdll_get_thread_data()->wait_fd[1] );
1080 ntdll_get_thread_data()->reply_fd = reply_pipe[0];
1081 close( reply_pipe[1] );
1083 SERVER_START_REQ( init_thread )
1085 req->unix_pid = getpid();
1086 req->unix_tid = get_unix_tid();
1087 req->teb = wine_server_client_ptr( NtCurrentTeb() );
1088 req->entry = wine_server_client_ptr( entry_point );
1089 req->reply_fd = reply_pipe[1];
1090 req->wait_fd = ntdll_get_thread_data()->wait_fd[1];
1091 req->debug_level = (TRACE_ON(server) != 0);
1092 req->cpu = client_cpu;
1093 ret = wine_server_call( req );
1094 NtCurrentTeb()->ClientId.UniqueProcess = ULongToHandle(reply->pid);
1095 NtCurrentTeb()->ClientId.UniqueThread = ULongToHandle(reply->tid);
1096 info_size = reply->info_size;
1097 server_start_time = reply->server_start;
1098 server_cpus = reply->all_cpus;
1102 is_wow64 = !is_win64 && (server_cpus & (1 << CPU_x86_64)) != 0;
1103 ntdll_get_thread_data()->wow64_redir = is_wow64;
1107 case STATUS_SUCCESS:
1110 if (!strcmp( arch, "win32" ) && (is_win64 || is_wow64))
1111 fatal_error( "WINEARCH set to win32 but '%s' is a 64-bit installation.\n",
1112 wine_get_config_dir() );
1113 if (!strcmp( arch, "win64" ) && !is_wow64)
1114 fatal_error( "WINEARCH set to win64 but '%s' is a 32-bit installation.\n",
1115 wine_get_config_dir() );
1118 case STATUS_NOT_REGISTRY_FILE:
1119 fatal_error( "'%s' is a 32-bit installation, it cannot support 64-bit applications.\n",
1120 wine_get_config_dir() );
1121 case STATUS_NOT_SUPPORTED:
1123 fatal_error( "wineserver is 32-bit, it cannot support 64-bit applications.\n" );
1125 fatal_error( "'%s' is a 64-bit installation, it cannot be used with a 32-bit wineserver.\n",
1126 wine_get_config_dir() );
1128 server_protocol_error( "init_thread failed with status %x\n", ret );