winemac: Don't use sprintfW in copy_system_cursor_name.
[wine.git] / libs / wine / loader.c
blobad72ec50904e20c4aace5730197b0ccecdfc9a05
1 /*
2 * Win32 builtin dlls support
4 * Copyright 2000 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
23 #include <assert.h>
24 #include <ctype.h>
25 #include <fcntl.h>
26 #include <limits.h>
27 #include <stdarg.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/types.h>
31 #include <sys/mman.h>
32 #ifdef HAVE_SYS_RESOURCE_H
33 # include <sys/resource.h>
34 #endif
35 #include <unistd.h>
36 #include <dlfcn.h>
38 #ifdef __APPLE__
39 #include <crt_externs.h>
40 #define environ (*_NSGetEnviron())
41 #include <CoreFoundation/CoreFoundation.h>
42 #define LoadResource MacLoadResource
43 #define GetCurrentThread MacGetCurrentThread
44 #include <CoreServices/CoreServices.h>
45 #undef LoadResource
46 #undef GetCurrentThread
47 #include <pthread.h>
48 #include <mach-o/getsect.h>
49 #else
50 extern char **environ;
51 #endif
53 #define NONAMELESSUNION
54 #define NONAMELESSSTRUCT
55 #include "windef.h"
56 #include "winbase.h"
57 #include "wine/asm.h"
59 /* argc/argv for the Windows application */
60 int __wine_main_argc = 0;
61 char **__wine_main_argv = NULL;
62 WCHAR **__wine_main_wargv = NULL;
63 char **__wine_main_environ = NULL;
65 #define MAX_DLLS 100
67 static struct
69 const IMAGE_NT_HEADERS *nt; /* NT header */
70 const char *filename; /* DLL file name */
71 } builtin_dlls[MAX_DLLS];
73 static int nb_dlls;
75 static const IMAGE_NT_HEADERS *main_exe;
77 typedef void (*load_dll_callback_t)( void *, const char * );
78 static load_dll_callback_t load_dll_callback;
80 extern void *wine_anon_mmap( void *start, size_t size, int prot, int flags );
82 #ifdef __ASM_OBSOLETE
84 struct dll_path_context
86 unsigned int index; /* current index in the dll path list */
87 char *buffer; /* buffer used for storing path names */
88 char *name; /* start of file name part in buffer (including leading slash) */
89 int namelen; /* length of file name without .so extension */
90 int win16; /* 16-bit dll search */
93 static const char *default_dlldir;
94 static const char **dll_paths;
95 static unsigned int nb_dll_paths;
96 static int dll_path_maxlen;
98 extern const char *build_dir;
100 extern void wine_init_argv0_path_obsolete( const char *argv0 );
101 extern void mmap_init(void);
102 extern const char *get_dlldir( const char **default_dlldir );
104 /* build the dll load path from the WINEDLLPATH variable */
105 static void build_dll_path(void)
107 int len, count = 0;
108 char *p, *path = getenv( "WINEDLLPATH" );
109 const char *dlldir = get_dlldir( &default_dlldir );
111 if (path)
113 /* count how many path elements we need */
114 path = strdup(path);
115 p = path;
116 while (*p)
118 while (*p == ':') p++;
119 if (!*p) break;
120 count++;
121 while (*p && *p != ':') p++;
125 dll_paths = malloc( (count+2) * sizeof(*dll_paths) );
126 nb_dll_paths = 0;
128 if (dlldir)
130 dll_path_maxlen = strlen(dlldir);
131 dll_paths[nb_dll_paths++] = dlldir;
133 else if (build_dir)
135 dll_path_maxlen = strlen(build_dir) + sizeof("/programs");
138 if (count)
140 p = path;
141 while (*p)
143 while (*p == ':') *p++ = 0;
144 if (!*p) break;
145 dll_paths[nb_dll_paths] = p;
146 while (*p && *p != ':') p++;
147 if (p - dll_paths[nb_dll_paths] > dll_path_maxlen)
148 dll_path_maxlen = p - dll_paths[nb_dll_paths];
149 nb_dll_paths++;
153 /* append default dll dir (if not empty) to path */
154 if ((len = strlen(default_dlldir)) > 0)
156 if (len > dll_path_maxlen) dll_path_maxlen = len;
157 dll_paths[nb_dll_paths++] = default_dlldir;
161 static inline char *prepend( char *buffer, const char *str, size_t len )
163 return memcpy( buffer - len, str, len );
166 /* get a filename from the next entry in the dll path */
167 static char *next_dll_path( struct dll_path_context *context )
169 unsigned int index = context->index++;
170 int namelen = context->namelen;
171 char *path = context->name;
173 switch(index)
175 case 0: /* try dlls dir with subdir prefix */
176 if (namelen > 4 && !memcmp( context->name + namelen - 4, ".dll", 4 )) namelen -= 4;
177 if (!context->win16) path = prepend( path, context->name, namelen );
178 path = prepend( path, "/dlls", sizeof("/dlls") - 1 );
179 path = prepend( path, build_dir, strlen(build_dir) );
180 return path;
181 case 1: /* try programs dir with subdir prefix */
182 if (!context->win16)
184 if (namelen > 4 && !memcmp( context->name + namelen - 4, ".exe", 4 )) namelen -= 4;
185 path = prepend( path, context->name, namelen );
186 path = prepend( path, "/programs", sizeof("/programs") - 1 );
187 path = prepend( path, build_dir, strlen(build_dir) );
188 return path;
190 context->index++;
191 /* fall through */
192 default:
193 index -= 2;
194 if (index >= nb_dll_paths) return NULL;
195 path = prepend( path, dll_paths[index], strlen( dll_paths[index] ));
196 return path;
201 /* get a filename from the first entry in the dll path */
202 static char *first_dll_path( const char *name, int win16, struct dll_path_context *context )
204 char *p;
205 int namelen = strlen( name );
206 const char *ext = win16 ? "16" : ".so";
208 context->buffer = malloc( dll_path_maxlen + 2 * namelen + strlen(ext) + 3 );
209 context->index = build_dir ? 0 : 2; /* if no build dir skip all the build dir magic cases */
210 context->name = context->buffer + dll_path_maxlen + namelen + 1;
211 context->namelen = namelen + 1;
212 context->win16 = win16;
214 /* store the name at the end of the buffer, followed by extension */
215 p = context->name;
216 *p++ = '/';
217 memcpy( p, name, namelen );
218 strcpy( p + namelen, ext );
219 return next_dll_path( context );
223 /* free the dll path context created by first_dll_path */
224 static inline void free_dll_path( struct dll_path_context *context )
226 free( context->buffer );
229 #endif /* __ASM_OBSOLETE */
231 /* adjust an array of pointers to make them into RVAs */
232 static inline void fixup_rva_ptrs( void *array, BYTE *base, unsigned int count )
234 void **src = (void **)array;
235 DWORD *dst = (DWORD *)array;
236 while (count--)
238 *dst++ = *src ? (BYTE *)*src - base : 0;
239 src++;
243 /* fixup an array of RVAs by adding the specified delta */
244 static inline void fixup_rva_dwords( DWORD *ptr, int delta, unsigned int count )
246 while (count--)
248 if (*ptr) *ptr += delta;
249 ptr++;
254 /* fixup an array of name/ordinal RVAs by adding the specified delta */
255 static inline void fixup_rva_names( UINT_PTR *ptr, int delta )
257 while (*ptr)
259 if (!(*ptr & IMAGE_ORDINAL_FLAG)) *ptr += delta;
260 ptr++;
265 /* fixup RVAs in the import directory */
266 static void fixup_imports( IMAGE_IMPORT_DESCRIPTOR *dir, BYTE *base, int delta )
268 while (dir->Name)
270 fixup_rva_dwords( &dir->u.OriginalFirstThunk, delta, 1 );
271 fixup_rva_dwords( &dir->Name, delta, 1 );
272 fixup_rva_dwords( &dir->FirstThunk, delta, 1 );
273 if (dir->u.OriginalFirstThunk) fixup_rva_names( (UINT_PTR *)(base + dir->u.OriginalFirstThunk), delta );
274 if (dir->FirstThunk) fixup_rva_names( (UINT_PTR *)(base + dir->FirstThunk), delta );
275 dir++;
280 /* fixup RVAs in the export directory */
281 static void fixup_exports( IMAGE_EXPORT_DIRECTORY *dir, BYTE *base, int delta )
283 fixup_rva_dwords( &dir->Name, delta, 1 );
284 fixup_rva_dwords( &dir->AddressOfFunctions, delta, 1 );
285 fixup_rva_dwords( &dir->AddressOfNames, delta, 1 );
286 fixup_rva_dwords( &dir->AddressOfNameOrdinals, delta, 1 );
287 fixup_rva_dwords( (DWORD *)(base + dir->AddressOfNames), delta, dir->NumberOfNames );
288 fixup_rva_ptrs( (base + dir->AddressOfFunctions), base, dir->NumberOfFunctions );
292 /* fixup RVAs in the resource directory */
293 static void fixup_resources( IMAGE_RESOURCE_DIRECTORY *dir, BYTE *root, int delta )
295 IMAGE_RESOURCE_DIRECTORY_ENTRY *entry;
296 int i;
298 entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
299 for (i = 0; i < dir->NumberOfNamedEntries + dir->NumberOfIdEntries; i++, entry++)
301 void *ptr = root + entry->u2.s2.OffsetToDirectory;
302 if (entry->u2.s2.DataIsDirectory) fixup_resources( ptr, root, delta );
303 else
305 IMAGE_RESOURCE_DATA_ENTRY *data = ptr;
306 fixup_rva_dwords( &data->OffsetToData, delta, 1 );
312 /* map a builtin dll in memory and fixup RVAs */
313 static void *map_dll( const IMAGE_NT_HEADERS *nt_descr )
315 IMAGE_DATA_DIRECTORY *dir;
316 IMAGE_DOS_HEADER *dos;
317 IMAGE_NT_HEADERS *nt;
318 IMAGE_SECTION_HEADER *sec;
319 BYTE *addr;
320 DWORD code_start, code_end, data_start, data_end;
321 const size_t page_size = sysconf( _SC_PAGESIZE );
322 const size_t page_mask = page_size - 1;
323 int delta, nb_sections = 2; /* code + data */
324 unsigned int i;
325 #ifdef __APPLE__
326 Dl_info dli;
327 unsigned long data_size;
328 #endif
330 size_t size = (sizeof(IMAGE_DOS_HEADER)
331 + sizeof(IMAGE_NT_HEADERS)
332 + nb_sections * sizeof(IMAGE_SECTION_HEADER));
334 assert( size <= page_size );
336 /* module address must be aligned on 64K boundary */
337 addr = (BYTE *)((nt_descr->OptionalHeader.ImageBase + 0xffff) & ~0xffff);
338 if (wine_anon_mmap( addr, page_size, PROT_READ|PROT_WRITE, MAP_FIXED ) != addr) return NULL;
340 dos = (IMAGE_DOS_HEADER *)addr;
341 nt = (IMAGE_NT_HEADERS *)(dos + 1);
342 sec = (IMAGE_SECTION_HEADER *)(nt + 1);
344 /* Build the DOS and NT headers */
346 dos->e_magic = IMAGE_DOS_SIGNATURE;
347 dos->e_cblp = 0x90;
348 dos->e_cp = 3;
349 dos->e_cparhdr = (sizeof(*dos)+0xf)/0x10;
350 dos->e_minalloc = 0;
351 dos->e_maxalloc = 0xffff;
352 dos->e_ss = 0x0000;
353 dos->e_sp = 0x00b8;
354 dos->e_lfarlc = sizeof(*dos);
355 dos->e_lfanew = sizeof(*dos);
357 *nt = *nt_descr;
359 delta = (const BYTE *)nt_descr - addr;
360 code_start = page_size;
361 data_start = delta & ~page_mask;
362 #ifdef __APPLE__
363 /* Need the mach_header, not the PE header, to give to getsegmentdata(3) */
364 dladdr(addr, &dli);
365 code_end = getsegmentdata(dli.dli_fbase, "__DATA", &data_size) - addr;
366 data_end = (code_end + data_size + page_mask) & ~page_mask;
367 #else
368 code_end = data_start;
369 data_end = (nt->OptionalHeader.SizeOfImage + delta + page_mask) & ~page_mask;
370 #endif
372 fixup_rva_ptrs( &nt->OptionalHeader.AddressOfEntryPoint, addr, 1 );
374 nt->FileHeader.NumberOfSections = nb_sections;
375 nt->OptionalHeader.BaseOfCode = code_start;
376 #ifndef _WIN64
377 nt->OptionalHeader.BaseOfData = data_start;
378 #endif
379 nt->OptionalHeader.SizeOfCode = code_end - code_start;
380 nt->OptionalHeader.SizeOfInitializedData = data_end - data_start;
381 nt->OptionalHeader.SizeOfUninitializedData = 0;
382 nt->OptionalHeader.SizeOfImage = data_end;
383 nt->OptionalHeader.ImageBase = (ULONG_PTR)addr;
385 /* Build the code section */
387 memcpy( sec->Name, ".text", sizeof(".text") );
388 sec->SizeOfRawData = code_end - code_start;
389 sec->Misc.VirtualSize = sec->SizeOfRawData;
390 sec->VirtualAddress = code_start;
391 sec->PointerToRawData = code_start;
392 sec->Characteristics = (IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ);
393 sec++;
395 /* Build the data section */
397 memcpy( sec->Name, ".data", sizeof(".data") );
398 sec->SizeOfRawData = data_end - data_start;
399 sec->Misc.VirtualSize = sec->SizeOfRawData;
400 sec->VirtualAddress = data_start;
401 sec->PointerToRawData = data_start;
402 sec->Characteristics = (IMAGE_SCN_CNT_INITIALIZED_DATA |
403 IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ);
404 sec++;
406 for (i = 0; i < nt->OptionalHeader.NumberOfRvaAndSizes; i++)
407 fixup_rva_dwords( &nt->OptionalHeader.DataDirectory[i].VirtualAddress, delta, 1 );
409 /* Build the import directory */
411 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY];
412 if (dir->Size)
414 IMAGE_IMPORT_DESCRIPTOR *imports = (void *)(addr + dir->VirtualAddress);
415 fixup_imports( imports, addr, delta );
418 /* Build the resource directory */
420 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_RESOURCE_DIRECTORY];
421 if (dir->Size)
423 void *ptr = (void *)(addr + dir->VirtualAddress);
424 fixup_resources( ptr, ptr, delta );
427 /* Build the export directory */
429 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_EXPORT_DIRECTORY];
430 if (dir->Size)
432 IMAGE_EXPORT_DIRECTORY *exports = (void *)(addr + dir->VirtualAddress);
433 fixup_exports( exports, addr, delta );
435 return addr;
439 /***********************************************************************
440 * __wine_get_main_environment
442 * Return an environment pointer to work around lack of environ variable.
443 * Only exported on Mac OS.
445 char **__wine_get_main_environment(void)
447 return environ;
451 /***********************************************************************
452 * __wine_dll_register
454 * Register a built-in DLL descriptor.
456 void __wine_dll_register( const IMAGE_NT_HEADERS *header, const char *filename )
458 if (load_dll_callback) load_dll_callback( map_dll(header), filename );
459 else
461 if (!(header->FileHeader.Characteristics & IMAGE_FILE_DLL))
462 main_exe = header;
463 else
465 assert( nb_dlls < MAX_DLLS );
466 builtin_dlls[nb_dlls].nt = header;
467 builtin_dlls[nb_dlls].filename = filename;
468 nb_dlls++;
474 /***********************************************************************
475 * wine_dll_set_callback
477 * Set the callback function for dll loading, and call it
478 * for all dlls that were implicitly loaded already.
480 void wine_dll_set_callback( load_dll_callback_t load )
482 int i;
483 load_dll_callback = load;
484 for (i = 0; i < nb_dlls; i++)
486 const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
487 if (!nt) continue;
488 builtin_dlls[i].nt = NULL;
489 load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
491 nb_dlls = 0;
492 if (main_exe) load_dll_callback( map_dll(main_exe), "" );
496 #ifdef __ASM_OBSOLETE
498 /***********************************************************************
499 * wine_dll_enum_load_path
501 * Enumerate the dll load path.
503 const char *wine_dll_enum_load_path_obsolete( unsigned int index )
505 if (index >= nb_dll_paths) return NULL;
506 return dll_paths[index];
511 * These functions provide wrappers around dlopen() and associated
512 * functions. They work around a bug in glibc 2.1.x where calling
513 * a dl*() function after a previous dl*() function has failed
514 * without a dlerror() call between the two will cause a crash.
515 * They all take a pointer to a buffer that
516 * will receive the error description (from dlerror()). This
517 * parameter may be NULL if the error description is not required.
520 #ifndef RTLD_FIRST
521 #define RTLD_FIRST 0
522 #endif
524 /***********************************************************************
525 * wine_dlopen
527 void *wine_dlopen_obsolete( const char *filename, int flag, char *error, size_t errorsize )
529 void *ret;
530 const char *s;
532 #ifdef __APPLE__
533 /* the Mac OS loader pretends to be able to load PE files, so avoid them here */
534 unsigned char magic[2];
535 int fd = open( filename, O_RDONLY );
536 if (fd != -1)
538 if (pread( fd, magic, 2, 0 ) == 2 && magic[0] == 'M' && magic[1] == 'Z')
540 if (error && errorsize)
542 static const char msg[] = "MZ format";
543 size_t len = min( errorsize, sizeof(msg) );
544 memcpy( error, msg, len );
545 error[len - 1] = 0;
547 close( fd );
548 return NULL;
550 close( fd );
552 #endif
553 dlerror(); dlerror();
554 #ifdef __sun
555 if (strchr( filename, ':' ))
557 char path[PATH_MAX];
558 /* Solaris' brain damaged dlopen() treats ':' as a path separator */
559 realpath( filename, path );
560 ret = dlopen( path, flag | RTLD_FIRST );
562 else
563 #endif
564 ret = dlopen( filename, flag | RTLD_FIRST );
565 s = dlerror();
566 if (error && errorsize)
568 if (s)
570 size_t len = strlen(s);
571 if (len >= errorsize) len = errorsize - 1;
572 memcpy( error, s, len );
573 error[len] = 0;
575 else error[0] = 0;
577 dlerror();
578 return ret;
581 /***********************************************************************
582 * wine_dlsym
584 void *wine_dlsym_obsolete( void *handle, const char *symbol, char *error, size_t errorsize )
586 void *ret;
587 const char *s;
588 dlerror(); dlerror();
589 ret = dlsym( handle, symbol );
590 s = dlerror();
591 if (error && errorsize)
593 if (s)
595 size_t len = strlen(s);
596 if (len >= errorsize) len = errorsize - 1;
597 memcpy( error, s, len );
598 error[len] = 0;
600 else error[0] = 0;
602 dlerror();
603 return ret;
606 /***********************************************************************
607 * wine_dlclose
609 int wine_dlclose_obsolete( void *handle, char *error, size_t errorsize )
611 int ret;
612 const char *s;
613 dlerror(); dlerror();
614 ret = dlclose( handle );
615 s = dlerror();
616 if (error && errorsize)
618 if (s)
620 size_t len = strlen(s);
621 if (len >= errorsize) len = errorsize - 1;
622 memcpy( error, s, len );
623 error[len] = 0;
625 else error[0] = 0;
627 dlerror();
628 return ret;
632 /* check if the library is the correct architecture */
633 /* only returns false for a valid library of the wrong arch */
634 static int check_library_arch( int fd )
636 #ifdef __APPLE__
637 struct /* Mach-O header */
639 unsigned int magic;
640 unsigned int cputype;
641 } header;
643 if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
644 if (header.magic != 0xfeedface) return 1;
645 if (sizeof(void *) == sizeof(int)) return !(header.cputype >> 24);
646 else return (header.cputype >> 24) == 1; /* CPU_ARCH_ABI64 */
647 #else
648 struct /* ELF header */
650 unsigned char magic[4];
651 unsigned char class;
652 unsigned char data;
653 unsigned char version;
654 } header;
656 if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
657 if (memcmp( header.magic, "\177ELF", 4 )) return 1;
658 if (header.version != 1 /* EV_CURRENT */) return 1;
659 #ifdef WORDS_BIGENDIAN
660 if (header.data != 2 /* ELFDATA2MSB */) return 1;
661 #else
662 if (header.data != 1 /* ELFDATA2LSB */) return 1;
663 #endif
664 if (sizeof(void *) == sizeof(int)) return header.class == 1; /* ELFCLASS32 */
665 else return header.class == 2; /* ELFCLASS64 */
666 #endif
669 /* check if a given file can be opened */
670 static int file_exists( const char *name )
672 int ret = 0;
673 int fd = open( name, O_RDONLY );
674 if (fd != -1)
676 ret = check_library_arch( fd );
677 close( fd );
679 return ret;
682 /* open a library for a given dll, searching in the dll path
683 * 'name' must be the Windows dll name (e.g. "kernel32.dll") */
684 static void *dlopen_dll( const char *name, char *error, int errorsize,
685 int test_only, int *exists )
687 struct dll_path_context context;
688 char *path;
689 void *ret = NULL;
691 *exists = 0;
692 for (path = first_dll_path( name, 0, &context ); path; path = next_dll_path( &context ))
694 if (!test_only && (ret = wine_dlopen_obsolete( path, RTLD_NOW, error, errorsize ))) break;
695 if ((*exists = file_exists( path ))) break; /* exists but cannot be loaded, return the error */
697 free_dll_path( &context );
698 return ret;
702 /***********************************************************************
703 * wine_dll_load
705 * Load a builtin dll.
707 void *wine_dll_load_obsolete( const char *filename, char *error, int errorsize, int *file_exists )
709 int i;
711 /* callback must have been set already */
712 assert( load_dll_callback );
714 /* check if we have it in the list */
715 /* this can happen when initializing pre-loaded dlls in wine_dll_set_callback */
716 for (i = 0; i < nb_dlls; i++)
718 if (!builtin_dlls[i].nt) continue;
719 if (!strcmp( builtin_dlls[i].filename, filename ))
721 const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
722 builtin_dlls[i].nt = NULL;
723 load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
724 *file_exists = 1;
725 return (void *)1;
728 return dlopen_dll( filename, error, errorsize, 0, file_exists );
732 /***********************************************************************
733 * wine_dll_unload
735 * Unload a builtin dll.
737 void wine_dll_unload_obsolete( void *handle )
739 if (handle != (void *)1)
740 wine_dlclose_obsolete( handle, NULL, 0 );
744 /***********************************************************************
745 * wine_dll_load_main_exe
747 * Try to load the .so for the main exe.
749 void *wine_dll_load_main_exe_obsolete( const char *name, char *error, int errorsize,
750 int test_only, int *file_exists )
752 return dlopen_dll( name, error, errorsize, test_only, file_exists );
756 /***********************************************************************
757 * wine_dll_get_owner
759 * Retrieve the name of the 32-bit owner dll for a 16-bit dll.
760 * Return 0 if OK, -1 on error.
762 int wine_dll_get_owner_obsolete( const char *name, char *buffer, int size, int *exists )
764 int ret = -1;
765 char *path;
766 struct dll_path_context context;
768 *exists = 0;
770 for (path = first_dll_path( name, 1, &context ); path; path = next_dll_path( &context ))
772 int fd = open( path, O_RDONLY );
773 if (fd != -1)
775 int res = read( fd, buffer, size - 1 );
776 while (res > 0 && (buffer[res-1] == '\n' || buffer[res-1] == '\r')) res--;
777 buffer[res] = 0;
778 close( fd );
779 *exists = 1;
780 ret = 0;
781 break;
784 free_dll_path( &context );
785 return ret;
789 /***********************************************************************
790 * set_max_limit
792 * Set a user limit to the maximum allowed value.
794 static void set_max_limit( int limit )
796 struct rlimit rlimit;
798 if (!getrlimit( limit, &rlimit ))
800 rlimit.rlim_cur = rlimit.rlim_max;
801 if (setrlimit( limit, &rlimit ) != 0)
803 #if defined(__APPLE__) && defined(RLIMIT_NOFILE) && defined(OPEN_MAX)
804 /* On Leopard, setrlimit(RLIMIT_NOFILE, ...) fails on attempts to set
805 * rlim_cur above OPEN_MAX (even if rlim_max > OPEN_MAX). */
806 if (limit == RLIMIT_NOFILE && rlimit.rlim_cur > OPEN_MAX)
808 rlimit.rlim_cur = OPEN_MAX;
809 setrlimit( limit, &rlimit );
811 #endif
817 #ifdef __APPLE__
818 struct apple_stack_info
820 void *stack;
821 size_t desired_size;
824 /***********************************************************************
825 * apple_alloc_thread_stack
827 * Callback for wine_mmap_enum_reserved_areas to allocate space for
828 * the secondary thread's stack.
830 #ifndef _WIN64
831 static int apple_alloc_thread_stack( void *base, size_t size, void *arg )
833 struct apple_stack_info *info = arg;
835 /* For mysterious reasons, putting the thread stack at the very top
836 * of the address space causes subsequent execs to fail, even on the
837 * child side of a fork. Avoid the top 16MB. */
838 char * const limit = (char*)0xff000000;
839 if ((char *)base >= limit) return 0;
840 if (size > limit - (char*)base)
841 size = limit - (char*)base;
842 if (size < info->desired_size) return 0;
843 info->stack = wine_anon_mmap( (char *)base + size - info->desired_size,
844 info->desired_size, PROT_READ|PROT_WRITE, MAP_FIXED );
845 return (info->stack != (void *)-1);
847 #endif
849 /***********************************************************************
850 * apple_create_wine_thread
852 * Spin off a secondary thread to complete Wine initialization, leaving
853 * the original thread for the Mac frameworks.
855 * Invoked as a CFRunLoopSource perform callback.
857 static void apple_create_wine_thread( void *init_func )
859 int success = 0;
860 pthread_t thread;
861 pthread_attr_t attr;
863 if (!pthread_attr_init( &attr ))
865 #ifndef _WIN64
866 struct apple_stack_info info;
868 /* Try to put the new thread's stack in the reserved area. If this
869 * fails, just let it go wherever. It'll be a waste of space, but we
870 * can go on. */
871 if (!pthread_attr_getstacksize( &attr, &info.desired_size ) &&
872 wine_mmap_enum_reserved_areas_obsolete( apple_alloc_thread_stack, &info, 1 ))
874 wine_mmap_remove_reserved_area_obsolete( info.stack, info.desired_size, 0 );
875 pthread_attr_setstackaddr( &attr, (char*)info.stack + info.desired_size );
877 #endif
879 if (!pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ) &&
880 !pthread_create( &thread, &attr, init_func, NULL ))
881 success = 1;
883 pthread_attr_destroy( &attr );
886 /* Failure is indicated by returning from wine_init(). Stopping
887 * the run loop allows apple_main_thread() and thus wine_init() to
888 * return. */
889 if (!success)
890 CFRunLoopStop( CFRunLoopGetCurrent() );
894 /***********************************************************************
895 * apple_main_thread
897 * Park the process's original thread in a Core Foundation run loop for
898 * use by the Mac frameworks, especially receiving and handling
899 * distributed notifications. Spin off a new thread for the rest of the
900 * Wine initialization.
902 static void apple_main_thread( void (*init_func)(void) )
904 CFRunLoopSourceContext source_context = { 0 };
905 CFRunLoopSourceRef source;
907 if (!pthread_main_np())
909 init_func();
910 return;
913 /* Multi-processing Services can get confused about the main thread if the
914 * first time it's used is on a secondary thread. Use it here to make sure
915 * that doesn't happen. */
916 MPTaskIsPreemptive(MPCurrentTaskID());
918 /* Give ourselves the best chance of having the distributed notification
919 * center scheduled on this thread's run loop. In theory, it's scheduled
920 * in the first thread to ask for it. */
921 CFNotificationCenterGetDistributedCenter();
923 /* We use this run loop source for two purposes. First, a run loop exits
924 * if it has no more sources scheduled. So, we need at least one source
925 * to keep the run loop running. Second, although it's not critical, it's
926 * preferable for the Wine initialization to not proceed until we know
927 * the run loop is running. So, we signal our source immediately after
928 * adding it and have its callback spin off the Wine thread. */
929 source_context.info = init_func;
930 source_context.perform = apple_create_wine_thread;
931 source = CFRunLoopSourceCreate( NULL, 0, &source_context );
933 if (source)
935 CFRunLoopAddSource( CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes );
936 CFRunLoopSourceSignal( source );
937 CFRelease( source );
939 CFRunLoopRun(); /* Should never return, except on error. */
942 /* If we get here (i.e. return), that indicates failure to our caller. */
944 #endif
947 /***********************************************************************
948 * wine_init
950 * Main Wine initialisation.
952 void wine_init_obsolete( int argc, char *argv[], char *error, int error_size )
954 struct dll_path_context context;
955 char *path;
956 void *ntdll = NULL;
957 void (*init_func)(void);
959 /* force a few limits that are set too low on some platforms */
960 #ifdef RLIMIT_NOFILE
961 set_max_limit( RLIMIT_NOFILE );
962 #endif
963 #ifdef RLIMIT_AS
964 set_max_limit( RLIMIT_AS );
965 #endif
967 wine_init_argv0_path_obsolete( argv[0] );
968 build_dll_path();
969 __wine_main_argc = argc;
970 __wine_main_argv = argv;
971 __wine_main_environ = __wine_get_main_environment();
972 mmap_init();
974 for (path = first_dll_path( "ntdll.dll", 0, &context ); path; path = next_dll_path( &context ))
976 if ((ntdll = dlopen( path, RTLD_NOW )))
978 /* if we didn't use the default dll dir, remove it from the search path */
979 if (default_dlldir[0] && context.index < nb_dll_paths + 2) nb_dll_paths--;
980 break;
983 free_dll_path( &context );
985 if (!ntdll || !(init_func = dlsym( ntdll, "__wine_process_init" )))
987 if (error && error_size)
989 const char *s = dlerror();
990 if (s)
992 size_t len = min( strlen(s), error_size - 1 );
993 memcpy( error, s, len );
994 error[len] = 0;
996 else error[0] = 0;
998 return;
1000 #ifdef __APPLE__
1001 apple_main_thread( init_func );
1002 #else
1003 init_func();
1004 #endif
1007 __ASM_OBSOLETE(wine_dlopen);
1008 __ASM_OBSOLETE(wine_dlsym);
1009 __ASM_OBSOLETE(wine_dlclose);
1010 __ASM_OBSOLETE(wine_dll_enum_load_path);
1011 __ASM_OBSOLETE(wine_dll_get_owner);
1012 __ASM_OBSOLETE(wine_dll_load);
1013 __ASM_OBSOLETE(wine_dll_load_main_exe);
1014 __ASM_OBSOLETE(wine_dll_unload);
1015 __ASM_OBSOLETE(wine_init);
1017 #endif /* __ASM_OBSOLETE */