server: Add support for 64-bits client/server
[wine/wine64.git] / dlls / ntdll / server.c
blob4af510387cf857d3e415b45ab27af2fc11d5a6ab
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_UNISTD_H
55 # include <unistd.h>
56 #endif
58 #include "ntstatus.h"
59 #define WIN32_NO_STATUS
60 #include "wine/library.h"
61 #include "wine/pthread.h"
62 #include "wine/server.h"
63 #include "wine/debug.h"
64 #include "ntdll_misc.h"
66 WINE_DEFAULT_DEBUG_CHANNEL(server);
68 /* Some versions of glibc don't define this */
69 #ifndef SCM_RIGHTS
70 #define SCM_RIGHTS 1
71 #endif
73 #define SOCKETNAME "socket" /* name of the socket file */
74 #define LOCKNAME "lock" /* name of the lock file */
76 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
77 /* data structure used to pass an fd with sendmsg/recvmsg */
78 struct cmsg_fd
80 struct
82 size_t len; /* size of structure */
83 int level; /* SOL_SOCKET */
84 int type; /* SCM_RIGHTS */
85 } header;
86 int fd; /* fd to pass */
88 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
90 timeout_t server_start_time = 0; /* time of server startup */
92 extern struct wine_pthread_functions pthread_functions;
94 sigset_t server_block_set; /* signals to block during server calls */
95 static int fd_socket = -1; /* socket to exchange file descriptors with the server */
97 static RTL_CRITICAL_SECTION fd_cache_section;
98 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
100 0, 0, &fd_cache_section,
101 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
102 0, 0, { (DWORD_PTR)(__FILE__ ": fd_cache_section") }
104 static RTL_CRITICAL_SECTION fd_cache_section = { &critsect_debug, -1, 0, 0, 0, 0 };
107 #ifdef __GNUC__
108 static void fatal_error( const char *err, ... ) __attribute__((noreturn, format(printf,1,2)));
109 static void fatal_perror( const char *err, ... ) __attribute__((noreturn, format(printf,1,2)));
110 static void server_connect_error( const char *serverdir ) __attribute__((noreturn));
111 #endif
113 /* die on a fatal error; use only during initialization */
114 static void fatal_error( const char *err, ... )
116 va_list args;
118 va_start( args, err );
119 fprintf( stderr, "wine: " );
120 vfprintf( stderr, err, args );
121 va_end( args );
122 exit(1);
125 /* die on a fatal error; use only during initialization */
126 static void fatal_perror( const char *err, ... )
128 va_list args;
130 va_start( args, err );
131 fprintf( stderr, "wine: " );
132 vfprintf( stderr, err, args );
133 perror( " " );
134 va_end( args );
135 exit(1);
139 /***********************************************************************
140 * server_exit_thread
142 void server_exit_thread( int status )
144 struct wine_pthread_thread_info info;
145 int fds[4];
147 RtlAcquirePebLock();
148 RemoveEntryList( &NtCurrentTeb()->TlsLinks );
149 RtlReleasePebLock();
150 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->FlsSlots );
151 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->TlsExpansionSlots );
153 info.stack_base = NtCurrentTeb()->DeallocationStack;
154 info.teb_base = NtCurrentTeb();
155 info.teb_sel = wine_get_fs();
156 info.exit_status = status;
158 fds[0] = ntdll_get_thread_data()->wait_fd[0];
159 fds[1] = ntdll_get_thread_data()->wait_fd[1];
160 fds[2] = ntdll_get_thread_data()->reply_fd;
161 fds[3] = ntdll_get_thread_data()->request_fd;
162 pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, NULL );
164 info.stack_size = virtual_free_system_view( &info.stack_base );
165 info.teb_size = virtual_free_system_view( &info.teb_base );
167 close( fds[0] );
168 close( fds[1] );
169 close( fds[2] );
170 close( fds[3] );
171 pthread_functions.exit_thread( &info );
175 /***********************************************************************
176 * server_abort_thread
178 void server_abort_thread( int status )
180 pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, NULL );
181 close( ntdll_get_thread_data()->wait_fd[0] );
182 close( ntdll_get_thread_data()->wait_fd[1] );
183 close( ntdll_get_thread_data()->reply_fd );
184 close( ntdll_get_thread_data()->request_fd );
185 pthread_functions.abort_thread( status );
189 /***********************************************************************
190 * server_protocol_error
192 void server_protocol_error( const char *err, ... )
194 va_list args;
196 va_start( args, err );
197 fprintf( stderr, "wine client error:%x: ", GetCurrentThreadId() );
198 vfprintf( stderr, err, args );
199 va_end( args );
200 server_abort_thread(1);
204 /***********************************************************************
205 * server_protocol_perror
207 void server_protocol_perror( const char *err )
209 fprintf( stderr, "wine client error:%x: ", GetCurrentThreadId() );
210 perror( err );
211 server_abort_thread(1);
215 /***********************************************************************
216 * send_request
218 * Send a request to the server.
220 static unsigned int send_request( const struct __server_request_info *req )
222 unsigned int i;
223 int ret;
225 if (!req->u.req.request_header.request_size)
227 if ((ret = write( ntdll_get_thread_data()->request_fd, &req->u.req,
228 sizeof(req->u.req) )) == sizeof(req->u.req)) return STATUS_SUCCESS;
231 else
233 struct iovec vec[__SERVER_MAX_DATA+1];
235 vec[0].iov_base = (void *)&req->u.req;
236 vec[0].iov_len = sizeof(req->u.req);
237 for (i = 0; i < req->data_count; i++)
239 vec[i+1].iov_base = (void *)req->data[i].ptr;
240 vec[i+1].iov_len = req->data[i].size;
242 if ((ret = writev( ntdll_get_thread_data()->request_fd, vec, i+1 )) ==
243 req->u.req.request_header.request_size + sizeof(req->u.req)) return STATUS_SUCCESS;
246 if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
247 if (errno == EPIPE) server_abort_thread(0);
248 if (errno == EFAULT) return STATUS_ACCESS_VIOLATION;
249 server_protocol_perror( "write" );
253 /***********************************************************************
254 * read_reply_data
256 * Read data from the reply buffer; helper for wait_reply.
258 static void read_reply_data( void *buffer, size_t size )
260 int ret;
262 for (;;)
264 if ((ret = read( ntdll_get_thread_data()->reply_fd, buffer, size )) > 0)
266 if (!(size -= ret)) return;
267 buffer = (char *)buffer + ret;
268 continue;
270 if (!ret) break;
271 if (errno == EINTR) continue;
272 if (errno == EPIPE) break;
273 server_protocol_perror("read");
275 /* the server closed the connection; time to die... */
276 server_abort_thread(0);
280 /***********************************************************************
281 * wait_reply
283 * Wait for a reply from the server.
285 static inline unsigned int wait_reply( struct __server_request_info *req )
287 read_reply_data( &req->u.reply, sizeof(req->u.reply) );
288 if (req->u.reply.reply_header.reply_size)
289 read_reply_data( req->reply_data, req->u.reply.reply_header.reply_size );
290 return req->u.reply.reply_header.error;
294 /***********************************************************************
295 * wine_server_call (NTDLL.@)
297 * Perform a server call.
299 * PARAMS
300 * req_ptr [I/O] Function dependent data
302 * RETURNS
303 * Depends on server function being called, but usually an NTSTATUS code.
305 * NOTES
306 * Use the SERVER_START_REQ and SERVER_END_REQ to help you fill out the
307 * server request structure for the particular call. E.g:
308 *| SERVER_START_REQ( event_op )
309 *| {
310 *| req->handle = handle;
311 *| req->op = SET_EVENT;
312 *| ret = wine_server_call( req );
313 *| }
314 *| SERVER_END_REQ;
316 unsigned int wine_server_call( void *req_ptr )
318 struct __server_request_info * const req = req_ptr;
319 sigset_t old_set;
320 unsigned int ret;
322 pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, &old_set );
323 ret = send_request( req );
324 if (!ret) ret = wait_reply( req );
325 pthread_functions.sigprocmask( SIG_SETMASK, &old_set, NULL );
326 return ret;
330 /***********************************************************************
331 * server_enter_uninterrupted_section
333 void server_enter_uninterrupted_section( RTL_CRITICAL_SECTION *cs, sigset_t *sigset )
335 pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, sigset );
336 RtlEnterCriticalSection( cs );
340 /***********************************************************************
341 * server_leave_uninterrupted_section
343 void server_leave_uninterrupted_section( RTL_CRITICAL_SECTION *cs, sigset_t *sigset )
345 RtlLeaveCriticalSection( cs );
346 pthread_functions.sigprocmask( SIG_SETMASK, sigset, NULL );
350 /***********************************************************************
351 * wine_server_send_fd (NTDLL.@)
353 * Send a file descriptor to the server.
355 * PARAMS
356 * fd [I] file descriptor to send
358 * RETURNS
359 * nothing
361 void CDECL wine_server_send_fd( int fd )
363 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
364 struct cmsg_fd cmsg;
365 #endif
366 struct send_fd data;
367 struct msghdr msghdr;
368 struct iovec vec;
369 int ret;
371 vec.iov_base = (void *)&data;
372 vec.iov_len = sizeof(data);
374 msghdr.msg_name = NULL;
375 msghdr.msg_namelen = 0;
376 msghdr.msg_iov = &vec;
377 msghdr.msg_iovlen = 1;
379 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
380 msghdr.msg_accrights = (void *)&fd;
381 msghdr.msg_accrightslen = sizeof(fd);
382 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
383 cmsg.header.len = sizeof(cmsg.header) + sizeof(fd);
384 cmsg.header.level = SOL_SOCKET;
385 cmsg.header.type = SCM_RIGHTS;
386 cmsg.fd = fd;
387 msghdr.msg_control = &cmsg;
388 msghdr.msg_controllen = sizeof(cmsg.header) + sizeof(fd);
389 msghdr.msg_flags = 0;
390 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
392 data.tid = GetCurrentThreadId();
393 data.fd = fd;
395 for (;;)
397 if ((ret = sendmsg( fd_socket, &msghdr, 0 )) == sizeof(data)) return;
398 if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
399 if (errno == EINTR) continue;
400 if (errno == EPIPE) server_abort_thread(0);
401 server_protocol_perror( "sendmsg" );
406 /***********************************************************************
407 * receive_fd
409 * Receive a file descriptor passed from the server.
411 static int receive_fd( obj_handle_t *handle )
413 struct iovec vec;
414 int ret, fd;
416 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
417 struct msghdr msghdr;
419 fd = -1;
420 msghdr.msg_accrights = (void *)&fd;
421 msghdr.msg_accrightslen = sizeof(fd);
422 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
423 struct msghdr msghdr;
424 struct cmsg_fd cmsg;
426 cmsg.header.len = sizeof(cmsg.header) + sizeof(fd);
427 cmsg.header.level = SOL_SOCKET;
428 cmsg.header.type = SCM_RIGHTS;
429 cmsg.fd = -1;
430 msghdr.msg_control = &cmsg;
431 msghdr.msg_controllen = sizeof(cmsg.header) + sizeof(fd);
432 msghdr.msg_flags = 0;
433 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
435 msghdr.msg_name = NULL;
436 msghdr.msg_namelen = 0;
437 msghdr.msg_iov = &vec;
438 msghdr.msg_iovlen = 1;
439 vec.iov_base = (void *)handle;
440 vec.iov_len = sizeof(*handle);
442 for (;;)
444 if ((ret = recvmsg( fd_socket, &msghdr, 0 )) > 0)
446 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
447 fd = cmsg.fd;
448 #endif
449 if (fd != -1) fcntl( fd, F_SETFD, 1 ); /* set close on exec flag */
450 return fd;
452 if (!ret) break;
453 if (errno == EINTR) continue;
454 if (errno == EPIPE) break;
455 server_protocol_perror("recvmsg");
457 /* the server closed the connection; time to die... */
458 server_abort_thread(0);
462 /***********************************************************************/
463 /* fd cache support */
465 struct fd_cache_entry
467 int fd;
468 enum server_fd_type type : 6;
469 unsigned int access : 2;
470 unsigned int options : 24;
473 #define FD_CACHE_BLOCK_SIZE (65536 / sizeof(struct fd_cache_entry))
474 #define FD_CACHE_ENTRIES 128
476 static struct fd_cache_entry *fd_cache[FD_CACHE_ENTRIES];
477 static struct fd_cache_entry fd_cache_initial_block[FD_CACHE_BLOCK_SIZE];
479 static inline unsigned int handle_to_index( HANDLE handle, unsigned int *entry )
481 unsigned int idx = (wine_server_obj_handle(handle) >> 2) - 1;
482 *entry = idx / FD_CACHE_BLOCK_SIZE;
483 return idx % FD_CACHE_BLOCK_SIZE;
487 /***********************************************************************
488 * add_fd_to_cache
490 * Caller must hold fd_cache_section.
492 static int add_fd_to_cache( HANDLE handle, int fd, enum server_fd_type type,
493 unsigned int access, unsigned int options )
495 unsigned int entry, idx = handle_to_index( handle, &entry );
496 int prev_fd;
498 if (entry >= FD_CACHE_ENTRIES)
500 FIXME( "too many allocated handles, not caching %p\n", handle );
501 return 0;
504 if (!fd_cache[entry]) /* do we need to allocate a new block of entries? */
506 if (!entry) fd_cache[0] = fd_cache_initial_block;
507 else
509 void *ptr = wine_anon_mmap( NULL, FD_CACHE_BLOCK_SIZE * sizeof(struct fd_cache_entry),
510 PROT_READ | PROT_WRITE, 0 );
511 if (ptr == MAP_FAILED) return 0;
512 fd_cache[entry] = ptr;
515 /* store fd+1 so that 0 can be used as the unset value */
516 prev_fd = interlocked_xchg( &fd_cache[entry][idx].fd, fd + 1 ) - 1;
517 fd_cache[entry][idx].type = type;
518 fd_cache[entry][idx].access = access;
519 fd_cache[entry][idx].options = options;
520 if (prev_fd != -1) close( prev_fd );
521 return 1;
525 /***********************************************************************
526 * get_cached_fd
528 * Caller must hold fd_cache_section.
530 static inline int get_cached_fd( HANDLE handle, enum server_fd_type *type,
531 unsigned int *access, unsigned int *options )
533 unsigned int entry, idx = handle_to_index( handle, &entry );
534 int fd = -1;
536 if (entry < FD_CACHE_ENTRIES && fd_cache[entry])
538 fd = fd_cache[entry][idx].fd - 1;
539 if (type) *type = fd_cache[entry][idx].type;
540 if (access) *access = fd_cache[entry][idx].access;
541 if (options) *options = fd_cache[entry][idx].options;
543 return fd;
547 /***********************************************************************
548 * server_remove_fd_from_cache
550 int server_remove_fd_from_cache( HANDLE handle )
552 unsigned int entry, idx = handle_to_index( handle, &entry );
553 int fd = -1;
555 if (entry < FD_CACHE_ENTRIES && fd_cache[entry])
556 fd = interlocked_xchg( &fd_cache[entry][idx].fd, 0 ) - 1;
558 return fd;
562 /***********************************************************************
563 * server_get_unix_fd
565 * The returned unix_fd should be closed iff needs_close is non-zero.
567 int server_get_unix_fd( HANDLE handle, unsigned int wanted_access, int *unix_fd,
568 int *needs_close, enum server_fd_type *type, unsigned int *options )
570 sigset_t sigset;
571 obj_handle_t fd_handle;
572 int ret = 0, fd;
573 unsigned int access = 0;
575 *unix_fd = -1;
576 *needs_close = 0;
577 wanted_access &= FILE_READ_DATA | FILE_WRITE_DATA;
579 server_enter_uninterrupted_section( &fd_cache_section, &sigset );
581 fd = get_cached_fd( handle, type, &access, options );
582 if (fd != -1) goto done;
584 SERVER_START_REQ( get_handle_fd )
586 req->handle = wine_server_obj_handle( handle );
587 if (!(ret = wine_server_call( req )))
589 if (type) *type = reply->type;
590 if (options) *options = reply->options;
591 access = reply->access;
592 if ((fd = receive_fd( &fd_handle )) != -1)
594 assert( wine_server_ptr_handle(fd_handle) == handle );
595 *needs_close = (reply->removable ||
596 !add_fd_to_cache( handle, fd, reply->type,
597 reply->access, reply->options ));
599 else ret = STATUS_TOO_MANY_OPENED_FILES;
602 SERVER_END_REQ;
604 done:
605 server_leave_uninterrupted_section( &fd_cache_section, &sigset );
606 if (!ret && ((access & wanted_access) != wanted_access))
608 ret = STATUS_ACCESS_DENIED;
609 if (*needs_close) close( fd );
611 if (!ret) *unix_fd = fd;
612 return ret;
616 /***********************************************************************
617 * wine_server_fd_to_handle (NTDLL.@)
619 * Allocate a file handle for a Unix file descriptor.
621 * PARAMS
622 * fd [I] Unix file descriptor.
623 * access [I] Win32 access flags.
624 * attributes [I] Object attributes.
625 * handle [O] Address where Wine file handle will be stored.
627 * RETURNS
628 * NTSTATUS code
630 int CDECL wine_server_fd_to_handle( int fd, unsigned int access, unsigned int attributes, HANDLE *handle )
632 int ret;
634 *handle = 0;
635 wine_server_send_fd( fd );
637 SERVER_START_REQ( alloc_file_handle )
639 req->access = access;
640 req->attributes = attributes;
641 req->fd = fd;
642 if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
644 SERVER_END_REQ;
645 return ret;
649 /***********************************************************************
650 * wine_server_handle_to_fd (NTDLL.@)
652 * Retrieve the file descriptor corresponding to a file handle.
654 * PARAMS
655 * handle [I] Wine file handle.
656 * access [I] Win32 file access rights requested.
657 * unix_fd [O] Address where Unix file descriptor will be stored.
658 * options [O] Address where the file open options will be stored. Optional.
660 * RETURNS
661 * NTSTATUS code
663 int CDECL wine_server_handle_to_fd( HANDLE handle, unsigned int access, int *unix_fd,
664 unsigned int *options )
666 int needs_close, ret = server_get_unix_fd( handle, access, unix_fd, &needs_close, NULL, options );
668 if (!ret && !needs_close)
670 if ((*unix_fd = dup(*unix_fd)) == -1) ret = FILE_GetNtStatus();
672 return ret;
676 /***********************************************************************
677 * wine_server_release_fd (NTDLL.@)
679 * Release the Unix file descriptor returned by wine_server_handle_to_fd.
681 * PARAMS
682 * handle [I] Wine file handle.
683 * unix_fd [I] Unix file descriptor to release.
685 * RETURNS
686 * nothing
688 void CDECL wine_server_release_fd( HANDLE handle, int unix_fd )
690 close( unix_fd );
694 /***********************************************************************
695 * start_server
697 * Start a new wine server.
699 static void start_server(void)
701 static int started; /* we only try once */
702 char *argv[3];
703 static char wineserver[] = "server/wineserver";
704 static char debug[] = "-d";
706 if (!started)
708 int status;
709 int pid = fork();
710 if (pid == -1) fatal_perror( "fork" );
711 if (!pid)
713 argv[0] = wineserver;
714 argv[1] = TRACE_ON(server) ? debug : NULL;
715 argv[2] = 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 */
723 started = 1;
728 /***********************************************************************
729 * setup_config_dir
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)
743 struct stat st;
744 char *tmp_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",
751 tmp_dir );
752 free( tmp_dir );
755 mkdir( config_dir, 0777 );
756 if (chdir( config_dir ) == -1) fatal_perror( "chdir to %s\n", config_dir );
757 MESSAGE( "wine: created the configuration directory '%s'\n", config_dir );
760 if (mkdir( "dosdevices", 0777 ) == -1)
762 if (errno == EEXIST) return;
763 fatal_perror( "cannot create %s/dosdevices\n", config_dir );
766 /* create the drive symlinks */
768 mkdir( "drive_c", 0777 );
769 symlink( "../drive_c", "dosdevices/c:" );
770 symlink( "/", "dosdevices/z:" );
774 /***********************************************************************
775 * server_connect_error
777 * Try to display a meaningful explanation of why we couldn't connect
778 * to the server.
780 static void server_connect_error( const char *serverdir )
782 int fd;
783 struct flock fl;
785 if ((fd = open( LOCKNAME, O_WRONLY )) == -1)
786 fatal_error( "for some mysterious reason, the wine server never started.\n" );
788 fl.l_type = F_WRLCK;
789 fl.l_whence = SEEK_SET;
790 fl.l_start = 0;
791 fl.l_len = 1;
792 if (fcntl( fd, F_GETLK, &fl ) != -1)
794 if (fl.l_type == F_WRLCK) /* the file is locked */
795 fatal_error( "a wine server seems to be running, but I cannot connect to it.\n"
796 " You probably need to kill that process (it might be pid %d).\n",
797 (int)fl.l_pid );
798 fatal_error( "for some mysterious reason, the wine server failed to run.\n" );
800 fatal_error( "the file system of '%s' doesn't support locks,\n"
801 " and there is a 'socket' file in that directory that prevents wine from starting.\n"
802 " You should make sure no wine server is running, remove that file and try again.\n",
803 serverdir );
807 /***********************************************************************
808 * server_connect
810 * Attempt to connect to an existing server socket.
811 * We need to be in the server directory already.
813 static int server_connect(void)
815 const char *serverdir;
816 struct sockaddr_un addr;
817 struct stat st;
818 int s, slen, retry, fd_cwd;
820 /* retrieve the current directory */
821 fd_cwd = open( ".", O_RDONLY );
822 if (fd_cwd != -1) fcntl( fd_cwd, F_SETFD, 1 ); /* set close on exec flag */
824 setup_config_dir();
825 serverdir = wine_get_server_dir();
827 /* chdir to the server directory */
828 if (chdir( serverdir ) == -1)
830 if (errno != ENOENT) fatal_perror( "chdir to %s", serverdir );
831 start_server();
832 if (chdir( serverdir ) == -1) fatal_perror( "chdir to %s", serverdir );
835 /* make sure we are at the right place */
836 if (stat( ".", &st ) == -1) fatal_perror( "stat %s", serverdir );
837 if (st.st_uid != getuid()) fatal_error( "'%s' is not owned by you\n", serverdir );
838 if (st.st_mode & 077) fatal_error( "'%s' must not be accessible by other users\n", serverdir );
840 for (retry = 0; retry < 6; retry++)
842 /* if not the first try, wait a bit to leave the previous server time to exit */
843 if (retry)
845 usleep( 100000 * retry * retry );
846 start_server();
847 if (lstat( SOCKETNAME, &st ) == -1) continue; /* still no socket, wait a bit more */
849 else if (lstat( SOCKETNAME, &st ) == -1) /* check for an already existing socket */
851 if (errno != ENOENT) fatal_perror( "lstat %s/%s", serverdir, SOCKETNAME );
852 start_server();
853 if (lstat( SOCKETNAME, &st ) == -1) continue; /* still no socket, wait a bit more */
856 /* make sure the socket is sane (ISFIFO needed for Solaris) */
857 if (!S_ISSOCK(st.st_mode) && !S_ISFIFO(st.st_mode))
858 fatal_error( "'%s/%s' is not a socket\n", serverdir, SOCKETNAME );
859 if (st.st_uid != getuid())
860 fatal_error( "'%s/%s' is not owned by you\n", serverdir, SOCKETNAME );
862 /* try to connect to it */
863 addr.sun_family = AF_UNIX;
864 strcpy( addr.sun_path, SOCKETNAME );
865 slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
866 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
867 addr.sun_len = slen;
868 #endif
869 if ((s = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_perror( "socket" );
870 if (connect( s, (struct sockaddr *)&addr, slen ) != -1)
872 /* switch back to the starting directory */
873 if (fd_cwd != -1)
875 fchdir( fd_cwd );
876 close( fd_cwd );
878 fcntl( s, F_SETFD, 1 ); /* set close on exec flag */
879 return s;
881 close( s );
883 server_connect_error( serverdir );
887 #ifdef __APPLE__
888 #include <mach/mach.h>
889 #include <mach/mach_error.h>
890 #include <servers/bootstrap.h>
892 /* send our task port to the server */
893 static void send_server_task_port(void)
895 mach_port_t bootstrap_port, wineserver_port;
896 kern_return_t kret;
898 struct {
899 mach_msg_header_t header;
900 mach_msg_body_t body;
901 mach_msg_port_descriptor_t task_port;
902 } msg;
904 if (task_get_bootstrap_port(mach_task_self(), &bootstrap_port) != KERN_SUCCESS) return;
906 kret = bootstrap_look_up(bootstrap_port, (char*)wine_get_server_dir(), &wineserver_port);
907 if (kret != KERN_SUCCESS)
908 fatal_error( "cannot find the server port: 0x%08x\n", kret );
910 mach_port_deallocate(mach_task_self(), bootstrap_port);
912 msg.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0) | MACH_MSGH_BITS_COMPLEX;
913 msg.header.msgh_size = sizeof(msg);
914 msg.header.msgh_remote_port = wineserver_port;
915 msg.header.msgh_local_port = MACH_PORT_NULL;
917 msg.body.msgh_descriptor_count = 1;
918 msg.task_port.name = mach_task_self();
919 msg.task_port.disposition = MACH_MSG_TYPE_COPY_SEND;
920 msg.task_port.type = MACH_MSG_PORT_DESCRIPTOR;
922 kret = mach_msg_send(&msg.header);
923 if (kret != KERN_SUCCESS)
924 server_protocol_error( "mach_msg_send failed: 0x%08x\n", kret );
926 mach_port_deallocate(mach_task_self(), wineserver_port);
928 #endif /* __APPLE__ */
930 /***********************************************************************
931 * server_init_process
933 * Start the server and create the initial socket pair.
935 void server_init_process(void)
937 obj_handle_t dummy_handle;
938 const char *env_socket = getenv( "WINESERVERSOCKET" );
940 if (env_socket)
942 fd_socket = atoi( env_socket );
943 if (fcntl( fd_socket, F_SETFD, 1 ) == -1)
944 fatal_perror( "Bad server socket %d", fd_socket );
945 unsetenv( "WINESERVERSOCKET" );
947 else fd_socket = server_connect();
949 /* setup the signal mask */
950 sigemptyset( &server_block_set );
951 sigaddset( &server_block_set, SIGALRM );
952 sigaddset( &server_block_set, SIGIO );
953 sigaddset( &server_block_set, SIGINT );
954 sigaddset( &server_block_set, SIGHUP );
955 sigaddset( &server_block_set, SIGUSR1 );
956 sigaddset( &server_block_set, SIGUSR2 );
957 sigaddset( &server_block_set, SIGCHLD );
958 pthread_functions.sigprocmask( SIG_BLOCK, &server_block_set, NULL );
960 /* receive the first thread request fd on the main socket */
961 ntdll_get_thread_data()->request_fd = receive_fd( &dummy_handle );
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 = peb->ImageBaseAddress;
990 req->entry = (char *)peb->ImageBaseAddress + nt->OptionalHeader.AddressOfEntryPoint;
991 req->gui = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
992 status = wine_server_call( req );
994 SERVER_END_REQ;
996 return status;
1000 /***********************************************************************
1001 * server_init_thread
1003 * Send an init thread request. Return 0 if OK.
1005 size_t server_init_thread( int unix_pid, int unix_tid, void *entry_point )
1007 int version, ret;
1008 int reply_pipe[2];
1009 struct sigaction sig_act;
1010 size_t info_size;
1011 int pointer_bytes;
1013 sig_act.sa_handler = SIG_IGN;
1014 sig_act.sa_flags = 0;
1015 sigemptyset( &sig_act.sa_mask );
1017 /* ignore SIGPIPE so that we get an EPIPE error instead */
1018 sigaction( SIGPIPE, &sig_act, NULL );
1019 /* automatic child reaping to avoid zombies */
1020 #ifdef SA_NOCLDWAIT
1021 sig_act.sa_flags |= SA_NOCLDWAIT;
1022 #endif
1023 sigaction( SIGCHLD, &sig_act, NULL );
1025 /* create the server->client communication pipes */
1026 if (pipe( reply_pipe ) == -1) server_protocol_perror( "pipe" );
1027 if (pipe( ntdll_get_thread_data()->wait_fd ) == -1) server_protocol_perror( "pipe" );
1028 wine_server_send_fd( reply_pipe[1] );
1029 wine_server_send_fd( ntdll_get_thread_data()->wait_fd[1] );
1030 ntdll_get_thread_data()->reply_fd = reply_pipe[0];
1031 close( reply_pipe[1] );
1033 /* set close on exec flag */
1034 fcntl( ntdll_get_thread_data()->reply_fd, F_SETFD, 1 );
1035 fcntl( ntdll_get_thread_data()->wait_fd[0], F_SETFD, 1 );
1036 fcntl( ntdll_get_thread_data()->wait_fd[1], F_SETFD, 1 );
1038 SERVER_START_REQ( init_thread )
1040 req->unix_pid = unix_pid;
1041 req->unix_tid = unix_tid;
1042 req->teb = (int)(long)NtCurrentTeb();
1043 req->peb = (int)(long)NtCurrentTeb()->Peb;
1044 req->entry = (int)(long)entry_point;
1045 req->ldt_copy = (int)(long)&wine_ldt_copy;
1046 #ifdef _WIN64
1047 req->teb_high = (int)(((long)NtCurrentTeb()) >> 32L);
1048 req->peb_high = (int)(((long)NtCurrentTeb()->Peb) >> 32L);
1049 req->entry_high = (int)(((long)entry_point) >> 32L);
1050 req->ldt_copy_high= (int)(((long)&wine_ldt_copy) >> 32L);
1051 #endif
1052 req->reply_fd = reply_pipe[1];
1053 req->wait_fd = ntdll_get_thread_data()->wait_fd[1];
1054 req->debug_level = (TRACE_ON(server) != 0);
1055 req->pointer_bytes= sizeof(void *);
1056 ret = wine_server_call( req );
1057 NtCurrentTeb()->ClientId.UniqueProcess = ULongToHandle(reply->pid);
1058 NtCurrentTeb()->ClientId.UniqueThread = ULongToHandle(reply->tid);
1059 info_size = reply->info_size;
1060 version = reply->version;
1061 server_start_time = reply->server_start;
1062 pointer_bytes = reply->pointer_bytes;
1064 SERVER_END_REQ;
1066 if (ret) server_protocol_error( "init_thread failed with status %x\n", ret );
1067 if (version != SERVER_PROTOCOL_VERSION)
1068 server_protocol_error( "version mismatch %d/%d.\n"
1069 "Your %s binary was not upgraded correctly,\n"
1070 "or you have an older one somewhere in your PATH.\n"
1071 "Or maybe the wrong wineserver is still running?\n",
1072 version, SERVER_PROTOCOL_VERSION,
1073 (version > SERVER_PROTOCOL_VERSION) ? "wine" : "wineserver" );
1074 if (sizeof(void*) != pointer_bytes)
1075 server_protocol_error( "Wineserver doesn't support %d bits binaries,\n"
1076 "instead it was built for %d bits binaries\n",
1077 (int)sizeof(void*)*8, pointer_bytes*8 );
1078 return info_size;