push cc8bc80451cc24f4d7cf75168b569f0ebfe19547
[wine/hacks.git] / dlls / ntdll / server.c
bloba7bc49392fd2a20cee5c1e64ca2208ddd6c84014
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 #include <signal.h>
32 #include <stdarg.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <sys/types.h>
36 #ifdef HAVE_SYS_SOCKET_H
37 # include <sys/socket.h>
38 #endif
39 #ifdef HAVE_SYS_WAIT_H
40 #include <sys/wait.h>
41 #endif
42 #ifdef HAVE_SYS_UN_H
43 #include <sys/un.h>
44 #endif
45 #ifdef HAVE_SYS_MMAN_H
46 #include <sys/mman.h>
47 #endif
48 #ifdef HAVE_SYS_STAT_H
49 # include <sys/stat.h>
50 #endif
51 #ifdef HAVE_SYS_UIO_H
52 #include <sys/uio.h>
53 #endif
54 #ifdef HAVE_SYS_THR_H
55 #include <sys/ucontext.h>
56 #include <sys/thr.h>
57 #endif
58 #ifdef HAVE_UNISTD_H
59 # include <unistd.h>
60 #endif
62 #include "ntstatus.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 */
72 #ifndef SCM_RIGHTS
73 #define SCM_RIGHTS 1
74 #endif
76 #define SOCKETNAME "socket" /* name of the socket file */
77 #define LOCKNAME "lock" /* name of the lock file */
79 #ifdef __i386__
80 static const enum cpu_type client_cpu = CPU_x86;
81 #elif defined(__x86_64__)
82 static const enum cpu_type client_cpu = CPU_x86_64;
83 #elif defined(__ALPHA__)
84 static const enum cpu_type client_cpu = CPU_ALPHA;
85 #elif defined(__powerpc__)
86 static const enum cpu_type client_cpu = CPU_POWERPC;
87 #elif defined(__sparc__)
88 static const enum cpu_type client_cpu = CPU_SPARC;
89 #else
90 #error Unsupported CPU
91 #endif
93 unsigned int server_cpus = 0;
95 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
96 /* data structure used to pass an fd with sendmsg/recvmsg */
97 struct cmsg_fd
99 struct
101 size_t len; /* size of structure */
102 int level; /* SOL_SOCKET */
103 int type; /* SCM_RIGHTS */
104 } header;
105 int fd; /* fd to pass */
107 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
109 timeout_t server_start_time = 0; /* time of server startup */
111 sigset_t server_block_set; /* signals to block during server calls */
112 static int fd_socket = -1; /* socket to exchange file descriptors with the server */
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 };
124 #ifdef __GNUC__
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));
128 #endif
130 /* die on a fatal error; use only during initialization */
131 static void fatal_error( const char *err, ... )
133 va_list args;
135 va_start( args, err );
136 fprintf( stderr, "wine: " );
137 vfprintf( stderr, err, args );
138 va_end( args );
139 exit(1);
142 /* die on a fatal error; use only during initialization */
143 static void fatal_perror( const char *err, ... )
145 va_list args;
147 va_start( args, err );
148 fprintf( stderr, "wine: " );
149 vfprintf( stderr, err, args );
150 perror( " " );
151 va_end( args );
152 exit(1);
156 /***********************************************************************
157 * server_protocol_error
159 void server_protocol_error( const char *err, ... )
161 va_list args;
163 va_start( args, err );
164 fprintf( stderr, "wine client error:%x: ", GetCurrentThreadId() );
165 vfprintf( stderr, err, args );
166 va_end( args );
167 abort_thread(1);
171 /***********************************************************************
172 * server_protocol_perror
174 void server_protocol_perror( const char *err )
176 fprintf( stderr, "wine client error:%x: ", GetCurrentThreadId() );
177 perror( err );
178 abort_thread(1);
182 /***********************************************************************
183 * send_request
185 * Send a request to the server.
187 static unsigned int send_request( const struct __server_request_info *req )
189 unsigned int i;
190 int ret;
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;
198 else
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 /***********************************************************************
221 * read_reply_data
223 * Read data from the reply buffer; helper for wait_reply.
225 static void read_reply_data( void *buffer, size_t size )
227 int ret;
229 for (;;)
231 if ((ret = read( ntdll_get_thread_data()->reply_fd, buffer, size )) > 0)
233 if (!(size -= ret)) return;
234 buffer = (char *)buffer + ret;
235 continue;
237 if (!ret) break;
238 if (errno == EINTR) continue;
239 if (errno == EPIPE) break;
240 server_protocol_perror("read");
242 /* the server closed the connection; time to die... */
243 abort_thread(0);
247 /***********************************************************************
248 * wait_reply
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.
266 * PARAMS
267 * req_ptr [I/O] Function dependent data
269 * RETURNS
270 * Depends on server function being called, but usually an NTSTATUS code.
272 * NOTES
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 )
276 *| {
277 *| req->handle = handle;
278 *| req->op = SET_EVENT;
279 *| ret = wine_server_call( req );
280 *| }
281 *| SERVER_END_REQ;
283 unsigned int wine_server_call( void *req_ptr )
285 struct __server_request_info * const req = req_ptr;
286 sigset_t old_set;
287 unsigned int ret;
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 );
293 return ret;
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.
322 * PARAMS
323 * fd [I] file descriptor to send
325 * RETURNS
326 * nothing
328 void CDECL wine_server_send_fd( int fd )
330 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
331 struct cmsg_fd cmsg;
332 #endif
333 struct send_fd data;
334 struct msghdr msghdr;
335 struct iovec vec;
336 int ret;
338 vec.iov_base = (void *)&data;
339 vec.iov_len = sizeof(data);
341 msghdr.msg_name = NULL;
342 msghdr.msg_namelen = 0;
343 msghdr.msg_iov = &vec;
344 msghdr.msg_iovlen = 1;
346 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
347 msghdr.msg_accrights = (void *)&fd;
348 msghdr.msg_accrightslen = sizeof(fd);
349 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
350 cmsg.header.len = sizeof(cmsg.header) + sizeof(fd);
351 cmsg.header.level = SOL_SOCKET;
352 cmsg.header.type = SCM_RIGHTS;
353 cmsg.fd = fd;
354 msghdr.msg_control = &cmsg;
355 msghdr.msg_controllen = sizeof(cmsg.header) + sizeof(fd);
356 msghdr.msg_flags = 0;
357 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
359 data.tid = GetCurrentThreadId();
360 data.fd = fd;
362 for (;;)
364 if ((ret = sendmsg( fd_socket, &msghdr, 0 )) == sizeof(data)) return;
365 if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
366 if (errno == EINTR) continue;
367 if (errno == EPIPE) abort_thread(0);
368 server_protocol_perror( "sendmsg" );
373 /***********************************************************************
374 * receive_fd
376 * Receive a file descriptor passed from the server.
378 static int receive_fd( obj_handle_t *handle )
380 struct iovec vec;
381 int ret, fd;
383 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
384 struct msghdr msghdr;
386 fd = -1;
387 msghdr.msg_accrights = (void *)&fd;
388 msghdr.msg_accrightslen = sizeof(fd);
389 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
390 struct msghdr msghdr;
391 struct cmsg_fd cmsg;
393 cmsg.header.len = sizeof(cmsg.header) + sizeof(fd);
394 cmsg.header.level = SOL_SOCKET;
395 cmsg.header.type = SCM_RIGHTS;
396 cmsg.fd = -1;
397 msghdr.msg_control = &cmsg;
398 msghdr.msg_controllen = sizeof(cmsg.header) + sizeof(fd);
399 msghdr.msg_flags = 0;
400 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
402 msghdr.msg_name = NULL;
403 msghdr.msg_namelen = 0;
404 msghdr.msg_iov = &vec;
405 msghdr.msg_iovlen = 1;
406 vec.iov_base = (void *)handle;
407 vec.iov_len = sizeof(*handle);
409 for (;;)
411 if ((ret = recvmsg( fd_socket, &msghdr, 0 )) > 0)
413 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
414 fd = cmsg.fd;
415 #endif
416 if (fd != -1) fcntl( fd, F_SETFD, 1 ); /* set close on exec flag */
417 return fd;
419 if (!ret) break;
420 if (errno == EINTR) continue;
421 if (errno == EPIPE) break;
422 server_protocol_perror("recvmsg");
424 /* the server closed the connection; time to die... */
425 abort_thread(0);
429 /***********************************************************************/
430 /* fd cache support */
432 struct fd_cache_entry
434 int fd;
435 enum server_fd_type type : 6;
436 unsigned int access : 2;
437 unsigned int options : 24;
440 #define FD_CACHE_BLOCK_SIZE (65536 / sizeof(struct fd_cache_entry))
441 #define FD_CACHE_ENTRIES 128
443 static struct fd_cache_entry *fd_cache[FD_CACHE_ENTRIES];
444 static struct fd_cache_entry fd_cache_initial_block[FD_CACHE_BLOCK_SIZE];
446 static inline unsigned int handle_to_index( HANDLE handle, unsigned int *entry )
448 unsigned int idx = (wine_server_obj_handle(handle) >> 2) - 1;
449 *entry = idx / FD_CACHE_BLOCK_SIZE;
450 return idx % FD_CACHE_BLOCK_SIZE;
454 /***********************************************************************
455 * add_fd_to_cache
457 * Caller must hold fd_cache_section.
459 static int add_fd_to_cache( HANDLE handle, int fd, enum server_fd_type type,
460 unsigned int access, unsigned int options )
462 unsigned int entry, idx = handle_to_index( handle, &entry );
463 int prev_fd;
465 if (entry >= FD_CACHE_ENTRIES)
467 FIXME( "too many allocated handles, not caching %p\n", handle );
468 return 0;
471 if (!fd_cache[entry]) /* do we need to allocate a new block of entries? */
473 if (!entry) fd_cache[0] = fd_cache_initial_block;
474 else
476 void *ptr = wine_anon_mmap( NULL, FD_CACHE_BLOCK_SIZE * sizeof(struct fd_cache_entry),
477 PROT_READ | PROT_WRITE, 0 );
478 if (ptr == MAP_FAILED) return 0;
479 fd_cache[entry] = ptr;
482 /* store fd+1 so that 0 can be used as the unset value */
483 prev_fd = interlocked_xchg( &fd_cache[entry][idx].fd, fd + 1 ) - 1;
484 fd_cache[entry][idx].type = type;
485 fd_cache[entry][idx].access = access;
486 fd_cache[entry][idx].options = options;
487 if (prev_fd != -1) close( prev_fd );
488 return 1;
492 /***********************************************************************
493 * get_cached_fd
495 * Caller must hold fd_cache_section.
497 static inline int get_cached_fd( HANDLE handle, enum server_fd_type *type,
498 unsigned int *access, unsigned int *options )
500 unsigned int entry, idx = handle_to_index( handle, &entry );
501 int fd = -1;
503 if (entry < FD_CACHE_ENTRIES && fd_cache[entry])
505 fd = fd_cache[entry][idx].fd - 1;
506 if (type) *type = fd_cache[entry][idx].type;
507 if (access) *access = fd_cache[entry][idx].access;
508 if (options) *options = fd_cache[entry][idx].options;
510 return fd;
514 /***********************************************************************
515 * server_remove_fd_from_cache
517 int server_remove_fd_from_cache( HANDLE handle )
519 unsigned int entry, idx = handle_to_index( handle, &entry );
520 int fd = -1;
522 if (entry < FD_CACHE_ENTRIES && fd_cache[entry])
523 fd = interlocked_xchg( &fd_cache[entry][idx].fd, 0 ) - 1;
525 return fd;
529 /***********************************************************************
530 * server_get_unix_fd
532 * The returned unix_fd should be closed iff needs_close is non-zero.
534 int server_get_unix_fd( HANDLE handle, unsigned int wanted_access, int *unix_fd,
535 int *needs_close, enum server_fd_type *type, unsigned int *options )
537 sigset_t sigset;
538 obj_handle_t fd_handle;
539 int ret = 0, fd;
540 unsigned int access = 0;
542 *unix_fd = -1;
543 *needs_close = 0;
544 wanted_access &= FILE_READ_DATA | FILE_WRITE_DATA;
546 server_enter_uninterrupted_section( &fd_cache_section, &sigset );
548 fd = get_cached_fd( handle, type, &access, options );
549 if (fd != -1) goto done;
551 SERVER_START_REQ( get_handle_fd )
553 req->handle = wine_server_obj_handle( handle );
554 if (!(ret = wine_server_call( req )))
556 if (type) *type = reply->type;
557 if (options) *options = reply->options;
558 access = reply->access;
559 if ((fd = receive_fd( &fd_handle )) != -1)
561 assert( wine_server_ptr_handle(fd_handle) == handle );
562 *needs_close = (reply->removable ||
563 !add_fd_to_cache( handle, fd, reply->type,
564 reply->access, reply->options ));
566 else ret = STATUS_TOO_MANY_OPENED_FILES;
569 SERVER_END_REQ;
571 done:
572 server_leave_uninterrupted_section( &fd_cache_section, &sigset );
573 if (!ret && ((access & wanted_access) != wanted_access))
575 ret = STATUS_ACCESS_DENIED;
576 if (*needs_close) close( fd );
578 if (!ret) *unix_fd = fd;
579 return ret;
583 /***********************************************************************
584 * wine_server_fd_to_handle (NTDLL.@)
586 * Allocate a file handle for a Unix file descriptor.
588 * PARAMS
589 * fd [I] Unix file descriptor.
590 * access [I] Win32 access flags.
591 * attributes [I] Object attributes.
592 * handle [O] Address where Wine file handle will be stored.
594 * RETURNS
595 * NTSTATUS code
597 int CDECL wine_server_fd_to_handle( int fd, unsigned int access, unsigned int attributes, HANDLE *handle )
599 int ret;
601 *handle = 0;
602 wine_server_send_fd( fd );
604 SERVER_START_REQ( alloc_file_handle )
606 req->access = access;
607 req->attributes = attributes;
608 req->fd = fd;
609 if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
611 SERVER_END_REQ;
612 return ret;
616 /***********************************************************************
617 * wine_server_handle_to_fd (NTDLL.@)
619 * Retrieve the file descriptor corresponding to a file handle.
621 * PARAMS
622 * handle [I] Wine file handle.
623 * access [I] Win32 file access rights requested.
624 * unix_fd [O] Address where Unix file descriptor will be stored.
625 * options [O] Address where the file open options will be stored. Optional.
627 * RETURNS
628 * NTSTATUS code
630 int CDECL wine_server_handle_to_fd( HANDLE handle, unsigned int access, int *unix_fd,
631 unsigned int *options )
633 int needs_close, ret = server_get_unix_fd( handle, access, unix_fd, &needs_close, NULL, options );
635 if (!ret && !needs_close)
637 if ((*unix_fd = dup(*unix_fd)) == -1) ret = FILE_GetNtStatus();
639 return ret;
643 /***********************************************************************
644 * wine_server_release_fd (NTDLL.@)
646 * Release the Unix file descriptor returned by wine_server_handle_to_fd.
648 * PARAMS
649 * handle [I] Wine file handle.
650 * unix_fd [I] Unix file descriptor to release.
652 * RETURNS
653 * nothing
655 void CDECL wine_server_release_fd( HANDLE handle, int unix_fd )
657 close( unix_fd );
661 /***********************************************************************
662 * start_server
664 * Start a new wine server.
666 static void start_server(void)
668 static int started; /* we only try once */
669 char *argv[3];
670 static char wineserver[] = "server/wineserver";
671 static char debug[] = "-d";
673 if (!started)
675 int status;
676 int pid = fork();
677 if (pid == -1) fatal_perror( "fork" );
678 if (!pid)
680 argv[0] = wineserver;
681 argv[1] = TRACE_ON(server) ? debug : NULL;
682 argv[2] = NULL;
683 wine_exec_wine_binary( argv[0], argv, getenv("WINESERVER") );
684 fatal_error( "could not exec wineserver\n" );
686 waitpid( pid, &status, 0 );
687 status = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
688 if (status == 2) return; /* server lock held by someone else, will retry later */
689 if (status) exit(status); /* server failed */
690 started = 1;
695 /***********************************************************************
696 * setup_config_dir
698 * Setup the wine configuration dir.
700 static void setup_config_dir(void)
702 const char *p, *config_dir = wine_get_config_dir();
704 if (chdir( config_dir ) == -1)
706 if (errno != ENOENT) fatal_perror( "chdir to %s\n", config_dir );
708 if ((p = strrchr( config_dir, '/' )) && p != config_dir)
710 struct stat st;
711 char *tmp_dir;
713 if (!(tmp_dir = malloc( p + 1 - config_dir ))) fatal_error( "out of memory\n" );
714 memcpy( tmp_dir, config_dir, p - config_dir );
715 tmp_dir[p - config_dir] = 0;
716 if (!stat( tmp_dir, &st ) && st.st_uid != getuid())
717 fatal_error( "'%s' is not owned by you, refusing to create a configuration directory there\n",
718 tmp_dir );
719 free( tmp_dir );
722 mkdir( config_dir, 0777 );
723 if (chdir( config_dir ) == -1) fatal_perror( "chdir to %s\n", config_dir );
724 MESSAGE( "wine: created the configuration directory '%s'\n", config_dir );
727 if (mkdir( "dosdevices", 0777 ) == -1)
729 if (errno == EEXIST) return;
730 fatal_perror( "cannot create %s/dosdevices\n", config_dir );
733 /* create the drive symlinks */
735 mkdir( "drive_c", 0777 );
736 symlink( "../drive_c", "dosdevices/c:" );
737 symlink( "/", "dosdevices/z:" );
741 /***********************************************************************
742 * server_connect_error
744 * Try to display a meaningful explanation of why we couldn't connect
745 * to the server.
747 static void server_connect_error( const char *serverdir )
749 int fd;
750 struct flock fl;
752 if ((fd = open( LOCKNAME, O_WRONLY )) == -1)
753 fatal_error( "for some mysterious reason, the wine server never started.\n" );
755 fl.l_type = F_WRLCK;
756 fl.l_whence = SEEK_SET;
757 fl.l_start = 0;
758 fl.l_len = 1;
759 if (fcntl( fd, F_GETLK, &fl ) != -1)
761 if (fl.l_type == F_WRLCK) /* the file is locked */
762 fatal_error( "a wine server seems to be running, but I cannot connect to it.\n"
763 " You probably need to kill that process (it might be pid %d).\n",
764 (int)fl.l_pid );
765 fatal_error( "for some mysterious reason, the wine server failed to run.\n" );
767 fatal_error( "the file system of '%s' doesn't support locks,\n"
768 " and there is a 'socket' file in that directory that prevents wine from starting.\n"
769 " You should make sure no wine server is running, remove that file and try again.\n",
770 serverdir );
774 /***********************************************************************
775 * server_connect
777 * Attempt to connect to an existing server socket.
778 * We need to be in the server directory already.
780 static int server_connect(void)
782 const char *serverdir;
783 struct sockaddr_un addr;
784 struct stat st;
785 int s, slen, retry, fd_cwd;
787 /* retrieve the current directory */
788 fd_cwd = open( ".", O_RDONLY );
789 if (fd_cwd != -1) fcntl( fd_cwd, F_SETFD, 1 ); /* set close on exec flag */
791 setup_config_dir();
792 serverdir = wine_get_server_dir();
794 /* chdir to the server directory */
795 if (chdir( serverdir ) == -1)
797 if (errno != ENOENT) fatal_perror( "chdir to %s", serverdir );
798 start_server();
799 if (chdir( serverdir ) == -1) fatal_perror( "chdir to %s", serverdir );
802 /* make sure we are at the right place */
803 if (stat( ".", &st ) == -1) fatal_perror( "stat %s", serverdir );
804 if (st.st_uid != getuid()) fatal_error( "'%s' is not owned by you\n", serverdir );
805 if (st.st_mode & 077) fatal_error( "'%s' must not be accessible by other users\n", serverdir );
807 for (retry = 0; retry < 6; retry++)
809 /* if not the first try, wait a bit to leave the previous server time to exit */
810 if (retry)
812 usleep( 100000 * retry * retry );
813 start_server();
814 if (lstat( SOCKETNAME, &st ) == -1) continue; /* still no socket, wait a bit more */
816 else if (lstat( SOCKETNAME, &st ) == -1) /* check for an already existing socket */
818 if (errno != ENOENT) fatal_perror( "lstat %s/%s", serverdir, SOCKETNAME );
819 start_server();
820 if (lstat( SOCKETNAME, &st ) == -1) continue; /* still no socket, wait a bit more */
823 /* make sure the socket is sane (ISFIFO needed for Solaris) */
824 if (!S_ISSOCK(st.st_mode) && !S_ISFIFO(st.st_mode))
825 fatal_error( "'%s/%s' is not a socket\n", serverdir, SOCKETNAME );
826 if (st.st_uid != getuid())
827 fatal_error( "'%s/%s' is not owned by you\n", serverdir, SOCKETNAME );
829 /* try to connect to it */
830 addr.sun_family = AF_UNIX;
831 strcpy( addr.sun_path, SOCKETNAME );
832 slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
833 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
834 addr.sun_len = slen;
835 #endif
836 if ((s = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_perror( "socket" );
837 if (connect( s, (struct sockaddr *)&addr, slen ) != -1)
839 /* switch back to the starting directory */
840 if (fd_cwd != -1)
842 fchdir( fd_cwd );
843 close( fd_cwd );
845 fcntl( s, F_SETFD, 1 ); /* set close on exec flag */
846 return s;
848 close( s );
850 server_connect_error( serverdir );
854 #ifdef __APPLE__
855 #include <mach/mach.h>
856 #include <mach/mach_error.h>
857 #include <servers/bootstrap.h>
859 /* send our task port to the server */
860 static void send_server_task_port(void)
862 mach_port_t bootstrap_port, wineserver_port;
863 kern_return_t kret;
865 struct {
866 mach_msg_header_t header;
867 mach_msg_body_t body;
868 mach_msg_port_descriptor_t task_port;
869 } msg;
871 if (task_get_bootstrap_port(mach_task_self(), &bootstrap_port) != KERN_SUCCESS) return;
873 kret = bootstrap_look_up(bootstrap_port, (char*)wine_get_server_dir(), &wineserver_port);
874 if (kret != KERN_SUCCESS)
875 fatal_error( "cannot find the server port: 0x%08x\n", kret );
877 mach_port_deallocate(mach_task_self(), bootstrap_port);
879 msg.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0) | MACH_MSGH_BITS_COMPLEX;
880 msg.header.msgh_size = sizeof(msg);
881 msg.header.msgh_remote_port = wineserver_port;
882 msg.header.msgh_local_port = MACH_PORT_NULL;
884 msg.body.msgh_descriptor_count = 1;
885 msg.task_port.name = mach_task_self();
886 msg.task_port.disposition = MACH_MSG_TYPE_COPY_SEND;
887 msg.task_port.type = MACH_MSG_PORT_DESCRIPTOR;
889 kret = mach_msg_send(&msg.header);
890 if (kret != KERN_SUCCESS)
891 server_protocol_error( "mach_msg_send failed: 0x%08x\n", kret );
893 mach_port_deallocate(mach_task_self(), wineserver_port);
895 #endif /* __APPLE__ */
898 /***********************************************************************
899 * get_unix_tid
901 * Retrieve the Unix tid to use on the server side for the current thread.
903 static int get_unix_tid(void)
905 int ret = -1;
906 #if defined(linux) && defined(__i386__)
907 __asm__("int $0x80" : "=a" (ret) : "0" (224) /* SYS_gettid */);
908 #elif defined(linux) && defined(__x86_64__)
909 __asm__("syscall" : "=a" (ret) : "0" (186) /* SYS_gettid */);
910 #elif defined(__sun)
911 ret = pthread_self();
912 #elif defined(__APPLE__)
913 ret = mach_thread_self();
914 #elif defined(__FreeBSD__)
915 long lwpid;
916 thr_self( &lwpid );
917 ret = lwpid;
918 #endif
919 return ret;
923 /***********************************************************************
924 * server_init_process
926 * Start the server and create the initial socket pair.
928 void server_init_process(void)
930 obj_handle_t version;
931 const char *env_socket = getenv( "WINESERVERSOCKET" );
933 if (env_socket)
935 fd_socket = atoi( env_socket );
936 if (fcntl( fd_socket, F_SETFD, 1 ) == -1)
937 fatal_perror( "Bad server socket %d", fd_socket );
938 unsetenv( "WINESERVERSOCKET" );
940 else fd_socket = server_connect();
942 /* setup the signal mask */
943 sigemptyset( &server_block_set );
944 sigaddset( &server_block_set, SIGALRM );
945 sigaddset( &server_block_set, SIGIO );
946 sigaddset( &server_block_set, SIGINT );
947 sigaddset( &server_block_set, SIGHUP );
948 sigaddset( &server_block_set, SIGUSR1 );
949 sigaddset( &server_block_set, SIGUSR2 );
950 sigaddset( &server_block_set, SIGCHLD );
951 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
953 /* receive the first thread request fd on the main socket */
954 ntdll_get_thread_data()->request_fd = receive_fd( &version );
956 if (version != SERVER_PROTOCOL_VERSION)
957 server_protocol_error( "version mismatch %d/%d.\n"
958 "Your %s binary was not upgraded correctly,\n"
959 "or you have an older one somewhere in your PATH.\n"
960 "Or maybe the wrong wineserver is still running?\n",
961 version, SERVER_PROTOCOL_VERSION,
962 (version > SERVER_PROTOCOL_VERSION) ? "wine" : "wineserver" );
963 #ifdef __APPLE__
964 send_server_task_port();
965 #endif
969 /***********************************************************************
970 * server_init_process_done
972 NTSTATUS server_init_process_done(void)
974 PEB *peb = NtCurrentTeb()->Peb;
975 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
976 NTSTATUS status;
978 /* Install signal handlers; this cannot be done earlier, since we cannot
979 * send exceptions to the debugger before the create process event that
980 * is sent by REQ_INIT_PROCESS_DONE.
981 * We do need the handlers in place by the time the request is over, so
982 * we set them up here. If we segfault between here and the server call
983 * something is very wrong... */
984 signal_init_process();
986 /* Signal the parent process to continue */
987 SERVER_START_REQ( init_process_done )
989 req->module = wine_server_client_ptr( peb->ImageBaseAddress );
990 #ifdef __i386__
991 req->ldt_copy = wine_server_client_ptr( &wine_ldt_copy );
992 #endif
993 req->entry = wine_server_client_ptr( (char *)peb->ImageBaseAddress + nt->OptionalHeader.AddressOfEntryPoint );
994 req->gui = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
995 status = wine_server_call( req );
997 SERVER_END_REQ;
999 return status;
1003 /***********************************************************************
1004 * server_init_thread
1006 * Send an init thread request. Return 0 if OK.
1008 size_t server_init_thread( void *entry_point )
1010 int ret;
1011 int reply_pipe[2];
1012 struct sigaction sig_act;
1013 size_t info_size;
1015 sig_act.sa_handler = SIG_IGN;
1016 sig_act.sa_flags = 0;
1017 sigemptyset( &sig_act.sa_mask );
1019 /* ignore SIGPIPE so that we get an EPIPE error instead */
1020 sigaction( SIGPIPE, &sig_act, NULL );
1021 /* automatic child reaping to avoid zombies */
1022 #ifdef SA_NOCLDWAIT
1023 sig_act.sa_flags |= SA_NOCLDWAIT;
1024 #endif
1025 sigaction( SIGCHLD, &sig_act, NULL );
1027 /* create the server->client communication pipes */
1028 if (pipe( reply_pipe ) == -1) server_protocol_perror( "pipe" );
1029 if (pipe( ntdll_get_thread_data()->wait_fd ) == -1) server_protocol_perror( "pipe" );
1030 wine_server_send_fd( reply_pipe[1] );
1031 wine_server_send_fd( ntdll_get_thread_data()->wait_fd[1] );
1032 ntdll_get_thread_data()->reply_fd = reply_pipe[0];
1033 close( reply_pipe[1] );
1035 /* set close on exec flag */
1036 fcntl( ntdll_get_thread_data()->reply_fd, F_SETFD, 1 );
1037 fcntl( ntdll_get_thread_data()->wait_fd[0], F_SETFD, 1 );
1038 fcntl( ntdll_get_thread_data()->wait_fd[1], F_SETFD, 1 );
1040 SERVER_START_REQ( init_thread )
1042 req->unix_pid = getpid();
1043 req->unix_tid = get_unix_tid();
1044 req->teb = wine_server_client_ptr( NtCurrentTeb() );
1045 req->entry = wine_server_client_ptr( entry_point );
1046 req->reply_fd = reply_pipe[1];
1047 req->wait_fd = ntdll_get_thread_data()->wait_fd[1];
1048 req->debug_level = (TRACE_ON(server) != 0);
1049 req->cpu = client_cpu;
1050 ret = wine_server_call( req );
1051 NtCurrentTeb()->ClientId.UniqueProcess = ULongToHandle(reply->pid);
1052 NtCurrentTeb()->ClientId.UniqueThread = ULongToHandle(reply->tid);
1053 info_size = reply->info_size;
1054 server_start_time = reply->server_start;
1055 server_cpus = reply->all_cpus;
1057 SERVER_END_REQ;
1059 if (ret)
1061 if (ret == STATUS_NOT_SUPPORTED)
1063 static const char * const cpu_arch[] = { "x86", "x86_64", "Alpha", "PowerPC", "Sparc" };
1064 server_protocol_error( "the running wineserver doesn't support the %s architecture.\n",
1065 cpu_arch[client_cpu] );
1067 else server_protocol_error( "init_thread failed with status %x\n", ret );
1069 return info_size;