Fixed bugs in safe arrays.
[wine.git] / files / file.c
blob8f5d3e4cde9d6f8c0f2274bf6bc577b469b5adcf
1 /*
2 * File handling functions
4 * Copyright 1993 John Burton
5 * Copyright 1996 Alexandre Julliard
7 * TODO:
8 * Fix the CopyFileEx methods to implement the "extended" functionality.
9 * Right now, they simply call the CopyFile method.
12 #include "config.h"
13 #include "wine/port.h"
15 #include <assert.h>
16 #include <ctype.h>
17 #include <errno.h>
18 #include <fcntl.h>
19 #include <stdlib.h>
20 #include <stdio.h>
21 #include <string.h>
22 #ifdef HAVE_SYS_ERRNO_H
23 #include <sys/errno.h>
24 #endif
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #ifdef HAVE_SYS_MMAN_H
28 #include <sys/mman.h>
29 #endif
30 #include <sys/time.h>
31 #include <sys/poll.h>
32 #include <time.h>
33 #include <unistd.h>
34 #include <utime.h>
36 #include "winerror.h"
37 #include "windef.h"
38 #include "winbase.h"
39 #include "wine/winbase16.h"
40 #include "drive.h"
41 #include "file.h"
42 #include "heap.h"
43 #include "msdos.h"
44 #include "wincon.h"
45 #include "debugtools.h"
47 #include "wine/server.h"
49 DEFAULT_DEBUG_CHANNEL(file);
51 #if defined(MAP_ANONYMOUS) && !defined(MAP_ANON)
52 #define MAP_ANON MAP_ANONYMOUS
53 #endif
55 /* Size of per-process table of DOS handles */
56 #define DOS_TABLE_SIZE 256
58 static HANDLE dos_handles[DOS_TABLE_SIZE];
61 /***********************************************************************
62 * FILE_ConvertOFMode
64 * Convert OF_* mode into flags for CreateFile.
66 static void FILE_ConvertOFMode( INT mode, DWORD *access, DWORD *sharing )
68 switch(mode & 0x03)
70 case OF_READ: *access = GENERIC_READ; break;
71 case OF_WRITE: *access = GENERIC_WRITE; break;
72 case OF_READWRITE: *access = GENERIC_READ | GENERIC_WRITE; break;
73 default: *access = 0; break;
75 switch(mode & 0x70)
77 case OF_SHARE_EXCLUSIVE: *sharing = 0; break;
78 case OF_SHARE_DENY_WRITE: *sharing = FILE_SHARE_READ; break;
79 case OF_SHARE_DENY_READ: *sharing = FILE_SHARE_WRITE; break;
80 case OF_SHARE_DENY_NONE:
81 case OF_SHARE_COMPAT:
82 default: *sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
87 /***********************************************************************
88 * FILE_strcasecmp
90 * locale-independent case conversion for file I/O
92 int FILE_strcasecmp( const char *str1, const char *str2 )
94 for (;;)
96 int ret = FILE_toupper(*str1) - FILE_toupper(*str2);
97 if (ret || !*str1) return ret;
98 str1++;
99 str2++;
104 /***********************************************************************
105 * FILE_strncasecmp
107 * locale-independent case conversion for file I/O
109 int FILE_strncasecmp( const char *str1, const char *str2, int len )
111 int ret = 0;
112 for ( ; len > 0; len--, str1++, str2++)
113 if ((ret = FILE_toupper(*str1) - FILE_toupper(*str2)) || !*str1) break;
114 return ret;
118 /***********************************************************************
119 * FILE_SetDosError
121 * Set the DOS error code from errno.
123 void FILE_SetDosError(void)
125 int save_errno = errno; /* errno gets overwritten by printf */
127 TRACE("errno = %d %s\n", errno, strerror(errno));
128 switch (save_errno)
130 case EAGAIN:
131 SetLastError( ERROR_SHARING_VIOLATION );
132 break;
133 case EBADF:
134 SetLastError( ERROR_INVALID_HANDLE );
135 break;
136 case ENOSPC:
137 SetLastError( ERROR_HANDLE_DISK_FULL );
138 break;
139 case EACCES:
140 case EPERM:
141 case EROFS:
142 SetLastError( ERROR_ACCESS_DENIED );
143 break;
144 case EBUSY:
145 SetLastError( ERROR_LOCK_VIOLATION );
146 break;
147 case ENOENT:
148 SetLastError( ERROR_FILE_NOT_FOUND );
149 break;
150 case EISDIR:
151 SetLastError( ERROR_CANNOT_MAKE );
152 break;
153 case ENFILE:
154 case EMFILE:
155 SetLastError( ERROR_NO_MORE_FILES );
156 break;
157 case EEXIST:
158 SetLastError( ERROR_FILE_EXISTS );
159 break;
160 case EINVAL:
161 case ESPIPE:
162 SetLastError( ERROR_SEEK );
163 break;
164 case ENOTEMPTY:
165 SetLastError( ERROR_DIR_NOT_EMPTY );
166 break;
167 case ENOEXEC:
168 SetLastError( ERROR_BAD_FORMAT );
169 break;
170 default:
171 WARN("unknown file error: %s\n", strerror(save_errno) );
172 SetLastError( ERROR_GEN_FAILURE );
173 break;
175 errno = save_errno;
179 /***********************************************************************
180 * FILE_DupUnixHandle
182 * Duplicate a Unix handle into a task handle.
183 * Returns 0 on failure.
185 HANDLE FILE_DupUnixHandle( int fd, DWORD access )
187 HANDLE ret;
189 wine_server_send_fd( fd );
191 SERVER_START_REQ( alloc_file_handle )
193 req->access = access;
194 req->fd = fd;
195 SERVER_CALL();
196 ret = req->handle;
198 SERVER_END_REQ;
199 return ret;
203 /***********************************************************************
204 * FILE_GetUnixHandleType
206 * Retrieve the Unix handle corresponding to a file handle.
207 * Returns -1 on failure.
209 int FILE_GetUnixHandleType( HANDLE handle, DWORD access, DWORD *type )
211 int ret, fd = -1;
215 SERVER_START_REQ( get_handle_fd )
217 req->handle = handle;
218 req->access = access;
219 if (!(ret = SERVER_CALL_ERR()))
221 fd = req->fd;
223 if (type) *type = req->type;
225 SERVER_END_REQ;
226 if (ret) return -1;
228 if (fd == -1) /* it wasn't in the cache, get it from the server */
229 fd = wine_server_recv_fd( handle );
231 } while (fd == -2); /* -2 means race condition, so restart from scratch */
233 if (fd != -1)
235 if ((fd = dup(fd)) == -1)
236 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
238 return fd;
241 /***********************************************************************
242 * FILE_GetUnixHandle
244 * Retrieve the Unix handle corresponding to a file handle.
245 * Returns -1 on failure.
247 int FILE_GetUnixHandle( HANDLE handle, DWORD access )
249 return FILE_GetUnixHandleType(handle, access, NULL);
252 /*************************************************************************
253 * FILE_OpenConsole
255 * Open a handle to the current process console.
256 * Returns 0 on failure.
258 static HANDLE FILE_OpenConsole( BOOL output, DWORD access, LPSECURITY_ATTRIBUTES sa )
260 HANDLE ret;
262 SERVER_START_REQ( open_console )
264 req->output = output;
265 req->access = access;
266 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
267 SetLastError(0);
268 SERVER_CALL_ERR();
269 ret = req->handle;
271 SERVER_END_REQ;
272 return ret;
276 /***********************************************************************
277 * FILE_CreateFile
279 * Implementation of CreateFile. Takes a Unix path name.
280 * Returns 0 on failure.
282 HANDLE FILE_CreateFile( LPCSTR filename, DWORD access, DWORD sharing,
283 LPSECURITY_ATTRIBUTES sa, DWORD creation,
284 DWORD attributes, HANDLE template, BOOL fail_read_only )
286 DWORD err;
287 HANDLE ret;
288 size_t len = strlen(filename);
290 if (len > REQUEST_MAX_VAR_SIZE)
292 FIXME("filename '%s' too long\n", filename );
293 SetLastError( ERROR_INVALID_PARAMETER );
294 return 0;
297 restart:
298 SERVER_START_VAR_REQ( create_file, len )
300 req->access = access;
301 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
302 req->sharing = sharing;
303 req->create = creation;
304 req->attrs = attributes;
305 memcpy( server_data_ptr(req), filename, len );
306 SetLastError(0);
307 err = SERVER_CALL();
308 ret = req->handle;
310 SERVER_END_VAR_REQ;
312 /* If write access failed, retry without GENERIC_WRITE */
314 if (!ret && !fail_read_only && (access & GENERIC_WRITE))
316 if ((err == STATUS_MEDIA_WRITE_PROTECTED) || (err == STATUS_ACCESS_DENIED))
318 TRACE("Write access failed for file '%s', trying without "
319 "write access\n", filename);
320 access &= ~GENERIC_WRITE;
321 goto restart;
325 if (err) SetLastError( RtlNtStatusToDosError(err) );
327 if (!ret)
328 WARN("Unable to create file '%s' (GLE %ld)\n", filename, GetLastError());
330 return ret;
334 /***********************************************************************
335 * FILE_CreateDevice
337 * Same as FILE_CreateFile but for a device
338 * Returns 0 on failure.
340 HANDLE FILE_CreateDevice( int client_id, DWORD access, LPSECURITY_ATTRIBUTES sa )
342 HANDLE ret;
343 SERVER_START_REQ( create_device )
345 req->access = access;
346 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
347 req->id = client_id;
348 SetLastError(0);
349 SERVER_CALL_ERR();
350 ret = req->handle;
352 SERVER_END_REQ;
353 return ret;
356 static HANDLE FILE_OpenPipe(LPCSTR name, DWORD access)
358 HANDLE ret;
359 DWORD len = name ? MultiByteToWideChar( CP_ACP, 0, name, strlen(name), NULL, 0 ) : 0;
361 TRACE("name %s access %lx\n",name,access);
363 if (len >= MAX_PATH)
365 SetLastError( ERROR_FILENAME_EXCED_RANGE );
366 return 0;
368 SERVER_START_VAR_REQ( open_named_pipe, len * sizeof(WCHAR) )
370 req->access = access;
372 if (len) MultiByteToWideChar( CP_ACP, 0, name, strlen(name), server_data_ptr(req), len );
373 SetLastError(0);
374 SERVER_CALL_ERR();
375 ret = req->handle;
377 SERVER_END_VAR_REQ;
378 TRACE("Returned %d\n",ret);
379 return ret;
382 /*************************************************************************
383 * CreateFileA [KERNEL32.@] Creates or opens a file or other object
385 * Creates or opens an object, and returns a handle that can be used to
386 * access that object.
388 * PARAMS
390 * filename [in] pointer to filename to be accessed
391 * access [in] access mode requested
392 * sharing [in] share mode
393 * sa [in] pointer to security attributes
394 * creation [in] how to create the file
395 * attributes [in] attributes for newly created file
396 * template [in] handle to file with extended attributes to copy
398 * RETURNS
399 * Success: Open handle to specified file
400 * Failure: INVALID_HANDLE_VALUE
402 * NOTES
403 * Should call SetLastError() on failure.
405 * BUGS
407 * Doesn't support character devices, template files, or a
408 * lot of the 'attributes' flags yet.
410 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
411 LPSECURITY_ATTRIBUTES sa, DWORD creation,
412 DWORD attributes, HANDLE template )
414 DOS_FULL_NAME full_name;
415 HANDLE ret;
417 if (!filename)
419 SetLastError( ERROR_INVALID_PARAMETER );
420 return INVALID_HANDLE_VALUE;
422 TRACE("%s %s%s%s%s%s%s%s\n",filename,
423 ((access & GENERIC_READ)==GENERIC_READ)?"GENERIC_READ ":"",
424 ((access & GENERIC_WRITE)==GENERIC_WRITE)?"GENERIC_WRITE ":"",
425 (!access)?"QUERY_ACCESS ":"",
426 ((sharing & FILE_SHARE_READ)==FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
427 ((sharing & FILE_SHARE_WRITE)==FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
428 ((sharing & FILE_SHARE_DELETE)==FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
429 (creation ==CREATE_NEW)?"CREATE_NEW":
430 (creation ==CREATE_ALWAYS)?"CREATE_ALWAYS ":
431 (creation ==OPEN_EXISTING)?"OPEN_EXISTING ":
432 (creation ==OPEN_ALWAYS)?"OPEN_ALWAYS ":
433 (creation ==TRUNCATE_EXISTING)?"TRUNCATE_EXISTING ":"");
435 /* If the name starts with '\\?\', ignore the first 4 chars. */
436 if (!strncmp(filename, "\\\\?\\", 4))
438 filename += 4;
439 if (!strncmp(filename, "UNC\\", 4))
441 FIXME("UNC name (%s) not supported.\n", filename );
442 SetLastError( ERROR_PATH_NOT_FOUND );
443 return INVALID_HANDLE_VALUE;
447 if (!strncmp(filename, "\\\\.\\", 4)) {
448 if(!strncasecmp(&filename[4],"pipe\\",5))
450 TRACE("Opening a pipe: %s\n",filename);
451 ret = FILE_OpenPipe(filename,access);
452 goto done;
454 else if (!DOSFS_GetDevice( filename ))
456 ret = DEVICE_Open( filename+4, access, sa );
457 goto done;
459 else
460 filename+=4; /* fall into DOSFS_Device case below */
463 /* If the name still starts with '\\', it's a UNC name. */
464 if (!strncmp(filename, "\\\\", 2))
466 FIXME("UNC name (%s) not supported.\n", filename );
467 SetLastError( ERROR_PATH_NOT_FOUND );
468 return INVALID_HANDLE_VALUE;
471 /* If the name contains a DOS wild card (* or ?), do no create a file */
472 if(strchr(filename,'*') || strchr(filename,'?'))
473 return INVALID_HANDLE_VALUE;
475 /* Open a console for CONIN$ or CONOUT$ */
476 if (!strcasecmp(filename, "CONIN$"))
478 ret = FILE_OpenConsole( FALSE, access, sa );
479 goto done;
481 if (!strcasecmp(filename, "CONOUT$"))
483 ret = FILE_OpenConsole( TRUE, access, sa );
484 goto done;
487 if (DOSFS_GetDevice( filename ))
489 TRACE("opening device '%s'\n", filename );
491 if (!(ret = DOSFS_OpenDevice( filename, access, attributes )))
493 /* Do not silence this please. It is a critical error. -MM */
494 ERR("Couldn't open device '%s'!\n",filename);
495 SetLastError( ERROR_FILE_NOT_FOUND );
497 goto done;
500 /* check for filename, don't check for last entry if creating */
501 if (!DOSFS_GetFullName( filename,
502 (creation == OPEN_EXISTING) ||
503 (creation == TRUNCATE_EXISTING),
504 &full_name )) {
505 WARN("Unable to get full filename from '%s' (GLE %ld)\n",
506 filename, GetLastError());
507 return INVALID_HANDLE_VALUE;
510 ret = FILE_CreateFile( full_name.long_name, access, sharing,
511 sa, creation, attributes, template,
512 DRIVE_GetFlags(full_name.drive) & DRIVE_FAIL_READ_ONLY );
513 done:
514 if (!ret) ret = INVALID_HANDLE_VALUE;
515 return ret;
520 /*************************************************************************
521 * CreateFileW (KERNEL32.@)
523 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
524 LPSECURITY_ATTRIBUTES sa, DWORD creation,
525 DWORD attributes, HANDLE template)
527 LPSTR afn = HEAP_strdupWtoA( GetProcessHeap(), 0, filename );
528 HANDLE res = CreateFileA( afn, access, sharing, sa, creation, attributes, template );
529 HeapFree( GetProcessHeap(), 0, afn );
530 return res;
534 /***********************************************************************
535 * FILE_FillInfo
537 * Fill a file information from a struct stat.
539 static void FILE_FillInfo( struct stat *st, BY_HANDLE_FILE_INFORMATION *info )
541 if (S_ISDIR(st->st_mode))
542 info->dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
543 else
544 info->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
545 if (!(st->st_mode & S_IWUSR))
546 info->dwFileAttributes |= FILE_ATTRIBUTE_READONLY;
548 RtlSecondsSince1970ToTime( st->st_mtime, &info->ftCreationTime );
549 RtlSecondsSince1970ToTime( st->st_mtime, &info->ftLastWriteTime );
550 RtlSecondsSince1970ToTime( st->st_atime, &info->ftLastAccessTime );
552 info->dwVolumeSerialNumber = 0; /* FIXME */
553 info->nFileSizeHigh = 0;
554 info->nFileSizeLow = 0;
555 if (!S_ISDIR(st->st_mode)) {
556 info->nFileSizeHigh = st->st_size >> 32;
557 info->nFileSizeLow = st->st_size & 0xffffffff;
559 info->nNumberOfLinks = st->st_nlink;
560 info->nFileIndexHigh = 0;
561 info->nFileIndexLow = st->st_ino;
565 /***********************************************************************
566 * FILE_Stat
568 * Stat a Unix path name. Return TRUE if OK.
570 BOOL FILE_Stat( LPCSTR unixName, BY_HANDLE_FILE_INFORMATION *info )
572 struct stat st;
574 if (lstat( unixName, &st ) == -1)
576 FILE_SetDosError();
577 return FALSE;
579 if (!S_ISLNK(st.st_mode)) FILE_FillInfo( &st, info );
580 else
582 /* do a "real" stat to find out
583 about the type of the symlink destination */
584 if (stat( unixName, &st ) == -1)
586 FILE_SetDosError();
587 return FALSE;
589 FILE_FillInfo( &st, info );
590 info->dwFileAttributes |= FILE_ATTRIBUTE_SYMLINK;
592 return TRUE;
596 /***********************************************************************
597 * GetFileInformationByHandle (KERNEL32.@)
599 DWORD WINAPI GetFileInformationByHandle( HANDLE hFile,
600 BY_HANDLE_FILE_INFORMATION *info )
602 DWORD ret;
603 if (!info) return 0;
605 SERVER_START_REQ( get_file_info )
607 req->handle = hFile;
608 if ((ret = !SERVER_CALL_ERR()))
610 /* FIXME: which file types are supported ?
611 * Serial ports (FILE_TYPE_CHAR) are not,
612 * and MSDN also says that pipes are not supported.
613 * FILE_TYPE_REMOTE seems to be supported according to
614 * MSDN q234741.txt */
615 if ((req->type == FILE_TYPE_DISK)
616 || (req->type == FILE_TYPE_REMOTE))
618 RtlSecondsSince1970ToTime( req->write_time, &info->ftCreationTime );
619 RtlSecondsSince1970ToTime( req->write_time, &info->ftLastWriteTime );
620 RtlSecondsSince1970ToTime( req->access_time, &info->ftLastAccessTime );
621 info->dwFileAttributes = req->attr;
622 info->dwVolumeSerialNumber = req->serial;
623 info->nFileSizeHigh = req->size_high;
624 info->nFileSizeLow = req->size_low;
625 info->nNumberOfLinks = req->links;
626 info->nFileIndexHigh = req->index_high;
627 info->nFileIndexLow = req->index_low;
629 else
631 SetLastError(ERROR_NOT_SUPPORTED);
632 ret = 0;
636 SERVER_END_REQ;
637 return ret;
641 /**************************************************************************
642 * GetFileAttributes (KERNEL.420)
644 DWORD WINAPI GetFileAttributes16( LPCSTR name )
646 return GetFileAttributesA( name );
650 /**************************************************************************
651 * GetFileAttributesA (KERNEL32.@)
653 DWORD WINAPI GetFileAttributesA( LPCSTR name )
655 DOS_FULL_NAME full_name;
656 BY_HANDLE_FILE_INFORMATION info;
658 if (name == NULL)
660 SetLastError( ERROR_INVALID_PARAMETER );
661 return -1;
663 if (!DOSFS_GetFullName( name, TRUE, &full_name) )
664 return -1;
665 if (!FILE_Stat( full_name.long_name, &info )) return -1;
666 return info.dwFileAttributes;
670 /**************************************************************************
671 * GetFileAttributesW (KERNEL32.@)
673 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
675 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
676 DWORD res = GetFileAttributesA( nameA );
677 HeapFree( GetProcessHeap(), 0, nameA );
678 return res;
682 /***********************************************************************
683 * GetFileSize (KERNEL32.@)
685 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
687 BY_HANDLE_FILE_INFORMATION info;
688 if (!GetFileInformationByHandle( hFile, &info )) return -1;
689 if (filesizehigh) *filesizehigh = info.nFileSizeHigh;
690 return info.nFileSizeLow;
694 /***********************************************************************
695 * GetFileTime (KERNEL32.@)
697 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
698 FILETIME *lpLastAccessTime,
699 FILETIME *lpLastWriteTime )
701 BY_HANDLE_FILE_INFORMATION info;
702 if (!GetFileInformationByHandle( hFile, &info )) return FALSE;
703 if (lpCreationTime) *lpCreationTime = info.ftCreationTime;
704 if (lpLastAccessTime) *lpLastAccessTime = info.ftLastAccessTime;
705 if (lpLastWriteTime) *lpLastWriteTime = info.ftLastWriteTime;
706 return TRUE;
709 /***********************************************************************
710 * CompareFileTime (KERNEL32.@)
712 INT WINAPI CompareFileTime( LPFILETIME x, LPFILETIME y )
714 if (!x || !y) return -1;
716 if (x->dwHighDateTime > y->dwHighDateTime)
717 return 1;
718 if (x->dwHighDateTime < y->dwHighDateTime)
719 return -1;
720 if (x->dwLowDateTime > y->dwLowDateTime)
721 return 1;
722 if (x->dwLowDateTime < y->dwLowDateTime)
723 return -1;
724 return 0;
727 /***********************************************************************
728 * FILE_GetTempFileName : utility for GetTempFileName
730 static UINT FILE_GetTempFileName( LPCSTR path, LPCSTR prefix, UINT unique,
731 LPSTR buffer, BOOL isWin16 )
733 static UINT unique_temp;
734 DOS_FULL_NAME full_name;
735 int i;
736 LPSTR p;
737 UINT num;
739 if ( !path || !prefix || !buffer ) return 0;
741 if (!unique_temp) unique_temp = time(NULL) & 0xffff;
742 num = unique ? (unique & 0xffff) : (unique_temp++ & 0xffff);
744 strcpy( buffer, path );
745 p = buffer + strlen(buffer);
747 /* add a \, if there isn't one and path is more than just the drive letter ... */
748 if ( !((strlen(buffer) == 2) && (buffer[1] == ':'))
749 && ((p == buffer) || (p[-1] != '\\'))) *p++ = '\\';
751 if (isWin16) *p++ = '~';
752 for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
753 sprintf( p, "%04x.tmp", num );
755 /* Now try to create it */
757 if (!unique)
761 HFILE handle = CreateFileA( buffer, GENERIC_WRITE, 0, NULL,
762 CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
763 if (handle != INVALID_HANDLE_VALUE)
764 { /* We created it */
765 TRACE("created %s\n",
766 buffer);
767 CloseHandle( handle );
768 break;
770 if (GetLastError() != ERROR_FILE_EXISTS)
771 break; /* No need to go on */
772 num++;
773 sprintf( p, "%04x.tmp", num );
774 } while (num != (unique & 0xffff));
777 /* Get the full path name */
779 if (DOSFS_GetFullName( buffer, FALSE, &full_name ))
781 /* Check if we have write access in the directory */
782 if ((p = strrchr( full_name.long_name, '/' ))) *p = '\0';
783 if (access( full_name.long_name, W_OK ) == -1)
784 WARN("returns '%s', which doesn't seem to be writeable.\n",
785 buffer);
787 TRACE("returning %s\n", buffer );
788 return unique ? unique : num;
792 /***********************************************************************
793 * GetTempFileNameA (KERNEL32.@)
795 UINT WINAPI GetTempFileNameA( LPCSTR path, LPCSTR prefix, UINT unique,
796 LPSTR buffer)
798 return FILE_GetTempFileName(path, prefix, unique, buffer, FALSE);
801 /***********************************************************************
802 * GetTempFileNameW (KERNEL32.@)
804 UINT WINAPI GetTempFileNameW( LPCWSTR path, LPCWSTR prefix, UINT unique,
805 LPWSTR buffer )
807 LPSTR patha,prefixa;
808 char buffera[144];
809 UINT ret;
811 if (!path) return 0;
812 patha = HEAP_strdupWtoA( GetProcessHeap(), 0, path );
813 prefixa = HEAP_strdupWtoA( GetProcessHeap(), 0, prefix );
814 ret = FILE_GetTempFileName( patha, prefixa, unique, buffera, FALSE );
815 MultiByteToWideChar( CP_ACP, 0, buffera, -1, buffer, MAX_PATH );
816 HeapFree( GetProcessHeap(), 0, patha );
817 HeapFree( GetProcessHeap(), 0, prefixa );
818 return ret;
822 /***********************************************************************
823 * GetTempFileName (KERNEL.97)
825 UINT16 WINAPI GetTempFileName16( BYTE drive, LPCSTR prefix, UINT16 unique,
826 LPSTR buffer )
828 char temppath[144];
830 if (!(drive & ~TF_FORCEDRIVE)) /* drive 0 means current default drive */
831 drive |= DRIVE_GetCurrentDrive() + 'A';
833 if ((drive & TF_FORCEDRIVE) &&
834 !DRIVE_IsValid( toupper(drive & ~TF_FORCEDRIVE) - 'A' ))
836 drive &= ~TF_FORCEDRIVE;
837 WARN("invalid drive %d specified\n", drive );
840 if (drive & TF_FORCEDRIVE)
841 sprintf(temppath,"%c:", drive & ~TF_FORCEDRIVE );
842 else
843 GetTempPathA( 132, temppath );
844 return (UINT16)FILE_GetTempFileName( temppath, prefix, unique, buffer, TRUE );
847 /***********************************************************************
848 * FILE_DoOpenFile
850 * Implementation of OpenFile16() and OpenFile32().
852 static HFILE FILE_DoOpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode,
853 BOOL win32 )
855 HFILE hFileRet;
856 FILETIME filetime;
857 WORD filedatetime[2];
858 DOS_FULL_NAME full_name;
859 DWORD access, sharing;
860 char *p;
862 if (!ofs) return HFILE_ERROR;
864 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
865 ((mode & 0x3 )==OF_READ)?"OF_READ":
866 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
867 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
868 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
869 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
870 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
871 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
872 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
873 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
874 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
875 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
876 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
877 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
878 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
879 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
880 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
881 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
885 ofs->cBytes = sizeof(OFSTRUCT);
886 ofs->nErrCode = 0;
887 if (mode & OF_REOPEN) name = ofs->szPathName;
889 if (!name) {
890 ERR("called with `name' set to NULL ! Please debug.\n");
891 return HFILE_ERROR;
894 TRACE("%s %04x\n", name, mode );
896 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
897 Are there any cases where getting the path here is wrong?
898 Uwe Bonnes 1997 Apr 2 */
899 if (!GetFullPathNameA( name, sizeof(ofs->szPathName),
900 ofs->szPathName, NULL )) goto error;
901 FILE_ConvertOFMode( mode, &access, &sharing );
903 /* OF_PARSE simply fills the structure */
905 if (mode & OF_PARSE)
907 ofs->fFixedDisk = (GetDriveType16( ofs->szPathName[0]-'A' )
908 != DRIVE_REMOVABLE);
909 TRACE("(%s): OF_PARSE, res = '%s'\n",
910 name, ofs->szPathName );
911 return 0;
914 /* OF_CREATE is completely different from all other options, so
915 handle it first */
917 if (mode & OF_CREATE)
919 if ((hFileRet = CreateFileA( name, GENERIC_READ | GENERIC_WRITE,
920 sharing, NULL, CREATE_ALWAYS,
921 FILE_ATTRIBUTE_NORMAL, 0 ))== INVALID_HANDLE_VALUE)
922 goto error;
923 goto success;
926 /* If OF_SEARCH is set, ignore the given path */
928 if ((mode & OF_SEARCH) && !(mode & OF_REOPEN))
930 /* First try the file name as is */
931 if (DOSFS_GetFullName( name, TRUE, &full_name )) goto found;
932 /* Now remove the path */
933 if (name[0] && (name[1] == ':')) name += 2;
934 if ((p = strrchr( name, '\\' ))) name = p + 1;
935 if ((p = strrchr( name, '/' ))) name = p + 1;
936 if (!name[0]) goto not_found;
939 /* Now look for the file */
941 if (!DIR_SearchPath( NULL, name, NULL, &full_name, win32 )) goto not_found;
943 found:
944 TRACE("found %s = %s\n",
945 full_name.long_name, full_name.short_name );
946 lstrcpynA( ofs->szPathName, full_name.short_name,
947 sizeof(ofs->szPathName) );
949 if (mode & OF_SHARE_EXCLUSIVE)
950 /* Some InstallShield version uses OF_SHARE_EXCLUSIVE
951 on the file <tempdir>/_ins0432._mp to determine how
952 far installation has proceeded.
953 _ins0432._mp is an executable and while running the
954 application expects the open with OF_SHARE_ to fail*/
955 /* Probable FIXME:
956 As our loader closes the files after loading the executable,
957 we can't find the running executable with FILE_InUse.
958 The loader should keep the file open, as Windows does that, too.
961 char *last = strrchr(full_name.long_name,'/');
962 if (!last)
963 last = full_name.long_name - 1;
964 if (GetModuleHandle16(last+1))
966 TRACE("Denying shared open for %s\n",full_name.long_name);
967 return HFILE_ERROR;
971 if (mode & OF_DELETE)
973 if (unlink( full_name.long_name ) == -1) goto not_found;
974 TRACE("(%s): OF_DELETE return = OK\n", name);
975 return 1;
978 hFileRet = FILE_CreateFile( full_name.long_name, access, sharing,
979 NULL, OPEN_EXISTING, 0, 0,
980 DRIVE_GetFlags(full_name.drive) & DRIVE_FAIL_READ_ONLY );
981 if (!hFileRet) goto not_found;
983 GetFileTime( hFileRet, NULL, NULL, &filetime );
984 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
985 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
987 if (memcmp( ofs->reserved, filedatetime, sizeof(ofs->reserved) ))
989 CloseHandle( hFileRet );
990 WARN("(%s): OF_VERIFY failed\n", name );
991 /* FIXME: what error here? */
992 SetLastError( ERROR_FILE_NOT_FOUND );
993 goto error;
996 memcpy( ofs->reserved, filedatetime, sizeof(ofs->reserved) );
998 success: /* We get here if the open was successful */
999 TRACE("(%s): OK, return = %d\n", name, hFileRet );
1000 if (win32)
1002 if (mode & OF_EXIST) /* Return the handle, but close it first */
1003 CloseHandle( hFileRet );
1005 else
1007 hFileRet = Win32HandleToDosFileHandle( hFileRet );
1008 if (hFileRet == HFILE_ERROR16) goto error;
1009 if (mode & OF_EXIST) /* Return the handle, but close it first */
1010 _lclose16( hFileRet );
1012 return hFileRet;
1014 not_found: /* We get here if the file does not exist */
1015 WARN("'%s' not found or sharing violation\n", name );
1016 SetLastError( ERROR_FILE_NOT_FOUND );
1017 /* fall through */
1019 error: /* We get here if there was an error opening the file */
1020 ofs->nErrCode = GetLastError();
1021 WARN("(%s): return = HFILE_ERROR error= %d\n",
1022 name,ofs->nErrCode );
1023 return HFILE_ERROR;
1027 /***********************************************************************
1028 * OpenFile (KERNEL.74)
1029 * OpenFileEx (KERNEL.360)
1031 HFILE16 WINAPI OpenFile16( LPCSTR name, OFSTRUCT *ofs, UINT16 mode )
1033 return FILE_DoOpenFile( name, ofs, mode, FALSE );
1037 /***********************************************************************
1038 * OpenFile (KERNEL32.@)
1040 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
1042 return FILE_DoOpenFile( name, ofs, mode, TRUE );
1046 /***********************************************************************
1047 * FILE_InitProcessDosHandles
1049 * Allocates the default DOS handles for a process. Called either by
1050 * Win32HandleToDosFileHandle below or by the DOSVM stuff.
1052 static void FILE_InitProcessDosHandles( void )
1054 dos_handles[0] = GetStdHandle(STD_INPUT_HANDLE);
1055 dos_handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
1056 dos_handles[2] = GetStdHandle(STD_ERROR_HANDLE);
1057 dos_handles[3] = GetStdHandle(STD_ERROR_HANDLE);
1058 dos_handles[4] = GetStdHandle(STD_ERROR_HANDLE);
1061 /***********************************************************************
1062 * Win32HandleToDosFileHandle (KERNEL32.21)
1064 * Allocate a DOS handle for a Win32 handle. The Win32 handle is no
1065 * longer valid after this function (even on failure).
1067 * Note: this is not exactly right, since on Win95 the Win32 handles
1068 * are on top of DOS handles and we do it the other way
1069 * around. Should be good enough though.
1071 HFILE WINAPI Win32HandleToDosFileHandle( HANDLE handle )
1073 int i;
1075 if (!handle || (handle == INVALID_HANDLE_VALUE))
1076 return HFILE_ERROR;
1078 for (i = 5; i < DOS_TABLE_SIZE; i++)
1079 if (!dos_handles[i])
1081 dos_handles[i] = handle;
1082 TRACE("Got %d for h32 %d\n", i, handle );
1083 return (HFILE)i;
1085 CloseHandle( handle );
1086 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1087 return HFILE_ERROR;
1091 /***********************************************************************
1092 * DosFileHandleToWin32Handle (KERNEL32.20)
1094 * Return the Win32 handle for a DOS handle.
1096 * Note: this is not exactly right, since on Win95 the Win32 handles
1097 * are on top of DOS handles and we do it the other way
1098 * around. Should be good enough though.
1100 HANDLE WINAPI DosFileHandleToWin32Handle( HFILE handle )
1102 HFILE16 hfile = (HFILE16)handle;
1103 if (hfile < 5 && !dos_handles[hfile]) FILE_InitProcessDosHandles();
1104 if ((hfile >= DOS_TABLE_SIZE) || !dos_handles[hfile])
1106 SetLastError( ERROR_INVALID_HANDLE );
1107 return INVALID_HANDLE_VALUE;
1109 return dos_handles[hfile];
1113 /***********************************************************************
1114 * DisposeLZ32Handle (KERNEL32.22)
1116 * Note: this is not entirely correct, we should only close the
1117 * 32-bit handle and not the 16-bit one, but we cannot do
1118 * this because of the way our DOS handles are implemented.
1119 * It shouldn't break anything though.
1121 void WINAPI DisposeLZ32Handle( HANDLE handle )
1123 int i;
1125 if (!handle || (handle == INVALID_HANDLE_VALUE)) return;
1127 for (i = 5; i < DOS_TABLE_SIZE; i++)
1128 if (dos_handles[i] == handle)
1130 dos_handles[i] = 0;
1131 CloseHandle( handle );
1132 break;
1137 /***********************************************************************
1138 * FILE_Dup2
1140 * dup2() function for DOS handles.
1142 HFILE16 FILE_Dup2( HFILE16 hFile1, HFILE16 hFile2 )
1144 HANDLE new_handle;
1146 if (hFile1 < 5 && !dos_handles[hFile1]) FILE_InitProcessDosHandles();
1148 if ((hFile1 >= DOS_TABLE_SIZE) || (hFile2 >= DOS_TABLE_SIZE) || !dos_handles[hFile1])
1150 SetLastError( ERROR_INVALID_HANDLE );
1151 return HFILE_ERROR16;
1153 if (hFile2 < 5)
1155 FIXME("stdio handle closed, need proper conversion\n" );
1156 SetLastError( ERROR_INVALID_HANDLE );
1157 return HFILE_ERROR16;
1159 if (!DuplicateHandle( GetCurrentProcess(), dos_handles[hFile1],
1160 GetCurrentProcess(), &new_handle,
1161 0, FALSE, DUPLICATE_SAME_ACCESS ))
1162 return HFILE_ERROR16;
1163 if (dos_handles[hFile2]) CloseHandle( dos_handles[hFile2] );
1164 dos_handles[hFile2] = new_handle;
1165 return hFile2;
1169 /***********************************************************************
1170 * _lclose (KERNEL.81)
1172 HFILE16 WINAPI _lclose16( HFILE16 hFile )
1174 if (hFile < 5)
1176 FIXME("stdio handle closed, need proper conversion\n" );
1177 SetLastError( ERROR_INVALID_HANDLE );
1178 return HFILE_ERROR16;
1180 if ((hFile >= DOS_TABLE_SIZE) || !dos_handles[hFile])
1182 SetLastError( ERROR_INVALID_HANDLE );
1183 return HFILE_ERROR16;
1185 TRACE("%d (handle32=%d)\n", hFile, dos_handles[hFile] );
1186 CloseHandle( dos_handles[hFile] );
1187 dos_handles[hFile] = 0;
1188 return 0;
1192 /***********************************************************************
1193 * _lclose (KERNEL32.@)
1195 HFILE WINAPI _lclose( HFILE hFile )
1197 TRACE("handle %d\n", hFile );
1198 return CloseHandle( hFile ) ? 0 : HFILE_ERROR;
1201 /***********************************************************************
1202 * GetOverlappedResult (KERNEL32.@)
1204 * Check the result of an Asynchronous data transfer from a file.
1206 * RETURNS
1207 * TRUE on success
1208 * FALSE on failure
1210 * If successful (and relevant) lpTransfered will hold the number of
1211 * bytes transfered during the async operation.
1213 * BUGS
1215 * Currently only works for WaitCommEvent, ReadFile, WriteFile
1216 * with communications ports.
1219 BOOL WINAPI GetOverlappedResult(
1220 HANDLE hFile, /* [in] handle of file to check on */
1221 LPOVERLAPPED lpOverlapped, /* [in/out] pointer to overlapped */
1222 LPDWORD lpTransferred, /* [in/out] number of bytes transfered */
1223 BOOL bWait /* [in] wait for the transfer to complete ? */
1225 DWORD r;
1227 TRACE("(%d %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait);
1229 if(lpOverlapped==NULL)
1231 ERR("lpOverlapped was null\n");
1232 return FALSE;
1234 if(!lpOverlapped->hEvent)
1236 ERR("lpOverlapped->hEvent was null\n");
1237 return FALSE;
1240 do {
1241 TRACE("waiting on %p\n",lpOverlapped);
1242 r = WaitForSingleObjectEx(lpOverlapped->hEvent, bWait?INFINITE:0, TRUE);
1243 TRACE("wait on %p returned %ld\n",lpOverlapped,r);
1244 } while (r==STATUS_USER_APC);
1246 if(lpTransferred)
1247 *lpTransferred = lpOverlapped->InternalHigh;
1249 SetLastError(lpOverlapped->Internal);
1251 return (r==WAIT_OBJECT_0);
1255 /***********************************************************************
1256 * CancelIo (KERNEL32.@)
1258 BOOL WINAPI CancelIo(HANDLE handle)
1260 FIXME("(%d) stub\n",handle);
1261 return FALSE;
1264 /***********************************************************************
1265 * FILE_AsyncReadService (INTERNAL)
1267 * This function is called while the client is waiting on the
1268 * server, so we can't make any server calls here.
1270 static void FILE_AsyncReadService(async_private *ovp, int events)
1272 LPOVERLAPPED lpOverlapped = ovp->lpOverlapped;
1273 int result, r;
1275 TRACE("%p %p %08x\n", lpOverlapped, ovp->buffer, events );
1277 /* if POLLNVAL, then our fd was closed or we have the wrong fd */
1278 if(events&POLLNVAL)
1280 ERR("fd %d invalid for %p\n",ovp->fd,ovp);
1281 r = STATUS_UNSUCCESSFUL;
1282 goto async_end;
1285 /* if there are no events, it must be a timeout */
1286 if(events==0)
1288 TRACE("read timed out\n");
1289 r = STATUS_TIMEOUT;
1290 goto async_end;
1293 /* check to see if the data is ready (non-blocking) */
1294 result = read(ovp->fd, &ovp->buffer[lpOverlapped->InternalHigh],
1295 ovp->count - lpOverlapped->InternalHigh);
1297 if ( (result<0) && ((errno == EAGAIN) || (errno == EINTR)))
1299 TRACE("Deferred read %d\n",errno);
1300 r = STATUS_PENDING;
1301 goto async_end;
1304 /* check to see if the transfer is complete */
1305 if(result<0)
1307 TRACE("read returned errno %d\n",errno);
1308 r = STATUS_UNSUCCESSFUL;
1309 goto async_end;
1312 lpOverlapped->InternalHigh += result;
1313 TRACE("read %d more bytes %ld/%d so far\n",result,lpOverlapped->InternalHigh,ovp->count);
1315 if(lpOverlapped->InternalHigh < ovp->count)
1316 r = STATUS_PENDING;
1317 else
1318 r = STATUS_SUCCESS;
1320 async_end:
1321 lpOverlapped->Internal = r;
1324 /* flogged from wineserver */
1325 /* add a timeout in milliseconds to an absolute time */
1326 static void add_timeout( struct timeval *when, int timeout )
1328 if (timeout)
1330 long sec = timeout / 1000;
1331 if ((when->tv_usec += (timeout - 1000*sec) * 1000) >= 1000000)
1333 when->tv_usec -= 1000000;
1334 when->tv_sec++;
1336 when->tv_sec += sec;
1340 /***********************************************************************
1341 * FILE_ReadFileEx (INTERNAL)
1343 static BOOL FILE_ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
1344 LPOVERLAPPED overlapped,
1345 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
1347 async_private *ovp;
1348 int fd, timeout, ret;
1350 TRACE("file %d to buf %p num %ld %p func %p\n",
1351 hFile, buffer, bytesToRead, overlapped, lpCompletionRoutine);
1353 /* check that there is an overlapped struct with an event flag */
1354 if ( (overlapped==NULL) || NtResetEvent( overlapped->hEvent, NULL ) )
1356 TRACE("Overlapped not specified or invalid event flag\n");
1357 SetLastError(ERROR_INVALID_PARAMETER);
1358 return FALSE;
1362 * Although the overlapped transfer will be done in this thread
1363 * we still need to register the operation with the server, in
1364 * case it is cancelled and to get a file handle and the timeout info.
1366 SERVER_START_REQ(create_async)
1368 req->count = bytesToRead;
1369 req->type = ASYNC_TYPE_READ;
1370 req->file_handle = hFile;
1371 ret = SERVER_CALL();
1372 timeout = req->timeout;
1374 SERVER_END_REQ;
1375 if (ret)
1377 TRACE("server call failed\n");
1378 return FALSE;
1381 fd = FILE_GetUnixHandle( hFile, GENERIC_READ );
1382 if(fd<0)
1384 TRACE("Couldn't get FD\n");
1385 return FALSE;
1388 ovp = (async_private *) HeapAlloc(GetProcessHeap(), 0, sizeof (async_private));
1389 if(!ovp)
1391 TRACE("HeapAlloc Failed\n");
1392 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1393 close(fd);
1394 return FALSE;
1396 ovp->lpOverlapped = overlapped;
1397 ovp->count = bytesToRead;
1398 ovp->completion_func = lpCompletionRoutine;
1399 ovp->timeout = timeout;
1400 gettimeofday(&ovp->tv,NULL);
1401 add_timeout(&ovp->tv,timeout);
1402 ovp->event = POLLIN;
1403 ovp->func = FILE_AsyncReadService;
1404 ovp->buffer = buffer;
1405 ovp->fd = fd;
1407 /* hook this overlap into the pending async operation list */
1408 ovp->next = NtCurrentTeb()->pending_list;
1409 ovp->prev = NULL;
1410 if(ovp->next)
1411 ovp->next->prev = ovp;
1412 NtCurrentTeb()->pending_list = ovp;
1414 return TRUE;
1417 /***********************************************************************
1418 * ReadFileEx (KERNEL32.@)
1420 BOOL WINAPI ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
1421 LPOVERLAPPED overlapped,
1422 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
1424 /* FIXME: MS docs say we shouldn't set overlapped->hEvent */
1425 overlapped->Internal = STATUS_PENDING;
1426 overlapped->InternalHigh = 0;
1427 return FILE_ReadFileEx(hFile,buffer,bytesToRead,overlapped,lpCompletionRoutine);
1430 /***********************************************************************
1431 * ReadFile (KERNEL32.@)
1433 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
1434 LPDWORD bytesRead, LPOVERLAPPED overlapped )
1436 int unix_handle, result;
1437 DWORD type;
1439 TRACE("%d %p %ld %p %p\n", hFile, buffer, bytesToRead,
1440 bytesRead, overlapped );
1442 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
1443 if (!bytesToRead) return TRUE;
1445 unix_handle = FILE_GetUnixHandleType( hFile, GENERIC_READ, &type );
1446 if (unix_handle == -1)
1447 return FALSE;
1449 switch(type)
1451 case FD_TYPE_OVERLAPPED:
1452 if(!overlapped)
1454 close(unix_handle);
1455 SetLastError(ERROR_INVALID_PARAMETER);
1456 return FALSE;
1459 /* see if we can read some data already (this shouldn't block) */
1460 result = read( unix_handle, buffer, bytesToRead );
1461 close(unix_handle);
1463 if(result<0)
1465 FILE_SetDosError();
1466 return FALSE;
1469 /* if we read enough to keep the app happy, then return now */
1470 if(result>=bytesToRead)
1472 *bytesRead = result;
1473 return TRUE;
1476 /* at last resort, do an overlapped read */
1477 overlapped->Internal = STATUS_PENDING;
1478 overlapped->InternalHigh = result;
1480 if(!FILE_ReadFileEx(hFile, buffer, bytesToRead, overlapped, NULL))
1481 return FALSE;
1483 /* fail on return, with ERROR_IO_PENDING */
1484 SetLastError(ERROR_IO_PENDING);
1485 return FALSE;
1487 default:
1488 if(overlapped)
1490 close(unix_handle);
1491 SetLastError(ERROR_INVALID_PARAMETER);
1492 return FALSE;
1494 break;
1497 /* code for synchronous reads */
1498 while ((result = read( unix_handle, buffer, bytesToRead )) == -1)
1500 if ((errno == EAGAIN) || (errno == EINTR)) continue;
1501 if ((errno == EFAULT) && !IsBadWritePtr( buffer, bytesToRead )) continue;
1502 FILE_SetDosError();
1503 break;
1505 close( unix_handle );
1506 if (result == -1) return FALSE;
1507 if (bytesRead) *bytesRead = result;
1508 return TRUE;
1512 /***********************************************************************
1513 * FILE_AsyncWriteService (INTERNAL)
1515 * This function is called while the client is waiting on the
1516 * server, so we can't make any server calls here.
1518 static void FILE_AsyncWriteService(struct async_private *ovp, int events)
1520 LPOVERLAPPED lpOverlapped = ovp->lpOverlapped;
1521 int result, r;
1523 TRACE("(%p %p %08x)\n",lpOverlapped,ovp->buffer,events);
1525 /* if POLLNVAL, then our fd was closed or we have the wrong fd */
1526 if(events&POLLNVAL)
1528 ERR("fd %d invalid for %p\n",ovp->fd,ovp);
1529 r = STATUS_UNSUCCESSFUL;
1530 goto async_end;
1533 /* if there are no events, it must be a timeout */
1534 if(events==0)
1536 TRACE("write timed out\n");
1537 r = STATUS_TIMEOUT;
1538 goto async_end;
1541 /* write some data (non-blocking) */
1542 result = write(ovp->fd, &ovp->buffer[lpOverlapped->InternalHigh],
1543 ovp->count-lpOverlapped->InternalHigh);
1545 if ( (result<0) && ((errno == EAGAIN) || (errno == EINTR)))
1547 r = STATUS_PENDING;
1548 goto async_end;
1551 /* check to see if the transfer is complete */
1552 if(result<0)
1554 r = STATUS_UNSUCCESSFUL;
1555 goto async_end;
1558 lpOverlapped->InternalHigh += result;
1560 TRACE("wrote %d more bytes %ld/%d so far\n",result,lpOverlapped->InternalHigh,ovp->count);
1562 if(lpOverlapped->InternalHigh < ovp->count)
1563 r = STATUS_PENDING;
1564 else
1565 r = STATUS_SUCCESS;
1567 async_end:
1568 lpOverlapped->Internal = r;
1571 /***********************************************************************
1572 * WriteFileEx (KERNEL32.@)
1574 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
1575 LPOVERLAPPED overlapped,
1576 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
1578 async_private *ovp;
1579 int timeout,ret;
1581 TRACE("file %d to buf %p num %ld %p func %p stub\n",
1582 hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
1584 if ( (overlapped == NULL) || NtResetEvent( overlapped->hEvent, NULL ) )
1586 SetLastError(ERROR_INVALID_PARAMETER);
1587 return FALSE;
1590 overlapped->Internal = STATUS_PENDING;
1591 overlapped->InternalHigh = 0;
1593 /* need to check the server to get the timeout info */
1594 SERVER_START_REQ(create_async)
1596 req->count = bytesToWrite;
1597 req->type = ASYNC_TYPE_WRITE;
1598 req->file_handle = hFile;
1599 ret = SERVER_CALL();
1600 timeout = req->timeout;
1602 SERVER_END_REQ;
1603 if (ret)
1605 TRACE("server call failed\n");
1606 return FALSE;
1609 ovp = (async_private*) HeapAlloc(GetProcessHeap(), 0, sizeof (async_private));
1610 if(!ovp)
1612 TRACE("HeapAlloc Failed\n");
1613 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1614 return FALSE;
1616 ovp->lpOverlapped = overlapped;
1617 ovp->timeout = timeout;
1618 gettimeofday(&ovp->tv,NULL);
1619 add_timeout(&ovp->tv,timeout);
1620 ovp->event = POLLOUT;
1621 ovp->func = FILE_AsyncWriteService;
1622 ovp->buffer = (LPVOID) buffer;
1623 ovp->count = bytesToWrite;
1624 ovp->completion_func = lpCompletionRoutine;
1625 ovp->fd = FILE_GetUnixHandle( hFile, GENERIC_WRITE );
1626 if(ovp->fd <0)
1628 HeapFree(GetProcessHeap(), 0, ovp);
1629 return FALSE;
1632 /* hook this overlap into the pending async operation list */
1633 ovp->next = NtCurrentTeb()->pending_list;
1634 ovp->prev = NULL;
1635 if(ovp->next)
1636 ovp->next->prev = ovp;
1637 NtCurrentTeb()->pending_list = ovp;
1639 SetLastError(ERROR_IO_PENDING);
1641 /* always fail on return, either ERROR_IO_PENDING or other error */
1642 return FALSE;
1645 /***********************************************************************
1646 * WriteFile (KERNEL32.@)
1648 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
1649 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
1651 int unix_handle, result;
1653 TRACE("%d %p %ld %p %p\n", hFile, buffer, bytesToWrite,
1654 bytesWritten, overlapped );
1656 if (bytesWritten) *bytesWritten = 0; /* Do this before anything else */
1657 if (!bytesToWrite) return TRUE;
1659 /* this will only have impact if the overlappd structure is specified */
1660 if ( overlapped )
1661 return WriteFileEx(hFile, buffer, bytesToWrite, overlapped, NULL);
1663 unix_handle = FILE_GetUnixHandle( hFile, GENERIC_WRITE );
1664 if (unix_handle == -1) return FALSE;
1666 /* synchronous file write */
1667 while ((result = write( unix_handle, buffer, bytesToWrite )) == -1)
1669 if ((errno == EAGAIN) || (errno == EINTR)) continue;
1670 if ((errno == EFAULT) && !IsBadReadPtr( buffer, bytesToWrite )) continue;
1671 if (errno == ENOSPC)
1672 SetLastError( ERROR_DISK_FULL );
1673 else
1674 FILE_SetDosError();
1675 break;
1677 close( unix_handle );
1678 if (result == -1) return FALSE;
1679 if (bytesWritten) *bytesWritten = result;
1680 return TRUE;
1684 /***********************************************************************
1685 * _hread (KERNEL.349)
1687 LONG WINAPI WIN16_hread( HFILE16 hFile, SEGPTR buffer, LONG count )
1689 LONG maxlen;
1691 TRACE("%d %08lx %ld\n",
1692 hFile, (DWORD)buffer, count );
1694 /* Some programs pass a count larger than the allocated buffer */
1695 maxlen = GetSelectorLimit16( SELECTOROF(buffer) ) - OFFSETOF(buffer) + 1;
1696 if (count > maxlen) count = maxlen;
1697 return _lread(DosFileHandleToWin32Handle(hFile), MapSL(buffer), count );
1701 /***********************************************************************
1702 * _lread (KERNEL.82)
1704 UINT16 WINAPI WIN16_lread( HFILE16 hFile, SEGPTR buffer, UINT16 count )
1706 return (UINT16)WIN16_hread( hFile, buffer, (LONG)count );
1710 /***********************************************************************
1711 * _lread (KERNEL32.@)
1713 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
1715 DWORD result;
1716 if (!ReadFile( handle, buffer, count, &result, NULL )) return -1;
1717 return result;
1721 /***********************************************************************
1722 * _lread16 (KERNEL.82)
1724 UINT16 WINAPI _lread16( HFILE16 hFile, LPVOID buffer, UINT16 count )
1726 return (UINT16)_lread(DosFileHandleToWin32Handle(hFile), buffer, (LONG)count );
1730 /***********************************************************************
1731 * _lcreat (KERNEL.83)
1733 HFILE16 WINAPI _lcreat16( LPCSTR path, INT16 attr )
1735 return Win32HandleToDosFileHandle( _lcreat( path, attr ) );
1739 /***********************************************************************
1740 * _lcreat (KERNEL32.@)
1742 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
1744 /* Mask off all flags not explicitly allowed by the doc */
1745 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
1746 TRACE("%s %02x\n", path, attr );
1747 return CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
1748 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1749 CREATE_ALWAYS, attr, 0 );
1753 /***********************************************************************
1754 * SetFilePointer (KERNEL32.@)
1756 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword,
1757 DWORD method )
1759 DWORD ret = 0xffffffff;
1761 TRACE("handle %d offset %ld high %ld origin %ld\n",
1762 hFile, distance, highword?*highword:0, method );
1764 SERVER_START_REQ( set_file_pointer )
1766 req->handle = hFile;
1767 req->low = distance;
1768 req->high = highword ? *highword : (distance >= 0) ? 0 : -1;
1769 /* FIXME: assumes 1:1 mapping between Windows and Unix seek constants */
1770 req->whence = method;
1771 SetLastError( 0 );
1772 if (!SERVER_CALL_ERR())
1774 ret = req->new_low;
1775 if (highword) *highword = req->new_high;
1778 SERVER_END_REQ;
1779 return ret;
1783 /***********************************************************************
1784 * _llseek (KERNEL.84)
1786 * FIXME:
1787 * Seeking before the start of the file should be allowed for _llseek16,
1788 * but cause subsequent I/O operations to fail (cf. interrupt list)
1791 LONG WINAPI _llseek16( HFILE16 hFile, LONG lOffset, INT16 nOrigin )
1793 return SetFilePointer( DosFileHandleToWin32Handle(hFile), lOffset, NULL, nOrigin );
1797 /***********************************************************************
1798 * _llseek (KERNEL32.@)
1800 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
1802 return SetFilePointer( hFile, lOffset, NULL, nOrigin );
1806 /***********************************************************************
1807 * _lopen (KERNEL.85)
1809 HFILE16 WINAPI _lopen16( LPCSTR path, INT16 mode )
1811 return Win32HandleToDosFileHandle( _lopen( path, mode ) );
1815 /***********************************************************************
1816 * _lopen (KERNEL32.@)
1818 HFILE WINAPI _lopen( LPCSTR path, INT mode )
1820 DWORD access, sharing;
1822 TRACE("('%s',%04x)\n", path, mode );
1823 FILE_ConvertOFMode( mode, &access, &sharing );
1824 return CreateFileA( path, access, sharing, NULL, OPEN_EXISTING, 0, 0 );
1828 /***********************************************************************
1829 * _lwrite (KERNEL.86)
1831 UINT16 WINAPI _lwrite16( HFILE16 hFile, LPCSTR buffer, UINT16 count )
1833 return (UINT16)_hwrite( DosFileHandleToWin32Handle(hFile), buffer, (LONG)count );
1836 /***********************************************************************
1837 * _lwrite (KERNEL32.@)
1839 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
1841 return (UINT)_hwrite( hFile, buffer, (LONG)count );
1845 /***********************************************************************
1846 * _hread16 (KERNEL.349)
1848 LONG WINAPI _hread16( HFILE16 hFile, LPVOID buffer, LONG count)
1850 return _lread( DosFileHandleToWin32Handle(hFile), buffer, count );
1854 /***********************************************************************
1855 * _hread (KERNEL32.@)
1857 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
1859 return _lread( hFile, buffer, count );
1863 /***********************************************************************
1864 * _hwrite (KERNEL.350)
1866 LONG WINAPI _hwrite16( HFILE16 hFile, LPCSTR buffer, LONG count )
1868 return _hwrite( DosFileHandleToWin32Handle(hFile), buffer, count );
1872 /***********************************************************************
1873 * _hwrite (KERNEL32.@)
1875 * experimentation yields that _lwrite:
1876 * o truncates the file at the current position with
1877 * a 0 len write
1878 * o returns 0 on a 0 length write
1879 * o works with console handles
1882 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
1884 DWORD result;
1886 TRACE("%d %p %ld\n", handle, buffer, count );
1888 if (!count)
1890 /* Expand or truncate at current position */
1891 if (!SetEndOfFile( handle )) return HFILE_ERROR;
1892 return 0;
1894 if (!WriteFile( handle, buffer, count, &result, NULL ))
1895 return HFILE_ERROR;
1896 return result;
1900 /***********************************************************************
1901 * SetHandleCount (KERNEL.199)
1903 UINT16 WINAPI SetHandleCount16( UINT16 count )
1905 return SetHandleCount( count );
1909 /*************************************************************************
1910 * SetHandleCount (KERNEL32.@)
1912 UINT WINAPI SetHandleCount( UINT count )
1914 return min( 256, count );
1918 /***********************************************************************
1919 * FlushFileBuffers (KERNEL32.@)
1921 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
1923 BOOL ret;
1924 SERVER_START_REQ( flush_file )
1926 req->handle = hFile;
1927 ret = !SERVER_CALL_ERR();
1929 SERVER_END_REQ;
1930 return ret;
1934 /**************************************************************************
1935 * SetEndOfFile (KERNEL32.@)
1937 BOOL WINAPI SetEndOfFile( HANDLE hFile )
1939 BOOL ret;
1940 SERVER_START_REQ( truncate_file )
1942 req->handle = hFile;
1943 ret = !SERVER_CALL_ERR();
1945 SERVER_END_REQ;
1946 return ret;
1950 /***********************************************************************
1951 * DeleteFile (KERNEL.146)
1953 BOOL16 WINAPI DeleteFile16( LPCSTR path )
1955 return DeleteFileA( path );
1959 /***********************************************************************
1960 * DeleteFileA (KERNEL32.@)
1962 BOOL WINAPI DeleteFileA( LPCSTR path )
1964 DOS_FULL_NAME full_name;
1966 if (!path)
1968 SetLastError(ERROR_INVALID_PARAMETER);
1969 return FALSE;
1971 TRACE("'%s'\n", path );
1973 if (!*path)
1975 ERR("Empty path passed\n");
1976 return FALSE;
1978 if (DOSFS_GetDevice( path ))
1980 WARN("cannot remove DOS device '%s'!\n", path);
1981 SetLastError( ERROR_FILE_NOT_FOUND );
1982 return FALSE;
1985 if (!DOSFS_GetFullName( path, TRUE, &full_name )) return FALSE;
1986 if (unlink( full_name.long_name ) == -1)
1988 FILE_SetDosError();
1989 return FALSE;
1991 return TRUE;
1995 /***********************************************************************
1996 * DeleteFileW (KERNEL32.@)
1998 BOOL WINAPI DeleteFileW( LPCWSTR path )
2000 LPSTR xpath = HEAP_strdupWtoA( GetProcessHeap(), 0, path );
2001 BOOL ret = DeleteFileA( xpath );
2002 HeapFree( GetProcessHeap(), 0, xpath );
2003 return ret;
2007 /***********************************************************************
2008 * GetFileType (KERNEL32.@)
2010 DWORD WINAPI GetFileType( HANDLE hFile )
2012 DWORD ret = FILE_TYPE_UNKNOWN;
2013 SERVER_START_REQ( get_file_info )
2015 req->handle = hFile;
2016 if (!SERVER_CALL_ERR()) ret = req->type;
2018 SERVER_END_REQ;
2019 return ret;
2023 /* check if a file name is for an executable file (.exe or .com) */
2024 inline static BOOL is_executable( const char *name )
2026 int len = strlen(name);
2028 if (len < 4) return FALSE;
2029 return (!strcasecmp( name + len - 4, ".exe" ) ||
2030 !strcasecmp( name + len - 4, ".com" ));
2034 /**************************************************************************
2035 * MoveFileExA (KERNEL32.@)
2037 BOOL WINAPI MoveFileExA( LPCSTR fn1, LPCSTR fn2, DWORD flag )
2039 DOS_FULL_NAME full_name1, full_name2;
2041 TRACE("(%s,%s,%04lx)\n", fn1, fn2, flag);
2043 if (!fn1) {
2044 SetLastError(ERROR_INVALID_PARAMETER);
2045 return FALSE;
2048 if (!DOSFS_GetFullName( fn1, TRUE, &full_name1 )) return FALSE;
2050 if (fn2) /* !fn2 means delete fn1 */
2052 if (DOSFS_GetFullName( fn2, TRUE, &full_name2 ))
2054 /* target exists, check if we may overwrite */
2055 if (!(flag & MOVEFILE_REPLACE_EXISTING))
2057 /* FIXME: Use right error code */
2058 SetLastError( ERROR_ACCESS_DENIED );
2059 return FALSE;
2062 else if (!DOSFS_GetFullName( fn2, FALSE, &full_name2 )) return FALSE;
2064 /* Source name and target path are valid */
2066 if (flag & MOVEFILE_DELAY_UNTIL_REBOOT)
2068 /* FIXME: (bon@elektron.ikp.physik.th-darmstadt.de 970706)
2069 Perhaps we should queue these command and execute it
2070 when exiting... What about using on_exit(2)
2072 FIXME("Please move existing file '%s' to file '%s' when Wine has finished\n",
2073 full_name1.long_name, full_name2.long_name);
2074 return TRUE;
2077 if (full_name1.drive != full_name2.drive)
2079 /* use copy, if allowed */
2080 if (!(flag & MOVEFILE_COPY_ALLOWED))
2082 /* FIXME: Use right error code */
2083 SetLastError( ERROR_FILE_EXISTS );
2084 return FALSE;
2086 return CopyFileA( fn1, fn2, !(flag & MOVEFILE_REPLACE_EXISTING) );
2088 if (rename( full_name1.long_name, full_name2.long_name ) == -1)
2090 FILE_SetDosError();
2091 return FALSE;
2093 if (is_executable( full_name1.long_name ) != is_executable( full_name2.long_name ))
2095 struct stat fstat;
2096 if (stat( full_name2.long_name, &fstat ) != -1)
2098 if (is_executable( full_name2.long_name ))
2099 /* set executable bit where read bit is set */
2100 fstat.st_mode |= (fstat.st_mode & 0444) >> 2;
2101 else
2102 fstat.st_mode &= ~0111;
2103 chmod( full_name2.long_name, fstat.st_mode );
2106 return TRUE;
2108 else /* fn2 == NULL means delete source */
2110 if (flag & MOVEFILE_DELAY_UNTIL_REBOOT)
2112 if (flag & MOVEFILE_COPY_ALLOWED) {
2113 WARN("Illegal flag\n");
2114 SetLastError( ERROR_GEN_FAILURE );
2115 return FALSE;
2117 /* FIXME: (bon@elektron.ikp.physik.th-darmstadt.de 970706)
2118 Perhaps we should queue these command and execute it
2119 when exiting... What about using on_exit(2)
2121 FIXME("Please delete file '%s' when Wine has finished\n",
2122 full_name1.long_name);
2123 return TRUE;
2126 if (unlink( full_name1.long_name ) == -1)
2128 FILE_SetDosError();
2129 return FALSE;
2131 return TRUE; /* successfully deleted */
2135 /**************************************************************************
2136 * MoveFileExW (KERNEL32.@)
2138 BOOL WINAPI MoveFileExW( LPCWSTR fn1, LPCWSTR fn2, DWORD flag )
2140 LPSTR afn1 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn1 );
2141 LPSTR afn2 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn2 );
2142 BOOL res = MoveFileExA( afn1, afn2, flag );
2143 HeapFree( GetProcessHeap(), 0, afn1 );
2144 HeapFree( GetProcessHeap(), 0, afn2 );
2145 return res;
2149 /**************************************************************************
2150 * MoveFileA (KERNEL32.@)
2152 * Move file or directory
2154 BOOL WINAPI MoveFileA( LPCSTR fn1, LPCSTR fn2 )
2156 DOS_FULL_NAME full_name1, full_name2;
2157 struct stat fstat;
2159 TRACE("(%s,%s)\n", fn1, fn2 );
2161 if (!DOSFS_GetFullName( fn1, TRUE, &full_name1 )) return FALSE;
2162 if (DOSFS_GetFullName( fn2, TRUE, &full_name2 )) {
2163 /* The new name must not already exist */
2164 SetLastError(ERROR_ALREADY_EXISTS);
2165 return FALSE;
2167 if (!DOSFS_GetFullName( fn2, FALSE, &full_name2 )) return FALSE;
2169 if (full_name1.drive == full_name2.drive) /* move */
2170 return MoveFileExA( fn1, fn2, MOVEFILE_COPY_ALLOWED );
2172 /* copy */
2173 if (stat( full_name1.long_name, &fstat ))
2175 WARN("Invalid source file %s\n",
2176 full_name1.long_name);
2177 FILE_SetDosError();
2178 return FALSE;
2180 if (S_ISDIR(fstat.st_mode)) {
2181 /* No Move for directories across file systems */
2182 /* FIXME: Use right error code */
2183 SetLastError( ERROR_GEN_FAILURE );
2184 return FALSE;
2186 return CopyFileA(fn1, fn2, TRUE); /*fail, if exist */
2190 /**************************************************************************
2191 * MoveFileW (KERNEL32.@)
2193 BOOL WINAPI MoveFileW( LPCWSTR fn1, LPCWSTR fn2 )
2195 LPSTR afn1 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn1 );
2196 LPSTR afn2 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn2 );
2197 BOOL res = MoveFileA( afn1, afn2 );
2198 HeapFree( GetProcessHeap(), 0, afn1 );
2199 HeapFree( GetProcessHeap(), 0, afn2 );
2200 return res;
2204 /**************************************************************************
2205 * CopyFileA (KERNEL32.@)
2207 BOOL WINAPI CopyFileA( LPCSTR source, LPCSTR dest, BOOL fail_if_exists )
2209 HFILE h1, h2;
2210 BY_HANDLE_FILE_INFORMATION info;
2211 UINT count;
2212 BOOL ret = FALSE;
2213 int mode;
2214 char buffer[2048];
2216 if ((h1 = _lopen( source, OF_READ )) == HFILE_ERROR) return FALSE;
2217 if (!GetFileInformationByHandle( h1, &info ))
2219 CloseHandle( h1 );
2220 return FALSE;
2222 mode = (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY) ? 0444 : 0666;
2223 if ((h2 = CreateFileA( dest, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
2224 fail_if_exists ? CREATE_NEW : CREATE_ALWAYS,
2225 info.dwFileAttributes, h1 )) == INVALID_HANDLE_VALUE)
2227 CloseHandle( h1 );
2228 return FALSE;
2230 while ((count = _lread( h1, buffer, sizeof(buffer) )) > 0)
2232 char *p = buffer;
2233 while (count > 0)
2235 INT res = _lwrite( h2, p, count );
2236 if (res <= 0) goto done;
2237 p += res;
2238 count -= res;
2241 ret = TRUE;
2242 done:
2243 CloseHandle( h1 );
2244 CloseHandle( h2 );
2245 return ret;
2249 /**************************************************************************
2250 * CopyFileW (KERNEL32.@)
2252 BOOL WINAPI CopyFileW( LPCWSTR source, LPCWSTR dest, BOOL fail_if_exists)
2254 LPSTR sourceA = HEAP_strdupWtoA( GetProcessHeap(), 0, source );
2255 LPSTR destA = HEAP_strdupWtoA( GetProcessHeap(), 0, dest );
2256 BOOL ret = CopyFileA( sourceA, destA, fail_if_exists );
2257 HeapFree( GetProcessHeap(), 0, sourceA );
2258 HeapFree( GetProcessHeap(), 0, destA );
2259 return ret;
2263 /**************************************************************************
2264 * CopyFileExA (KERNEL32.@)
2266 * This implementation ignores most of the extra parameters passed-in into
2267 * the "ex" version of the method and calls the CopyFile method.
2268 * It will have to be fixed eventually.
2270 BOOL WINAPI CopyFileExA(LPCSTR sourceFilename,
2271 LPCSTR destFilename,
2272 LPPROGRESS_ROUTINE progressRoutine,
2273 LPVOID appData,
2274 LPBOOL cancelFlagPointer,
2275 DWORD copyFlags)
2277 BOOL failIfExists = FALSE;
2280 * Interpret the only flag that CopyFile can interpret.
2282 if ( (copyFlags & COPY_FILE_FAIL_IF_EXISTS) != 0)
2284 failIfExists = TRUE;
2287 return CopyFileA(sourceFilename, destFilename, failIfExists);
2290 /**************************************************************************
2291 * CopyFileExW (KERNEL32.@)
2293 BOOL WINAPI CopyFileExW(LPCWSTR sourceFilename,
2294 LPCWSTR destFilename,
2295 LPPROGRESS_ROUTINE progressRoutine,
2296 LPVOID appData,
2297 LPBOOL cancelFlagPointer,
2298 DWORD copyFlags)
2300 LPSTR sourceA = HEAP_strdupWtoA( GetProcessHeap(), 0, sourceFilename );
2301 LPSTR destA = HEAP_strdupWtoA( GetProcessHeap(), 0, destFilename );
2303 BOOL ret = CopyFileExA(sourceA,
2304 destA,
2305 progressRoutine,
2306 appData,
2307 cancelFlagPointer,
2308 copyFlags);
2310 HeapFree( GetProcessHeap(), 0, sourceA );
2311 HeapFree( GetProcessHeap(), 0, destA );
2313 return ret;
2317 /***********************************************************************
2318 * SetFileTime (KERNEL32.@)
2320 BOOL WINAPI SetFileTime( HANDLE hFile,
2321 const FILETIME *lpCreationTime,
2322 const FILETIME *lpLastAccessTime,
2323 const FILETIME *lpLastWriteTime )
2325 BOOL ret;
2326 SERVER_START_REQ( set_file_time )
2328 req->handle = hFile;
2329 if (lpLastAccessTime)
2330 RtlTimeToSecondsSince1970( lpLastAccessTime, (DWORD *)&req->access_time );
2331 else
2332 req->access_time = 0; /* FIXME */
2333 if (lpLastWriteTime)
2334 RtlTimeToSecondsSince1970( lpLastWriteTime, (DWORD *)&req->write_time );
2335 else
2336 req->write_time = 0; /* FIXME */
2337 ret = !SERVER_CALL_ERR();
2339 SERVER_END_REQ;
2340 return ret;
2344 /**************************************************************************
2345 * LockFile (KERNEL32.@)
2347 BOOL WINAPI LockFile( HANDLE hFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh,
2348 DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh )
2350 BOOL ret;
2351 SERVER_START_REQ( lock_file )
2353 req->handle = hFile;
2354 req->offset_low = dwFileOffsetLow;
2355 req->offset_high = dwFileOffsetHigh;
2356 req->count_low = nNumberOfBytesToLockLow;
2357 req->count_high = nNumberOfBytesToLockHigh;
2358 ret = !SERVER_CALL_ERR();
2360 SERVER_END_REQ;
2361 return ret;
2364 /**************************************************************************
2365 * LockFileEx [KERNEL32.@]
2367 * Locks a byte range within an open file for shared or exclusive access.
2369 * RETURNS
2370 * success: TRUE
2371 * failure: FALSE
2373 * NOTES
2374 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
2376 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
2377 DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh,
2378 LPOVERLAPPED pOverlapped )
2380 FIXME("hFile=%d,flags=%ld,reserved=%ld,lowbytes=%ld,highbytes=%ld,overlapped=%p: stub.\n",
2381 hFile, flags, reserved, nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh,
2382 pOverlapped);
2383 if (reserved == 0)
2384 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2385 else
2387 ERR("reserved == %ld: Supposed to be 0??\n", reserved);
2388 SetLastError(ERROR_INVALID_PARAMETER);
2391 return FALSE;
2395 /**************************************************************************
2396 * UnlockFile (KERNEL32.@)
2398 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh,
2399 DWORD nNumberOfBytesToUnlockLow, DWORD nNumberOfBytesToUnlockHigh )
2401 BOOL ret;
2402 SERVER_START_REQ( unlock_file )
2404 req->handle = hFile;
2405 req->offset_low = dwFileOffsetLow;
2406 req->offset_high = dwFileOffsetHigh;
2407 req->count_low = nNumberOfBytesToUnlockLow;
2408 req->count_high = nNumberOfBytesToUnlockHigh;
2409 ret = !SERVER_CALL_ERR();
2411 SERVER_END_REQ;
2412 return ret;
2416 /**************************************************************************
2417 * UnlockFileEx (KERNEL32.@)
2419 BOOL WINAPI UnlockFileEx(
2420 HFILE hFile,
2421 DWORD dwReserved,
2422 DWORD nNumberOfBytesToUnlockLow,
2423 DWORD nNumberOfBytesToUnlockHigh,
2424 LPOVERLAPPED lpOverlapped
2427 FIXME("hFile=%d,reserved=%ld,lowbytes=%ld,highbytes=%ld,overlapped=%p: stub.\n",
2428 hFile, dwReserved, nNumberOfBytesToUnlockLow, nNumberOfBytesToUnlockHigh,
2429 lpOverlapped);
2430 if (dwReserved == 0)
2431 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2432 else
2434 ERR("reserved == %ld: Supposed to be 0??\n", dwReserved);
2435 SetLastError(ERROR_INVALID_PARAMETER);
2438 return FALSE;
2442 #if 0
2444 struct DOS_FILE_LOCK {
2445 struct DOS_FILE_LOCK * next;
2446 DWORD base;
2447 DWORD len;
2448 DWORD processId;
2449 FILE_OBJECT * dos_file;
2450 /* char * unix_name;*/
2453 typedef struct DOS_FILE_LOCK DOS_FILE_LOCK;
2455 static DOS_FILE_LOCK *locks = NULL;
2456 static void DOS_RemoveFileLocks(FILE_OBJECT *file);
2459 /* Locks need to be mirrored because unix file locking is based
2460 * on the pid. Inside of wine there can be multiple WINE processes
2461 * that share the same unix pid.
2462 * Read's and writes should check these locks also - not sure
2463 * how critical that is at this point (FIXME).
2466 static BOOL DOS_AddLock(FILE_OBJECT *file, struct flock *f)
2468 DOS_FILE_LOCK *curr;
2469 DWORD processId;
2471 processId = GetCurrentProcessId();
2473 /* check if lock overlaps a current lock for the same file */
2474 #if 0
2475 for (curr = locks; curr; curr = curr->next) {
2476 if (strcmp(curr->unix_name, file->unix_name) == 0) {
2477 if ((f->l_start == curr->base) && (f->l_len == curr->len))
2478 return TRUE;/* region is identic */
2479 if ((f->l_start < (curr->base + curr->len)) &&
2480 ((f->l_start + f->l_len) > curr->base)) {
2481 /* region overlaps */
2482 return FALSE;
2486 #endif
2488 curr = HeapAlloc( GetProcessHeap(), 0, sizeof(DOS_FILE_LOCK) );
2489 curr->processId = GetCurrentProcessId();
2490 curr->base = f->l_start;
2491 curr->len = f->l_len;
2492 /* curr->unix_name = HEAP_strdupA( GetProcessHeap(), 0, file->unix_name);*/
2493 curr->next = locks;
2494 curr->dos_file = file;
2495 locks = curr;
2496 return TRUE;
2499 static void DOS_RemoveFileLocks(FILE_OBJECT *file)
2501 DWORD processId;
2502 DOS_FILE_LOCK **curr;
2503 DOS_FILE_LOCK *rem;
2505 processId = GetCurrentProcessId();
2506 curr = &locks;
2507 while (*curr) {
2508 if ((*curr)->dos_file == file) {
2509 rem = *curr;
2510 *curr = (*curr)->next;
2511 /* HeapFree( GetProcessHeap(), 0, rem->unix_name );*/
2512 HeapFree( GetProcessHeap(), 0, rem );
2514 else
2515 curr = &(*curr)->next;
2519 static BOOL DOS_RemoveLock(FILE_OBJECT *file, struct flock *f)
2521 DWORD processId;
2522 DOS_FILE_LOCK **curr;
2523 DOS_FILE_LOCK *rem;
2525 processId = GetCurrentProcessId();
2526 for (curr = &locks; *curr; curr = &(*curr)->next) {
2527 if ((*curr)->processId == processId &&
2528 (*curr)->dos_file == file &&
2529 (*curr)->base == f->l_start &&
2530 (*curr)->len == f->l_len) {
2531 /* this is the same lock */
2532 rem = *curr;
2533 *curr = (*curr)->next;
2534 /* HeapFree( GetProcessHeap(), 0, rem->unix_name );*/
2535 HeapFree( GetProcessHeap(), 0, rem );
2536 return TRUE;
2539 /* no matching lock found */
2540 return FALSE;
2544 /**************************************************************************
2545 * LockFile (KERNEL32.@)
2547 BOOL WINAPI LockFile(
2548 HFILE hFile,DWORD dwFileOffsetLow,DWORD dwFileOffsetHigh,
2549 DWORD nNumberOfBytesToLockLow,DWORD nNumberOfBytesToLockHigh )
2551 struct flock f;
2552 FILE_OBJECT *file;
2554 TRACE("handle %d offsetlow=%ld offsethigh=%ld nbyteslow=%ld nbyteshigh=%ld\n",
2555 hFile, dwFileOffsetLow, dwFileOffsetHigh,
2556 nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh);
2558 if (dwFileOffsetHigh || nNumberOfBytesToLockHigh) {
2559 FIXME("Unimplemented bytes > 32bits\n");
2560 return FALSE;
2563 f.l_start = dwFileOffsetLow;
2564 f.l_len = nNumberOfBytesToLockLow;
2565 f.l_whence = SEEK_SET;
2566 f.l_pid = 0;
2567 f.l_type = F_WRLCK;
2569 if (!(file = FILE_GetFile(hFile,0,NULL))) return FALSE;
2571 /* shadow locks internally */
2572 if (!DOS_AddLock(file, &f)) {
2573 SetLastError( ERROR_LOCK_VIOLATION );
2574 return FALSE;
2577 /* FIXME: Unix locking commented out for now, doesn't work with Excel */
2578 #ifdef USE_UNIX_LOCKS
2579 if (fcntl(file->unix_handle, F_SETLK, &f) == -1) {
2580 if (errno == EACCES || errno == EAGAIN) {
2581 SetLastError( ERROR_LOCK_VIOLATION );
2583 else {
2584 FILE_SetDosError();
2586 /* remove our internal copy of the lock */
2587 DOS_RemoveLock(file, &f);
2588 return FALSE;
2590 #endif
2591 return TRUE;
2595 /**************************************************************************
2596 * UnlockFile (KERNEL32.@)
2598 BOOL WINAPI UnlockFile(
2599 HFILE hFile,DWORD dwFileOffsetLow,DWORD dwFileOffsetHigh,
2600 DWORD nNumberOfBytesToUnlockLow,DWORD nNumberOfBytesToUnlockHigh )
2602 FILE_OBJECT *file;
2603 struct flock f;
2605 TRACE("handle %d offsetlow=%ld offsethigh=%ld nbyteslow=%ld nbyteshigh=%ld\n",
2606 hFile, dwFileOffsetLow, dwFileOffsetHigh,
2607 nNumberOfBytesToUnlockLow, nNumberOfBytesToUnlockHigh);
2609 if (dwFileOffsetHigh || nNumberOfBytesToUnlockHigh) {
2610 WARN("Unimplemented bytes > 32bits\n");
2611 return FALSE;
2614 f.l_start = dwFileOffsetLow;
2615 f.l_len = nNumberOfBytesToUnlockLow;
2616 f.l_whence = SEEK_SET;
2617 f.l_pid = 0;
2618 f.l_type = F_UNLCK;
2620 if (!(file = FILE_GetFile(hFile,0,NULL))) return FALSE;
2622 DOS_RemoveLock(file, &f); /* ok if fails - may be another wine */
2624 /* FIXME: Unix locking commented out for now, doesn't work with Excel */
2625 #ifdef USE_UNIX_LOCKS
2626 if (fcntl(file->unix_handle, F_SETLK, &f) == -1) {
2627 FILE_SetDosError();
2628 return FALSE;
2630 #endif
2631 return TRUE;
2633 #endif
2635 /**************************************************************************
2636 * GetFileAttributesExA [KERNEL32.@]
2638 BOOL WINAPI GetFileAttributesExA(
2639 LPCSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId,
2640 LPVOID lpFileInformation)
2642 DOS_FULL_NAME full_name;
2643 BY_HANDLE_FILE_INFORMATION info;
2645 if (lpFileName == NULL) return FALSE;
2646 if (lpFileInformation == NULL) return FALSE;
2648 if (fInfoLevelId == GetFileExInfoStandard) {
2649 LPWIN32_FILE_ATTRIBUTE_DATA lpFad =
2650 (LPWIN32_FILE_ATTRIBUTE_DATA) lpFileInformation;
2651 if (!DOSFS_GetFullName( lpFileName, TRUE, &full_name )) return FALSE;
2652 if (!FILE_Stat( full_name.long_name, &info )) return FALSE;
2654 lpFad->dwFileAttributes = info.dwFileAttributes;
2655 lpFad->ftCreationTime = info.ftCreationTime;
2656 lpFad->ftLastAccessTime = info.ftLastAccessTime;
2657 lpFad->ftLastWriteTime = info.ftLastWriteTime;
2658 lpFad->nFileSizeHigh = info.nFileSizeHigh;
2659 lpFad->nFileSizeLow = info.nFileSizeLow;
2661 else {
2662 FIXME("invalid info level %d!\n", fInfoLevelId);
2663 return FALSE;
2666 return TRUE;
2670 /**************************************************************************
2671 * GetFileAttributesExW [KERNEL32.@]
2673 BOOL WINAPI GetFileAttributesExW(
2674 LPCWSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId,
2675 LPVOID lpFileInformation)
2677 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, lpFileName );
2678 BOOL res =
2679 GetFileAttributesExA( nameA, fInfoLevelId, lpFileInformation);
2680 HeapFree( GetProcessHeap(), 0, nameA );
2681 return res;