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