Quiet some valgrind reports.
[wine/wine64.git] / files / file.c
blob9e45fa0c744a06f3e2c1ecb8162fb2971a7b82f4
1 /*
2 * File handling functions
4 * Copyright 1993 John Burton
5 * Copyright 1996 Alexandre Julliard
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.
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.
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
21 * TODO:
22 * Fix the CopyFileEx methods to implement the "extended" functionality.
23 * Right now, they simply call the CopyFile method.
26 #include "config.h"
27 #include "wine/port.h"
29 #include <assert.h>
30 #include <ctype.h>
31 #include <errno.h>
32 #include <fcntl.h>
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <string.h>
36 #ifdef HAVE_SYS_ERRNO_H
37 #include <sys/errno.h>
38 #endif
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #ifdef HAVE_SYS_MMAN_H
42 #include <sys/mman.h>
43 #endif
44 #ifdef HAVE_SYS_TIME_H
45 # include <sys/time.h>
46 #endif
47 #ifdef HAVE_SYS_POLL_H
48 # include <sys/poll.h>
49 #endif
50 #include <time.h>
51 #ifdef HAVE_UNISTD_H
52 # include <unistd.h>
53 #endif
54 #ifdef HAVE_UTIME_H
55 # include <utime.h>
56 #endif
58 #define NONAMELESSUNION
59 #define NONAMELESSSTRUCT
60 #include "winerror.h"
61 #include "windef.h"
62 #include "winbase.h"
63 #include "winternl.h"
64 #include "wine/winbase16.h"
65 #include "wine/server.h"
67 #include "drive.h"
68 #include "file.h"
69 #include "async.h"
70 #include "heap.h"
71 #include "msdos.h"
72 #include "wincon.h"
74 #include "smb.h"
75 #include "wine/unicode.h"
76 #include "wine/debug.h"
78 WINE_DEFAULT_DEBUG_CHANNEL(file);
80 #if defined(MAP_ANONYMOUS) && !defined(MAP_ANON)
81 #define MAP_ANON MAP_ANONYMOUS
82 #endif
84 /* Size of per-process table of DOS handles */
85 #define DOS_TABLE_SIZE 256
87 /* Macro to derive file offset from OVERLAPPED struct */
88 #define OVERLAPPED_OFFSET(overlapped) ((off_t) (overlapped)->Offset + ((off_t) (overlapped)->OffsetHigh << 32))
90 static HANDLE dos_handles[DOS_TABLE_SIZE];
92 mode_t FILE_umask;
94 extern HANDLE WINAPI FILE_SmbOpen(LPCSTR name);
96 /***********************************************************************
97 * Asynchronous file I/O *
99 static DWORD fileio_get_async_status (const async_private *ovp);
100 static DWORD fileio_get_async_count (const async_private *ovp);
101 static void fileio_set_async_status (async_private *ovp, const DWORD status);
102 static void CALLBACK fileio_call_completion_func (ULONG_PTR data);
103 static void fileio_async_cleanup (async_private *ovp);
105 static async_ops fileio_async_ops =
107 fileio_get_async_status, /* get_status */
108 fileio_set_async_status, /* set_status */
109 fileio_get_async_count, /* get_count */
110 fileio_call_completion_func, /* call_completion */
111 fileio_async_cleanup /* cleanup */
114 static async_ops fileio_nocomp_async_ops =
116 fileio_get_async_status, /* get_status */
117 fileio_set_async_status, /* set_status */
118 fileio_get_async_count, /* get_count */
119 NULL, /* call_completion */
120 fileio_async_cleanup /* cleanup */
123 typedef struct async_fileio
125 struct async_private async;
126 LPOVERLAPPED lpOverlapped;
127 LPOVERLAPPED_COMPLETION_ROUTINE completion_func;
128 char *buffer;
129 unsigned int count;
130 enum fd_type fd_type;
131 } async_fileio;
133 static DWORD fileio_get_async_status (const struct async_private *ovp)
135 return ((async_fileio*) ovp)->lpOverlapped->Internal;
138 static void fileio_set_async_status (async_private *ovp, const DWORD status)
140 ((async_fileio*) ovp)->lpOverlapped->Internal = status;
143 static DWORD fileio_get_async_count (const struct async_private *ovp)
145 async_fileio *fileio = (async_fileio*) ovp;
147 if (fileio->count < fileio->lpOverlapped->InternalHigh)
148 return 0;
149 return fileio->count - fileio->lpOverlapped->InternalHigh;
152 static void CALLBACK fileio_call_completion_func (ULONG_PTR data)
154 async_fileio *ovp = (async_fileio*) data;
155 TRACE ("data: %p\n", ovp);
157 ovp->completion_func( RtlNtStatusToDosError ( ovp->lpOverlapped->Internal ),
158 ovp->lpOverlapped->InternalHigh,
159 ovp->lpOverlapped );
161 fileio_async_cleanup ( &ovp->async );
164 static void fileio_async_cleanup ( struct async_private *ovp )
166 HeapFree ( GetProcessHeap(), 0, ovp );
169 /***********************************************************************
170 * FILE_ConvertOFMode
172 * Convert OF_* mode into flags for CreateFile.
174 static void FILE_ConvertOFMode( INT mode, DWORD *access, DWORD *sharing )
176 switch(mode & 0x03)
178 case OF_READ: *access = GENERIC_READ; break;
179 case OF_WRITE: *access = GENERIC_WRITE; break;
180 case OF_READWRITE: *access = GENERIC_READ | GENERIC_WRITE; break;
181 default: *access = 0; break;
183 switch(mode & 0x70)
185 case OF_SHARE_EXCLUSIVE: *sharing = 0; break;
186 case OF_SHARE_DENY_WRITE: *sharing = FILE_SHARE_READ; break;
187 case OF_SHARE_DENY_READ: *sharing = FILE_SHARE_WRITE; break;
188 case OF_SHARE_DENY_NONE:
189 case OF_SHARE_COMPAT:
190 default: *sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
195 /***********************************************************************
196 * FILE_strcasecmp
198 * locale-independent case conversion for file I/O
200 int FILE_strcasecmp( const char *str1, const char *str2 )
202 int ret = 0;
203 for ( ; ; str1++, str2++)
204 if ((ret = FILE_toupper(*str1) - FILE_toupper(*str2)) || !*str1) break;
205 return ret;
209 /***********************************************************************
210 * FILE_strncasecmp
212 * locale-independent case conversion for file I/O
214 int FILE_strncasecmp( const char *str1, const char *str2, int len )
216 int ret = 0;
217 for ( ; len > 0; len--, str1++, str2++)
218 if ((ret = FILE_toupper(*str1) - FILE_toupper(*str2)) || !*str1) break;
219 return ret;
223 /***********************************************************************
224 * FILE_GetNtStatus(void)
226 * Retrieve the Nt Status code from errno.
227 * Try to be consistent with FILE_SetDosError().
229 DWORD FILE_GetNtStatus(void)
231 int err = errno;
232 DWORD nt;
233 TRACE ( "errno = %d\n", errno );
234 switch ( err )
236 case EAGAIN: nt = STATUS_SHARING_VIOLATION; break;
237 case EBADF: nt = STATUS_INVALID_HANDLE; break;
238 case ENOSPC: nt = STATUS_DISK_FULL; break;
239 case EPERM:
240 case EROFS:
241 case EACCES: nt = STATUS_ACCESS_DENIED; break;
242 case ENOENT: nt = STATUS_SHARING_VIOLATION; break;
243 case EISDIR: nt = STATUS_FILE_IS_A_DIRECTORY; break;
244 case EMFILE:
245 case ENFILE: nt = STATUS_NO_MORE_FILES; break;
246 case EINVAL:
247 case ENOTEMPTY: nt = STATUS_DIRECTORY_NOT_EMPTY; break;
248 case EPIPE: nt = STATUS_PIPE_BROKEN; break;
249 case ENOEXEC: /* ?? */
250 case ESPIPE: /* ?? */
251 case EEXIST: /* ?? */
252 default:
253 FIXME ( "Converting errno %d to STATUS_UNSUCCESSFUL\n", err );
254 nt = STATUS_UNSUCCESSFUL;
256 return nt;
259 /***********************************************************************
260 * FILE_SetDosError
262 * Set the DOS error code from errno.
264 void FILE_SetDosError(void)
266 int save_errno = errno; /* errno gets overwritten by printf */
268 TRACE("errno = %d %s\n", errno, strerror(errno));
269 switch (save_errno)
271 case EAGAIN:
272 SetLastError( ERROR_SHARING_VIOLATION );
273 break;
274 case EBADF:
275 SetLastError( ERROR_INVALID_HANDLE );
276 break;
277 case ENOSPC:
278 SetLastError( ERROR_HANDLE_DISK_FULL );
279 break;
280 case EACCES:
281 case EPERM:
282 case EROFS:
283 SetLastError( ERROR_ACCESS_DENIED );
284 break;
285 case EBUSY:
286 SetLastError( ERROR_LOCK_VIOLATION );
287 break;
288 case ENOENT:
289 SetLastError( ERROR_FILE_NOT_FOUND );
290 break;
291 case EISDIR:
292 SetLastError( ERROR_CANNOT_MAKE );
293 break;
294 case ENFILE:
295 case EMFILE:
296 SetLastError( ERROR_NO_MORE_FILES );
297 break;
298 case EEXIST:
299 SetLastError( ERROR_FILE_EXISTS );
300 break;
301 case EINVAL:
302 case ESPIPE:
303 SetLastError( ERROR_SEEK );
304 break;
305 case ENOTEMPTY:
306 SetLastError( ERROR_DIR_NOT_EMPTY );
307 break;
308 case ENOEXEC:
309 SetLastError( ERROR_BAD_FORMAT );
310 break;
311 default:
312 WARN("unknown file error: %s\n", strerror(save_errno) );
313 SetLastError( ERROR_GEN_FAILURE );
314 break;
316 errno = save_errno;
320 /***********************************************************************
321 * FILE_GetUnixHandleType
323 * Retrieve the Unix handle corresponding to a file handle.
324 * Returns -1 on failure.
326 static int FILE_GetUnixHandleType( HANDLE handle, DWORD access, enum fd_type *type, int *flags_ptr )
328 int ret, flags, fd = -1;
330 ret = wine_server_handle_to_fd( handle, access, &fd, type, &flags );
331 if (flags_ptr) *flags_ptr = flags;
332 if (ret) SetLastError( RtlNtStatusToDosError(ret) );
333 else if (((access & GENERIC_READ) && (flags & FD_FLAG_RECV_SHUTDOWN)) ||
334 ((access & GENERIC_WRITE) && (flags & FD_FLAG_SEND_SHUTDOWN)))
336 close (fd);
337 SetLastError ( ERROR_PIPE_NOT_CONNECTED );
338 return -1;
340 return fd;
343 /***********************************************************************
344 * FILE_GetUnixHandle
346 * Retrieve the Unix handle corresponding to a file handle.
347 * Returns -1 on failure.
349 int FILE_GetUnixHandle( HANDLE handle, DWORD access )
351 return FILE_GetUnixHandleType( handle, access, NULL, NULL );
354 /*************************************************************************
355 * FILE_OpenConsole
357 * Open a handle to the current process console.
358 * Returns 0 on failure.
360 static HANDLE FILE_OpenConsole( BOOL output, DWORD access, DWORD sharing, LPSECURITY_ATTRIBUTES sa )
362 HANDLE ret;
364 SERVER_START_REQ( open_console )
366 req->from = output;
367 req->access = access;
368 req->share = sharing;
369 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
370 SetLastError(0);
371 wine_server_call_err( req );
372 ret = reply->handle;
374 SERVER_END_REQ;
375 return ret;
378 /* FIXME: those routines defined as pointers are needed, because this file is
379 * currently compiled into NTDLL whereas it belongs to kernel32.
380 * this shall go away once all the DLL separation process is done
382 typedef BOOL (WINAPI* pRW)(HANDLE, const void*, DWORD, DWORD*, void*);
384 static BOOL FILE_ReadConsole(HANDLE hCon, void* buf, DWORD nb, DWORD* nr, void* p)
386 static HANDLE hKernel /* = 0 */;
387 static pRW pReadConsole /* = 0 */;
389 if ((!hKernel && !(hKernel = LoadLibraryA("kernel32"))) ||
390 (!pReadConsole &&
391 !(pReadConsole = GetProcAddress(hKernel, "ReadConsoleA"))))
393 *nr = 0;
394 return 0;
396 return (pReadConsole)(hCon, buf, nb, nr, p);
399 static BOOL FILE_WriteConsole(HANDLE hCon, const void* buf, DWORD nb, DWORD* nr, void* p)
401 static HANDLE hKernel /* = 0 */;
402 static pRW pWriteConsole /* = 0 */;
404 if ((!hKernel && !(hKernel = LoadLibraryA("kernel32"))) ||
405 (!pWriteConsole &&
406 !(pWriteConsole = GetProcAddress(hKernel, "WriteConsoleA"))))
408 *nr = 0;
409 return 0;
411 return (pWriteConsole)(hCon, buf, nb, nr, p);
413 /* end of FIXME */
415 /***********************************************************************
416 * FILE_CreateFile
418 * Implementation of CreateFile. Takes a Unix path name.
419 * Returns 0 on failure.
421 HANDLE FILE_CreateFile( LPCSTR filename, DWORD access, DWORD sharing,
422 LPSECURITY_ATTRIBUTES sa, DWORD creation,
423 DWORD attributes, HANDLE template, BOOL fail_read_only,
424 UINT drive_type )
426 unsigned int err;
427 HANDLE ret;
429 for (;;)
431 SERVER_START_REQ( create_file )
433 req->access = access;
434 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
435 req->sharing = sharing;
436 req->create = creation;
437 req->attrs = attributes;
438 req->drive_type = drive_type;
439 wine_server_add_data( req, filename, strlen(filename) );
440 SetLastError(0);
441 err = wine_server_call( req );
442 ret = reply->handle;
444 SERVER_END_REQ;
446 /* If write access failed, retry without GENERIC_WRITE */
448 if (!ret && !fail_read_only && (access & GENERIC_WRITE))
450 if ((err == STATUS_MEDIA_WRITE_PROTECTED) || (err == STATUS_ACCESS_DENIED))
452 TRACE("Write access failed for file '%s', trying without "
453 "write access\n", filename);
454 access &= ~GENERIC_WRITE;
455 continue;
459 if (err)
461 /* In the case file creation was rejected due to CREATE_NEW flag
462 * was specified and file with that name already exists, correct
463 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
464 * Note: RtlNtStatusToDosError is not the subject to blame here.
466 if (err == STATUS_OBJECT_NAME_COLLISION)
467 SetLastError( ERROR_FILE_EXISTS );
468 else
469 SetLastError( RtlNtStatusToDosError(err) );
472 if (!ret) WARN("Unable to create file '%s' (GLE %ld)\n", filename, GetLastError());
473 return ret;
478 /***********************************************************************
479 * FILE_CreateDevice
481 * Same as FILE_CreateFile but for a device
482 * Returns 0 on failure.
484 HANDLE FILE_CreateDevice( int client_id, DWORD access, LPSECURITY_ATTRIBUTES sa )
486 HANDLE ret;
487 SERVER_START_REQ( create_device )
489 req->access = access;
490 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
491 req->id = client_id;
492 SetLastError(0);
493 wine_server_call_err( req );
494 ret = reply->handle;
496 SERVER_END_REQ;
497 return ret;
500 static HANDLE FILE_OpenPipe(LPCWSTR name, DWORD access)
502 HANDLE ret;
503 DWORD len = 0;
505 if (name && (len = strlenW(name)) > MAX_PATH)
507 SetLastError( ERROR_FILENAME_EXCED_RANGE );
508 return 0;
510 SERVER_START_REQ( open_named_pipe )
512 req->access = access;
513 SetLastError(0);
514 wine_server_add_data( req, name, len * sizeof(WCHAR) );
515 wine_server_call_err( req );
516 ret = reply->handle;
518 SERVER_END_REQ;
519 TRACE("Returned %p\n",ret);
520 return ret;
523 /*************************************************************************
524 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
526 * Creates or opens an object, and returns a handle that can be used to
527 * access that object.
529 * PARAMS
531 * filename [in] pointer to filename to be accessed
532 * access [in] access mode requested
533 * sharing [in] share mode
534 * sa [in] pointer to security attributes
535 * creation [in] how to create the file
536 * attributes [in] attributes for newly created file
537 * template [in] handle to file with extended attributes to copy
539 * RETURNS
540 * Success: Open handle to specified file
541 * Failure: INVALID_HANDLE_VALUE
543 * NOTES
544 * Should call SetLastError() on failure.
546 * BUGS
548 * Doesn't support character devices, template files, or a
549 * lot of the 'attributes' flags yet.
551 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
552 LPSECURITY_ATTRIBUTES sa, DWORD creation,
553 DWORD attributes, HANDLE template )
555 DOS_FULL_NAME full_name;
556 HANDLE ret;
557 static const WCHAR bkslashes_with_question_markW[] = {'\\','\\','?','\\',0};
558 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
559 static const WCHAR bkslashesW[] = {'\\','\\',0};
560 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
561 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
563 if (!filename)
565 SetLastError( ERROR_INVALID_PARAMETER );
566 return INVALID_HANDLE_VALUE;
568 TRACE("%s %s%s%s%s%s%s%s attributes 0x%lx\n", debugstr_w(filename),
569 ((access & GENERIC_READ)==GENERIC_READ)?"GENERIC_READ ":"",
570 ((access & GENERIC_WRITE)==GENERIC_WRITE)?"GENERIC_WRITE ":"",
571 (!access)?"QUERY_ACCESS ":"",
572 ((sharing & FILE_SHARE_READ)==FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
573 ((sharing & FILE_SHARE_WRITE)==FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
574 ((sharing & FILE_SHARE_DELETE)==FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
575 (creation ==CREATE_NEW)?"CREATE_NEW":
576 (creation ==CREATE_ALWAYS)?"CREATE_ALWAYS ":
577 (creation ==OPEN_EXISTING)?"OPEN_EXISTING ":
578 (creation ==OPEN_ALWAYS)?"OPEN_ALWAYS ":
579 (creation ==TRUNCATE_EXISTING)?"TRUNCATE_EXISTING ":"", attributes);
581 /* If the name starts with '\\?\', ignore the first 4 chars. */
582 if (!strncmpW(filename, bkslashes_with_question_markW, 4))
584 static const WCHAR uncW[] = {'U','N','C','\\',0};
585 filename += 4;
586 if (!strncmpiW(filename, uncW, 4))
588 FIXME("UNC name (%s) not supported.\n", debugstr_w(filename) );
589 SetLastError( ERROR_PATH_NOT_FOUND );
590 return INVALID_HANDLE_VALUE;
594 if (!strncmpW(filename, bkslashes_with_dotW, 4))
596 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
597 if(!strncmpiW(filename + 4, pipeW, 5))
599 TRACE("Opening a pipe: %s\n", debugstr_w(filename));
600 ret = FILE_OpenPipe(filename,access);
601 goto done;
603 else if (isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0')
605 ret = FILE_CreateDevice( (toupperW(filename[4]) - 'A') | 0x20000, access, sa );
606 goto done;
608 else if (!DOSFS_GetDevice( filename ))
610 ret = DEVICE_Open( filename+4, access, sa );
611 goto done;
613 else
614 filename+=4; /* fall into DOSFS_Device case below */
617 /* If the name still starts with '\\', it's a UNC name. */
618 if (!strncmpW(filename, bkslashesW, 2))
620 ret = SMB_CreateFileW(filename, access, sharing, sa, creation, attributes, template );
621 goto done;
624 /* If the name contains a DOS wild card (* or ?), do no create a file */
625 if(strchrW(filename, '*') || strchrW(filename, '?'))
627 SetLastError(ERROR_BAD_PATHNAME);
628 return INVALID_HANDLE_VALUE;
631 /* Open a console for CONIN$ or CONOUT$ */
632 if (!strcmpiW(filename, coninW))
634 ret = FILE_OpenConsole( FALSE, access, sharing, sa );
635 goto done;
637 if (!strcmpiW(filename, conoutW))
639 ret = FILE_OpenConsole( TRUE, access, sharing, sa );
640 goto done;
643 if (DOSFS_GetDevice( filename ))
645 TRACE("opening device %s\n", debugstr_w(filename) );
647 if (!(ret = DOSFS_OpenDevice( filename, access, attributes, sa )))
649 /* Do not silence this please. It is a critical error. -MM */
650 ERR("Couldn't open device %s!\n", debugstr_w(filename));
651 SetLastError( ERROR_FILE_NOT_FOUND );
653 goto done;
656 /* check for filename, don't check for last entry if creating */
657 if (!DOSFS_GetFullName( filename,
658 (creation == OPEN_EXISTING) ||
659 (creation == TRUNCATE_EXISTING),
660 &full_name )) {
661 WARN("Unable to get full filename from %s (GLE %ld)\n",
662 debugstr_w(filename), GetLastError());
663 return INVALID_HANDLE_VALUE;
666 ret = FILE_CreateFile( full_name.long_name, access, sharing,
667 sa, creation, attributes, template,
668 DRIVE_GetFlags(full_name.drive) & DRIVE_FAIL_READ_ONLY,
669 GetDriveTypeW( full_name.short_name ) );
670 done:
671 if (!ret) ret = INVALID_HANDLE_VALUE;
672 TRACE("returning %p\n", ret);
673 return ret;
678 /*************************************************************************
679 * CreateFileA (KERNEL32.@)
681 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
682 LPSECURITY_ATTRIBUTES sa, DWORD creation,
683 DWORD attributes, HANDLE template)
685 UNICODE_STRING filenameW;
686 HANDLE ret = INVALID_HANDLE_VALUE;
688 if (!filename)
690 SetLastError( ERROR_INVALID_PARAMETER );
691 return INVALID_HANDLE_VALUE;
694 if (RtlCreateUnicodeStringFromAsciiz(&filenameW, filename))
696 ret = CreateFileW(filenameW.Buffer, access, sharing, sa, creation,
697 attributes, template);
698 RtlFreeUnicodeString(&filenameW);
700 else
701 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
702 return ret;
706 /***********************************************************************
707 * FILE_FillInfo
709 * Fill a file information from a struct stat.
711 static void FILE_FillInfo( struct stat *st, BY_HANDLE_FILE_INFORMATION *info )
713 if (S_ISDIR(st->st_mode))
714 info->dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
715 else
716 info->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
717 if (!(st->st_mode & S_IWUSR))
718 info->dwFileAttributes |= FILE_ATTRIBUTE_READONLY;
720 RtlSecondsSince1970ToTime( st->st_mtime, (LARGE_INTEGER *)&info->ftCreationTime );
721 RtlSecondsSince1970ToTime( st->st_mtime, (LARGE_INTEGER *)&info->ftLastWriteTime );
722 RtlSecondsSince1970ToTime( st->st_atime, (LARGE_INTEGER *)&info->ftLastAccessTime );
724 info->dwVolumeSerialNumber = 0; /* FIXME */
725 info->nFileSizeHigh = 0;
726 info->nFileSizeLow = 0;
727 if (!S_ISDIR(st->st_mode)) {
728 info->nFileSizeHigh = st->st_size >> 32;
729 info->nFileSizeLow = st->st_size & 0xffffffff;
731 info->nNumberOfLinks = st->st_nlink;
732 info->nFileIndexHigh = 0;
733 info->nFileIndexLow = st->st_ino;
737 /***********************************************************************
738 * FILE_Stat
740 * Stat a Unix path name. Return TRUE if OK.
742 BOOL FILE_Stat( LPCSTR unixName, BY_HANDLE_FILE_INFORMATION *info, BOOL *is_symlink_ptr )
744 struct stat st;
745 int is_symlink;
746 LPCSTR p;
748 if (lstat( unixName, &st ) == -1)
750 FILE_SetDosError();
751 return FALSE;
753 is_symlink = S_ISLNK(st.st_mode);
754 if (is_symlink)
756 /* do a "real" stat to find out
757 about the type of the symlink destination */
758 if (stat( unixName, &st ) == -1)
760 FILE_SetDosError();
761 return FALSE;
765 /* fill in the information we gathered so far */
766 FILE_FillInfo( &st, info );
768 /* and now see if this is a hidden file, based on the name */
769 p = strrchr( unixName, '/');
770 p = p ? p + 1 : unixName;
771 if (*p == '.' && *(p+1) && (*(p+1) != '.' || *(p+2)))
773 static const WCHAR wineW[] = {'w','i','n','e',0};
774 static const WCHAR ShowDotFilesW[] = {'S','h','o','w','D','o','t','F','i','l','e','s',0};
775 static int show_dot_files = -1;
776 if (show_dot_files == -1)
777 show_dot_files = PROFILE_GetWineIniBool(wineW, ShowDotFilesW, 0);
778 if (!show_dot_files)
779 info->dwFileAttributes |= FILE_ATTRIBUTE_HIDDEN;
781 if (is_symlink_ptr) *is_symlink_ptr = is_symlink;
782 return TRUE;
786 /***********************************************************************
787 * GetFileInformationByHandle (KERNEL32.@)
789 DWORD WINAPI GetFileInformationByHandle( HANDLE hFile,
790 BY_HANDLE_FILE_INFORMATION *info )
792 DWORD ret;
793 if (!info) return 0;
795 TRACE("%p\n", hFile);
797 SERVER_START_REQ( get_file_info )
799 req->handle = hFile;
800 if ((ret = !wine_server_call_err( req )))
802 /* FIXME: which file types are supported ?
803 * Serial ports (FILE_TYPE_CHAR) are not,
804 * and MSDN also says that pipes are not supported.
805 * FILE_TYPE_REMOTE seems to be supported according to
806 * MSDN q234741.txt */
807 if ((reply->type == FILE_TYPE_DISK) || (reply->type == FILE_TYPE_REMOTE))
809 RtlSecondsSince1970ToTime( reply->write_time, (LARGE_INTEGER *)&info->ftCreationTime );
810 RtlSecondsSince1970ToTime( reply->write_time, (LARGE_INTEGER *)&info->ftLastWriteTime );
811 RtlSecondsSince1970ToTime( reply->access_time, (LARGE_INTEGER *)&info->ftLastAccessTime );
812 info->dwFileAttributes = reply->attr;
813 info->dwVolumeSerialNumber = reply->serial;
814 info->nFileSizeHigh = reply->size_high;
815 info->nFileSizeLow = reply->size_low;
816 info->nNumberOfLinks = reply->links;
817 info->nFileIndexHigh = reply->index_high;
818 info->nFileIndexLow = reply->index_low;
820 else
822 SetLastError(ERROR_NOT_SUPPORTED);
823 ret = 0;
827 SERVER_END_REQ;
828 return ret;
832 /**************************************************************************
833 * GetFileAttributes (KERNEL.420)
835 DWORD WINAPI GetFileAttributes16( LPCSTR name )
837 return GetFileAttributesA( name );
841 /**************************************************************************
842 * GetFileAttributesW (KERNEL32.@)
844 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
846 DOS_FULL_NAME full_name;
847 BY_HANDLE_FILE_INFORMATION info;
849 if (name == NULL)
851 SetLastError( ERROR_INVALID_PARAMETER );
852 return -1;
854 if (!DOSFS_GetFullName( name, TRUE, &full_name) )
855 return -1;
856 if (!FILE_Stat( full_name.long_name, &info, NULL )) return -1;
857 return info.dwFileAttributes;
861 /**************************************************************************
862 * GetFileAttributesA (KERNEL32.@)
864 DWORD WINAPI GetFileAttributesA( LPCSTR name )
866 UNICODE_STRING nameW;
867 DWORD ret = (DWORD)-1;
869 if (!name)
871 SetLastError( ERROR_INVALID_PARAMETER );
872 return (DWORD)-1;
875 if (RtlCreateUnicodeStringFromAsciiz(&nameW, name))
877 ret = GetFileAttributesW(nameW.Buffer);
878 RtlFreeUnicodeString(&nameW);
880 else
881 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
882 return ret;
886 /**************************************************************************
887 * SetFileAttributes (KERNEL.421)
889 BOOL16 WINAPI SetFileAttributes16( LPCSTR lpFileName, DWORD attributes )
891 return SetFileAttributesA( lpFileName, attributes );
895 /**************************************************************************
896 * SetFileAttributesW (KERNEL32.@)
898 BOOL WINAPI SetFileAttributesW(LPCWSTR lpFileName, DWORD attributes)
900 struct stat buf;
901 DOS_FULL_NAME full_name;
903 if (!lpFileName)
905 SetLastError( ERROR_INVALID_PARAMETER );
906 return FALSE;
909 TRACE("(%s,%lx)\n", debugstr_w(lpFileName), attributes);
911 if (!DOSFS_GetFullName( lpFileName, TRUE, &full_name ))
912 return FALSE;
914 if(stat(full_name.long_name,&buf)==-1)
916 FILE_SetDosError();
917 return FALSE;
919 if (attributes & FILE_ATTRIBUTE_READONLY)
921 if(S_ISDIR(buf.st_mode))
922 /* FIXME */
923 WARN("FILE_ATTRIBUTE_READONLY ignored for directory.\n");
924 else
925 buf.st_mode &= ~0222; /* octal!, clear write permission bits */
926 attributes &= ~FILE_ATTRIBUTE_READONLY;
928 else
930 /* add write permission */
931 buf.st_mode |= (0600 | ((buf.st_mode & 044) >> 1)) & (~FILE_umask);
933 if (attributes & FILE_ATTRIBUTE_DIRECTORY)
935 if (!S_ISDIR(buf.st_mode))
936 FIXME("SetFileAttributes expected the file %s to be a directory\n",
937 debugstr_w(lpFileName));
938 attributes &= ~FILE_ATTRIBUTE_DIRECTORY;
940 attributes &= ~(FILE_ATTRIBUTE_NORMAL|FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_HIDDEN|FILE_ATTRIBUTE_SYSTEM);
941 if (attributes)
942 FIXME("(%s):%lx attribute(s) not implemented.\n", debugstr_w(lpFileName), attributes);
943 if (-1==chmod(full_name.long_name,buf.st_mode))
945 if (GetDriveTypeW(lpFileName) == DRIVE_CDROM)
947 SetLastError( ERROR_ACCESS_DENIED );
948 return FALSE;
952 * FIXME: We don't return FALSE here because of differences between
953 * Linux and Windows privileges. Under Linux only the owner of
954 * the file is allowed to change file attributes. Under Windows,
955 * applications expect that if you can write to a file, you can also
956 * change its attributes (see GENERIC_WRITE). We could try to be
957 * clever here but that would break multi-user installations where
958 * users share read-only DLLs. This is because some installers like
959 * to change attributes of already installed DLLs.
961 FIXME("Couldn't set file attributes for existing file \"%s\".\n"
962 "Check permissions or set VFAT \"quiet\" mount flag\n", full_name.long_name);
964 return TRUE;
968 /**************************************************************************
969 * SetFileAttributesA (KERNEL32.@)
971 BOOL WINAPI SetFileAttributesA(LPCSTR lpFileName, DWORD attributes)
973 UNICODE_STRING filenameW;
974 BOOL ret = FALSE;
976 if (!lpFileName)
978 SetLastError( ERROR_INVALID_PARAMETER );
979 return FALSE;
982 if (RtlCreateUnicodeStringFromAsciiz(&filenameW, lpFileName))
984 ret = SetFileAttributesW(filenameW.Buffer, attributes);
985 RtlFreeUnicodeString(&filenameW);
987 else
988 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
989 return ret;
993 /***********************************************************************
994 * GetFileSize (KERNEL32.@)
996 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
998 BY_HANDLE_FILE_INFORMATION info;
999 if (!GetFileInformationByHandle( hFile, &info )) return -1;
1000 if (filesizehigh) *filesizehigh = info.nFileSizeHigh;
1001 return info.nFileSizeLow;
1005 /***********************************************************************
1006 * GetFileSizeEx (KERNEL32.@)
1008 BOOL WINAPI GetFileSizeEx( HANDLE hFile, PLARGE_INTEGER lpFileSize )
1010 BY_HANDLE_FILE_INFORMATION info;
1012 if (!lpFileSize)
1014 SetLastError( ERROR_INVALID_PARAMETER );
1015 return FALSE;
1018 if (!GetFileInformationByHandle( hFile, &info ))
1020 return FALSE;
1023 lpFileSize->s.LowPart = info.nFileSizeLow;
1024 lpFileSize->s.HighPart = info.nFileSizeHigh;
1026 return TRUE;
1030 /***********************************************************************
1031 * GetFileTime (KERNEL32.@)
1033 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
1034 FILETIME *lpLastAccessTime,
1035 FILETIME *lpLastWriteTime )
1037 BY_HANDLE_FILE_INFORMATION info;
1038 if (!GetFileInformationByHandle( hFile, &info )) return FALSE;
1039 if (lpCreationTime) *lpCreationTime = info.ftCreationTime;
1040 if (lpLastAccessTime) *lpLastAccessTime = info.ftLastAccessTime;
1041 if (lpLastWriteTime) *lpLastWriteTime = info.ftLastWriteTime;
1042 return TRUE;
1045 /***********************************************************************
1046 * FILE_GetTempFileName : utility for GetTempFileName
1048 static UINT FILE_GetTempFileName( LPCWSTR path, LPCWSTR prefix, UINT unique,
1049 LPWSTR buffer )
1051 static UINT unique_temp;
1052 DOS_FULL_NAME full_name;
1053 int i;
1054 LPWSTR p;
1055 UINT num;
1056 char buf[20];
1058 if ( !path || !prefix || !buffer )
1060 SetLastError( ERROR_INVALID_PARAMETER );
1061 return 0;
1064 if (!unique_temp) unique_temp = time(NULL) & 0xffff;
1065 num = unique ? (unique & 0xffff) : (unique_temp++ & 0xffff);
1067 strcpyW( buffer, path );
1068 p = buffer + strlenW(buffer);
1070 /* add a \, if there isn't one and path is more than just the drive letter ... */
1071 if ( !((strlenW(buffer) == 2) && (buffer[1] == ':'))
1072 && ((p == buffer) || (p[-1] != '\\'))) *p++ = '\\';
1074 for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
1076 sprintf( buf, "%04x.tmp", num );
1077 MultiByteToWideChar(CP_ACP, 0, buf, -1, p, 20);
1079 /* Now try to create it */
1081 if (!unique)
1085 HANDLE handle = CreateFileW( buffer, GENERIC_WRITE, 0, NULL,
1086 CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
1087 if (handle != INVALID_HANDLE_VALUE)
1088 { /* We created it */
1089 TRACE("created %s\n", debugstr_w(buffer) );
1090 CloseHandle( handle );
1091 break;
1093 if (GetLastError() != ERROR_FILE_EXISTS)
1094 break; /* No need to go on */
1095 num++;
1096 sprintf( buf, "%04x.tmp", num );
1097 MultiByteToWideChar(CP_ACP, 0, buf, -1, p, 20);
1098 } while (num != (unique & 0xffff));
1101 /* Get the full path name */
1103 if (DOSFS_GetFullName( buffer, FALSE, &full_name ))
1105 char *slash;
1106 /* Check if we have write access in the directory */
1107 if ((slash = strrchr( full_name.long_name, '/' ))) *slash = '\0';
1108 if (access( full_name.long_name, W_OK ) == -1)
1109 WARN("returns %s, which doesn't seem to be writeable.\n",
1110 debugstr_w(buffer) );
1112 TRACE("returning %s\n", debugstr_w(buffer) );
1113 return unique ? unique : num;
1117 /***********************************************************************
1118 * GetTempFileNameA (KERNEL32.@)
1120 UINT WINAPI GetTempFileNameA( LPCSTR path, LPCSTR prefix, UINT unique,
1121 LPSTR buffer)
1123 UNICODE_STRING pathW, prefixW;
1124 WCHAR bufferW[MAX_PATH];
1125 UINT ret;
1127 if ( !path || !prefix || !buffer )
1129 SetLastError( ERROR_INVALID_PARAMETER );
1130 return 0;
1133 RtlCreateUnicodeStringFromAsciiz(&pathW, path);
1134 RtlCreateUnicodeStringFromAsciiz(&prefixW, prefix);
1136 ret = GetTempFileNameW(pathW.Buffer, prefixW.Buffer, unique, bufferW);
1137 if (ret)
1138 WideCharToMultiByte(CP_ACP, 0, bufferW, -1, buffer, MAX_PATH, NULL, NULL);
1140 RtlFreeUnicodeString(&pathW);
1141 RtlFreeUnicodeString(&prefixW);
1142 return ret;
1145 /***********************************************************************
1146 * GetTempFileNameW (KERNEL32.@)
1148 UINT WINAPI GetTempFileNameW( LPCWSTR path, LPCWSTR prefix, UINT unique,
1149 LPWSTR buffer )
1151 return FILE_GetTempFileName( path, prefix, unique, buffer );
1155 /***********************************************************************
1156 * GetTempFileName (KERNEL.97)
1158 UINT16 WINAPI GetTempFileName16( BYTE drive, LPCSTR prefix, UINT16 unique,
1159 LPSTR buffer )
1161 char temppath[MAX_PATH];
1162 char *prefix16 = NULL;
1163 UINT16 ret;
1165 if (!(drive & ~TF_FORCEDRIVE)) /* drive 0 means current default drive */
1166 drive |= DRIVE_GetCurrentDrive() + 'A';
1168 if ((drive & TF_FORCEDRIVE) &&
1169 !DRIVE_IsValid( toupper(drive & ~TF_FORCEDRIVE) - 'A' ))
1171 drive &= ~TF_FORCEDRIVE;
1172 WARN("invalid drive %d specified\n", drive );
1175 if (drive & TF_FORCEDRIVE)
1176 sprintf(temppath,"%c:", drive & ~TF_FORCEDRIVE );
1177 else
1178 GetTempPathA( MAX_PATH, temppath );
1180 if (prefix)
1182 prefix16 = HeapAlloc(GetProcessHeap(), 0, strlen(prefix) + 2);
1183 *prefix16 = '~';
1184 strcpy(prefix16 + 1, prefix);
1187 ret = GetTempFileNameA( temppath, prefix16, unique, buffer );
1189 if (prefix16) HeapFree(GetProcessHeap(), 0, prefix16);
1190 return ret;
1193 /***********************************************************************
1194 * FILE_DoOpenFile
1196 * Implementation of OpenFile16() and OpenFile32().
1198 static HFILE FILE_DoOpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode,
1199 BOOL win32 )
1201 HFILE hFileRet;
1202 HANDLE handle;
1203 FILETIME filetime;
1204 WORD filedatetime[2];
1205 DOS_FULL_NAME full_name;
1206 DWORD access, sharing;
1207 WCHAR *p;
1208 WCHAR buffer[MAX_PATH];
1209 LPWSTR nameW;
1211 if (!ofs) return HFILE_ERROR;
1213 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
1214 ((mode & 0x3 )==OF_READ)?"OF_READ":
1215 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
1216 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
1217 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
1218 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
1219 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
1220 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
1221 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
1222 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
1223 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
1224 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
1225 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
1226 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
1227 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
1228 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
1229 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
1230 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
1234 ofs->cBytes = sizeof(OFSTRUCT);
1235 ofs->nErrCode = 0;
1236 if (mode & OF_REOPEN) name = ofs->szPathName;
1238 if (!name) {
1239 ERR("called with `name' set to NULL ! Please debug.\n");
1240 return HFILE_ERROR;
1243 TRACE("%s %04x\n", name, mode );
1245 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
1246 Are there any cases where getting the path here is wrong?
1247 Uwe Bonnes 1997 Apr 2 */
1248 if (!GetFullPathNameA( name, sizeof(ofs->szPathName),
1249 ofs->szPathName, NULL )) goto error;
1250 FILE_ConvertOFMode( mode, &access, &sharing );
1252 /* OF_PARSE simply fills the structure */
1254 if (mode & OF_PARSE)
1256 ofs->fFixedDisk = (GetDriveType16( ofs->szPathName[0]-'A' )
1257 != DRIVE_REMOVABLE);
1258 TRACE("(%s): OF_PARSE, res = '%s'\n",
1259 name, ofs->szPathName );
1260 return 0;
1263 /* OF_CREATE is completely different from all other options, so
1264 handle it first */
1266 if (mode & OF_CREATE)
1268 if ((handle = CreateFileA( name, GENERIC_READ | GENERIC_WRITE,
1269 sharing, NULL, CREATE_ALWAYS,
1270 FILE_ATTRIBUTE_NORMAL, 0 ))== INVALID_HANDLE_VALUE)
1271 goto error;
1272 goto success;
1275 MultiByteToWideChar(CP_ACP, 0, name, -1, buffer, MAX_PATH);
1276 nameW = buffer;
1278 /* If OF_SEARCH is set, ignore the given path */
1280 if ((mode & OF_SEARCH) && !(mode & OF_REOPEN))
1282 /* First try the file name as is */
1283 if (DOSFS_GetFullName( nameW, TRUE, &full_name )) goto found;
1284 /* Now remove the path */
1285 if (nameW[0] && (nameW[1] == ':')) nameW += 2;
1286 if ((p = strrchrW( nameW, '\\' ))) nameW = p + 1;
1287 if ((p = strrchrW( nameW, '/' ))) nameW = p + 1;
1288 if (!nameW[0]) goto not_found;
1291 /* Now look for the file */
1293 if (!DIR_SearchPath( NULL, nameW, NULL, &full_name, win32 )) goto not_found;
1295 found:
1296 TRACE("found %s = %s\n",
1297 full_name.long_name, debugstr_w(full_name.short_name) );
1298 WideCharToMultiByte(CP_ACP, 0, full_name.short_name, -1,
1299 ofs->szPathName, sizeof(ofs->szPathName), NULL, NULL);
1301 if (mode & OF_SHARE_EXCLUSIVE)
1302 /* Some InstallShield version uses OF_SHARE_EXCLUSIVE
1303 on the file <tempdir>/_ins0432._mp to determine how
1304 far installation has proceeded.
1305 _ins0432._mp is an executable and while running the
1306 application expects the open with OF_SHARE_ to fail*/
1307 /* Probable FIXME:
1308 As our loader closes the files after loading the executable,
1309 we can't find the running executable with FILE_InUse.
1310 The loader should keep the file open, as Windows does that, too.
1313 char *last = strrchr(full_name.long_name,'/');
1314 if (!last)
1315 last = full_name.long_name - 1;
1316 if (GetModuleHandle16(last+1))
1318 TRACE("Denying shared open for %s\n",full_name.long_name);
1319 return HFILE_ERROR;
1323 if (mode & OF_DELETE)
1325 if (unlink( full_name.long_name ) == -1) goto not_found;
1326 TRACE("(%s): OF_DELETE return = OK\n", name);
1327 return 1;
1330 handle = FILE_CreateFile( full_name.long_name, access, sharing,
1331 NULL, OPEN_EXISTING, 0, 0,
1332 DRIVE_GetFlags(full_name.drive) & DRIVE_FAIL_READ_ONLY,
1333 GetDriveTypeW( full_name.short_name ) );
1334 if (!handle) goto not_found;
1336 GetFileTime( handle, NULL, NULL, &filetime );
1337 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
1338 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
1340 if (ofs->Reserved1 != filedatetime[0] || ofs->Reserved2 != filedatetime[1] )
1342 CloseHandle( handle );
1343 WARN("(%s): OF_VERIFY failed\n", name );
1344 /* FIXME: what error here? */
1345 SetLastError( ERROR_FILE_NOT_FOUND );
1346 goto error;
1349 ofs->Reserved1 = filedatetime[0];
1350 ofs->Reserved2 = filedatetime[1];
1352 success: /* We get here if the open was successful */
1353 TRACE("(%s): OK, return = %p\n", name, handle );
1354 if (win32)
1356 hFileRet = (HFILE)handle;
1357 if (mode & OF_EXIST) /* Return the handle, but close it first */
1358 CloseHandle( handle );
1360 else
1362 hFileRet = Win32HandleToDosFileHandle( handle );
1363 if (hFileRet == HFILE_ERROR16) goto error;
1364 if (mode & OF_EXIST) /* Return the handle, but close it first */
1365 _lclose16( hFileRet );
1367 return hFileRet;
1369 not_found: /* We get here if the file does not exist */
1370 WARN("'%s' not found or sharing violation\n", name );
1371 SetLastError( ERROR_FILE_NOT_FOUND );
1372 /* fall through */
1374 error: /* We get here if there was an error opening the file */
1375 ofs->nErrCode = GetLastError();
1376 WARN("(%s): return = HFILE_ERROR error= %d\n",
1377 name,ofs->nErrCode );
1378 return HFILE_ERROR;
1382 /***********************************************************************
1383 * OpenFile (KERNEL.74)
1384 * OpenFileEx (KERNEL.360)
1386 HFILE16 WINAPI OpenFile16( LPCSTR name, OFSTRUCT *ofs, UINT16 mode )
1388 return FILE_DoOpenFile( name, ofs, mode, FALSE );
1392 /***********************************************************************
1393 * OpenFile (KERNEL32.@)
1395 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
1397 return FILE_DoOpenFile( name, ofs, mode, TRUE );
1401 /***********************************************************************
1402 * FILE_InitProcessDosHandles
1404 * Allocates the default DOS handles for a process. Called either by
1405 * Win32HandleToDosFileHandle below or by the DOSVM stuff.
1407 static void FILE_InitProcessDosHandles( void )
1409 HANDLE cp = GetCurrentProcess();
1410 DuplicateHandle(cp, GetStdHandle(STD_INPUT_HANDLE), cp, &dos_handles[0],
1411 0, TRUE, DUPLICATE_SAME_ACCESS);
1412 DuplicateHandle(cp, GetStdHandle(STD_OUTPUT_HANDLE), cp, &dos_handles[1],
1413 0, TRUE, DUPLICATE_SAME_ACCESS);
1414 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[2],
1415 0, TRUE, DUPLICATE_SAME_ACCESS);
1416 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[3],
1417 0, TRUE, DUPLICATE_SAME_ACCESS);
1418 DuplicateHandle(cp, GetStdHandle(STD_ERROR_HANDLE), cp, &dos_handles[4],
1419 0, TRUE, DUPLICATE_SAME_ACCESS);
1422 /***********************************************************************
1423 * Win32HandleToDosFileHandle (KERNEL32.21)
1425 * Allocate a DOS handle for a Win32 handle. The Win32 handle is no
1426 * longer valid after this function (even on failure).
1428 * Note: this is not exactly right, since on Win95 the Win32 handles
1429 * are on top of DOS handles and we do it the other way
1430 * around. Should be good enough though.
1432 HFILE WINAPI Win32HandleToDosFileHandle( HANDLE handle )
1434 int i;
1436 if (!handle || (handle == INVALID_HANDLE_VALUE))
1437 return HFILE_ERROR;
1439 for (i = 5; i < DOS_TABLE_SIZE; i++)
1440 if (!dos_handles[i])
1442 dos_handles[i] = handle;
1443 TRACE("Got %d for h32 %p\n", i, handle );
1444 return (HFILE)i;
1446 CloseHandle( handle );
1447 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1448 return HFILE_ERROR;
1452 /***********************************************************************
1453 * DosFileHandleToWin32Handle (KERNEL32.20)
1455 * Return the Win32 handle for a DOS handle.
1457 * Note: this is not exactly right, since on Win95 the Win32 handles
1458 * are on top of DOS handles and we do it the other way
1459 * around. Should be good enough though.
1461 HANDLE WINAPI DosFileHandleToWin32Handle( HFILE handle )
1463 HFILE16 hfile = (HFILE16)handle;
1464 if (hfile < 5 && !dos_handles[hfile]) FILE_InitProcessDosHandles();
1465 if ((hfile >= DOS_TABLE_SIZE) || !dos_handles[hfile])
1467 SetLastError( ERROR_INVALID_HANDLE );
1468 return INVALID_HANDLE_VALUE;
1470 return dos_handles[hfile];
1474 /***********************************************************************
1475 * DisposeLZ32Handle (KERNEL32.22)
1477 * Note: this is not entirely correct, we should only close the
1478 * 32-bit handle and not the 16-bit one, but we cannot do
1479 * this because of the way our DOS handles are implemented.
1480 * It shouldn't break anything though.
1482 void WINAPI DisposeLZ32Handle( HANDLE handle )
1484 int i;
1486 if (!handle || (handle == INVALID_HANDLE_VALUE)) return;
1488 for (i = 5; i < DOS_TABLE_SIZE; i++)
1489 if (dos_handles[i] == handle)
1491 dos_handles[i] = 0;
1492 CloseHandle( handle );
1493 break;
1498 /***********************************************************************
1499 * FILE_Dup2
1501 * dup2() function for DOS handles.
1503 HFILE16 FILE_Dup2( HFILE16 hFile1, HFILE16 hFile2 )
1505 HANDLE new_handle;
1507 if (hFile1 < 5 && !dos_handles[hFile1]) FILE_InitProcessDosHandles();
1509 if ((hFile1 >= DOS_TABLE_SIZE) || (hFile2 >= DOS_TABLE_SIZE) || !dos_handles[hFile1])
1511 SetLastError( ERROR_INVALID_HANDLE );
1512 return HFILE_ERROR16;
1514 if (!DuplicateHandle( GetCurrentProcess(), dos_handles[hFile1],
1515 GetCurrentProcess(), &new_handle,
1516 0, FALSE, DUPLICATE_SAME_ACCESS ))
1517 return HFILE_ERROR16;
1518 if (dos_handles[hFile2]) CloseHandle( dos_handles[hFile2] );
1519 dos_handles[hFile2] = new_handle;
1520 return hFile2;
1524 /***********************************************************************
1525 * _lclose (KERNEL.81)
1527 HFILE16 WINAPI _lclose16( HFILE16 hFile )
1529 if ((hFile >= DOS_TABLE_SIZE) || !dos_handles[hFile])
1531 SetLastError( ERROR_INVALID_HANDLE );
1532 return HFILE_ERROR16;
1534 TRACE("%d (handle32=%p)\n", hFile, dos_handles[hFile] );
1535 CloseHandle( dos_handles[hFile] );
1536 dos_handles[hFile] = 0;
1537 return 0;
1541 /***********************************************************************
1542 * _lclose (KERNEL32.@)
1544 HFILE WINAPI _lclose( HFILE hFile )
1546 TRACE("handle %d\n", hFile );
1547 return CloseHandle( (HANDLE)hFile ) ? 0 : HFILE_ERROR;
1550 /***********************************************************************
1551 * GetOverlappedResult (KERNEL32.@)
1553 * Check the result of an Asynchronous data transfer from a file.
1555 * RETURNS
1556 * TRUE on success
1557 * FALSE on failure
1559 * If successful (and relevant) lpTransferred will hold the number of
1560 * bytes transferred during the async operation.
1562 * BUGS
1564 * Currently only works for WaitCommEvent, ReadFile, WriteFile
1565 * with communications ports.
1568 BOOL WINAPI GetOverlappedResult(
1569 HANDLE hFile, /* [in] handle of file to check on */
1570 LPOVERLAPPED lpOverlapped, /* [in/out] pointer to overlapped */
1571 LPDWORD lpTransferred, /* [in/out] number of bytes transferred */
1572 BOOL bWait /* [in] wait for the transfer to complete ? */
1574 DWORD r;
1576 TRACE("(%p %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait);
1578 if(lpOverlapped==NULL)
1580 ERR("lpOverlapped was null\n");
1581 return FALSE;
1583 if(!lpOverlapped->hEvent)
1585 ERR("lpOverlapped->hEvent was null\n");
1586 return FALSE;
1589 if ( bWait )
1591 do {
1592 TRACE("waiting on %p\n",lpOverlapped);
1593 r = WaitForSingleObjectEx(lpOverlapped->hEvent, INFINITE, TRUE);
1594 TRACE("wait on %p returned %ld\n",lpOverlapped,r);
1595 } while (r==STATUS_USER_APC);
1597 else if ( lpOverlapped->Internal == STATUS_PENDING )
1599 /* Wait in order to give APCs a chance to run. */
1600 /* This is cheating, so we must set the event again in case of success -
1601 it may be a non-manual reset event. */
1602 do {
1603 TRACE("waiting on %p\n",lpOverlapped);
1604 r = WaitForSingleObjectEx(lpOverlapped->hEvent, 0, TRUE);
1605 TRACE("wait on %p returned %ld\n",lpOverlapped,r);
1606 } while (r==STATUS_USER_APC);
1607 if ( r == WAIT_OBJECT_0 )
1608 NtSetEvent ( lpOverlapped->hEvent, NULL );
1611 if(lpTransferred)
1612 *lpTransferred = lpOverlapped->InternalHigh;
1614 switch ( lpOverlapped->Internal )
1616 case STATUS_SUCCESS:
1617 return TRUE;
1618 case STATUS_PENDING:
1619 SetLastError ( ERROR_IO_INCOMPLETE );
1620 if ( bWait ) ERR ("PENDING status after waiting!\n");
1621 return FALSE;
1622 default:
1623 SetLastError ( RtlNtStatusToDosError ( lpOverlapped->Internal ) );
1624 return FALSE;
1628 /***********************************************************************
1629 * CancelIo (KERNEL32.@)
1631 BOOL WINAPI CancelIo(HANDLE handle)
1633 async_private *ovp,*t;
1635 TRACE("handle = %p\n",handle);
1637 for (ovp = NtCurrentTeb()->pending_list; ovp; ovp = t)
1639 t = ovp->next;
1640 if ( ovp->handle == handle )
1641 cancel_async ( ovp );
1643 WaitForMultipleObjectsEx(0,NULL,FALSE,1,TRUE);
1644 return TRUE;
1647 /***********************************************************************
1648 * FILE_AsyncReadService (INTERNAL)
1650 * This function is called while the client is waiting on the
1651 * server, so we can't make any server calls here.
1653 static void FILE_AsyncReadService(async_private *ovp)
1655 async_fileio *fileio = (async_fileio*) ovp;
1656 LPOVERLAPPED lpOverlapped = fileio->lpOverlapped;
1657 int result, r;
1658 int already = lpOverlapped->InternalHigh;
1660 TRACE("%p %p\n", lpOverlapped, fileio->buffer );
1662 /* check to see if the data is ready (non-blocking) */
1664 if ( fileio->fd_type == FD_TYPE_SOCKET )
1665 result = read (ovp->fd, &fileio->buffer[already], fileio->count - already);
1666 else
1668 result = pread (ovp->fd, &fileio->buffer[already], fileio->count - already,
1669 OVERLAPPED_OFFSET (lpOverlapped) + already);
1670 if ((result < 0) && (errno == ESPIPE))
1671 result = read (ovp->fd, &fileio->buffer[already], fileio->count - already);
1674 if ( (result<0) && ((errno == EAGAIN) || (errno == EINTR)))
1676 TRACE("Deferred read %d\n",errno);
1677 r = STATUS_PENDING;
1678 goto async_end;
1681 /* check to see if the transfer is complete */
1682 if(result<0)
1684 r = FILE_GetNtStatus ();
1685 goto async_end;
1687 else if ( result == 0 )
1689 r = ( lpOverlapped->InternalHigh ? STATUS_SUCCESS : STATUS_END_OF_FILE );
1690 goto async_end;
1693 lpOverlapped->InternalHigh += result;
1694 TRACE("read %d more bytes %ld/%d so far\n",result,lpOverlapped->InternalHigh,fileio->count);
1696 if(lpOverlapped->InternalHigh >= fileio->count || fileio->fd_type == FD_TYPE_SOCKET )
1697 r = STATUS_SUCCESS;
1698 else
1699 r = STATUS_PENDING;
1701 async_end:
1702 lpOverlapped->Internal = r;
1705 /***********************************************************************
1706 * FILE_ReadFileEx (INTERNAL)
1708 static BOOL FILE_ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
1709 LPOVERLAPPED overlapped,
1710 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
1711 HANDLE hEvent)
1713 async_fileio *ovp;
1714 int fd;
1715 int flags;
1716 enum fd_type type;
1718 TRACE("file %p to buf %p num %ld %p func %p\n",
1719 hFile, buffer, bytesToRead, overlapped, lpCompletionRoutine);
1721 /* check that there is an overlapped struct */
1722 if (overlapped==NULL)
1724 SetLastError(ERROR_INVALID_PARAMETER);
1725 return FALSE;
1728 fd = FILE_GetUnixHandleType ( hFile, GENERIC_READ, &type, &flags);
1729 if ( fd < 0 )
1731 WARN ( "Couldn't get FD\n" );
1732 return FALSE;
1735 ovp = (async_fileio*) HeapAlloc(GetProcessHeap(), 0, sizeof (async_fileio));
1736 if(!ovp)
1738 TRACE("HeapAlloc Failed\n");
1739 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1740 goto error;
1743 ovp->async.ops = ( lpCompletionRoutine ? &fileio_async_ops : &fileio_nocomp_async_ops );
1744 ovp->async.handle = hFile;
1745 ovp->async.fd = fd;
1746 ovp->async.type = ASYNC_TYPE_READ;
1747 ovp->async.func = FILE_AsyncReadService;
1748 ovp->async.event = hEvent;
1749 ovp->lpOverlapped = overlapped;
1750 ovp->count = bytesToRead;
1751 ovp->completion_func = lpCompletionRoutine;
1752 ovp->buffer = buffer;
1753 ovp->fd_type = type;
1755 return !register_new_async (&ovp->async);
1757 error:
1758 close (fd);
1759 return FALSE;
1763 /***********************************************************************
1764 * ReadFileEx (KERNEL32.@)
1766 BOOL WINAPI ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
1767 LPOVERLAPPED overlapped,
1768 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
1770 overlapped->InternalHigh = 0;
1771 return FILE_ReadFileEx(hFile,buffer,bytesToRead,overlapped,lpCompletionRoutine, INVALID_HANDLE_VALUE);
1774 static BOOL FILE_TimeoutRead(HANDLE hFile, LPVOID buffer, DWORD bytesToRead, LPDWORD bytesRead)
1776 OVERLAPPED ov;
1777 BOOL r = FALSE;
1779 TRACE("%p %p %ld %p\n", hFile, buffer, bytesToRead, bytesRead );
1781 ZeroMemory(&ov, sizeof (OVERLAPPED));
1782 if(STATUS_SUCCESS==NtCreateEvent(&ov.hEvent, SYNCHRONIZE, NULL, 0, 0))
1784 if(FILE_ReadFileEx(hFile, buffer, bytesToRead, &ov, NULL, ov.hEvent))
1786 r = GetOverlappedResult(hFile, &ov, bytesRead, TRUE);
1789 CloseHandle(ov.hEvent);
1790 return r;
1793 /***********************************************************************
1794 * ReadFile (KERNEL32.@)
1796 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
1797 LPDWORD bytesRead, LPOVERLAPPED overlapped )
1799 int unix_handle, result, flags;
1800 enum fd_type type;
1802 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToRead,
1803 bytesRead, overlapped );
1805 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
1806 if (!bytesToRead) return TRUE;
1808 unix_handle = FILE_GetUnixHandleType( hFile, GENERIC_READ, &type, &flags );
1810 if (flags & FD_FLAG_OVERLAPPED)
1812 if (unix_handle == -1) return FALSE;
1813 if ( (overlapped==NULL) || NtResetEvent( overlapped->hEvent, NULL ) )
1815 TRACE("Overlapped not specified or invalid event flag\n");
1816 close(unix_handle);
1817 SetLastError(ERROR_INVALID_PARAMETER);
1818 return FALSE;
1821 close(unix_handle);
1822 overlapped->InternalHigh = 0;
1824 if(!FILE_ReadFileEx(hFile, buffer, bytesToRead, overlapped, NULL, overlapped->hEvent))
1825 return FALSE;
1827 if ( !GetOverlappedResult (hFile, overlapped, bytesRead, FALSE) )
1829 if ( GetLastError() == ERROR_IO_INCOMPLETE )
1830 SetLastError ( ERROR_IO_PENDING );
1831 return FALSE;
1834 return TRUE;
1836 if (flags & FD_FLAG_TIMEOUT)
1838 close(unix_handle);
1839 return FILE_TimeoutRead(hFile, buffer, bytesToRead, bytesRead);
1841 switch(type)
1843 case FD_TYPE_SMB:
1844 return SMB_ReadFile(hFile, buffer, bytesToRead, bytesRead, NULL);
1846 case FD_TYPE_CONSOLE:
1847 return FILE_ReadConsole(hFile, buffer, bytesToRead, bytesRead, NULL);
1849 case FD_TYPE_DEFAULT:
1850 /* normal unix files */
1851 if (unix_handle == -1) return FALSE;
1852 if (overlapped)
1854 DWORD highOffset = overlapped->OffsetHigh;
1855 if ( (INVALID_SET_FILE_POINTER == SetFilePointer(hFile, overlapped->Offset,
1856 &highOffset, FILE_BEGIN)) &&
1857 (GetLastError() != NO_ERROR) )
1859 close(unix_handle);
1860 return FALSE;
1863 break;
1865 default:
1866 if (unix_handle == -1)
1867 return FALSE;
1870 if(overlapped)
1872 off_t offset = OVERLAPPED_OFFSET(overlapped);
1873 if(lseek(unix_handle, offset, SEEK_SET) == -1)
1875 close(unix_handle);
1876 SetLastError(ERROR_INVALID_PARAMETER);
1877 return FALSE;
1881 /* code for synchronous reads */
1882 while ((result = read( unix_handle, buffer, bytesToRead )) == -1)
1884 if ((errno == EAGAIN) || (errno == EINTR)) continue;
1885 if ((errno == EFAULT) && !IsBadWritePtr( buffer, bytesToRead )) continue;
1886 FILE_SetDosError();
1887 break;
1889 close( unix_handle );
1890 if (result == -1) return FALSE;
1891 if (bytesRead) *bytesRead = result;
1892 return TRUE;
1896 /***********************************************************************
1897 * FILE_AsyncWriteService (INTERNAL)
1899 * This function is called while the client is waiting on the
1900 * server, so we can't make any server calls here.
1902 static void FILE_AsyncWriteService(struct async_private *ovp)
1904 async_fileio *fileio = (async_fileio *) ovp;
1905 LPOVERLAPPED lpOverlapped = fileio->lpOverlapped;
1906 int result, r;
1907 int already = lpOverlapped->InternalHigh;
1909 TRACE("(%p %p)\n",lpOverlapped,fileio->buffer);
1911 /* write some data (non-blocking) */
1913 if ( fileio->fd_type == FD_TYPE_SOCKET )
1914 result = write(ovp->fd, &fileio->buffer[already], fileio->count - already);
1915 else
1917 result = pwrite(ovp->fd, &fileio->buffer[already], fileio->count - already,
1918 OVERLAPPED_OFFSET (lpOverlapped) + already);
1919 if ((result < 0) && (errno == ESPIPE))
1920 result = write(ovp->fd, &fileio->buffer[already], fileio->count - already);
1923 if ( (result<0) && ((errno == EAGAIN) || (errno == EINTR)))
1925 r = STATUS_PENDING;
1926 goto async_end;
1929 /* check to see if the transfer is complete */
1930 if(result<0)
1932 r = FILE_GetNtStatus ();
1933 goto async_end;
1936 lpOverlapped->InternalHigh += result;
1938 TRACE("wrote %d more bytes %ld/%d so far\n",result,lpOverlapped->InternalHigh,fileio->count);
1940 if(lpOverlapped->InternalHigh < fileio->count)
1941 r = STATUS_PENDING;
1942 else
1943 r = STATUS_SUCCESS;
1945 async_end:
1946 lpOverlapped->Internal = r;
1949 /***********************************************************************
1950 * FILE_WriteFileEx
1952 static BOOL FILE_WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
1953 LPOVERLAPPED overlapped,
1954 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine,
1955 HANDLE hEvent)
1957 async_fileio *ovp;
1958 int fd;
1959 int flags;
1960 enum fd_type type;
1962 TRACE("file %p to buf %p num %ld %p func %p handle %p\n",
1963 hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine, hEvent);
1965 if (overlapped == NULL)
1967 SetLastError(ERROR_INVALID_PARAMETER);
1968 return FALSE;
1971 fd = FILE_GetUnixHandleType ( hFile, GENERIC_WRITE, &type, &flags );
1972 if ( fd < 0 )
1974 TRACE( "Couldn't get FD\n" );
1975 return FALSE;
1978 ovp = (async_fileio*) HeapAlloc(GetProcessHeap(), 0, sizeof (async_fileio));
1979 if(!ovp)
1981 TRACE("HeapAlloc Failed\n");
1982 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1983 goto error;
1986 ovp->async.ops = ( lpCompletionRoutine ? &fileio_async_ops : &fileio_nocomp_async_ops );
1987 ovp->async.handle = hFile;
1988 ovp->async.fd = fd;
1989 ovp->async.type = ASYNC_TYPE_WRITE;
1990 ovp->async.func = FILE_AsyncWriteService;
1991 ovp->lpOverlapped = overlapped;
1992 ovp->async.event = hEvent;
1993 ovp->buffer = (LPVOID) buffer;
1994 ovp->count = bytesToWrite;
1995 ovp->completion_func = lpCompletionRoutine;
1996 ovp->fd_type = type;
1998 return !register_new_async (&ovp->async);
2000 error:
2001 close (fd);
2002 return FALSE;
2005 /***********************************************************************
2006 * WriteFileEx (KERNEL32.@)
2008 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
2009 LPOVERLAPPED overlapped,
2010 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
2012 overlapped->InternalHigh = 0;
2014 return FILE_WriteFileEx(hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine, INVALID_HANDLE_VALUE);
2017 /***********************************************************************
2018 * WriteFile (KERNEL32.@)
2020 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
2021 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
2023 int unix_handle, result, flags;
2024 enum fd_type type;
2026 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToWrite,
2027 bytesWritten, overlapped );
2029 if (bytesWritten) *bytesWritten = 0; /* Do this before anything else */
2030 if (!bytesToWrite) return TRUE;
2032 unix_handle = FILE_GetUnixHandleType( hFile, GENERIC_WRITE, &type, &flags );
2034 if (flags & FD_FLAG_OVERLAPPED)
2036 if (unix_handle == -1) return FALSE;
2037 if ( (overlapped==NULL) || NtResetEvent( overlapped->hEvent, NULL ) )
2039 TRACE("Overlapped not specified or invalid event flag\n");
2040 close(unix_handle);
2041 SetLastError(ERROR_INVALID_PARAMETER);
2042 return FALSE;
2045 close(unix_handle);
2046 overlapped->InternalHigh = 0;
2048 if(!FILE_WriteFileEx(hFile, buffer, bytesToWrite, overlapped, NULL, overlapped->hEvent))
2049 return FALSE;
2051 if ( !GetOverlappedResult (hFile, overlapped, bytesWritten, FALSE) )
2053 if ( GetLastError() == ERROR_IO_INCOMPLETE )
2054 SetLastError ( ERROR_IO_PENDING );
2055 return FALSE;
2058 return TRUE;
2061 switch(type)
2063 case FD_TYPE_CONSOLE:
2064 TRACE("%p %s %ld %p %p\n", hFile, debugstr_an(buffer, bytesToWrite), bytesToWrite,
2065 bytesWritten, overlapped );
2066 return FILE_WriteConsole(hFile, buffer, bytesToWrite, bytesWritten, NULL);
2068 case FD_TYPE_DEFAULT:
2069 if (unix_handle == -1) return FALSE;
2071 if(overlapped)
2073 DWORD highOffset = overlapped->OffsetHigh;
2074 if ( (INVALID_SET_FILE_POINTER == SetFilePointer(hFile, overlapped->Offset,
2075 &highOffset, FILE_BEGIN)) &&
2076 (GetLastError() != NO_ERROR) )
2078 close(unix_handle);
2079 return FALSE;
2082 break;
2084 default:
2085 if (unix_handle == -1)
2086 return FALSE;
2087 if (overlapped)
2089 close(unix_handle);
2090 SetLastError(ERROR_INVALID_PARAMETER);
2091 return FALSE;
2093 break;
2096 if(overlapped)
2098 off_t offset = OVERLAPPED_OFFSET(overlapped);
2099 if(lseek(unix_handle, offset, SEEK_SET) == -1)
2101 close(unix_handle);
2102 SetLastError(ERROR_INVALID_PARAMETER);
2103 return FALSE;
2107 /* synchronous file write */
2108 while ((result = write( unix_handle, buffer, bytesToWrite )) == -1)
2110 if ((errno == EAGAIN) || (errno == EINTR)) continue;
2111 if ((errno == EFAULT) && !IsBadReadPtr( buffer, bytesToWrite )) continue;
2112 if (errno == ENOSPC)
2113 SetLastError( ERROR_DISK_FULL );
2114 else
2115 FILE_SetDosError();
2116 break;
2118 close( unix_handle );
2119 if (result == -1) return FALSE;
2120 if (bytesWritten) *bytesWritten = result;
2121 return TRUE;
2125 /***********************************************************************
2126 * _hread (KERNEL.349)
2128 LONG WINAPI WIN16_hread( HFILE16 hFile, SEGPTR buffer, LONG count )
2130 LONG maxlen;
2132 TRACE("%d %08lx %ld\n",
2133 hFile, (DWORD)buffer, count );
2135 /* Some programs pass a count larger than the allocated buffer */
2136 maxlen = GetSelectorLimit16( SELECTOROF(buffer) ) - OFFSETOF(buffer) + 1;
2137 if (count > maxlen) count = maxlen;
2138 return _lread((HFILE)DosFileHandleToWin32Handle(hFile), MapSL(buffer), count );
2142 /***********************************************************************
2143 * _lread (KERNEL.82)
2145 UINT16 WINAPI WIN16_lread( HFILE16 hFile, SEGPTR buffer, UINT16 count )
2147 return (UINT16)WIN16_hread( hFile, buffer, (LONG)count );
2151 /***********************************************************************
2152 * _lread (KERNEL32.@)
2154 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
2156 DWORD result;
2157 if (!ReadFile( (HANDLE)handle, buffer, count, &result, NULL )) return -1;
2158 return result;
2162 /***********************************************************************
2163 * _lread16 (KERNEL.82)
2165 UINT16 WINAPI _lread16( HFILE16 hFile, LPVOID buffer, UINT16 count )
2167 return (UINT16)_lread((HFILE)DosFileHandleToWin32Handle(hFile), buffer, (LONG)count );
2171 /***********************************************************************
2172 * _lcreat (KERNEL.83)
2174 HFILE16 WINAPI _lcreat16( LPCSTR path, INT16 attr )
2176 return Win32HandleToDosFileHandle( (HANDLE)_lcreat( path, attr ) );
2180 /***********************************************************************
2181 * _lcreat (KERNEL32.@)
2183 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
2185 /* Mask off all flags not explicitly allowed by the doc */
2186 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
2187 TRACE("%s %02x\n", path, attr );
2188 return (HFILE)CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
2189 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
2190 CREATE_ALWAYS, attr, 0 );
2194 /***********************************************************************
2195 * SetFilePointer (KERNEL32.@)
2197 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword,
2198 DWORD method )
2200 DWORD ret = INVALID_SET_FILE_POINTER;
2202 TRACE("handle %p offset %ld high %ld origin %ld\n",
2203 hFile, distance, highword?*highword:0, method );
2205 SERVER_START_REQ( set_file_pointer )
2207 req->handle = hFile;
2208 req->low = distance;
2209 req->high = highword ? *highword : (distance >= 0) ? 0 : -1;
2210 /* FIXME: assumes 1:1 mapping between Windows and Unix seek constants */
2211 req->whence = method;
2212 SetLastError( 0 );
2213 if (!wine_server_call_err( req ))
2215 ret = reply->new_low;
2216 if (highword) *highword = reply->new_high;
2219 SERVER_END_REQ;
2220 return ret;
2224 /***********************************************************************
2225 * _llseek (KERNEL.84)
2227 * FIXME:
2228 * Seeking before the start of the file should be allowed for _llseek16,
2229 * but cause subsequent I/O operations to fail (cf. interrupt list)
2232 LONG WINAPI _llseek16( HFILE16 hFile, LONG lOffset, INT16 nOrigin )
2234 return SetFilePointer( DosFileHandleToWin32Handle(hFile), lOffset, NULL, nOrigin );
2238 /***********************************************************************
2239 * _llseek (KERNEL32.@)
2241 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
2243 return SetFilePointer( (HANDLE)hFile, lOffset, NULL, nOrigin );
2247 /***********************************************************************
2248 * _lopen (KERNEL.85)
2250 HFILE16 WINAPI _lopen16( LPCSTR path, INT16 mode )
2252 return Win32HandleToDosFileHandle( (HANDLE)_lopen( path, mode ) );
2256 /***********************************************************************
2257 * _lopen (KERNEL32.@)
2259 HFILE WINAPI _lopen( LPCSTR path, INT mode )
2261 DWORD access, sharing;
2263 TRACE("('%s',%04x)\n", path, mode );
2264 FILE_ConvertOFMode( mode, &access, &sharing );
2265 return (HFILE)CreateFileA( path, access, sharing, NULL, OPEN_EXISTING, 0, 0 );
2269 /***********************************************************************
2270 * _lwrite (KERNEL.86)
2272 UINT16 WINAPI _lwrite16( HFILE16 hFile, LPCSTR buffer, UINT16 count )
2274 return (UINT16)_hwrite( (HFILE)DosFileHandleToWin32Handle(hFile), buffer, (LONG)count );
2277 /***********************************************************************
2278 * _lwrite (KERNEL32.@)
2280 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
2282 return (UINT)_hwrite( hFile, buffer, (LONG)count );
2286 /***********************************************************************
2287 * _hread16 (KERNEL.349)
2289 LONG WINAPI _hread16( HFILE16 hFile, LPVOID buffer, LONG count)
2291 return _lread( (HFILE)DosFileHandleToWin32Handle(hFile), buffer, count );
2295 /***********************************************************************
2296 * _hread (KERNEL32.@)
2298 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
2300 return _lread( hFile, buffer, count );
2304 /***********************************************************************
2305 * _hwrite (KERNEL.350)
2307 LONG WINAPI _hwrite16( HFILE16 hFile, LPCSTR buffer, LONG count )
2309 return _hwrite( (HFILE)DosFileHandleToWin32Handle(hFile), buffer, count );
2313 /***********************************************************************
2314 * _hwrite (KERNEL32.@)
2316 * experimentation yields that _lwrite:
2317 * o truncates the file at the current position with
2318 * a 0 len write
2319 * o returns 0 on a 0 length write
2320 * o works with console handles
2323 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
2325 DWORD result;
2327 TRACE("%d %p %ld\n", handle, buffer, count );
2329 if (!count)
2331 /* Expand or truncate at current position */
2332 if (!SetEndOfFile( (HANDLE)handle )) return HFILE_ERROR;
2333 return 0;
2335 if (!WriteFile( (HANDLE)handle, buffer, count, &result, NULL ))
2336 return HFILE_ERROR;
2337 return result;
2341 /***********************************************************************
2342 * SetHandleCount (KERNEL.199)
2344 UINT16 WINAPI SetHandleCount16( UINT16 count )
2346 return SetHandleCount( count );
2350 /*************************************************************************
2351 * SetHandleCount (KERNEL32.@)
2353 UINT WINAPI SetHandleCount( UINT count )
2355 return min( 256, count );
2359 /***********************************************************************
2360 * FlushFileBuffers (KERNEL32.@)
2362 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
2364 NTSTATUS nts;
2365 IO_STATUS_BLOCK ioblk;
2367 nts = NtFlushBuffersFile( hFile, &ioblk );
2368 if (nts != STATUS_SUCCESS)
2370 SetLastError( RtlNtStatusToDosError( nts ) );
2371 return FALSE;
2374 return TRUE;
2378 /**************************************************************************
2379 * SetEndOfFile (KERNEL32.@)
2381 BOOL WINAPI SetEndOfFile( HANDLE hFile )
2383 BOOL ret;
2384 SERVER_START_REQ( truncate_file )
2386 req->handle = hFile;
2387 ret = !wine_server_call_err( req );
2389 SERVER_END_REQ;
2390 return ret;
2394 /***********************************************************************
2395 * DeleteFile (KERNEL.146)
2397 BOOL16 WINAPI DeleteFile16( LPCSTR path )
2399 return DeleteFileA( path );
2403 /***********************************************************************
2404 * DeleteFileW (KERNEL32.@)
2406 BOOL WINAPI DeleteFileW( LPCWSTR path )
2408 DOS_FULL_NAME full_name;
2409 HANDLE hFile;
2411 TRACE("%s\n", debugstr_w(path) );
2412 if (!path || !*path)
2414 SetLastError(ERROR_PATH_NOT_FOUND);
2415 return FALSE;
2417 if (DOSFS_GetDevice( path ))
2419 WARN("cannot remove DOS device %s!\n", debugstr_w(path));
2420 SetLastError( ERROR_FILE_NOT_FOUND );
2421 return FALSE;
2424 if (!DOSFS_GetFullName( path, TRUE, &full_name )) return FALSE;
2426 /* check if we are allowed to delete the source */
2427 hFile = FILE_CreateFile( full_name.long_name, GENERIC_READ|GENERIC_WRITE, 0,
2428 NULL, OPEN_EXISTING, 0, 0, TRUE,
2429 GetDriveTypeW( full_name.short_name ) );
2430 if (!hFile) return FALSE;
2432 if (unlink( full_name.long_name ) == -1)
2434 FILE_SetDosError();
2435 CloseHandle(hFile);
2436 return FALSE;
2438 CloseHandle(hFile);
2439 return TRUE;
2443 /***********************************************************************
2444 * DeleteFileA (KERNEL32.@)
2446 BOOL WINAPI DeleteFileA( LPCSTR path )
2448 UNICODE_STRING pathW;
2449 BOOL ret = FALSE;
2451 if (!path)
2453 SetLastError(ERROR_INVALID_PARAMETER);
2454 return FALSE;
2457 if (RtlCreateUnicodeStringFromAsciiz(&pathW, path))
2459 ret = DeleteFileW(pathW.Buffer);
2460 RtlFreeUnicodeString(&pathW);
2462 else
2463 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
2464 return ret;
2468 /***********************************************************************
2469 * GetFileType (KERNEL32.@)
2471 DWORD WINAPI GetFileType( HANDLE hFile )
2473 DWORD ret = FILE_TYPE_UNKNOWN;
2474 SERVER_START_REQ( get_file_info )
2476 req->handle = hFile;
2477 if (!wine_server_call_err( req )) ret = reply->type;
2479 SERVER_END_REQ;
2480 return ret;
2484 /* check if a file name is for an executable file (.exe or .com) */
2485 inline static BOOL is_executable( const char *name )
2487 int len = strlen(name);
2489 if (len < 4) return FALSE;
2490 return (!strcasecmp( name + len - 4, ".exe" ) ||
2491 !strcasecmp( name + len - 4, ".com" ));
2495 /***********************************************************************
2496 * FILE_AddBootRenameEntry
2498 * Adds an entry to the registry that is loaded when windows boots and
2499 * checks if there are some files to be removed or renamed/moved.
2500 * <fn1> has to be valid and <fn2> may be NULL. If both pointers are
2501 * non-NULL then the file is moved, otherwise it is deleted. The
2502 * entry of the registrykey is always appended with two zero
2503 * terminated strings. If <fn2> is NULL then the second entry is
2504 * simply a single 0-byte. Otherwise the second filename goes
2505 * there. The entries are prepended with \??\ before the path and the
2506 * second filename gets also a '!' as the first character if
2507 * MOVEFILE_REPLACE_EXISTING is set. After the final string another
2508 * 0-byte follows to indicate the end of the strings.
2509 * i.e.:
2510 * \??\D:\test\file1[0]
2511 * !\??\D:\test\file1_renamed[0]
2512 * \??\D:\Test|delete[0]
2513 * [0] <- file is to be deleted, second string empty
2514 * \??\D:\test\file2[0]
2515 * !\??\D:\test\file2_renamed[0]
2516 * [0] <- indicates end of strings
2518 * or:
2519 * \??\D:\test\file1[0]
2520 * !\??\D:\test\file1_renamed[0]
2521 * \??\D:\Test|delete[0]
2522 * [0] <- file is to be deleted, second string empty
2523 * [0] <- indicates end of strings
2526 static BOOL FILE_AddBootRenameEntry( LPCWSTR fn1, LPCWSTR fn2, DWORD flags )
2528 static const WCHAR PreString[] = {'\\','?','?','\\',0};
2529 static const WCHAR ValueName[] = {'P','e','n','d','i','n','g',
2530 'F','i','l','e','R','e','n','a','m','e',
2531 'O','p','e','r','a','t','i','o','n','s',0};
2532 static const WCHAR SessionW[] = {'M','a','c','h','i','n','e','\\',
2533 'S','y','s','t','e','m','\\',
2534 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
2535 'C','o','n','t','r','o','l','\\',
2536 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
2537 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
2539 OBJECT_ATTRIBUTES attr;
2540 UNICODE_STRING nameW;
2541 KEY_VALUE_PARTIAL_INFORMATION *info;
2542 BOOL rc = FALSE;
2543 HKEY Reboot = 0;
2544 DWORD len0, len1, len2;
2545 DWORD DataSize = 0;
2546 BYTE *Buffer = NULL;
2547 WCHAR *p;
2549 attr.Length = sizeof(attr);
2550 attr.RootDirectory = 0;
2551 attr.ObjectName = &nameW;
2552 attr.Attributes = 0;
2553 attr.SecurityDescriptor = NULL;
2554 attr.SecurityQualityOfService = NULL;
2555 RtlInitUnicodeString( &nameW, SessionW );
2557 if (NtCreateKey( &Reboot, KEY_ALL_ACCESS, &attr, 0, NULL, 0, NULL ) != STATUS_SUCCESS)
2559 WARN("Error creating key for reboot managment [%s]\n",
2560 "SYSTEM\\CurrentControlSet\\Control\\Session Manager");
2561 return FALSE;
2564 len0 = strlenW(PreString);
2565 len1 = strlenW(fn1) + len0 + 1;
2566 if (fn2)
2568 len2 = strlenW(fn2) + len0 + 1;
2569 if (flags & MOVEFILE_REPLACE_EXISTING) len2++; /* Plus 1 because of the leading '!' */
2571 else len2 = 1; /* minimum is the 0 characters for the empty second string */
2573 /* convert characters to bytes */
2574 len0 *= sizeof(WCHAR);
2575 len1 *= sizeof(WCHAR);
2576 len2 *= sizeof(WCHAR);
2578 RtlInitUnicodeString( &nameW, ValueName );
2580 /* First we check if the key exists and if so how many bytes it already contains. */
2581 if (NtQueryValueKey( Reboot, &nameW, KeyValuePartialInformation,
2582 NULL, 0, &DataSize ) == STATUS_BUFFER_OVERFLOW)
2584 if (!(Buffer = HeapAlloc( GetProcessHeap(), 0, DataSize + len1 + len2 + sizeof(WCHAR) )))
2585 goto Quit;
2586 if (NtQueryValueKey( Reboot, &nameW, KeyValuePartialInformation,
2587 Buffer, DataSize, &DataSize )) goto Quit;
2588 info = (KEY_VALUE_PARTIAL_INFORMATION *)Buffer;
2589 if (info->Type != REG_MULTI_SZ) goto Quit;
2590 if (DataSize > sizeof(info)) DataSize -= sizeof(WCHAR); /* remove terminating null (will be added back later) */
2592 else
2594 DataSize = info_size;
2595 if (!(Buffer = HeapAlloc( GetProcessHeap(), 0, DataSize + len1 + len2 + sizeof(WCHAR) )))
2596 goto Quit;
2599 p = (WCHAR *)(Buffer + DataSize);
2600 strcpyW( p, PreString );
2601 strcatW( p, fn1 );
2602 DataSize += len1;
2603 if (fn2)
2605 p = (WCHAR *)(Buffer + DataSize);
2606 if (flags & MOVEFILE_REPLACE_EXISTING)
2607 *p++ = '!';
2608 strcpyW( p, PreString );
2609 strcatW( p, fn2 );
2610 DataSize += len2;
2612 else
2614 p = (WCHAR *)(Buffer + DataSize);
2615 *p = 0;
2616 DataSize += sizeof(WCHAR);
2619 /* add final null */
2620 p = (WCHAR *)(Buffer + DataSize);
2621 *p = 0;
2622 DataSize += sizeof(WCHAR);
2624 rc = !NtSetValueKey(Reboot, &nameW, 0, REG_MULTI_SZ, Buffer + info_size, DataSize - info_size);
2626 Quit:
2627 if (Reboot) NtClose(Reboot);
2628 if (Buffer) HeapFree( GetProcessHeap(), 0, Buffer );
2629 return(rc);
2633 /**************************************************************************
2634 * MoveFileExW (KERNEL32.@)
2636 BOOL WINAPI MoveFileExW( LPCWSTR fn1, LPCWSTR fn2, DWORD flag )
2638 DOS_FULL_NAME full_name1, full_name2;
2639 HANDLE hFile;
2640 DWORD attr = INVALID_FILE_ATTRIBUTES;
2642 TRACE("(%s,%s,%04lx)\n", debugstr_w(fn1), debugstr_w(fn2), flag);
2644 /* FIXME: <Gerhard W. Gruber>sparhawk@gmx.at
2645 In case of W9x and lesser this function should return 120 (ERROR_CALL_NOT_IMPLEMENTED)
2646 to be really compatible. Most programs wont have any problems though. In case
2647 you encounter one, this is what you should return here. I don't know what's up
2648 with NT 3.5. Is this function available there or not?
2649 Does anybody really care about 3.5? :)
2652 /* Filename1 has to be always set to a valid path. Filename2 may be NULL
2653 if the source file has to be deleted.
2655 if (!fn1) {
2656 SetLastError(ERROR_INVALID_PARAMETER);
2657 return FALSE;
2660 /* This function has to be run through in order to process the name properly.
2661 If the BOOTDELAY flag is set, the file doesn't need to exist though. At least
2662 that is the behaviour on NT 4.0. The operation accepts the filenames as
2663 they are given but it can't reply with a reasonable returncode. Success
2664 means in that case success for entering the values into the registry.
2666 if(!DOSFS_GetFullName( fn1, TRUE, &full_name1 ))
2668 if(!(flag & MOVEFILE_DELAY_UNTIL_REBOOT))
2669 return FALSE;
2672 if (fn2) /* !fn2 means delete fn1 */
2674 if (DOSFS_GetFullName( fn2, TRUE, &full_name2 ))
2676 if(!(flag & MOVEFILE_DELAY_UNTIL_REBOOT))
2678 /* target exists, check if we may overwrite */
2679 if (!(flag & MOVEFILE_REPLACE_EXISTING))
2681 SetLastError( ERROR_FILE_EXISTS );
2682 return FALSE;
2686 else
2688 if (!DOSFS_GetFullName( fn2, FALSE, &full_name2 ))
2690 if(!(flag & MOVEFILE_DELAY_UNTIL_REBOOT))
2691 return FALSE;
2695 /* Source name and target path are valid */
2697 if (flag & MOVEFILE_DELAY_UNTIL_REBOOT)
2699 return FILE_AddBootRenameEntry( fn1, fn2, flag );
2702 attr = GetFileAttributesW( fn1 );
2703 if ( attr == INVALID_FILE_ATTRIBUTES ) return FALSE;
2705 /* check if we are allowed to rename the source */
2706 hFile = FILE_CreateFile( full_name1.long_name, 0, 0,
2707 NULL, OPEN_EXISTING, 0, 0, TRUE,
2708 GetDriveTypeW( full_name1.short_name ) );
2709 if (!hFile)
2711 if (GetLastError() != ERROR_ACCESS_DENIED) return FALSE;
2712 if ( !(attr & FILE_ATTRIBUTE_DIRECTORY) ) return FALSE;
2713 /* if it's a directory we can continue */
2715 else CloseHandle(hFile);
2717 /* check, if we are allowed to delete the destination,
2718 ** (but the file not being there is fine) */
2719 hFile = FILE_CreateFile( full_name2.long_name, GENERIC_READ|GENERIC_WRITE, 0,
2720 NULL, OPEN_EXISTING, 0, 0, TRUE,
2721 GetDriveTypeW( full_name2.short_name ) );
2722 if(!hFile && GetLastError() != ERROR_FILE_NOT_FOUND) return FALSE;
2723 CloseHandle(hFile);
2725 if (full_name1.drive != full_name2.drive)
2727 if (!(flag & MOVEFILE_COPY_ALLOWED))
2729 SetLastError( ERROR_NOT_SAME_DEVICE );
2730 return FALSE;
2732 else if ( attr & FILE_ATTRIBUTE_DIRECTORY )
2734 /* Strange, but that's what Windows returns */
2735 SetLastError ( ERROR_ACCESS_DENIED );
2736 return FALSE;
2739 if (rename( full_name1.long_name, full_name2.long_name ) == -1)
2740 /* Try copy/delete unless it's a directory. */
2741 /* FIXME: This does not handle the (unlikely) case that the two locations
2742 are on the same Wine drive, but on different Unix file systems. */
2744 if ( attr & FILE_ATTRIBUTE_DIRECTORY )
2746 FILE_SetDosError();
2747 return FALSE;
2749 else
2751 if ( ! CopyFileW( fn1, fn2, !(flag & MOVEFILE_REPLACE_EXISTING) ))
2752 return FALSE;
2753 if ( ! DeleteFileW ( fn1 ) )
2754 return FALSE;
2757 if (is_executable( full_name1.long_name ) != is_executable( full_name2.long_name ))
2759 struct stat fstat;
2760 if (stat( full_name2.long_name, &fstat ) != -1)
2762 if (is_executable( full_name2.long_name ))
2763 /* set executable bit where read bit is set */
2764 fstat.st_mode |= (fstat.st_mode & 0444) >> 2;
2765 else
2766 fstat.st_mode &= ~0111;
2767 chmod( full_name2.long_name, fstat.st_mode );
2770 return TRUE;
2772 else /* fn2 == NULL means delete source */
2774 if (flag & MOVEFILE_DELAY_UNTIL_REBOOT)
2776 if (flag & MOVEFILE_COPY_ALLOWED) {
2777 WARN("Illegal flag\n");
2778 SetLastError( ERROR_GEN_FAILURE );
2779 return FALSE;
2782 return FILE_AddBootRenameEntry( fn1, NULL, flag );
2785 if (unlink( full_name1.long_name ) == -1)
2787 FILE_SetDosError();
2788 return FALSE;
2790 return TRUE; /* successfully deleted */
2794 /**************************************************************************
2795 * MoveFileExA (KERNEL32.@)
2797 BOOL WINAPI MoveFileExA( LPCSTR fn1, LPCSTR fn2, DWORD flag )
2799 UNICODE_STRING fn1W, fn2W;
2800 BOOL ret;
2802 if (!fn1)
2804 SetLastError(ERROR_INVALID_PARAMETER);
2805 return FALSE;
2808 RtlCreateUnicodeStringFromAsciiz(&fn1W, fn1);
2809 if (fn2) RtlCreateUnicodeStringFromAsciiz(&fn2W, fn2);
2810 else fn2W.Buffer = NULL;
2812 ret = MoveFileExW( fn1W.Buffer, fn2W.Buffer, flag );
2814 RtlFreeUnicodeString(&fn1W);
2815 RtlFreeUnicodeString(&fn2W);
2816 return ret;
2820 /**************************************************************************
2821 * MoveFileW (KERNEL32.@)
2823 * Move file or directory
2825 BOOL WINAPI MoveFileW( LPCWSTR fn1, LPCWSTR fn2 )
2827 return MoveFileExW( fn1, fn2, MOVEFILE_COPY_ALLOWED );
2831 /**************************************************************************
2832 * MoveFileA (KERNEL32.@)
2834 BOOL WINAPI MoveFileA( LPCSTR fn1, LPCSTR fn2 )
2836 return MoveFileExA( fn1, fn2, MOVEFILE_COPY_ALLOWED );
2840 /**************************************************************************
2841 * CopyFileW (KERNEL32.@)
2843 BOOL WINAPI CopyFileW( LPCWSTR source, LPCWSTR dest, BOOL fail_if_exists )
2845 HANDLE h1, h2;
2846 BY_HANDLE_FILE_INFORMATION info;
2847 DWORD count;
2848 BOOL ret = FALSE;
2849 char buffer[2048];
2851 if (!source || !dest)
2853 SetLastError(ERROR_INVALID_PARAMETER);
2854 return FALSE;
2857 TRACE("%s -> %s\n", debugstr_w(source), debugstr_w(dest));
2859 if ((h1 = CreateFileW(source, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
2860 NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE)
2862 WARN("Unable to open source %s\n", debugstr_w(source));
2863 return FALSE;
2866 if (!GetFileInformationByHandle( h1, &info ))
2868 WARN("GetFileInformationByHandle returned error for %s\n", debugstr_w(source));
2869 CloseHandle( h1 );
2870 return FALSE;
2873 if ((h2 = CreateFileW( dest, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
2874 fail_if_exists ? CREATE_NEW : CREATE_ALWAYS,
2875 info.dwFileAttributes, h1 )) == INVALID_HANDLE_VALUE)
2877 WARN("Unable to open dest %s\n", debugstr_w(dest));
2878 CloseHandle( h1 );
2879 return FALSE;
2882 while (ReadFile( h1, buffer, sizeof(buffer), &count, NULL ) && count)
2884 char *p = buffer;
2885 while (count != 0)
2887 DWORD res;
2888 if (!WriteFile( h2, p, count, &res, NULL ) || !res) goto done;
2889 p += res;
2890 count -= res;
2893 ret = TRUE;
2894 done:
2895 CloseHandle( h1 );
2896 CloseHandle( h2 );
2897 return ret;
2901 /**************************************************************************
2902 * CopyFileA (KERNEL32.@)
2904 BOOL WINAPI CopyFileA( LPCSTR source, LPCSTR dest, BOOL fail_if_exists)
2906 UNICODE_STRING sourceW, destW;
2907 BOOL ret;
2909 if (!source || !dest)
2911 SetLastError(ERROR_INVALID_PARAMETER);
2912 return FALSE;
2915 RtlCreateUnicodeStringFromAsciiz(&sourceW, source);
2916 RtlCreateUnicodeStringFromAsciiz(&destW, dest);
2918 ret = CopyFileW(sourceW.Buffer, destW.Buffer, fail_if_exists);
2920 RtlFreeUnicodeString(&sourceW);
2921 RtlFreeUnicodeString(&destW);
2922 return ret;
2926 /**************************************************************************
2927 * CopyFileExW (KERNEL32.@)
2929 * This implementation ignores most of the extra parameters passed-in into
2930 * the "ex" version of the method and calls the CopyFile method.
2931 * It will have to be fixed eventually.
2933 BOOL WINAPI CopyFileExW(LPCWSTR sourceFilename, LPCWSTR destFilename,
2934 LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
2935 LPBOOL cancelFlagPointer, DWORD copyFlags)
2938 * Interpret the only flag that CopyFile can interpret.
2940 return CopyFileW(sourceFilename, destFilename, (copyFlags & COPY_FILE_FAIL_IF_EXISTS) != 0);
2943 /**************************************************************************
2944 * CopyFileExA (KERNEL32.@)
2946 BOOL WINAPI CopyFileExA(LPCSTR sourceFilename, LPCSTR destFilename,
2947 LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
2948 LPBOOL cancelFlagPointer, DWORD copyFlags)
2950 UNICODE_STRING sourceW, destW;
2951 BOOL ret;
2953 if (!sourceFilename || !destFilename)
2955 SetLastError(ERROR_INVALID_PARAMETER);
2956 return FALSE;
2959 RtlCreateUnicodeStringFromAsciiz(&sourceW, sourceFilename);
2960 RtlCreateUnicodeStringFromAsciiz(&destW, destFilename);
2962 ret = CopyFileExW(sourceW.Buffer, destW.Buffer, progressRoutine, appData,
2963 cancelFlagPointer, copyFlags);
2965 RtlFreeUnicodeString(&sourceW);
2966 RtlFreeUnicodeString(&destW);
2967 return ret;
2971 /***********************************************************************
2972 * SetFileTime (KERNEL32.@)
2974 BOOL WINAPI SetFileTime( HANDLE hFile,
2975 const FILETIME *lpCreationTime,
2976 const FILETIME *lpLastAccessTime,
2977 const FILETIME *lpLastWriteTime )
2979 BOOL ret;
2980 SERVER_START_REQ( set_file_time )
2982 req->handle = hFile;
2983 if (lpLastAccessTime)
2984 RtlTimeToSecondsSince1970( (PLARGE_INTEGER) lpLastAccessTime, (DWORD *)&req->access_time );
2985 else
2986 req->access_time = 0; /* FIXME */
2987 if (lpLastWriteTime)
2988 RtlTimeToSecondsSince1970( (PLARGE_INTEGER) lpLastWriteTime, (DWORD *)&req->write_time );
2989 else
2990 req->write_time = 0; /* FIXME */
2991 ret = !wine_server_call_err( req );
2993 SERVER_END_REQ;
2994 return ret;
2998 /**************************************************************************
2999 * LockFile (KERNEL32.@)
3001 BOOL WINAPI LockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
3002 DWORD count_low, DWORD count_high )
3004 BOOL ret;
3006 TRACE( "%p %lx%08lx %lx%08lx\n", hFile, offset_high, offset_low, count_high, count_low );
3008 SERVER_START_REQ( lock_file )
3010 req->handle = hFile;
3011 req->offset_low = offset_low;
3012 req->offset_high = offset_high;
3013 req->count_low = count_low;
3014 req->count_high = count_high;
3015 req->shared = FALSE;
3016 req->wait = FALSE;
3017 ret = !wine_server_call_err( req );
3019 SERVER_END_REQ;
3020 return ret;
3023 /**************************************************************************
3024 * LockFileEx [KERNEL32.@]
3026 * Locks a byte range within an open file for shared or exclusive access.
3028 * RETURNS
3029 * success: TRUE
3030 * failure: FALSE
3032 * NOTES
3033 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
3035 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
3036 DWORD count_low, DWORD count_high, LPOVERLAPPED overlapped )
3038 NTSTATUS err;
3039 BOOL async;
3040 HANDLE handle;
3042 if (reserved)
3044 SetLastError( ERROR_INVALID_PARAMETER );
3045 return FALSE;
3048 TRACE( "%p %lx%08lx %lx%08lx flags %lx\n",
3049 hFile, overlapped->OffsetHigh, overlapped->Offset, count_high, count_low, flags );
3051 for (;;)
3053 SERVER_START_REQ( lock_file )
3055 req->handle = hFile;
3056 req->offset_low = overlapped->Offset;
3057 req->offset_high = overlapped->OffsetHigh;
3058 req->count_low = count_low;
3059 req->count_high = count_high;
3060 req->shared = !(flags & LOCKFILE_EXCLUSIVE_LOCK);
3061 req->wait = !(flags & LOCKFILE_FAIL_IMMEDIATELY);
3062 err = wine_server_call( req );
3063 handle = reply->handle;
3064 async = reply->overlapped;
3066 SERVER_END_REQ;
3067 if (err != STATUS_PENDING)
3069 if (err) SetLastError( RtlNtStatusToDosError(err) );
3070 return !err;
3072 if (async)
3074 FIXME( "Async I/O lock wait not implemented, might deadlock\n" );
3075 if (handle) CloseHandle( handle );
3076 SetLastError( ERROR_IO_PENDING );
3077 return FALSE;
3079 if (handle)
3081 WaitForSingleObject( handle, INFINITE );
3082 CloseHandle( handle );
3084 else Sleep(100); /* Unix lock conflict, sleep a bit and retry */
3089 /**************************************************************************
3090 * UnlockFile (KERNEL32.@)
3092 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD offset_low, DWORD offset_high,
3093 DWORD count_low, DWORD count_high )
3095 BOOL ret;
3097 TRACE( "%p %lx%08lx %lx%08lx\n", hFile, offset_high, offset_low, count_high, count_low );
3099 SERVER_START_REQ( unlock_file )
3101 req->handle = hFile;
3102 req->offset_low = offset_low;
3103 req->offset_high = offset_high;
3104 req->count_low = count_low;
3105 req->count_high = count_high;
3106 ret = !wine_server_call_err( req );
3108 SERVER_END_REQ;
3109 return ret;
3113 /**************************************************************************
3114 * UnlockFileEx (KERNEL32.@)
3116 BOOL WINAPI UnlockFileEx( HANDLE hFile, DWORD reserved, DWORD count_low, DWORD count_high,
3117 LPOVERLAPPED overlapped )
3119 if (reserved)
3121 SetLastError( ERROR_INVALID_PARAMETER );
3122 return FALSE;
3124 return UnlockFile( hFile, overlapped->Offset, overlapped->OffsetHigh, count_low, count_high );
3128 /**************************************************************************
3129 * GetFileAttributesExW (KERNEL32.@)
3131 BOOL WINAPI GetFileAttributesExW(
3132 LPCWSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId,
3133 LPVOID lpFileInformation)
3135 DOS_FULL_NAME full_name;
3136 BY_HANDLE_FILE_INFORMATION info;
3138 if (!lpFileName || !lpFileInformation)
3140 SetLastError(ERROR_INVALID_PARAMETER);
3141 return FALSE;
3144 if (fInfoLevelId == GetFileExInfoStandard) {
3145 LPWIN32_FILE_ATTRIBUTE_DATA lpFad =
3146 (LPWIN32_FILE_ATTRIBUTE_DATA) lpFileInformation;
3147 if (!DOSFS_GetFullName( lpFileName, TRUE, &full_name )) return FALSE;
3148 if (!FILE_Stat( full_name.long_name, &info, NULL )) return FALSE;
3150 lpFad->dwFileAttributes = info.dwFileAttributes;
3151 lpFad->ftCreationTime = info.ftCreationTime;
3152 lpFad->ftLastAccessTime = info.ftLastAccessTime;
3153 lpFad->ftLastWriteTime = info.ftLastWriteTime;
3154 lpFad->nFileSizeHigh = info.nFileSizeHigh;
3155 lpFad->nFileSizeLow = info.nFileSizeLow;
3157 else {
3158 FIXME("invalid info level %d!\n", fInfoLevelId);
3159 return FALSE;
3162 return TRUE;
3166 /**************************************************************************
3167 * GetFileAttributesExA (KERNEL32.@)
3169 BOOL WINAPI GetFileAttributesExA(
3170 LPCSTR filename, GET_FILEEX_INFO_LEVELS fInfoLevelId,
3171 LPVOID lpFileInformation)
3173 UNICODE_STRING filenameW;
3174 BOOL ret = FALSE;
3176 if (!filename || !lpFileInformation)
3178 SetLastError(ERROR_INVALID_PARAMETER);
3179 return FALSE;
3182 if (RtlCreateUnicodeStringFromAsciiz(&filenameW, filename))
3184 ret = GetFileAttributesExW(filenameW.Buffer, fInfoLevelId, lpFileInformation);
3185 RtlFreeUnicodeString(&filenameW);
3187 else
3188 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
3189 return ret;
3192 /**************************************************************************
3193 * ReplaceFileW (KERNEL32.@)
3194 * ReplaceFile (KERNEL32.@)
3196 BOOL WINAPI ReplaceFileW(LPCWSTR lpReplacedFileName,LPCWSTR lpReplacementFileName,
3197 LPCWSTR lpBackupFileName, DWORD dwReplaceFlags,
3198 LPVOID lpExclude, LPVOID lpReserved)
3200 FIXME("(%s,%s,%s,%08lx,%p,%p) stub\n",debugstr_w(lpReplacedFileName),debugstr_w(lpReplacementFileName),
3201 debugstr_w(lpBackupFileName),dwReplaceFlags,lpExclude,lpReserved);
3202 SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
3203 return FALSE;
3206 /**************************************************************************
3207 * ReplaceFileA (KERNEL32.@)
3209 BOOL WINAPI ReplaceFileA(LPCSTR lpReplacedFileName,LPCSTR lpReplacementFileName,
3210 LPCSTR lpBackupFileName, DWORD dwReplaceFlags,
3211 LPVOID lpExclude, LPVOID lpReserved)
3213 FIXME("(%s,%s,%s,%08lx,%p,%p) stub\n",lpReplacedFileName,lpReplacementFileName,
3214 lpBackupFileName,dwReplaceFlags,lpExclude,lpReserved);
3215 SetLastError(ERROR_UNABLE_TO_MOVE_REPLACEMENT);
3216 return FALSE;