Fix problem exposed by the improvements in version 8b. Demonstrated by
[wine] / loader / loadorder.c
1 /*
2  * Module/Library loadorder
3  *
4  * Copyright 1999 Bertho Stultiens
5  */
6
7 #include "config.h"
8
9 #include <stdlib.h>
10 #include <string.h>
11 #include <assert.h>
12
13 #include "windef.h"
14 #include "winreg.h"
15 #include "winerror.h"
16 #include "options.h"
17 #include "file.h"
18 #include "module.h"
19 #include "debugtools.h"
20
21 DEFAULT_DEBUG_CHANNEL(module);
22
23 #define LOADORDER_ALLOC_CLUSTER 32      /* Allocate with 32 entries at a time */
24
25 typedef struct module_loadorder
26 {
27     const char         *modulename;
28     enum loadorder_type loadorder[LOADORDER_NTYPES];
29 } module_loadorder_t;
30
31 struct loadorder_list
32 {
33     int                 count;
34     int                 alloc;
35     module_loadorder_t *order;
36 };
37
38 /* default load-order if nothing specified */
39 /* the list must remain sorted by dll name */
40 static module_loadorder_t default_order_list[] =
41 {
42     { "display",      { LOADORDER_BI,  0,             0, 0 } },
43     { "gdi",          { LOADORDER_BI,  0,             0, 0 } },
44     { "gdi32",        { LOADORDER_BI,  0,             0, 0 } },
45     { "glide2x",      { LOADORDER_SO,  LOADORDER_DLL, 0, 0 } },
46     { "glide3x",      { LOADORDER_SO,  LOADORDER_DLL, 0, 0 } },
47     { "icmp",         { LOADORDER_BI,  0,             0, 0 } },
48     { "kernel",       { LOADORDER_BI,  0,             0, 0 } },
49     { "kernel32",     { LOADORDER_BI,  0,             0, 0 } },
50     { "keyboard",     { LOADORDER_BI,  0,             0, 0 } },
51     { "krnl386",      { LOADORDER_BI,  0,             0, 0 } },
52     { "mmsystem",     { LOADORDER_BI,  0,             0, 0 } },
53     { "mouse",        { LOADORDER_BI,  0,             0, 0 } },
54     { "ntdll",        { LOADORDER_BI,  0,             0, 0 } },
55     { "odbc32",       { LOADORDER_BI,  0,             0, 0 } },
56     { "system",       { LOADORDER_BI,  0,             0, 0 } },
57     { "toolhelp",     { LOADORDER_BI,  0,             0, 0 } },
58     { "ttydrv",       { LOADORDER_BI,  0,             0, 0 } },
59     { "user",         { LOADORDER_BI,  0,             0, 0 } },
60     { "user32",       { LOADORDER_BI,  0,             0, 0 } },
61     { "w32skrnl",     { LOADORDER_BI,  0,             0, 0 } },
62     { "winaspi",      { LOADORDER_BI,  0,             0, 0 } },
63     { "windebug",     { LOADORDER_DLL, LOADORDER_BI,  0, 0 } },
64     { "winedos",      { LOADORDER_BI,  0,             0, 0 } },
65     { "wineps",       { LOADORDER_BI,  0,             0, 0 } },
66     { "wing",         { LOADORDER_BI,  0,             0, 0 } },
67     { "winmm",        { LOADORDER_BI,  0,             0, 0 } },
68     { "winsock",      { LOADORDER_BI,  0,             0, 0 } },
69     { "wnaspi32",     { LOADORDER_BI,  0,             0, 0 } },
70     { "wow32",        { LOADORDER_BI,  0,             0, 0 } },
71     { "wprocs",       { LOADORDER_BI,  0,             0, 0 } },
72     { "ws2_32",       { LOADORDER_BI,  0,             0, 0 } },
73     { "wsock32",      { LOADORDER_BI,  0,             0, 0 } },
74     { "x11drv",       { LOADORDER_BI,  0,             0, 0 } }
75 };
76
77 static const struct loadorder_list default_list =
78 {
79     sizeof(default_order_list)/sizeof(default_order_list[0]),
80     sizeof(default_order_list)/sizeof(default_order_list[0]),
81     default_order_list
82 };
83
84 static struct loadorder_list cmdline_list;
85
86
87 /***************************************************************************
88  *      cmp_sort_func   (internal, static)
89  *
90  * Sorting and comparing function used in sort and search of loadorder
91  * entries.
92  */
93 static int cmp_sort_func(const void *s1, const void *s2)
94 {
95     return FILE_strcasecmp(((module_loadorder_t *)s1)->modulename,
96                            ((module_loadorder_t *)s2)->modulename);
97 }
98
99
100 /***************************************************************************
101  *      get_tok (internal, static)
102  *
103  * strtok wrapper for non-destructive buffer writing.
104  * NOTE: strtok is not reentrant and therefore this code is neither.
105  */
106 static char *get_tok(const char *str, const char *delim)
107 {
108         static char *buf = NULL;
109         char *cptr;
110
111         if(!str && !buf)
112                 return NULL;
113
114         if(str && buf)
115         {
116                 HeapFree(GetProcessHeap(), 0, buf);
117                 buf = NULL;
118         }
119
120         if(str && !buf)
121         {
122                 buf = HeapAlloc(GetProcessHeap(), 0, strlen(str)+1);
123                 strcpy( buf, str );
124                 cptr = strtok(buf, delim);
125         }
126         else
127         {
128                 cptr = strtok(NULL, delim);
129         }
130
131         if(!cptr)
132         {
133                 HeapFree(GetProcessHeap(), 0, buf);
134                 buf = NULL;
135         }
136         return cptr;
137 }
138
139
140 /***************************************************************************
141  *      ParseLoadOrder  (internal, static)
142  *
143  * Parses the loadorder options from the configuration and puts it into
144  * a structure.
145  */
146 static BOOL ParseLoadOrder(char *order, enum loadorder_type lo[])
147 {
148     static int warn;
149         char *cptr;
150         int n = 0;
151
152         cptr = get_tok(order, ", \t");
153         while(cptr)
154         {
155             enum loadorder_type type = LOADORDER_INVALID;
156
157                 if(n >= LOADORDER_NTYPES-1)
158                 {
159                         ERR("More than existing %d module-types specified, rest ignored\n", LOADORDER_NTYPES-1);
160                         break;
161                 }
162
163                 switch(*cptr)
164                 {
165                 case 'N':       /* Native */
166                 case 'n': type = LOADORDER_DLL; break;
167
168                 case 'E':       /* Elfdll */
169                 case 'e':
170                     if (!warn++) MESSAGE("Load order 'elfdll' no longer supported, ignored\n");
171                     break;
172                 case 'S':       /* So */
173                 case 's': type = LOADORDER_SO; break;
174
175                 case 'B':       /* Builtin */
176                 case 'b': type = LOADORDER_BI; break;
177
178                 default:
179                         ERR("Invalid load order module-type '%s', ignored\n", cptr);
180                 }
181
182                 if(type != LOADORDER_INVALID) lo[n++] = type;
183                 cptr = get_tok(NULL, ", \t");
184         }
185         lo[n] = LOADORDER_INVALID;
186         return TRUE;
187 }
188
189
190 /***************************************************************************
191  *      AddLoadOrder    (internal, static)
192  *
193  * Adds an entry in the list of command-line overrides.
194  */
195 static BOOL AddLoadOrder(module_loadorder_t *plo)
196 {
197         int i;
198
199         /* TRACE(module, "'%s' -> %08lx\n", plo->modulename, *(DWORD *)(plo->loadorder)); */
200
201         for(i = 0; i < cmdline_list.count; i++)
202         {
203             if(!cmp_sort_func(plo, &cmdline_list.order[i] ))
204             {
205                 /* replace existing option */
206                 memcpy( cmdline_list.order[i].loadorder, plo->loadorder, sizeof(plo->loadorder));
207                 return TRUE;
208             }
209         }
210
211         if (i >= cmdline_list.alloc)
212         {
213                 /* No space in current array, make it larger */
214                 cmdline_list.alloc += LOADORDER_ALLOC_CLUSTER;
215                 cmdline_list.order = HeapReAlloc(GetProcessHeap(), 0, cmdline_list.order,
216                                           cmdline_list.alloc * sizeof(module_loadorder_t));
217                 if(!cmdline_list.order)
218                 {
219                         MESSAGE("Virtual memory exhausted\n");
220                         exit(1);
221                 }
222         }
223         memcpy(cmdline_list.order[i].loadorder, plo->loadorder, sizeof(plo->loadorder));
224         cmdline_list.order[i].modulename = HeapAlloc(GetProcessHeap(), 0, strlen(plo->modulename)+1);
225         strcpy( (char *)cmdline_list.order[i].modulename, plo->modulename );
226         cmdline_list.count++;
227         return TRUE;
228 }
229
230
231 /***************************************************************************
232  *      AddLoadOrderSet (internal, static)
233  *
234  * Adds a set of entries in the list of command-line overrides from the key parameter.
235  */
236 static BOOL AddLoadOrderSet(char *key, char *order)
237 {
238         module_loadorder_t ldo;
239         char *cptr;
240
241         /* Parse the loadorder before the rest because strtok is not reentrant */
242         if(!ParseLoadOrder(order, ldo.loadorder))
243                 return FALSE;
244
245         cptr = get_tok(key, ", \t");
246         while(cptr)
247         {
248                 char *ext = strrchr(cptr, '.');
249                 if(ext)
250                 {
251                         if(strlen(ext) == 4 &&
252                            (!FILE_strcasecmp(ext, ".dll") || !FILE_strcasecmp(ext, ".exe")))
253                                 MESSAGE("Warning: Loadorder override '%s' contains an extension and might not be found during lookup\n", cptr);
254                 }
255
256                 ldo.modulename = cptr;
257                 if(!AddLoadOrder(&ldo)) return FALSE;
258                 cptr = get_tok(NULL, ", \t");
259         }
260         return TRUE;
261 }
262
263
264 /***************************************************************************
265  *      MODULE_AddLoadOrderOption
266  *
267  * The commandline option is in the form:
268  * name[,name,...]=native[,b,...]
269  */
270 void MODULE_AddLoadOrderOption( const char *option )
271 {
272     char *value, *key = HeapAlloc(GetProcessHeap(), 0, strlen(option)+1);
273
274     strcpy( key, option );
275     if (!(value = strchr(key, '='))) goto error;
276     *value++ = '\0';
277
278     TRACE("Commandline override '%s' = '%s'\n", key, value);
279
280     if (!AddLoadOrderSet(key, value)) goto error;
281     HeapFree(GetProcessHeap(), 0, key);
282
283     /* sort the array for quick lookup */
284     qsort(cmdline_list.order, cmdline_list.count, sizeof(cmdline_list.order[0]), cmp_sort_func);
285     return;
286
287  error:
288     MESSAGE( "Syntax: -dll name[,name[,...]]={native|so|builtin}[,{n|s|b}[,...]]\n"
289              "    - 'name' is the name of any dll without extension\n"
290              "    - the order of loading (native, so and builtin) can be abbreviated\n"
291              "      with the first letter\n"
292              "    - the option can be specified multiple times\n"
293              "    Example:\n"
294              "    -dll comdlg32,commdlg=n -dll shell,shell32=b\n" );
295     ExitProcess(1);
296 }
297
298
299 /***************************************************************************
300  *      set_registry_keys
301  *
302  * Set individual registry keys for a multiple dll specification
303  * Helper for MODULE_InitLoadOrder().
304  */
305 inline static void set_registry_keys( HKEY hkey, char *module, const char *buffer )
306 {
307     static int warn;
308     char *p = get_tok( module, ", \t" );
309
310     TRACE( "converting \"%s\" = \"%s\"\n", module, buffer );
311
312     if (!warn)
313         MESSAGE( "Warning: setting multiple modules in a single DllOverrides entry is no longer\n"
314                  "recommended. It is suggested that you rewrite the configuration file entry:\n\n"
315                  "\"%s\" = \"%s\"\n\n"
316                  "into something like:\n\n", module, buffer );
317     while (p)
318     {
319         if (!warn) MESSAGE( "\"%s\" = \"%s\"\n", p, buffer );
320         /* only set it if not existing already */
321         if (RegQueryValueExA( hkey, p, 0, NULL, NULL, NULL ) == ERROR_FILE_NOT_FOUND)
322             RegSetValueExA( hkey, p, 0, REG_SZ, buffer, strlen(buffer)+1 );
323         p = get_tok( NULL, ", \t" );
324     }
325     if (!warn) MESSAGE( "\n" );
326     warn = 1;
327 }
328
329
330 /***************************************************************************
331  *      MODULE_InitLoadOrder
332  *
333  * Convert entries containing multiple dll names (old syntax) to the
334  * new one dll module per entry syntax
335  */
336 void MODULE_InitLoadOrder(void)
337 {
338     char module[80];
339     char buffer[1024];
340     char *p;
341     HKEY hkey;
342     DWORD index = 0;
343
344     if (RegOpenKeyA( HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\DllOverrides", &hkey ))
345         return;
346
347     for (;;)
348     {
349         DWORD type, count = sizeof(buffer), name_len = sizeof(module);
350
351         if (RegEnumValueA( hkey, index, module, &name_len, NULL, &type, buffer, &count )) break;
352         p = module;
353         while (isspace(*p)) p++;
354         p += strcspn( p, ", \t" );
355         while (isspace(*p)) p++;
356         if (*p)
357         {
358             RegDeleteValueA( hkey, module );
359             set_registry_keys( hkey, module, buffer );
360         }
361         else index++;
362     }
363     RegCloseKey( hkey );
364 }
365
366
367 /***************************************************************************
368  *      get_list_load_order
369  *
370  * Get the load order for a given module from the command-line or
371  * default lists.
372  */
373 static BOOL get_list_load_order( const char *module, const struct loadorder_list *list,
374                                  enum loadorder_type lo[] )
375 {
376     module_loadorder_t tmp, *res = NULL;
377
378     tmp.modulename = module;
379     /* some bsearch implementations (Solaris) are buggy when the number of items is 0 */
380     if (list->count && (res = bsearch(&tmp, list->order, list->count, sizeof(list->order[0]), cmp_sort_func)))
381         memcpy( lo, res->loadorder, sizeof(res->loadorder) );
382     return (res != NULL);
383 }
384
385
386 /***************************************************************************
387  *      get_app_load_order
388  *
389  * Get the load order for a given module from the app-specific DllOverrides list.
390  * Also look for default '*' key if no module key found.
391  */
392 static BOOL get_app_load_order( const char *module, enum loadorder_type lo[], BOOL *got_default )
393 {
394     HKEY hkey, appkey;
395     DWORD count, type, res;
396     char buffer[MAX_PATH+16], *appname, *p;
397
398     if (!GetModuleFileName16( GetCurrentTask(), buffer, MAX_PATH ) &&
399         !GetModuleFileNameA( 0, buffer, MAX_PATH ))
400     {
401         WARN( "could not get module file name loading %s\n", module );
402         return FALSE;
403     }
404     appname = buffer;
405     if ((p = strrchr( appname, '/' ))) appname = p + 1;
406     if ((p = strrchr( appname, '\\' ))) appname = p + 1;
407
408     TRACE( "searching '%s' in AppDefaults\\%s\\DllOverrides\n", module, appname );
409
410     if (RegOpenKeyA( HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\AppDefaults", &hkey ))
411         return FALSE;
412
413     /* open AppDefaults\\appname\\DllOverrides key */
414     strcat( appname, "\\DllOverrides" );
415     res = RegOpenKeyA( hkey, appname, &appkey );
416     RegCloseKey( hkey );
417     if (res) return FALSE;
418
419     count = sizeof(buffer);
420     if ((res = RegQueryValueExA( appkey, module, NULL, &type, buffer, &count )))
421     {
422         if (!(res = RegQueryValueExA( appkey, "*", NULL, &type, buffer, &count )))
423             *got_default = TRUE;
424     }
425     else TRACE( "got app loadorder '%s' for '%s'\n", buffer, module );
426     RegCloseKey( appkey );
427     if (res) return FALSE;
428     return ParseLoadOrder( buffer, lo );
429 }
430
431
432 /***************************************************************************
433  *      get_standard_load_order
434  *
435  * Get the load order for a given module from the main DllOverrides list
436  * Also look for default '*' key if no module key found.
437  */
438 static BOOL get_standard_load_order( const char *module, enum loadorder_type lo[],
439                                      BOOL *got_default )
440 {
441     HKEY hkey;
442     DWORD count, type, res;
443     char buffer[80];
444
445     if (RegOpenKeyA( HKEY_LOCAL_MACHINE, "Software\\Wine\\Wine\\Config\\DllOverrides", &hkey ))
446         return FALSE;
447
448     count = sizeof(buffer);
449     if ((res = RegQueryValueExA( hkey, module, NULL, &type, buffer, &count )))
450     {
451         if (!(res = RegQueryValueExA( hkey, "*", NULL, &type, buffer, &count )))
452             *got_default = TRUE;
453     }
454     else TRACE( "got standard loadorder '%s' for '%s'\n", buffer, module );
455     RegCloseKey( hkey );
456     if (res) return FALSE;
457     return ParseLoadOrder( buffer, lo );
458 }
459
460
461 /***************************************************************************
462  *      get_default_load_order
463  *
464  * Get the default load order if nothing specified for a given dll.
465  */
466 static void get_default_load_order( enum loadorder_type lo[] )
467 {
468     DWORD res;
469     static enum loadorder_type default_loadorder[LOADORDER_NTYPES];
470     static int loaded;
471
472     if (!loaded)
473     {
474         char buffer[80];
475         HKEY hkey;
476
477         if (!(res = RegOpenKeyA( HKEY_LOCAL_MACHINE,
478                                  "Software\\Wine\\Wine\\Config\\DllDefaults", &hkey )))
479         {
480             DWORD type, count = sizeof(buffer);
481
482             res = RegQueryValueExA( hkey, "DefaultLoadOrder", NULL, &type, buffer, &count );
483             RegCloseKey( hkey );
484         }
485         if (res) strcpy( buffer, "n,b,s" );
486         ParseLoadOrder( buffer, default_loadorder );
487         loaded = 1;
488         TRACE( "got default loadorder '%s'\n", buffer );
489     }
490     memcpy( lo, default_loadorder, sizeof(default_loadorder) );
491 }
492
493
494 /***************************************************************************
495  *      MODULE_GetLoadOrder     (internal)
496  *
497  * Locate the loadorder of a module.
498  * Any path is stripped from the path-argument and so are the extension
499  * '.dll' and '.exe'. A lookup in the table can yield an override for
500  * the specific dll. Otherwise the default load order is returned.
501  */
502 void MODULE_GetLoadOrder( enum loadorder_type loadorder[], const char *path, BOOL win32 )
503 {
504         char fname[256];
505         char sysdir[MAX_PATH+1];
506         char *cptr;
507         char *name;
508         int len;
509         BOOL got_app_default = FALSE, got_std_default = FALSE;
510         enum loadorder_type lo_default[LOADORDER_NTYPES];
511
512         TRACE("looking for %s\n", path);
513
514         if ( ! GetSystemDirectoryA ( sysdir, MAX_PATH ) ) goto done;
515
516         /* Strip path information for 16 bit modules or if the module 
517            resides in the system directory */
518         if ( !win32 || !FILE_strncasecmp ( sysdir, path, strlen (sysdir) ) )
519         {
520         
521             cptr = strrchr(path, '\\');
522             if(!cptr)
523                 name = strrchr(path, '/');
524             else
525                 name = strrchr(cptr, '/');
526             
527             if(!name)
528                 name = cptr ? cptr+1 : (char *)path;
529             else
530                 name++;
531             
532             if((cptr = strchr(name, ':')) != NULL)      /* Also strip drive if in format 'C:MODULE.DLL' */
533                 name = cptr+1;
534         }
535         else 
536           name = (char *)path;
537     
538         len = strlen(name);
539         if(len >= sizeof(fname) || len <= 0)
540         {
541             WARN("Path '%s' -> '%s' reduces to zilch or just too large...\n", path, name);
542             goto done;
543         }
544
545         strcpy(fname, name);
546         if(len >= 4 && (!FILE_strcasecmp(fname+len-4, ".dll") || !FILE_strcasecmp(fname+len-4, ".exe")))
547                 fname[len-4] = '\0';
548
549         /* check command-line first */
550         if (get_list_load_order( fname, &cmdline_list, loadorder )) return;
551
552         /* then app-specific config */
553         if (get_app_load_order( fname, loadorder, &got_app_default ))
554         {
555             if (!got_app_default) return;
556             /* save the default value for later on */
557             memcpy( lo_default, loadorder, sizeof(lo_default) );
558         }
559
560         /* then standard config */
561         if (get_standard_load_order( fname, loadorder, &got_std_default ))
562         {
563             if (!got_std_default) return;
564             /* save the default value for later on */
565             if (!got_app_default) memcpy( lo_default, loadorder, sizeof(lo_default) );
566         }
567
568         /* then compiled-in defaults */
569         if (get_list_load_order( fname, &default_list, loadorder )) return;
570
571  done:
572         /* last, return the default */
573         if (got_app_default || got_std_default)
574             memcpy( loadorder, lo_default, sizeof(lo_default) );
575         else
576             get_default_load_order( loadorder );
577 }