kernel32: Use wide-char string literals.
[wine.git] / dlls / kernel32 / file.c
blob897d8abd14aee757b287f4a75d3c997c37d02182
1 /*
2 * File handling functions
4 * Copyright 1993 John Burton
5 * Copyright 1996, 2004 Alexandre Julliard
6 * Copyright 2008 Jeff Zaroyko
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with this library; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <errno.h>
27 #define NONAMELESSUNION
28 #define NONAMELESSSTRUCT
29 #include "winerror.h"
30 #include "ntstatus.h"
31 #define WIN32_NO_STATUS
32 #include "windef.h"
33 #include "winbase.h"
34 #include "winternl.h"
35 #include "winioctl.h"
36 #include "wincon.h"
37 #include "ddk/ntddk.h"
38 #include "kernel_private.h"
39 #include "fileapi.h"
40 #include "shlwapi.h"
42 #include "wine/exception.h"
43 #include "wine/debug.h"
45 WINE_DEFAULT_DEBUG_CHANNEL(file);
47 /***********************************************************************
48 * create_file_OF
50 * Wrapper for CreateFile that takes OF_* mode flags.
52 static HANDLE create_file_OF( LPCSTR path, INT mode )
54 DWORD access, sharing, creation;
56 if (mode & OF_CREATE)
58 creation = CREATE_ALWAYS;
59 access = GENERIC_READ | GENERIC_WRITE;
61 else
63 creation = OPEN_EXISTING;
64 switch(mode & 0x03)
66 case OF_READ: access = GENERIC_READ; break;
67 case OF_WRITE: access = GENERIC_WRITE; break;
68 case OF_READWRITE: access = GENERIC_READ | GENERIC_WRITE; break;
69 default: access = 0; break;
73 switch(mode & 0x70)
75 case OF_SHARE_EXCLUSIVE: sharing = 0; break;
76 case OF_SHARE_DENY_WRITE: sharing = FILE_SHARE_READ; break;
77 case OF_SHARE_DENY_READ: sharing = FILE_SHARE_WRITE; break;
78 case OF_SHARE_DENY_NONE:
79 case OF_SHARE_COMPAT:
80 default: sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
82 return CreateFileA( path, access, sharing, NULL, creation, FILE_ATTRIBUTE_NORMAL, 0 );
86 /***********************************************************************
87 * FILE_name_AtoW
89 * Convert a file name to Unicode, taking into account the OEM/Ansi API mode.
91 * If alloc is FALSE uses the TEB static buffer, so it can only be used when
92 * there is no possibility for the function to do that twice, taking into
93 * account any called function.
95 WCHAR *FILE_name_AtoW( LPCSTR name, BOOL alloc )
97 ANSI_STRING str;
98 UNICODE_STRING strW, *pstrW;
99 NTSTATUS status;
101 RtlInitAnsiString( &str, name );
102 pstrW = alloc ? &strW : &NtCurrentTeb()->StaticUnicodeString;
103 if (!AreFileApisANSI())
104 status = RtlOemStringToUnicodeString( pstrW, &str, alloc );
105 else
106 status = RtlAnsiStringToUnicodeString( pstrW, &str, alloc );
107 if (status == STATUS_SUCCESS) return pstrW->Buffer;
109 if (status == STATUS_BUFFER_OVERFLOW)
110 SetLastError( ERROR_FILENAME_EXCED_RANGE );
111 else
112 SetLastError( RtlNtStatusToDosError(status) );
113 return NULL;
117 /***********************************************************************
118 * FILE_name_WtoA
120 * Convert a file name back to OEM/Ansi. Returns number of bytes copied.
122 DWORD FILE_name_WtoA( LPCWSTR src, INT srclen, LPSTR dest, INT destlen )
124 DWORD ret;
126 if (srclen < 0) srclen = lstrlenW( src ) + 1;
127 if (!destlen)
129 if (!AreFileApisANSI())
131 UNICODE_STRING strW;
132 strW.Buffer = (WCHAR *)src;
133 strW.Length = srclen * sizeof(WCHAR);
134 ret = RtlUnicodeStringToOemSize( &strW ) - 1;
136 else
137 RtlUnicodeToMultiByteSize( &ret, src, srclen * sizeof(WCHAR) );
139 else
141 if (!AreFileApisANSI())
142 RtlUnicodeToOemN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
143 else
144 RtlUnicodeToMultiByteN( dest, destlen, &ret, src, srclen * sizeof(WCHAR) );
146 return ret;
150 /***********************************************************************
151 * _hread (KERNEL32.@)
153 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
155 return _lread( hFile, buffer, count );
159 /***********************************************************************
160 * _hwrite (KERNEL32.@)
162 * experimentation yields that _lwrite:
163 * o truncates the file at the current position with
164 * a 0 len write
165 * o returns 0 on a 0 length write
166 * o works with console handles
169 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
171 DWORD result;
173 TRACE("%d %p %d\n", handle, buffer, count );
175 if (!count)
177 /* Expand or truncate at current position */
178 if (!SetEndOfFile( LongToHandle(handle) )) return HFILE_ERROR;
179 return 0;
181 if (!WriteFile( LongToHandle(handle), buffer, count, &result, NULL ))
182 return HFILE_ERROR;
183 return result;
187 /***********************************************************************
188 * _lclose (KERNEL32.@)
190 HFILE WINAPI _lclose( HFILE hFile )
192 TRACE("handle %d\n", hFile );
193 return CloseHandle( LongToHandle(hFile) ) ? 0 : HFILE_ERROR;
197 /***********************************************************************
198 * _lcreat (KERNEL32.@)
200 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
202 HANDLE hfile;
204 /* Mask off all flags not explicitly allowed by the doc */
205 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
206 TRACE("%s %02x\n", path, attr );
207 hfile = CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
208 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
209 CREATE_ALWAYS, attr, 0 );
210 return HandleToLong(hfile);
214 /***********************************************************************
215 * _lopen (KERNEL32.@)
217 HFILE WINAPI _lopen( LPCSTR path, INT mode )
219 HANDLE hfile;
221 TRACE("(%s,%04x)\n", debugstr_a(path), mode );
222 hfile = create_file_OF( path, mode & ~OF_CREATE );
223 return HandleToLong(hfile);
226 /***********************************************************************
227 * _lread (KERNEL32.@)
229 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
231 DWORD result;
232 if (!ReadFile( LongToHandle(handle), buffer, count, &result, NULL ))
233 return HFILE_ERROR;
234 return result;
238 /***********************************************************************
239 * _llseek (KERNEL32.@)
241 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
243 return SetFilePointer( LongToHandle(hFile), lOffset, NULL, nOrigin );
247 /***********************************************************************
248 * _lwrite (KERNEL32.@)
250 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
252 return (UINT)_hwrite( hFile, buffer, (LONG)count );
256 /**************************************************************************
257 * SetFileCompletionNotificationModes (KERNEL32.@)
259 BOOL WINAPI SetFileCompletionNotificationModes( HANDLE file, UCHAR flags )
261 FILE_IO_COMPLETION_NOTIFICATION_INFORMATION info;
262 IO_STATUS_BLOCK io;
264 info.Flags = flags;
265 return set_ntstatus( NtSetInformationFile( file, &io, &info, sizeof(info),
266 FileIoCompletionNotificationInformation ));
270 /*************************************************************************
271 * SetHandleCount (KERNEL32.@)
273 UINT WINAPI SetHandleCount( UINT count )
275 return count;
279 /*************************************************************************
280 * ReadFile (KERNEL32.@)
282 BOOL WINAPI KERNEL32_ReadFile( HANDLE file, LPVOID buffer, DWORD count,
283 LPDWORD result, LPOVERLAPPED overlapped )
285 if (result) *result = 0;
287 if (is_console_handle( file ))
289 DWORD conread, mode;
291 if (!ReadConsoleA( file, buffer, count, &conread, NULL) || !GetConsoleMode( file, &mode ))
292 return FALSE;
293 /* ctrl-Z (26) means end of file on window (if at beginning of buffer)
294 * but Unix uses ctrl-D (4), and ctrl-Z is a bad idea on Unix :-/
295 * So map both ctrl-D ctrl-Z to EOF.
297 if ((mode & ENABLE_PROCESSED_INPUT) && conread > 0 &&
298 (((char *)buffer)[0] == 26 || ((char *)buffer)[0] == 4))
300 conread = 0;
302 if (result) *result = conread;
303 return TRUE;
305 return ReadFile( file, buffer, count, result, overlapped );
309 /*************************************************************************
310 * WriteFile (KERNEL32.@)
312 BOOL WINAPI KERNEL32_WriteFile( HANDLE file, LPCVOID buffer, DWORD count,
313 LPDWORD result, LPOVERLAPPED overlapped )
315 if (is_console_handle( file )) return WriteConsoleA( file, buffer, count, result, NULL );
316 return WriteFile( file, buffer, count, result, overlapped );
320 /***********************************************************************
321 * DosDateTimeToFileTime (KERNEL32.@)
323 BOOL WINAPI DosDateTimeToFileTime( WORD fatdate, WORD fattime, FILETIME *ft )
325 TIME_FIELDS fields;
326 LARGE_INTEGER time;
328 fields.Year = (fatdate >> 9) + 1980;
329 fields.Month = ((fatdate >> 5) & 0x0f);
330 fields.Day = (fatdate & 0x1f);
331 fields.Hour = (fattime >> 11);
332 fields.Minute = (fattime >> 5) & 0x3f;
333 fields.Second = (fattime & 0x1f) * 2;
334 fields.Milliseconds = 0;
335 if (!RtlTimeFieldsToTime( &fields, &time )) return FALSE;
336 ft->dwLowDateTime = time.u.LowPart;
337 ft->dwHighDateTime = time.u.HighPart;
338 return TRUE;
342 /***********************************************************************
343 * FileTimeToDosDateTime (KERNEL32.@)
345 BOOL WINAPI FileTimeToDosDateTime( const FILETIME *ft, WORD *fatdate, WORD *fattime )
347 TIME_FIELDS fields;
348 LARGE_INTEGER time;
350 if (!fatdate || !fattime)
352 SetLastError( ERROR_INVALID_PARAMETER );
353 return FALSE;
355 time.u.LowPart = ft->dwLowDateTime;
356 time.u.HighPart = ft->dwHighDateTime;
357 RtlTimeToTimeFields( &time, &fields );
358 if (fields.Year < 1980)
360 SetLastError( ERROR_INVALID_PARAMETER );
361 return FALSE;
363 *fattime = (fields.Hour << 11) + (fields.Minute << 5) + (fields.Second / 2);
364 *fatdate = ((fields.Year - 1980) << 9) + (fields.Month << 5) + fields.Day;
365 return TRUE;
369 /**************************************************************************
370 * Operations on file names *
371 **************************************************************************/
374 /**************************************************************************
375 * ReplaceFileA (KERNEL32.@)
377 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
378 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
379 LPVOID lpExclude, LPVOID lpReserved)
381 WCHAR *replacedW, *replacementW, *backupW = NULL;
382 BOOL ret;
384 /* This function only makes sense when the first two parameters are defined */
385 if (!lpReplacedFileName || !(replacedW = FILE_name_AtoW( lpReplacedFileName, TRUE )))
387 SetLastError(ERROR_INVALID_PARAMETER);
388 return FALSE;
390 if (!lpReplacementFileName || !(replacementW = FILE_name_AtoW( lpReplacementFileName, TRUE )))
392 HeapFree( GetProcessHeap(), 0, replacedW );
393 SetLastError(ERROR_INVALID_PARAMETER);
394 return FALSE;
396 /* The backup parameter, however, is optional */
397 if (lpBackupFileName)
399 if (!(backupW = FILE_name_AtoW( lpBackupFileName, TRUE )))
401 HeapFree( GetProcessHeap(), 0, replacedW );
402 HeapFree( GetProcessHeap(), 0, replacementW );
403 SetLastError(ERROR_INVALID_PARAMETER);
404 return FALSE;
407 ret = ReplaceFileW( replacedW, replacementW, backupW, dwReplaceFlags, lpExclude, lpReserved );
408 HeapFree( GetProcessHeap(), 0, replacedW );
409 HeapFree( GetProcessHeap(), 0, replacementW );
410 HeapFree( GetProcessHeap(), 0, backupW );
411 return ret;
415 /***********************************************************************
416 * OpenVxDHandle (KERNEL32.@)
418 * This function is supposed to return the corresponding Ring 0
419 * ("kernel") handle for a Ring 3 handle in Win9x.
420 * Evidently, Wine will have problems with this. But we try anyway,
421 * maybe it helps...
423 HANDLE WINAPI OpenVxDHandle(HANDLE hHandleRing3)
425 FIXME( "(%p), stub! (returning Ring 3 handle instead of Ring 0)\n", hHandleRing3);
426 return hHandleRing3;
430 /****************************************************************************
431 * DeviceIoControl (KERNEL32.@)
433 BOOL WINAPI DeviceIoControl(HANDLE hDevice, DWORD dwIoControlCode,
434 LPVOID lpvInBuffer, DWORD cbInBuffer,
435 LPVOID lpvOutBuffer, DWORD cbOutBuffer,
436 LPDWORD lpcbBytesReturned,
437 LPOVERLAPPED lpOverlapped)
439 NTSTATUS status;
441 TRACE( "(%p,%x,%p,%d,%p,%d,%p,%p)\n",
442 hDevice,dwIoControlCode,lpvInBuffer,cbInBuffer,
443 lpvOutBuffer,cbOutBuffer,lpcbBytesReturned,lpOverlapped );
445 /* Check if this is a user defined control code for a VxD */
447 if (HIWORD( dwIoControlCode ) == 0 && (GetVersion() & 0x80000000))
449 typedef BOOL (WINAPI *DeviceIoProc)(DWORD, LPVOID, DWORD, LPVOID, DWORD, LPDWORD, LPOVERLAPPED);
450 static DeviceIoProc (*vxd_get_proc)(HANDLE);
451 DeviceIoProc proc = NULL;
453 if (!vxd_get_proc) vxd_get_proc = (void *)GetProcAddress( GetModuleHandleW(L"krnl386.exe16"),
454 "__wine_vxd_get_proc" );
455 if (vxd_get_proc) proc = vxd_get_proc( hDevice );
456 if (proc) return proc( dwIoControlCode, lpvInBuffer, cbInBuffer,
457 lpvOutBuffer, cbOutBuffer, lpcbBytesReturned, lpOverlapped );
460 /* Not a VxD, let ntdll handle it */
462 if (lpOverlapped)
464 LPVOID cvalue = ((ULONG_PTR)lpOverlapped->hEvent & 1) ? NULL : lpOverlapped;
465 lpOverlapped->Internal = STATUS_PENDING;
466 lpOverlapped->InternalHigh = 0;
467 if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
468 status = NtFsControlFile(hDevice, lpOverlapped->hEvent,
469 NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
470 dwIoControlCode, lpvInBuffer, cbInBuffer,
471 lpvOutBuffer, cbOutBuffer);
472 else
473 status = NtDeviceIoControlFile(hDevice, lpOverlapped->hEvent,
474 NULL, cvalue, (PIO_STATUS_BLOCK)lpOverlapped,
475 dwIoControlCode, lpvInBuffer, cbInBuffer,
476 lpvOutBuffer, cbOutBuffer);
477 if (lpcbBytesReturned) *lpcbBytesReturned = lpOverlapped->InternalHigh;
479 else
481 IO_STATUS_BLOCK iosb;
483 if (HIWORD(dwIoControlCode) == FILE_DEVICE_FILE_SYSTEM)
484 status = NtFsControlFile(hDevice, NULL, NULL, NULL, &iosb,
485 dwIoControlCode, lpvInBuffer, cbInBuffer,
486 lpvOutBuffer, cbOutBuffer);
487 else
488 status = NtDeviceIoControlFile(hDevice, NULL, NULL, NULL, &iosb,
489 dwIoControlCode, lpvInBuffer, cbInBuffer,
490 lpvOutBuffer, cbOutBuffer);
491 if (lpcbBytesReturned) *lpcbBytesReturned = iosb.Information;
493 return set_ntstatus( status );
497 /***********************************************************************
498 * OpenFile (KERNEL32.@)
500 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
502 HANDLE handle;
503 FILETIME filetime;
504 WORD filedatetime[2];
505 DWORD len;
507 if (!ofs) return HFILE_ERROR;
509 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
510 ((mode & 0x3 )==OF_READ)?"OF_READ":
511 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
512 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
513 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
514 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
515 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
516 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
517 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
518 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
519 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
520 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
521 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
522 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
523 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
524 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
525 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
526 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
530 ofs->cBytes = sizeof(OFSTRUCT);
531 ofs->nErrCode = 0;
532 if (mode & OF_REOPEN) name = ofs->szPathName;
534 if (!name) return HFILE_ERROR;
536 TRACE("%s %04x\n", name, mode );
538 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
539 Are there any cases where getting the path here is wrong?
540 Uwe Bonnes 1997 Apr 2 */
541 len = GetFullPathNameA( name, sizeof(ofs->szPathName), ofs->szPathName, NULL );
542 if (!len) goto error;
543 if (len >= sizeof(ofs->szPathName))
545 SetLastError(ERROR_INVALID_DATA);
546 goto error;
549 /* OF_PARSE simply fills the structure */
551 if (mode & OF_PARSE)
553 ofs->fFixedDisk = (GetDriveTypeA( ofs->szPathName ) != DRIVE_REMOVABLE);
554 TRACE("(%s): OF_PARSE, res = '%s'\n", name, ofs->szPathName );
555 return 0;
558 /* OF_CREATE is completely different from all other options, so
559 handle it first */
561 if (mode & OF_CREATE)
563 if ((handle = create_file_OF( name, mode )) == INVALID_HANDLE_VALUE)
564 goto error;
566 else
568 /* Now look for the file */
570 len = SearchPathA( NULL, name, NULL, sizeof(ofs->szPathName), ofs->szPathName, NULL );
571 if (!len) goto error;
572 if (len >= sizeof(ofs->szPathName))
574 SetLastError(ERROR_INVALID_DATA);
575 goto error;
578 TRACE("found %s\n", debugstr_a(ofs->szPathName) );
580 if (mode & OF_DELETE)
582 if (!DeleteFileA( ofs->szPathName )) goto error;
583 TRACE("(%s): OF_DELETE return = OK\n", name);
584 return TRUE;
587 handle = LongToHandle(_lopen( ofs->szPathName, mode ));
588 if (handle == INVALID_HANDLE_VALUE) goto error;
590 GetFileTime( handle, NULL, NULL, &filetime );
591 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
592 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
594 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
596 CloseHandle( handle );
597 WARN("(%s): OF_VERIFY failed\n", name );
598 /* FIXME: what error here? */
599 SetLastError( ERROR_FILE_NOT_FOUND );
600 goto error;
603 ofs->Reserved1 = filedatetime[0];
604 ofs->Reserved2 = filedatetime[1];
606 TRACE("(%s): OK, return = %p\n", name, handle );
607 if (mode & OF_EXIST) /* Return TRUE instead of a handle */
609 CloseHandle( handle );
610 return TRUE;
612 return HandleToLong(handle);
614 error: /* We get here if there was an error opening the file */
615 ofs->nErrCode = GetLastError();
616 WARN("(%s): return = HFILE_ERROR error= %d\n", name,ofs->nErrCode );
617 return HFILE_ERROR;