quartz: Handle state changes in direct sound renderer correctly.
[wine/multimedia.git] / dlls / ntdll / server.c
blobdf46935c304249bd4443746c3fad6eee76690d58
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_PRCTL_H
49 # include <sys/prctl.h>
50 #endif
51 #ifdef HAVE_SYS_STAT_H
52 # include <sys/stat.h>
53 #endif
54 #ifdef HAVE_SYS_UIO_H
55 #include <sys/uio.h>
56 #endif
57 #ifdef HAVE_SYS_THR_H
58 #include <sys/ucontext.h>
59 #include <sys/thr.h>
60 #endif
61 #ifdef HAVE_UNISTD_H
62 # include <unistd.h>
63 #endif
65 #include "ntstatus.h"
66 #define WIN32_NO_STATUS
67 #include "wine/library.h"
68 #include "wine/server.h"
69 #include "wine/debug.h"
70 #include "ntdll_misc.h"
72 WINE_DEFAULT_DEBUG_CHANNEL(server);
74 /* Some versions of glibc don't define this */
75 #ifndef SCM_RIGHTS
76 #define SCM_RIGHTS 1
77 #endif
79 #ifndef MSG_CMSG_CLOEXEC
80 #define MSG_CMSG_CLOEXEC 0
81 #endif
83 #define SOCKETNAME "socket" /* name of the socket file */
84 #define LOCKNAME "lock" /* name of the lock file */
86 #ifdef __i386__
87 static const enum cpu_type client_cpu = CPU_x86;
88 #elif defined(__x86_64__)
89 static const enum cpu_type client_cpu = CPU_x86_64;
90 #elif defined(__ALPHA__)
91 static const enum cpu_type client_cpu = CPU_ALPHA;
92 #elif defined(__powerpc__)
93 static const enum cpu_type client_cpu = CPU_POWERPC;
94 #elif defined(__sparc__)
95 static const enum cpu_type client_cpu = CPU_SPARC;
96 #elif defined(__arm__)
97 static const enum cpu_type client_cpu = CPU_ARM;
98 #else
99 #error Unsupported CPU
100 #endif
102 unsigned int server_cpus = 0;
103 int is_wow64 = FALSE;
105 timeout_t server_start_time = 0; /* time of server startup */
107 sigset_t server_block_set; /* signals to block during server calls */
108 static int fd_socket = -1; /* socket to exchange file descriptors with the server */
109 static pid_t server_pid;
111 static RTL_CRITICAL_SECTION fd_cache_section;
112 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
114 0, 0, &fd_cache_section,
115 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
116 0, 0, { (DWORD_PTR)(__FILE__ ": fd_cache_section") }
118 static RTL_CRITICAL_SECTION fd_cache_section = { &critsect_debug, -1, 0, 0, 0, 0 };
121 #ifdef __GNUC__
122 static void fatal_error( const char *err, ... ) __attribute__((noreturn, format(printf,1,2)));
123 static void fatal_perror( const char *err, ... ) __attribute__((noreturn, format(printf,1,2)));
124 static void server_connect_error( const char *serverdir ) __attribute__((noreturn));
125 #endif
127 /* die on a fatal error; use only during initialization */
128 static void fatal_error( const char *err, ... )
130 va_list args;
132 va_start( args, err );
133 fprintf( stderr, "wine: " );
134 vfprintf( stderr, err, args );
135 va_end( args );
136 exit(1);
139 /* die on a fatal error; use only during initialization */
140 static void fatal_perror( const char *err, ... )
142 va_list args;
144 va_start( args, err );
145 fprintf( stderr, "wine: " );
146 vfprintf( stderr, err, args );
147 perror( " " );
148 va_end( args );
149 exit(1);
153 /***********************************************************************
154 * server_protocol_error
156 void server_protocol_error( const char *err, ... )
158 va_list args;
160 va_start( args, err );
161 fprintf( stderr, "wine client error:%x: ", GetCurrentThreadId() );
162 vfprintf( stderr, err, args );
163 va_end( args );
164 abort_thread(1);
168 /***********************************************************************
169 * server_protocol_perror
171 void server_protocol_perror( const char *err )
173 fprintf( stderr, "wine client error:%x: ", GetCurrentThreadId() );
174 perror( err );
175 abort_thread(1);
179 /***********************************************************************
180 * send_request
182 * Send a request to the server.
184 static unsigned int send_request( const struct __server_request_info *req )
186 unsigned int i;
187 int ret;
189 if (!req->u.req.request_header.request_size)
191 if ((ret = write( ntdll_get_thread_data()->request_fd, &req->u.req,
192 sizeof(req->u.req) )) == sizeof(req->u.req)) return STATUS_SUCCESS;
195 else
197 struct iovec vec[__SERVER_MAX_DATA+1];
199 vec[0].iov_base = (void *)&req->u.req;
200 vec[0].iov_len = sizeof(req->u.req);
201 for (i = 0; i < req->data_count; i++)
203 vec[i+1].iov_base = (void *)req->data[i].ptr;
204 vec[i+1].iov_len = req->data[i].size;
206 if ((ret = writev( ntdll_get_thread_data()->request_fd, vec, i+1 )) ==
207 req->u.req.request_header.request_size + sizeof(req->u.req)) return STATUS_SUCCESS;
210 if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
211 if (errno == EPIPE) abort_thread(0);
212 if (errno == EFAULT) return STATUS_ACCESS_VIOLATION;
213 server_protocol_perror( "write" );
217 /***********************************************************************
218 * read_reply_data
220 * Read data from the reply buffer; helper for wait_reply.
222 static void read_reply_data( void *buffer, size_t size )
224 int ret;
226 for (;;)
228 if ((ret = read( ntdll_get_thread_data()->reply_fd, buffer, size )) > 0)
230 if (!(size -= ret)) return;
231 buffer = (char *)buffer + ret;
232 continue;
234 if (!ret) break;
235 if (errno == EINTR) continue;
236 if (errno == EPIPE) break;
237 server_protocol_perror("read");
239 /* the server closed the connection; time to die... */
240 abort_thread(0);
244 /***********************************************************************
245 * wait_reply
247 * Wait for a reply from the server.
249 static inline unsigned int wait_reply( struct __server_request_info *req )
251 read_reply_data( &req->u.reply, sizeof(req->u.reply) );
252 if (req->u.reply.reply_header.reply_size)
253 read_reply_data( req->reply_data, req->u.reply.reply_header.reply_size );
254 return req->u.reply.reply_header.error;
258 /***********************************************************************
259 * wine_server_call (NTDLL.@)
261 * Perform a server call.
263 * PARAMS
264 * req_ptr [I/O] Function dependent data
266 * RETURNS
267 * Depends on server function being called, but usually an NTSTATUS code.
269 * NOTES
270 * Use the SERVER_START_REQ and SERVER_END_REQ to help you fill out the
271 * server request structure for the particular call. E.g:
272 *| SERVER_START_REQ( event_op )
273 *| {
274 *| req->handle = handle;
275 *| req->op = SET_EVENT;
276 *| ret = wine_server_call( req );
277 *| }
278 *| SERVER_END_REQ;
280 unsigned int wine_server_call( void *req_ptr )
282 struct __server_request_info * const req = req_ptr;
283 sigset_t old_set;
284 unsigned int ret;
286 pthread_sigmask( SIG_BLOCK, &server_block_set, &old_set );
287 ret = send_request( req );
288 if (!ret) ret = wait_reply( req );
289 pthread_sigmask( SIG_SETMASK, &old_set, NULL );
290 return ret;
294 /***********************************************************************
295 * server_enter_uninterrupted_section
297 void server_enter_uninterrupted_section( RTL_CRITICAL_SECTION *cs, sigset_t *sigset )
299 pthread_sigmask( SIG_BLOCK, &server_block_set, sigset );
300 RtlEnterCriticalSection( cs );
304 /***********************************************************************
305 * server_leave_uninterrupted_section
307 void server_leave_uninterrupted_section( RTL_CRITICAL_SECTION *cs, sigset_t *sigset )
309 RtlLeaveCriticalSection( cs );
310 pthread_sigmask( SIG_SETMASK, sigset, NULL );
314 /***********************************************************************
315 * wine_server_send_fd (NTDLL.@)
317 * Send a file descriptor to the server.
319 * PARAMS
320 * fd [I] file descriptor to send
322 * RETURNS
323 * nothing
325 void CDECL wine_server_send_fd( int fd )
327 struct send_fd data;
328 struct msghdr msghdr;
329 struct iovec vec;
330 int ret;
332 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
333 msghdr.msg_accrights = (void *)&fd;
334 msghdr.msg_accrightslen = sizeof(fd);
335 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
336 char cmsg_buffer[256];
337 struct cmsghdr *cmsg;
338 msghdr.msg_control = cmsg_buffer;
339 msghdr.msg_controllen = sizeof(cmsg_buffer);
340 msghdr.msg_flags = 0;
341 cmsg = CMSG_FIRSTHDR( &msghdr );
342 cmsg->cmsg_len = CMSG_LEN( sizeof(fd) );
343 cmsg->cmsg_level = SOL_SOCKET;
344 cmsg->cmsg_type = SCM_RIGHTS;
345 *(int *)CMSG_DATA(cmsg) = fd;
346 msghdr.msg_controllen = cmsg->cmsg_len;
347 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
349 msghdr.msg_name = NULL;
350 msghdr.msg_namelen = 0;
351 msghdr.msg_iov = &vec;
352 msghdr.msg_iovlen = 1;
354 vec.iov_base = (void *)&data;
355 vec.iov_len = sizeof(data);
357 data.tid = GetCurrentThreadId();
358 data.fd = fd;
360 for (;;)
362 if ((ret = sendmsg( fd_socket, &msghdr, 0 )) == sizeof(data)) return;
363 if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
364 if (errno == EINTR) continue;
365 if (errno == EPIPE) abort_thread(0);
366 server_protocol_perror( "sendmsg" );
371 /***********************************************************************
372 * receive_fd
374 * Receive a file descriptor passed from the server.
376 static int receive_fd( obj_handle_t *handle )
378 struct iovec vec;
379 struct msghdr msghdr;
380 int ret, fd = -1;
382 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
383 msghdr.msg_accrights = (void *)&fd;
384 msghdr.msg_accrightslen = sizeof(fd);
385 #else /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
386 char cmsg_buffer[256];
387 msghdr.msg_control = cmsg_buffer;
388 msghdr.msg_controllen = sizeof(cmsg_buffer);
389 msghdr.msg_flags = 0;
390 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
392 msghdr.msg_name = NULL;
393 msghdr.msg_namelen = 0;
394 msghdr.msg_iov = &vec;
395 msghdr.msg_iovlen = 1;
396 vec.iov_base = (void *)handle;
397 vec.iov_len = sizeof(*handle);
399 for (;;)
401 if ((ret = recvmsg( fd_socket, &msghdr, MSG_CMSG_CLOEXEC )) > 0)
403 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
404 struct cmsghdr *cmsg;
405 for (cmsg = CMSG_FIRSTHDR( &msghdr ); cmsg; cmsg = CMSG_NXTHDR( &msghdr, cmsg ))
407 if (cmsg->cmsg_level != SOL_SOCKET) continue;
408 if (cmsg->cmsg_type == SCM_RIGHTS) fd = *(int *)CMSG_DATA(cmsg);
409 #ifdef SCM_CREDENTIALS
410 else if (cmsg->cmsg_type == SCM_CREDENTIALS)
412 struct ucred *ucred = (struct ucred *)CMSG_DATA(cmsg);
413 server_pid = ucred->pid;
415 #endif
417 #endif /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
418 if (fd != -1) fcntl( fd, F_SETFD, FD_CLOEXEC ); /* in case MSG_CMSG_CLOEXEC is not supported */
419 return fd;
421 if (!ret) break;
422 if (errno == EINTR) continue;
423 if (errno == EPIPE) break;
424 server_protocol_perror("recvmsg");
426 /* the server closed the connection; time to die... */
427 abort_thread(0);
431 /***********************************************************************/
432 /* fd cache support */
434 struct fd_cache_entry
436 int fd;
437 enum server_fd_type type : 6;
438 unsigned int access : 2;
439 unsigned int options : 24;
442 #define FD_CACHE_BLOCK_SIZE (65536 / sizeof(struct fd_cache_entry))
443 #define FD_CACHE_ENTRIES 128
445 static struct fd_cache_entry *fd_cache[FD_CACHE_ENTRIES];
446 static struct fd_cache_entry fd_cache_initial_block[FD_CACHE_BLOCK_SIZE];
448 static inline unsigned int handle_to_index( HANDLE handle, unsigned int *entry )
450 unsigned int idx = (wine_server_obj_handle(handle) >> 2) - 1;
451 *entry = idx / FD_CACHE_BLOCK_SIZE;
452 return idx % FD_CACHE_BLOCK_SIZE;
456 /***********************************************************************
457 * add_fd_to_cache
459 * Caller must hold fd_cache_section.
461 static int add_fd_to_cache( HANDLE handle, int fd, enum server_fd_type type,
462 unsigned int access, unsigned int options )
464 unsigned int entry, idx = handle_to_index( handle, &entry );
465 int prev_fd;
467 if (entry >= FD_CACHE_ENTRIES)
469 FIXME( "too many allocated handles, not caching %p\n", handle );
470 return 0;
473 if (!fd_cache[entry]) /* do we need to allocate a new block of entries? */
475 if (!entry) fd_cache[0] = fd_cache_initial_block;
476 else
478 void *ptr = wine_anon_mmap( NULL, FD_CACHE_BLOCK_SIZE * sizeof(struct fd_cache_entry),
479 PROT_READ | PROT_WRITE, 0 );
480 if (ptr == MAP_FAILED) return 0;
481 fd_cache[entry] = ptr;
484 /* store fd+1 so that 0 can be used as the unset value */
485 prev_fd = interlocked_xchg( &fd_cache[entry][idx].fd, fd + 1 ) - 1;
486 fd_cache[entry][idx].type = type;
487 fd_cache[entry][idx].access = access;
488 fd_cache[entry][idx].options = options;
489 if (prev_fd != -1) close( prev_fd );
490 return 1;
494 /***********************************************************************
495 * get_cached_fd
497 * Caller must hold fd_cache_section.
499 static inline int get_cached_fd( HANDLE handle, enum server_fd_type *type,
500 unsigned int *access, unsigned int *options )
502 unsigned int entry, idx = handle_to_index( handle, &entry );
503 int fd = -1;
505 if (entry < FD_CACHE_ENTRIES && fd_cache[entry])
507 fd = fd_cache[entry][idx].fd - 1;
508 if (type) *type = fd_cache[entry][idx].type;
509 if (access) *access = fd_cache[entry][idx].access;
510 if (options) *options = fd_cache[entry][idx].options;
512 return fd;
516 /***********************************************************************
517 * server_remove_fd_from_cache
519 int server_remove_fd_from_cache( HANDLE handle )
521 unsigned int entry, idx = handle_to_index( handle, &entry );
522 int fd = -1;
524 if (entry < FD_CACHE_ENTRIES && fd_cache[entry])
525 fd = interlocked_xchg( &fd_cache[entry][idx].fd, 0 ) - 1;
527 return fd;
531 /***********************************************************************
532 * server_get_unix_fd
534 * The returned unix_fd should be closed iff needs_close is non-zero.
536 int server_get_unix_fd( HANDLE handle, unsigned int wanted_access, int *unix_fd,
537 int *needs_close, enum server_fd_type *type, unsigned int *options )
539 sigset_t sigset;
540 obj_handle_t fd_handle;
541 int ret = 0, fd;
542 unsigned int access = 0;
544 *unix_fd = -1;
545 *needs_close = 0;
546 wanted_access &= FILE_READ_DATA | FILE_WRITE_DATA;
548 server_enter_uninterrupted_section( &fd_cache_section, &sigset );
550 fd = get_cached_fd( handle, type, &access, options );
551 if (fd != -1) goto done;
553 SERVER_START_REQ( get_handle_fd )
555 req->handle = wine_server_obj_handle( handle );
556 if (!(ret = wine_server_call( req )))
558 if (type) *type = reply->type;
559 if (options) *options = reply->options;
560 access = reply->access;
561 if ((fd = receive_fd( &fd_handle )) != -1)
563 assert( wine_server_ptr_handle(fd_handle) == handle );
564 *needs_close = (!reply->cacheable ||
565 !add_fd_to_cache( handle, fd, reply->type,
566 reply->access, reply->options ));
568 else ret = STATUS_TOO_MANY_OPENED_FILES;
571 SERVER_END_REQ;
573 done:
574 server_leave_uninterrupted_section( &fd_cache_section, &sigset );
575 if (!ret && ((access & wanted_access) != wanted_access))
577 ret = STATUS_ACCESS_DENIED;
578 if (*needs_close) close( fd );
580 if (!ret) *unix_fd = fd;
581 return ret;
585 /***********************************************************************
586 * wine_server_fd_to_handle (NTDLL.@)
588 * Allocate a file handle for a Unix file descriptor.
590 * PARAMS
591 * fd [I] Unix file descriptor.
592 * access [I] Win32 access flags.
593 * attributes [I] Object attributes.
594 * handle [O] Address where Wine file handle will be stored.
596 * RETURNS
597 * NTSTATUS code
599 int CDECL wine_server_fd_to_handle( int fd, unsigned int access, unsigned int attributes, HANDLE *handle )
601 int ret;
603 *handle = 0;
604 wine_server_send_fd( fd );
606 SERVER_START_REQ( alloc_file_handle )
608 req->access = access;
609 req->attributes = attributes;
610 req->fd = fd;
611 if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
613 SERVER_END_REQ;
614 return ret;
618 /***********************************************************************
619 * wine_server_handle_to_fd (NTDLL.@)
621 * Retrieve the file descriptor corresponding to a file handle.
623 * PARAMS
624 * handle [I] Wine file handle.
625 * access [I] Win32 file access rights requested.
626 * unix_fd [O] Address where Unix file descriptor will be stored.
627 * options [O] Address where the file open options will be stored. Optional.
629 * RETURNS
630 * NTSTATUS code
632 int CDECL wine_server_handle_to_fd( HANDLE handle, unsigned int access, int *unix_fd,
633 unsigned int *options )
635 int needs_close, ret = server_get_unix_fd( handle, access, unix_fd, &needs_close, NULL, options );
637 if (!ret && !needs_close)
639 if ((*unix_fd = dup(*unix_fd)) == -1) ret = FILE_GetNtStatus();
641 return ret;
645 /***********************************************************************
646 * wine_server_release_fd (NTDLL.@)
648 * Release the Unix file descriptor returned by wine_server_handle_to_fd.
650 * PARAMS
651 * handle [I] Wine file handle.
652 * unix_fd [I] Unix file descriptor to release.
654 * RETURNS
655 * nothing
657 void CDECL wine_server_release_fd( HANDLE handle, int unix_fd )
659 close( unix_fd );
663 /***********************************************************************
664 * server_pipe
666 * Create a pipe for communicating with the server.
668 int server_pipe( int fd[2] )
670 int ret;
671 #ifdef HAVE_PIPE2
672 static int have_pipe2 = 1;
674 if (have_pipe2)
676 if (!(ret = pipe2( fd, O_CLOEXEC ))) return ret;
677 if (errno == ENOSYS || errno == EINVAL) have_pipe2 = 0; /* don't try again */
679 #endif
680 if (!(ret = pipe( fd )))
682 fcntl( fd[0], F_SETFD, FD_CLOEXEC );
683 fcntl( fd[1], F_SETFD, FD_CLOEXEC );
685 return ret;
689 /***********************************************************************
690 * start_server
692 * Start a new wine server.
694 static void start_server(void)
696 static int started; /* we only try once */
697 char *argv[3];
698 static char wineserver[] = "server/wineserver";
699 static char debug[] = "-d";
701 if (!started)
703 int status;
704 int pid = fork();
705 if (pid == -1) fatal_perror( "fork" );
706 if (!pid)
708 argv[0] = wineserver;
709 argv[1] = TRACE_ON(server) ? debug : NULL;
710 argv[2] = NULL;
711 wine_exec_wine_binary( argv[0], argv, getenv("WINESERVER") );
712 fatal_error( "could not exec wineserver\n" );
714 waitpid( pid, &status, 0 );
715 status = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
716 if (status == 2) return; /* server lock held by someone else, will retry later */
717 if (status) exit(status); /* server failed */
718 started = 1;
723 /***********************************************************************
724 * setup_config_dir
726 * Setup the wine configuration dir.
728 static void setup_config_dir(void)
730 const char *p, *config_dir = wine_get_config_dir();
732 if (chdir( config_dir ) == -1)
734 if (errno != ENOENT) fatal_perror( "chdir to %s\n", config_dir );
736 if ((p = strrchr( config_dir, '/' )) && p != config_dir)
738 struct stat st;
739 char *tmp_dir;
741 if (!(tmp_dir = malloc( p + 1 - config_dir ))) fatal_error( "out of memory\n" );
742 memcpy( tmp_dir, config_dir, p - config_dir );
743 tmp_dir[p - config_dir] = 0;
744 if (!stat( tmp_dir, &st ) && st.st_uid != getuid())
745 fatal_error( "'%s' is not owned by you, refusing to create a configuration directory there\n",
746 tmp_dir );
747 free( tmp_dir );
750 mkdir( config_dir, 0777 );
751 if (chdir( config_dir ) == -1) fatal_perror( "chdir to %s\n", config_dir );
753 if ((p = getenv( "WINEARCH" )) && !strcmp( p, "win32" ))
755 /* force creation of a 32-bit prefix */
756 int fd = open( "system.reg", O_WRONLY | O_CREAT | O_EXCL, 0666 );
757 if (fd != -1)
759 static const char regfile[] = "WINE REGISTRY Version 2\n\n#arch=win32\n";
760 write( fd, regfile, sizeof(regfile) - 1 );
761 close( fd );
764 MESSAGE( "wine: created the configuration directory '%s'\n", config_dir );
767 if (mkdir( "dosdevices", 0777 ) == -1)
769 if (errno == EEXIST) return;
770 fatal_perror( "cannot create %s/dosdevices\n", config_dir );
773 /* create the drive symlinks */
775 mkdir( "drive_c", 0777 );
776 symlink( "../drive_c", "dosdevices/c:" );
777 symlink( "/", "dosdevices/z:" );
781 /***********************************************************************
782 * server_connect_error
784 * Try to display a meaningful explanation of why we couldn't connect
785 * to the server.
787 static void server_connect_error( const char *serverdir )
789 int fd;
790 struct flock fl;
792 if ((fd = open( LOCKNAME, O_WRONLY )) == -1)
793 fatal_error( "for some mysterious reason, the wine server never started.\n" );
795 fl.l_type = F_WRLCK;
796 fl.l_whence = SEEK_SET;
797 fl.l_start = 0;
798 fl.l_len = 1;
799 if (fcntl( fd, F_GETLK, &fl ) != -1)
801 if (fl.l_type == F_WRLCK) /* the file is locked */
802 fatal_error( "a wine server seems to be running, but I cannot connect to it.\n"
803 " You probably need to kill that process (it might be pid %d).\n",
804 (int)fl.l_pid );
805 fatal_error( "for some mysterious reason, the wine server failed to run.\n" );
807 fatal_error( "the file system of '%s' doesn't support locks,\n"
808 " and there is a 'socket' file in that directory that prevents wine from starting.\n"
809 " You should make sure no wine server is running, remove that file and try again.\n",
810 serverdir );
814 /***********************************************************************
815 * server_connect
817 * Attempt to connect to an existing server socket.
818 * We need to be in the server directory already.
820 static int server_connect(void)
822 const char *serverdir;
823 struct sockaddr_un addr;
824 struct stat st;
825 int s, slen, retry, fd_cwd;
827 /* retrieve the current directory */
828 fd_cwd = open( ".", O_RDONLY );
829 if (fd_cwd != -1) fcntl( fd_cwd, F_SETFD, 1 ); /* set close on exec flag */
831 setup_config_dir();
832 serverdir = wine_get_server_dir();
834 /* chdir to the server directory */
835 if (chdir( serverdir ) == -1)
837 if (errno != ENOENT) fatal_perror( "chdir to %s", serverdir );
838 start_server();
839 if (chdir( serverdir ) == -1) fatal_perror( "chdir to %s", serverdir );
842 /* make sure we are at the right place */
843 if (stat( ".", &st ) == -1) fatal_perror( "stat %s", serverdir );
844 if (st.st_uid != getuid()) fatal_error( "'%s' is not owned by you\n", serverdir );
845 if (st.st_mode & 077) fatal_error( "'%s' must not be accessible by other users\n", serverdir );
847 for (retry = 0; retry < 6; retry++)
849 /* if not the first try, wait a bit to leave the previous server time to exit */
850 if (retry)
852 usleep( 100000 * retry * retry );
853 start_server();
854 if (lstat( SOCKETNAME, &st ) == -1) continue; /* still no socket, wait a bit more */
856 else if (lstat( SOCKETNAME, &st ) == -1) /* check for an already existing socket */
858 if (errno != ENOENT) fatal_perror( "lstat %s/%s", serverdir, SOCKETNAME );
859 start_server();
860 if (lstat( SOCKETNAME, &st ) == -1) continue; /* still no socket, wait a bit more */
863 /* make sure the socket is sane (ISFIFO needed for Solaris) */
864 if (!S_ISSOCK(st.st_mode) && !S_ISFIFO(st.st_mode))
865 fatal_error( "'%s/%s' is not a socket\n", serverdir, SOCKETNAME );
866 if (st.st_uid != getuid())
867 fatal_error( "'%s/%s' is not owned by you\n", serverdir, SOCKETNAME );
869 /* try to connect to it */
870 addr.sun_family = AF_UNIX;
871 strcpy( addr.sun_path, SOCKETNAME );
872 slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
873 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
874 addr.sun_len = slen;
875 #endif
876 if ((s = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_perror( "socket" );
877 if (connect( s, (struct sockaddr *)&addr, slen ) != -1)
879 /* switch back to the starting directory */
880 if (fd_cwd != -1)
882 fchdir( fd_cwd );
883 close( fd_cwd );
885 fcntl( s, F_SETFD, 1 ); /* set close on exec flag */
886 return s;
888 close( s );
890 server_connect_error( serverdir );
894 #ifdef __APPLE__
895 #include <mach/mach.h>
896 #include <mach/mach_error.h>
897 #include <servers/bootstrap.h>
899 /* send our task port to the server */
900 static void send_server_task_port(void)
902 mach_port_t bootstrap_port, wineserver_port;
903 kern_return_t kret;
905 struct {
906 mach_msg_header_t header;
907 mach_msg_body_t body;
908 mach_msg_port_descriptor_t task_port;
909 } msg;
911 if (task_get_bootstrap_port(mach_task_self(), &bootstrap_port) != KERN_SUCCESS) return;
913 kret = bootstrap_look_up(bootstrap_port, (char*)wine_get_server_dir(), &wineserver_port);
914 if (kret != KERN_SUCCESS)
915 fatal_error( "cannot find the server port: 0x%08x\n", kret );
917 mach_port_deallocate(mach_task_self(), bootstrap_port);
919 msg.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0) | MACH_MSGH_BITS_COMPLEX;
920 msg.header.msgh_size = sizeof(msg);
921 msg.header.msgh_remote_port = wineserver_port;
922 msg.header.msgh_local_port = MACH_PORT_NULL;
924 msg.body.msgh_descriptor_count = 1;
925 msg.task_port.name = mach_task_self();
926 msg.task_port.disposition = MACH_MSG_TYPE_COPY_SEND;
927 msg.task_port.type = MACH_MSG_PORT_DESCRIPTOR;
929 kret = mach_msg_send(&msg.header);
930 if (kret != KERN_SUCCESS)
931 server_protocol_error( "mach_msg_send failed: 0x%08x\n", kret );
933 mach_port_deallocate(mach_task_self(), wineserver_port);
935 #endif /* __APPLE__ */
938 /***********************************************************************
939 * get_unix_tid
941 * Retrieve the Unix tid to use on the server side for the current thread.
943 static int get_unix_tid(void)
945 int ret = -1;
946 #if defined(linux) && defined(__i386__)
947 ret = syscall(224 /*SYS_gettid*/);
948 #elif defined(linux) && defined(__x86_64__)
949 ret = syscall(186 /*SYS_gettid*/);
950 #elif defined(__sun)
951 ret = pthread_self();
952 #elif defined(__APPLE__)
953 ret = mach_thread_self();
954 mach_port_deallocate(mach_task_self(), ret);
955 #elif defined(__FreeBSD__)
956 long lwpid;
957 thr_self( &lwpid );
958 ret = lwpid;
959 #endif
960 return ret;
964 /***********************************************************************
965 * server_init_process
967 * Start the server and create the initial socket pair.
969 void server_init_process(void)
971 obj_handle_t version;
972 const char *env_socket = getenv( "WINESERVERSOCKET" );
974 server_pid = -1;
975 if (env_socket)
977 fd_socket = atoi( env_socket );
978 if (fcntl( fd_socket, F_SETFD, 1 ) == -1)
979 fatal_perror( "Bad server socket %d", fd_socket );
980 unsetenv( "WINESERVERSOCKET" );
982 else fd_socket = server_connect();
984 /* setup the signal mask */
985 sigemptyset( &server_block_set );
986 sigaddset( &server_block_set, SIGALRM );
987 sigaddset( &server_block_set, SIGIO );
988 sigaddset( &server_block_set, SIGINT );
989 sigaddset( &server_block_set, SIGHUP );
990 sigaddset( &server_block_set, SIGUSR1 );
991 sigaddset( &server_block_set, SIGUSR2 );
992 sigaddset( &server_block_set, SIGCHLD );
993 pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
995 /* receive the first thread request fd on the main socket */
996 #ifdef SO_PASSCRED
997 if (server_pid == -1)
999 int enable = 1;
1000 setsockopt( fd_socket, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
1001 ntdll_get_thread_data()->request_fd = receive_fd( &version );
1002 enable = 0;
1003 setsockopt( fd_socket, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
1005 else
1006 #endif
1007 ntdll_get_thread_data()->request_fd = receive_fd( &version );
1009 if (version != SERVER_PROTOCOL_VERSION)
1010 server_protocol_error( "version mismatch %d/%d.\n"
1011 "Your %s binary was not upgraded correctly,\n"
1012 "or you have an older one somewhere in your PATH.\n"
1013 "Or maybe the wrong wineserver is still running?\n",
1014 version, SERVER_PROTOCOL_VERSION,
1015 (version > SERVER_PROTOCOL_VERSION) ? "wine" : "wineserver" );
1016 #ifdef __APPLE__
1017 send_server_task_port();
1018 #endif
1019 #if defined(__linux__) && defined(HAVE_PRCTL)
1020 /* work around Ubuntu's ptrace breakage */
1021 if (server_pid != -1) prctl( 0x59616d61 /* PR_SET_PTRACER */, server_pid );
1022 #endif
1026 /***********************************************************************
1027 * server_init_process_done
1029 NTSTATUS server_init_process_done(void)
1031 PEB *peb = NtCurrentTeb()->Peb;
1032 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
1033 NTSTATUS status;
1035 /* Install signal handlers; this cannot be done earlier, since we cannot
1036 * send exceptions to the debugger before the create process event that
1037 * is sent by REQ_INIT_PROCESS_DONE.
1038 * We do need the handlers in place by the time the request is over, so
1039 * we set them up here. If we segfault between here and the server call
1040 * something is very wrong... */
1041 signal_init_process();
1043 /* Signal the parent process to continue */
1044 SERVER_START_REQ( init_process_done )
1046 req->module = wine_server_client_ptr( peb->ImageBaseAddress );
1047 #ifdef __i386__
1048 req->ldt_copy = wine_server_client_ptr( &wine_ldt_copy );
1049 #endif
1050 req->entry = wine_server_client_ptr( (char *)peb->ImageBaseAddress + nt->OptionalHeader.AddressOfEntryPoint );
1051 req->gui = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
1052 status = wine_server_call( req );
1054 SERVER_END_REQ;
1056 return status;
1060 /***********************************************************************
1061 * server_init_thread
1063 * Send an init thread request. Return 0 if OK.
1065 size_t server_init_thread( void *entry_point )
1067 static const int is_win64 = (sizeof(void *) > sizeof(int));
1068 const char *arch = getenv( "WINEARCH" );
1069 int ret;
1070 int reply_pipe[2];
1071 struct sigaction sig_act;
1072 size_t info_size;
1074 sig_act.sa_handler = SIG_IGN;
1075 sig_act.sa_flags = 0;
1076 sigemptyset( &sig_act.sa_mask );
1078 /* ignore SIGPIPE so that we get an EPIPE error instead */
1079 sigaction( SIGPIPE, &sig_act, NULL );
1080 /* automatic child reaping to avoid zombies */
1081 #ifdef SA_NOCLDWAIT
1082 sig_act.sa_flags |= SA_NOCLDWAIT;
1083 #endif
1084 sigaction( SIGCHLD, &sig_act, NULL );
1086 /* create the server->client communication pipes */
1087 if (server_pipe( reply_pipe ) == -1) server_protocol_perror( "pipe" );
1088 if (server_pipe( ntdll_get_thread_data()->wait_fd ) == -1) server_protocol_perror( "pipe" );
1089 wine_server_send_fd( reply_pipe[1] );
1090 wine_server_send_fd( ntdll_get_thread_data()->wait_fd[1] );
1091 ntdll_get_thread_data()->reply_fd = reply_pipe[0];
1092 close( reply_pipe[1] );
1094 SERVER_START_REQ( init_thread )
1096 req->unix_pid = getpid();
1097 req->unix_tid = get_unix_tid();
1098 req->teb = wine_server_client_ptr( NtCurrentTeb() );
1099 req->entry = wine_server_client_ptr( entry_point );
1100 req->reply_fd = reply_pipe[1];
1101 req->wait_fd = ntdll_get_thread_data()->wait_fd[1];
1102 req->debug_level = (TRACE_ON(server) != 0);
1103 req->cpu = client_cpu;
1104 ret = wine_server_call( req );
1105 NtCurrentTeb()->ClientId.UniqueProcess = ULongToHandle(reply->pid);
1106 NtCurrentTeb()->ClientId.UniqueThread = ULongToHandle(reply->tid);
1107 info_size = reply->info_size;
1108 server_start_time = reply->server_start;
1109 server_cpus = reply->all_cpus;
1111 SERVER_END_REQ;
1113 is_wow64 = !is_win64 && (server_cpus & (1 << CPU_x86_64)) != 0;
1114 ntdll_get_thread_data()->wow64_redir = is_wow64;
1116 switch (ret)
1118 case STATUS_SUCCESS:
1119 if (arch)
1121 if (!strcmp( arch, "win32" ) && (is_win64 || is_wow64))
1122 fatal_error( "WINEARCH set to win32 but '%s' is a 64-bit installation.\n",
1123 wine_get_config_dir() );
1124 if (!strcmp( arch, "win64" ) && !is_wow64)
1125 fatal_error( "WINEARCH set to win64 but '%s' is a 32-bit installation.\n",
1126 wine_get_config_dir() );
1128 return info_size;
1129 case STATUS_NOT_REGISTRY_FILE:
1130 fatal_error( "'%s' is a 32-bit installation, it cannot support 64-bit applications.\n",
1131 wine_get_config_dir() );
1132 case STATUS_NOT_SUPPORTED:
1133 if (is_win64)
1134 fatal_error( "wineserver is 32-bit, it cannot support 64-bit applications.\n" );
1135 else
1136 fatal_error( "'%s' is a 64-bit installation, it cannot be used with a 32-bit wineserver.\n",
1137 wine_get_config_dir() );
1138 default:
1139 server_protocol_error( "init_thread failed with status %x\n", ret );