Fixed buffer size in DIR_TryModulePath for Win32 modules.
[wine] / files / directory.c
1 /*
2  * DOS directories functions
3  *
4  * Copyright 1995 Alexandre Julliard
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 <ctype.h>
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <string.h>
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #ifdef HAVE_UNISTD_H
30 # include <unistd.h>
31 #endif
32 #include <errno.h>
33 #ifdef HAVE_SYS_ERRNO_H
34 #include <sys/errno.h>
35 #endif
36
37 #include "winbase.h"
38 #include "wine/winbase16.h"
39 #include "windef.h"
40 #include "wingdi.h"
41 #include "wine/winuser16.h"
42 #include "winerror.h"
43 #include "winreg.h"
44 #include "ntddk.h"
45 #include "wine/unicode.h"
46 #include "drive.h"
47 #include "file.h"
48 #include "heap.h"
49 #include "msdos.h"
50 #include "wine/debug.h"
51
52 WINE_DEFAULT_DEBUG_CHANNEL(dosfs);
53 WINE_DECLARE_DEBUG_CHANNEL(file);
54
55 static DOS_FULL_NAME DIR_Windows;
56 static DOS_FULL_NAME DIR_System;
57
58 static const WCHAR wineW[] = {'w','i','n','e',0};
59
60 /***********************************************************************
61  *           DIR_GetPath
62  *
63  * Get a path name from the wine.ini file and make sure it is valid.
64  */
65 static int DIR_GetPath( LPCWSTR keyname, LPCWSTR defval, DOS_FULL_NAME *full_name,
66                         LPWSTR longname, INT longname_len, BOOL warn )
67 {
68     WCHAR path[MAX_PATHNAME_LEN];
69     BY_HANDLE_FILE_INFORMATION info;
70     const char *mess = "does not exist";
71
72     PROFILE_GetWineIniString( wineW, keyname, defval, path, MAX_PATHNAME_LEN );
73
74     if (!DOSFS_GetFullName( path, TRUE, full_name ) ||
75         (!FILE_Stat( full_name->long_name, &info ) && (mess=strerror(errno)))||
76         (!(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && (mess="not a directory")) ||
77         (!(GetLongPathNameW(full_name->short_name, longname, longname_len))) )
78     {
79         if (warn)
80             MESSAGE("Invalid path %s for %s directory: %s\n",
81                     debugstr_w(path), debugstr_w(keyname), mess);
82         return 0;
83     }
84     return 1;
85 }
86
87
88 /***********************************************************************
89  *           DIR_Init
90  */
91 int DIR_Init(void)
92 {
93     char path[MAX_PATHNAME_LEN];
94     WCHAR longpath[MAX_PATHNAME_LEN];
95     DOS_FULL_NAME tmp_dir, profile_dir;
96     int drive;
97     const char *cwd;
98     static const WCHAR windowsW[] = {'w','i','n','d','o','w','s',0};
99     static const WCHAR systemW[] = {'s','y','s','t','e','m',0};
100     static const WCHAR tempW[] = {'t','e','m','p',0};
101     static const WCHAR profileW[] = {'p','r','o','f','i','l','e',0};
102     static const WCHAR windows_dirW[] = {'c',':','\\','w','i','n','d','o','w','s',0};
103     static const WCHAR system_dirW[] = {'c',':','\\','w','i','n','d','o','w','s','\\','s','y','s','t','e','m',0};
104     static const WCHAR pathW[] = {'p','a','t','h',0};
105     static const WCHAR path_dirW[] = {'c',':','\\','w','i','n','d','o','w','s',';',
106                                       'c',':','\\','w','i','n','d','o','w','s','\\','s','y','s','t','e','m',0};
107     static const WCHAR path_capsW[] = {'P','A','T','H',0};
108     static const WCHAR temp_capsW[] = {'T','E','M','P',0};
109     static const WCHAR tmp_capsW[] = {'T','M','P',0};
110     static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
111     static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
112     static const WCHAR userprofileW[] = {'U','S','E','R','P','R','O','F','I','L','E',0};
113     static const WCHAR systemrootW[] = {'S','Y','S','T','E','M','R','O','O','T',0};
114     static const WCHAR empty_strW[] = { 0 };
115
116     if (!getcwd( path, MAX_PATHNAME_LEN ))
117     {
118         perror( "Could not get current directory" );
119         return 0;
120     }
121     cwd = path;
122     if ((drive = DRIVE_FindDriveRoot( &cwd )) == -1)
123     {
124         MESSAGE("Warning: could not find wine config [Drive x] entry "
125             "for current working directory %s; "
126             "starting in windows directory.\n", cwd );
127     }
128     else
129     {
130         WCHAR szdrive[3]={drive+'A',':',0};
131         MultiByteToWideChar(DRIVE_GetCodepage(drive), 0, cwd, -1, longpath, MAX_PATHNAME_LEN);
132         DRIVE_SetCurrentDrive( drive );
133         DRIVE_Chdir( drive, longpath );
134         if(GetDriveTypeW(szdrive)==DRIVE_CDROM)
135             chdir("/"); /* change to root directory so as not to lock cdroms */
136     }
137
138     if (!(DIR_GetPath( windowsW, windows_dirW, &DIR_Windows, longpath, MAX_PATHNAME_LEN, TRUE )) ||
139         !(DIR_GetPath( systemW, system_dirW, &DIR_System, longpath, MAX_PATHNAME_LEN, TRUE )) ||
140         !(DIR_GetPath( tempW, windows_dirW, &tmp_dir, longpath, MAX_PATHNAME_LEN, TRUE )))
141     {
142         PROFILE_UsageWineIni();
143         return 0;
144     }
145     if (-1 == access( tmp_dir.long_name, W_OK ))
146     {
147         if (errno==EACCES)
148         {
149                 MESSAGE("Warning: the temporary directory '%s' (specified in wine configuration file) is not writeable.\n", tmp_dir.long_name);
150                 PROFILE_UsageWineIni();
151         }
152         else
153                 MESSAGE("Warning: access to temporary directory '%s' failed (%s).\n",
154                     tmp_dir.long_name, strerror(errno));
155     }
156
157     if (drive == -1)
158     {
159         drive = DIR_Windows.drive;
160         DRIVE_SetCurrentDrive( drive );
161         DRIVE_Chdir( drive, DIR_Windows.short_name + 2 );
162     }
163
164     PROFILE_GetWineIniString(wineW, pathW, path_dirW, longpath, MAX_PATHNAME_LEN);
165     if (strchrW(longpath, '/'))
166     {
167         MESSAGE("Fix your wine config to use DOS drive syntax in [wine] 'Path=' statement! (no '/' allowed)\n");
168         PROFILE_UsageWineIni();
169         ExitProcess(1);
170     }
171
172     /* Set the environment variables */
173
174     SetEnvironmentVariableW( path_capsW, longpath );
175     SetEnvironmentVariableW( temp_capsW, tmp_dir.short_name );
176     SetEnvironmentVariableW( tmp_capsW, tmp_dir.short_name );
177     SetEnvironmentVariableW( windirW, DIR_Windows.short_name );
178     SetEnvironmentVariableW( winsysdirW, DIR_System.short_name );
179
180     /* set COMSPEC only if it doesn't exist already */
181     if (!GetEnvironmentVariableA( "COMSPEC", NULL, 0 ))
182         SetEnvironmentVariableA( "COMSPEC", "c:\\command.com" );
183
184     TRACE("WindowsDir = %s (%s)\n",
185           debugstr_w(DIR_Windows.short_name), DIR_Windows.long_name );
186     TRACE("SystemDir  = %s (%s)\n",
187           debugstr_w(DIR_System.short_name), DIR_System.long_name );
188     TRACE("TempDir    = %s (%s)\n",
189           debugstr_w(tmp_dir.short_name), tmp_dir.long_name );
190     TRACE("Path       = %s\n", debugstr_w(longpath) );
191     TRACE("Cwd        = %c:\\%s\n",
192           'A' + drive, debugstr_w(DRIVE_GetDosCwd(drive)) );
193
194     if (DIR_GetPath( profileW, empty_strW, &profile_dir, longpath, MAX_PATHNAME_LEN, FALSE ))
195     {
196         TRACE("USERPROFILE= %s\n", debugstr_w(longpath) );
197         SetEnvironmentVariableW( userprofileW, longpath );
198     }
199
200     TRACE("SYSTEMROOT = %s\n", debugstr_w(DIR_Windows.short_name) );
201     SetEnvironmentVariableW( systemrootW, DIR_Windows.short_name );
202
203     return 1;
204 }
205
206
207 /***********************************************************************
208  *           GetTempPathA   (KERNEL32.@)
209  */
210 UINT WINAPI GetTempPathA( UINT count, LPSTR path )
211 {
212     WCHAR pathW[MAX_PATH];
213     UINT ret;
214
215     ret = GetTempPathW(MAX_PATH, pathW);
216
217     if (!ret)
218         return 0;
219
220     if (ret > MAX_PATH)
221     {
222         SetLastError(ERROR_FILENAME_EXCED_RANGE);
223         return 0;
224     }
225
226     ret = WideCharToMultiByte(CP_ACP, 0, pathW, -1, NULL, 0, NULL, NULL);
227     if (ret <= count)
228     {
229         WideCharToMultiByte(CP_ACP, 0, pathW, -1, path, count, NULL, NULL);
230         ret--; /* length without 0 */
231     }
232     return ret;
233 }
234
235
236 /***********************************************************************
237  *           GetTempPathW   (KERNEL32.@)
238  */
239 UINT WINAPI GetTempPathW( UINT count, LPWSTR path )
240 {
241     static const WCHAR tmp[]  = { 'T', 'M', 'P', 0 };
242     static const WCHAR temp[] = { 'T', 'E', 'M', 'P', 0 };
243     WCHAR tmp_path[MAX_PATH];
244     UINT ret;
245
246     TRACE("%u,%p\n", count, path);
247
248     if (!(ret = GetEnvironmentVariableW( tmp, tmp_path, MAX_PATH )))
249         if (!(ret = GetEnvironmentVariableW( temp, tmp_path, MAX_PATH )))
250             if (!(ret = GetCurrentDirectoryW( MAX_PATH, tmp_path )))
251                 return 0;
252
253     if (ret > MAX_PATH)
254     {
255         SetLastError(ERROR_FILENAME_EXCED_RANGE);
256         return 0;
257     }
258
259     ret = GetFullPathNameW(tmp_path, MAX_PATH, tmp_path, NULL);
260     if (!ret) return 0;
261
262     if (ret > MAX_PATH - 2)
263     {
264         SetLastError(ERROR_FILENAME_EXCED_RANGE);
265         return 0;
266     }
267
268     if (tmp_path[ret-1] != '\\')
269     {
270         tmp_path[ret++] = '\\';
271         tmp_path[ret]   = '\0';
272     }
273
274     ret++; /* add space for terminating 0 */
275
276     if (count)
277     {
278         lstrcpynW(path, tmp_path, count);
279         if (count >= ret)
280             ret--; /* return length without 0 */
281         else if (count < 4)
282             path[0] = 0; /* avoid returning ambiguous "X:" */
283     }
284
285     TRACE("returning %u, %s\n", ret, debugstr_w(path));
286     return ret;
287 }
288
289
290 /***********************************************************************
291  *           DIR_GetWindowsUnixDir
292  */
293 UINT DIR_GetWindowsUnixDir( LPSTR path, UINT count )
294 {
295     if (path) lstrcpynA( path, DIR_Windows.long_name, count );
296     return strlen( DIR_Windows.long_name );
297 }
298
299
300 /***********************************************************************
301  *           DIR_GetSystemUnixDir
302  */
303 UINT DIR_GetSystemUnixDir( LPSTR path, UINT count )
304 {
305     if (path) lstrcpynA( path, DIR_System.long_name, count );
306     return strlen( DIR_System.long_name );
307 }
308
309
310 /***********************************************************************
311  *           GetTempDrive   (KERNEL.92)
312  * A closer look at krnl386.exe shows what the SDK doesn't mention:
313  *
314  * returns:
315  *   AL: driveletter
316  *   AH: ':'            - yes, some kernel code even does stosw with
317  *                            the returned AX.
318  *   DX: 1 for success
319  */
320 UINT WINAPI GetTempDrive( BYTE ignored )
321 {
322     char *buffer;
323     BYTE ret;
324     UINT len = GetTempPathA( 0, NULL );
325
326     if (!(buffer = HeapAlloc( GetProcessHeap(), 0, len + 1 )) )
327         ret = DRIVE_GetCurrentDrive() + 'A';
328     else
329     {
330         /* FIXME: apparently Windows does something with the ignored byte */
331         if (!GetTempPathA( len, buffer )) buffer[0] = 'C';
332         ret = toupper(buffer[0]);
333         HeapFree( GetProcessHeap(), 0, buffer );
334     }
335     return MAKELONG( ret | (':' << 8), 1 );
336 }
337
338
339 /***********************************************************************
340  *           GetWindowsDirectory   (KERNEL.134)
341  */
342 UINT16 WINAPI GetWindowsDirectory16( LPSTR path, UINT16 count )
343 {
344     return (UINT16)GetWindowsDirectoryA( path, count );
345 }
346
347
348 /***********************************************************************
349  *           GetWindowsDirectoryW   (KERNEL32.@)
350  *
351  * See comment for GetWindowsDirectoryA.
352  */
353 UINT WINAPI GetWindowsDirectoryW( LPWSTR path, UINT count )
354 {
355     UINT len = strlenW( DIR_Windows.short_name ) + 1;
356     if (path && count >= len)
357     {
358         strcpyW( path, DIR_Windows.short_name );
359         len--;
360     }
361     return len;
362 }
363
364
365 /***********************************************************************
366  *           GetWindowsDirectoryA   (KERNEL32.@)
367  *
368  * Return value:
369  * If buffer is large enough to hold full path and terminating '\0' character
370  * function copies path to buffer and returns length of the path without '\0'.
371  * Otherwise function returns required size including '\0' character and
372  * does not touch the buffer.
373  */
374 UINT WINAPI GetWindowsDirectoryA( LPSTR path, UINT count )
375 {
376     UINT len = WideCharToMultiByte( CP_ACP, 0, DIR_Windows.short_name, -1, NULL, 0, NULL, NULL );
377     if (path && count >= len)
378     {
379         WideCharToMultiByte( CP_ACP, 0, DIR_Windows.short_name, -1, path, count, NULL, NULL );
380         len--;
381     }
382     return len;
383 }
384
385
386 /***********************************************************************
387  *           GetSystemWindowsDirectoryA   (KERNEL32.@) W2K, TS4.0SP4
388  */
389 UINT WINAPI GetSystemWindowsDirectoryA( LPSTR path, UINT count )
390 {
391     return GetWindowsDirectoryA( path, count );
392 }
393
394
395 /***********************************************************************
396  *           GetSystemWindowsDirectoryW   (KERNEL32.@) W2K, TS4.0SP4
397  */
398 UINT WINAPI GetSystemWindowsDirectoryW( LPWSTR path, UINT count )
399 {
400     return GetWindowsDirectoryW( path, count );
401 }
402
403
404 /***********************************************************************
405  *           GetSystemDirectory   (KERNEL.135)
406  */
407 UINT16 WINAPI GetSystemDirectory16( LPSTR path, UINT16 count )
408 {
409     return (UINT16)GetSystemDirectoryA( path, count );
410 }
411
412
413 /***********************************************************************
414  *           GetSystemDirectoryW   (KERNEL32.@)
415  *
416  * See comment for GetWindowsDirectoryA.
417  */
418 UINT WINAPI GetSystemDirectoryW( LPWSTR path, UINT count )
419 {
420     UINT len = strlenW( DIR_System.short_name ) + 1;
421     if (path && count >= len)
422     {
423         strcpyW( path, DIR_System.short_name );
424         len--;
425     }
426     return len;
427 }
428
429
430 /***********************************************************************
431  *           GetSystemDirectoryA   (KERNEL32.@)
432  *
433  * See comment for GetWindowsDirectoryA.
434  */
435 UINT WINAPI GetSystemDirectoryA( LPSTR path, UINT count )
436 {
437     UINT len = WideCharToMultiByte( CP_ACP, 0, DIR_System.short_name, -1, NULL, 0, NULL, NULL );
438     if (path && count >= len)
439     {
440         WideCharToMultiByte( CP_ACP, 0, DIR_System.short_name, -1, path, count, NULL, NULL );
441         len--;
442     }
443     return len;
444 }
445
446
447 /***********************************************************************
448  *           CreateDirectory   (KERNEL.144)
449  */
450 BOOL16 WINAPI CreateDirectory16( LPCSTR path, LPVOID dummy )
451 {
452     TRACE_(file)("(%s,%p)\n", path, dummy );
453     return (BOOL16)CreateDirectoryA( path, NULL );
454 }
455
456
457 /***********************************************************************
458  *           CreateDirectoryW   (KERNEL32.@)
459  * RETURNS:
460  *      TRUE : success
461  *      FALSE : failure
462  *              ERROR_DISK_FULL:        on full disk
463  *              ERROR_ALREADY_EXISTS:   if directory name exists (even as file)
464  *              ERROR_ACCESS_DENIED:    on permission problems
465  *              ERROR_FILENAME_EXCED_RANGE: too long filename(s)
466  */
467 BOOL WINAPI CreateDirectoryW( LPCWSTR path,
468                                   LPSECURITY_ATTRIBUTES lpsecattribs )
469 {
470     DOS_FULL_NAME full_name;
471
472     if (!path || !*path)
473     {
474         SetLastError(ERROR_PATH_NOT_FOUND);
475         return FALSE;
476     }
477
478     TRACE_(file)("(%s,%p)\n", debugstr_w(path), lpsecattribs );
479
480     if (DOSFS_GetDevice( path ))
481     {
482         TRACE_(file)("cannot use device %s!\n", debugstr_w(path));
483         SetLastError( ERROR_ACCESS_DENIED );
484         return FALSE;
485     }
486     if (!DOSFS_GetFullName( path, FALSE, &full_name )) return 0;
487     if (mkdir( full_name.long_name, 0777 ) == -1) {
488         WARN_(file)("Error '%s' trying to create directory '%s'\n", strerror(errno), full_name.long_name);
489         /* the FILE_SetDosError() generated error codes don't match the
490          * CreateDirectory ones for some errnos */
491         switch (errno) {
492         case EEXIST:
493         {
494             if (!strcmp(DRIVE_GetRoot(full_name.drive), full_name.long_name))
495                 SetLastError(ERROR_ACCESS_DENIED);
496             else
497                 SetLastError(ERROR_ALREADY_EXISTS);
498             break;
499         }
500         case ENOSPC: SetLastError(ERROR_DISK_FULL); break;
501         default: FILE_SetDosError();break;
502         }
503         return FALSE;
504     }
505     return TRUE;
506 }
507
508
509 /***********************************************************************
510  *           CreateDirectoryA   (KERNEL32.@)
511  */
512 BOOL WINAPI CreateDirectoryA( LPCSTR path,
513                                   LPSECURITY_ATTRIBUTES lpsecattribs )
514 {
515     UNICODE_STRING pathW;
516     BOOL ret = FALSE;
517
518     if (!path || !*path)
519     {
520         SetLastError(ERROR_PATH_NOT_FOUND);
521         return FALSE;
522     }
523
524     if (RtlCreateUnicodeStringFromAsciiz(&pathW, path))
525     {
526         ret = CreateDirectoryW(pathW.Buffer, lpsecattribs);
527         RtlFreeUnicodeString(&pathW);
528     }
529     else
530         SetLastError(ERROR_NOT_ENOUGH_MEMORY);
531     return ret;
532 }
533
534
535 /***********************************************************************
536  *           CreateDirectoryExA   (KERNEL32.@)
537  */
538 BOOL WINAPI CreateDirectoryExA( LPCSTR template, LPCSTR path,
539                                     LPSECURITY_ATTRIBUTES lpsecattribs)
540 {
541     return CreateDirectoryA(path,lpsecattribs);
542 }
543
544
545 /***********************************************************************
546  *           CreateDirectoryExW   (KERNEL32.@)
547  */
548 BOOL WINAPI CreateDirectoryExW( LPCWSTR template, LPCWSTR path,
549                                     LPSECURITY_ATTRIBUTES lpsecattribs)
550 {
551     return CreateDirectoryW(path,lpsecattribs);
552 }
553
554
555 /***********************************************************************
556  *           RemoveDirectory   (KERNEL.145)
557  */
558 BOOL16 WINAPI RemoveDirectory16( LPCSTR path )
559 {
560     return (BOOL16)RemoveDirectoryA( path );
561 }
562
563
564 /***********************************************************************
565  *           RemoveDirectoryW   (KERNEL32.@)
566  */
567 BOOL WINAPI RemoveDirectoryW( LPCWSTR path )
568 {
569     DOS_FULL_NAME full_name;
570
571     if (!path)
572     {
573         SetLastError(ERROR_INVALID_PARAMETER);
574         return FALSE;
575     }
576
577     TRACE_(file)("%s\n", debugstr_w(path));
578
579     if (DOSFS_GetDevice( path ))
580     {
581         TRACE_(file)("cannot remove device %s!\n", debugstr_w(path));
582         SetLastError( ERROR_FILE_NOT_FOUND );
583         return FALSE;
584     }
585     if (!DOSFS_GetFullName( path, TRUE, &full_name )) return FALSE;
586     if (rmdir( full_name.long_name ) == -1)
587     {
588         FILE_SetDosError();
589         return FALSE;
590     }
591     return TRUE;
592 }
593
594
595 /***********************************************************************
596  *           RemoveDirectoryA   (KERNEL32.@)
597  */
598 BOOL WINAPI RemoveDirectoryA( LPCSTR path )
599 {
600     UNICODE_STRING pathW;
601     BOOL ret = FALSE;
602
603     if (!path)
604     {
605         SetLastError(ERROR_INVALID_PARAMETER);
606         return FALSE;
607     }
608
609     if (RtlCreateUnicodeStringFromAsciiz(&pathW, path))
610     {
611         ret = RemoveDirectoryW(pathW.Buffer);
612         RtlFreeUnicodeString(&pathW);
613     }
614     else
615         SetLastError(ERROR_NOT_ENOUGH_MEMORY);
616     return ret;
617 }
618
619
620 /***********************************************************************
621  *           DIR_TryPath
622  *
623  * Helper function for DIR_SearchPath.
624  */
625 static BOOL DIR_TryPath( const DOS_FULL_NAME *dir, LPCWSTR name,
626                            DOS_FULL_NAME *full_name )
627 {
628     LPSTR p_l = full_name->long_name + strlen(dir->long_name) + 1;
629     LPWSTR p_s = full_name->short_name + strlenW(dir->short_name) + 1;
630
631     if ((p_s >= full_name->short_name + sizeof(full_name->short_name)/sizeof(full_name->short_name[0]) - 14) ||
632         (p_l >= full_name->long_name + sizeof(full_name->long_name) - 1))
633     {
634         SetLastError( ERROR_PATH_NOT_FOUND );
635         return FALSE;
636     }
637     if (!DOSFS_FindUnixName( dir, name, p_l,
638                    sizeof(full_name->long_name) - (p_l - full_name->long_name),
639                    p_s, !(DRIVE_GetFlags(dir->drive) & DRIVE_CASE_SENSITIVE) ))
640         return FALSE;
641
642     full_name->drive = dir->drive;
643     strcpy( full_name->long_name, dir->long_name );
644     p_l[-1] = '/';
645     strcpyW( full_name->short_name, dir->short_name );
646     p_s[-1] = '\\';
647     return TRUE;
648 }
649
650 static BOOL DIR_SearchSemicolonedPaths(LPCWSTR name, DOS_FULL_NAME *full_name, LPWSTR pathlist)
651 {
652     LPWSTR next, buffer = NULL;
653     INT len = strlenW(name), newlen, currlen = 0;
654     BOOL ret = FALSE;
655
656     next = pathlist;
657     while (!ret && next)
658     {
659         static const WCHAR bkslashW[] = {'\\',0};
660         LPWSTR cur = next;
661         while (*cur == ';') cur++;
662         if (!*cur) break;
663         next = strchrW( cur, ';' );
664         if (next) *next++ = '\0';
665         newlen = strlenW(cur) + len + 2;
666
667         if (newlen > currlen)
668         {
669             if (!(buffer = HeapReAlloc( GetProcessHeap(), 0, buffer, newlen * sizeof(WCHAR))))
670                 goto done;
671             currlen = newlen;
672         }
673
674         strcpyW( buffer, cur );
675         strcatW( buffer, bkslashW );
676         strcatW( buffer, name );
677         ret = DOSFS_GetFullName( buffer, TRUE, full_name );
678     }
679 done:
680     HeapFree( GetProcessHeap(), 0, buffer );
681     return ret;
682 }
683
684
685 /***********************************************************************
686  *           DIR_TryEnvironmentPath
687  *
688  * Helper function for DIR_SearchPath.
689  * Search in the specified path, or in $PATH if NULL.
690  */
691 static BOOL DIR_TryEnvironmentPath( LPCWSTR name, DOS_FULL_NAME *full_name, LPCWSTR envpath )
692 {
693     LPWSTR path;
694     BOOL ret = FALSE;
695     DWORD size;
696     static const WCHAR pathW[] = {'P','A','T','H',0};
697
698     size = envpath ? strlenW(envpath)+1 : GetEnvironmentVariableW( pathW, NULL, 0 );
699     if (!size) return FALSE;
700     if (!(path = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return FALSE;
701     if (envpath) strcpyW( path, envpath );
702     else if (!GetEnvironmentVariableW( pathW, path, size )) goto done;
703
704     ret = DIR_SearchSemicolonedPaths(name, full_name, path);
705
706 done:
707     HeapFree( GetProcessHeap(), 0, path );
708     return ret;
709 }
710
711
712 /***********************************************************************
713  *           DIR_TryModulePath
714  *
715  * Helper function for DIR_SearchPath.
716  */
717 static BOOL DIR_TryModulePath( LPCWSTR name, DOS_FULL_NAME *full_name, BOOL win32 )
718 {
719     WCHAR bufferW[MAX_PATH];
720     LPWSTR p;
721
722     if (!win32)
723     {
724         char buffer[OFS_MAXPATHNAME];
725         if (!GetCurrentTask()) return FALSE;
726         if (!GetModuleFileName16( GetCurrentTask(), buffer, sizeof(buffer) ))
727             return FALSE;
728         MultiByteToWideChar(CP_ACP, 0, buffer, -1, bufferW, MAX_PATH);
729     } else {
730         if (!GetModuleFileNameW( 0, bufferW, MAX_PATH ) )
731             return FALSE;
732     }
733     if (!(p = strrchrW( bufferW, '\\' ))) return FALSE;
734     if (MAX_PATH - (++p - bufferW) <= strlenW(name)) return FALSE;
735     strcpyW( p, name );
736     return DOSFS_GetFullName( bufferW, TRUE, full_name );
737 }
738
739
740 /***********************************************************************
741  *           DIR_TryAppPath
742  *
743  * Helper function for DIR_SearchPath.
744  */
745 static BOOL DIR_TryAppPath( LPCWSTR name, DOS_FULL_NAME *full_name )
746 {
747     HKEY hkAppPaths = 0, hkApp = 0;
748     WCHAR lpAppName[MAX_PATHNAME_LEN], lpAppPaths[MAX_PATHNAME_LEN];
749     LPWSTR lpFileName;
750     BOOL res = FALSE;
751     DWORD type, count;
752     static const WCHAR PathW[] = {'P','a','t','h',0};
753
754     if (RegOpenKeyA(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\App Paths", &hkAppPaths) != ERROR_SUCCESS)
755         return FALSE;
756
757     if (!GetModuleFileNameW(0, lpAppName, MAX_PATHNAME_LEN))
758     {
759         WARN("huh, module not found ??\n");
760         goto end;
761     }
762     lpFileName = strrchrW(lpAppName, '\\');
763     if (!lpFileName)
764         goto end;
765     else lpFileName++; /* skip '\\' */
766     if (RegOpenKeyW(hkAppPaths, lpFileName, &hkApp) != ERROR_SUCCESS)
767         goto end;
768     count = sizeof(lpAppPaths);
769     if (RegQueryValueExW(hkApp, PathW, 0, &type, (LPBYTE)lpAppPaths, &count) != ERROR_SUCCESS)
770         goto end;
771     TRACE("successfully opened App Paths for %s\n", debugstr_w(lpFileName));
772
773     res = DIR_SearchSemicolonedPaths(name, full_name, lpAppPaths);
774 end:
775     if (hkApp)
776         RegCloseKey(hkApp);
777     if (hkAppPaths)
778         RegCloseKey(hkAppPaths);
779     return res;
780 }
781
782 /***********************************************************************
783  *           DIR_SearchPath
784  *
785  * Implementation of SearchPathA. 'win32' specifies whether the search
786  * order is Win16 (module path last) or Win32 (module path first).
787  *
788  * FIXME: should return long path names.
789  */
790 DWORD DIR_SearchPath( LPCWSTR path, LPCWSTR name, LPCWSTR ext,
791                       DOS_FULL_NAME *full_name, BOOL win32 )
792 {
793     LPCWSTR p;
794     LPWSTR tmp = NULL;
795     BOOL ret = TRUE;
796
797     /* First check the supplied parameters */
798
799     p = strrchrW( name, '.' );
800     if (p && !strchrW( p, '/' ) && !strchrW( p, '\\' ))
801         ext = NULL;  /* Ignore the specified extension */
802     if (FILE_contains_pathW (name))
803         path = NULL;  /* Ignore path if name already contains a path */
804     if (path && !*path) path = NULL;  /* Ignore empty path */
805
806     /* Allocate a buffer for the file name and extension */
807
808     if (ext)
809     {
810         DWORD len = strlenW(name) + strlenW(ext);
811         if (!(tmp = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
812         {
813             SetLastError( ERROR_OUTOFMEMORY );
814             return 0;
815         }
816         strcpyW( tmp, name );
817         strcatW( tmp, ext );
818         name = tmp;
819     }
820
821     /* If the name contains an explicit path, everything's easy */
822
823     if (FILE_contains_pathW(name))
824     {
825         ret = DOSFS_GetFullName( name, TRUE, full_name );
826         goto done;
827     }
828
829     /* Search in the specified path */
830
831     if (path)
832     {
833         ret = DIR_TryEnvironmentPath( name, full_name, path );
834         goto done;
835     }
836
837     /* Try the path of the current executable (for Win32 search order) */
838
839     if (win32 && DIR_TryModulePath( name, full_name, win32 )) goto done;
840
841     /* Try the current directory */
842
843     if (DOSFS_GetFullName( name, TRUE, full_name )) goto done;
844
845     /* Try the Windows system directory */
846
847     if (DIR_TryPath( &DIR_System, name, full_name ))
848         goto done;
849
850     /* Try the Windows directory */
851
852     if (DIR_TryPath( &DIR_Windows, name, full_name ))
853         goto done;
854
855     /* Try the path of the current executable (for Win16 search order) */
856
857     if (!win32 && DIR_TryModulePath( name, full_name, win32 )) goto done;
858
859     /* Try the "App Paths" entry if existing (undocumented ??) */
860     if (DIR_TryAppPath(name, full_name))
861         goto done;
862
863     /* Try all directories in path */
864
865     ret = DIR_TryEnvironmentPath( name, full_name, NULL );
866
867 done:
868     if (tmp) HeapFree( GetProcessHeap(), 0, tmp );
869     return ret;
870 }
871
872
873 /***********************************************************************
874  * SearchPathW [KERNEL32.@]
875  *
876  * Searches for a specified file in the search path.
877  *
878  * PARAMS
879  *    path      [I] Path to search
880  *    name      [I] Filename to search for.
881  *    ext       [I] File extension to append to file name. The first
882  *                  character must be a period. This parameter is
883  *                  specified only if the filename given does not
884  *                  contain an extension.
885  *    buflen    [I] size of buffer, in characters
886  *    buffer    [O] buffer for found filename
887  *    lastpart  [O] address of pointer to last used character in
888  *                  buffer (the final '\')
889  *
890  * RETURNS
891  *    Success: length of string copied into buffer, not including
892  *             terminating null character. If the filename found is
893  *             longer than the length of the buffer, the length of the
894  *             filename is returned.
895  *    Failure: Zero
896  *
897  * NOTES
898  *    If the file is not found, calls SetLastError(ERROR_FILE_NOT_FOUND)
899  *    (tested on NT 4.0)
900  */
901 DWORD WINAPI SearchPathW( LPCWSTR path, LPCWSTR name, LPCWSTR ext, DWORD buflen,
902                           LPWSTR buffer, LPWSTR *lastpart )
903 {
904     LPSTR res;
905     DOS_FULL_NAME full_name;
906
907     if (!DIR_SearchPath( path, name, ext, &full_name, TRUE ))
908     {
909         SetLastError(ERROR_FILE_NOT_FOUND);
910         return 0;
911     }
912
913 TRACE("found %s %s\n", full_name.long_name, debugstr_w(full_name.short_name));
914 TRACE("drive %c: root %s\n", 'A' + full_name.drive, DRIVE_GetRoot(full_name.drive));
915
916     lstrcpynW( buffer, full_name.short_name, buflen );
917     res = full_name.long_name +
918               strlen(DRIVE_GetRoot( full_name.drive ));
919     while (*res == '/') res++;
920     if (buflen)
921     {
922         LPWSTR p;
923         if (buflen > 3)
924         {
925             MultiByteToWideChar(DRIVE_GetCodepage(full_name.drive), 0,
926                                 res, -1, buffer + 3, buflen - 3);
927             buffer[buflen - 1] = 0;
928         }
929         for (p = buffer; *p; p++) if (*p == '/') *p = '\\';
930         if (lastpart) *lastpart = strrchrW( buffer, '\\' ) + 1;
931     }
932     TRACE("Returning %s\n", debugstr_w(buffer) );
933     return strlenW(buffer);
934 }
935
936
937 /***********************************************************************
938  *           SearchPathA   (KERNEL32.@)
939  */
940 DWORD WINAPI SearchPathA( LPCSTR path, LPCSTR name, LPCSTR ext,
941                           DWORD buflen, LPSTR buffer, LPSTR *lastpart )
942 {
943     UNICODE_STRING pathW, nameW, extW;
944     WCHAR bufferW[MAX_PATH];
945     DWORD ret, retW;
946
947     if (path) RtlCreateUnicodeStringFromAsciiz(&pathW, path);
948     else pathW.Buffer = NULL;
949     if (name) RtlCreateUnicodeStringFromAsciiz(&nameW, name);
950     else nameW.Buffer = NULL;
951     if (ext) RtlCreateUnicodeStringFromAsciiz(&extW, ext);
952     else extW.Buffer = NULL;
953
954     retW = SearchPathW(pathW.Buffer, nameW.Buffer, extW.Buffer, MAX_PATH, bufferW, NULL);
955
956     if (!retW)
957         ret = 0;
958     else if (retW > MAX_PATH)
959     {
960         SetLastError(ERROR_FILENAME_EXCED_RANGE);
961         ret = 0;
962     }
963     else
964     {
965         ret = WideCharToMultiByte(CP_ACP, 0, bufferW, -1, NULL, 0, NULL, NULL);
966         if (buflen >= ret)
967         {
968             WideCharToMultiByte(CP_ACP, 0, bufferW, -1, buffer, buflen, NULL, NULL);
969             ret--; /* length without 0 */
970             if (lastpart) *lastpart = strrchr(buffer, '\\') + 1;
971         }
972     }
973
974     RtlFreeUnicodeString(&pathW);
975     RtlFreeUnicodeString(&nameW);
976     RtlFreeUnicodeString(&extW);
977     return ret;
978 }
979
980
981 /***********************************************************************
982  *           search_alternate_path
983  *
984  *
985  * FIXME: should return long path names.?
986  */
987 static BOOL search_alternate_path(LPCWSTR dll_path, LPCWSTR name, LPCWSTR ext,
988                                   DOS_FULL_NAME *full_name)
989 {
990     LPCWSTR p;
991     LPWSTR tmp = NULL;
992     BOOL ret = TRUE;
993
994     /* First check the supplied parameters */
995
996     p = strrchrW( name, '.' );
997     if (p && !strchrW( p, '/' ) && !strchrW( p, '\\' ))
998         ext = NULL;  /* Ignore the specified extension */
999
1000     /* Allocate a buffer for the file name and extension */
1001
1002     if (ext)
1003     {
1004         DWORD len = strlenW(name) + strlenW(ext);
1005         if (!(tmp = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1006         {
1007             SetLastError( ERROR_OUTOFMEMORY );
1008             return 0;
1009         }
1010         strcpyW( tmp, name );
1011         strcatW( tmp, ext );
1012         name = tmp;
1013     }
1014
1015     if (DIR_TryEnvironmentPath (name, full_name, dll_path))
1016         ;
1017     else if (DOSFS_GetFullName (name, TRUE, full_name)) /* current dir */
1018         ;
1019     else if (DIR_TryPath (&DIR_System, name, full_name)) /* System dir */
1020         ;
1021     else if (DIR_TryPath (&DIR_Windows, name, full_name)) /* Windows dir */
1022         ;
1023     else
1024         ret = DIR_TryEnvironmentPath( name, full_name, NULL );
1025
1026     if (tmp) HeapFree( GetProcessHeap(), 0, tmp );
1027     return ret;
1028 }
1029
1030
1031 /***********************************************************************
1032  * DIR_SearchAlternatePath
1033  *
1034  * Searches for a specified file in the search path.
1035  *
1036  * PARAMS
1037  *    dll_path  [I] Path to search
1038  *    name      [I] Filename to search for.
1039  *    ext       [I] File extension to append to file name. The first
1040  *                  character must be a period. This parameter is
1041  *                  specified only if the filename given does not
1042  *                  contain an extension.
1043  *    buflen    [I] size of buffer, in characters
1044  *    buffer    [O] buffer for found filename
1045  *    lastpart  [O] address of pointer to last used character in
1046  *                  buffer (the final '\') (May be NULL)
1047  *
1048  * RETURNS
1049  *    Success: length of string copied into buffer, not including
1050  *             terminating null character. If the filename found is
1051  *             longer than the length of the buffer, the length of the
1052  *             filename is returned.
1053  *    Failure: Zero
1054  *
1055  * NOTES
1056  *    If the file is not found, calls SetLastError(ERROR_FILE_NOT_FOUND)
1057  *
1058  * FIXME: convert to unicode
1059  */
1060 DWORD DIR_SearchAlternatePath( LPCSTR dll_path, LPCSTR name, LPCSTR ext,
1061                                DWORD buflen, LPSTR buffer, LPSTR *lastpart )
1062 {
1063     LPSTR p;
1064     DOS_FULL_NAME full_name;
1065     DWORD ret = 0;
1066     UNICODE_STRING dll_pathW, nameW, extW;
1067
1068     if (dll_path) RtlCreateUnicodeStringFromAsciiz(&dll_pathW, dll_path);
1069     else dll_pathW.Buffer = NULL;
1070     if (name) RtlCreateUnicodeStringFromAsciiz(&nameW, name);
1071     else nameW.Buffer = NULL;
1072     if (ext) RtlCreateUnicodeStringFromAsciiz(&extW, ext);
1073     else extW.Buffer = NULL;
1074
1075     if (search_alternate_path( dll_pathW.Buffer, nameW.Buffer, extW.Buffer, &full_name))
1076     {
1077         ret = WideCharToMultiByte(CP_ACP, 0, full_name.short_name, -1, NULL, 0, NULL, NULL);
1078         if (buflen >= ret)
1079         {
1080             WideCharToMultiByte(CP_ACP, 0, full_name.short_name, -1, buffer, buflen, NULL, NULL);
1081             for (p = buffer; *p; p++) if (*p == '/') *p = '\\';
1082             if (lastpart) *lastpart = strrchr( buffer, '\\' ) + 1;
1083             ret--; /* length without 0 */
1084         }
1085     }
1086     else
1087         SetLastError(ERROR_FILE_NOT_FOUND);
1088
1089     RtlFreeUnicodeString(&dll_pathW);
1090     RtlFreeUnicodeString(&nameW);
1091     RtlFreeUnicodeString(&extW);
1092
1093     TRACE("Returning %ld\n", ret );
1094     return ret;
1095 }