loader.c 34 KB

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