Removed a number of internal file functions that are no longer used.
[wine/multimedia.git] / files / file.c
blob3752c593ec8a887e70770bd98b1648328bb6fa4f
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 <stdarg.h>
35 #include <stdio.h>
36 #include <string.h>
37 #ifdef HAVE_SYS_ERRNO_H
38 #include <sys/errno.h>
39 #endif
40 #include <sys/types.h>
41 #include <sys/stat.h>
42 #ifdef HAVE_SYS_MMAN_H
43 #include <sys/mman.h>
44 #endif
45 #ifdef HAVE_SYS_TIME_H
46 # include <sys/time.h>
47 #endif
48 #ifdef HAVE_SYS_POLL_H
49 # include <sys/poll.h>
50 #endif
51 #include <time.h>
52 #ifdef HAVE_UNISTD_H
53 # include <unistd.h>
54 #endif
55 #ifdef HAVE_UTIME_H
56 # include <utime.h>
57 #endif
58 #ifdef HAVE_IO_H
59 # include <io.h>
60 #endif
62 #define NONAMELESSUNION
63 #define NONAMELESSSTRUCT
64 #include "winerror.h"
65 #include "ntstatus.h"
66 #include "windef.h"
67 #include "winbase.h"
68 #include "winreg.h"
69 #include "winternl.h"
70 #include "wine/winbase16.h"
71 #include "wine/server.h"
73 #include "file.h"
74 #include "wincon.h"
75 #include "kernel_private.h"
77 #include "smb.h"
78 #include "wine/unicode.h"
79 #include "wine/debug.h"
81 WINE_DEFAULT_DEBUG_CHANNEL(file);
84 /***********************************************************************
85 * FILE_ConvertOFMode
87 * Convert OF_* mode into flags for CreateFile.
89 void FILE_ConvertOFMode( INT mode, DWORD *access, DWORD *sharing )
91 switch(mode & 0x03)
93 case OF_READ: *access = GENERIC_READ; break;
94 case OF_WRITE: *access = GENERIC_WRITE; break;
95 case OF_READWRITE: *access = GENERIC_READ | GENERIC_WRITE; break;
96 default: *access = 0; break;
98 switch(mode & 0x70)
100 case OF_SHARE_EXCLUSIVE: *sharing = 0; break;
101 case OF_SHARE_DENY_WRITE: *sharing = FILE_SHARE_READ; break;
102 case OF_SHARE_DENY_READ: *sharing = FILE_SHARE_WRITE; break;
103 case OF_SHARE_DENY_NONE:
104 case OF_SHARE_COMPAT:
105 default: *sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
110 /***********************************************************************
111 * FILE_SetDosError
113 * Set the DOS error code from errno.
115 void FILE_SetDosError(void)
117 int save_errno = errno; /* errno gets overwritten by printf */
119 TRACE("errno = %d %s\n", errno, strerror(errno));
120 switch (save_errno)
122 case EAGAIN:
123 SetLastError( ERROR_SHARING_VIOLATION );
124 break;
125 case EBADF:
126 SetLastError( ERROR_INVALID_HANDLE );
127 break;
128 case ENOSPC:
129 SetLastError( ERROR_HANDLE_DISK_FULL );
130 break;
131 case EACCES:
132 case EPERM:
133 case EROFS:
134 SetLastError( ERROR_ACCESS_DENIED );
135 break;
136 case EBUSY:
137 SetLastError( ERROR_LOCK_VIOLATION );
138 break;
139 case ENOENT:
140 SetLastError( ERROR_FILE_NOT_FOUND );
141 break;
142 case EISDIR:
143 SetLastError( ERROR_CANNOT_MAKE );
144 break;
145 case ENFILE:
146 case EMFILE:
147 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
148 break;
149 case EEXIST:
150 SetLastError( ERROR_FILE_EXISTS );
151 break;
152 case EINVAL:
153 case ESPIPE:
154 SetLastError( ERROR_SEEK );
155 break;
156 case ENOTEMPTY:
157 SetLastError( ERROR_DIR_NOT_EMPTY );
158 break;
159 case ENOEXEC:
160 SetLastError( ERROR_BAD_FORMAT );
161 break;
162 case ENOTDIR:
163 SetLastError( ERROR_PATH_NOT_FOUND );
164 break;
165 case EXDEV:
166 SetLastError( ERROR_NOT_SAME_DEVICE );
167 break;
168 default:
169 WARN("unknown file error: %s\n", strerror(save_errno) );
170 SetLastError( ERROR_GEN_FAILURE );
171 break;
173 errno = save_errno;
177 /***********************************************************************
178 * FILE_CreateFile
180 * Implementation of CreateFile. Takes a Unix path name.
181 * Returns 0 on failure.
183 HANDLE FILE_CreateFile( LPCSTR filename, DWORD access, DWORD sharing,
184 LPSECURITY_ATTRIBUTES sa, DWORD creation,
185 DWORD attributes, HANDLE template )
187 unsigned int err;
188 UINT disp, options;
189 HANDLE ret;
191 switch (creation)
193 case CREATE_ALWAYS: disp = FILE_OVERWRITE_IF; break;
194 case CREATE_NEW: disp = FILE_CREATE; break;
195 case OPEN_ALWAYS: disp = FILE_OPEN_IF; break;
196 case OPEN_EXISTING: disp = FILE_OPEN; break;
197 case TRUNCATE_EXISTING: disp = FILE_OVERWRITE; break;
198 default:
199 SetLastError( ERROR_INVALID_PARAMETER );
200 return 0;
203 options = 0;
204 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
205 options |= FILE_OPEN_FOR_BACKUP_INTENT;
206 else
207 options |= FILE_NON_DIRECTORY_FILE;
208 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
209 options |= FILE_DELETE_ON_CLOSE;
210 if (!(attributes & FILE_FLAG_OVERLAPPED))
211 options |= FILE_SYNCHRONOUS_IO_ALERT;
212 if (attributes & FILE_FLAG_RANDOM_ACCESS)
213 options |= FILE_RANDOM_ACCESS;
214 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
216 SERVER_START_REQ( create_file )
218 req->access = access;
219 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
220 req->sharing = sharing;
221 req->create = disp;
222 req->options = options;
223 req->attrs = attributes;
224 wine_server_add_data( req, filename, strlen(filename) );
225 SetLastError(0);
226 err = wine_server_call( req );
227 ret = reply->handle;
229 SERVER_END_REQ;
231 if (err)
233 /* In the case file creation was rejected due to CREATE_NEW flag
234 * was specified and file with that name already exists, correct
235 * last error is ERROR_FILE_EXISTS and not ERROR_ALREADY_EXISTS.
236 * Note: RtlNtStatusToDosError is not the subject to blame here.
238 if (err == STATUS_OBJECT_NAME_COLLISION)
239 SetLastError( ERROR_FILE_EXISTS );
240 else
241 SetLastError( RtlNtStatusToDosError(err) );
244 if (!ret) WARN("Unable to create file '%s' (GLE %ld)\n", filename, GetLastError());
245 return ret;
249 static HANDLE FILE_OpenPipe(LPCWSTR name, DWORD access, LPSECURITY_ATTRIBUTES sa )
251 HANDLE ret;
252 DWORD len = 0;
254 if (name && (len = strlenW(name)) > MAX_PATH)
256 SetLastError( ERROR_FILENAME_EXCED_RANGE );
257 return 0;
259 SERVER_START_REQ( open_named_pipe )
261 req->access = access;
262 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
263 SetLastError(0);
264 wine_server_add_data( req, name, len * sizeof(WCHAR) );
265 wine_server_call_err( req );
266 ret = reply->handle;
268 SERVER_END_REQ;
269 TRACE("Returned %p\n",ret);
270 return ret;
273 /*************************************************************************
274 * CreateFileW [KERNEL32.@] Creates or opens a file or other object
276 * Creates or opens an object, and returns a handle that can be used to
277 * access that object.
279 * PARAMS
281 * filename [in] pointer to filename to be accessed
282 * access [in] access mode requested
283 * sharing [in] share mode
284 * sa [in] pointer to security attributes
285 * creation [in] how to create the file
286 * attributes [in] attributes for newly created file
287 * template [in] handle to file with extended attributes to copy
289 * RETURNS
290 * Success: Open handle to specified file
291 * Failure: INVALID_HANDLE_VALUE
293 * NOTES
294 * Should call SetLastError() on failure.
296 * BUGS
298 * Doesn't support character devices, template files, or a
299 * lot of the 'attributes' flags yet.
301 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
302 LPSECURITY_ATTRIBUTES sa, DWORD creation,
303 DWORD attributes, HANDLE template )
305 NTSTATUS status;
306 UINT options;
307 OBJECT_ATTRIBUTES attr;
308 UNICODE_STRING nameW;
309 IO_STATUS_BLOCK io;
310 HANDLE ret;
311 DWORD dosdev;
312 static const WCHAR bkslashes_with_dotW[] = {'\\','\\','.','\\',0};
313 static const WCHAR coninW[] = {'C','O','N','I','N','$',0};
314 static const WCHAR conoutW[] = {'C','O','N','O','U','T','$',0};
316 static const char * const creation_name[5] =
317 { "CREATE_NEW", "CREATE_ALWAYS", "OPEN_EXISTING", "OPEN_ALWAYS", "TRUNCATE_EXISTING" };
319 static const UINT nt_disposition[5] =
321 FILE_CREATE, /* CREATE_NEW */
322 FILE_OVERWRITE_IF, /* CREATE_ALWAYS */
323 FILE_OPEN, /* OPEN_EXISTING */
324 FILE_OPEN_IF, /* OPEN_ALWAYS */
325 FILE_OVERWRITE /* TRUNCATE_EXISTING */
329 /* sanity checks */
331 if (!filename || !filename[0])
333 SetLastError( ERROR_PATH_NOT_FOUND );
334 return INVALID_HANDLE_VALUE;
337 if (creation < CREATE_NEW || creation > TRUNCATE_EXISTING)
339 SetLastError( ERROR_INVALID_PARAMETER );
340 return INVALID_HANDLE_VALUE;
343 TRACE("%s %s%s%s%s%s%s%s attributes 0x%lx\n", debugstr_w(filename),
344 (access & GENERIC_READ)?"GENERIC_READ ":"",
345 (access & GENERIC_WRITE)?"GENERIC_WRITE ":"",
346 (!access)?"QUERY_ACCESS ":"",
347 (sharing & FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
348 (sharing & FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
349 (sharing & FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
350 creation_name[creation - CREATE_NEW], attributes);
352 /* Open a console for CONIN$ or CONOUT$ */
354 if (!strcmpiW(filename, coninW) || !strcmpiW(filename, conoutW))
356 ret = OpenConsoleW(filename, access, (sa && sa->bInheritHandle), creation);
357 goto done;
360 if (!strncmpW(filename, bkslashes_with_dotW, 4))
362 static const WCHAR pipeW[] = {'P','I','P','E','\\',0};
363 if(!strncmpiW(filename + 4, pipeW, 5))
365 TRACE("Opening a pipe: %s\n", debugstr_w(filename));
366 ret = FILE_OpenPipe( filename, access, sa );
367 goto done;
369 else if (isalphaW(filename[4]) && filename[5] == ':' && filename[6] == '\0')
371 const char *device = DRIVE_GetDevice( toupperW(filename[4]) - 'A' );
372 if (device)
374 ret = FILE_CreateFile( device, access, sharing, sa, creation,
375 attributes, template );
377 else
379 SetLastError( ERROR_ACCESS_DENIED );
380 return INVALID_HANDLE_VALUE;
382 goto done;
384 else if ((dosdev = RtlIsDosDeviceName_U( filename + 4 )))
386 dosdev += MAKELONG( 0, 4*sizeof(WCHAR) ); /* adjust position to start of filename */
388 else if (filename[4])
390 ret = VXD_Open( filename+4, access, sa );
391 goto done;
393 else
395 SetLastError( ERROR_INVALID_NAME );
396 return INVALID_HANDLE_VALUE;
399 else dosdev = RtlIsDosDeviceName_U( filename );
401 if (dosdev)
403 static const WCHAR conW[] = {'C','O','N'};
405 if (LOWORD(dosdev) == sizeof(conW) &&
406 !memicmpW( filename + HIWORD(dosdev)/sizeof(WCHAR), conW, sizeof(conW)))
408 switch (access & (GENERIC_READ|GENERIC_WRITE))
410 case GENERIC_READ:
411 ret = OpenConsoleW(coninW, access, (sa && sa->bInheritHandle), creation);
412 goto done;
413 case GENERIC_WRITE:
414 ret = OpenConsoleW(conoutW, access, (sa && sa->bInheritHandle), creation);
415 goto done;
416 default:
417 SetLastError( ERROR_FILE_NOT_FOUND );
418 return INVALID_HANDLE_VALUE;
423 if (!RtlDosPathNameToNtPathName_U( filename, &nameW, NULL, NULL ))
425 SetLastError( ERROR_PATH_NOT_FOUND );
426 return INVALID_HANDLE_VALUE;
429 /* now call NtCreateFile */
431 options = 0;
432 if (attributes & FILE_FLAG_BACKUP_SEMANTICS)
433 options |= FILE_OPEN_FOR_BACKUP_INTENT;
434 else
435 options |= FILE_NON_DIRECTORY_FILE;
436 if (attributes & FILE_FLAG_DELETE_ON_CLOSE)
437 options |= FILE_DELETE_ON_CLOSE;
438 if (!(attributes & FILE_FLAG_OVERLAPPED))
439 options |= FILE_SYNCHRONOUS_IO_ALERT;
440 if (attributes & FILE_FLAG_RANDOM_ACCESS)
441 options |= FILE_RANDOM_ACCESS;
442 attributes &= FILE_ATTRIBUTE_VALID_FLAGS;
444 attr.Length = sizeof(attr);
445 attr.RootDirectory = 0;
446 attr.Attributes = OBJ_CASE_INSENSITIVE;
447 attr.ObjectName = &nameW;
448 attr.SecurityDescriptor = sa ? sa->lpSecurityDescriptor : NULL;
449 attr.SecurityQualityOfService = NULL;
451 if (sa && sa->bInheritHandle) attr.Attributes |= OBJ_INHERIT;
453 status = NtCreateFile( &ret, access, &attr, &io, NULL, attributes,
454 sharing, nt_disposition[creation - CREATE_NEW],
455 options, NULL, 0 );
456 if (status)
458 WARN("Unable to create file %s (status %lx)\n", debugstr_w(filename), status);
459 ret = INVALID_HANDLE_VALUE;
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 (status == STATUS_OBJECT_NAME_COLLISION)
467 SetLastError( ERROR_FILE_EXISTS );
468 else
469 SetLastError( RtlNtStatusToDosError(status) );
471 else SetLastError(0);
472 RtlFreeUnicodeString( &nameW );
474 done:
475 if (!ret) ret = INVALID_HANDLE_VALUE;
476 TRACE("returning %p\n", ret);
477 return ret;
482 /*************************************************************************
483 * CreateFileA (KERNEL32.@)
485 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
486 LPSECURITY_ATTRIBUTES sa, DWORD creation,
487 DWORD attributes, HANDLE template)
489 UNICODE_STRING filenameW;
490 HANDLE ret = INVALID_HANDLE_VALUE;
492 if (!filename)
494 SetLastError( ERROR_INVALID_PARAMETER );
495 return INVALID_HANDLE_VALUE;
498 if (RtlCreateUnicodeStringFromAsciiz(&filenameW, filename))
500 ret = CreateFileW(filenameW.Buffer, access, sharing, sa, creation,
501 attributes, template);
502 RtlFreeUnicodeString(&filenameW);
504 else
505 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
506 return ret;
510 /***********************************************************************
511 * FILE_FillInfo
513 * Fill a file information from a struct stat.
515 static void FILE_FillInfo( struct stat *st, BY_HANDLE_FILE_INFORMATION *info )
517 if (S_ISDIR(st->st_mode))
518 info->dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
519 else
520 info->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
521 if (!(st->st_mode & S_IWUSR))
522 info->dwFileAttributes |= FILE_ATTRIBUTE_READONLY;
524 RtlSecondsSince1970ToTime( st->st_mtime, (LARGE_INTEGER *)&info->ftCreationTime );
525 RtlSecondsSince1970ToTime( st->st_mtime, (LARGE_INTEGER *)&info->ftLastWriteTime );
526 RtlSecondsSince1970ToTime( st->st_atime, (LARGE_INTEGER *)&info->ftLastAccessTime );
528 info->dwVolumeSerialNumber = 0; /* FIXME */
529 if (S_ISDIR(st->st_mode))
531 info->nFileSizeHigh = 0;
532 info->nFileSizeLow = 0;
533 info->nNumberOfLinks = 1;
535 else
537 info->nFileSizeHigh = st->st_size >> 32;
538 info->nFileSizeLow = (DWORD)st->st_size;
539 info->nNumberOfLinks = st->st_nlink;
541 info->nFileIndexHigh = st->st_ino >> 32;
542 info->nFileIndexLow = (DWORD)st->st_ino;
546 /***********************************************************************
547 * GetFileInformationByHandle (KERNEL32.@)
549 BOOL WINAPI GetFileInformationByHandle( HANDLE hFile, BY_HANDLE_FILE_INFORMATION *info )
551 NTSTATUS status;
552 int fd;
553 BOOL ret = FALSE;
555 TRACE("%p,%p\n", hFile, info);
557 if (!info) return 0;
559 if (!(status = wine_server_handle_to_fd( hFile, 0, &fd, NULL, NULL )))
561 struct stat st;
563 if (fstat( fd, &st ) == -1)
564 FILE_SetDosError();
565 else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
566 SetLastError( ERROR_INVALID_FUNCTION );
567 else
569 FILE_FillInfo( &st, info );
570 ret = TRUE;
572 wine_server_release_fd( hFile, fd );
574 else SetLastError( RtlNtStatusToDosError(status) );
576 return ret;
580 /***********************************************************************
581 * GetFileTime (KERNEL32.@)
583 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
584 FILETIME *lpLastAccessTime,
585 FILETIME *lpLastWriteTime )
587 BY_HANDLE_FILE_INFORMATION info;
588 if (!GetFileInformationByHandle( hFile, &info )) return FALSE;
589 if (lpCreationTime) *lpCreationTime = info.ftCreationTime;
590 if (lpLastAccessTime) *lpLastAccessTime = info.ftLastAccessTime;
591 if (lpLastWriteTime) *lpLastWriteTime = info.ftLastWriteTime;
592 return TRUE;
596 /***********************************************************************
597 * GetTempFileNameA (KERNEL32.@)
599 UINT WINAPI GetTempFileNameA( LPCSTR path, LPCSTR prefix, UINT unique,
600 LPSTR buffer)
602 UNICODE_STRING pathW, prefixW;
603 WCHAR bufferW[MAX_PATH];
604 UINT ret;
606 if ( !path || !prefix || !buffer )
608 SetLastError( ERROR_INVALID_PARAMETER );
609 return 0;
612 RtlCreateUnicodeStringFromAsciiz(&pathW, path);
613 RtlCreateUnicodeStringFromAsciiz(&prefixW, prefix);
615 ret = GetTempFileNameW(pathW.Buffer, prefixW.Buffer, unique, bufferW);
616 if (ret)
617 WideCharToMultiByte(CP_ACP, 0, bufferW, -1, buffer, MAX_PATH, NULL, NULL);
619 RtlFreeUnicodeString(&pathW);
620 RtlFreeUnicodeString(&prefixW);
621 return ret;
624 /***********************************************************************
625 * GetTempFileNameW (KERNEL32.@)
627 UINT WINAPI GetTempFileNameW( LPCWSTR path, LPCWSTR prefix, UINT unique,
628 LPWSTR buffer )
630 static const WCHAR formatW[] = {'%','x','.','t','m','p',0};
632 int i;
633 LPWSTR p;
635 if ( !path || !prefix || !buffer )
637 SetLastError( ERROR_INVALID_PARAMETER );
638 return 0;
641 strcpyW( buffer, path );
642 p = buffer + strlenW(buffer);
644 /* add a \, if there isn't one */
645 if ((p == buffer) || (p[-1] != '\\')) *p++ = '\\';
647 for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
649 unique &= 0xffff;
651 if (unique) sprintfW( p, formatW, unique );
652 else
654 /* get a "random" unique number and try to create the file */
655 HANDLE handle;
656 UINT num = GetTickCount() & 0xffff;
658 if (!num) num = 1;
659 unique = num;
662 sprintfW( p, formatW, unique );
663 handle = CreateFileW( buffer, GENERIC_WRITE, 0, NULL,
664 CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
665 if (handle != INVALID_HANDLE_VALUE)
666 { /* We created it */
667 TRACE("created %s\n", debugstr_w(buffer) );
668 CloseHandle( handle );
669 break;
671 if (GetLastError() != ERROR_FILE_EXISTS &&
672 GetLastError() != ERROR_SHARING_VIOLATION)
673 break; /* No need to go on */
674 if (!(++unique & 0xffff)) unique = 1;
675 } while (unique != num);
678 TRACE("returning %s\n", debugstr_w(buffer) );
679 return unique;
683 /******************************************************************
684 * FILE_ReadWriteApc (internal)
688 static void WINAPI FILE_ReadWriteApc(void* apc_user, PIO_STATUS_BLOCK io_status, ULONG len)
690 LPOVERLAPPED_COMPLETION_ROUTINE cr = (LPOVERLAPPED_COMPLETION_ROUTINE)apc_user;
692 cr(RtlNtStatusToDosError(io_status->u.Status), len, (LPOVERLAPPED)io_status);
695 /***********************************************************************
696 * ReadFileEx (KERNEL32.@)
698 BOOL WINAPI ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
699 LPOVERLAPPED overlapped,
700 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
702 LARGE_INTEGER offset;
703 NTSTATUS status;
704 PIO_STATUS_BLOCK io_status;
706 if (!overlapped)
708 SetLastError(ERROR_INVALID_PARAMETER);
709 return FALSE;
712 offset.u.LowPart = overlapped->Offset;
713 offset.u.HighPart = overlapped->OffsetHigh;
714 io_status = (PIO_STATUS_BLOCK)overlapped;
715 io_status->u.Status = STATUS_PENDING;
717 status = NtReadFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
718 io_status, buffer, bytesToRead, &offset, NULL);
720 if (status)
722 SetLastError( RtlNtStatusToDosError(status) );
723 return FALSE;
725 return TRUE;
728 /***********************************************************************
729 * ReadFile (KERNEL32.@)
731 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
732 LPDWORD bytesRead, LPOVERLAPPED overlapped )
734 LARGE_INTEGER offset;
735 PLARGE_INTEGER poffset = NULL;
736 IO_STATUS_BLOCK iosb;
737 PIO_STATUS_BLOCK io_status = &iosb;
738 HANDLE hEvent = 0;
739 NTSTATUS status;
741 TRACE("%p %p %ld %p %p\n", hFile, buffer, bytesToRead,
742 bytesRead, overlapped );
744 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
745 if (!bytesToRead) return TRUE;
747 if (IsBadReadPtr(buffer, bytesToRead))
749 SetLastError(ERROR_WRITE_FAULT); /* FIXME */
750 return FALSE;
752 if (is_console_handle(hFile))
753 return ReadConsoleA(hFile, buffer, bytesToRead, bytesRead, NULL);
755 if (overlapped != NULL)
757 offset.u.LowPart = overlapped->Offset;
758 offset.u.HighPart = overlapped->OffsetHigh;
759 poffset = &offset;
760 hEvent = overlapped->hEvent;
761 io_status = (PIO_STATUS_BLOCK)overlapped;
763 io_status->u.Status = STATUS_PENDING;
764 io_status->Information = 0;
766 status = NtReadFile(hFile, hEvent, NULL, NULL, io_status, buffer, bytesToRead, poffset, NULL);
768 if (status != STATUS_PENDING && bytesRead)
769 *bytesRead = io_status->Information;
771 if (status && status != STATUS_END_OF_FILE)
773 SetLastError( RtlNtStatusToDosError(status) );
774 return FALSE;
776 return TRUE;
780 /***********************************************************************
781 * WriteFileEx (KERNEL32.@)
783 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
784 LPOVERLAPPED overlapped,
785 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
787 LARGE_INTEGER offset;
788 NTSTATUS status;
789 PIO_STATUS_BLOCK io_status;
791 TRACE("%p %p %ld %p %p\n",
792 hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
794 if (overlapped == NULL)
796 SetLastError(ERROR_INVALID_PARAMETER);
797 return FALSE;
799 offset.u.LowPart = overlapped->Offset;
800 offset.u.HighPart = overlapped->OffsetHigh;
802 io_status = (PIO_STATUS_BLOCK)overlapped;
803 io_status->u.Status = STATUS_PENDING;
805 status = NtWriteFile(hFile, NULL, FILE_ReadWriteApc, lpCompletionRoutine,
806 io_status, buffer, bytesToWrite, &offset, NULL);
808 if (status) SetLastError( RtlNtStatusToDosError(status) );
809 return !status;
812 /***********************************************************************
813 * WriteFile (KERNEL32.@)
815 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
816 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
818 HANDLE hEvent = NULL;
819 LARGE_INTEGER offset;
820 PLARGE_INTEGER poffset = NULL;
821 NTSTATUS status;
822 IO_STATUS_BLOCK iosb;
823 PIO_STATUS_BLOCK piosb = &iosb;
825 TRACE("%p %p %ld %p %p\n",
826 hFile, buffer, bytesToWrite, bytesWritten, overlapped );
828 if (is_console_handle(hFile))
829 return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
831 if (IsBadReadPtr(buffer, bytesToWrite))
833 SetLastError(ERROR_READ_FAULT); /* FIXME */
834 return FALSE;
837 if (overlapped)
839 offset.u.LowPart = overlapped->Offset;
840 offset.u.HighPart = overlapped->OffsetHigh;
841 poffset = &offset;
842 hEvent = overlapped->hEvent;
843 piosb = (PIO_STATUS_BLOCK)overlapped;
845 piosb->u.Status = STATUS_PENDING;
846 piosb->Information = 0;
848 status = NtWriteFile(hFile, hEvent, NULL, NULL, piosb,
849 buffer, bytesToWrite, poffset, NULL);
850 if (status)
852 SetLastError( RtlNtStatusToDosError(status) );
853 return FALSE;
855 if (bytesWritten) *bytesWritten = piosb->Information;
857 return TRUE;
861 /***********************************************************************
862 * SetFilePointer (KERNEL32.@)
864 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword,
865 DWORD method )
867 static const int whence[3] = { SEEK_SET, SEEK_CUR, SEEK_END };
868 DWORD ret = INVALID_SET_FILE_POINTER;
869 NTSTATUS status;
870 int fd;
872 TRACE("handle %p offset %ld high %ld origin %ld\n",
873 hFile, distance, highword?*highword:0, method );
875 if (method > FILE_END)
877 SetLastError( ERROR_INVALID_PARAMETER );
878 return ret;
881 if (!(status = wine_server_handle_to_fd( hFile, 0, &fd, NULL, NULL )))
883 off_t pos, res;
885 if (highword) pos = ((off_t)*highword << 32) | (ULONG)distance;
886 else pos = (off_t)distance;
887 if ((res = lseek( fd, pos, whence[method] )) == (off_t)-1)
889 /* also check EPERM due to SuSE7 2.2.16 lseek() EPERM kernel bug */
890 if (((errno == EINVAL) || (errno == EPERM)) && (method != FILE_BEGIN) && (pos < 0))
891 SetLastError( ERROR_NEGATIVE_SEEK );
892 else
893 FILE_SetDosError();
895 else
897 ret = (DWORD)res;
898 if (highword) *highword = (res >> 32);
899 if (ret == INVALID_SET_FILE_POINTER) SetLastError( 0 );
901 wine_server_release_fd( hFile, fd );
903 else SetLastError( RtlNtStatusToDosError(status) );
905 return ret;
909 /*************************************************************************
910 * SetHandleCount (KERNEL32.@)
912 UINT WINAPI SetHandleCount( UINT count )
914 return min( 256, count );
918 /**************************************************************************
919 * SetEndOfFile (KERNEL32.@)
921 BOOL WINAPI SetEndOfFile( HANDLE hFile )
923 BOOL ret;
924 SERVER_START_REQ( truncate_file )
926 req->handle = hFile;
927 ret = !wine_server_call_err( req );
929 SERVER_END_REQ;
930 return ret;
934 /***********************************************************************
935 * GetFileType (KERNEL32.@)
937 DWORD WINAPI GetFileType( HANDLE hFile )
939 NTSTATUS status;
940 int fd;
941 DWORD ret = FILE_TYPE_UNKNOWN;
943 if (is_console_handle( hFile ))
944 return FILE_TYPE_CHAR;
946 if (!(status = wine_server_handle_to_fd( hFile, 0, &fd, NULL, NULL )))
948 struct stat st;
950 if (fstat( fd, &st ) == -1)
951 FILE_SetDosError();
952 else if (S_ISFIFO(st.st_mode) || S_ISSOCK(st.st_mode))
953 ret = FILE_TYPE_PIPE;
954 else if (S_ISCHR(st.st_mode))
955 ret = FILE_TYPE_CHAR;
956 else
957 ret = FILE_TYPE_DISK;
958 wine_server_release_fd( hFile, fd );
960 else SetLastError( RtlNtStatusToDosError(status) );
962 return ret;
966 /**************************************************************************
967 * CopyFileW (KERNEL32.@)
969 BOOL WINAPI CopyFileW( LPCWSTR source, LPCWSTR dest, BOOL fail_if_exists )
971 HANDLE h1, h2;
972 BY_HANDLE_FILE_INFORMATION info;
973 DWORD count;
974 BOOL ret = FALSE;
975 char buffer[2048];
977 if (!source || !dest)
979 SetLastError(ERROR_INVALID_PARAMETER);
980 return FALSE;
983 TRACE("%s -> %s\n", debugstr_w(source), debugstr_w(dest));
985 if ((h1 = CreateFileW(source, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
986 NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE)
988 WARN("Unable to open source %s\n", debugstr_w(source));
989 return FALSE;
992 if (!GetFileInformationByHandle( h1, &info ))
994 WARN("GetFileInformationByHandle returned error for %s\n", debugstr_w(source));
995 CloseHandle( h1 );
996 return FALSE;
999 if ((h2 = CreateFileW( dest, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1000 fail_if_exists ? CREATE_NEW : CREATE_ALWAYS,
1001 info.dwFileAttributes, h1 )) == INVALID_HANDLE_VALUE)
1003 WARN("Unable to open dest %s\n", debugstr_w(dest));
1004 CloseHandle( h1 );
1005 return FALSE;
1008 while (ReadFile( h1, buffer, sizeof(buffer), &count, NULL ) && count)
1010 char *p = buffer;
1011 while (count != 0)
1013 DWORD res;
1014 if (!WriteFile( h2, p, count, &res, NULL ) || !res) goto done;
1015 p += res;
1016 count -= res;
1019 ret = TRUE;
1020 done:
1021 CloseHandle( h1 );
1022 CloseHandle( h2 );
1023 return ret;
1027 /**************************************************************************
1028 * CopyFileA (KERNEL32.@)
1030 BOOL WINAPI CopyFileA( LPCSTR source, LPCSTR dest, BOOL fail_if_exists)
1032 UNICODE_STRING sourceW, destW;
1033 BOOL ret;
1035 if (!source || !dest)
1037 SetLastError(ERROR_INVALID_PARAMETER);
1038 return FALSE;
1041 RtlCreateUnicodeStringFromAsciiz(&sourceW, source);
1042 RtlCreateUnicodeStringFromAsciiz(&destW, dest);
1044 ret = CopyFileW(sourceW.Buffer, destW.Buffer, fail_if_exists);
1046 RtlFreeUnicodeString(&sourceW);
1047 RtlFreeUnicodeString(&destW);
1048 return ret;
1052 /**************************************************************************
1053 * CopyFileExW (KERNEL32.@)
1055 * This implementation ignores most of the extra parameters passed-in into
1056 * the "ex" version of the method and calls the CopyFile method.
1057 * It will have to be fixed eventually.
1059 BOOL WINAPI CopyFileExW(LPCWSTR sourceFilename, LPCWSTR destFilename,
1060 LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
1061 LPBOOL cancelFlagPointer, DWORD copyFlags)
1064 * Interpret the only flag that CopyFile can interpret.
1066 return CopyFileW(sourceFilename, destFilename, (copyFlags & COPY_FILE_FAIL_IF_EXISTS) != 0);
1070 /**************************************************************************
1071 * CopyFileExA (KERNEL32.@)
1073 BOOL WINAPI CopyFileExA(LPCSTR sourceFilename, LPCSTR destFilename,
1074 LPPROGRESS_ROUTINE progressRoutine, LPVOID appData,
1075 LPBOOL cancelFlagPointer, DWORD copyFlags)
1077 UNICODE_STRING sourceW, destW;
1078 BOOL ret;
1080 if (!sourceFilename || !destFilename)
1082 SetLastError(ERROR_INVALID_PARAMETER);
1083 return FALSE;
1086 RtlCreateUnicodeStringFromAsciiz(&sourceW, sourceFilename);
1087 RtlCreateUnicodeStringFromAsciiz(&destW, destFilename);
1089 ret = CopyFileExW(sourceW.Buffer, destW.Buffer, progressRoutine, appData,
1090 cancelFlagPointer, copyFlags);
1092 RtlFreeUnicodeString(&sourceW);
1093 RtlFreeUnicodeString(&destW);
1094 return ret;