ntdll: Prefer a portable function to get thread id.
[wine/multimedia.git] / dlls / ntdll / server.c
blobcc49bad31cdf757b762b9354aefcb5e241c98adb
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 #ifdef HAVE_PTHREAD_NP_H
32 # include <pthread_np.h>
33 #endif
34 #include <signal.h>
35 #include <stdarg.h>
36 #include <stdio.h>
37 #include <string.h>
38 #include <sys/types.h>
39 #ifdef HAVE_SYS_SOCKET_H
40 # include <sys/socket.h>
41 #endif
42 #ifdef HAVE_SYS_WAIT_H
43 #include <sys/wait.h>
44 #endif
45 #ifdef HAVE_SYS_UN_H
46 #include <sys/un.h>
47 #endif
48 #ifdef HAVE_SYS_MMAN_H
49 #include <sys/mman.h>
50 #endif
51 #ifdef HAVE_SYS_PRCTL_H
52 # include <sys/prctl.h>
53 #endif
54 #ifdef HAVE_SYS_STAT_H
55 # include <sys/stat.h>
56 #endif
57 #ifdef HAVE_SYS_SYSCALL_H
58 # include <sys/syscall.h>
59 #endif
60 #ifdef HAVE_SYS_UIO_H
61 #include <sys/uio.h>
62 #endif
63 #ifdef HAVE_SYS_THR_H
64 #include <sys/ucontext.h>
65 #include <sys/thr.h>
66 #endif
67 #ifdef HAVE_UNISTD_H
68 # include <unistd.h>
69 #endif
71 #include "ntstatus.h"
72 #define WIN32_NO_STATUS
73 #include "wine/library.h"
74 #include "wine/server.h"
75 #include "wine/debug.h"
76 #include "ntdll_misc.h"
78 WINE_DEFAULT_DEBUG_CHANNEL(server);
80 /* Some versions of glibc don't define this */
81 #ifndef SCM_RIGHTS
82 #define SCM_RIGHTS 1
83 #endif
85 #ifndef MSG_CMSG_CLOEXEC
86 #define MSG_CMSG_CLOEXEC 0
87 #endif
89 #define SOCKETNAME "socket" /* name of the socket file */
90 #define LOCKNAME "lock" /* name of the lock file */
92 #ifdef __i386__
93 static const enum cpu_type client_cpu = CPU_x86;
94 #elif defined(__x86_64__)
95 static const enum cpu_type client_cpu = CPU_x86_64;
96 #elif defined(__powerpc__)
97 static const enum cpu_type client_cpu = CPU_POWERPC;
98 #elif defined(__sparc__)
99 static const enum cpu_type client_cpu = CPU_SPARC;
100 #elif defined(__arm__)
101 static const enum cpu_type client_cpu = CPU_ARM;
102 #else
103 #error Unsupported CPU
104 #endif
106 unsigned int server_cpus = 0;
107 int is_wow64 = FALSE;
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 */
113 static pid_t server_pid;
115 static RTL_CRITICAL_SECTION fd_cache_section;
116 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
118 0, 0, &fd_cache_section,
119 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
120 0, 0, { (DWORD_PTR)(__FILE__ ": fd_cache_section") }
122 static RTL_CRITICAL_SECTION fd_cache_section = { &critsect_debug, -1, 0, 0, 0, 0 };
125 #ifdef __GNUC__
126 static void fatal_error( const char *err, ... ) __attribute__((noreturn, format(printf,1,2)));
127 static void fatal_perror( const char *err, ... ) __attribute__((noreturn, format(printf,1,2)));
128 static void server_connect_error( const char *serverdir ) __attribute__((noreturn));
129 #endif
131 /* die on a fatal error; use only during initialization */
132 static void fatal_error( const char *err, ... )
134 va_list args;
136 va_start( args, err );
137 fprintf( stderr, "wine: " );
138 vfprintf( stderr, err, args );
139 va_end( args );
140 exit(1);
143 /* die on a fatal error; use only during initialization */
144 static void fatal_perror( const char *err, ... )
146 va_list args;
148 va_start( args, err );
149 fprintf( stderr, "wine: " );
150 vfprintf( stderr, err, args );
151 perror( " " );
152 va_end( args );
153 exit(1);
157 /***********************************************************************
158 * server_protocol_error
160 void server_protocol_error( const char *err, ... )
162 va_list args;
164 va_start( args, err );
165 fprintf( stderr, "wine client error:%x: ", GetCurrentThreadId() );
166 vfprintf( stderr, err, args );
167 va_end( args );
168 abort_thread(1);
172 /***********************************************************************
173 * server_protocol_perror
175 void server_protocol_perror( const char *err )
177 fprintf( stderr, "wine client error:%x: ", GetCurrentThreadId() );
178 perror( err );
179 abort_thread(1);
183 /***********************************************************************
184 * send_request
186 * Send a request to the server.
188 static unsigned int send_request( const struct __server_request_info *req )
190 unsigned int i;
191 int ret;
193 if (!req->u.req.request_header.request_size)
195 if ((ret = write( ntdll_get_thread_data()->request_fd, &req->u.req,
196 sizeof(req->u.req) )) == sizeof(req->u.req)) return STATUS_SUCCESS;
199 else
201 struct iovec vec[__SERVER_MAX_DATA+1];
203 vec[0].iov_base = (void *)&req->u.req;
204 vec[0].iov_len = sizeof(req->u.req);
205 for (i = 0; i < req->data_count; i++)
207 vec[i+1].iov_base = (void *)req->data[i].ptr;
208 vec[i+1].iov_len = req->data[i].size;
210 if ((ret = writev( ntdll_get_thread_data()->request_fd, vec, i+1 )) ==
211 req->u.req.request_header.request_size + sizeof(req->u.req)) return STATUS_SUCCESS;
214 if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
215 if (errno == EPIPE) abort_thread(0);
216 if (errno == EFAULT) return STATUS_ACCESS_VIOLATION;
217 server_protocol_perror( "write" );
221 /***********************************************************************
222 * read_reply_data
224 * Read data from the reply buffer; helper for wait_reply.
226 static void read_reply_data( void *buffer, size_t size )
228 int ret;
230 for (;;)
232 if ((ret = read( ntdll_get_thread_data()->reply_fd, buffer, size )) > 0)
234 if (!(size -= ret)) return;
235 buffer = (char *)buffer + ret;
236 continue;
238 if (!ret) break;
239 if (errno == EINTR) continue;
240 if (errno == EPIPE) break;
241 server_protocol_perror("read");
243 /* the server closed the connection; time to die... */
244 abort_thread(0);
248 /***********************************************************************
249 * wait_reply
251 * Wait for a reply from the server.
253 static inline unsigned int wait_reply( struct __server_request_info *req )
255 read_reply_data( &req->u.reply, sizeof(req->u.reply) );
256 if (req->u.reply.reply_header.reply_size)
257 read_reply_data( req->reply_data, req->u.reply.reply_header.reply_size );
258 return req->u.reply.reply_header.error;
262 /***********************************************************************
263 * wine_server_call (NTDLL.@)
265 * Perform a server call.
267 * PARAMS
268 * req_ptr [I/O] Function dependent data
270 * RETURNS
271 * Depends on server function being called, but usually an NTSTATUS code.
273 * NOTES
274 * Use the SERVER_START_REQ and SERVER_END_REQ to help you fill out the
275 * server request structure for the particular call. E.g:
276 *| SERVER_START_REQ( event_op )
277 *| {
278 *| req->handle = handle;
279 *| req->op = SET_EVENT;
280 *| ret = wine_server_call( req );
281 *| }
282 *| SERVER_END_REQ;
284 unsigned int wine_server_call( void *req_ptr )
286 struct __server_request_info * const req = req_ptr;
287 sigset_t old_set;
288 unsigned int ret;
290 pthread_sigmask( SIG_BLOCK, &server_block_set, &old_set );
291 ret = send_request( req );
292 if (!ret) ret = wait_reply( req );
293 pthread_sigmask( SIG_SETMASK, &old_set, NULL );
294 return ret;
298 /***********************************************************************
299 * server_enter_uninterrupted_section
301 void server_enter_uninterrupted_section( RTL_CRITICAL_SECTION *cs, sigset_t *sigset )
303 pthread_sigmask( SIG_BLOCK, &server_block_set, sigset );
304 RtlEnterCriticalSection( cs );
308 /***********************************************************************
309 * server_leave_uninterrupted_section
311 void server_leave_uninterrupted_section( RTL_CRITICAL_SECTION *cs, sigset_t *sigset )
313 RtlLeaveCriticalSection( cs );
314 pthread_sigmask( SIG_SETMASK, sigset, NULL );
318 /***********************************************************************
319 * wine_server_send_fd (NTDLL.@)
321 * Send a file descriptor to the server.
323 * PARAMS
324 * fd [I] file descriptor to send
326 * RETURNS
327 * nothing
329 void CDECL wine_server_send_fd( int fd )
331 struct send_fd data;
332 struct msghdr msghdr;
333 struct iovec vec;
334 int ret;
336 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
337 msghdr.msg_accrights = (void *)&fd;
338 msghdr.msg_accrightslen = sizeof(fd);
339 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
340 char cmsg_buffer[256];
341 struct cmsghdr *cmsg;
342 msghdr.msg_control = cmsg_buffer;
343 msghdr.msg_controllen = sizeof(cmsg_buffer);
344 msghdr.msg_flags = 0;
345 cmsg = CMSG_FIRSTHDR( &msghdr );
346 cmsg->cmsg_len = CMSG_LEN( sizeof(fd) );
347 cmsg->cmsg_level = SOL_SOCKET;
348 cmsg->cmsg_type = SCM_RIGHTS;
349 *(int *)CMSG_DATA(cmsg) = fd;
350 msghdr.msg_controllen = cmsg->cmsg_len;
351 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
353 msghdr.msg_name = NULL;
354 msghdr.msg_namelen = 0;
355 msghdr.msg_iov = &vec;
356 msghdr.msg_iovlen = 1;
358 vec.iov_base = (void *)&data;
359 vec.iov_len = sizeof(data);
361 data.tid = GetCurrentThreadId();
362 data.fd = fd;
364 for (;;)
366 if ((ret = sendmsg( fd_socket, &msghdr, 0 )) == sizeof(data)) return;
367 if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
368 if (errno == EINTR) continue;
369 if (errno == EPIPE) abort_thread(0);
370 server_protocol_perror( "sendmsg" );
375 /***********************************************************************
376 * receive_fd
378 * Receive a file descriptor passed from the server.
380 static int receive_fd( obj_handle_t *handle )
382 struct iovec vec;
383 struct msghdr msghdr;
384 int ret, fd = -1;
386 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
387 msghdr.msg_accrights = (void *)&fd;
388 msghdr.msg_accrightslen = sizeof(fd);
389 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
390 char cmsg_buffer[256];
391 msghdr.msg_control = cmsg_buffer;
392 msghdr.msg_controllen = sizeof(cmsg_buffer);
393 msghdr.msg_flags = 0;
394 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
396 msghdr.msg_name = NULL;
397 msghdr.msg_namelen = 0;
398 msghdr.msg_iov = &vec;
399 msghdr.msg_iovlen = 1;
400 vec.iov_base = (void *)handle;
401 vec.iov_len = sizeof(*handle);
403 for (;;)
405 if ((ret = recvmsg( fd_socket, &msghdr, MSG_CMSG_CLOEXEC )) > 0)
407 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
408 struct cmsghdr *cmsg;
409 for (cmsg = CMSG_FIRSTHDR( &msghdr ); cmsg; cmsg = CMSG_NXTHDR( &msghdr, cmsg ))
411 if (cmsg->cmsg_level != SOL_SOCKET) continue;
412 if (cmsg->cmsg_type == SCM_RIGHTS) fd = *(int *)CMSG_DATA(cmsg);
413 #ifdef SCM_CREDENTIALS
414 else if (cmsg->cmsg_type == SCM_CREDENTIALS)
416 struct ucred *ucred = (struct ucred *)CMSG_DATA(cmsg);
417 server_pid = ucred->pid;
419 #endif
421 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
422 if (fd != -1) fcntl( fd, F_SETFD, FD_CLOEXEC ); /* in case MSG_CMSG_CLOEXEC is not supported */
423 return fd;
425 if (!ret) break;
426 if (errno == EINTR) continue;
427 if (errno == EPIPE) break;
428 server_protocol_perror("recvmsg");
430 /* the server closed the connection; time to die... */
431 abort_thread(0);
435 /***********************************************************************/
436 /* fd cache support */
438 struct fd_cache_entry
440 int fd;
441 enum server_fd_type type : 6;
442 unsigned int access : 2;
443 unsigned int options : 24;
446 #define FD_CACHE_BLOCK_SIZE (65536 / sizeof(struct fd_cache_entry))
447 #define FD_CACHE_ENTRIES 128
449 static struct fd_cache_entry *fd_cache[FD_CACHE_ENTRIES];
450 static struct fd_cache_entry fd_cache_initial_block[FD_CACHE_BLOCK_SIZE];
452 static inline unsigned int handle_to_index( HANDLE handle, unsigned int *entry )
454 unsigned int idx = (wine_server_obj_handle(handle) >> 2) - 1;
455 *entry = idx / FD_CACHE_BLOCK_SIZE;
456 return idx % FD_CACHE_BLOCK_SIZE;
460 /***********************************************************************
461 * add_fd_to_cache
463 * Caller must hold fd_cache_section.
465 static int add_fd_to_cache( HANDLE handle, int fd, enum server_fd_type type,
466 unsigned int access, unsigned int options )
468 unsigned int entry, idx = handle_to_index( handle, &entry );
469 int prev_fd;
471 if (entry >= FD_CACHE_ENTRIES)
473 FIXME( "too many allocated handles, not caching %p\n", handle );
474 return 0;
477 if (!fd_cache[entry]) /* do we need to allocate a new block of entries? */
479 if (!entry) fd_cache[0] = fd_cache_initial_block;
480 else
482 void *ptr = wine_anon_mmap( NULL, FD_CACHE_BLOCK_SIZE * sizeof(struct fd_cache_entry),
483 PROT_READ | PROT_WRITE, 0 );
484 if (ptr == MAP_FAILED) return 0;
485 fd_cache[entry] = ptr;
488 /* store fd+1 so that 0 can be used as the unset value */
489 prev_fd = interlocked_xchg( &fd_cache[entry][idx].fd, fd + 1 ) - 1;
490 fd_cache[entry][idx].type = type;
491 fd_cache[entry][idx].access = access;
492 fd_cache[entry][idx].options = options;
493 if (prev_fd != -1) close( prev_fd );
494 return 1;
498 /***********************************************************************
499 * get_cached_fd
501 * Caller must hold fd_cache_section.
503 static inline int get_cached_fd( HANDLE handle, enum server_fd_type *type,
504 unsigned int *access, unsigned int *options )
506 unsigned int entry, idx = handle_to_index( handle, &entry );
507 int fd = -1;
509 if (entry < FD_CACHE_ENTRIES && fd_cache[entry])
511 fd = fd_cache[entry][idx].fd - 1;
512 if (type) *type = fd_cache[entry][idx].type;
513 if (access) *access = fd_cache[entry][idx].access;
514 if (options) *options = fd_cache[entry][idx].options;
516 return fd;
520 /***********************************************************************
521 * server_remove_fd_from_cache
523 int server_remove_fd_from_cache( HANDLE handle )
525 unsigned int entry, idx = handle_to_index( handle, &entry );
526 int fd = -1;
528 if (entry < FD_CACHE_ENTRIES && fd_cache[entry])
529 fd = interlocked_xchg( &fd_cache[entry][idx].fd, 0 ) - 1;
531 return fd;
535 /***********************************************************************
536 * server_get_unix_fd
538 * The returned unix_fd should be closed iff needs_close is non-zero.
540 int server_get_unix_fd( HANDLE handle, unsigned int wanted_access, int *unix_fd,
541 int *needs_close, enum server_fd_type *type, unsigned int *options )
543 sigset_t sigset;
544 obj_handle_t fd_handle;
545 int ret = 0, fd;
546 unsigned int access = 0;
548 *unix_fd = -1;
549 *needs_close = 0;
550 wanted_access &= FILE_READ_DATA | FILE_WRITE_DATA;
552 server_enter_uninterrupted_section( &fd_cache_section, &sigset );
554 fd = get_cached_fd( handle, type, &access, options );
555 if (fd != -1) goto done;
557 SERVER_START_REQ( get_handle_fd )
559 req->handle = wine_server_obj_handle( handle );
560 if (!(ret = wine_server_call( req )))
562 if (type) *type = reply->type;
563 if (options) *options = reply->options;
564 access = reply->access;
565 if ((fd = receive_fd( &fd_handle )) != -1)
567 assert( wine_server_ptr_handle(fd_handle) == handle );
568 *needs_close = (!reply->cacheable ||
569 !add_fd_to_cache( handle, fd, reply->type,
570 reply->access, reply->options ));
572 else ret = STATUS_TOO_MANY_OPENED_FILES;
575 SERVER_END_REQ;
577 done:
578 server_leave_uninterrupted_section( &fd_cache_section, &sigset );
579 if (!ret && ((access & wanted_access) != wanted_access))
581 ret = STATUS_ACCESS_DENIED;
582 if (*needs_close) close( fd );
584 if (!ret) *unix_fd = fd;
585 return ret;
589 /***********************************************************************
590 * wine_server_fd_to_handle (NTDLL.@)
592 * Allocate a file handle for a Unix file descriptor.
594 * PARAMS
595 * fd [I] Unix file descriptor.
596 * access [I] Win32 access flags.
597 * attributes [I] Object attributes.
598 * handle [O] Address where Wine file handle will be stored.
600 * RETURNS
601 * NTSTATUS code
603 int CDECL wine_server_fd_to_handle( int fd, unsigned int access, unsigned int attributes, HANDLE *handle )
605 int ret;
607 *handle = 0;
608 wine_server_send_fd( fd );
610 SERVER_START_REQ( alloc_file_handle )
612 req->access = access;
613 req->attributes = attributes;
614 req->fd = fd;
615 if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
617 SERVER_END_REQ;
618 return ret;
622 /***********************************************************************
623 * wine_server_handle_to_fd (NTDLL.@)
625 * Retrieve the file descriptor corresponding to a file handle.
627 * PARAMS
628 * handle [I] Wine file handle.
629 * access [I] Win32 file access rights requested.
630 * unix_fd [O] Address where Unix file descriptor will be stored.
631 * options [O] Address where the file open options will be stored. Optional.
633 * RETURNS
634 * NTSTATUS code
636 int CDECL wine_server_handle_to_fd( HANDLE handle, unsigned int access, int *unix_fd,
637 unsigned int *options )
639 int needs_close, ret = server_get_unix_fd( handle, access, unix_fd, &needs_close, NULL, options );
641 if (!ret && !needs_close)
643 if ((*unix_fd = dup(*unix_fd)) == -1) ret = FILE_GetNtStatus();
645 return ret;
649 /***********************************************************************
650 * wine_server_release_fd (NTDLL.@)
652 * Release the Unix file descriptor returned by wine_server_handle_to_fd.
654 * PARAMS
655 * handle [I] Wine file handle.
656 * unix_fd [I] Unix file descriptor to release.
658 * RETURNS
659 * nothing
661 void CDECL wine_server_release_fd( HANDLE handle, int unix_fd )
663 close( unix_fd );
667 /***********************************************************************
668 * server_pipe
670 * Create a pipe for communicating with the server.
672 int server_pipe( int fd[2] )
674 int ret;
675 #ifdef HAVE_PIPE2
676 static int have_pipe2 = 1;
678 if (have_pipe2)
680 if (!(ret = pipe2( fd, O_CLOEXEC ))) return ret;
681 if (errno == ENOSYS || errno == EINVAL) have_pipe2 = 0; /* don't try again */
683 #endif
684 if (!(ret = pipe( fd )))
686 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
687 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
689 return ret;
693 /***********************************************************************
694 * start_server
696 * Start a new wine server.
698 static void start_server(void)
700 static int started; /* we only try once */
701 char *argv[3];
702 static char wineserver[] = "server/wineserver";
703 static char debug[] = "-d";
705 if (!started)
707 int status;
708 int pid = fork();
709 if (pid == -1) fatal_perror( "fork" );
710 if (!pid)
712 argv[0] = wineserver;
713 argv[1] = TRACE_ON(server) ? debug : NULL;
714 argv[2] = NULL;
715 wine_exec_wine_binary( argv[0], argv, getenv("WINESERVER") );
716 fatal_error( "could not exec wineserver\n" );
718 waitpid( pid, &status, 0 );
719 status = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
720 if (status == 2) return; /* server lock held by someone else, will retry later */
721 if (status) exit(status); /* server failed */
722 started = 1;
727 /***********************************************************************
728 * setup_config_dir
730 * Setup the wine configuration dir.
732 static void setup_config_dir(void)
734 const char *p, *config_dir = wine_get_config_dir();
736 if (chdir( config_dir ) == -1)
738 if (errno != ENOENT) fatal_perror( "chdir to %s\n", config_dir );
740 if ((p = strrchr( config_dir, '/' )) && p != config_dir)
742 struct stat st;
743 char *tmp_dir;
745 if (!(tmp_dir = malloc( p + 1 - config_dir ))) fatal_error( "out of memory\n" );
746 memcpy( tmp_dir, config_dir, p - config_dir );
747 tmp_dir[p - config_dir] = 0;
748 if (!stat( tmp_dir, &st ) && st.st_uid != getuid())
749 fatal_error( "'%s' is not owned by you, refusing to create a configuration directory there\n",
750 tmp_dir );
751 free( tmp_dir );
754 mkdir( config_dir, 0777 );
755 if (chdir( config_dir ) == -1) fatal_perror( "chdir to %s\n", config_dir );
757 if ((p = getenv( "WINEARCH" )) && !strcmp( p, "win32" ))
759 /* force creation of a 32-bit prefix */
760 int fd = open( "system.reg", O_WRONLY | O_CREAT | O_EXCL, 0666 );
761 if (fd != -1)
763 static const char regfile[] = "WINE REGISTRY Version 2\n\n#arch=win32\n";
764 write( fd, regfile, sizeof(regfile) - 1 );
765 close( fd );
768 MESSAGE( "wine: created the configuration directory '%s'\n", config_dir );
771 if (mkdir( "dosdevices", 0777 ) == -1)
773 if (errno == EEXIST) return;
774 fatal_perror( "cannot create %s/dosdevices\n", config_dir );
777 /* create the drive symlinks */
779 mkdir( "drive_c", 0777 );
780 symlink( "../drive_c", "dosdevices/c:" );
781 symlink( "/", "dosdevices/z:" );
785 /***********************************************************************
786 * server_connect_error
788 * Try to display a meaningful explanation of why we couldn't connect
789 * to the server.
791 static void server_connect_error( const char *serverdir )
793 int fd;
794 struct flock fl;
796 if ((fd = open( LOCKNAME, O_WRONLY )) == -1)
797 fatal_error( "for some mysterious reason, the wine server never started.\n" );
799 fl.l_type = F_WRLCK;
800 fl.l_whence = SEEK_SET;
801 fl.l_start = 0;
802 fl.l_len = 1;
803 if (fcntl( fd, F_GETLK, &fl ) != -1)
805 if (fl.l_type == F_WRLCK) /* the file is locked */
806 fatal_error( "a wine server seems to be running, but I cannot connect to it.\n"
807 " You probably need to kill that process (it might be pid %d).\n",
808 (int)fl.l_pid );
809 fatal_error( "for some mysterious reason, the wine server failed to run.\n" );
811 fatal_error( "the file system of '%s' doesn't support locks,\n"
812 " and there is a 'socket' file in that directory that prevents wine from starting.\n"
813 " You should make sure no wine server is running, remove that file and try again.\n",
814 serverdir );
818 /***********************************************************************
819 * server_connect
821 * Attempt to connect to an existing server socket.
822 * We need to be in the server directory already.
824 static int server_connect(void)
826 const char *serverdir;
827 struct sockaddr_un addr;
828 struct stat st;
829 int s, slen, retry, fd_cwd;
831 /* retrieve the current directory */
832 fd_cwd = open( ".", O_RDONLY );
833 if (fd_cwd != -1) fcntl( fd_cwd, F_SETFD, 1 ); /* set close on exec flag */
835 setup_config_dir();
836 serverdir = wine_get_server_dir();
838 /* chdir to the server directory */
839 if (chdir( serverdir ) == -1)
841 if (errno != ENOENT) fatal_perror( "chdir to %s", serverdir );
842 start_server();
843 if (chdir( serverdir ) == -1) fatal_perror( "chdir to %s", serverdir );
846 /* make sure we are at the right place */
847 if (stat( ".", &st ) == -1) fatal_perror( "stat %s", serverdir );
848 if (st.st_uid != getuid()) fatal_error( "'%s' is not owned by you\n", serverdir );
849 if (st.st_mode & 077) fatal_error( "'%s' must not be accessible by other users\n", serverdir );
851 for (retry = 0; retry < 6; retry++)
853 /* if not the first try, wait a bit to leave the previous server time to exit */
854 if (retry)
856 usleep( 100000 * retry * retry );
857 start_server();
858 if (lstat( SOCKETNAME, &st ) == -1) continue; /* still no socket, wait a bit more */
860 else if (lstat( SOCKETNAME, &st ) == -1) /* check for an already existing socket */
862 if (errno != ENOENT) fatal_perror( "lstat %s/%s", serverdir, SOCKETNAME );
863 start_server();
864 if (lstat( SOCKETNAME, &st ) == -1) continue; /* still no socket, wait a bit more */
867 /* make sure the socket is sane (ISFIFO needed for Solaris) */
868 if (!S_ISSOCK(st.st_mode) && !S_ISFIFO(st.st_mode))
869 fatal_error( "'%s/%s' is not a socket\n", serverdir, SOCKETNAME );
870 if (st.st_uid != getuid())
871 fatal_error( "'%s/%s' is not owned by you\n", serverdir, SOCKETNAME );
873 /* try to connect to it */
874 addr.sun_family = AF_UNIX;
875 strcpy( addr.sun_path, SOCKETNAME );
876 slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
877 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
878 addr.sun_len = slen;
879 #endif
880 if ((s = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_perror( "socket" );
881 if (connect( s, (struct sockaddr *)&addr, slen ) != -1)
883 /* switch back to the starting directory */
884 if (fd_cwd != -1)
886 fchdir( fd_cwd );
887 close( fd_cwd );
889 fcntl( s, F_SETFD, 1 ); /* set close on exec flag */
890 return s;
892 close( s );
894 server_connect_error( serverdir );
898 #ifdef __APPLE__
899 #include <mach/mach.h>
900 #include <mach/mach_error.h>
901 #include <servers/bootstrap.h>
903 /* send our task port to the server */
904 static void send_server_task_port(void)
906 mach_port_t bootstrap_port, wineserver_port;
907 kern_return_t kret;
909 struct {
910 mach_msg_header_t header;
911 mach_msg_body_t body;
912 mach_msg_port_descriptor_t task_port;
913 } msg;
915 if (task_get_bootstrap_port(mach_task_self(), &bootstrap_port) != KERN_SUCCESS) return;
917 kret = bootstrap_look_up(bootstrap_port, (char*)wine_get_server_dir(), &wineserver_port);
918 if (kret != KERN_SUCCESS)
919 fatal_error( "cannot find the server port: 0x%08x\n", kret );
921 mach_port_deallocate(mach_task_self(), bootstrap_port);
923 msg.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0) | MACH_MSGH_BITS_COMPLEX;
924 msg.header.msgh_size = sizeof(msg);
925 msg.header.msgh_remote_port = wineserver_port;
926 msg.header.msgh_local_port = MACH_PORT_NULL;
928 msg.body.msgh_descriptor_count = 1;
929 msg.task_port.name = mach_task_self();
930 msg.task_port.disposition = MACH_MSG_TYPE_COPY_SEND;
931 msg.task_port.type = MACH_MSG_PORT_DESCRIPTOR;
933 kret = mach_msg_send(&msg.header);
934 if (kret != KERN_SUCCESS)
935 server_protocol_error( "mach_msg_send failed: 0x%08x\n", kret );
937 mach_port_deallocate(mach_task_self(), wineserver_port);
939 #endif /* __APPLE__ */
942 /***********************************************************************
943 * get_unix_tid
945 * Retrieve the Unix tid to use on the server side for the current thread.
947 static int get_unix_tid(void)
949 int ret = -1;
950 #ifdef HAVE_PTHREAD_GETTHREADID_NP
951 ret = pthread_getthreadid_np();
952 #elif defined(linux)
953 ret = syscall( SYS_gettid );
954 #elif defined(__sun)
955 ret = pthread_self();
956 #elif defined(__APPLE__)
957 ret = mach_thread_self();
958 mach_port_deallocate(mach_task_self(), ret);
959 #elif defined(__FreeBSD__)
960 long lwpid;
961 thr_self( &lwpid );
962 ret = lwpid;
963 #elif defined(__DragonFly__)
964 ret = lwp_gettid();
965 #endif
966 return ret;
970 /***********************************************************************
971 * server_init_process
973 * Start the server and create the initial socket pair.
975 void server_init_process(void)
977 obj_handle_t version;
978 const char *env_socket = getenv( "WINESERVERSOCKET" );
980 server_pid = -1;
981 if (env_socket)
983 fd_socket = atoi( env_socket );
984 if (fcntl( fd_socket, F_SETFD, 1 ) == -1)
985 fatal_perror( "Bad server socket %d", fd_socket );
986 unsetenv( "WINESERVERSOCKET" );
988 else fd_socket = server_connect();
990 /* setup the signal mask */
991 sigemptyset( &server_block_set );
992 sigaddset( &server_block_set, SIGALRM );
993 sigaddset( &server_block_set, SIGIO );
994 sigaddset( &server_block_set, SIGINT );
995 sigaddset( &server_block_set, SIGHUP );
996 sigaddset( &server_block_set, SIGUSR1 );
997 sigaddset( &server_block_set, SIGUSR2 );
998 sigaddset( &server_block_set, SIGCHLD );
999 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
1001 /* receive the first thread request fd on the main socket */
1002 #ifdef SO_PASSCRED
1003 if (server_pid == -1)
1005 int enable = 1;
1006 setsockopt( fd_socket, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
1007 ntdll_get_thread_data()->request_fd = receive_fd( &version );
1008 enable = 0;
1009 setsockopt( fd_socket, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
1011 else
1012 #endif
1013 ntdll_get_thread_data()->request_fd = receive_fd( &version );
1015 if (version != SERVER_PROTOCOL_VERSION)
1016 server_protocol_error( "version mismatch %d/%d.\n"
1017 "Your %s binary was not upgraded correctly,\n"
1018 "or you have an older one somewhere in your PATH.\n"
1019 "Or maybe the wrong wineserver is still running?\n",
1020 version, SERVER_PROTOCOL_VERSION,
1021 (version > SERVER_PROTOCOL_VERSION) ? "wine" : "wineserver" );
1022 #ifdef __APPLE__
1023 send_server_task_port();
1024 #endif
1025 #if defined(__linux__) && defined(HAVE_PRCTL)
1026 /* work around Ubuntu's ptrace breakage */
1027 if (server_pid != -1) prctl( 0x59616d61 /* PR_SET_PTRACER */, server_pid );
1028 #endif
1032 /***********************************************************************
1033 * server_init_process_done
1035 NTSTATUS server_init_process_done(void)
1037 PEB *peb = NtCurrentTeb()->Peb;
1038 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
1039 NTSTATUS status;
1041 /* Install signal handlers; this cannot be done earlier, since we cannot
1042 * send exceptions to the debugger before the create process event that
1043 * is sent by REQ_INIT_PROCESS_DONE.
1044 * We do need the handlers in place by the time the request is over, so
1045 * we set them up here. If we segfault between here and the server call
1046 * something is very wrong... */
1047 signal_init_process();
1049 /* Signal the parent process to continue */
1050 SERVER_START_REQ( init_process_done )
1052 req->module = wine_server_client_ptr( peb->ImageBaseAddress );
1053 #ifdef __i386__
1054 req->ldt_copy = wine_server_client_ptr( &wine_ldt_copy );
1055 #endif
1056 req->entry = wine_server_client_ptr( (char *)peb->ImageBaseAddress + nt->OptionalHeader.AddressOfEntryPoint );
1057 req->gui = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
1058 status = wine_server_call( req );
1060 SERVER_END_REQ;
1062 return status;
1066 /***********************************************************************
1067 * server_init_thread
1069 * Send an init thread request. Return 0 if OK.
1071 size_t server_init_thread( void *entry_point )
1073 static const int is_win64 = (sizeof(void *) > sizeof(int));
1074 const char *arch = getenv( "WINEARCH" );
1075 int ret;
1076 int reply_pipe[2];
1077 struct sigaction sig_act;
1078 size_t info_size;
1080 sig_act.sa_handler = SIG_IGN;
1081 sig_act.sa_flags = 0;
1082 sigemptyset( &sig_act.sa_mask );
1084 /* ignore SIGPIPE so that we get an EPIPE error instead */
1085 sigaction( SIGPIPE, &sig_act, NULL );
1087 /* create the server->client communication pipes */
1088 if (server_pipe( reply_pipe ) == -1) server_protocol_perror( "pipe" );
1089 if (server_pipe( ntdll_get_thread_data()->wait_fd ) == -1) server_protocol_perror( "pipe" );
1090 wine_server_send_fd( reply_pipe[1] );
1091 wine_server_send_fd( ntdll_get_thread_data()->wait_fd[1] );
1092 ntdll_get_thread_data()->reply_fd = reply_pipe[0];
1093 close( reply_pipe[1] );
1095 SERVER_START_REQ( init_thread )
1097 req->unix_pid = getpid();
1098 req->unix_tid = get_unix_tid();
1099 req->teb = wine_server_client_ptr( NtCurrentTeb() );
1100 req->entry = wine_server_client_ptr( entry_point );
1101 req->reply_fd = reply_pipe[1];
1102 req->wait_fd = ntdll_get_thread_data()->wait_fd[1];
1103 req->debug_level = (TRACE_ON(server) != 0);
1104 req->cpu = client_cpu;
1105 ret = wine_server_call( req );
1106 NtCurrentTeb()->ClientId.UniqueProcess = ULongToHandle(reply->pid);
1107 NtCurrentTeb()->ClientId.UniqueThread = ULongToHandle(reply->tid);
1108 info_size = reply->info_size;
1109 server_start_time = reply->server_start;
1110 server_cpus = reply->all_cpus;
1112 SERVER_END_REQ;
1114 is_wow64 = !is_win64 && (server_cpus & (1 << CPU_x86_64)) != 0;
1115 ntdll_get_thread_data()->wow64_redir = is_wow64;
1117 switch (ret)
1119 case STATUS_SUCCESS:
1120 if (arch)
1122 if (!strcmp( arch, "win32" ) && (is_win64 || is_wow64))
1123 fatal_error( "WINEARCH set to win32 but '%s' is a 64-bit installation.\n",
1124 wine_get_config_dir() );
1125 if (!strcmp( arch, "win64" ) && !is_win64 && !is_wow64)
1126 fatal_error( "WINEARCH set to win64 but '%s' is a 32-bit installation.\n",
1127 wine_get_config_dir() );
1129 return info_size;
1130 case STATUS_NOT_REGISTRY_FILE:
1131 fatal_error( "'%s' is a 32-bit installation, it cannot support 64-bit applications.\n",
1132 wine_get_config_dir() );
1133 case STATUS_NOT_SUPPORTED:
1134 if (is_win64)
1135 fatal_error( "wineserver is 32-bit, it cannot support 64-bit applications.\n" );
1136 else
1137 fatal_error( "'%s' is a 64-bit installation, it cannot be used with a 32-bit wineserver.\n",
1138 wine_get_config_dir() );
1139 default:
1140 server_protocol_error( "init_thread failed with status %x\n", ret );