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