Added support for loading a Winelib app linked as a .so from the wine
[wine] / library / loader.c
1 /*
2  * Win32 builtin dlls support
3  *
4  * Copyright 2000 Alexandre Julliard
5  */
6
7 #include "config.h"
8
9 #include <assert.h>
10 #include <ctype.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include <sys/types.h>
14 #include <unistd.h>
15 #ifdef HAVE_SYS_MMAN_H
16 #include <sys/mman.h>
17 #endif
18 #ifdef HAVE_DL_API
19 #include <dlfcn.h>
20 #endif
21
22 #include "winnt.h"
23 #include "wine/library.h"
24 #include "wine/port.h"
25
26 #define MAX_DLLS 100
27
28 static struct
29 {
30     const IMAGE_NT_HEADERS *nt;           /* NT header */
31     const char             *filename;     /* DLL file name */
32 } builtin_dlls[MAX_DLLS];
33
34 static int nb_dlls;
35
36 static const IMAGE_NT_HEADERS *main_exe;
37
38 static load_dll_callback_t load_dll_callback;
39
40 static char **dll_paths;
41 static int nb_dll_paths;
42 static int dll_path_maxlen;
43 static int init_done;
44
45
46 /* build the dll load path from the WINEDLLPATH variable */
47 static void build_dll_path(void)
48 {
49     int count = 0;
50     char *p, *path = getenv( "WINEDLLPATH" );
51
52     init_done = 1;
53     if (!path) return;
54     path = strdup(path);
55     p = path;
56     while (*p)
57     {
58         while (*p == ':') p++;
59         if (!*p) break;
60         count++;
61         while (*p && *p != ':') p++;
62     }
63
64     dll_paths = malloc( count * sizeof(*dll_paths) );
65     p = path;
66     nb_dll_paths = 0;
67     while (*p)
68     {
69         while (*p == ':') *p++ = 0;
70         if (!*p) break;
71         dll_paths[nb_dll_paths] = p;
72         while (*p && *p != ':') p++;
73         if (p - dll_paths[nb_dll_paths] > dll_path_maxlen)
74             dll_path_maxlen = p - dll_paths[nb_dll_paths];
75         nb_dll_paths++;
76     }
77 }
78
79
80 /* open a library for a given dll, searching in the dll path
81  * 'name' must be the Windows dll name (e.g. "kernel32.dll") */
82 static void *dlopen_dll( const char *name )
83 {
84 #ifdef HAVE_DL_API
85     int i, namelen = strlen(name);
86     char *buffer, *p;
87     void *ret = NULL;
88
89     if (!init_done) build_dll_path();
90
91     /* check for .dll or .exe extension to remove */
92     if ((p = strrchr( name, '.' )))
93     {
94         if (!strcasecmp( p, ".dll" ) || !strcasecmp( p, ".exe" )) namelen -= 4;
95     }
96
97     buffer = malloc( dll_path_maxlen + namelen + 8 );
98
99     /* store the name at the end of the buffer, prefixed by /lib and followed by .so */
100     p = buffer + dll_path_maxlen;
101     memcpy( p, "/lib", 4 );
102     for (i = 0, p += 4; i < namelen; i++, p++) *p = tolower(name[i]);
103     memcpy( p, ".so", 4 );
104
105     for (i = 0; i < nb_dll_paths; i++)
106     {
107         int len = strlen(dll_paths[i]);
108         char *p = buffer + dll_path_maxlen - len;
109         memcpy( p, dll_paths[i], len );
110         if ((ret = dlopen( p, RTLD_NOW ))) break;
111     }
112
113     /* now try the default dlopen search path */
114     if (!ret) ret = dlopen( buffer + dll_path_maxlen + 1, RTLD_NOW );
115     free( buffer );
116     return ret;
117 #else
118     return NULL;
119 #endif
120 }
121
122
123 /* adjust an array of pointers to make them into RVAs */
124 static inline void fixup_rva_ptrs( void *array, void *base, int count )
125 {
126     void **ptr = (void **)array;
127     while (count--)
128     {
129         if (*ptr) *ptr = (void *)((char *)*ptr - (char *)base);
130         ptr++;
131     }
132 }
133
134
135 /* fixup RVAs in the resource directory */
136 static void fixup_resources( IMAGE_RESOURCE_DIRECTORY *dir, char *root, void *base )
137 {
138     IMAGE_RESOURCE_DIRECTORY_ENTRY *entry;
139     int i;
140
141     entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
142     for (i = 0; i < dir->NumberOfNamedEntries + dir->NumberOfIdEntries; i++, entry++)
143     {
144         void *ptr = root + entry->u2.s.OffsetToDirectory;
145         if (entry->u2.s.DataIsDirectory) fixup_resources( ptr, root, base );
146         else
147         {
148             IMAGE_RESOURCE_DATA_ENTRY *data = ptr;
149             fixup_rva_ptrs( &data->OffsetToData, base, 1 );
150         }
151     }
152 }
153
154
155 /* map a builtin dll in memory and fixup RVAs */
156 static void *map_dll( const IMAGE_NT_HEADERS *nt_descr )
157 {
158     IMAGE_DATA_DIRECTORY *dir;
159     IMAGE_DOS_HEADER *dos;
160     IMAGE_NT_HEADERS *nt;
161     IMAGE_SECTION_HEADER *sec;
162     BYTE *addr, *code_start, *data_start;
163     size_t page_size = getpagesize();
164     int nb_sections = 2;  /* code + data */
165
166     size_t size = (sizeof(IMAGE_DOS_HEADER)
167                    + sizeof(IMAGE_NT_HEADERS)
168                    + nb_sections * sizeof(IMAGE_SECTION_HEADER));
169
170     assert( size <= page_size );
171
172     if (nt_descr->OptionalHeader.ImageBase)
173     {
174         addr = wine_anon_mmap( (void *)nt_descr->OptionalHeader.ImageBase,
175                                page_size, PROT_READ|PROT_WRITE, MAP_FIXED );
176         if (addr != (BYTE *)nt_descr->OptionalHeader.ImageBase) return NULL;
177     }
178     else
179     {
180         /* this will leak memory; but it should never happen */
181         addr = wine_anon_mmap( NULL, page_size, PROT_READ|PROT_WRITE, 0 );
182         if (addr == (BYTE *)-1) return NULL;
183     }
184
185     dos    = (IMAGE_DOS_HEADER *)addr;
186     nt     = (IMAGE_NT_HEADERS *)(dos + 1);
187     sec    = (IMAGE_SECTION_HEADER *)(nt + 1);
188     code_start = addr + page_size;
189
190     /* HACK! */
191     data_start = code_start + page_size;
192
193     /* Build the DOS and NT headers */
194
195     dos->e_magic  = IMAGE_DOS_SIGNATURE;
196     dos->e_lfanew = sizeof(*dos);
197
198     *nt = *nt_descr;
199
200     nt->FileHeader.NumberOfSections                = nb_sections;
201     nt->OptionalHeader.SizeOfCode                  = data_start - code_start;
202     nt->OptionalHeader.SizeOfInitializedData       = 0;
203     nt->OptionalHeader.SizeOfUninitializedData     = 0;
204     nt->OptionalHeader.ImageBase                   = (DWORD)addr;
205
206     fixup_rva_ptrs( &nt->OptionalHeader.AddressOfEntryPoint, addr, 1 );
207
208     /* Build the code section */
209
210     strcpy( sec->Name, ".text" );
211     sec->SizeOfRawData = data_start - code_start;
212     sec->Misc.VirtualSize = sec->SizeOfRawData;
213     sec->VirtualAddress   = code_start - addr;
214     sec->PointerToRawData = code_start - addr;
215     sec->Characteristics  = (IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ);
216     sec++;
217
218     /* Build the data section */
219
220     strcpy( sec->Name, ".data" );
221     sec->SizeOfRawData = 0;
222     sec->Misc.VirtualSize = sec->SizeOfRawData;
223     sec->VirtualAddress   = data_start - addr;
224     sec->PointerToRawData = data_start - addr;
225     sec->Characteristics  = (IMAGE_SCN_CNT_INITIALIZED_DATA |
226                              IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ);
227     sec++;
228
229     /* Build the import directory */
230
231     dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY];
232     if (dir->Size)
233     {
234         IMAGE_IMPORT_DESCRIPTOR *imports = (void *)dir->VirtualAddress;
235         fixup_rva_ptrs( &dir->VirtualAddress, addr, 1 );
236         /* we can fixup everything at once since we only have pointers and 0 values */
237         fixup_rva_ptrs( imports, addr, dir->Size / sizeof(void*) );
238     }
239
240     /* Build the resource directory */
241
242     dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_RESOURCE_DIRECTORY];
243     if (dir->Size)
244     {
245         void *ptr = (void *)dir->VirtualAddress;
246         fixup_rva_ptrs( &dir->VirtualAddress, addr, 1 );
247         fixup_resources( ptr, ptr, addr );
248     }
249
250     /* Build the export directory */
251
252     dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_EXPORT_DIRECTORY];
253     if (dir->Size)
254     {
255         IMAGE_EXPORT_DIRECTORY *exports = (void *)dir->VirtualAddress;
256         fixup_rva_ptrs( &dir->VirtualAddress, addr, 1 );
257         fixup_rva_ptrs( (void *)exports->AddressOfFunctions, addr, exports->NumberOfFunctions );
258         fixup_rva_ptrs( (void *)exports->AddressOfNames, addr, exports->NumberOfNames );
259         fixup_rva_ptrs( &exports->Name, addr, 1 );
260         fixup_rva_ptrs( &exports->AddressOfFunctions, addr, 1 );
261         fixup_rva_ptrs( &exports->AddressOfNames, addr, 1 );
262         fixup_rva_ptrs( &exports->AddressOfNameOrdinals, addr, 1 );
263     }
264     return addr;
265 }
266
267
268 /***********************************************************************
269  *           __wine_dll_register
270  *
271  * Register a built-in DLL descriptor.
272  */
273 void __wine_dll_register( const IMAGE_NT_HEADERS *header, const char *filename )
274 {
275     if (load_dll_callback) load_dll_callback( map_dll(header), filename );
276     else
277     {
278         if (!(header->FileHeader.Characteristics & IMAGE_FILE_DLL))
279             main_exe = header;
280         else
281         {
282             assert( nb_dlls < MAX_DLLS );
283             builtin_dlls[nb_dlls].nt = header;
284             builtin_dlls[nb_dlls].filename = filename;
285             nb_dlls++;
286         }
287     }
288 }
289
290
291 /***********************************************************************
292  *           wine_dll_set_callback
293  *
294  * Set the callback function for dll loading, and call it
295  * for all dlls that were implicitly loaded already.
296  */
297 void wine_dll_set_callback( load_dll_callback_t load )
298 {
299     int i;
300     load_dll_callback = load;
301     for (i = 0; i < nb_dlls; i++)
302     {
303         const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
304         if (!nt) continue;
305         builtin_dlls[i].nt = NULL;
306         load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
307     }
308     nb_dlls = 0;
309     if (main_exe) load_dll_callback( map_dll(main_exe), "" );
310 }
311
312
313 /***********************************************************************
314  *           wine_dll_load
315  *
316  * Load a builtin dll.
317  */
318 void *wine_dll_load( const char *filename )
319 {
320     int i;
321
322     /* callback must have been set already */
323     assert( load_dll_callback );
324
325     /* check if we have it in the list */
326     /* this can happen when initializing pre-loaded dlls in wine_dll_set_callback */
327     for (i = 0; i < nb_dlls; i++)
328     {
329         if (!builtin_dlls[i].nt) continue;
330         if (!strcasecmp( builtin_dlls[i].filename, filename ))
331         {
332             const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
333             builtin_dlls[i].nt = NULL;
334             load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
335             return (void *)1;
336         }
337     }
338     return dlopen_dll( filename );
339 }
340
341
342 /***********************************************************************
343  *           wine_dll_unload
344  *
345  * Unload a builtin dll.
346  */
347 void wine_dll_unload( void *handle )
348 {
349 #ifdef HAVE_DL_API
350     if (handle != (void *)1) dlclose( handle );
351 #endif
352 }
353
354
355 /***********************************************************************
356  *           wine_dll_load_main_exe
357  *
358  * Try to load the .so for the main exe, optionally searching for it in PATH.
359  */
360 void *wine_dll_load_main_exe( const char *name, int search_path )
361 {
362     void *ret = NULL;
363 #ifdef HAVE_DL_API
364     const char *path = NULL;
365     if (search_path) path = getenv( "PATH" );
366
367     if (!path)
368     {
369         /* no path, try only the specified name */
370         ret = dlopen( name, RTLD_NOW );
371     }
372     else
373     {
374         char buffer[128], *tmp = buffer;
375         size_t namelen = strlen(name);
376         size_t pathlen = strlen(path);
377
378         if (namelen + pathlen + 2 > sizeof(buffer)) tmp = malloc( namelen + pathlen + 2 );
379         if (tmp)
380         {
381             char *basename = tmp + pathlen;
382             *basename = '/';
383             strcpy( basename + 1, name );
384             for (;;)
385             {
386                 int len;
387                 const char *p = strchr( path, ':' );
388                 if (!p) p = path + strlen(path);
389                 if ((len = p - path) > 0)
390                 {
391                     memcpy( basename - len, path, len );
392                     if ((ret = dlopen( basename - len, RTLD_NOW ))) break;
393                 }
394                 if (!*p) break;
395                 path = p + 1;
396             }
397             if (tmp != buffer) free( tmp );
398         }
399     }
400 #endif  /* HAVE_DL_API */
401     return ret;
402 }