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