loader: On Mac, if Wine is already on secondary thread, don't reserve it for the...
[wine] / libs / wine / loader.c
1 /*
2  * Win32 builtin dlls support
3  *
4  * Copyright 2000 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 #include <fcntl.h>
27 #include <limits.h>
28 #include <stdarg.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/types.h>
32 #ifdef HAVE_SYS_MMAN_H
33 #include <sys/mman.h>
34 #endif
35 #ifdef HAVE_SYS_RESOURCE_H
36 # include <sys/resource.h>
37 #endif
38 #ifdef HAVE_UNISTD_H
39 # include <unistd.h>
40 #endif
41
42 #ifdef __APPLE__
43 #include <crt_externs.h>
44 #define environ (*_NSGetEnviron())
45 #include <CoreFoundation/CoreFoundation.h>
46 #define LoadResource MacLoadResource
47 #define GetCurrentThread MacGetCurrentThread
48 #include <CoreServices/CoreServices.h>
49 #undef LoadResource
50 #undef GetCurrentThread
51 #include <pthread.h>
52 #else
53 extern char **environ;
54 #endif
55
56 #define NONAMELESSUNION
57 #define NONAMELESSSTRUCT
58 #include "windef.h"
59 #include "winbase.h"
60 #include "wine/library.h"
61
62 /* argc/argv for the Windows application */
63 int __wine_main_argc = 0;
64 char **__wine_main_argv = NULL;
65 WCHAR **__wine_main_wargv = NULL;
66 char **__wine_main_environ = NULL;
67
68 struct dll_path_context
69 {
70     unsigned int index; /* current index in the dll path list */
71     char *buffer;       /* buffer used for storing path names */
72     char *name;         /* start of file name part in buffer (including leading slash) */
73     int   namelen;      /* length of file name without .so extension */
74     int   win16;        /* 16-bit dll search */
75 };
76
77 #define MAX_DLLS 100
78
79 static struct
80 {
81     const IMAGE_NT_HEADERS *nt;           /* NT header */
82     const char             *filename;     /* DLL file name */
83 } builtin_dlls[MAX_DLLS];
84
85 static int nb_dlls;
86
87 static const IMAGE_NT_HEADERS *main_exe;
88
89 static load_dll_callback_t load_dll_callback;
90
91 static const char *build_dir;
92 static const char *default_dlldir;
93 static const char **dll_paths;
94 static unsigned int nb_dll_paths;
95 static int dll_path_maxlen;
96
97 extern void mmap_init(void);
98 extern const char *get_dlldir( const char **default_dlldir );
99
100 /* build the dll load path from the WINEDLLPATH variable */
101 static void build_dll_path(void)
102 {
103     int len, count = 0;
104     char *p, *path = getenv( "WINEDLLPATH" );
105     const char *dlldir = get_dlldir( &default_dlldir );
106
107     if (path)
108     {
109         /* count how many path elements we need */
110         path = strdup(path);
111         p = path;
112         while (*p)
113         {
114             while (*p == ':') p++;
115             if (!*p) break;
116             count++;
117             while (*p && *p != ':') p++;
118         }
119     }
120
121     dll_paths = malloc( (count+2) * sizeof(*dll_paths) );
122     nb_dll_paths = 0;
123
124     if (dlldir)
125     {
126         dll_path_maxlen = strlen(dlldir);
127         dll_paths[nb_dll_paths++] = dlldir;
128     }
129     else if ((build_dir = wine_get_build_dir()))
130     {
131         dll_path_maxlen = strlen(build_dir) + sizeof("/programs");
132     }
133
134     if (count)
135     {
136         p = path;
137         while (*p)
138         {
139             while (*p == ':') *p++ = 0;
140             if (!*p) break;
141             dll_paths[nb_dll_paths] = p;
142             while (*p && *p != ':') p++;
143             if (p - dll_paths[nb_dll_paths] > dll_path_maxlen)
144                 dll_path_maxlen = p - dll_paths[nb_dll_paths];
145             nb_dll_paths++;
146         }
147     }
148
149     /* append default dll dir (if not empty) to path */
150     if ((len = strlen(default_dlldir)) > 0)
151     {
152         if (len > dll_path_maxlen) dll_path_maxlen = len;
153         dll_paths[nb_dll_paths++] = default_dlldir;
154     }
155 }
156
157 /* check if the library is the correct architecture */
158 /* only returns false for a valid library of the wrong arch */
159 static int check_library_arch( int fd )
160 {
161 #ifdef __APPLE__
162     struct  /* Mach-O header */
163     {
164         unsigned int magic;
165         unsigned int cputype;
166     } header;
167
168     if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
169     if (header.magic != 0xfeedface) return 1;
170     if (sizeof(void *) == sizeof(int)) return !(header.cputype >> 24);
171     else return (header.cputype >> 24) == 1; /* CPU_ARCH_ABI64 */
172 #else
173     struct  /* ELF header */
174     {
175         unsigned char magic[4];
176         unsigned char class;
177         unsigned char data;
178         unsigned char version;
179     } header;
180
181     if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
182     if (memcmp( header.magic, "\177ELF", 4 )) return 1;
183     if (header.version != 1 /* EV_CURRENT */) return 1;
184 #ifdef WORDS_BIGENDIAN
185     if (header.data != 2 /* ELFDATA2MSB */) return 1;
186 #else
187     if (header.data != 1 /* ELFDATA2LSB */) return 1;
188 #endif
189     if (sizeof(void *) == sizeof(int)) return header.class == 1; /* ELFCLASS32 */
190     else return header.class == 2; /* ELFCLASS64 */
191 #endif
192 }
193
194 /* check if a given file can be opened */
195 static inline int file_exists( const char *name )
196 {
197     int ret = 0;
198     int fd = open( name, O_RDONLY );
199     if (fd != -1)
200     {
201         ret = check_library_arch( fd );
202         close( fd );
203     }
204     return ret;
205 }
206
207 static inline char *prepend( char *buffer, const char *str, size_t len )
208 {
209     return memcpy( buffer - len, str, len );
210 }
211
212 /* get a filename from the next entry in the dll path */
213 static char *next_dll_path( struct dll_path_context *context )
214 {
215     unsigned int index = context->index++;
216     int namelen = context->namelen;
217     char *path = context->name;
218
219     switch(index)
220     {
221     case 0:  /* try dlls dir with subdir prefix */
222         if (namelen > 4 && !memcmp( context->name + namelen - 4, ".dll", 4 )) namelen -= 4;
223         if (!context->win16) path = prepend( path, context->name, namelen );
224         path = prepend( path, "/dlls", sizeof("/dlls") - 1 );
225         path = prepend( path, build_dir, strlen(build_dir) );
226         return path;
227     case 1:  /* try programs dir with subdir prefix */
228         if (!context->win16)
229         {
230             if (namelen > 4 && !memcmp( context->name + namelen - 4, ".exe", 4 )) namelen -= 4;
231             path = prepend( path, context->name, namelen );
232             path = prepend( path, "/programs", sizeof("/programs") - 1 );
233             path = prepend( path, build_dir, strlen(build_dir) );
234             return path;
235         }
236         context->index++;
237         /* fall through */
238     default:
239         index -= 2;
240         if (index < nb_dll_paths)
241             return prepend( context->name, dll_paths[index], strlen( dll_paths[index] ));
242         break;
243     }
244     return NULL;
245 }
246
247
248 /* get a filename from the first entry in the dll path */
249 static char *first_dll_path( const char *name, int win16, struct dll_path_context *context )
250 {
251     char *p;
252     int namelen = strlen( name );
253     const char *ext = win16 ? "16" : ".so";
254
255     context->buffer = malloc( dll_path_maxlen + 2 * namelen + strlen(ext) + 3 );
256     context->index = build_dir ? 0 : 2;  /* if no build dir skip all the build dir magic cases */
257     context->name = context->buffer + dll_path_maxlen + namelen + 1;
258     context->namelen = namelen + 1;
259     context->win16 = win16;
260
261     /* store the name at the end of the buffer, followed by extension */
262     p = context->name;
263     *p++ = '/';
264     memcpy( p, name, namelen );
265     strcpy( p + namelen, ext );
266     return next_dll_path( context );
267 }
268
269
270 /* free the dll path context created by first_dll_path */
271 static inline void free_dll_path( struct dll_path_context *context )
272 {
273     free( context->buffer );
274 }
275
276
277 /* open a library for a given dll, searching in the dll path
278  * 'name' must be the Windows dll name (e.g. "kernel32.dll") */
279 static void *dlopen_dll( const char *name, char *error, int errorsize,
280                          int test_only, int *exists )
281 {
282     struct dll_path_context context;
283     char *path;
284     void *ret = NULL;
285
286     *exists = 0;
287     for (path = first_dll_path( name, 0, &context ); path; path = next_dll_path( &context ))
288     {
289         if (!test_only && (ret = wine_dlopen( path, RTLD_NOW, error, errorsize ))) break;
290         if ((*exists = file_exists( path ))) break; /* exists but cannot be loaded, return the error */
291     }
292     free_dll_path( &context );
293     return ret;
294 }
295
296
297 /* adjust an array of pointers to make them into RVAs */
298 static inline void fixup_rva_ptrs( void *array, BYTE *base, unsigned int count )
299 {
300     void **src = (void **)array;
301     DWORD *dst = (DWORD *)array;
302     while (count--)
303     {
304         *dst++ = *src ? (BYTE *)*src - base : 0;
305         src++;
306     }
307 }
308
309 /* fixup an array of RVAs by adding the specified delta */
310 static inline void fixup_rva_dwords( DWORD *ptr, int delta, unsigned int count )
311 {
312     while (count--)
313     {
314         if (*ptr) *ptr += delta;
315         ptr++;
316     }
317 }
318
319
320 /* fixup RVAs in the import directory */
321 static void fixup_imports( IMAGE_IMPORT_DESCRIPTOR *dir, BYTE *base, int delta )
322 {
323     UINT_PTR *ptr;
324
325     while (dir->Name)
326     {
327         fixup_rva_dwords( &dir->u.OriginalFirstThunk, delta, 1 );
328         fixup_rva_dwords( &dir->Name, delta, 1 );
329         fixup_rva_dwords( &dir->FirstThunk, delta, 1 );
330         ptr = (UINT_PTR *)(base + (dir->u.OriginalFirstThunk ? dir->u.OriginalFirstThunk : dir->FirstThunk));
331         while (*ptr)
332         {
333             if (!(*ptr & IMAGE_ORDINAL_FLAG)) *ptr += delta;
334             ptr++;
335         }
336         dir++;
337     }
338 }
339
340
341 /* fixup RVAs in the export directory */
342 static void fixup_exports( IMAGE_EXPORT_DIRECTORY *dir, BYTE *base, int delta )
343 {
344     fixup_rva_dwords( &dir->Name, delta, 1 );
345     fixup_rva_dwords( &dir->AddressOfFunctions, delta, 1 );
346     fixup_rva_dwords( &dir->AddressOfNames, delta, 1 );
347     fixup_rva_dwords( &dir->AddressOfNameOrdinals, delta, 1 );
348     fixup_rva_dwords( (DWORD *)(base + dir->AddressOfNames), delta, dir->NumberOfNames );
349     fixup_rva_ptrs( (base + dir->AddressOfFunctions), base, dir->NumberOfFunctions );
350 }
351
352
353 /* fixup RVAs in the resource directory */
354 static void fixup_resources( IMAGE_RESOURCE_DIRECTORY *dir, BYTE *root, int delta )
355 {
356     IMAGE_RESOURCE_DIRECTORY_ENTRY *entry;
357     int i;
358
359     entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
360     for (i = 0; i < dir->NumberOfNamedEntries + dir->NumberOfIdEntries; i++, entry++)
361     {
362         void *ptr = root + entry->u2.s3.OffsetToDirectory;
363         if (entry->u2.s3.DataIsDirectory) fixup_resources( ptr, root, delta );
364         else
365         {
366             IMAGE_RESOURCE_DATA_ENTRY *data = ptr;
367             fixup_rva_dwords( &data->OffsetToData, delta, 1 );
368         }
369     }
370 }
371
372
373 /* map a builtin dll in memory and fixup RVAs */
374 static void *map_dll( const IMAGE_NT_HEADERS *nt_descr )
375 {
376 #ifdef HAVE_MMAP
377     IMAGE_DATA_DIRECTORY *dir;
378     IMAGE_DOS_HEADER *dos;
379     IMAGE_NT_HEADERS *nt;
380     IMAGE_SECTION_HEADER *sec;
381     BYTE *addr;
382     DWORD code_start, data_start, data_end;
383     const size_t page_size = sysconf( _SC_PAGESIZE );
384     const size_t page_mask = page_size - 1;
385     int delta, nb_sections = 2;  /* code + data */
386     unsigned int i;
387
388     size_t size = (sizeof(IMAGE_DOS_HEADER)
389                    + sizeof(IMAGE_NT_HEADERS)
390                    + nb_sections * sizeof(IMAGE_SECTION_HEADER));
391
392     assert( size <= page_size );
393
394     /* module address must be aligned on 64K boundary */
395     addr = (BYTE *)((nt_descr->OptionalHeader.ImageBase + 0xffff) & ~0xffff);
396     if (wine_anon_mmap( addr, page_size, PROT_READ|PROT_WRITE, MAP_FIXED ) != addr) return NULL;
397
398     dos    = (IMAGE_DOS_HEADER *)addr;
399     nt     = (IMAGE_NT_HEADERS *)(dos + 1);
400     sec    = (IMAGE_SECTION_HEADER *)(nt + 1);
401
402     /* Build the DOS and NT headers */
403
404     dos->e_magic    = IMAGE_DOS_SIGNATURE;
405     dos->e_cblp     = 0x90;
406     dos->e_cp       = 3;
407     dos->e_cparhdr  = (sizeof(*dos)+0xf)/0x10;
408     dos->e_minalloc = 0;
409     dos->e_maxalloc = 0xffff;
410     dos->e_ss       = 0x0000;
411     dos->e_sp       = 0x00b8;
412     dos->e_lfarlc   = sizeof(*dos);
413     dos->e_lfanew   = sizeof(*dos);
414
415     *nt = *nt_descr;
416
417     delta      = (const BYTE *)nt_descr - addr;
418     code_start = page_size;
419     data_start = delta & ~page_mask;
420     data_end   = (nt->OptionalHeader.SizeOfImage + delta + page_mask) & ~page_mask;
421
422     fixup_rva_ptrs( &nt->OptionalHeader.AddressOfEntryPoint, addr, 1 );
423
424     nt->FileHeader.NumberOfSections                = nb_sections;
425     nt->OptionalHeader.BaseOfCode                  = code_start;
426 #ifndef _WIN64
427     nt->OptionalHeader.BaseOfData                  = data_start;
428 #endif
429     nt->OptionalHeader.SizeOfCode                  = data_start - code_start;
430     nt->OptionalHeader.SizeOfInitializedData       = data_end - data_start;
431     nt->OptionalHeader.SizeOfUninitializedData     = 0;
432     nt->OptionalHeader.SizeOfImage                 = data_end;
433     nt->OptionalHeader.ImageBase                   = (ULONG_PTR)addr;
434
435     /* Build the code section */
436
437     memcpy( sec->Name, ".text", sizeof(".text") );
438     sec->SizeOfRawData = data_start - code_start;
439     sec->Misc.VirtualSize = sec->SizeOfRawData;
440     sec->VirtualAddress   = code_start;
441     sec->PointerToRawData = code_start;
442     sec->Characteristics  = (IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ);
443     sec++;
444
445     /* Build the data section */
446
447     memcpy( sec->Name, ".data", sizeof(".data") );
448     sec->SizeOfRawData = data_end - data_start;
449     sec->Misc.VirtualSize = sec->SizeOfRawData;
450     sec->VirtualAddress   = data_start;
451     sec->PointerToRawData = data_start;
452     sec->Characteristics  = (IMAGE_SCN_CNT_INITIALIZED_DATA |
453                              IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ);
454     sec++;
455
456     for (i = 0; i < nt->OptionalHeader.NumberOfRvaAndSizes; i++)
457         fixup_rva_dwords( &nt->OptionalHeader.DataDirectory[i].VirtualAddress, delta, 1 );
458
459     /* Build the import directory */
460
461     dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY];
462     if (dir->Size)
463     {
464         IMAGE_IMPORT_DESCRIPTOR *imports = (void *)(addr + dir->VirtualAddress);
465         fixup_imports( imports, addr, delta );
466     }
467
468     /* Build the resource directory */
469
470     dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_RESOURCE_DIRECTORY];
471     if (dir->Size)
472     {
473         void *ptr = (void *)(addr + dir->VirtualAddress);
474         fixup_resources( ptr, ptr, delta );
475     }
476
477     /* Build the export directory */
478
479     dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_EXPORT_DIRECTORY];
480     if (dir->Size)
481     {
482         IMAGE_EXPORT_DIRECTORY *exports = (void *)(addr + dir->VirtualAddress);
483         fixup_exports( exports, addr, delta );
484     }
485     return addr;
486 #else  /* HAVE_MMAP */
487     return NULL;
488 #endif  /* HAVE_MMAP */
489 }
490
491
492 /***********************************************************************
493  *           __wine_get_main_environment
494  *
495  * Return an environment pointer to work around lack of environ variable.
496  * Only exported on Mac OS.
497  */
498 char **__wine_get_main_environment(void)
499 {
500     return environ;
501 }
502
503
504 /***********************************************************************
505  *           __wine_dll_register
506  *
507  * Register a built-in DLL descriptor.
508  */
509 void __wine_dll_register( const IMAGE_NT_HEADERS *header, const char *filename )
510 {
511     if (load_dll_callback) load_dll_callback( map_dll(header), filename );
512     else
513     {
514         if (!(header->FileHeader.Characteristics & IMAGE_FILE_DLL))
515             main_exe = header;
516         else
517         {
518             assert( nb_dlls < MAX_DLLS );
519             builtin_dlls[nb_dlls].nt = header;
520             builtin_dlls[nb_dlls].filename = filename;
521             nb_dlls++;
522         }
523     }
524 }
525
526
527 /***********************************************************************
528  *           wine_dll_set_callback
529  *
530  * Set the callback function for dll loading, and call it
531  * for all dlls that were implicitly loaded already.
532  */
533 void wine_dll_set_callback( load_dll_callback_t load )
534 {
535     int i;
536     load_dll_callback = load;
537     for (i = 0; i < nb_dlls; i++)
538     {
539         const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
540         if (!nt) continue;
541         builtin_dlls[i].nt = NULL;
542         load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
543     }
544     nb_dlls = 0;
545     if (main_exe) load_dll_callback( map_dll(main_exe), "" );
546 }
547
548
549 /***********************************************************************
550  *           wine_dll_load
551  *
552  * Load a builtin dll.
553  */
554 void *wine_dll_load( const char *filename, char *error, int errorsize, int *file_exists )
555 {
556     int i;
557
558     /* callback must have been set already */
559     assert( load_dll_callback );
560
561     /* check if we have it in the list */
562     /* this can happen when initializing pre-loaded dlls in wine_dll_set_callback */
563     for (i = 0; i < nb_dlls; i++)
564     {
565         if (!builtin_dlls[i].nt) continue;
566         if (!strcmp( builtin_dlls[i].filename, filename ))
567         {
568             const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
569             builtin_dlls[i].nt = NULL;
570             load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
571             *file_exists = 1;
572             return (void *)1;
573         }
574     }
575     return dlopen_dll( filename, error, errorsize, 0, file_exists );
576 }
577
578
579 /***********************************************************************
580  *           wine_dll_unload
581  *
582  * Unload a builtin dll.
583  */
584 void wine_dll_unload( void *handle )
585 {
586     if (handle != (void *)1)
587         wine_dlclose( handle, NULL, 0 );
588 }
589
590
591 /***********************************************************************
592  *           wine_dll_load_main_exe
593  *
594  * Try to load the .so for the main exe.
595  */
596 void *wine_dll_load_main_exe( const char *name, char *error, int errorsize,
597                               int test_only, int *file_exists )
598 {
599     return dlopen_dll( name, error, errorsize, test_only, file_exists );
600 }
601
602
603 /***********************************************************************
604  *           wine_dll_enum_load_path
605  *
606  * Enumerate the dll load path.
607  */
608 const char *wine_dll_enum_load_path( unsigned int index )
609 {
610     if (index >= nb_dll_paths) return NULL;
611     return dll_paths[index];
612 }
613
614
615 /***********************************************************************
616  *           wine_dll_get_owner
617  *
618  * Retrieve the name of the 32-bit owner dll for a 16-bit dll.
619  * Return 0 if OK, -1 on error.
620  */
621 int wine_dll_get_owner( const char *name, char *buffer, int size, int *exists )
622 {
623     int ret = -1;
624     char *path;
625     struct dll_path_context context;
626
627     *exists = 0;
628
629     for (path = first_dll_path( name, 1, &context ); path; path = next_dll_path( &context ))
630     {
631         int fd = open( path, O_RDONLY );
632         if (fd != -1)
633         {
634             int res = read( fd, buffer, size - 1 );
635             while (res > 0 && (buffer[res-1] == '\n' || buffer[res-1] == '\r')) res--;
636             buffer[res] = 0;
637             close( fd );
638             *exists = 1;
639             ret = 0;
640             break;
641         }
642     }
643     free_dll_path( &context );
644     return ret;
645 }
646
647
648 /***********************************************************************
649  *           set_max_limit
650  *
651  * Set a user limit to the maximum allowed value.
652  */
653 static void set_max_limit( int limit )
654 {
655 #ifdef HAVE_SETRLIMIT
656     struct rlimit rlimit;
657
658     if (!getrlimit( limit, &rlimit ))
659     {
660         rlimit.rlim_cur = rlimit.rlim_max;
661         if (setrlimit( limit, &rlimit ) != 0)
662         {
663 #if defined(__APPLE__) && defined(RLIMIT_NOFILE) && defined(OPEN_MAX)
664             /* On Leopard, setrlimit(RLIMIT_NOFILE, ...) fails on attempts to set
665              * rlim_cur above OPEN_MAX (even if rlim_max > OPEN_MAX). */
666             if (limit == RLIMIT_NOFILE && rlimit.rlim_cur > OPEN_MAX)
667             {
668                 rlimit.rlim_cur = OPEN_MAX;
669                 setrlimit( limit, &rlimit );
670             }
671 #endif
672         }
673     }
674 #endif
675 }
676
677
678 #ifdef __APPLE__
679 struct apple_stack_info
680 {
681     void *stack;
682     size_t desired_size;
683 };
684
685 /***********************************************************************
686  *           apple_alloc_thread_stack
687  *
688  * Callback for wine_mmap_enum_reserved_areas to allocate space for
689  * the secondary thread's stack.
690  */
691 static int apple_alloc_thread_stack( void *base, size_t size, void *arg )
692 {
693     struct apple_stack_info *info = arg;
694
695     /* For mysterious reasons, putting the thread stack at the very top
696      * of the address space causes subsequent execs to fail, even on the
697      * child side of a fork.  Avoid the top 16MB. */
698     char * const limit = (char*)0xff000000;
699     if ((char *)base >= limit) return 0;
700     if (size > limit - (char*)base)
701         size = limit - (char*)base;
702     if (size < info->desired_size) return 0;
703     info->stack = wine_anon_mmap( (char *)base + size - info->desired_size,
704                                   info->desired_size, PROT_READ|PROT_WRITE, MAP_FIXED );
705     return (info->stack != (void *)-1);
706 }
707
708 /***********************************************************************
709  *           apple_create_wine_thread
710  *
711  * Spin off a secondary thread to complete Wine initialization, leaving
712  * the original thread for the Mac frameworks.
713  *
714  * Invoked as a CFRunLoopSource perform callback.
715  */
716 static void apple_create_wine_thread( void *init_func )
717 {
718     int success = 0;
719     pthread_t thread;
720     pthread_attr_t attr;
721
722     if (!pthread_attr_init( &attr ))
723     {
724         struct apple_stack_info info;
725
726         /* Try to put the new thread's stack in the reserved area.  If this
727          * fails, just let it go wherever.  It'll be a waste of space, but we
728          * can go on. */
729         if (!pthread_attr_getstacksize( &attr, &info.desired_size ) &&
730             wine_mmap_enum_reserved_areas( apple_alloc_thread_stack, &info, 1 ))
731         {
732             wine_mmap_remove_reserved_area( info.stack, info.desired_size, 0 );
733             pthread_attr_setstackaddr( &attr, (char*)info.stack + info.desired_size );
734         }
735
736         if (!pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ) &&
737             !pthread_create( &thread, &attr, init_func, NULL ))
738             success = 1;
739
740         pthread_attr_destroy( &attr );
741     }
742
743     /* Failure is indicated by returning from wine_init().  Stopping
744      * the run loop allows apple_main_thread() and thus wine_init() to
745      * return. */
746     if (!success)
747         CFRunLoopStop( CFRunLoopGetCurrent() );
748 }
749
750
751 /***********************************************************************
752  *           apple_main_thread
753  *
754  * Park the process's original thread in a Core Foundation run loop for
755  * use by the Mac frameworks, especially receiving and handling
756  * distributed notifications.  Spin off a new thread for the rest of the
757  * Wine initialization.
758  */
759 static void apple_main_thread( void (*init_func)(void) )
760 {
761     CFRunLoopSourceContext source_context = { 0 };
762     CFRunLoopSourceRef source;
763
764     if (!pthread_main_np())
765     {
766         init_func();
767         return;
768     }
769
770     /* Multi-processing Services can get confused about the main thread if the
771      * first time it's used is on a secondary thread.  Use it here to make sure
772      * that doesn't happen. */
773     MPTaskIsPreemptive(MPCurrentTaskID());
774
775     /* Give ourselves the best chance of having the distributed notification
776      * center scheduled on this thread's run loop.  In theory, it's scheduled
777      * in the first thread to ask for it. */
778     CFNotificationCenterGetDistributedCenter();
779
780     /* We use this run loop source for two purposes.  First, a run loop exits
781      * if it has no more sources scheduled.  So, we need at least one source
782      * to keep the run loop running.  Second, although it's not critical, it's
783      * preferable for the Wine initialization to not proceed until we know
784      * the run loop is running.  So, we signal our source immediately after
785      * adding it and have its callback spin off the Wine thread. */
786     source_context.info = init_func;
787     source_context.perform = apple_create_wine_thread;
788     source = CFRunLoopSourceCreate( NULL, 0, &source_context );
789
790     if (source)
791     {
792         CFRunLoopAddSource( CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes );
793         CFRunLoopSourceSignal( source );
794         CFRelease( source );
795
796         CFRunLoopRun(); /* Should never return, except on error. */
797     }
798
799     /* If we get here (i.e. return), that indicates failure to our caller. */
800 }
801 #endif
802
803
804 /***********************************************************************
805  *           wine_init
806  *
807  * Main Wine initialisation.
808  */
809 void wine_init( int argc, char *argv[], char *error, int error_size )
810 {
811     struct dll_path_context context;
812     char *path;
813     void *ntdll = NULL;
814     void (*init_func)(void);
815
816     /* force a few limits that are set too low on some platforms */
817 #ifdef RLIMIT_NOFILE
818     set_max_limit( RLIMIT_NOFILE );
819 #endif
820 #ifdef RLIMIT_AS
821     set_max_limit( RLIMIT_AS );
822 #endif
823
824     wine_init_argv0_path( argv[0] );
825     build_dll_path();
826     __wine_main_argc = argc;
827     __wine_main_argv = argv;
828     __wine_main_environ = __wine_get_main_environment();
829     mmap_init();
830
831     for (path = first_dll_path( "ntdll.dll", 0, &context ); path; path = next_dll_path( &context ))
832     {
833         if ((ntdll = wine_dlopen( path, RTLD_NOW, error, error_size )))
834         {
835             /* if we didn't use the default dll dir, remove it from the search path */
836             if (default_dlldir[0] && context.index < nb_dll_paths + 2) nb_dll_paths--;
837             break;
838         }
839     }
840     free_dll_path( &context );
841
842     if (!ntdll) return;
843     if (!(init_func = wine_dlsym( ntdll, "__wine_process_init", error, error_size ))) return;
844 #ifdef __APPLE__
845     apple_main_thread( init_func );
846 #else
847     init_func();
848 #endif
849 }
850
851
852 /*
853  * These functions provide wrappers around dlopen() and associated
854  * functions.  They work around a bug in glibc 2.1.x where calling
855  * a dl*() function after a previous dl*() function has failed
856  * without a dlerror() call between the two will cause a crash.
857  * They all take a pointer to a buffer that
858  * will receive the error description (from dlerror()).  This
859  * parameter may be NULL if the error description is not required.
860  */
861
862 #ifndef RTLD_FIRST
863 #define RTLD_FIRST 0
864 #endif
865
866 /***********************************************************************
867  *              wine_dlopen
868  */
869 void *wine_dlopen( const char *filename, int flag, char *error, size_t errorsize )
870 {
871 #ifdef HAVE_DLOPEN
872     void *ret;
873     const char *s;
874
875 #ifdef __APPLE__
876     /* the Mac OS loader pretends to be able to load PE files, so avoid them here */
877     unsigned char magic[2];
878     int fd = open( filename, O_RDONLY );
879     if (fd != -1)
880     {
881         if (pread( fd, magic, 2, 0 ) == 2 && magic[0] == 'M' && magic[1] == 'Z')
882         {
883             static const char msg[] = "MZ format";
884             size_t len = min( errorsize, sizeof(msg) );
885             memcpy( error, msg, len );
886             error[len - 1] = 0;
887             close( fd );
888             return NULL;
889         }
890         close( fd );
891     }
892 #endif
893     dlerror(); dlerror();
894 #ifdef __sun
895     if (strchr( filename, ':' ))
896     {
897         char path[PATH_MAX];
898         /* Solaris' brain damaged dlopen() treats ':' as a path separator */
899         realpath( filename, path );
900         ret = dlopen( path, flag | RTLD_FIRST );
901     }
902     else
903 #endif
904     ret = dlopen( filename, flag | RTLD_FIRST );
905     s = dlerror();
906     if (error && errorsize)
907     {
908         if (s)
909         {
910             size_t len = strlen(s);
911             if (len >= errorsize) len = errorsize - 1;
912             memcpy( error, s, len );
913             error[len] = 0;
914         }
915         else error[0] = 0;
916     }
917     dlerror();
918     return ret;
919 #else
920     if (error)
921     {
922         static const char msg[] = "dlopen interface not detected by configure";
923         size_t len = min( errorsize, sizeof(msg) );
924         memcpy( error, msg, len );
925         error[len - 1] = 0;
926     }
927     return NULL;
928 #endif
929 }
930
931 /***********************************************************************
932  *              wine_dlsym
933  */
934 void *wine_dlsym( void *handle, const char *symbol, char *error, size_t errorsize )
935 {
936 #ifdef HAVE_DLOPEN
937     void *ret;
938     const char *s;
939     dlerror(); dlerror();
940     ret = dlsym( handle, symbol );
941     s = dlerror();
942     if (error && errorsize)
943     {
944         if (s)
945         {
946             size_t len = strlen(s);
947             if (len >= errorsize) len = errorsize - 1;
948             memcpy( error, s, len );
949             error[len] = 0;
950         }
951         else error[0] = 0;
952     }
953     dlerror();
954     return ret;
955 #else
956     if (error)
957     {
958         static const char msg[] = "dlopen interface not detected by configure";
959         size_t len = min( errorsize, sizeof(msg) );
960         memcpy( error, msg, len );
961         error[len - 1] = 0;
962     }
963     return NULL;
964 #endif
965 }
966
967 /***********************************************************************
968  *              wine_dlclose
969  */
970 int wine_dlclose( void *handle, char *error, size_t errorsize )
971 {
972 #ifdef HAVE_DLOPEN
973     int ret;
974     const char *s;
975     dlerror(); dlerror();
976     ret = dlclose( handle );
977     s = dlerror();
978     if (error && errorsize)
979     {
980         if (s)
981         {
982             size_t len = strlen(s);
983             if (len >= errorsize) len = errorsize - 1;
984             memcpy( error, s, len );
985             error[len] = 0;
986         }
987         else error[0] = 0;
988     }
989     dlerror();
990     return ret;
991 #else
992     if (error)
993     {
994         static const char msg[] = "dlopen interface not detected by configure";
995         size_t len = min( errorsize, sizeof(msg) );
996         memcpy( error, msg, len );
997         error[len - 1] = 0;
998     }
999     return 1;
1000 #endif
1001 }