Do not put the TEMP and TMP variables into the Unix environment, use
[wine.git] / files / directory.c
blobca5464f569440595facf231484729215c35a87b8
1 /*
2 * DOS directories functions
4 * Copyright 1995 Alexandre Julliard
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.
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.
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
21 #include "config.h"
23 #include <ctype.h>
24 #include <stdlib.h>
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <string.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #ifdef HAVE_UNISTD_H
31 # include <unistd.h>
32 #endif
33 #include <errno.h>
34 #ifdef HAVE_SYS_ERRNO_H
35 #include <sys/errno.h>
36 #endif
38 #include "ntstatus.h"
39 #include "windef.h"
40 #include "winbase.h"
41 #include "wine/winbase16.h"
42 #include "wingdi.h"
43 #include "wine/winuser16.h"
44 #include "winerror.h"
45 #include "winreg.h"
46 #include "winternl.h"
47 #include "wine/unicode.h"
48 #include "file.h"
49 #include "wine/debug.h"
51 WINE_DEFAULT_DEBUG_CHANNEL(dosfs);
52 WINE_DECLARE_DEBUG_CHANNEL(file);
54 static DOS_FULL_NAME DIR_Windows;
55 static DOS_FULL_NAME DIR_System;
57 /***********************************************************************
58 * FILE_contains_pathW
60 inline static int FILE_contains_pathW (LPCWSTR name)
62 return ((*name && (name[1] == ':')) ||
63 strchrW (name, '/') || strchrW (name, '\\'));
66 /***********************************************************************
67 * DIR_GetPath
69 * Get a path name from the wine.ini file and make sure it is valid.
71 static int DIR_GetPath( HKEY hkey, LPCWSTR keyname, LPCWSTR defval, DOS_FULL_NAME *full_name,
72 LPWSTR longname, INT longname_len, BOOL warn )
74 UNICODE_STRING nameW;
75 DWORD dummy;
76 WCHAR tmp[MAX_PATHNAME_LEN];
77 BY_HANDLE_FILE_INFORMATION info;
78 const WCHAR *path = defval;
79 const char *mess = "does not exist";
81 RtlInitUnicodeString( &nameW, keyname );
82 if (hkey && !NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation, tmp, sizeof(tmp), &dummy ))
83 path = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
85 if (!DOSFS_GetFullName( path, TRUE, full_name ) ||
86 (!FILE_Stat( full_name->long_name, &info, NULL ) && (mess=strerror(errno)))||
87 (!(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && (mess="not a directory")) ||
88 (!(GetLongPathNameW(full_name->short_name, longname, longname_len))) )
90 if (warn)
92 MESSAGE("Invalid path %s for %s directory: %s.\n",
93 debugstr_w(path), debugstr_w(keyname), mess);
94 MESSAGE("Perhaps you have not properly edited your Wine configuration file (%s/config)\n",
95 wine_get_config_dir());
97 return 0;
99 return 1;
103 /***********************************************************************
104 * DIR_Init
106 int DIR_Init(void)
108 OBJECT_ATTRIBUTES attr;
109 UNICODE_STRING nameW;
110 HKEY hkey;
111 char path[MAX_PATHNAME_LEN];
112 WCHAR longpath[MAX_PATHNAME_LEN];
113 DOS_FULL_NAME tmp_dir, profile_dir;
114 int drive;
115 const char *cwd;
116 static const WCHAR wineW[] = {'M','a','c','h','i','n','e','\\',
117 'S','o','f','t','w','a','r','e','\\',
118 'W','i','n','e','\\','W','i','n','e','\\',
119 'C','o','n','f','i','g','\\','W','i','n','e',0};
120 static const WCHAR windowsW[] = {'w','i','n','d','o','w','s',0};
121 static const WCHAR systemW[] = {'s','y','s','t','e','m',0};
122 static const WCHAR tempW[] = {'t','e','m','p',0};
123 static const WCHAR profileW[] = {'p','r','o','f','i','l','e',0};
124 static const WCHAR windows_dirW[] = {'c',':','\\','w','i','n','d','o','w','s',0};
125 static const WCHAR system_dirW[] = {'c',':','\\','w','i','n','d','o','w','s','\\','s','y','s','t','e','m',0};
126 static const WCHAR pathW[] = {'p','a','t','h',0};
127 static const WCHAR path_dirW[] = {'c',':','\\','w','i','n','d','o','w','s',';',
128 'c',':','\\','w','i','n','d','o','w','s','\\','s','y','s','t','e','m',0};
129 static const WCHAR path_capsW[] = {'P','A','T','H',0};
130 static const WCHAR temp_capsW[] = {'T','E','M','P',0};
131 static const WCHAR tmp_capsW[] = {'T','M','P',0};
132 static const WCHAR windirW[] = {'w','i','n','d','i','r',0};
133 static const WCHAR winsysdirW[] = {'w','i','n','s','y','s','d','i','r',0};
134 static const WCHAR userprofileW[] = {'U','S','E','R','P','R','O','F','I','L','E',0};
135 static const WCHAR systemrootW[] = {'S','Y','S','T','E','M','R','O','O','T',0};
136 static const WCHAR wcmdW[] = {'\\','w','c','m','d','.','e','x','e',0};
137 static const WCHAR comspecW[] = {'C','O','M','S','P','E','C',0};
138 static const WCHAR empty_strW[] = { 0 };
140 if (!getcwd( path, MAX_PATHNAME_LEN ))
142 perror( "Could not get current directory" );
143 return 0;
145 cwd = path;
146 if ((drive = DRIVE_FindDriveRoot( &cwd )) == -1)
148 MESSAGE("Warning: could not find wine config [Drive x] entry "
149 "for current working directory %s; "
150 "starting in windows directory.\n", cwd );
152 else
154 WCHAR szdrive[3]={drive+'A',':',0};
155 MultiByteToWideChar(CP_UNIXCP, 0, cwd, -1, longpath, MAX_PATHNAME_LEN);
156 DRIVE_SetCurrentDrive( drive );
157 DRIVE_Chdir( drive, longpath );
158 if(GetDriveTypeW(szdrive)==DRIVE_CDROM)
159 chdir("/"); /* change to root directory so as not to lock cdroms */
162 attr.Length = sizeof(attr);
163 attr.RootDirectory = 0;
164 attr.ObjectName = &nameW;
165 attr.Attributes = 0;
166 attr.SecurityDescriptor = NULL;
167 attr.SecurityQualityOfService = NULL;
169 RtlInitUnicodeString( &nameW, wineW );
170 if (NtCreateKey( &hkey, KEY_ALL_ACCESS, &attr, 0, NULL, 0, NULL )) hkey = 0;
172 if (!(DIR_GetPath( hkey, windowsW, windows_dirW, &DIR_Windows, longpath, MAX_PATHNAME_LEN, TRUE )) ||
173 !(DIR_GetPath( hkey, systemW, system_dirW, &DIR_System, longpath, MAX_PATHNAME_LEN, TRUE )) ||
174 !(DIR_GetPath( hkey, tempW, windows_dirW, &tmp_dir, longpath, MAX_PATHNAME_LEN, TRUE )))
176 if (hkey) NtClose( hkey );
177 return 0;
179 if (-1 == access( tmp_dir.long_name, W_OK ))
181 if (errno==EACCES)
183 MESSAGE("Warning: the temporary directory '%s' specified in your\n"
184 "configuration file (%s) is not writeable.\n",
185 tmp_dir.long_name, wine_get_config_dir() );
187 else
188 MESSAGE("Warning: access to temporary directory '%s' failed (%s).\n",
189 tmp_dir.long_name, strerror(errno));
192 if (drive == -1)
194 drive = DIR_Windows.drive;
195 DRIVE_SetCurrentDrive( drive );
196 DRIVE_Chdir( drive, DIR_Windows.short_name + 2 );
199 /* Set the environment variables */
201 /* set COMSPEC only if it doesn't exist already */
202 if (!GetEnvironmentVariableW( comspecW, NULL, 0 ))
204 strcpyW( longpath, DIR_System.short_name );
205 strcatW( longpath, wcmdW );
206 SetEnvironmentVariableW( comspecW, longpath );
209 /* set PATH only if not set already */
210 if (!GetEnvironmentVariableW( path_capsW, NULL, 0 ))
212 WCHAR tmp[MAX_PATHNAME_LEN];
213 DWORD dummy;
214 const WCHAR *path = path_dirW;
216 RtlInitUnicodeString( &nameW, pathW );
217 if (hkey && !NtQueryValueKey( hkey, &nameW, KeyValuePartialInformation,
218 tmp, sizeof(tmp), &dummy ))
220 path = (WCHAR *)((KEY_VALUE_PARTIAL_INFORMATION *)tmp)->Data;
223 if (strchrW(path, '/'))
225 MESSAGE("Fix your wine config (%s/config) to use DOS drive syntax in [wine] 'Path=' statement! (no '/' allowed)\n", wine_get_config_dir() );
226 ExitProcess(1);
228 SetEnvironmentVariableW( path_capsW, path );
229 TRACE("Path = %s\n", debugstr_w(path) );
232 if (!GetEnvironmentVariableW( temp_capsW, NULL, 0 ))
233 SetEnvironmentVariableW( temp_capsW, tmp_dir.short_name );
234 if (!GetEnvironmentVariableW( tmp_capsW, NULL, 0 ))
235 SetEnvironmentVariableW( tmp_capsW, tmp_dir.short_name );
236 SetEnvironmentVariableW( windirW, DIR_Windows.short_name );
237 SetEnvironmentVariableW( winsysdirW, DIR_System.short_name );
239 TRACE("WindowsDir = %s (%s)\n",
240 debugstr_w(DIR_Windows.short_name), DIR_Windows.long_name );
241 TRACE("SystemDir = %s (%s)\n",
242 debugstr_w(DIR_System.short_name), DIR_System.long_name );
243 TRACE("TempDir = %s (%s)\n",
244 debugstr_w(tmp_dir.short_name), tmp_dir.long_name );
245 TRACE("Cwd = %c:\\%s\n",
246 'A' + drive, debugstr_w(DRIVE_GetDosCwd(drive)) );
248 if (DIR_GetPath( hkey, profileW, empty_strW, &profile_dir, longpath, MAX_PATHNAME_LEN, FALSE ))
250 TRACE("USERPROFILE= %s\n", debugstr_w(longpath) );
251 SetEnvironmentVariableW( userprofileW, longpath );
254 TRACE("SYSTEMROOT = %s\n", debugstr_w(DIR_Windows.short_name) );
255 SetEnvironmentVariableW( systemrootW, DIR_Windows.short_name );
256 if (hkey) NtClose( hkey );
258 return 1;
262 /***********************************************************************
263 * GetTempPathA (KERNEL32.@)
265 UINT WINAPI GetTempPathA( UINT count, LPSTR path )
267 WCHAR pathW[MAX_PATH];
268 UINT ret;
270 ret = GetTempPathW(MAX_PATH, pathW);
272 if (!ret)
273 return 0;
275 if (ret > MAX_PATH)
277 SetLastError(ERROR_FILENAME_EXCED_RANGE);
278 return 0;
281 ret = WideCharToMultiByte(CP_ACP, 0, pathW, -1, NULL, 0, NULL, NULL);
282 if (ret <= count)
284 WideCharToMultiByte(CP_ACP, 0, pathW, -1, path, count, NULL, NULL);
285 ret--; /* length without 0 */
287 return ret;
291 /***********************************************************************
292 * GetTempPathW (KERNEL32.@)
294 UINT WINAPI GetTempPathW( UINT count, LPWSTR path )
296 static const WCHAR tmp[] = { 'T', 'M', 'P', 0 };
297 static const WCHAR temp[] = { 'T', 'E', 'M', 'P', 0 };
298 WCHAR tmp_path[MAX_PATH];
299 UINT ret;
301 TRACE("%u,%p\n", count, path);
303 if (!(ret = GetEnvironmentVariableW( tmp, tmp_path, MAX_PATH )))
304 if (!(ret = GetEnvironmentVariableW( temp, tmp_path, MAX_PATH )))
305 if (!(ret = GetCurrentDirectoryW( MAX_PATH, tmp_path )))
306 return 0;
308 if (ret > MAX_PATH)
310 SetLastError(ERROR_FILENAME_EXCED_RANGE);
311 return 0;
314 ret = GetFullPathNameW(tmp_path, MAX_PATH, tmp_path, NULL);
315 if (!ret) return 0;
317 if (ret > MAX_PATH - 2)
319 SetLastError(ERROR_FILENAME_EXCED_RANGE);
320 return 0;
323 if (tmp_path[ret-1] != '\\')
325 tmp_path[ret++] = '\\';
326 tmp_path[ret] = '\0';
329 ret++; /* add space for terminating 0 */
331 if (count)
333 lstrcpynW(path, tmp_path, count);
334 if (count >= ret)
335 ret--; /* return length without 0 */
336 else if (count < 4)
337 path[0] = 0; /* avoid returning ambiguous "X:" */
340 TRACE("returning %u, %s\n", ret, debugstr_w(path));
341 return ret;
345 /***********************************************************************
346 * GetTempDrive (KERNEL.92)
347 * A closer look at krnl386.exe shows what the SDK doesn't mention:
349 * returns:
350 * AL: driveletter
351 * AH: ':' - yes, some kernel code even does stosw with
352 * the returned AX.
353 * DX: 1 for success
355 UINT WINAPI GetTempDrive( BYTE ignored )
357 char *buffer;
358 BYTE ret;
359 UINT len = GetTempPathA( 0, NULL );
361 if (!(buffer = HeapAlloc( GetProcessHeap(), 0, len + 1 )) )
362 ret = DRIVE_GetCurrentDrive() + 'A';
363 else
365 /* FIXME: apparently Windows does something with the ignored byte */
366 if (!GetTempPathA( len, buffer )) buffer[0] = 'C';
367 ret = toupper(buffer[0]);
368 HeapFree( GetProcessHeap(), 0, buffer );
370 return MAKELONG( ret | (':' << 8), 1 );
374 /***********************************************************************
375 * GetWindowsDirectoryW (KERNEL32.@)
377 * See comment for GetWindowsDirectoryA.
379 UINT WINAPI GetWindowsDirectoryW( LPWSTR path, UINT count )
381 UINT len = strlenW( DIR_Windows.short_name ) + 1;
382 if (path && count >= len)
384 strcpyW( path, DIR_Windows.short_name );
385 len--;
387 return len;
391 /***********************************************************************
392 * GetWindowsDirectoryA (KERNEL32.@)
394 * Return value:
395 * If buffer is large enough to hold full path and terminating '\0' character
396 * function copies path to buffer and returns length of the path without '\0'.
397 * Otherwise function returns required size including '\0' character and
398 * does not touch the buffer.
400 UINT WINAPI GetWindowsDirectoryA( LPSTR path, UINT count )
402 UINT len = WideCharToMultiByte( CP_ACP, 0, DIR_Windows.short_name, -1, NULL, 0, NULL, NULL );
403 if (path && count >= len)
405 WideCharToMultiByte( CP_ACP, 0, DIR_Windows.short_name, -1, path, count, NULL, NULL );
406 len--;
408 return len;
412 /***********************************************************************
413 * GetSystemWindowsDirectoryA (KERNEL32.@) W2K, TS4.0SP4
415 UINT WINAPI GetSystemWindowsDirectoryA( LPSTR path, UINT count )
417 return GetWindowsDirectoryA( path, count );
421 /***********************************************************************
422 * GetSystemWindowsDirectoryW (KERNEL32.@) W2K, TS4.0SP4
424 UINT WINAPI GetSystemWindowsDirectoryW( LPWSTR path, UINT count )
426 return GetWindowsDirectoryW( path, count );
430 /***********************************************************************
431 * GetSystemDirectoryW (KERNEL32.@)
433 * See comment for GetWindowsDirectoryA.
435 UINT WINAPI GetSystemDirectoryW( LPWSTR path, UINT count )
437 UINT len = strlenW( DIR_System.short_name ) + 1;
438 if (path && count >= len)
440 strcpyW( path, DIR_System.short_name );
441 len--;
443 return len;
447 /***********************************************************************
448 * GetSystemDirectoryA (KERNEL32.@)
450 * See comment for GetWindowsDirectoryA.
452 UINT WINAPI GetSystemDirectoryA( LPSTR path, UINT count )
454 UINT len = WideCharToMultiByte( CP_ACP, 0, DIR_System.short_name, -1, NULL, 0, NULL, NULL );
455 if (path && count >= len)
457 WideCharToMultiByte( CP_ACP, 0, DIR_System.short_name, -1, path, count, NULL, NULL );
458 len--;
460 return len;
464 /***********************************************************************
465 * CreateDirectoryW (KERNEL32.@)
466 * RETURNS:
467 * TRUE : success
468 * FALSE : failure
469 * ERROR_DISK_FULL: on full disk
470 * ERROR_ALREADY_EXISTS: if directory name exists (even as file)
471 * ERROR_ACCESS_DENIED: on permission problems
472 * ERROR_FILENAME_EXCED_RANGE: too long filename(s)
474 BOOL WINAPI CreateDirectoryW( LPCWSTR path,
475 LPSECURITY_ATTRIBUTES lpsecattribs )
477 DOS_FULL_NAME full_name;
479 if (!path || !*path)
481 SetLastError(ERROR_PATH_NOT_FOUND);
482 return FALSE;
485 TRACE_(file)("(%s,%p)\n", debugstr_w(path), lpsecattribs );
487 if (RtlIsDosDeviceName_U( path ))
489 TRACE_(file)("cannot use device %s!\n", debugstr_w(path));
490 SetLastError( ERROR_ACCESS_DENIED );
491 return FALSE;
493 if (!DOSFS_GetFullName( path, FALSE, &full_name )) return 0;
494 if (mkdir( full_name.long_name, 0777 ) == -1) {
495 WARN_(file)("Error '%s' trying to create directory '%s'\n", strerror(errno), full_name.long_name);
496 /* the FILE_SetDosError() generated error codes don't match the
497 * CreateDirectory ones for some errnos */
498 switch (errno) {
499 case EEXIST:
501 if (!strcmp(DRIVE_GetRoot(full_name.drive), full_name.long_name))
502 SetLastError(ERROR_ACCESS_DENIED);
503 else
504 SetLastError(ERROR_ALREADY_EXISTS);
505 break;
507 case ENOSPC: SetLastError(ERROR_DISK_FULL); break;
508 default: FILE_SetDosError();break;
510 return FALSE;
512 return TRUE;
516 /***********************************************************************
517 * CreateDirectoryA (KERNEL32.@)
519 BOOL WINAPI CreateDirectoryA( LPCSTR path,
520 LPSECURITY_ATTRIBUTES lpsecattribs )
522 UNICODE_STRING pathW;
523 BOOL ret = FALSE;
525 if (!path || !*path)
527 SetLastError(ERROR_PATH_NOT_FOUND);
528 return FALSE;
531 if (RtlCreateUnicodeStringFromAsciiz(&pathW, path))
533 ret = CreateDirectoryW(pathW.Buffer, lpsecattribs);
534 RtlFreeUnicodeString(&pathW);
536 else
537 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
538 return ret;
542 /***********************************************************************
543 * CreateDirectoryExA (KERNEL32.@)
545 BOOL WINAPI CreateDirectoryExA( LPCSTR template, LPCSTR path,
546 LPSECURITY_ATTRIBUTES lpsecattribs)
548 return CreateDirectoryA(path,lpsecattribs);
552 /***********************************************************************
553 * CreateDirectoryExW (KERNEL32.@)
555 BOOL WINAPI CreateDirectoryExW( LPCWSTR template, LPCWSTR path,
556 LPSECURITY_ATTRIBUTES lpsecattribs)
558 return CreateDirectoryW(path,lpsecattribs);
562 /***********************************************************************
563 * RemoveDirectoryW (KERNEL32.@)
565 BOOL WINAPI RemoveDirectoryW( LPCWSTR path )
567 DOS_FULL_NAME full_name;
569 if (!path)
571 SetLastError(ERROR_INVALID_PARAMETER);
572 return FALSE;
575 TRACE_(file)("%s\n", debugstr_w(path));
577 if (RtlIsDosDeviceName_U( path ))
579 TRACE_(file)("cannot remove device %s!\n", debugstr_w(path));
580 SetLastError( ERROR_FILE_NOT_FOUND );
581 return FALSE;
583 if (!DOSFS_GetFullName( path, TRUE, &full_name )) return FALSE;
584 if (rmdir( full_name.long_name ) == -1)
586 FILE_SetDosError();
587 return FALSE;
589 return TRUE;
593 /***********************************************************************
594 * RemoveDirectoryA (KERNEL32.@)
596 BOOL WINAPI RemoveDirectoryA( LPCSTR path )
598 UNICODE_STRING pathW;
599 BOOL ret = FALSE;
601 if (!path)
603 SetLastError(ERROR_INVALID_PARAMETER);
604 return FALSE;
607 if (RtlCreateUnicodeStringFromAsciiz(&pathW, path))
609 ret = RemoveDirectoryW(pathW.Buffer);
610 RtlFreeUnicodeString(&pathW);
612 else
613 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
614 return ret;
618 /***********************************************************************
619 * DIR_TryPath
621 * Helper function for DIR_SearchPath.
623 static BOOL DIR_TryPath( const DOS_FULL_NAME *dir, LPCWSTR name,
624 DOS_FULL_NAME *full_name )
626 LPSTR p_l = full_name->long_name + strlen(dir->long_name) + 1;
627 LPWSTR p_s = full_name->short_name + strlenW(dir->short_name) + 1;
629 if ((p_s >= full_name->short_name + sizeof(full_name->short_name)/sizeof(full_name->short_name[0]) - 14) ||
630 (p_l >= full_name->long_name + sizeof(full_name->long_name) - 1))
632 SetLastError( ERROR_PATH_NOT_FOUND );
633 return FALSE;
635 if (!DOSFS_FindUnixName( dir, name, p_l,
636 sizeof(full_name->long_name) - (p_l - full_name->long_name), p_s ))
637 return FALSE;
639 full_name->drive = dir->drive;
640 strcpy( full_name->long_name, dir->long_name );
641 p_l[-1] = '/';
642 strcpyW( full_name->short_name, dir->short_name );
643 p_s[-1] = '\\';
644 return TRUE;
647 static BOOL DIR_SearchSemicolonedPaths(LPCWSTR name, DOS_FULL_NAME *full_name, LPWSTR pathlist)
649 LPWSTR next, buffer = NULL;
650 INT len = strlenW(name), newlen, currlen = 0;
651 BOOL ret = FALSE;
653 next = pathlist;
654 while (!ret && next)
656 static const WCHAR bkslashW[] = {'\\',0};
657 LPWSTR cur = next;
658 while (*cur == ';') cur++;
659 if (!*cur) break;
660 next = strchrW( cur, ';' );
661 if (next) *next++ = '\0';
662 newlen = strlenW(cur) + len + 2;
664 if (newlen > currlen)
666 if (buffer)
667 buffer = HeapReAlloc( GetProcessHeap(), 0, buffer, newlen * sizeof(WCHAR));
668 else
669 buffer = HeapAlloc( GetProcessHeap(), 0, newlen * sizeof(WCHAR));
671 if(!buffer)
672 goto done;
673 currlen = newlen;
676 strcpyW( buffer, cur );
677 strcatW( buffer, bkslashW );
678 strcatW( buffer, name );
679 ret = DOSFS_GetFullName( buffer, TRUE, full_name );
681 done:
682 HeapFree( GetProcessHeap(), 0, buffer );
683 return ret;
687 /***********************************************************************
688 * DIR_TryEnvironmentPath
690 * Helper function for DIR_SearchPath.
691 * Search in the specified path, or in $PATH if NULL.
693 static BOOL DIR_TryEnvironmentPath( LPCWSTR name, DOS_FULL_NAME *full_name, LPCWSTR envpath )
695 LPWSTR path;
696 BOOL ret = FALSE;
697 DWORD size;
698 static const WCHAR pathW[] = {'P','A','T','H',0};
700 size = envpath ? strlenW(envpath)+1 : GetEnvironmentVariableW( pathW, NULL, 0 );
701 if (!size) return FALSE;
702 if (!(path = HeapAlloc( GetProcessHeap(), 0, size * sizeof(WCHAR) ))) return FALSE;
703 if (envpath) strcpyW( path, envpath );
704 else if (!GetEnvironmentVariableW( pathW, path, size )) goto done;
706 ret = DIR_SearchSemicolonedPaths(name, full_name, path);
708 done:
709 HeapFree( GetProcessHeap(), 0, path );
710 return ret;
714 /***********************************************************************
715 * DIR_TryModulePath
717 * Helper function for DIR_SearchPath.
719 static BOOL DIR_TryModulePath( LPCWSTR name, DOS_FULL_NAME *full_name, BOOL win32 )
721 WCHAR bufferW[MAX_PATH];
722 LPWSTR p;
724 if (!win32)
726 char buffer[OFS_MAXPATHNAME];
727 if (!GetCurrentTask()) return FALSE;
728 if (!GetModuleFileName16( GetCurrentTask(), buffer, sizeof(buffer) ))
729 return FALSE;
730 MultiByteToWideChar(CP_ACP, 0, buffer, -1, bufferW, MAX_PATH);
731 } else {
732 if (!GetModuleFileNameW( 0, bufferW, MAX_PATH ) )
733 return FALSE;
735 if (!(p = strrchrW( bufferW, '\\' ))) return FALSE;
736 if (MAX_PATH - (++p - bufferW) <= strlenW(name)) return FALSE;
737 strcpyW( p, name );
738 return DOSFS_GetFullName( bufferW, TRUE, full_name );
742 /***********************************************************************
743 * DIR_SearchPath
745 * Implementation of SearchPathA. 'win32' specifies whether the search
746 * order is Win16 (module path last) or Win32 (module path first).
748 * FIXME: should return long path names.
750 DWORD DIR_SearchPath( LPCWSTR path, LPCWSTR name, LPCWSTR ext,
751 DOS_FULL_NAME *full_name, BOOL win32 )
753 LPCWSTR p;
754 LPWSTR tmp = NULL;
755 BOOL ret = TRUE;
757 /* First check the supplied parameters */
759 p = strrchrW( name, '.' );
760 if (p && !strchrW( p, '/' ) && !strchrW( p, '\\' ))
761 ext = NULL; /* Ignore the specified extension */
762 if (FILE_contains_pathW (name))
763 path = NULL; /* Ignore path if name already contains a path */
764 if (path && !*path) path = NULL; /* Ignore empty path */
766 /* Allocate a buffer for the file name and extension */
768 if (ext)
770 DWORD len = strlenW(name) + strlenW(ext);
771 if (!(tmp = HeapAlloc( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
773 SetLastError( ERROR_OUTOFMEMORY );
774 return 0;
776 strcpyW( tmp, name );
777 strcatW( tmp, ext );
778 name = tmp;
781 /* If the name contains an explicit path, everything's easy */
783 if (FILE_contains_pathW(name))
785 ret = DOSFS_GetFullName( name, TRUE, full_name );
786 goto done;
789 /* Search in the specified path */
791 if (path)
793 ret = DIR_TryEnvironmentPath( name, full_name, path );
794 goto done;
797 /* Try the path of the current executable (for Win32 search order) */
799 if (win32 && DIR_TryModulePath( name, full_name, win32 )) goto done;
801 /* Try the current directory */
803 if (DOSFS_GetFullName( name, TRUE, full_name )) goto done;
805 /* Try the Windows system directory */
807 if (DIR_TryPath( &DIR_System, name, full_name ))
808 goto done;
810 /* Try the Windows directory */
812 if (DIR_TryPath( &DIR_Windows, name, full_name ))
813 goto done;
815 /* Try the path of the current executable (for Win16 search order) */
817 if (!win32 && DIR_TryModulePath( name, full_name, win32 )) goto done;
819 /* Try all directories in path */
821 ret = DIR_TryEnvironmentPath( name, full_name, NULL );
823 done:
824 if (tmp) HeapFree( GetProcessHeap(), 0, tmp );
825 return ret;
829 /***********************************************************************
830 * SearchPathW [KERNEL32.@]
832 * Searches for a specified file in the search path.
834 * PARAMS
835 * path [I] Path to search
836 * name [I] Filename to search for.
837 * ext [I] File extension to append to file name. The first
838 * character must be a period. This parameter is
839 * specified only if the filename given does not
840 * contain an extension.
841 * buflen [I] size of buffer, in characters
842 * buffer [O] buffer for found filename
843 * lastpart [O] address of pointer to last used character in
844 * buffer (the final '\')
846 * RETURNS
847 * Success: length of string copied into buffer, not including
848 * terminating null character. If the filename found is
849 * longer than the length of the buffer, the length of the
850 * filename is returned.
851 * Failure: Zero
853 * NOTES
854 * If the file is not found, calls SetLastError(ERROR_FILE_NOT_FOUND)
855 * (tested on NT 4.0)
857 DWORD WINAPI SearchPathW( LPCWSTR path, LPCWSTR name, LPCWSTR ext, DWORD buflen,
858 LPWSTR buffer, LPWSTR *lastpart )
860 LPSTR res;
861 DOS_FULL_NAME full_name;
863 if (!DIR_SearchPath( path, name, ext, &full_name, TRUE ))
865 SetLastError(ERROR_FILE_NOT_FOUND);
866 return 0;
869 TRACE("found %s %s\n", full_name.long_name, debugstr_w(full_name.short_name));
870 TRACE("drive %c: root %s\n", 'A' + full_name.drive, DRIVE_GetRoot(full_name.drive));
872 lstrcpynW( buffer, full_name.short_name, buflen );
873 res = full_name.long_name +
874 strlen(DRIVE_GetRoot( full_name.drive ));
875 while (*res == '/') res++;
876 if (buflen)
878 LPWSTR p;
879 if (buflen > 3)
881 MultiByteToWideChar(CP_UNIXCP, 0, res, -1, buffer + 3, buflen - 3);
882 buffer[buflen - 1] = 0;
884 for (p = buffer; *p; p++) if (*p == '/') *p = '\\';
885 if (lastpart) *lastpart = strrchrW( buffer, '\\' ) + 1;
887 TRACE("Returning %s\n", debugstr_w(buffer) );
888 return strlenW(buffer);
892 /***********************************************************************
893 * SearchPathA (KERNEL32.@)
895 DWORD WINAPI SearchPathA( LPCSTR path, LPCSTR name, LPCSTR ext,
896 DWORD buflen, LPSTR buffer, LPSTR *lastpart )
898 UNICODE_STRING pathW, nameW, extW;
899 WCHAR bufferW[MAX_PATH];
900 DWORD ret, retW;
902 if (path) RtlCreateUnicodeStringFromAsciiz(&pathW, path);
903 else pathW.Buffer = NULL;
904 if (name) RtlCreateUnicodeStringFromAsciiz(&nameW, name);
905 else nameW.Buffer = NULL;
906 if (ext) RtlCreateUnicodeStringFromAsciiz(&extW, ext);
907 else extW.Buffer = NULL;
909 retW = SearchPathW(pathW.Buffer, nameW.Buffer, extW.Buffer, MAX_PATH, bufferW, NULL);
911 if (!retW)
912 ret = 0;
913 else if (retW > MAX_PATH)
915 SetLastError(ERROR_FILENAME_EXCED_RANGE);
916 ret = 0;
918 else
920 ret = WideCharToMultiByte(CP_ACP, 0, bufferW, -1, NULL, 0, NULL, NULL);
921 if (buflen >= ret)
923 WideCharToMultiByte(CP_ACP, 0, bufferW, -1, buffer, buflen, NULL, NULL);
924 ret--; /* length without 0 */
925 if (lastpart) *lastpart = strrchr(buffer, '\\') + 1;
929 RtlFreeUnicodeString(&pathW);
930 RtlFreeUnicodeString(&nameW);
931 RtlFreeUnicodeString(&extW);
932 return ret;