jscript: Rename jsheap_t to heap_pool_t.
[wine] / dlls / ntdll / server.c
1 /*
2  * Wine server communication
3  *
4  * Copyright (C) 1998 Alexandre Julliard
5  *
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.
10  *
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.
15  *
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
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
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_LWP_H
32 #include <lwp.h>
33 #endif
34 #ifdef HAVE_PTHREAD_NP_H
35 # include <pthread_np.h>
36 #endif
37 #include <signal.h>
38 #include <stdarg.h>
39 #include <stdio.h>
40 #include <string.h>
41 #include <sys/types.h>
42 #ifdef HAVE_SYS_SOCKET_H
43 # include <sys/socket.h>
44 #endif
45 #ifdef HAVE_SYS_WAIT_H
46 #include <sys/wait.h>
47 #endif
48 #ifdef HAVE_SYS_UN_H
49 #include <sys/un.h>
50 #endif
51 #ifdef HAVE_SYS_MMAN_H
52 #include <sys/mman.h>
53 #endif
54 #ifdef HAVE_SYS_PRCTL_H
55 # include <sys/prctl.h>
56 #endif
57 #ifdef HAVE_SYS_STAT_H
58 # include <sys/stat.h>
59 #endif
60 #ifdef HAVE_SYS_SYSCALL_H
61 # include <sys/syscall.h>
62 #endif
63 #ifdef HAVE_SYS_UIO_H
64 #include <sys/uio.h>
65 #endif
66 #ifdef HAVE_SYS_THR_H
67 #include <sys/ucontext.h>
68 #include <sys/thr.h>
69 #endif
70 #ifdef HAVE_UNISTD_H
71 # include <unistd.h>
72 #endif
73
74 #include "ntstatus.h"
75 #define WIN32_NO_STATUS
76 #include "wine/library.h"
77 #include "wine/server.h"
78 #include "wine/debug.h"
79 #include "ntdll_misc.h"
80
81 WINE_DEFAULT_DEBUG_CHANNEL(server);
82
83 /* Some versions of glibc don't define this */
84 #ifndef SCM_RIGHTS
85 #define SCM_RIGHTS 1
86 #endif
87
88 #ifndef MSG_CMSG_CLOEXEC
89 #define MSG_CMSG_CLOEXEC 0
90 #endif
91
92 #define SOCKETNAME "socket"        /* name of the socket file */
93 #define LOCKNAME   "lock"          /* name of the lock file */
94
95 #ifdef __i386__
96 static const enum cpu_type client_cpu = CPU_x86;
97 #elif defined(__x86_64__)
98 static const enum cpu_type client_cpu = CPU_x86_64;
99 #elif defined(__powerpc__)
100 static const enum cpu_type client_cpu = CPU_POWERPC;
101 #elif defined(__sparc__)
102 static const enum cpu_type client_cpu = CPU_SPARC;
103 #elif defined(__arm__)
104 static const enum cpu_type client_cpu = CPU_ARM;
105 #elif defined(__aarch64__)
106 static const enum cpu_type client_cpu = CPU_ARM64;
107 #else
108 #error Unsupported CPU
109 #endif
110
111 unsigned int server_cpus = 0;
112 int is_wow64 = FALSE;
113
114 timeout_t server_start_time = 0;  /* time of server startup */
115
116 sigset_t server_block_set;  /* signals to block during server calls */
117 static int fd_socket = -1;  /* socket to exchange file descriptors with the server */
118 static pid_t server_pid;
119
120 static RTL_CRITICAL_SECTION fd_cache_section;
121 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
122 {
123     0, 0, &fd_cache_section,
124     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
125       0, 0, { (DWORD_PTR)(__FILE__ ": fd_cache_section") }
126 };
127 static RTL_CRITICAL_SECTION fd_cache_section = { &critsect_debug, -1, 0, 0, 0, 0 };
128
129
130 #ifdef __GNUC__
131 static void fatal_error( const char *err, ... ) __attribute__((noreturn, format(printf,1,2)));
132 static void fatal_perror( const char *err, ... ) __attribute__((noreturn, format(printf,1,2)));
133 static void server_connect_error( const char *serverdir ) __attribute__((noreturn));
134 #endif
135
136 /* die on a fatal error; use only during initialization */
137 static void fatal_error( const char *err, ... )
138 {
139     va_list args;
140
141     va_start( args, err );
142     fprintf( stderr, "wine: " );
143     vfprintf( stderr, err, args );
144     va_end( args );
145     exit(1);
146 }
147
148 /* die on a fatal error; use only during initialization */
149 static void fatal_perror( const char *err, ... )
150 {
151     va_list args;
152
153     va_start( args, err );
154     fprintf( stderr, "wine: " );
155     vfprintf( stderr, err, args );
156     perror( " " );
157     va_end( args );
158     exit(1);
159 }
160
161
162 /***********************************************************************
163  *           server_protocol_error
164  */
165 void server_protocol_error( const char *err, ... )
166 {
167     va_list args;
168
169     va_start( args, err );
170     fprintf( stderr, "wine client error:%x: ", GetCurrentThreadId() );
171     vfprintf( stderr, err, args );
172     va_end( args );
173     abort_thread(1);
174 }
175
176
177 /***********************************************************************
178  *           server_protocol_perror
179  */
180 void server_protocol_perror( const char *err )
181 {
182     fprintf( stderr, "wine client error:%x: ", GetCurrentThreadId() );
183     perror( err );
184     abort_thread(1);
185 }
186
187
188 /***********************************************************************
189  *           send_request
190  *
191  * Send a request to the server.
192  */
193 static unsigned int send_request( const struct __server_request_info *req )
194 {
195     unsigned int i;
196     int ret;
197
198     if (!req->u.req.request_header.request_size)
199     {
200         if ((ret = write( ntdll_get_thread_data()->request_fd, &req->u.req,
201                           sizeof(req->u.req) )) == sizeof(req->u.req)) return STATUS_SUCCESS;
202
203     }
204     else
205     {
206         struct iovec vec[__SERVER_MAX_DATA+1];
207
208         vec[0].iov_base = (void *)&req->u.req;
209         vec[0].iov_len = sizeof(req->u.req);
210         for (i = 0; i < req->data_count; i++)
211         {
212             vec[i+1].iov_base = (void *)req->data[i].ptr;
213             vec[i+1].iov_len = req->data[i].size;
214         }
215         if ((ret = writev( ntdll_get_thread_data()->request_fd, vec, i+1 )) ==
216             req->u.req.request_header.request_size + sizeof(req->u.req)) return STATUS_SUCCESS;
217     }
218
219     if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
220     if (errno == EPIPE) abort_thread(0);
221     if (errno == EFAULT) return STATUS_ACCESS_VIOLATION;
222     server_protocol_perror( "write" );
223 }
224
225
226 /***********************************************************************
227  *           read_reply_data
228  *
229  * Read data from the reply buffer; helper for wait_reply.
230  */
231 static void read_reply_data( void *buffer, size_t size )
232 {
233     int ret;
234
235     for (;;)
236     {
237         if ((ret = read( ntdll_get_thread_data()->reply_fd, buffer, size )) > 0)
238         {
239             if (!(size -= ret)) return;
240             buffer = (char *)buffer + ret;
241             continue;
242         }
243         if (!ret) break;
244         if (errno == EINTR) continue;
245         if (errno == EPIPE) break;
246         server_protocol_perror("read");
247     }
248     /* the server closed the connection; time to die... */
249     abort_thread(0);
250 }
251
252
253 /***********************************************************************
254  *           wait_reply
255  *
256  * Wait for a reply from the server.
257  */
258 static inline unsigned int wait_reply( struct __server_request_info *req )
259 {
260     read_reply_data( &req->u.reply, sizeof(req->u.reply) );
261     if (req->u.reply.reply_header.reply_size)
262         read_reply_data( req->reply_data, req->u.reply.reply_header.reply_size );
263     return req->u.reply.reply_header.error;
264 }
265
266
267 /***********************************************************************
268  *           wine_server_call (NTDLL.@)
269  *
270  * Perform a server call.
271  *
272  * PARAMS
273  *     req_ptr [I/O] Function dependent data
274  *
275  * RETURNS
276  *     Depends on server function being called, but usually an NTSTATUS code.
277  *
278  * NOTES
279  *     Use the SERVER_START_REQ and SERVER_END_REQ to help you fill out the
280  *     server request structure for the particular call. E.g:
281  *|     SERVER_START_REQ( event_op )
282  *|     {
283  *|         req->handle = handle;
284  *|         req->op     = SET_EVENT;
285  *|         ret = wine_server_call( req );
286  *|     }
287  *|     SERVER_END_REQ;
288  */
289 unsigned int wine_server_call( void *req_ptr )
290 {
291     struct __server_request_info * const req = req_ptr;
292     sigset_t old_set;
293     unsigned int ret;
294
295     pthread_sigmask( SIG_BLOCK, &server_block_set, &old_set );
296     ret = send_request( req );
297     if (!ret) ret = wait_reply( req );
298     pthread_sigmask( SIG_SETMASK, &old_set, NULL );
299     return ret;
300 }
301
302
303 /***********************************************************************
304  *           server_enter_uninterrupted_section
305  */
306 void server_enter_uninterrupted_section( RTL_CRITICAL_SECTION *cs, sigset_t *sigset )
307 {
308     pthread_sigmask( SIG_BLOCK, &server_block_set, sigset );
309     RtlEnterCriticalSection( cs );
310 }
311
312
313 /***********************************************************************
314  *           server_leave_uninterrupted_section
315  */
316 void server_leave_uninterrupted_section( RTL_CRITICAL_SECTION *cs, sigset_t *sigset )
317 {
318     RtlLeaveCriticalSection( cs );
319     pthread_sigmask( SIG_SETMASK, sigset, NULL );
320 }
321
322
323 /***********************************************************************
324  *           wine_server_send_fd   (NTDLL.@)
325  *
326  * Send a file descriptor to the server.
327  *
328  * PARAMS
329  *     fd [I] file descriptor to send
330  *
331  * RETURNS
332  *     nothing
333  */
334 void CDECL wine_server_send_fd( int fd )
335 {
336     struct send_fd data;
337     struct msghdr msghdr;
338     struct iovec vec;
339     int ret;
340
341 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
342     msghdr.msg_accrights    = (void *)&fd;
343     msghdr.msg_accrightslen = sizeof(fd);
344 #else  /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
345     char cmsg_buffer[256];
346     struct cmsghdr *cmsg;
347     msghdr.msg_control    = cmsg_buffer;
348     msghdr.msg_controllen = sizeof(cmsg_buffer);
349     msghdr.msg_flags      = 0;
350     cmsg = CMSG_FIRSTHDR( &msghdr );
351     cmsg->cmsg_len   = CMSG_LEN( sizeof(fd) );
352     cmsg->cmsg_level = SOL_SOCKET;
353     cmsg->cmsg_type  = SCM_RIGHTS;
354     *(int *)CMSG_DATA(cmsg) = fd;
355     msghdr.msg_controllen = cmsg->cmsg_len;
356 #endif  /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
357
358     msghdr.msg_name    = NULL;
359     msghdr.msg_namelen = 0;
360     msghdr.msg_iov     = &vec;
361     msghdr.msg_iovlen  = 1;
362
363     vec.iov_base = (void *)&data;
364     vec.iov_len  = sizeof(data);
365
366     data.tid = GetCurrentThreadId();
367     data.fd  = fd;
368
369     for (;;)
370     {
371         if ((ret = sendmsg( fd_socket, &msghdr, 0 )) == sizeof(data)) return;
372         if (ret >= 0) server_protocol_error( "partial write %d\n", ret );
373         if (errno == EINTR) continue;
374         if (errno == EPIPE) abort_thread(0);
375         server_protocol_perror( "sendmsg" );
376     }
377 }
378
379
380 /***********************************************************************
381  *           receive_fd
382  *
383  * Receive a file descriptor passed from the server.
384  */
385 static int receive_fd( obj_handle_t *handle )
386 {
387     struct iovec vec;
388     struct msghdr msghdr;
389     int ret, fd = -1;
390
391 #ifdef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
392     msghdr.msg_accrights    = (void *)&fd;
393     msghdr.msg_accrightslen = sizeof(fd);
394 #else  /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
395     char cmsg_buffer[256];
396     msghdr.msg_control    = cmsg_buffer;
397     msghdr.msg_controllen = sizeof(cmsg_buffer);
398     msghdr.msg_flags      = 0;
399 #endif  /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
400
401     msghdr.msg_name    = NULL;
402     msghdr.msg_namelen = 0;
403     msghdr.msg_iov     = &vec;
404     msghdr.msg_iovlen  = 1;
405     vec.iov_base = (void *)handle;
406     vec.iov_len  = sizeof(*handle);
407
408     for (;;)
409     {
410         if ((ret = recvmsg( fd_socket, &msghdr, MSG_CMSG_CLOEXEC )) > 0)
411         {
412 #ifndef HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS
413             struct cmsghdr *cmsg;
414             for (cmsg = CMSG_FIRSTHDR( &msghdr ); cmsg; cmsg = CMSG_NXTHDR( &msghdr, cmsg ))
415             {
416                 if (cmsg->cmsg_level != SOL_SOCKET) continue;
417                 if (cmsg->cmsg_type == SCM_RIGHTS) fd = *(int *)CMSG_DATA(cmsg);
418 #ifdef SCM_CREDENTIALS
419                 else if (cmsg->cmsg_type == SCM_CREDENTIALS)
420                 {
421                     struct ucred *ucred = (struct ucred *)CMSG_DATA(cmsg);
422                     server_pid = ucred->pid;
423                 }
424 #endif
425             }
426 #endif  /* HAVE_STRUCT_MSGHDR_MSG_ACCRIGHTS */
427             if (fd != -1) fcntl( fd, F_SETFD, FD_CLOEXEC ); /* in case MSG_CMSG_CLOEXEC is not supported */
428             return fd;
429         }
430         if (!ret) break;
431         if (errno == EINTR) continue;
432         if (errno == EPIPE) break;
433         server_protocol_perror("recvmsg");
434     }
435     /* the server closed the connection; time to die... */
436     abort_thread(0);
437 }
438
439
440 /***********************************************************************/
441 /* fd cache support */
442
443 struct fd_cache_entry
444 {
445     int fd;
446     enum server_fd_type type : 6;
447     unsigned int        access : 2;
448     unsigned int        options : 24;
449 };
450
451 #define FD_CACHE_BLOCK_SIZE  (65536 / sizeof(struct fd_cache_entry))
452 #define FD_CACHE_ENTRIES     128
453
454 static struct fd_cache_entry *fd_cache[FD_CACHE_ENTRIES];
455 static struct fd_cache_entry fd_cache_initial_block[FD_CACHE_BLOCK_SIZE];
456
457 static inline unsigned int handle_to_index( HANDLE handle, unsigned int *entry )
458 {
459     unsigned int idx = (wine_server_obj_handle(handle) >> 2) - 1;
460     *entry = idx / FD_CACHE_BLOCK_SIZE;
461     return idx % FD_CACHE_BLOCK_SIZE;
462 }
463
464
465 /***********************************************************************
466  *           add_fd_to_cache
467  *
468  * Caller must hold fd_cache_section.
469  */
470 static int add_fd_to_cache( HANDLE handle, int fd, enum server_fd_type type,
471                             unsigned int access, unsigned int options )
472 {
473     unsigned int entry, idx = handle_to_index( handle, &entry );
474     int prev_fd;
475
476     if (entry >= FD_CACHE_ENTRIES)
477     {
478         FIXME( "too many allocated handles, not caching %p\n", handle );
479         return 0;
480     }
481
482     if (!fd_cache[entry])  /* do we need to allocate a new block of entries? */
483     {
484         if (!entry) fd_cache[0] = fd_cache_initial_block;
485         else
486         {
487             void *ptr = wine_anon_mmap( NULL, FD_CACHE_BLOCK_SIZE * sizeof(struct fd_cache_entry),
488                                         PROT_READ | PROT_WRITE, 0 );
489             if (ptr == MAP_FAILED) return 0;
490             fd_cache[entry] = ptr;
491         }
492     }
493     /* store fd+1 so that 0 can be used as the unset value */
494     prev_fd = interlocked_xchg( &fd_cache[entry][idx].fd, fd + 1 ) - 1;
495     fd_cache[entry][idx].type = type;
496     fd_cache[entry][idx].access = access;
497     fd_cache[entry][idx].options = options;
498     if (prev_fd != -1) close( prev_fd );
499     return 1;
500 }
501
502
503 /***********************************************************************
504  *           get_cached_fd
505  *
506  * Caller must hold fd_cache_section.
507  */
508 static inline int get_cached_fd( HANDLE handle, enum server_fd_type *type,
509                                  unsigned int *access, unsigned int *options )
510 {
511     unsigned int entry, idx = handle_to_index( handle, &entry );
512     int fd = -1;
513
514     if (entry < FD_CACHE_ENTRIES && fd_cache[entry])
515     {
516         fd = fd_cache[entry][idx].fd - 1;
517         if (type) *type = fd_cache[entry][idx].type;
518         if (access) *access = fd_cache[entry][idx].access;
519         if (options) *options = fd_cache[entry][idx].options;
520     }
521     return fd;
522 }
523
524
525 /***********************************************************************
526  *           server_remove_fd_from_cache
527  */
528 int server_remove_fd_from_cache( HANDLE handle )
529 {
530     unsigned int entry, idx = handle_to_index( handle, &entry );
531     int fd = -1;
532
533     if (entry < FD_CACHE_ENTRIES && fd_cache[entry])
534         fd = interlocked_xchg( &fd_cache[entry][idx].fd, 0 ) - 1;
535
536     return fd;
537 }
538
539
540 /***********************************************************************
541  *           server_get_unix_fd
542  *
543  * The returned unix_fd should be closed iff needs_close is non-zero.
544  */
545 int server_get_unix_fd( HANDLE handle, unsigned int wanted_access, int *unix_fd,
546                         int *needs_close, enum server_fd_type *type, unsigned int *options )
547 {
548     sigset_t sigset;
549     obj_handle_t fd_handle;
550     int ret = 0, fd;
551     unsigned int access = 0;
552
553     *unix_fd = -1;
554     *needs_close = 0;
555     wanted_access &= FILE_READ_DATA | FILE_WRITE_DATA;
556
557     server_enter_uninterrupted_section( &fd_cache_section, &sigset );
558
559     fd = get_cached_fd( handle, type, &access, options );
560     if (fd != -1) goto done;
561
562     SERVER_START_REQ( get_handle_fd )
563     {
564         req->handle = wine_server_obj_handle( handle );
565         if (!(ret = wine_server_call( req )))
566         {
567             if (type) *type = reply->type;
568             if (options) *options = reply->options;
569             access = reply->access;
570             if ((fd = receive_fd( &fd_handle )) != -1)
571             {
572                 assert( wine_server_ptr_handle(fd_handle) == handle );
573                 *needs_close = (!reply->cacheable ||
574                                 !add_fd_to_cache( handle, fd, reply->type,
575                                                   reply->access, reply->options ));
576             }
577             else ret = STATUS_TOO_MANY_OPENED_FILES;
578         }
579     }
580     SERVER_END_REQ;
581
582 done:
583     server_leave_uninterrupted_section( &fd_cache_section, &sigset );
584     if (!ret && ((access & wanted_access) != wanted_access))
585     {
586         ret = STATUS_ACCESS_DENIED;
587         if (*needs_close) close( fd );
588     }
589     if (!ret) *unix_fd = fd;
590     return ret;
591 }
592
593
594 /***********************************************************************
595  *           wine_server_fd_to_handle   (NTDLL.@)
596  *
597  * Allocate a file handle for a Unix file descriptor.
598  *
599  * PARAMS
600  *     fd      [I] Unix file descriptor.
601  *     access  [I] Win32 access flags.
602  *     attributes [I] Object attributes.
603  *     handle  [O] Address where Wine file handle will be stored.
604  *
605  * RETURNS
606  *     NTSTATUS code
607  */
608 int CDECL wine_server_fd_to_handle( int fd, unsigned int access, unsigned int attributes, HANDLE *handle )
609 {
610     int ret;
611
612     *handle = 0;
613     wine_server_send_fd( fd );
614
615     SERVER_START_REQ( alloc_file_handle )
616     {
617         req->access     = access;
618         req->attributes = attributes;
619         req->fd         = fd;
620         if (!(ret = wine_server_call( req ))) *handle = wine_server_ptr_handle( reply->handle );
621     }
622     SERVER_END_REQ;
623     return ret;
624 }
625
626
627 /***********************************************************************
628  *           wine_server_handle_to_fd   (NTDLL.@)
629  *
630  * Retrieve the file descriptor corresponding to a file handle.
631  *
632  * PARAMS
633  *     handle  [I] Wine file handle.
634  *     access  [I] Win32 file access rights requested.
635  *     unix_fd [O] Address where Unix file descriptor will be stored.
636  *     options [O] Address where the file open options will be stored. Optional.
637  *
638  * RETURNS
639  *     NTSTATUS code
640  */
641 int CDECL wine_server_handle_to_fd( HANDLE handle, unsigned int access, int *unix_fd,
642                               unsigned int *options )
643 {
644     int needs_close, ret = server_get_unix_fd( handle, access, unix_fd, &needs_close, NULL, options );
645
646     if (!ret && !needs_close)
647     {
648         if ((*unix_fd = dup(*unix_fd)) == -1) ret = FILE_GetNtStatus();
649     }
650     return ret;
651 }
652
653
654 /***********************************************************************
655  *           wine_server_release_fd   (NTDLL.@)
656  *
657  * Release the Unix file descriptor returned by wine_server_handle_to_fd.
658  *
659  * PARAMS
660  *     handle  [I] Wine file handle.
661  *     unix_fd [I] Unix file descriptor to release.
662  *
663  * RETURNS
664  *     nothing
665  */
666 void CDECL wine_server_release_fd( HANDLE handle, int unix_fd )
667 {
668     close( unix_fd );
669 }
670
671
672 /***********************************************************************
673  *           server_pipe
674  *
675  * Create a pipe for communicating with the server.
676  */
677 int server_pipe( int fd[2] )
678 {
679     int ret;
680 #ifdef HAVE_PIPE2
681     static int have_pipe2 = 1;
682
683     if (have_pipe2)
684     {
685         if (!(ret = pipe2( fd, O_CLOEXEC ))) return ret;
686         if (errno == ENOSYS || errno == EINVAL) have_pipe2 = 0;  /* don't try again */
687     }
688 #endif
689     if (!(ret = pipe( fd )))
690     {
691         fcntl( fd[0], F_SETFD, FD_CLOEXEC );
692         fcntl( fd[1], F_SETFD, FD_CLOEXEC );
693     }
694     return ret;
695 }
696
697
698 /***********************************************************************
699  *           start_server
700  *
701  * Start a new wine server.
702  */
703 static void start_server(void)
704 {
705     static int started;  /* we only try once */
706     char *argv[3];
707     static char wineserver[] = "server/wineserver";
708     static char debug[] = "-d";
709
710     if (!started)
711     {
712         int status;
713         int pid = fork();
714         if (pid == -1) fatal_perror( "fork" );
715         if (!pid)
716         {
717             argv[0] = wineserver;
718             argv[1] = TRACE_ON(server) ? debug : NULL;
719             argv[2] = NULL;
720             wine_exec_wine_binary( argv[0], argv, getenv("WINESERVER") );
721             fatal_error( "could not exec wineserver\n" );
722         }
723         waitpid( pid, &status, 0 );
724         status = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
725         if (status == 2) return;  /* server lock held by someone else, will retry later */
726         if (status) exit(status);  /* server failed */
727         started = 1;
728     }
729 }
730
731
732 /***********************************************************************
733  *           setup_config_dir
734  *
735  * Setup the wine configuration dir.
736  */
737 static void setup_config_dir(void)
738 {
739     const char *p, *config_dir = wine_get_config_dir();
740
741     if (chdir( config_dir ) == -1)
742     {
743         if (errno != ENOENT) fatal_perror( "chdir to %s\n", config_dir );
744
745         if ((p = strrchr( config_dir, '/' )) && p != config_dir)
746         {
747             struct stat st;
748             char *tmp_dir;
749
750             if (!(tmp_dir = malloc( p + 1 - config_dir ))) fatal_error( "out of memory\n" );
751             memcpy( tmp_dir, config_dir, p - config_dir );
752             tmp_dir[p - config_dir] = 0;
753             if (!stat( tmp_dir, &st ) && st.st_uid != getuid())
754                 fatal_error( "'%s' is not owned by you, refusing to create a configuration directory there\n",
755                              tmp_dir );
756             free( tmp_dir );
757         }
758
759         mkdir( config_dir, 0777 );
760         if (chdir( config_dir ) == -1) fatal_perror( "chdir to %s\n", config_dir );
761
762         if ((p = getenv( "WINEARCH" )) && !strcmp( p, "win32" ))
763         {
764             /* force creation of a 32-bit prefix */
765             int fd = open( "system.reg", O_WRONLY | O_CREAT | O_EXCL, 0666 );
766             if (fd != -1)
767             {
768                 static const char regfile[] = "WINE REGISTRY Version 2\n\n#arch=win32\n";
769                 write( fd, regfile, sizeof(regfile) - 1 );
770                 close( fd );
771             }
772         }
773         MESSAGE( "wine: created the configuration directory '%s'\n", config_dir );
774     }
775
776     if (mkdir( "dosdevices", 0777 ) == -1)
777     {
778         if (errno == EEXIST) return;
779         fatal_perror( "cannot create %s/dosdevices\n", config_dir );
780     }
781
782     /* create the drive symlinks */
783
784     mkdir( "drive_c", 0777 );
785     symlink( "../drive_c", "dosdevices/c:" );
786     symlink( "/", "dosdevices/z:" );
787 }
788
789
790 /***********************************************************************
791  *           server_connect_error
792  *
793  * Try to display a meaningful explanation of why we couldn't connect
794  * to the server.
795  */
796 static void server_connect_error( const char *serverdir )
797 {
798     int fd;
799     struct flock fl;
800
801     if ((fd = open( LOCKNAME, O_WRONLY )) == -1)
802         fatal_error( "for some mysterious reason, the wine server never started.\n" );
803
804     fl.l_type   = F_WRLCK;
805     fl.l_whence = SEEK_SET;
806     fl.l_start  = 0;
807     fl.l_len    = 1;
808     if (fcntl( fd, F_GETLK, &fl ) != -1)
809     {
810         if (fl.l_type == F_WRLCK)  /* the file is locked */
811             fatal_error( "a wine server seems to be running, but I cannot connect to it.\n"
812                          "   You probably need to kill that process (it might be pid %d).\n",
813                          (int)fl.l_pid );
814         fatal_error( "for some mysterious reason, the wine server failed to run.\n" );
815     }
816     fatal_error( "the file system of '%s' doesn't support locks,\n"
817           "   and there is a 'socket' file in that directory that prevents wine from starting.\n"
818           "   You should make sure no wine server is running, remove that file and try again.\n",
819                  serverdir );
820 }
821
822
823 /***********************************************************************
824  *           server_connect
825  *
826  * Attempt to connect to an existing server socket.
827  * We need to be in the server directory already.
828  */
829 static int server_connect(void)
830 {
831     const char *serverdir;
832     struct sockaddr_un addr;
833     struct stat st;
834     int s, slen, retry, fd_cwd;
835
836     /* retrieve the current directory */
837     fd_cwd = open( ".", O_RDONLY );
838     if (fd_cwd != -1) fcntl( fd_cwd, F_SETFD, 1 ); /* set close on exec flag */
839
840     setup_config_dir();
841     serverdir = wine_get_server_dir();
842
843     /* chdir to the server directory */
844     if (chdir( serverdir ) == -1)
845     {
846         if (errno != ENOENT) fatal_perror( "chdir to %s", serverdir );
847         start_server();
848         if (chdir( serverdir ) == -1) fatal_perror( "chdir to %s", serverdir );
849     }
850
851     /* make sure we are at the right place */
852     if (stat( ".", &st ) == -1) fatal_perror( "stat %s", serverdir );
853     if (st.st_uid != getuid()) fatal_error( "'%s' is not owned by you\n", serverdir );
854     if (st.st_mode & 077) fatal_error( "'%s' must not be accessible by other users\n", serverdir );
855
856     for (retry = 0; retry < 6; retry++)
857     {
858         /* if not the first try, wait a bit to leave the previous server time to exit */
859         if (retry)
860         {
861             usleep( 100000 * retry * retry );
862             start_server();
863             if (lstat( SOCKETNAME, &st ) == -1) continue;  /* still no socket, wait a bit more */
864         }
865         else if (lstat( SOCKETNAME, &st ) == -1) /* check for an already existing socket */
866         {
867             if (errno != ENOENT) fatal_perror( "lstat %s/%s", serverdir, SOCKETNAME );
868             start_server();
869             if (lstat( SOCKETNAME, &st ) == -1) continue;  /* still no socket, wait a bit more */
870         }
871
872         /* make sure the socket is sane (ISFIFO needed for Solaris) */
873         if (!S_ISSOCK(st.st_mode) && !S_ISFIFO(st.st_mode))
874             fatal_error( "'%s/%s' is not a socket\n", serverdir, SOCKETNAME );
875         if (st.st_uid != getuid())
876             fatal_error( "'%s/%s' is not owned by you\n", serverdir, SOCKETNAME );
877
878         /* try to connect to it */
879         addr.sun_family = AF_UNIX;
880         strcpy( addr.sun_path, SOCKETNAME );
881         slen = sizeof(addr) - sizeof(addr.sun_path) + strlen(addr.sun_path) + 1;
882 #ifdef HAVE_STRUCT_SOCKADDR_UN_SUN_LEN
883         addr.sun_len = slen;
884 #endif
885         if ((s = socket( AF_UNIX, SOCK_STREAM, 0 )) == -1) fatal_perror( "socket" );
886 #ifdef SO_PASSCRED
887         else
888         {
889             int enable = 1;
890             setsockopt( s, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
891         }
892 #endif
893         if (connect( s, (struct sockaddr *)&addr, slen ) != -1)
894         {
895             /* switch back to the starting directory */
896             if (fd_cwd != -1)
897             {
898                 fchdir( fd_cwd );
899                 close( fd_cwd );
900             }
901             fcntl( s, F_SETFD, 1 ); /* set close on exec flag */
902             return s;
903         }
904         close( s );
905     }
906     server_connect_error( serverdir );
907 }
908
909
910 #ifdef __APPLE__
911 #include <mach/mach.h>
912 #include <mach/mach_error.h>
913 #include <servers/bootstrap.h>
914
915 /* send our task port to the server */
916 static void send_server_task_port(void)
917 {
918     mach_port_t bootstrap_port, wineserver_port;
919     kern_return_t kret;
920
921     struct {
922         mach_msg_header_t           header;
923         mach_msg_body_t             body;
924         mach_msg_port_descriptor_t  task_port;
925     } msg;
926
927     if (task_get_bootstrap_port(mach_task_self(), &bootstrap_port) != KERN_SUCCESS) return;
928
929     kret = bootstrap_look_up(bootstrap_port, (char*)wine_get_server_dir(), &wineserver_port);
930     if (kret != KERN_SUCCESS)
931         fatal_error( "cannot find the server port: 0x%08x\n", kret );
932
933     mach_port_deallocate(mach_task_self(), bootstrap_port);
934
935     msg.header.msgh_bits        = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0) | MACH_MSGH_BITS_COMPLEX;
936     msg.header.msgh_size        = sizeof(msg);
937     msg.header.msgh_remote_port = wineserver_port;
938     msg.header.msgh_local_port  = MACH_PORT_NULL;
939
940     msg.body.msgh_descriptor_count  = 1;
941     msg.task_port.name              = mach_task_self();
942     msg.task_port.disposition       = MACH_MSG_TYPE_COPY_SEND;
943     msg.task_port.type              = MACH_MSG_PORT_DESCRIPTOR;
944
945     kret = mach_msg_send(&msg.header);
946     if (kret != KERN_SUCCESS)
947         server_protocol_error( "mach_msg_send failed: 0x%08x\n", kret );
948
949     mach_port_deallocate(mach_task_self(), wineserver_port);
950 }
951 #endif  /* __APPLE__ */
952
953
954 /***********************************************************************
955  *           get_unix_tid
956  *
957  * Retrieve the Unix tid to use on the server side for the current thread.
958  */
959 static int get_unix_tid(void)
960 {
961     int ret = -1;
962 #ifdef HAVE_PTHREAD_GETTHREADID_NP
963     ret = pthread_getthreadid_np();
964 #elif defined(linux)
965     ret = syscall( __NR_gettid );
966 #elif defined(__sun)
967     ret = pthread_self();
968 #elif defined(__APPLE__)
969     ret = mach_thread_self();
970     mach_port_deallocate(mach_task_self(), ret);
971 #elif defined(__NetBSD__)
972     ret = _lwp_self();
973 #elif defined(__FreeBSD__)
974     long lwpid;
975     thr_self( &lwpid );
976     ret = lwpid;
977 #elif defined(__DragonFly__)
978     ret = lwp_gettid();
979 #endif
980     return ret;
981 }
982
983
984 /***********************************************************************
985  *           server_init_process
986  *
987  * Start the server and create the initial socket pair.
988  */
989 void server_init_process(void)
990 {
991     obj_handle_t version;
992     const char *env_socket = getenv( "WINESERVERSOCKET" );
993
994     server_pid = -1;
995     if (env_socket)
996     {
997         fd_socket = atoi( env_socket );
998         if (fcntl( fd_socket, F_SETFD, 1 ) == -1)
999             fatal_perror( "Bad server socket %d", fd_socket );
1000         unsetenv( "WINESERVERSOCKET" );
1001     }
1002     else fd_socket = server_connect();
1003
1004     /* setup the signal mask */
1005     sigemptyset( &server_block_set );
1006     sigaddset( &server_block_set, SIGALRM );
1007     sigaddset( &server_block_set, SIGIO );
1008     sigaddset( &server_block_set, SIGINT );
1009     sigaddset( &server_block_set, SIGHUP );
1010     sigaddset( &server_block_set, SIGUSR1 );
1011     sigaddset( &server_block_set, SIGUSR2 );
1012     sigaddset( &server_block_set, SIGCHLD );
1013     pthread_sigmask( SIG_BLOCK, &server_block_set, NULL );
1014
1015     /* receive the first thread request fd on the main socket */
1016     ntdll_get_thread_data()->request_fd = receive_fd( &version );
1017
1018 #ifdef SO_PASSCRED
1019     /* now that we hopefully received the server_pid, disable SO_PASSCRED */
1020     {
1021         int enable = 0;
1022         setsockopt( fd_socket, SOL_SOCKET, SO_PASSCRED, &enable, sizeof(enable) );
1023     }
1024 #endif
1025
1026     if (version != SERVER_PROTOCOL_VERSION)
1027         server_protocol_error( "version mismatch %d/%d.\n"
1028                                "Your %s binary was not upgraded correctly,\n"
1029                                "or you have an older one somewhere in your PATH.\n"
1030                                "Or maybe the wrong wineserver is still running?\n",
1031                                version, SERVER_PROTOCOL_VERSION,
1032                                (version > SERVER_PROTOCOL_VERSION) ? "wine" : "wineserver" );
1033 #ifdef __APPLE__
1034     send_server_task_port();
1035 #endif
1036 #if defined(__linux__) && defined(HAVE_PRCTL)
1037     /* work around Ubuntu's ptrace breakage */
1038     if (server_pid != -1) prctl( 0x59616d61 /* PR_SET_PTRACER */, server_pid );
1039 #endif
1040 }
1041
1042
1043 /***********************************************************************
1044  *           server_init_process_done
1045  */
1046 NTSTATUS server_init_process_done(void)
1047 {
1048     PEB *peb = NtCurrentTeb()->Peb;
1049     IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
1050     NTSTATUS status;
1051
1052     /* Install signal handlers; this cannot be done earlier, since we cannot
1053      * send exceptions to the debugger before the create process event that
1054      * is sent by REQ_INIT_PROCESS_DONE.
1055      * We do need the handlers in place by the time the request is over, so
1056      * we set them up here. If we segfault between here and the server call
1057      * something is very wrong... */
1058     signal_init_process();
1059
1060     /* Signal the parent process to continue */
1061     SERVER_START_REQ( init_process_done )
1062     {
1063         req->module   = wine_server_client_ptr( peb->ImageBaseAddress );
1064 #ifdef __i386__
1065         req->ldt_copy = wine_server_client_ptr( &wine_ldt_copy );
1066 #endif
1067         req->entry    = wine_server_client_ptr( (char *)peb->ImageBaseAddress + nt->OptionalHeader.AddressOfEntryPoint );
1068         req->gui      = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
1069         status = wine_server_call( req );
1070     }
1071     SERVER_END_REQ;
1072
1073     return status;
1074 }
1075
1076
1077 /***********************************************************************
1078  *           server_init_thread
1079  *
1080  * Send an init thread request. Return 0 if OK.
1081  */
1082 size_t server_init_thread( void *entry_point )
1083 {
1084     static const int is_win64 = (sizeof(void *) > sizeof(int));
1085     const char *arch = getenv( "WINEARCH" );
1086     int ret;
1087     int reply_pipe[2];
1088     struct sigaction sig_act;
1089     size_t info_size;
1090
1091     sig_act.sa_handler = SIG_IGN;
1092     sig_act.sa_flags   = 0;
1093     sigemptyset( &sig_act.sa_mask );
1094
1095     /* ignore SIGPIPE so that we get an EPIPE error instead  */
1096     sigaction( SIGPIPE, &sig_act, NULL );
1097
1098     /* create the server->client communication pipes */
1099     if (server_pipe( reply_pipe ) == -1) server_protocol_perror( "pipe" );
1100     if (server_pipe( ntdll_get_thread_data()->wait_fd ) == -1) server_protocol_perror( "pipe" );
1101     wine_server_send_fd( reply_pipe[1] );
1102     wine_server_send_fd( ntdll_get_thread_data()->wait_fd[1] );
1103     ntdll_get_thread_data()->reply_fd = reply_pipe[0];
1104     close( reply_pipe[1] );
1105
1106     SERVER_START_REQ( init_thread )
1107     {
1108         req->unix_pid    = getpid();
1109         req->unix_tid    = get_unix_tid();
1110         req->teb         = wine_server_client_ptr( NtCurrentTeb() );
1111         req->entry       = wine_server_client_ptr( entry_point );
1112         req->reply_fd    = reply_pipe[1];
1113         req->wait_fd     = ntdll_get_thread_data()->wait_fd[1];
1114         req->debug_level = (TRACE_ON(server) != 0);
1115         req->cpu         = client_cpu;
1116         ret = wine_server_call( req );
1117         NtCurrentTeb()->ClientId.UniqueProcess = ULongToHandle(reply->pid);
1118         NtCurrentTeb()->ClientId.UniqueThread  = ULongToHandle(reply->tid);
1119         info_size         = reply->info_size;
1120         server_start_time = reply->server_start;
1121         server_cpus       = reply->all_cpus;
1122     }
1123     SERVER_END_REQ;
1124
1125     is_wow64 = !is_win64 && (server_cpus & (1 << CPU_x86_64)) != 0;
1126     ntdll_get_thread_data()->wow64_redir = is_wow64;
1127
1128     switch (ret)
1129     {
1130     case STATUS_SUCCESS:
1131         if (arch)
1132         {
1133             if (!strcmp( arch, "win32" ) && (is_win64 || is_wow64))
1134                 fatal_error( "WINEARCH set to win32 but '%s' is a 64-bit installation.\n",
1135                              wine_get_config_dir() );
1136             if (!strcmp( arch, "win64" ) && !is_win64 && !is_wow64)
1137                 fatal_error( "WINEARCH set to win64 but '%s' is a 32-bit installation.\n",
1138                              wine_get_config_dir() );
1139         }
1140         return info_size;
1141     case STATUS_NOT_REGISTRY_FILE:
1142         fatal_error( "'%s' is a 32-bit installation, it cannot support 64-bit applications.\n",
1143                      wine_get_config_dir() );
1144     case STATUS_NOT_SUPPORTED:
1145         if (is_win64)
1146             fatal_error( "wineserver is 32-bit, it cannot support 64-bit applications.\n" );
1147         else
1148             fatal_error( "'%s' is a 64-bit installation, it cannot be used with a 32-bit wineserver.\n",
1149                          wine_get_config_dir() );
1150     default:
1151         server_protocol_error( "init_thread failed with status %x\n", ret );
1152     }
1153 }