Bugfix: *Don't* resolve PE imports if asked not to ...
[wine] / loader / loadorder.c
1 /*
2  * Module/Library loadorder
3  *
4  * Copyright 1999 Bertho Stultiens
5  */
6
7 #include <stdlib.h>
8 #include <string.h>
9 #include <assert.h>
10
11 #include "config.h"
12 #include "windef.h"
13 #include "options.h"
14 #include "loadorder.h"
15 #include "heap.h"
16 #include "options.h"
17 #include "module.h"
18 #include "elfdll.h"
19 #include "debugtools.h"
20
21 DEFAULT_DEBUG_CHANNEL(module)
22
23
24 /* #define DEBUG_LOADORDER */
25
26 #define LOADORDER_ALLOC_CLUSTER 32      /* Allocate with 32 entries at a time */
27
28 static module_loadorder_t default_loadorder;
29 static module_loadorder_t *module_loadorder = NULL;
30 static int nmodule_loadorder = 0;
31 static int nmodule_loadorder_alloc = 0;
32
33 static struct tagDllOverride {
34         char *key,*value;
35 } DefaultDllOverrides[] = {
36         {"kernel32,gdi32,user32",       "builtin"},
37         {"kernel,gdi,user",             "builtin"},
38         {"toolhelp",                    "builtin"},
39         {"comdlg32,commdlg",            "elfdll,builtin,native"},
40         {"version,ver",                 "elfdll,builtin,native"},
41         {"shell32,shell",               "builtin,native"},
42         {"shlwapi",                     "native,builtin"},
43         {"lz32,lzexpand",               "builtin,native"},
44         {"commctrl,comctl32",           "builtin,native"},
45         {"wsock32,winsock",             "builtin"},
46         {"advapi32,crtdll,ntdll",       "builtin,native"},
47         {"mpr,winspool.drv",            "builtin,native"},
48         {"ddraw,dinput,dsound",         "builtin,native"},
49         {"winmm, mmsystem",             "builtin"},
50         {"msvideo, msvfw32",            "builtin, native"},
51         {"mcicda.drv, mciseq.drv",      "builtin, native"},
52         {"mciwave.drv",                 "builtin, native"},
53         {"mciavi.drv, mcianim.drv",     "native, builtin"},
54         {"w32skrnl",                    "builtin"},
55         {"wnaspi32,wow32",              "builtin"},
56         {"system,display,wprocs ",      "builtin"},
57         {"wineps",                      "builtin"},
58         /* we have to use libglide2x.so instead of glide2x.dll ... */
59         {"glide2x",                     "so,native"},
60         {NULL,NULL},
61 };
62
63 /***************************************************************************
64  *      cmp_sort_func   (internal, static)
65  *
66  * Sorting and comparing function used in sort and search of loadorder
67  * entries.
68  */
69 static int cmp_sort_func(const void *s1, const void *s2)
70 {
71         return strcasecmp(((module_loadorder_t *)s1)->modulename, ((module_loadorder_t *)s2)->modulename);
72 }
73
74
75 /***************************************************************************
76  *      get_tok (internal, static)
77  *
78  * strtok wrapper for non-destructive buffer writing.
79  * NOTE: strtok is not reentrant and therefore this code is neither.
80  */
81 static char *get_tok(const char *str, const char *delim)
82 {
83         static char *buf = NULL;
84         char *cptr;
85
86         if(!str && !buf)
87                 return NULL;
88
89         if(str && buf)
90         {
91                 HeapFree(SystemHeap, 0, buf);
92                 buf = NULL;
93         }
94
95         if(str && !buf)
96         {
97                 buf = HEAP_strdupA(SystemHeap, 0, str);
98                 cptr = strtok(buf, delim);
99         }
100         else
101         {
102                 cptr = strtok(NULL, delim);
103         }
104
105         if(!cptr)
106         {
107                 HeapFree(SystemHeap, 0, buf);
108                 buf = NULL;
109         }
110         return cptr;
111 }
112
113
114 /***************************************************************************
115  *      ParseLoadOrder  (internal, static)
116  *
117  * Parses the loadorder options from the configuration and puts it into
118  * a structure.
119  */
120 static BOOL ParseLoadOrder(char *order, module_loadorder_t *mlo)
121 {
122         char *cptr;
123         int n = 0;
124
125         memset(mlo->loadorder, 0, sizeof(mlo->loadorder));
126
127         cptr = get_tok(order, ", \t");
128         while(cptr)
129         {
130                 char type = MODULE_LOADORDER_INVALID;
131
132                 if(n >= MODULE_LOADORDER_NTYPES)
133                 {
134                         ERR("More than existing %d module-types specified, rest ignored", MODULE_LOADORDER_NTYPES);
135                         break;
136                 }
137
138                 switch(*cptr)
139                 {
140                 case 'N':       /* Native */
141                 case 'n': type = MODULE_LOADORDER_DLL; break;
142
143                 case 'E':       /* Elfdll */
144                 case 'e': type = MODULE_LOADORDER_ELFDLL; break;
145
146                 case 'S':       /* So */
147                 case 's': type = MODULE_LOADORDER_SO; break;
148
149                 case 'B':       /* Builtin */
150                 case 'b': type = MODULE_LOADORDER_BI; break;
151
152                 default:
153                         ERR("Invalid load order module-type '%s', ignored\n", cptr);
154                 }
155
156                 if(type != MODULE_LOADORDER_INVALID)
157                 {
158                         mlo->loadorder[n++] = type;
159                 }
160                 cptr = get_tok(NULL, ", \t");
161         }
162         return TRUE;
163 }
164
165
166 /***************************************************************************
167  *      AddLoadOrder    (internal, static)
168  *
169  * Adds an entry in the list of overrides. If the entry exists then the
170  * override parameter determines whether it will be overwriten.
171  */
172 static BOOL AddLoadOrder(module_loadorder_t *plo, BOOL override)
173 {
174         int i;
175
176         /* TRACE(module, "'%s' -> %08lx\n", plo->modulename, *(DWORD *)(plo->loadorder)); */
177
178         for(i = 0; i < nmodule_loadorder; i++)
179         {
180                 if(!cmp_sort_func(plo, &module_loadorder[i]))
181                 {
182                         if(!override)
183                                 ERR("Module '%s' is already in the list of overrides, using first definition\n", plo->modulename);
184                         else
185                                 memcpy(module_loadorder[i].loadorder, plo->loadorder, sizeof(plo->loadorder));
186                         return TRUE;
187                 }
188         }
189
190         if(nmodule_loadorder >= nmodule_loadorder_alloc)
191         {
192                 /* No space in current array, make it larger */
193                 nmodule_loadorder_alloc += LOADORDER_ALLOC_CLUSTER;
194                 module_loadorder = (module_loadorder_t *)HeapReAlloc(SystemHeap,
195                                                                      0,
196                                                                      module_loadorder,
197                                                                      nmodule_loadorder_alloc * sizeof(module_loadorder_t));
198                 if(!module_loadorder)
199                 {
200                         MESSAGE("Virtual memory exhausted\n");
201                         exit(1);
202                 }
203         }
204         memcpy(module_loadorder[nmodule_loadorder].loadorder, plo->loadorder, sizeof(plo->loadorder));
205         module_loadorder[nmodule_loadorder].modulename = HEAP_strdupA(SystemHeap, 0, plo->modulename);
206         nmodule_loadorder++;
207         return TRUE;
208 }
209
210
211 /***************************************************************************
212  *      AddLoadOrderSet (internal, static)
213  *
214  * Adds an set of entries in the list of overrides from the key parameter.
215  * If the entry exists then the override parameter determines whether it
216  * will be overwriten.
217  */
218 static BOOL AddLoadOrderSet(char *key, char *order, BOOL override)
219 {
220         module_loadorder_t ldo;
221         char *cptr;
222
223         /* Parse the loadorder before the rest because strtok is not reentrant */
224         if(!ParseLoadOrder(order, &ldo))
225                 return FALSE;
226
227         cptr = get_tok(key, ", \t");
228         while(cptr)
229         {
230                 char *ext = strrchr(cptr, '.');
231                 if(ext)
232                 {
233                         if(strlen(ext) == 4 && (!strcasecmp(ext, ".dll") || !strcasecmp(ext, ".exe")))
234                                 MESSAGE("Warning: Loadorder override '%s' contains an extension and might not be found during lookup\n", cptr);
235                 }
236
237                 ldo.modulename = cptr;
238                 if(!AddLoadOrder(&ldo, override))
239                         return FALSE;
240                 cptr = get_tok(NULL, ", \t");
241         }
242         return TRUE;
243 }
244
245
246 /***************************************************************************
247  *      ParseCommandlineOverrides       (internal, static)
248  *
249  * The commandline is in the form:
250  * name[,name,...]=native[,b,...][:...]
251  */
252 static BOOL ParseCommandlineOverrides(void)
253 {
254         char *cpy;
255         char *key;
256         char *next;
257         char *value;
258         BOOL retval = TRUE;
259
260         if(!Options.dllFlags)
261                 return TRUE;
262
263         cpy = HEAP_strdupA(SystemHeap, 0, Options.dllFlags);
264         key = cpy;
265         next = key;
266         for(; next; key = next)
267         {
268                 next = strchr(key, ':');
269                 if(next)
270                 {
271                         *next = '\0';
272                         next++;
273                 }
274                 value = strchr(key, '=');
275                 if(!value)
276                 {
277                         retval = FALSE;
278                         goto endit;
279                 }
280                 *value = '\0';
281                 value++;
282
283                 TRACE("Commandline override '%s' = '%s'\n", key, value);
284                 
285                 if(!AddLoadOrderSet(key, value, TRUE))
286                 {
287                         retval = FALSE;
288                         goto endit;
289                 }
290         }
291 endit:
292         HeapFree(SystemHeap, 0, cpy);
293         return retval;;
294 }
295
296
297 /***************************************************************************
298  *      MODULE_InitLoadOrder    (internal)
299  *
300  * Initialize the load order from the wine.conf file.
301  * The section has tyhe following format:
302  * Section:
303  *      [DllDefaults]
304  *
305  * Keys:
306  *      EXTRA_LD_LIBRARY_PATH=/usr/local/lib/wine[:/more/path/to/search[:...]]
307  * The path will be appended to any existing LD_LIBRARY_PATH from the 
308  * environment (see note in code below).
309  *
310  *      DefaultLoadOrder=native,elfdll,so,builtin
311  * A comma seperated list of module-types to try to load in that specific
312  * order. The DefaultLoadOrder key is used as a fallback when a module is
313  * not specified explicitely. If the DefaultLoadOrder key is not found, 
314  * then the order "dll,elfdll,so,bi" is used
315  * The possible module-types are:
316  *      - native        Native windows dll files
317  *      - elfdll        Dlls encapsulated in .so libraries
318  *      - so            Native .so libraries mapped to dlls
319  *      - builtin       Built-in modules
320  *
321  * Case is not important and only the first letter of each type is enough to
322  * identify the type n[ative], e[lfdll], s[o], b[uiltin]. Also whitespace is
323  * ignored.
324  * E.g.:
325  *      n,el    ,s , b
326  * is equal to:
327  *      native,elfdll,so,builtin
328  *
329  * Section:
330  *      [DllOverrides]
331  *
332  * Keys:
333  * There are no explicit keys defined other than module/library names. A comma
334  * separated list of modules is followed by an assignment of the load-order
335  * for these specific modules. See above for possible types. You should not
336  * specify an extension.
337  * Examples:
338  * kernel32, gdi32, user32 = builtin
339  * kernel, gdi, user = builtin
340  * comdlg32 = elfdll, native, builtin
341  * commdlg = native, builtin
342  * version, ver = elfdll, native, builtin
343  *
344  * Section:
345  *      [DllPairs]
346  *
347  * Keys:
348  * This is a simple pairing in the form 'name1 = name2'. It is supposed to
349  * identify the dlls that cannot live without eachother unless they are
350  * loaded in the same format. Examples are common dialogs and controls,
351  * shell, kernel, gdi, user, etc...
352  * The code will issue a warning if the loadorder of these pairs are different
353  * and might cause hard-to-find bugs due to incompatible pairs loaded at
354  * run-time. Note that this pairing gives *no* guarantee that the pairs
355  * actually get loaded as the same type, nor that the correct versions are
356  * loaded (might be implemented later). It merely notes obvious trouble.
357  * Examples:
358  * kernel = kernel32
359  * commdlg = comdlg32
360  *
361  */
362
363 #define BUFFERSIZE      1024
364
365 BOOL MODULE_InitLoadOrder(void)
366 {
367         char buffer[BUFFERSIZE];
368         int nbuffer;
369
370 #if defined(HAVE_DL_API)
371         /* Get/set the new LD_LIBRARY_PATH */
372         nbuffer = PROFILE_GetWineIniString("DllDefaults", "EXTRA_LD_LIBRARY_PATH", "", buffer, sizeof(buffer));
373
374         if(nbuffer)
375         {
376                 extra_ld_library_path = HEAP_strdupA(SystemHeap, 0, buffer);
377                 TRACE("Setting extra LD_LIBRARY_PATH=%s\n", buffer);
378         }
379 #endif
380
381         /* Get the default load order */
382         nbuffer = PROFILE_GetWineIniString("DllDefaults", "DefaultLoadOrder", "n,e,s,b", buffer, sizeof(buffer));
383         if(!nbuffer)
384         {
385                 MESSAGE("MODULE_InitLoadOrder: misteriously read nothing from default loadorder\n");
386                 return FALSE;
387         }
388
389         TRACE("Setting default loadorder=%s\n", buffer);
390
391         if(!ParseLoadOrder(buffer, &default_loadorder))
392                 return FALSE;
393         default_loadorder.modulename = "<none>";
394
395         {
396             int i;
397             for (i=0;DefaultDllOverrides[i].key;i++)
398                 AddLoadOrderSet(
399                     DefaultDllOverrides[i].key,
400                     DefaultDllOverrides[i].value,
401                     FALSE
402                 );
403         }
404
405         /* Read the explicitely defined orders for specific modules as an entire section */
406         nbuffer = PROFILE_GetWineIniString("DllOverrides", NULL, "", buffer, sizeof(buffer));
407         if(nbuffer == BUFFERSIZE-2)
408         {
409                 ERR("BUFFERSIZE %d is too small to read [DllOverrides]. Needs to grow in the source\n", BUFFERSIZE);
410                 return FALSE;
411         }
412         if(nbuffer)
413         {
414                 /* We only have the keys in the buffer, not the values */
415                 char *key;
416                 char value[BUFFERSIZE];
417                 char *next;
418
419                 for(key = buffer; *key; key = next)
420                 {
421                         next = key + strlen(key) + 1;
422
423                         nbuffer = PROFILE_GetWineIniString("DllOverrides", key, "", value, sizeof(value));
424                         if(!nbuffer)
425                         {
426                                 ERR("Module(s) '%s' will always fail to load. Are you sure you want this?\n", key);
427                                 value[0] = '\0';        /* Just in case */
428                         }
429                         if(nbuffer == BUFFERSIZE-2)
430                         {
431                                 ERR("BUFFERSIZE %d is too small to read [DllOverrides] key '%s'. Needs to grow in the source\n", BUFFERSIZE, key);
432                                 return FALSE;
433                         }
434
435                         TRACE("Key '%s' uses override '%s'\n", key, value);
436
437                         if(!AddLoadOrderSet(key, value, TRUE))
438                                 return FALSE;
439                 }
440         }
441
442         /* Add the commandline overrides to the pool */
443         if(!ParseCommandlineOverrides())
444         {
445                 MESSAGE(        "Syntax: -dll name[,name[,...]]={native|elfdll|so|builtin}[,{n|e|s|b}[,...]][:...]\n"
446                         "    - 'name' is the name of any dll without extension\n"
447                         "    - the order of loading (native, elfdll, so and builtin) can be abbreviated\n"
448                         "      with the first letter\n"
449                         "    - different loadorders for different dlls can be specified by seperating the\n"
450                         "      commandline entries with a ':'\n"
451                         "    Example:\n"
452                         "    -dll comdlg32,commdlg=n:shell,shell32=b\n"
453                    );
454                 return FALSE;
455         }
456
457         /* Sort the array for quick lookup */
458         qsort(module_loadorder, nmodule_loadorder, sizeof(module_loadorder[0]), cmp_sort_func);
459
460         /* Check the pairs of dlls */
461         nbuffer = PROFILE_GetWineIniString("DllPairs", NULL, "", buffer, sizeof(buffer));
462         if(nbuffer == BUFFERSIZE-2)
463         {
464                 ERR("BUFFERSIZE %d is too small to read [DllPairs]. Needs to grow in the source\n", BUFFERSIZE);
465                 return FALSE;
466         }
467         if(nbuffer)
468         {
469                 /* We only have the keys in the buffer, not the values */
470                 char *key;
471                 char value[BUFFERSIZE];
472                 char *next;
473
474                 for(key = buffer; *key; key = next)
475                 {
476                         module_loadorder_t *plo1, *plo2;
477
478                         next = key + strlen(key) + 1;
479
480                         nbuffer = PROFILE_GetWineIniString("DllPairs", key, "", value, sizeof(value));
481                         if(!nbuffer)
482                         {
483                                 ERR("Module pair '%s' is not associated with another module?\n", key);
484                                 continue;
485                         }
486                         if(nbuffer == BUFFERSIZE-2)
487                         {
488                                 ERR("BUFFERSIZE %d is too small to read [DllPairs] key '%s'. Needs to grow in the source\n", BUFFERSIZE, key);
489                                 return FALSE;
490                         }
491
492                         plo1 = MODULE_GetLoadOrder(key);
493                         plo2 = MODULE_GetLoadOrder(value);
494                         assert(plo1 && plo2);
495
496                         if(memcmp(plo1->loadorder, plo2->loadorder, sizeof(plo1->loadorder)))
497                                 MESSAGE("Warning: Modules '%s' and '%s' have different loadorder which may cause trouble\n", key, value);
498                 }
499         }
500
501         if(TRACE_ON(module))
502         {
503                 int i, j;
504                 static char types[6] = "-NESB";
505
506                 for(i = 0; i < nmodule_loadorder; i++)
507                 {
508                         DPRINTF("%3d: %-12s:", i, module_loadorder[i].modulename);
509                         for(j = 0; j < MODULE_LOADORDER_NTYPES; j++)
510                                 DPRINTF(" %c", types[module_loadorder[i].loadorder[j] % (MODULE_LOADORDER_NTYPES+1)]);
511                         DPRINTF("\n");
512                 }
513         }
514
515         return TRUE;
516 }
517
518
519 /***************************************************************************
520  *      MODULE_GetLoadOrder     (internal)
521  *
522  * Locate the loadorder of a module.
523  * Any path is stripped from the path-argument and so are the extension
524  * '.dll' and '.exe'. A lookup in the table can yield an override for
525  * the specific dll. Otherwise the default load order is returned.
526  */
527 module_loadorder_t *MODULE_GetLoadOrder(const char *path)
528 {
529         module_loadorder_t lo, *tmp;
530         char fname[256];
531         char *cptr;
532         char *name;
533         int len;
534
535         assert(path != NULL);
536
537         /* Strip path information */
538         cptr = strrchr(path, '\\');
539         if(!cptr)
540                 name = strrchr(path, '/');
541         else
542                 name = strrchr(cptr, '/');
543
544         if(!name)
545                 name = cptr ? cptr+1 : (char *)path;
546         else
547                 name++;
548
549         if((cptr = strchr(name, ':')) != NULL)  /* Also strip drive if in format 'C:MODULE.DLL' */
550                 name = cptr+1;
551
552         len = strlen(name);
553         if(len >= sizeof(fname) || len <= 0)
554         {
555                 ERR("Path '%s' -> '%s' reduces to zilch or just too large...\n", path, name);
556                 return &default_loadorder;
557         }
558
559         strcpy(fname, name);
560         if(len >= 4 && (!lstrcmpiA(fname+len-4, ".dll") || !lstrcmpiA(fname+len-4, ".exe")))
561                 fname[len-4] = '\0';
562
563         lo.modulename = fname;
564         tmp = bsearch(&lo, module_loadorder, nmodule_loadorder, sizeof(module_loadorder[0]), cmp_sort_func);
565
566         TRACE("Looking for '%s' (%s), found '%s'\n", path, fname, tmp ? tmp->modulename : "<nothing>");
567
568         if(!tmp)
569                 return &default_loadorder;
570         return tmp;
571 }
572