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