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