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