ntdll/tests: Create the server port before starting the client thread.
[wine/multimedia.git] / dlls / ntdll / server.c
blobd16a248b3091311ad5f53328af1ce4dd2bbb96ab
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 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
80 /* data structure used to pass an fd with sendmsg/recvmsg */
81 struct cmsg_fd
83 struct
85 size_t len; /* size of structure */
86 int level; /* SOL_SOCKET */
87 int type; /* SCM_RIGHTS */
88 } header;
89 int fd; /* fd to pass */
91 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
93 timeout_t server_start_time = 0; /* time of server startup */
95 sigset_t server_block_set; /* signals to block during server calls */
96 static int fd_socket = -1; /* socket to exchange file descriptors with the server */
98 static RTL_CRITICAL_SECTION fd_cache_section;
99 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
101 0, 0, &fd_cache_section,
102 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
103 0, 0, { (DWORD_PTR)(__FILE__ ": fd_cache_section") }
105 static RTL_CRITICAL_SECTION fd_cache_section = { &critsect_debug, -1, 0, 0, 0, 0 };
108 #ifdef __GNUC__
109 static void fatal_error( const char *err, ... ) __attribute__((noreturn, format(printf,1,2)));
110 static void fatal_perror( const char *err, ... ) __attribute__((noreturn, format(printf,1,2)));
111 static void server_connect_error( const char *serverdir ) __attribute__((noreturn));
112 #endif
114 /* die on a fatal error; use only during initialization */
115 static void fatal_error( const char *err, ... )
117 va_list args;
119 va_start( args, err );
120 fprintf( stderr, "wine: " );
121 vfprintf( stderr, err, args );
122 va_end( args );
123 exit(1);
126 /* die on a fatal error; use only during initialization */
127 static void fatal_perror( const char *err, ... )
129 va_list args;
131 va_start( args, err );
132 fprintf( stderr, "wine: " );
133 vfprintf( stderr, err, args );
134 perror( " " );
135 va_end( args );
136 exit(1);
140 /***********************************************************************
141 * server_protocol_error
143 void server_protocol_error( const char *err, ... )
145 va_list args;
147 va_start( args, err );
148 fprintf( stderr, "wine client error:%x: ", GetCurrentThreadId() );
149 vfprintf( stderr, err, args );
150 va_end( args );
151 abort_thread(1);
155 /***********************************************************************
156 * server_protocol_perror
158 void server_protocol_perror( const char *err )
160 fprintf( stderr, "wine client error:%x: ", GetCurrentThreadId() );
161 perror( err );
162 abort_thread(1);
166 /***********************************************************************
167 * send_request
169 * Send a request to the server.
171 static unsigned int send_request( const struct __server_request_info *req )
173 unsigned int i;
174 int ret;
176 if (!req->u.req.request_header.request_size)
178 if ((ret = write( ntdll_get_thread_data()->request_fd, &req->u.req,
179 sizeof(req->u.req) )) == sizeof(req->u.req)) return STATUS_SUCCESS;
182 else
184 struct iovec vec[__SERVER_MAX_DATA+1];
186 vec[0].iov_base = (void *)&req->u.req;
187 vec[0].iov_len = sizeof(req->u.req);
188 for (i = 0; i < req->data_count; i++)
190 vec[i+1].iov_base = (void *)req->data[i].ptr;
191 vec[i+1].iov_len = req->data[i].size;
193 if ((ret = writev( ntdll_get_thread_data()->request_fd, vec, i+1 )) ==
194 req->u.req.request_header.request_size + sizeof(req->u.req)) return STATUS_SUCCESS;
197 if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
198 if (errno == EPIPE) abort_thread(0);
199 if (errno == EFAULT) return STATUS_ACCESS_VIOLATION;
200 server_protocol_perror( "write" );
204 /***********************************************************************
205 * read_reply_data
207 * Read data from the reply buffer; helper for wait_reply.
209 static void read_reply_data( void *buffer, size_t size )
211 int ret;
213 for (;;)
215 if ((ret = read( ntdll_get_thread_data()->reply_fd, buffer, size )) > 0)
217 if (!(size -= ret)) return;
218 buffer = (char *)buffer + ret;
219 continue;
221 if (!ret) break;
222 if (errno == EINTR) continue;
223 if (errno == EPIPE) break;
224 server_protocol_perror("read");
226 /* the server closed the connection; time to die... */
227 abort_thread(0);
231 /***********************************************************************
232 * wait_reply
234 * Wait for a reply from the server.
236 static inline unsigned int wait_reply( struct __server_request_info *req )
238 read_reply_data( &req->u.reply, sizeof(req->u.reply) );
239 if (req->u.reply.reply_header.reply_size)
240 read_reply_data( req->reply_data, req->u.reply.reply_header.reply_size );
241 return req->u.reply.reply_header.error;
245 /***********************************************************************
246 * wine_server_call (NTDLL.@)
248 * Perform a server call.
250 * PARAMS
251 * req_ptr [I/O] Function dependent data
253 * RETURNS
254 * Depends on server function being called, but usually an NTSTATUS code.
256 * NOTES
257 * Use the SERVER_START_REQ and SERVER_END_REQ to help you fill out the
258 * server request structure for the particular call. E.g:
259 *| SERVER_START_REQ( event_op )
260 *| {
261 *| req->handle = handle;
262 *| req->op = SET_EVENT;
263 *| ret = wine_server_call( req );
264 *| }
265 *| SERVER_END_REQ;
267 unsigned int wine_server_call( void *req_ptr )
269 struct __server_request_info * const req = req_ptr;
270 sigset_t old_set;
271 unsigned int ret;
273 pthread_sigmask( SIG_BLOCK, &server_block_set, &old_set );
274 ret = send_request( req );
275 if (!ret) ret = wait_reply( req );
276 pthread_sigmask( SIG_SETMASK, &old_set, NULL );
277 return ret;
281 /***********************************************************************
282 * server_enter_uninterrupted_section
284 void server_enter_uninterrupted_section( RTL_CRITICAL_SECTION *cs, sigset_t *sigset )
286 pthread_sigmask( SIG_BLOCK, &server_block_set, sigset );
287 RtlEnterCriticalSection( cs );
291 /***********************************************************************
292 * server_leave_uninterrupted_section
294 void server_leave_uninterrupted_section( RTL_CRITICAL_SECTION *cs, sigset_t *sigset )
296 RtlLeaveCriticalSection( cs );
297 pthread_sigmask( SIG_SETMASK, sigset, NULL );
301 /***********************************************************************
302 * wine_server_send_fd (NTDLL.@)
304 * Send a file descriptor to the server.
306 * PARAMS
307 * fd [I] file descriptor to send
309 * RETURNS
310 * nothing
312 void CDECL wine_server_send_fd( int fd )
314 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
315 struct cmsg_fd cmsg;
316 #endif
317 struct send_fd data;
318 struct msghdr msghdr;
319 struct iovec vec;
320 int ret;
322 vec.iov_base = (void *)&data;
323 vec.iov_len = sizeof(data);
325 msghdr.msg_name = NULL;
326 msghdr.msg_namelen = 0;
327 msghdr.msg_iov = &vec;
328 msghdr.msg_iovlen = 1;
330 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
331 msghdr.msg_accrights = (void *)&fd;
332 msghdr.msg_accrightslen = sizeof(fd);
333 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
334 cmsg.header.len = sizeof(cmsg.header) + sizeof(fd);
335 cmsg.header.level = SOL_SOCKET;
336 cmsg.header.type = SCM_RIGHTS;
337 cmsg.fd = fd;
338 msghdr.msg_control = &cmsg;
339 msghdr.msg_controllen = sizeof(cmsg.header) + sizeof(fd);
340 msghdr.msg_flags = 0;
341 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
343 data.tid = GetCurrentThreadId();
344 data.fd = fd;
346 for (;;)
348 if ((ret = sendmsg( fd_socket, &msghdr, 0 )) == sizeof(data)) return;
349 if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
350 if (errno == EINTR) continue;
351 if (errno == EPIPE) abort_thread(0);
352 server_protocol_perror( "sendmsg" );
357 /***********************************************************************
358 * receive_fd
360 * Receive a file descriptor passed from the server.
362 static int receive_fd( obj_handle_t *handle )
364 struct iovec vec;
365 int ret, fd;
367 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
368 struct msghdr msghdr;
370 fd = -1;
371 msghdr.msg_accrights = (void *)&fd;
372 msghdr.msg_accrightslen = sizeof(fd);
373 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
374 struct msghdr msghdr;
375 struct cmsg_fd cmsg;
377 cmsg.header.len = sizeof(cmsg.header) + sizeof(fd);
378 cmsg.header.level = SOL_SOCKET;
379 cmsg.header.type = SCM_RIGHTS;
380 cmsg.fd = -1;
381 msghdr.msg_control = &cmsg;
382 msghdr.msg_controllen = sizeof(cmsg.header) + sizeof(fd);
383 msghdr.msg_flags = 0;
384 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
386 msghdr.msg_name = NULL;
387 msghdr.msg_namelen = 0;
388 msghdr.msg_iov = &vec;
389 msghdr.msg_iovlen = 1;
390 vec.iov_base = (void *)handle;
391 vec.iov_len = sizeof(*handle);
393 for (;;)
395 if ((ret = recvmsg( fd_socket, &msghdr, 0 )) > 0)
397 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
398 fd = cmsg.fd;
399 #endif
400 if (fd != -1) fcntl( fd, F_SETFD, 1 ); /* set close on exec flag */
401 return fd;
403 if (!ret) break;
404 if (errno == EINTR) continue;
405 if (errno == EPIPE) break;
406 server_protocol_perror("recvmsg");
408 /* the server closed the connection; time to die... */
409 abort_thread(0);
413 /***********************************************************************/
414 /* fd cache support */
416 struct fd_cache_entry
418 int fd;
419 enum server_fd_type type : 6;
420 unsigned int access : 2;
421 unsigned int options : 24;
424 #define FD_CACHE_BLOCK_SIZE (65536 / sizeof(struct fd_cache_entry))
425 #define FD_CACHE_ENTRIES 128
427 static struct fd_cache_entry *fd_cache[FD_CACHE_ENTRIES];
428 static struct fd_cache_entry fd_cache_initial_block[FD_CACHE_BLOCK_SIZE];
430 static inline unsigned int handle_to_index( HANDLE handle, unsigned int *entry )
432 unsigned int idx = (wine_server_obj_handle(handle) >> 2) - 1;
433 *entry = idx / FD_CACHE_BLOCK_SIZE;
434 return idx % FD_CACHE_BLOCK_SIZE;
438 /***********************************************************************
439 * add_fd_to_cache
441 * Caller must hold fd_cache_section.
443 static int add_fd_to_cache( HANDLE handle, int fd, enum server_fd_type type,
444 unsigned int access, unsigned int options )
446 unsigned int entry, idx = handle_to_index( handle, &entry );
447 int prev_fd;
449 if (entry >= FD_CACHE_ENTRIES)
451 FIXME( "too many allocated handles, not caching %p\n", handle );
452 return 0;
455 if (!fd_cache[entry]) /* do we need to allocate a new block of entries? */
457 if (!entry) fd_cache[0] = fd_cache_initial_block;
458 else
460 void *ptr = wine_anon_mmap( NULL, FD_CACHE_BLOCK_SIZE * sizeof(struct fd_cache_entry),
461 PROT_READ | PROT_WRITE, 0 );
462 if (ptr == MAP_FAILED) return 0;
463 fd_cache[entry] = ptr;
466 /* store fd+1 so that 0 can be used as the unset value */
467 prev_fd = interlocked_xchg( &fd_cache[entry][idx].fd, fd + 1 ) - 1;
468 fd_cache[entry][idx].type = type;
469 fd_cache[entry][idx].access = access;
470 fd_cache[entry][idx].options = options;
471 if (prev_fd != -1) close( prev_fd );
472 return 1;
476 /***********************************************************************
477 * get_cached_fd
479 * Caller must hold fd_cache_section.
481 static inline int get_cached_fd( HANDLE handle, enum server_fd_type *type,
482 unsigned int *access, unsigned int *options )
484 unsigned int entry, idx = handle_to_index( handle, &entry );
485 int fd = -1;
487 if (entry < FD_CACHE_ENTRIES && fd_cache[entry])
489 fd = fd_cache[entry][idx].fd - 1;
490 if (type) *type = fd_cache[entry][idx].type;
491 if (access) *access = fd_cache[entry][idx].access;
492 if (options) *options = fd_cache[entry][idx].options;
494 return fd;
498 /***********************************************************************
499 * server_remove_fd_from_cache
501 int server_remove_fd_from_cache( HANDLE handle )
503 unsigned int entry, idx = handle_to_index( handle, &entry );
504 int fd = -1;
506 if (entry < FD_CACHE_ENTRIES && fd_cache[entry])
507 fd = interlocked_xchg( &fd_cache[entry][idx].fd, 0 ) - 1;
509 return fd;
513 /***********************************************************************
514 * server_get_unix_fd
516 * The returned unix_fd should be closed iff needs_close is non-zero.
518 int server_get_unix_fd( HANDLE handle, unsigned int wanted_access, int *unix_fd,
519 int *needs_close, enum server_fd_type *type, unsigned int *options )
521 sigset_t sigset;
522 obj_handle_t fd_handle;
523 int ret = 0, fd;
524 unsigned int access = 0;
526 *unix_fd = -1;
527 *needs_close = 0;
528 wanted_access &= FILE_READ_DATA | FILE_WRITE_DATA;
530 server_enter_uninterrupted_section( &fd_cache_section, &sigset );
532 fd = get_cached_fd( handle, type, &access, options );
533 if (fd != -1) goto done;
535 SERVER_START_REQ( get_handle_fd )
537 req->handle = wine_server_obj_handle( handle );
538 if (!(ret = wine_server_call( req )))
540 if (type) *type = reply->type;
541 if (options) *options = reply->options;
542 access = reply->access;
543 if ((fd = receive_fd( &fd_handle )) != -1)
545 assert( wine_server_ptr_handle(fd_handle) == handle );
546 *needs_close = (reply->removable ||
547 !add_fd_to_cache( handle, fd, reply->type,
548 reply->access, reply->options ));
550 else ret = STATUS_TOO_MANY_OPENED_FILES;
553 SERVER_END_REQ;
555 done:
556 server_leave_uninterrupted_section( &fd_cache_section, &sigset );
557 if (!ret && ((access & wanted_access) != wanted_access))
559 ret = STATUS_ACCESS_DENIED;
560 if (*needs_close) close( fd );
562 if (!ret) *unix_fd = fd;
563 return ret;
567 /***********************************************************************
568 * wine_server_fd_to_handle (NTDLL.@)
570 * Allocate a file handle for a Unix file descriptor.
572 * PARAMS
573 * fd [I] Unix file descriptor.
574 * access [I] Win32 access flags.
575 * attributes [I] Object attributes.
576 * handle [O] Address where Wine file handle will be stored.
578 * RETURNS
579 * NTSTATUS code
581 int CDECL wine_server_fd_to_handle( int fd, unsigned int access, unsigned int attributes, HANDLE *handle )
583 int ret;
585 *handle = 0;
586 wine_server_send_fd( fd );
588 SERVER_START_REQ( alloc_file_handle )
590 req->access = access;
591 req->attributes = attributes;
592 req->fd = fd;
593 if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
595 SERVER_END_REQ;
596 return ret;
600 /***********************************************************************
601 * wine_server_handle_to_fd (NTDLL.@)
603 * Retrieve the file descriptor corresponding to a file handle.
605 * PARAMS
606 * handle [I] Wine file handle.
607 * access [I] Win32 file access rights requested.
608 * unix_fd [O] Address where Unix file descriptor will be stored.
609 * options [O] Address where the file open options will be stored. Optional.
611 * RETURNS
612 * NTSTATUS code
614 int CDECL wine_server_handle_to_fd( HANDLE handle, unsigned int access, int *unix_fd,
615 unsigned int *options )
617 int needs_close, ret = server_get_unix_fd( handle, access, unix_fd, &needs_close, NULL, options );
619 if (!ret && !needs_close)
621 if ((*unix_fd = dup(*unix_fd)) == -1) ret = FILE_GetNtStatus();
623 return ret;
627 /***********************************************************************
628 * wine_server_release_fd (NTDLL.@)
630 * Release the Unix file descriptor returned by wine_server_handle_to_fd.
632 * PARAMS
633 * handle [I] Wine file handle.
634 * unix_fd [I] Unix file descriptor to release.
636 * RETURNS
637 * nothing
639 void CDECL wine_server_release_fd( HANDLE handle, int unix_fd )
641 close( unix_fd );
645 /***********************************************************************
646 * start_server
648 * Start a new wine server.
650 static void start_server(void)
652 static int started; /* we only try once */
653 char *argv[3];
654 static char wineserver[] = "server/wineserver";
655 static char debug[] = "-d";
657 if (!started)
659 int status;
660 int pid = fork();
661 if (pid == -1) fatal_perror( "fork" );
662 if (!pid)
664 argv[0] = wineserver;
665 argv[1] = TRACE_ON(server) ? debug : NULL;
666 argv[2] = NULL;
667 wine_exec_wine_binary( argv[0], argv, getenv("WINESERVER") );
668 fatal_error( "could not exec wineserver\n" );
670 waitpid( pid, &status, 0 );
671 status = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
672 if (status == 2) return; /* server lock held by someone else, will retry later */
673 if (status) exit(status); /* server failed */
674 started = 1;
679 /***********************************************************************
680 * setup_config_dir
682 * Setup the wine configuration dir.
684 static void setup_config_dir(void)
686 const char *p, *config_dir = wine_get_config_dir();
688 if (chdir( config_dir ) == -1)
690 if (errno != ENOENT) fatal_perror( "chdir to %s\n", config_dir );
692 if ((p = strrchr( config_dir, '/' )) && p != config_dir)
694 struct stat st;
695 char *tmp_dir;
697 if (!(tmp_dir = malloc( p + 1 - config_dir ))) fatal_error( "out of memory\n" );
698 memcpy( tmp_dir, config_dir, p - config_dir );
699 tmp_dir[p - config_dir] = 0;
700 if (!stat( tmp_dir, &st ) && st.st_uid != getuid())
701 fatal_error( "'%s' is not owned by you, refusing to create a configuration directory there\n",
702 tmp_dir );
703 free( tmp_dir );
706 mkdir( config_dir, 0777 );
707 if (chdir( config_dir ) == -1) fatal_perror( "chdir to %s\n", config_dir );
708 MESSAGE( "wine: created the configuration directory '%s'\n", config_dir );
711 if (mkdir( "dosdevices", 0777 ) == -1)
713 if (errno == EEXIST) return;
714 fatal_perror( "cannot create %s/dosdevices\n", config_dir );
717 /* create the drive symlinks */
719 mkdir( "drive_c", 0777 );
720 symlink( "../drive_c", "dosdevices/c:" );
721 symlink( "/", "dosdevices/z:" );
725 /***********************************************************************
726 * server_connect_error
728 * Try to display a meaningful explanation of why we couldn't connect
729 * to the server.
731 static void server_connect_error( const char *serverdir )
733 int fd;
734 struct flock fl;
736 if ((fd = open( LOCKNAME, O_WRONLY )) == -1)
737 fatal_error( "for some mysterious reason, the wine server never started.\n" );
739 fl.l_type = F_WRLCK;
740 fl.l_whence = SEEK_SET;
741 fl.l_start = 0;
742 fl.l_len = 1;
743 if (fcntl( fd, F_GETLK, &fl ) != -1)
745 if (fl.l_type == F_WRLCK) /* the file is locked */
746 fatal_error( "a wine server seems to be running, but I cannot connect to it.\n"
747 " You probably need to kill that process (it might be pid %d).\n",
748 (int)fl.l_pid );
749 fatal_error( "for some mysterious reason, the wine server failed to run.\n" );
751 fatal_error( "the file system of '%s' doesn't support locks,\n"
752 " and there is a 'socket' file in that directory that prevents wine from starting.\n"
753 " You should make sure no wine server is running, remove that file and try again.\n",
754 serverdir );
758 /***********************************************************************
759 * server_connect
761 * Attempt to connect to an existing server socket.
762 * We need to be in the server directory already.
764 static int server_connect(void)
766 const char *serverdir;
767 struct sockaddr_un addr;
768 struct stat st;
769 int s, slen, retry, fd_cwd;
771 /* retrieve the current directory */
772 fd_cwd = open( ".", O_RDONLY );
773 if (fd_cwd != -1) fcntl( fd_cwd, F_SETFD, 1 ); /* set close on exec flag */
775 setup_config_dir();
776 serverdir = wine_get_server_dir();
778 /* chdir to the server directory */
779 if (chdir( serverdir ) == -1)
781 if (errno != ENOENT) fatal_perror( "chdir to %s", serverdir );
782 start_server();
783 if (chdir( serverdir ) == -1) fatal_perror( "chdir to %s", serverdir );
786 /* make sure we are at the right place */
787 if (stat( ".", &st ) == -1) fatal_perror( "stat %s", serverdir );
788 if (st.st_uid != getuid()) fatal_error( "'%s' is not owned by you\n", serverdir );
789 if (st.st_mode & 077) fatal_error( "'%s' must not be accessible by other users\n", serverdir );
791 for (retry = 0; retry < 6; retry++)
793 /* if not the first try, wait a bit to leave the previous server time to exit */
794 if (retry)
796 usleep( 100000 * retry * retry );
797 start_server();
798 if (lstat( SOCKETNAME, &st ) == -1) continue; /* still no socket, wait a bit more */
800 else if (lstat( SOCKETNAME, &st ) == -1) /* check for an already existing socket */
802 if (errno != ENOENT) fatal_perror( "lstat %s/%s", serverdir, SOCKETNAME );
803 start_server();
804 if (lstat( SOCKETNAME, &st ) == -1) continue; /* still no socket, wait a bit more */
807 /* make sure the socket is sane (ISFIFO needed for Solaris) */
808 if (!S_ISSOCK(st.st_mode) && !S_ISFIFO(st.st_mode))
809 fatal_error( "'%s/%s' is not a socket\n", serverdir, SOCKETNAME );
810 if (st.st_uid != getuid())
811 fatal_error( "'%s/%s' is not owned by you\n", serverdir, SOCKETNAME );
813 /* try to connect to it */
814 addr.sun_family = AF_UNIX;
815 strcpy( addr.sun_path, SOCKETNAME );
816 slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
817 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
818 addr.sun_len = slen;
819 #endif
820 if ((s = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_perror( "socket" );
821 if (connect( s, (struct sockaddr *)&addr, slen ) != -1)
823 /* switch back to the starting directory */
824 if (fd_cwd != -1)
826 fchdir( fd_cwd );
827 close( fd_cwd );
829 fcntl( s, F_SETFD, 1 ); /* set close on exec flag */
830 return s;
832 close( s );
834 server_connect_error( serverdir );
838 #ifdef __APPLE__
839 #include <mach/mach.h>
840 #include <mach/mach_error.h>
841 #include <servers/bootstrap.h>
843 /* send our task port to the server */
844 static void send_server_task_port(void)
846 mach_port_t bootstrap_port, wineserver_port;
847 kern_return_t kret;
849 struct {
850 mach_msg_header_t header;
851 mach_msg_body_t body;
852 mach_msg_port_descriptor_t task_port;
853 } msg;
855 if (task_get_bootstrap_port(mach_task_self(), &bootstrap_port) != KERN_SUCCESS) return;
857 kret = bootstrap_look_up(bootstrap_port, (char*)wine_get_server_dir(), &wineserver_port);
858 if (kret != KERN_SUCCESS)
859 fatal_error( "cannot find the server port: 0x%08x\n", kret );
861 mach_port_deallocate(mach_task_self(), bootstrap_port);
863 msg.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0) | MACH_MSGH_BITS_COMPLEX;
864 msg.header.msgh_size = sizeof(msg);
865 msg.header.msgh_remote_port = wineserver_port;
866 msg.header.msgh_local_port = MACH_PORT_NULL;
868 msg.body.msgh_descriptor_count = 1;
869 msg.task_port.name = mach_task_self();
870 msg.task_port.disposition = MACH_MSG_TYPE_COPY_SEND;
871 msg.task_port.type = MACH_MSG_PORT_DESCRIPTOR;
873 kret = mach_msg_send(&msg.header);
874 if (kret != KERN_SUCCESS)
875 server_protocol_error( "mach_msg_send failed: 0x%08x\n", kret );
877 mach_port_deallocate(mach_task_self(), wineserver_port);
879 #endif /* __APPLE__ */
882 /***********************************************************************
883 * get_unix_tid
885 * Retrieve the Unix tid to use on the server side for the current thread.
887 static int get_unix_tid(void)
889 int ret = -1;
890 #if defined(linux) && defined(__i386__)
891 __asm__("int $0x80" : "=a" (ret) : "0" (224) /* SYS_gettid */);
892 #elif defined(linux) && defined(__x86_64__)
893 __asm__("syscall" : "=a" (ret) : "0" (186) /* SYS_gettid */);
894 #elif defined(__sun)
895 ret = pthread_self();
896 #elif defined(__APPLE__)
897 ret = mach_thread_self();
898 #elif defined(__FreeBSD__)
899 long lwpid;
900 thr_self( &lwpid );
901 ret = lwpid;
902 #endif
903 return ret;
907 /***********************************************************************
908 * server_init_process
910 * Start the server and create the initial socket pair.
912 void server_init_process(void)
914 obj_handle_t version;
915 const char *env_socket = getenv( "WINESERVERSOCKET" );
917 if (env_socket)
919 fd_socket = atoi( env_socket );
920 if (fcntl( fd_socket, F_SETFD, 1 ) == -1)
921 fatal_perror( "Bad server socket %d", fd_socket );
922 unsetenv( "WINESERVERSOCKET" );
924 else fd_socket = server_connect();
926 /* setup the signal mask */
927 sigemptyset( &server_block_set );
928 sigaddset( &server_block_set, SIGALRM );
929 sigaddset( &server_block_set, SIGIO );
930 sigaddset( &server_block_set, SIGINT );
931 sigaddset( &server_block_set, SIGHUP );
932 sigaddset( &server_block_set, SIGUSR1 );
933 sigaddset( &server_block_set, SIGUSR2 );
934 sigaddset( &server_block_set, SIGCHLD );
935 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
937 /* receive the first thread request fd on the main socket */
938 ntdll_get_thread_data()->request_fd = receive_fd( &version );
940 if (version != SERVER_PROTOCOL_VERSION)
941 server_protocol_error( "version mismatch %d/%d.\n"
942 "Your %s binary was not upgraded correctly,\n"
943 "or you have an older one somewhere in your PATH.\n"
944 "Or maybe the wrong wineserver is still running?\n",
945 version, SERVER_PROTOCOL_VERSION,
946 (version > SERVER_PROTOCOL_VERSION) ? "wine" : "wineserver" );
947 #ifdef __APPLE__
948 send_server_task_port();
949 #endif
953 /***********************************************************************
954 * server_init_process_done
956 NTSTATUS server_init_process_done(void)
958 PEB *peb = NtCurrentTeb()->Peb;
959 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
960 NTSTATUS status;
962 /* Install signal handlers; this cannot be done earlier, since we cannot
963 * send exceptions to the debugger before the create process event that
964 * is sent by REQ_INIT_PROCESS_DONE.
965 * We do need the handlers in place by the time the request is over, so
966 * we set them up here. If we segfault between here and the server call
967 * something is very wrong... */
968 signal_init_process();
970 /* Signal the parent process to continue */
971 SERVER_START_REQ( init_process_done )
973 req->module = wine_server_client_ptr( peb->ImageBaseAddress );
974 #ifdef __i386__
975 req->ldt_copy = wine_server_client_ptr( &wine_ldt_copy );
976 #endif
977 req->entry = wine_server_client_ptr( (char *)peb->ImageBaseAddress + nt->OptionalHeader.AddressOfEntryPoint );
978 req->gui = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
979 status = wine_server_call( req );
981 SERVER_END_REQ;
983 return status;
987 /***********************************************************************
988 * server_init_thread
990 * Send an init thread request. Return 0 if OK.
992 size_t server_init_thread( void *entry_point )
994 int ret;
995 int reply_pipe[2];
996 struct sigaction sig_act;
997 size_t info_size;
999 sig_act.sa_handler = SIG_IGN;
1000 sig_act.sa_flags = 0;
1001 sigemptyset( &sig_act.sa_mask );
1003 /* ignore SIGPIPE so that we get an EPIPE error instead */
1004 sigaction( SIGPIPE, &sig_act, NULL );
1005 /* automatic child reaping to avoid zombies */
1006 #ifdef SA_NOCLDWAIT
1007 sig_act.sa_flags |= SA_NOCLDWAIT;
1008 #endif
1009 sigaction( SIGCHLD, &sig_act, NULL );
1011 /* create the server->client communication pipes */
1012 if (pipe( reply_pipe ) == -1) server_protocol_perror( "pipe" );
1013 if (pipe( ntdll_get_thread_data()->wait_fd ) == -1) server_protocol_perror( "pipe" );
1014 wine_server_send_fd( reply_pipe[1] );
1015 wine_server_send_fd( ntdll_get_thread_data()->wait_fd[1] );
1016 ntdll_get_thread_data()->reply_fd = reply_pipe[0];
1017 close( reply_pipe[1] );
1019 /* set close on exec flag */
1020 fcntl( ntdll_get_thread_data()->reply_fd, F_SETFD, 1 );
1021 fcntl( ntdll_get_thread_data()->wait_fd[0], F_SETFD, 1 );
1022 fcntl( ntdll_get_thread_data()->wait_fd[1], F_SETFD, 1 );
1024 SERVER_START_REQ( init_thread )
1026 req->unix_pid = getpid();
1027 req->unix_tid = get_unix_tid();
1028 req->teb = wine_server_client_ptr( NtCurrentTeb() );
1029 req->peb = wine_server_client_ptr( NtCurrentTeb()->Peb );
1030 req->entry = wine_server_client_ptr( entry_point );
1031 req->reply_fd = reply_pipe[1];
1032 req->wait_fd = ntdll_get_thread_data()->wait_fd[1];
1033 req->debug_level = (TRACE_ON(server) != 0);
1034 ret = wine_server_call( req );
1035 NtCurrentTeb()->ClientId.UniqueProcess = ULongToHandle(reply->pid);
1036 NtCurrentTeb()->ClientId.UniqueThread = ULongToHandle(reply->tid);
1037 info_size = reply->info_size;
1038 server_start_time = reply->server_start;
1040 SERVER_END_REQ;
1042 if (ret) server_protocol_error( "init_thread failed with status %x\n", ret );
1043 return info_size;