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