If using the default values, also set dwType to REG_SZ as our default
[wine] / dlls / ntdll / loadorder.c
1 /*
2  * Dlls load order support
3  *
4  * Copyright 1999 Bertho Stultiens
5  * Copyright 2003 Alexandre Julliard
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <stdarg.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <assert.h>
29
30 #include "windef.h"
31 #include "winbase.h"
32 #include "winerror.h"
33 #include "winreg.h"
34 #include "winternl.h"
35 #include "ntdll_misc.h"
36 #include "module.h"
37
38 #include "wine/debug.h"
39 #include "wine/unicode.h"
40
41 WINE_DEFAULT_DEBUG_CHANNEL(module);
42
43 #define LOADORDER_ALLOC_CLUSTER 32      /* Allocate with 32 entries at a time */
44
45 typedef struct module_loadorder
46 {
47     const WCHAR        *modulename;
48     enum loadorder_type loadorder[LOADORDER_NTYPES];
49 } module_loadorder_t;
50
51 struct loadorder_list
52 {
53     int                 count;
54     int                 alloc;
55     module_loadorder_t *order;
56 };
57
58 /* dll to load as builtins if not explicitly specified otherwise */
59 /* the list must remain sorted by dll name */
60 static const WCHAR default_builtins[][16] =
61 {
62     { 'g','d','i','3','2',0 },
63     { 'i','c','m','p',0 },
64     { 'k','e','r','n','e','l','3','2',0 },
65     { 'm','m','s','y','s','t','e','m',0 },
66     { 'n','t','d','l','l',0 },
67     { 'o','d','b','c','3','2',0 },
68     { 's','o','u','n','d',0 },
69     { 't','t','y','d','r','v',0 },
70     { 'u','s','e','r','3','2',0 },
71     { 'w','3','2','s','k','r','n','l',0 },
72     { 'w','3','2','s','y','s',0 },
73     { 'w','i','n','3','2','s','1','6',0 },
74     { 'w','i','n','a','s','p','i',0 },
75     { 'w','i','n','e','d','o','s',0 },
76     { 'w','i','n','e','p','s','1','6','.','d','r','v',0 },
77     { 'w','i','n','e','p','s',0 },
78     { 'w','i','n','m','m',0 },
79     { 'w','i','n','s','o','c','k',0 },
80     { 'w','n','a','s','p','i','3','2',0 },
81     { 'w','o','w','3','2',0 },
82     { 'w','s','2','_','3','2',0 },
83     { 'w','s','o','c','k','3','2',0 },
84     { 'x','1','1','d','r','v',0 }
85 };
86
87 /* default if nothing else specified */
88 static const enum loadorder_type default_loadorder[LOADORDER_NTYPES] =
89 {
90     LOADORDER_BI, LOADORDER_DLL, 0
91 };
92
93 /* default for modules with an explicit path */
94 static const enum loadorder_type default_path_loadorder[LOADORDER_NTYPES] =
95 {
96     LOADORDER_DLL, LOADORDER_BI, 0
97 };
98
99 static const WCHAR separatorsW[] = {',',' ','\t',0};
100
101 static int init_done;
102 static struct loadorder_list env_list;
103
104
105 /***************************************************************************
106  *      cmp_sort_func   (internal, static)
107  *
108  * Sorting and comparing function used in sort and search of loadorder
109  * entries.
110  */
111 static int cmp_sort_func(const void *s1, const void *s2)
112 {
113     return strcmpiW(((module_loadorder_t *)s1)->modulename, ((module_loadorder_t *)s2)->modulename);
114 }
115
116
117 /***************************************************************************
118  *      strcmp_func
119  */
120 static int strcmp_func(const void *s1, const void *s2)
121 {
122     return strcmpiW( (WCHAR *)s1, (WCHAR *)s2 );
123 }
124
125
126 /***************************************************************************
127  *      get_basename
128  *
129  * Return the base name of a file name (i.e. remove the path components).
130  */
131 static const WCHAR *get_basename( const WCHAR *name )
132 {
133     const WCHAR *ptr;
134
135     if (name[0] && name[1] == ':') name += 2;  /* strip drive specification */
136     if ((ptr = strrchrW( name, '\\' ))) name = ptr + 1;
137     if ((ptr = strrchrW( name, '/' ))) name = ptr + 1;
138     return name;
139 }
140
141 /***************************************************************************
142  *      remove_dll_ext
143  *
144  * Remove extension if it is ".dll".
145  */
146 static inline void remove_dll_ext( WCHAR *ext )
147 {
148     if (ext[0] == '.' &&
149         toupperW(ext[1]) == 'D' &&
150         toupperW(ext[2]) == 'L' &&
151         toupperW(ext[3]) == 'L' &&
152         !ext[4]) ext[0] = 0;
153 }
154
155
156 /***************************************************************************
157  *      debugstr_loadorder
158  *
159  * Return a loadorder in printable form.
160  */
161 static const char *debugstr_loadorder( enum loadorder_type lo[] )
162 {
163     int i;
164     char buffer[LOADORDER_NTYPES*3+1];
165
166     buffer[0] = 0;
167     for(i = 0; i < LOADORDER_NTYPES; i++)
168     {
169         if (lo[i] == LOADORDER_INVALID) break;
170         switch(lo[i])
171         {
172         case LOADORDER_DLL: strcat( buffer, "n," ); break;
173         case LOADORDER_BI:  strcat( buffer, "b," ); break;
174         default:            strcat( buffer, "?," ); break;
175         }
176     }
177     if (buffer[0]) buffer[strlen(buffer)-1] = 0;
178     return debugstr_a(buffer);
179 }
180
181
182 /***************************************************************************
183  *      append_load_order
184  *
185  * Append a load order to the list if necessary.
186  */
187 static void append_load_order(enum loadorder_type lo[], enum loadorder_type append)
188 {
189     int i;
190
191     for (i = 0; i < LOADORDER_NTYPES; i++)
192     {
193         if (lo[i] == LOADORDER_INVALID)  /* append it here */
194         {
195             lo[i++] = append;
196             lo[i] = LOADORDER_INVALID;
197             return;
198         }
199         if (lo[i] == append) return;  /* already in the list */
200     }
201     assert(0);  /* cannot get here */
202 }
203
204
205 /***************************************************************************
206  *      parse_load_order
207  *
208  * Parses the loadorder options from the configuration and puts it into
209  * a structure.
210  */
211 static void parse_load_order( const WCHAR *order, enum loadorder_type lo[] )
212 {
213     lo[0] = LOADORDER_INVALID;
214     while (*order)
215     {
216         order += strspnW( order, separatorsW );
217         switch(*order)
218         {
219         case 'N':       /* Native */
220         case 'n':
221             append_load_order( lo, LOADORDER_DLL );
222             break;
223         case 'B':       /* Builtin */
224         case 'b':
225             append_load_order( lo, LOADORDER_BI );
226             break;
227         }
228         order += strcspnW( order, separatorsW );
229     }
230 }
231
232
233 /***************************************************************************
234  *      add_load_order
235  *
236  * Adds an entry in the list of environment overrides.
237  */
238 static void add_load_order( const module_loadorder_t *plo )
239 {
240     int i;
241
242     for(i = 0; i < env_list.count; i++)
243     {
244         if(!cmp_sort_func(plo, &env_list.order[i] ))
245         {
246             /* replace existing option */
247             memcpy( env_list.order[i].loadorder, plo->loadorder, sizeof(plo->loadorder));
248             return;
249         }
250     }
251
252     if (i >= env_list.alloc)
253     {
254         /* No space in current array, make it larger */
255         env_list.alloc += LOADORDER_ALLOC_CLUSTER;
256         if (env_list.order)
257             env_list.order = RtlReAllocateHeap(GetProcessHeap(), 0, env_list.order,
258                                                env_list.alloc * sizeof(module_loadorder_t));
259         else
260             env_list.order = RtlAllocateHeap(GetProcessHeap(), 0,
261                                              env_list.alloc * sizeof(module_loadorder_t));
262         if(!env_list.order)
263         {
264             MESSAGE("Virtual memory exhausted\n");
265             exit(1);
266         }
267     }
268     memcpy(env_list.order[i].loadorder, plo->loadorder, sizeof(plo->loadorder));
269     env_list.order[i].modulename = plo->modulename;
270     env_list.count++;
271 }
272
273
274 /***************************************************************************
275  *      add_load_order_set
276  *
277  * Adds a set of entries in the list of command-line overrides from the key parameter.
278  */
279 static void add_load_order_set( WCHAR *entry )
280 {
281     module_loadorder_t ldo;
282     WCHAR *end = strchrW( entry, '=' );
283
284     if (!end) return;
285     *end++ = 0;
286     parse_load_order( end, ldo.loadorder );
287
288     while (*entry)
289     {
290         entry += strspnW( entry, separatorsW );
291         end = entry + strcspnW( entry, separatorsW );
292         if (*end) *end++ = 0;
293         if (*entry)
294         {
295             WCHAR *ext = strrchrW(entry, '.');
296             if (ext) remove_dll_ext( ext );
297             ldo.modulename = entry;
298             add_load_order( &ldo );
299             entry = end;
300         }
301     }
302 }
303
304
305 /***************************************************************************
306  *      init_load_order
307  */
308 static void init_load_order(void)
309 {
310     const char *order = getenv( "WINEDLLOVERRIDES" );
311     UNICODE_STRING strW;
312     WCHAR *entry, *next;
313
314     init_done = 1;
315     if (!order) return;
316
317     if (!strcmp( order, "help" ))
318     {
319         MESSAGE( "Syntax:\n"
320                  "  WINEDLLOVERRIDES=\"entry;entry;entry...\"\n"
321                  "    where each entry is of the form:\n"
322                  "        module[,module...]={native|builtin}[,{b|n}]\n"
323                  "\n"
324                  "    Only the first letter of the override (native or builtin)\n"
325                  "    is significant.\n\n"
326                  "Example:\n"
327                  "  WINEDLLOVERRIDES=\"comdlg32,commdlg=n,b;shell,shell32=b\"\n" );
328         exit(0);
329     }
330
331     RtlCreateUnicodeStringFromAsciiz( &strW, order );
332     entry = strW.Buffer;
333     while (*entry)
334     {
335         while (*entry && *entry == ';') entry++;
336         if (!*entry) break;
337         next = strchrW( entry, ';' );
338         if (next) *next++ = 0;
339         else next = entry + strlenW(entry);
340         add_load_order_set( entry );
341         entry = next;
342     }
343
344     /* sort the array for quick lookup */
345     if (env_list.count)
346         qsort(env_list.order, env_list.count, sizeof(env_list.order[0]), cmp_sort_func);
347
348     /* Note: we don't free the Unicode string because the
349      * stored module names point inside it */
350 }
351
352
353 /***************************************************************************
354  *      get_env_load_order
355  *
356  * Get the load order for a given module from the WINEDLLOVERRIDES environment variable.
357  */
358 static inline BOOL get_env_load_order( const WCHAR *module, enum loadorder_type lo[] )
359 {
360     module_loadorder_t tmp, *res = NULL;
361
362     tmp.modulename = module;
363     /* some bsearch implementations (Solaris) are buggy when the number of items is 0 */
364     if (env_list.count &&
365         (res = bsearch(&tmp, env_list.order, env_list.count, sizeof(env_list.order[0]), cmp_sort_func)))
366         memcpy( lo, res->loadorder, sizeof(res->loadorder) );
367     return (res != NULL);
368 }
369
370
371 /***************************************************************************
372  *      get_default_load_order
373  *
374  * Get the load order for a given module from the default list.
375  */
376 static inline BOOL get_default_load_order( const WCHAR *module, enum loadorder_type lo[] )
377 {
378     const int count = sizeof(default_builtins) / sizeof(default_builtins[0]);
379     if (!bsearch( module, default_builtins, count, sizeof(default_builtins[0]), strcmp_func ))
380         return FALSE;
381     lo[0] = LOADORDER_BI;
382     lo[1] = LOADORDER_INVALID;
383     return TRUE;
384 }
385
386
387 /***************************************************************************
388  *      open_app_key
389  *
390  * Open the registry key to the app-specific DllOverrides list.
391  */
392 static HKEY open_app_key( const WCHAR *app_name, const WCHAR *module )
393 {
394     OBJECT_ATTRIBUTES attr;
395     UNICODE_STRING nameW;
396     HKEY hkey;
397     WCHAR *str;
398     static const WCHAR AppDefaultsW[] = {'M','a','c','h','i','n','e','\\',
399                                          'S','o','f','t','w','a','r','e','\\',
400                                          'W','i','n','e','\\',
401                                          'W','i','n','e','\\',
402                                          'C','o','n','f','i','g','\\',
403                                          'A','p','p','D','e','f','a','u','l','t','s','\\',0};
404     static const WCHAR DllOverridesW[] = {'\\','D','l','l','O','v','e','r','r','i','d','e','s',0};
405
406     str = RtlAllocateHeap( GetProcessHeap(), 0,
407                            sizeof(AppDefaultsW) + sizeof(DllOverridesW) +
408                            strlenW(app_name) * sizeof(WCHAR) );
409     if (!str) return 0;
410     strcpyW( str, AppDefaultsW );
411     strcatW( str, app_name );
412     strcatW( str, DllOverridesW );
413
414     TRACE( "searching %s in %s\n", debugstr_w(module), debugstr_w(str) );
415
416     attr.Length = sizeof(attr);
417     attr.RootDirectory = 0;
418     attr.ObjectName = &nameW;
419     attr.Attributes = 0;
420     attr.SecurityDescriptor = NULL;
421     attr.SecurityQualityOfService = NULL;
422     RtlInitUnicodeString( &nameW, str );
423
424     if (NtOpenKey( &hkey, KEY_ALL_ACCESS, &attr )) hkey = 0;
425     RtlFreeHeap( GetProcessHeap(), 0, str );
426     return hkey;
427 }
428
429
430 /***************************************************************************
431  *      get_registry_value
432  *
433  * Load the registry loadorder value for a given module.
434  */
435 static BOOL get_registry_value( HKEY hkey, const WCHAR *module, enum loadorder_type lo[] )
436 {
437     UNICODE_STRING valueW;
438     char buffer[80];
439     DWORD count;
440     BOOL ret;
441
442     RtlInitUnicodeString( &valueW, module );
443
444     if ((ret = !NtQueryValueKey( hkey, &valueW, KeyValuePartialInformation,
445                                  buffer, sizeof(buffer), &count )))
446     {
447         int i, n = 0;
448         WCHAR *str = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)buffer)->Data;
449
450         while (*str)
451         {
452             enum loadorder_type type = LOADORDER_INVALID;
453
454             while (*str == ',' || isspaceW(*str)) str++;
455             if (!*str) break;
456
457             switch(tolowerW(*str))
458             {
459             case 'n': type = LOADORDER_DLL; break;
460             case 'b': type = LOADORDER_BI; break;
461             case 's': break;  /* no longer supported, ignore */
462             case 0:   break;  /* end of string */
463             default:
464                 ERR("Invalid load order module-type %s, ignored\n", debugstr_w(str));
465                 break;
466             }
467             if (type != LOADORDER_INVALID)
468             {
469                 for (i = 0; i < n; i++) if (lo[i] == type) break;  /* already specified */
470                 if (i == n) lo[n++] = type;
471             }
472             while (*str && *str != ',' && !isspaceW(*str)) str++;
473         }
474         lo[n] = LOADORDER_INVALID;
475     }
476     return ret;
477 }
478
479
480 /***************************************************************************
481  *      MODULE_GetSystemDirectory
482  *
483  * Retrieve the system directory. The string must be freed by the caller.
484  */
485 BOOL MODULE_GetSystemDirectory( UNICODE_STRING *sysdir )
486 {
487     static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
488     UNICODE_STRING name;
489
490     RtlInitUnicodeString( &name, winsysdirW );
491     sysdir->MaximumLength = 0;
492     if (RtlQueryEnvironmentVariable_U( NULL, &name, sysdir ) != STATUS_BUFFER_TOO_SMALL)
493         return FALSE;
494     sysdir->MaximumLength = sysdir->Length + sizeof(WCHAR);
495     if (!(sysdir->Buffer = RtlAllocateHeap( GetProcessHeap(), 0, sysdir->MaximumLength )))
496         return FALSE;
497     if (RtlQueryEnvironmentVariable_U( NULL, &name, sysdir ) == STATUS_SUCCESS)
498         return TRUE;
499     RtlFreeUnicodeString( sysdir );
500     return FALSE;
501 }
502
503
504 /***************************************************************************
505  *      MODULE_GetLoadOrderW    (internal)
506  *
507  * Locate the loadorder of a module.
508  * Any path is stripped from the path-argument and so are the extension
509  * '.dll' and '.exe'. A lookup in the table can yield an override for
510  * the specific dll. Otherwise the default load order is returned.
511  */
512 void MODULE_GetLoadOrderW( enum loadorder_type loadorder[], const WCHAR *app_name,
513                           const WCHAR *path, BOOL win32 )
514 {
515     static const WCHAR DllOverridesW[] = {'M','a','c','h','i','n','e','\\',
516                                           'S','o','f','t','w','a','r','e','\\',
517                                           'W','i','n','e','\\',
518                                           'W','i','n','e','\\',
519                                           'C','o','n','f','i','g','\\',
520                                           'D','l','l','O','v','e','r','r','i','d','e','s',0};
521
522     static HKEY std_key = (HKEY)-1;  /* key to standard section, cached */
523     HKEY app_key = 0;
524     WCHAR *module, *basename;
525     int len;
526
527     if (!init_done) init_load_order();
528
529     TRACE("looking for %s\n", debugstr_w(path));
530
531     loadorder[0] = LOADORDER_INVALID;  /* in case something bad happens below */
532
533     /* Strip path information if the module resides in the system directory
534      * (path is already stripped by caller for 16-bit modules)
535      */
536     if (win32)
537     {
538         UNICODE_STRING path_str, sysdir;
539
540         if (!MODULE_GetSystemDirectory( &sysdir )) return;
541         RtlInitUnicodeString( &path_str, path );
542         if (RtlPrefixUnicodeString( &sysdir, &path_str, TRUE ))
543         {
544             const WCHAR *p = path + sysdir.Length / sizeof(WCHAR);
545             while (*p == '\\' || *p == '/') p++;
546             if (!strchrW( p, '\\' ) && !strchrW( p, '/' )) path = p;
547         }
548         RtlFreeUnicodeString( &sysdir );
549     }
550
551     if (!(len = strlenW(path))) return;
552     if (!(module = RtlAllocateHeap( GetProcessHeap(), 0, (len + 2) * sizeof(WCHAR) ))) return;
553     strcpyW( module+1, path );  /* reserve module[0] for the wildcard char */
554
555     if (len >= 4) remove_dll_ext( module + 1 + len - 4 );
556
557     /* check environment variable first */
558     if (get_env_load_order( module+1, loadorder ))
559     {
560         TRACE( "got environment %s for %s\n",
561                debugstr_loadorder(loadorder), debugstr_w(path) );
562         goto done;
563     }
564
565     /* then explicit module name in AppDefaults */
566     if (app_name)
567     {
568         app_key = open_app_key( app_name, module+1 );
569         if (app_key && get_registry_value( app_key, module+1, loadorder ))
570         {
571             TRACE( "got app defaults %s for %s\n",
572                    debugstr_loadorder(loadorder), debugstr_w(path) );
573             goto done;
574         }
575     }
576
577     /* then explicit module name in standard section */
578     if (std_key == (HKEY)-1)
579     {
580         OBJECT_ATTRIBUTES attr;
581         UNICODE_STRING nameW;
582
583         attr.Length = sizeof(attr);
584         attr.RootDirectory = 0;
585         attr.ObjectName = &nameW;
586         attr.Attributes = 0;
587         attr.SecurityDescriptor = NULL;
588         attr.SecurityQualityOfService = NULL;
589         RtlInitUnicodeString( &nameW, DllOverridesW );
590
591         if (NtOpenKey( &std_key, KEY_ALL_ACCESS, &attr )) std_key = 0;
592     }
593
594     if (std_key && get_registry_value( std_key, module+1, loadorder ))
595     {
596         TRACE( "got standard entry %s for %s\n",
597                debugstr_loadorder(loadorder), debugstr_w(path) );
598         goto done;
599     }
600
601     /* then module basename preceded by '*' in AppDefaults */
602     basename = (WCHAR *)get_basename( module+1 );
603     basename[-1] = '*';
604     if (app_key && get_registry_value( app_key, basename-1, loadorder ))
605     {
606         TRACE( "got app defaults basename %s for %s\n",
607                debugstr_loadorder(loadorder), debugstr_w(path) );
608         goto done;
609     }
610
611     /* then module name preceded by '*' in standard section */
612     if (std_key && get_registry_value( std_key, basename-1, loadorder ))
613     {
614         TRACE( "got standard base name %s for %s\n",
615                debugstr_loadorder(loadorder), debugstr_w(path) );
616         goto done;
617     }
618
619     /* then base name matching compiled-in defaults */
620     if (get_default_load_order( basename, loadorder ))
621     {
622         TRACE( "got compiled-in default %s for %s\n",
623                debugstr_loadorder(loadorder), debugstr_w(path) );
624         goto done;
625     }
626
627     if (basename == module+1)
628     {
629         static const WCHAR wildcardW[] = {'*',0};
630
631         /* then wildcard entry in AppDefaults (only if no explicit path) */
632         if (app_key && get_registry_value( app_key, wildcardW, loadorder ))
633         {
634             TRACE( "got app defaults wildcard %s for %s\n",
635                    debugstr_loadorder(loadorder), debugstr_w(path) );
636             goto done;
637         }
638
639         /* then wildcard entry in standard section (only if no explicit path) */
640         if (std_key && get_registry_value( std_key, wildcardW, loadorder ))
641         {
642             TRACE( "got standard wildcard %s for %s\n",
643                    debugstr_loadorder(loadorder), debugstr_w(path) );
644             goto done;
645         }
646
647         /* and last the hard-coded default */
648         memcpy( loadorder, default_loadorder, sizeof(default_loadorder) );
649         TRACE( "got hardcoded default %s for %s\n",
650                debugstr_loadorder(loadorder), debugstr_w(path) );
651     }
652     else  /* module contains an explicit path */
653     {
654         memcpy( loadorder, default_path_loadorder, sizeof(default_path_loadorder) );
655         TRACE( "got hardcoded path default %s for %s\n",
656                debugstr_loadorder(loadorder), debugstr_w(path) );
657     }
658
659  done:
660     if (app_key) NtClose( app_key );
661     RtlFreeHeap( GetProcessHeap(), 0, module );
662 }
663
664
665 /***************************************************************************
666  *      MODULE_GetLoadOrderA    (internal)
667  *
668  * Locate the loadorder of a module.
669  * Any path is stripped from the path-argument and so are the extension
670  * '.dll' and '.exe'. A lookup in the table can yield an override for
671  * the specific dll. Otherwise the default load order is returned.
672  *
673  * FIXME: should be removed, everything should be Unicode.
674  */
675 void MODULE_GetLoadOrderA( enum loadorder_type loadorder[], const WCHAR *app_name,
676                            const char *path, BOOL win32 )
677 {
678     UNICODE_STRING pathW;
679
680     RtlCreateUnicodeStringFromAsciiz( &pathW, path );
681     MODULE_GetLoadOrderW( loadorder, app_name, pathW.Buffer, win32 );
682     RtlFreeUnicodeString( &pathW );
683 }