loader.c 30 KB

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