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