conhost: Remove duplicate lines from current_config().
[wine.git] / libs / wine / loader.c
blob4245beea94b23f6a56780f7c0de31625980f4d63
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"
22 #include "wine/port.h"
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
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 #include <mach-o/getsect.h>
53 #else
54 extern char **environ;
55 #endif
57 #define NONAMELESSUNION
58 #define NONAMELESSSTRUCT
59 #include "windef.h"
60 #include "winbase.h"
61 #include "wine/asm.h"
63 /* argc/argv for the Windows application */
64 int __wine_main_argc = 0;
65 char **__wine_main_argv = NULL;
66 WCHAR **__wine_main_wargv = NULL;
67 char **__wine_main_environ = NULL;
69 #define MAX_DLLS 100
71 static struct
73 const IMAGE_NT_HEADERS *nt; /* NT header */
74 const char *filename; /* DLL file name */
75 } builtin_dlls[MAX_DLLS];
77 static int nb_dlls;
79 static const IMAGE_NT_HEADERS *main_exe;
81 typedef void (*load_dll_callback_t)( void *, const char * );
82 static load_dll_callback_t load_dll_callback;
84 extern void *wine_anon_mmap( void *start, size_t size, int prot, int flags );
86 #ifdef __ASM_OBSOLETE
88 struct dll_path_context
90 unsigned int index; /* current index in the dll path list */
91 char *buffer; /* buffer used for storing path names */
92 char *name; /* start of file name part in buffer (including leading slash) */
93 int namelen; /* length of file name without .so extension */
94 int win16; /* 16-bit dll search */
97 static const char *default_dlldir;
98 static const char **dll_paths;
99 static unsigned int nb_dll_paths;
100 static int dll_path_maxlen;
102 extern const char *build_dir;
104 extern void wine_init_argv0_path_obsolete( const char *argv0 );
105 extern void mmap_init(void);
106 extern const char *get_dlldir( const char **default_dlldir );
108 /* build the dll load path from the WINEDLLPATH variable */
109 static void build_dll_path(void)
111 int len, count = 0;
112 char *p, *path = getenv( "WINEDLLPATH" );
113 const char *dlldir = get_dlldir( &default_dlldir );
115 if (path)
117 /* count how many path elements we need */
118 path = strdup(path);
119 p = path;
120 while (*p)
122 while (*p == ':') p++;
123 if (!*p) break;
124 count++;
125 while (*p && *p != ':') p++;
129 dll_paths = malloc( (count+2) * sizeof(*dll_paths) );
130 nb_dll_paths = 0;
132 if (dlldir)
134 dll_path_maxlen = strlen(dlldir);
135 dll_paths[nb_dll_paths++] = dlldir;
137 else if (build_dir)
139 dll_path_maxlen = strlen(build_dir) + sizeof("/programs");
142 if (count)
144 p = path;
145 while (*p)
147 while (*p == ':') *p++ = 0;
148 if (!*p) break;
149 dll_paths[nb_dll_paths] = p;
150 while (*p && *p != ':') p++;
151 if (p - dll_paths[nb_dll_paths] > dll_path_maxlen)
152 dll_path_maxlen = p - dll_paths[nb_dll_paths];
153 nb_dll_paths++;
157 /* append default dll dir (if not empty) to path */
158 if ((len = strlen(default_dlldir)) > 0)
160 if (len > dll_path_maxlen) dll_path_maxlen = len;
161 dll_paths[nb_dll_paths++] = default_dlldir;
165 static inline char *prepend( char *buffer, const char *str, size_t len )
167 return memcpy( buffer - len, str, len );
170 /* get a filename from the next entry in the dll path */
171 static char *next_dll_path( struct dll_path_context *context )
173 unsigned int index = context->index++;
174 int namelen = context->namelen;
175 char *path = context->name;
177 switch(index)
179 case 0: /* try dlls dir with subdir prefix */
180 if (namelen > 4 && !memcmp( context->name + namelen - 4, ".dll", 4 )) namelen -= 4;
181 if (!context->win16) path = prepend( path, context->name, namelen );
182 path = prepend( path, "/dlls", sizeof("/dlls") - 1 );
183 path = prepend( path, build_dir, strlen(build_dir) );
184 return path;
185 case 1: /* try programs dir with subdir prefix */
186 if (!context->win16)
188 if (namelen > 4 && !memcmp( context->name + namelen - 4, ".exe", 4 )) namelen -= 4;
189 path = prepend( path, context->name, namelen );
190 path = prepend( path, "/programs", sizeof("/programs") - 1 );
191 path = prepend( path, build_dir, strlen(build_dir) );
192 return path;
194 context->index++;
195 /* fall through */
196 default:
197 index -= 2;
198 if (index >= nb_dll_paths) return NULL;
199 path = prepend( path, dll_paths[index], strlen( dll_paths[index] ));
200 return path;
205 /* get a filename from the first entry in the dll path */
206 static char *first_dll_path( const char *name, int win16, struct dll_path_context *context )
208 char *p;
209 int namelen = strlen( name );
210 const char *ext = win16 ? "16" : ".so";
212 context->buffer = malloc( dll_path_maxlen + 2 * namelen + strlen(ext) + 3 );
213 context->index = build_dir ? 0 : 2; /* if no build dir skip all the build dir magic cases */
214 context->name = context->buffer + dll_path_maxlen + namelen + 1;
215 context->namelen = namelen + 1;
216 context->win16 = win16;
218 /* store the name at the end of the buffer, followed by extension */
219 p = context->name;
220 *p++ = '/';
221 memcpy( p, name, namelen );
222 strcpy( p + namelen, ext );
223 return next_dll_path( context );
227 /* free the dll path context created by first_dll_path */
228 static inline void free_dll_path( struct dll_path_context *context )
230 free( context->buffer );
233 #endif /* __ASM_OBSOLETE */
235 /* adjust an array of pointers to make them into RVAs */
236 static inline void fixup_rva_ptrs( void *array, BYTE *base, unsigned int count )
238 void **src = (void **)array;
239 DWORD *dst = (DWORD *)array;
240 while (count--)
242 *dst++ = *src ? (BYTE *)*src - base : 0;
243 src++;
247 /* fixup an array of RVAs by adding the specified delta */
248 static inline void fixup_rva_dwords( DWORD *ptr, int delta, unsigned int count )
250 while (count--)
252 if (*ptr) *ptr += delta;
253 ptr++;
258 /* fixup an array of name/ordinal RVAs by adding the specified delta */
259 static inline void fixup_rva_names( UINT_PTR *ptr, int delta )
261 while (*ptr)
263 if (!(*ptr & IMAGE_ORDINAL_FLAG)) *ptr += delta;
264 ptr++;
269 /* fixup RVAs in the import directory */
270 static void fixup_imports( IMAGE_IMPORT_DESCRIPTOR *dir, BYTE *base, int delta )
272 while (dir->Name)
274 fixup_rva_dwords( &dir->u.OriginalFirstThunk, delta, 1 );
275 fixup_rva_dwords( &dir->Name, delta, 1 );
276 fixup_rva_dwords( &dir->FirstThunk, delta, 1 );
277 if (dir->u.OriginalFirstThunk) fixup_rva_names( (UINT_PTR *)(base + dir->u.OriginalFirstThunk), delta );
278 if (dir->FirstThunk) fixup_rva_names( (UINT_PTR *)(base + dir->FirstThunk), delta );
279 dir++;
284 /* fixup RVAs in the export directory */
285 static void fixup_exports( IMAGE_EXPORT_DIRECTORY *dir, BYTE *base, int delta )
287 fixup_rva_dwords( &dir->Name, delta, 1 );
288 fixup_rva_dwords( &dir->AddressOfFunctions, delta, 1 );
289 fixup_rva_dwords( &dir->AddressOfNames, delta, 1 );
290 fixup_rva_dwords( &dir->AddressOfNameOrdinals, delta, 1 );
291 fixup_rva_dwords( (DWORD *)(base + dir->AddressOfNames), delta, dir->NumberOfNames );
292 fixup_rva_ptrs( (base + dir->AddressOfFunctions), base, dir->NumberOfFunctions );
296 /* fixup RVAs in the resource directory */
297 static void fixup_resources( IMAGE_RESOURCE_DIRECTORY *dir, BYTE *root, int delta )
299 IMAGE_RESOURCE_DIRECTORY_ENTRY *entry;
300 int i;
302 entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
303 for (i = 0; i < dir->NumberOfNamedEntries + dir->NumberOfIdEntries; i++, entry++)
305 void *ptr = root + entry->u2.s2.OffsetToDirectory;
306 if (entry->u2.s2.DataIsDirectory) fixup_resources( ptr, root, delta );
307 else
309 IMAGE_RESOURCE_DATA_ENTRY *data = ptr;
310 fixup_rva_dwords( &data->OffsetToData, delta, 1 );
316 /* map a builtin dll in memory and fixup RVAs */
317 static void *map_dll( const IMAGE_NT_HEADERS *nt_descr )
319 IMAGE_DATA_DIRECTORY *dir;
320 IMAGE_DOS_HEADER *dos;
321 IMAGE_NT_HEADERS *nt;
322 IMAGE_SECTION_HEADER *sec;
323 BYTE *addr;
324 DWORD code_start, code_end, data_start, data_end;
325 const size_t page_size = sysconf( _SC_PAGESIZE );
326 const size_t page_mask = page_size - 1;
327 int delta, nb_sections = 2; /* code + data */
328 unsigned int i;
329 #ifdef __APPLE__
330 Dl_info dli;
331 unsigned long data_size;
332 #endif
334 size_t size = (sizeof(IMAGE_DOS_HEADER)
335 + sizeof(IMAGE_NT_HEADERS)
336 + nb_sections * sizeof(IMAGE_SECTION_HEADER));
338 assert( size <= page_size );
340 /* module address must be aligned on 64K boundary */
341 addr = (BYTE *)((nt_descr->OptionalHeader.ImageBase + 0xffff) & ~0xffff);
342 if (wine_anon_mmap( addr, page_size, PROT_READ|PROT_WRITE, MAP_FIXED ) != addr) return NULL;
344 dos = (IMAGE_DOS_HEADER *)addr;
345 nt = (IMAGE_NT_HEADERS *)(dos + 1);
346 sec = (IMAGE_SECTION_HEADER *)(nt + 1);
348 /* Build the DOS and NT headers */
350 dos->e_magic = IMAGE_DOS_SIGNATURE;
351 dos->e_cblp = 0x90;
352 dos->e_cp = 3;
353 dos->e_cparhdr = (sizeof(*dos)+0xf)/0x10;
354 dos->e_minalloc = 0;
355 dos->e_maxalloc = 0xffff;
356 dos->e_ss = 0x0000;
357 dos->e_sp = 0x00b8;
358 dos->e_lfarlc = sizeof(*dos);
359 dos->e_lfanew = sizeof(*dos);
361 *nt = *nt_descr;
363 delta = (const BYTE *)nt_descr - addr;
364 code_start = page_size;
365 data_start = delta & ~page_mask;
366 #ifdef __APPLE__
367 /* Need the mach_header, not the PE header, to give to getsegmentdata(3) */
368 dladdr(addr, &dli);
369 code_end = getsegmentdata(dli.dli_fbase, "__DATA", &data_size) - addr;
370 data_end = (code_end + data_size + page_mask) & ~page_mask;
371 #else
372 code_end = data_start;
373 data_end = (nt->OptionalHeader.SizeOfImage + delta + page_mask) & ~page_mask;
374 #endif
376 fixup_rva_ptrs( &nt->OptionalHeader.AddressOfEntryPoint, addr, 1 );
378 nt->FileHeader.NumberOfSections = nb_sections;
379 nt->OptionalHeader.BaseOfCode = code_start;
380 #ifndef _WIN64
381 nt->OptionalHeader.BaseOfData = data_start;
382 #endif
383 nt->OptionalHeader.SizeOfCode = code_end - code_start;
384 nt->OptionalHeader.SizeOfInitializedData = data_end - data_start;
385 nt->OptionalHeader.SizeOfUninitializedData = 0;
386 nt->OptionalHeader.SizeOfImage = data_end;
387 nt->OptionalHeader.ImageBase = (ULONG_PTR)addr;
389 /* Build the code section */
391 memcpy( sec->Name, ".text", sizeof(".text") );
392 sec->SizeOfRawData = code_end - code_start;
393 sec->Misc.VirtualSize = sec->SizeOfRawData;
394 sec->VirtualAddress = code_start;
395 sec->PointerToRawData = code_start;
396 sec->Characteristics = (IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ);
397 sec++;
399 /* Build the data section */
401 memcpy( sec->Name, ".data", sizeof(".data") );
402 sec->SizeOfRawData = data_end - data_start;
403 sec->Misc.VirtualSize = sec->SizeOfRawData;
404 sec->VirtualAddress = data_start;
405 sec->PointerToRawData = data_start;
406 sec->Characteristics = (IMAGE_SCN_CNT_INITIALIZED_DATA |
407 IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ);
408 sec++;
410 for (i = 0; i < nt->OptionalHeader.NumberOfRvaAndSizes; i++)
411 fixup_rva_dwords( &nt->OptionalHeader.DataDirectory[i].VirtualAddress, delta, 1 );
413 /* Build the import directory */
415 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY];
416 if (dir->Size)
418 IMAGE_IMPORT_DESCRIPTOR *imports = (void *)(addr + dir->VirtualAddress);
419 fixup_imports( imports, addr, delta );
422 /* Build the resource directory */
424 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_RESOURCE_DIRECTORY];
425 if (dir->Size)
427 void *ptr = (void *)(addr + dir->VirtualAddress);
428 fixup_resources( ptr, ptr, delta );
431 /* Build the export directory */
433 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_EXPORT_DIRECTORY];
434 if (dir->Size)
436 IMAGE_EXPORT_DIRECTORY *exports = (void *)(addr + dir->VirtualAddress);
437 fixup_exports( exports, addr, delta );
439 return addr;
443 /***********************************************************************
444 * __wine_get_main_environment
446 * Return an environment pointer to work around lack of environ variable.
447 * Only exported on Mac OS.
449 char **__wine_get_main_environment(void)
451 return environ;
455 /***********************************************************************
456 * __wine_dll_register
458 * Register a built-in DLL descriptor.
460 void __wine_dll_register( const IMAGE_NT_HEADERS *header, const char *filename )
462 if (load_dll_callback) load_dll_callback( map_dll(header), filename );
463 else
465 if (!(header->FileHeader.Characteristics & IMAGE_FILE_DLL))
466 main_exe = header;
467 else
469 assert( nb_dlls < MAX_DLLS );
470 builtin_dlls[nb_dlls].nt = header;
471 builtin_dlls[nb_dlls].filename = filename;
472 nb_dlls++;
478 /***********************************************************************
479 * wine_dll_set_callback
481 * Set the callback function for dll loading, and call it
482 * for all dlls that were implicitly loaded already.
484 void wine_dll_set_callback( load_dll_callback_t load )
486 int i;
487 load_dll_callback = load;
488 for (i = 0; i < nb_dlls; i++)
490 const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
491 if (!nt) continue;
492 builtin_dlls[i].nt = NULL;
493 load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
495 nb_dlls = 0;
496 if (main_exe) load_dll_callback( map_dll(main_exe), "" );
500 #ifdef __ASM_OBSOLETE
502 /***********************************************************************
503 * wine_dll_enum_load_path
505 * Enumerate the dll load path.
507 const char *wine_dll_enum_load_path_obsolete( unsigned int index )
509 if (index >= nb_dll_paths) return NULL;
510 return dll_paths[index];
515 * These functions provide wrappers around dlopen() and associated
516 * functions. They work around a bug in glibc 2.1.x where calling
517 * a dl*() function after a previous dl*() function has failed
518 * without a dlerror() call between the two will cause a crash.
519 * They all take a pointer to a buffer that
520 * will receive the error description (from dlerror()). This
521 * parameter may be NULL if the error description is not required.
524 #ifndef RTLD_FIRST
525 #define RTLD_FIRST 0
526 #endif
528 /***********************************************************************
529 * wine_dlopen
531 void *wine_dlopen_obsolete( const char *filename, int flag, char *error, size_t errorsize )
533 void *ret;
534 const char *s;
536 #ifdef __APPLE__
537 /* the Mac OS loader pretends to be able to load PE files, so avoid them here */
538 unsigned char magic[2];
539 int fd = open( filename, O_RDONLY );
540 if (fd != -1)
542 if (pread( fd, magic, 2, 0 ) == 2 && magic[0] == 'M' && magic[1] == 'Z')
544 if (error && errorsize)
546 static const char msg[] = "MZ format";
547 size_t len = min( errorsize, sizeof(msg) );
548 memcpy( error, msg, len );
549 error[len - 1] = 0;
551 close( fd );
552 return NULL;
554 close( fd );
556 #endif
557 dlerror(); dlerror();
558 #ifdef __sun
559 if (strchr( filename, ':' ))
561 char path[PATH_MAX];
562 /* Solaris' brain damaged dlopen() treats ':' as a path separator */
563 realpath( filename, path );
564 ret = dlopen( path, flag | RTLD_FIRST );
566 else
567 #endif
568 ret = dlopen( filename, flag | RTLD_FIRST );
569 s = dlerror();
570 if (error && errorsize)
572 if (s)
574 size_t len = strlen(s);
575 if (len >= errorsize) len = errorsize - 1;
576 memcpy( error, s, len );
577 error[len] = 0;
579 else error[0] = 0;
581 dlerror();
582 return ret;
585 /***********************************************************************
586 * wine_dlsym
588 void *wine_dlsym_obsolete( void *handle, const char *symbol, char *error, size_t errorsize )
590 void *ret;
591 const char *s;
592 dlerror(); dlerror();
593 ret = dlsym( handle, symbol );
594 s = dlerror();
595 if (error && errorsize)
597 if (s)
599 size_t len = strlen(s);
600 if (len >= errorsize) len = errorsize - 1;
601 memcpy( error, s, len );
602 error[len] = 0;
604 else error[0] = 0;
606 dlerror();
607 return ret;
610 /***********************************************************************
611 * wine_dlclose
613 int wine_dlclose_obsolete( void *handle, char *error, size_t errorsize )
615 int ret;
616 const char *s;
617 dlerror(); dlerror();
618 ret = dlclose( handle );
619 s = dlerror();
620 if (error && errorsize)
622 if (s)
624 size_t len = strlen(s);
625 if (len >= errorsize) len = errorsize - 1;
626 memcpy( error, s, len );
627 error[len] = 0;
629 else error[0] = 0;
631 dlerror();
632 return ret;
636 /* check if the library is the correct architecture */
637 /* only returns false for a valid library of the wrong arch */
638 static int check_library_arch( int fd )
640 #ifdef __APPLE__
641 struct /* Mach-O header */
643 unsigned int magic;
644 unsigned int cputype;
645 } header;
647 if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
648 if (header.magic != 0xfeedface) return 1;
649 if (sizeof(void *) == sizeof(int)) return !(header.cputype >> 24);
650 else return (header.cputype >> 24) == 1; /* CPU_ARCH_ABI64 */
651 #else
652 struct /* ELF header */
654 unsigned char magic[4];
655 unsigned char class;
656 unsigned char data;
657 unsigned char version;
658 } header;
660 if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
661 if (memcmp( header.magic, "\177ELF", 4 )) return 1;
662 if (header.version != 1 /* EV_CURRENT */) return 1;
663 #ifdef WORDS_BIGENDIAN
664 if (header.data != 2 /* ELFDATA2MSB */) return 1;
665 #else
666 if (header.data != 1 /* ELFDATA2LSB */) return 1;
667 #endif
668 if (sizeof(void *) == sizeof(int)) return header.class == 1; /* ELFCLASS32 */
669 else return header.class == 2; /* ELFCLASS64 */
670 #endif
673 /* check if a given file can be opened */
674 static int file_exists( const char *name )
676 int ret = 0;
677 int fd = open( name, O_RDONLY );
678 if (fd != -1)
680 ret = check_library_arch( fd );
681 close( fd );
683 return ret;
686 /* open a library for a given dll, searching in the dll path
687 * 'name' must be the Windows dll name (e.g. "kernel32.dll") */
688 static void *dlopen_dll( const char *name, char *error, int errorsize,
689 int test_only, int *exists )
691 struct dll_path_context context;
692 char *path;
693 void *ret = NULL;
695 *exists = 0;
696 for (path = first_dll_path( name, 0, &context ); path; path = next_dll_path( &context ))
698 if (!test_only && (ret = wine_dlopen_obsolete( path, RTLD_NOW, error, errorsize ))) break;
699 if ((*exists = file_exists( path ))) break; /* exists but cannot be loaded, return the error */
701 free_dll_path( &context );
702 return ret;
706 /***********************************************************************
707 * wine_dll_load
709 * Load a builtin dll.
711 void *wine_dll_load_obsolete( const char *filename, char *error, int errorsize, int *file_exists )
713 int i;
715 /* callback must have been set already */
716 assert( load_dll_callback );
718 /* check if we have it in the list */
719 /* this can happen when initializing pre-loaded dlls in wine_dll_set_callback */
720 for (i = 0; i < nb_dlls; i++)
722 if (!builtin_dlls[i].nt) continue;
723 if (!strcmp( builtin_dlls[i].filename, filename ))
725 const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
726 builtin_dlls[i].nt = NULL;
727 load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
728 *file_exists = 1;
729 return (void *)1;
732 return dlopen_dll( filename, error, errorsize, 0, file_exists );
736 /***********************************************************************
737 * wine_dll_unload
739 * Unload a builtin dll.
741 void wine_dll_unload_obsolete( void *handle )
743 if (handle != (void *)1)
744 wine_dlclose_obsolete( handle, NULL, 0 );
748 /***********************************************************************
749 * wine_dll_load_main_exe
751 * Try to load the .so for the main exe.
753 void *wine_dll_load_main_exe_obsolete( const char *name, char *error, int errorsize,
754 int test_only, int *file_exists )
756 return dlopen_dll( name, error, errorsize, test_only, file_exists );
760 /***********************************************************************
761 * wine_dll_get_owner
763 * Retrieve the name of the 32-bit owner dll for a 16-bit dll.
764 * Return 0 if OK, -1 on error.
766 int wine_dll_get_owner_obsolete( const char *name, char *buffer, int size, int *exists )
768 int ret = -1;
769 char *path;
770 struct dll_path_context context;
772 *exists = 0;
774 for (path = first_dll_path( name, 1, &context ); path; path = next_dll_path( &context ))
776 int fd = open( path, O_RDONLY );
777 if (fd != -1)
779 int res = read( fd, buffer, size - 1 );
780 while (res > 0 && (buffer[res-1] == '\n' || buffer[res-1] == '\r')) res--;
781 buffer[res] = 0;
782 close( fd );
783 *exists = 1;
784 ret = 0;
785 break;
788 free_dll_path( &context );
789 return ret;
793 /***********************************************************************
794 * set_max_limit
796 * Set a user limit to the maximum allowed value.
798 static void set_max_limit( int limit )
800 struct rlimit rlimit;
802 if (!getrlimit( limit, &rlimit ))
804 rlimit.rlim_cur = rlimit.rlim_max;
805 if (setrlimit( limit, &rlimit ) != 0)
807 #if defined(__APPLE__) && defined(RLIMIT_NOFILE) && defined(OPEN_MAX)
808 /* On Leopard, setrlimit(RLIMIT_NOFILE, ...) fails on attempts to set
809 * rlim_cur above OPEN_MAX (even if rlim_max > OPEN_MAX). */
810 if (limit == RLIMIT_NOFILE && rlimit.rlim_cur > OPEN_MAX)
812 rlimit.rlim_cur = OPEN_MAX;
813 setrlimit( limit, &rlimit );
815 #endif
821 #ifdef __APPLE__
822 struct apple_stack_info
824 void *stack;
825 size_t desired_size;
828 /***********************************************************************
829 * apple_alloc_thread_stack
831 * Callback for wine_mmap_enum_reserved_areas to allocate space for
832 * the secondary thread's stack.
834 #ifndef _WIN64
835 static int apple_alloc_thread_stack( void *base, size_t size, void *arg )
837 struct apple_stack_info *info = arg;
839 /* For mysterious reasons, putting the thread stack at the very top
840 * of the address space causes subsequent execs to fail, even on the
841 * child side of a fork. Avoid the top 16MB. */
842 char * const limit = (char*)0xff000000;
843 if ((char *)base >= limit) return 0;
844 if (size > limit - (char*)base)
845 size = limit - (char*)base;
846 if (size < info->desired_size) return 0;
847 info->stack = wine_anon_mmap( (char *)base + size - info->desired_size,
848 info->desired_size, PROT_READ|PROT_WRITE, MAP_FIXED );
849 return (info->stack != (void *)-1);
851 #endif
853 /***********************************************************************
854 * apple_create_wine_thread
856 * Spin off a secondary thread to complete Wine initialization, leaving
857 * the original thread for the Mac frameworks.
859 * Invoked as a CFRunLoopSource perform callback.
861 static void apple_create_wine_thread( void *init_func )
863 int success = 0;
864 pthread_t thread;
865 pthread_attr_t attr;
867 if (!pthread_attr_init( &attr ))
869 #ifndef _WIN64
870 struct apple_stack_info info;
872 /* Try to put the new thread's stack in the reserved area. If this
873 * fails, just let it go wherever. It'll be a waste of space, but we
874 * can go on. */
875 if (!pthread_attr_getstacksize( &attr, &info.desired_size ) &&
876 wine_mmap_enum_reserved_areas_obsolete( apple_alloc_thread_stack, &info, 1 ))
878 wine_mmap_remove_reserved_area_obsolete( info.stack, info.desired_size, 0 );
879 pthread_attr_setstackaddr( &attr, (char*)info.stack + info.desired_size );
881 #endif
883 if (!pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ) &&
884 !pthread_create( &thread, &attr, init_func, NULL ))
885 success = 1;
887 pthread_attr_destroy( &attr );
890 /* Failure is indicated by returning from wine_init(). Stopping
891 * the run loop allows apple_main_thread() and thus wine_init() to
892 * return. */
893 if (!success)
894 CFRunLoopStop( CFRunLoopGetCurrent() );
898 /***********************************************************************
899 * apple_main_thread
901 * Park the process's original thread in a Core Foundation run loop for
902 * use by the Mac frameworks, especially receiving and handling
903 * distributed notifications. Spin off a new thread for the rest of the
904 * Wine initialization.
906 static void apple_main_thread( void (*init_func)(void) )
908 CFRunLoopSourceContext source_context = { 0 };
909 CFRunLoopSourceRef source;
911 if (!pthread_main_np())
913 init_func();
914 return;
917 /* Multi-processing Services can get confused about the main thread if the
918 * first time it's used is on a secondary thread. Use it here to make sure
919 * that doesn't happen. */
920 MPTaskIsPreemptive(MPCurrentTaskID());
922 /* Give ourselves the best chance of having the distributed notification
923 * center scheduled on this thread's run loop. In theory, it's scheduled
924 * in the first thread to ask for it. */
925 CFNotificationCenterGetDistributedCenter();
927 /* We use this run loop source for two purposes. First, a run loop exits
928 * if it has no more sources scheduled. So, we need at least one source
929 * to keep the run loop running. Second, although it's not critical, it's
930 * preferable for the Wine initialization to not proceed until we know
931 * the run loop is running. So, we signal our source immediately after
932 * adding it and have its callback spin off the Wine thread. */
933 source_context.info = init_func;
934 source_context.perform = apple_create_wine_thread;
935 source = CFRunLoopSourceCreate( NULL, 0, &source_context );
937 if (source)
939 CFRunLoopAddSource( CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes );
940 CFRunLoopSourceSignal( source );
941 CFRelease( source );
943 CFRunLoopRun(); /* Should never return, except on error. */
946 /* If we get here (i.e. return), that indicates failure to our caller. */
948 #endif
951 /***********************************************************************
952 * wine_init
954 * Main Wine initialisation.
956 void wine_init_obsolete( int argc, char *argv[], char *error, int error_size )
958 struct dll_path_context context;
959 char *path;
960 void *ntdll = NULL;
961 void (*init_func)(void);
963 /* force a few limits that are set too low on some platforms */
964 #ifdef RLIMIT_NOFILE
965 set_max_limit( RLIMIT_NOFILE );
966 #endif
967 #ifdef RLIMIT_AS
968 set_max_limit( RLIMIT_AS );
969 #endif
971 wine_init_argv0_path_obsolete( argv[0] );
972 build_dll_path();
973 __wine_main_argc = argc;
974 __wine_main_argv = argv;
975 __wine_main_environ = __wine_get_main_environment();
976 mmap_init();
978 for (path = first_dll_path( "ntdll.dll", 0, &context ); path; path = next_dll_path( &context ))
980 if ((ntdll = dlopen( path, RTLD_NOW )))
982 /* if we didn't use the default dll dir, remove it from the search path */
983 if (default_dlldir[0] && context.index < nb_dll_paths + 2) nb_dll_paths--;
984 break;
987 free_dll_path( &context );
989 if (!ntdll || !(init_func = dlsym( ntdll, "__wine_process_init" )))
991 if (error && error_size)
993 const char *s = dlerror();
994 if (s)
996 size_t len = min( strlen(s), error_size - 1 );
997 memcpy( error, s, len );
998 error[len] = 0;
1000 else error[0] = 0;
1002 return;
1004 #ifdef __APPLE__
1005 apple_main_thread( init_func );
1006 #else
1007 init_func();
1008 #endif
1011 __ASM_OBSOLETE(wine_dlopen);
1012 __ASM_OBSOLETE(wine_dlsym);
1013 __ASM_OBSOLETE(wine_dlclose);
1014 __ASM_OBSOLETE(wine_dll_enum_load_path);
1015 __ASM_OBSOLETE(wine_dll_get_owner);
1016 __ASM_OBSOLETE(wine_dll_load);
1017 __ASM_OBSOLETE(wine_dll_load_main_exe);
1018 __ASM_OBSOLETE(wine_dll_unload);
1019 __ASM_OBSOLETE(wine_init);
1021 #endif /* __ASM_OBSOLETE */