Save a disk file's drive type in the server object.
[wine/multimedia.git] / files / file.c
blobb9e3fb00d6d862067fa8eec48506ac949f0c6c63
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,
285 UINT drive_type )
287 DWORD err;
288 HANDLE ret;
289 size_t len = strlen(filename);
291 if (len > REQUEST_MAX_VAR_SIZE)
293 FIXME("filename '%s' too long\n", filename );
294 SetLastError( ERROR_INVALID_PARAMETER );
295 return 0;
298 restart:
299 SERVER_START_VAR_REQ( create_file, len )
301 req->access = access;
302 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
303 req->sharing = sharing;
304 req->create = creation;
305 req->attrs = attributes;
306 req->drive_type = drive_type;
307 memcpy( server_data_ptr(req), filename, len );
308 SetLastError(0);
309 err = SERVER_CALL();
310 ret = req->handle;
312 SERVER_END_VAR_REQ;
314 /* If write access failed, retry without GENERIC_WRITE */
316 if (!ret && !fail_read_only && (access & GENERIC_WRITE))
318 if ((err == STATUS_MEDIA_WRITE_PROTECTED) || (err == STATUS_ACCESS_DENIED))
320 TRACE("Write access failed for file '%s', trying without "
321 "write access\n", filename);
322 access &= ~GENERIC_WRITE;
323 goto restart;
327 if (err) SetLastError( RtlNtStatusToDosError(err) );
329 if (!ret)
330 WARN("Unable to create file '%s' (GLE %ld)\n", filename, GetLastError());
332 return ret;
336 /***********************************************************************
337 * FILE_CreateDevice
339 * Same as FILE_CreateFile but for a device
340 * Returns 0 on failure.
342 HANDLE FILE_CreateDevice( int client_id, DWORD access, LPSECURITY_ATTRIBUTES sa )
344 HANDLE ret;
345 SERVER_START_REQ( create_device )
347 req->access = access;
348 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
349 req->id = client_id;
350 SetLastError(0);
351 SERVER_CALL_ERR();
352 ret = req->handle;
354 SERVER_END_REQ;
355 return ret;
358 static HANDLE FILE_OpenPipe(LPCSTR name, DWORD access)
360 HANDLE ret;
361 DWORD len = name ? MultiByteToWideChar( CP_ACP, 0, name, strlen(name), NULL, 0 ) : 0;
363 TRACE("name %s access %lx\n",name,access);
365 if (len >= MAX_PATH)
367 SetLastError( ERROR_FILENAME_EXCED_RANGE );
368 return 0;
370 SERVER_START_VAR_REQ( open_named_pipe, len * sizeof(WCHAR) )
372 req->access = access;
374 if (len) MultiByteToWideChar( CP_ACP, 0, name, strlen(name), server_data_ptr(req), len );
375 SetLastError(0);
376 SERVER_CALL_ERR();
377 ret = req->handle;
379 SERVER_END_VAR_REQ;
380 TRACE("Returned %d\n",ret);
381 return ret;
384 /*************************************************************************
385 * CreateFileA [KERNEL32.@] Creates or opens a file or other object
387 * Creates or opens an object, and returns a handle that can be used to
388 * access that object.
390 * PARAMS
392 * filename [in] pointer to filename to be accessed
393 * access [in] access mode requested
394 * sharing [in] share mode
395 * sa [in] pointer to security attributes
396 * creation [in] how to create the file
397 * attributes [in] attributes for newly created file
398 * template [in] handle to file with extended attributes to copy
400 * RETURNS
401 * Success: Open handle to specified file
402 * Failure: INVALID_HANDLE_VALUE
404 * NOTES
405 * Should call SetLastError() on failure.
407 * BUGS
409 * Doesn't support character devices, template files, or a
410 * lot of the 'attributes' flags yet.
412 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
413 LPSECURITY_ATTRIBUTES sa, DWORD creation,
414 DWORD attributes, HANDLE template )
416 DOS_FULL_NAME full_name;
417 HANDLE ret;
419 if (!filename)
421 SetLastError( ERROR_INVALID_PARAMETER );
422 return INVALID_HANDLE_VALUE;
424 TRACE("%s %s%s%s%s%s%s%s\n",filename,
425 ((access & GENERIC_READ)==GENERIC_READ)?"GENERIC_READ ":"",
426 ((access & GENERIC_WRITE)==GENERIC_WRITE)?"GENERIC_WRITE ":"",
427 (!access)?"QUERY_ACCESS ":"",
428 ((sharing & FILE_SHARE_READ)==FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
429 ((sharing & FILE_SHARE_WRITE)==FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
430 ((sharing & FILE_SHARE_DELETE)==FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
431 (creation ==CREATE_NEW)?"CREATE_NEW":
432 (creation ==CREATE_ALWAYS)?"CREATE_ALWAYS ":
433 (creation ==OPEN_EXISTING)?"OPEN_EXISTING ":
434 (creation ==OPEN_ALWAYS)?"OPEN_ALWAYS ":
435 (creation ==TRUNCATE_EXISTING)?"TRUNCATE_EXISTING ":"");
437 /* If the name starts with '\\?\', ignore the first 4 chars. */
438 if (!strncmp(filename, "\\\\?\\", 4))
440 filename += 4;
441 if (!strncmp(filename, "UNC\\", 4))
443 FIXME("UNC name (%s) not supported.\n", filename );
444 SetLastError( ERROR_PATH_NOT_FOUND );
445 return INVALID_HANDLE_VALUE;
449 if (!strncmp(filename, "\\\\.\\", 4)) {
450 if(!strncasecmp(&filename[4],"pipe\\",5))
452 TRACE("Opening a pipe: %s\n",filename);
453 ret = FILE_OpenPipe(filename,access);
454 goto done;
456 else if (!DOSFS_GetDevice( filename ))
458 ret = DEVICE_Open( filename+4, access, sa );
459 goto done;
461 else
462 filename+=4; /* fall into DOSFS_Device case below */
465 /* If the name still starts with '\\', it's a UNC name. */
466 if (!strncmp(filename, "\\\\", 2))
468 FIXME("UNC name (%s) not supported.\n", filename );
469 SetLastError( ERROR_PATH_NOT_FOUND );
470 return INVALID_HANDLE_VALUE;
473 /* If the name contains a DOS wild card (* or ?), do no create a file */
474 if(strchr(filename,'*') || strchr(filename,'?'))
475 return INVALID_HANDLE_VALUE;
477 /* Open a console for CONIN$ or CONOUT$ */
478 if (!strcasecmp(filename, "CONIN$"))
480 ret = FILE_OpenConsole( FALSE, access, sa );
481 goto done;
483 if (!strcasecmp(filename, "CONOUT$"))
485 ret = FILE_OpenConsole( TRUE, access, sa );
486 goto done;
489 if (DOSFS_GetDevice( filename ))
491 TRACE("opening device '%s'\n", filename );
493 if (!(ret = DOSFS_OpenDevice( filename, access, attributes, sa )))
495 /* Do not silence this please. It is a critical error. -MM */
496 ERR("Couldn't open device '%s'!\n",filename);
497 SetLastError( ERROR_FILE_NOT_FOUND );
499 goto done;
502 /* check for filename, don't check for last entry if creating */
503 if (!DOSFS_GetFullName( filename,
504 (creation == OPEN_EXISTING) ||
505 (creation == TRUNCATE_EXISTING),
506 &full_name )) {
507 WARN("Unable to get full filename from '%s' (GLE %ld)\n",
508 filename, GetLastError());
509 return INVALID_HANDLE_VALUE;
512 ret = FILE_CreateFile( full_name.long_name, access, sharing,
513 sa, creation, attributes, template,
514 DRIVE_GetFlags(full_name.drive) & DRIVE_FAIL_READ_ONLY,
515 GetDriveTypeA( full_name.short_name ) );
516 done:
517 if (!ret) ret = INVALID_HANDLE_VALUE;
518 return ret;
523 /*************************************************************************
524 * CreateFileW (KERNEL32.@)
526 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
527 LPSECURITY_ATTRIBUTES sa, DWORD creation,
528 DWORD attributes, HANDLE template)
530 LPSTR afn = HEAP_strdupWtoA( GetProcessHeap(), 0, filename );
531 HANDLE res = CreateFileA( afn, access, sharing, sa, creation, attributes, template );
532 HeapFree( GetProcessHeap(), 0, afn );
533 return res;
537 /***********************************************************************
538 * FILE_FillInfo
540 * Fill a file information from a struct stat.
542 static void FILE_FillInfo( struct stat *st, BY_HANDLE_FILE_INFORMATION *info )
544 if (S_ISDIR(st->st_mode))
545 info->dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
546 else
547 info->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
548 if (!(st->st_mode & S_IWUSR))
549 info->dwFileAttributes |= FILE_ATTRIBUTE_READONLY;
551 RtlSecondsSince1970ToTime( st->st_mtime, &info->ftCreationTime );
552 RtlSecondsSince1970ToTime( st->st_mtime, &info->ftLastWriteTime );
553 RtlSecondsSince1970ToTime( st->st_atime, &info->ftLastAccessTime );
555 info->dwVolumeSerialNumber = 0; /* FIXME */
556 info->nFileSizeHigh = 0;
557 info->nFileSizeLow = 0;
558 if (!S_ISDIR(st->st_mode)) {
559 info->nFileSizeHigh = st->st_size >> 32;
560 info->nFileSizeLow = st->st_size & 0xffffffff;
562 info->nNumberOfLinks = st->st_nlink;
563 info->nFileIndexHigh = 0;
564 info->nFileIndexLow = st->st_ino;
568 /***********************************************************************
569 * FILE_Stat
571 * Stat a Unix path name. Return TRUE if OK.
573 BOOL FILE_Stat( LPCSTR unixName, BY_HANDLE_FILE_INFORMATION *info )
575 struct stat st;
577 if (lstat( unixName, &st ) == -1)
579 FILE_SetDosError();
580 return FALSE;
582 if (!S_ISLNK(st.st_mode)) FILE_FillInfo( &st, info );
583 else
585 /* do a "real" stat to find out
586 about the type of the symlink destination */
587 if (stat( unixName, &st ) == -1)
589 FILE_SetDosError();
590 return FALSE;
592 FILE_FillInfo( &st, info );
593 info->dwFileAttributes |= FILE_ATTRIBUTE_SYMLINK;
595 return TRUE;
599 /***********************************************************************
600 * GetFileInformationByHandle (KERNEL32.@)
602 DWORD WINAPI GetFileInformationByHandle( HANDLE hFile,
603 BY_HANDLE_FILE_INFORMATION *info )
605 DWORD ret;
606 if (!info) return 0;
608 SERVER_START_REQ( get_file_info )
610 req->handle = hFile;
611 if ((ret = !SERVER_CALL_ERR()))
613 /* FIXME: which file types are supported ?
614 * Serial ports (FILE_TYPE_CHAR) are not,
615 * and MSDN also says that pipes are not supported.
616 * FILE_TYPE_REMOTE seems to be supported according to
617 * MSDN q234741.txt */
618 if ((req->type == FILE_TYPE_DISK)
619 || (req->type == FILE_TYPE_REMOTE))
621 RtlSecondsSince1970ToTime( req->write_time, &info->ftCreationTime );
622 RtlSecondsSince1970ToTime( req->write_time, &info->ftLastWriteTime );
623 RtlSecondsSince1970ToTime( req->access_time, &info->ftLastAccessTime );
624 info->dwFileAttributes = req->attr;
625 info->dwVolumeSerialNumber = req->serial;
626 info->nFileSizeHigh = req->size_high;
627 info->nFileSizeLow = req->size_low;
628 info->nNumberOfLinks = req->links;
629 info->nFileIndexHigh = req->index_high;
630 info->nFileIndexLow = req->index_low;
632 else
634 SetLastError(ERROR_NOT_SUPPORTED);
635 ret = 0;
639 SERVER_END_REQ;
640 return ret;
644 /**************************************************************************
645 * GetFileAttributes (KERNEL.420)
647 DWORD WINAPI GetFileAttributes16( LPCSTR name )
649 return GetFileAttributesA( name );
653 /**************************************************************************
654 * GetFileAttributesA (KERNEL32.@)
656 DWORD WINAPI GetFileAttributesA( LPCSTR name )
658 DOS_FULL_NAME full_name;
659 BY_HANDLE_FILE_INFORMATION info;
661 if (name == NULL)
663 SetLastError( ERROR_INVALID_PARAMETER );
664 return -1;
666 if (!DOSFS_GetFullName( name, TRUE, &full_name) )
667 return -1;
668 if (!FILE_Stat( full_name.long_name, &info )) return -1;
669 return info.dwFileAttributes;
673 /**************************************************************************
674 * GetFileAttributesW (KERNEL32.@)
676 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
678 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
679 DWORD res = GetFileAttributesA( nameA );
680 HeapFree( GetProcessHeap(), 0, nameA );
681 return res;
685 /***********************************************************************
686 * GetFileSize (KERNEL32.@)
688 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
690 BY_HANDLE_FILE_INFORMATION info;
691 if (!GetFileInformationByHandle( hFile, &info )) return -1;
692 if (filesizehigh) *filesizehigh = info.nFileSizeHigh;
693 return info.nFileSizeLow;
697 /***********************************************************************
698 * GetFileTime (KERNEL32.@)
700 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
701 FILETIME *lpLastAccessTime,
702 FILETIME *lpLastWriteTime )
704 BY_HANDLE_FILE_INFORMATION info;
705 if (!GetFileInformationByHandle( hFile, &info )) return FALSE;
706 if (lpCreationTime) *lpCreationTime = info.ftCreationTime;
707 if (lpLastAccessTime) *lpLastAccessTime = info.ftLastAccessTime;
708 if (lpLastWriteTime) *lpLastWriteTime = info.ftLastWriteTime;
709 return TRUE;
712 /***********************************************************************
713 * CompareFileTime (KERNEL32.@)
715 INT WINAPI CompareFileTime( LPFILETIME x, LPFILETIME y )
717 if (!x || !y) return -1;
719 if (x->dwHighDateTime > y->dwHighDateTime)
720 return 1;
721 if (x->dwHighDateTime < y->dwHighDateTime)
722 return -1;
723 if (x->dwLowDateTime > y->dwLowDateTime)
724 return 1;
725 if (x->dwLowDateTime < y->dwLowDateTime)
726 return -1;
727 return 0;
730 /***********************************************************************
731 * FILE_GetTempFileName : utility for GetTempFileName
733 static UINT FILE_GetTempFileName( LPCSTR path, LPCSTR prefix, UINT unique,
734 LPSTR buffer, BOOL isWin16 )
736 static UINT unique_temp;
737 DOS_FULL_NAME full_name;
738 int i;
739 LPSTR p;
740 UINT num;
742 if ( !path || !prefix || !buffer ) return 0;
744 if (!unique_temp) unique_temp = time(NULL) & 0xffff;
745 num = unique ? (unique & 0xffff) : (unique_temp++ & 0xffff);
747 strcpy( buffer, path );
748 p = buffer + strlen(buffer);
750 /* add a \, if there isn't one and path is more than just the drive letter ... */
751 if ( !((strlen(buffer) == 2) && (buffer[1] == ':'))
752 && ((p == buffer) || (p[-1] != '\\'))) *p++ = '\\';
754 if (isWin16) *p++ = '~';
755 for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
756 sprintf( p, "%04x.tmp", num );
758 /* Now try to create it */
760 if (!unique)
764 HFILE handle = CreateFileA( buffer, GENERIC_WRITE, 0, NULL,
765 CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
766 if (handle != INVALID_HANDLE_VALUE)
767 { /* We created it */
768 TRACE("created %s\n",
769 buffer);
770 CloseHandle( handle );
771 break;
773 if (GetLastError() != ERROR_FILE_EXISTS)
774 break; /* No need to go on */
775 num++;
776 sprintf( p, "%04x.tmp", num );
777 } while (num != (unique & 0xffff));
780 /* Get the full path name */
782 if (DOSFS_GetFullName( buffer, FALSE, &full_name ))
784 /* Check if we have write access in the directory */
785 if ((p = strrchr( full_name.long_name, '/' ))) *p = '\0';
786 if (access( full_name.long_name, W_OK ) == -1)
787 WARN("returns '%s', which doesn't seem to be writeable.\n",
788 buffer);
790 TRACE("returning %s\n", buffer );
791 return unique ? unique : num;
795 /***********************************************************************
796 * GetTempFileNameA (KERNEL32.@)
798 UINT WINAPI GetTempFileNameA( LPCSTR path, LPCSTR prefix, UINT unique,
799 LPSTR buffer)
801 return FILE_GetTempFileName(path, prefix, unique, buffer, FALSE);
804 /***********************************************************************
805 * GetTempFileNameW (KERNEL32.@)
807 UINT WINAPI GetTempFileNameW( LPCWSTR path, LPCWSTR prefix, UINT unique,
808 LPWSTR buffer )
810 LPSTR patha,prefixa;
811 char buffera[144];
812 UINT ret;
814 if (!path) return 0;
815 patha = HEAP_strdupWtoA( GetProcessHeap(), 0, path );
816 prefixa = HEAP_strdupWtoA( GetProcessHeap(), 0, prefix );
817 ret = FILE_GetTempFileName( patha, prefixa, unique, buffera, FALSE );
818 MultiByteToWideChar( CP_ACP, 0, buffera, -1, buffer, MAX_PATH );
819 HeapFree( GetProcessHeap(), 0, patha );
820 HeapFree( GetProcessHeap(), 0, prefixa );
821 return ret;
825 /***********************************************************************
826 * GetTempFileName (KERNEL.97)
828 UINT16 WINAPI GetTempFileName16( BYTE drive, LPCSTR prefix, UINT16 unique,
829 LPSTR buffer )
831 char temppath[144];
833 if (!(drive & ~TF_FORCEDRIVE)) /* drive 0 means current default drive */
834 drive |= DRIVE_GetCurrentDrive() + 'A';
836 if ((drive & TF_FORCEDRIVE) &&
837 !DRIVE_IsValid( toupper(drive & ~TF_FORCEDRIVE) - 'A' ))
839 drive &= ~TF_FORCEDRIVE;
840 WARN("invalid drive %d specified\n", drive );
843 if (drive & TF_FORCEDRIVE)
844 sprintf(temppath,"%c:", drive & ~TF_FORCEDRIVE );
845 else
846 GetTempPathA( 132, temppath );
847 return (UINT16)FILE_GetTempFileName( temppath, prefix, unique, buffer, TRUE );
850 /***********************************************************************
851 * FILE_DoOpenFile
853 * Implementation of OpenFile16() and OpenFile32().
855 static HFILE FILE_DoOpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode,
856 BOOL win32 )
858 HFILE hFileRet;
859 FILETIME filetime;
860 WORD filedatetime[2];
861 DOS_FULL_NAME full_name;
862 DWORD access, sharing;
863 char *p;
865 if (!ofs) return HFILE_ERROR;
867 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
868 ((mode & 0x3 )==OF_READ)?"OF_READ":
869 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
870 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
871 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
872 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
873 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
874 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
875 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
876 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
877 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
878 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
879 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
880 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
881 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
882 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
883 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
884 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
888 ofs->cBytes = sizeof(OFSTRUCT);
889 ofs->nErrCode = 0;
890 if (mode & OF_REOPEN) name = ofs->szPathName;
892 if (!name) {
893 ERR("called with `name' set to NULL ! Please debug.\n");
894 return HFILE_ERROR;
897 TRACE("%s %04x\n", name, mode );
899 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
900 Are there any cases where getting the path here is wrong?
901 Uwe Bonnes 1997 Apr 2 */
902 if (!GetFullPathNameA( name, sizeof(ofs->szPathName),
903 ofs->szPathName, NULL )) goto error;
904 FILE_ConvertOFMode( mode, &access, &sharing );
906 /* OF_PARSE simply fills the structure */
908 if (mode & OF_PARSE)
910 ofs->fFixedDisk = (GetDriveType16( ofs->szPathName[0]-'A' )
911 != DRIVE_REMOVABLE);
912 TRACE("(%s): OF_PARSE, res = '%s'\n",
913 name, ofs->szPathName );
914 return 0;
917 /* OF_CREATE is completely different from all other options, so
918 handle it first */
920 if (mode & OF_CREATE)
922 if ((hFileRet = CreateFileA( name, GENERIC_READ | GENERIC_WRITE,
923 sharing, NULL, CREATE_ALWAYS,
924 FILE_ATTRIBUTE_NORMAL, 0 ))== INVALID_HANDLE_VALUE)
925 goto error;
926 goto success;
929 /* If OF_SEARCH is set, ignore the given path */
931 if ((mode & OF_SEARCH) && !(mode & OF_REOPEN))
933 /* First try the file name as is */
934 if (DOSFS_GetFullName( name, TRUE, &full_name )) goto found;
935 /* Now remove the path */
936 if (name[0] && (name[1] == ':')) name += 2;
937 if ((p = strrchr( name, '\\' ))) name = p + 1;
938 if ((p = strrchr( name, '/' ))) name = p + 1;
939 if (!name[0]) goto not_found;
942 /* Now look for the file */
944 if (!DIR_SearchPath( NULL, name, NULL, &full_name, win32 )) goto not_found;
946 found:
947 TRACE("found %s = %s\n",
948 full_name.long_name, full_name.short_name );
949 lstrcpynA( ofs->szPathName, full_name.short_name,
950 sizeof(ofs->szPathName) );
952 if (mode & OF_SHARE_EXCLUSIVE)
953 /* Some InstallShield version uses OF_SHARE_EXCLUSIVE
954 on the file <tempdir>/_ins0432._mp to determine how
955 far installation has proceeded.
956 _ins0432._mp is an executable and while running the
957 application expects the open with OF_SHARE_ to fail*/
958 /* Probable FIXME:
959 As our loader closes the files after loading the executable,
960 we can't find the running executable with FILE_InUse.
961 The loader should keep the file open, as Windows does that, too.
964 char *last = strrchr(full_name.long_name,'/');
965 if (!last)
966 last = full_name.long_name - 1;
967 if (GetModuleHandle16(last+1))
969 TRACE("Denying shared open for %s\n",full_name.long_name);
970 return HFILE_ERROR;
974 if (mode & OF_DELETE)
976 if (unlink( full_name.long_name ) == -1) goto not_found;
977 TRACE("(%s): OF_DELETE return = OK\n", name);
978 return 1;
981 hFileRet = FILE_CreateFile( full_name.long_name, access, sharing,
982 NULL, OPEN_EXISTING, 0, 0,
983 DRIVE_GetFlags(full_name.drive) & DRIVE_FAIL_READ_ONLY,
984 GetDriveTypeA( full_name.short_name ) );
985 if (!hFileRet) goto not_found;
987 GetFileTime( hFileRet, NULL, NULL, &filetime );
988 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
989 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
991 if (memcmp( ofs->reserved, filedatetime, sizeof(ofs->reserved) ))
993 CloseHandle( hFileRet );
994 WARN("(%s): OF_VERIFY failed\n", name );
995 /* FIXME: what error here? */
996 SetLastError( ERROR_FILE_NOT_FOUND );
997 goto error;
1000 memcpy( ofs->reserved, filedatetime, sizeof(ofs->reserved) );
1002 success: /* We get here if the open was successful */
1003 TRACE("(%s): OK, return = %d\n", name, hFileRet );
1004 if (win32)
1006 if (mode & OF_EXIST) /* Return the handle, but close it first */
1007 CloseHandle( hFileRet );
1009 else
1011 hFileRet = Win32HandleToDosFileHandle( hFileRet );
1012 if (hFileRet == HFILE_ERROR16) goto error;
1013 if (mode & OF_EXIST) /* Return the handle, but close it first */
1014 _lclose16( hFileRet );
1016 return hFileRet;
1018 not_found: /* We get here if the file does not exist */
1019 WARN("'%s' not found or sharing violation\n", name );
1020 SetLastError( ERROR_FILE_NOT_FOUND );
1021 /* fall through */
1023 error: /* We get here if there was an error opening the file */
1024 ofs->nErrCode = GetLastError();
1025 WARN("(%s): return = HFILE_ERROR error= %d\n",
1026 name,ofs->nErrCode );
1027 return HFILE_ERROR;
1031 /***********************************************************************
1032 * OpenFile (KERNEL.74)
1033 * OpenFileEx (KERNEL.360)
1035 HFILE16 WINAPI OpenFile16( LPCSTR name, OFSTRUCT *ofs, UINT16 mode )
1037 return FILE_DoOpenFile( name, ofs, mode, FALSE );
1041 /***********************************************************************
1042 * OpenFile (KERNEL32.@)
1044 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
1046 return FILE_DoOpenFile( name, ofs, mode, TRUE );
1050 /***********************************************************************
1051 * FILE_InitProcessDosHandles
1053 * Allocates the default DOS handles for a process. Called either by
1054 * Win32HandleToDosFileHandle below or by the DOSVM stuff.
1056 static void FILE_InitProcessDosHandles( void )
1058 dos_handles[0] = GetStdHandle(STD_INPUT_HANDLE);
1059 dos_handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
1060 dos_handles[2] = GetStdHandle(STD_ERROR_HANDLE);
1061 dos_handles[3] = GetStdHandle(STD_ERROR_HANDLE);
1062 dos_handles[4] = GetStdHandle(STD_ERROR_HANDLE);
1065 /***********************************************************************
1066 * Win32HandleToDosFileHandle (KERNEL32.21)
1068 * Allocate a DOS handle for a Win32 handle. The Win32 handle is no
1069 * longer valid after this function (even on failure).
1071 * Note: this is not exactly right, since on Win95 the Win32 handles
1072 * are on top of DOS handles and we do it the other way
1073 * around. Should be good enough though.
1075 HFILE WINAPI Win32HandleToDosFileHandle( HANDLE handle )
1077 int i;
1079 if (!handle || (handle == INVALID_HANDLE_VALUE))
1080 return HFILE_ERROR;
1082 for (i = 5; i < DOS_TABLE_SIZE; i++)
1083 if (!dos_handles[i])
1085 dos_handles[i] = handle;
1086 TRACE("Got %d for h32 %d\n", i, handle );
1087 return (HFILE)i;
1089 CloseHandle( handle );
1090 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1091 return HFILE_ERROR;
1095 /***********************************************************************
1096 * DosFileHandleToWin32Handle (KERNEL32.20)
1098 * Return the Win32 handle for a DOS handle.
1100 * Note: this is not exactly right, since on Win95 the Win32 handles
1101 * are on top of DOS handles and we do it the other way
1102 * around. Should be good enough though.
1104 HANDLE WINAPI DosFileHandleToWin32Handle( HFILE handle )
1106 HFILE16 hfile = (HFILE16)handle;
1107 if (hfile < 5 && !dos_handles[hfile]) FILE_InitProcessDosHandles();
1108 if ((hfile >= DOS_TABLE_SIZE) || !dos_handles[hfile])
1110 SetLastError( ERROR_INVALID_HANDLE );
1111 return INVALID_HANDLE_VALUE;
1113 return dos_handles[hfile];
1117 /***********************************************************************
1118 * DisposeLZ32Handle (KERNEL32.22)
1120 * Note: this is not entirely correct, we should only close the
1121 * 32-bit handle and not the 16-bit one, but we cannot do
1122 * this because of the way our DOS handles are implemented.
1123 * It shouldn't break anything though.
1125 void WINAPI DisposeLZ32Handle( HANDLE handle )
1127 int i;
1129 if (!handle || (handle == INVALID_HANDLE_VALUE)) return;
1131 for (i = 5; i < DOS_TABLE_SIZE; i++)
1132 if (dos_handles[i] == handle)
1134 dos_handles[i] = 0;
1135 CloseHandle( handle );
1136 break;
1141 /***********************************************************************
1142 * FILE_Dup2
1144 * dup2() function for DOS handles.
1146 HFILE16 FILE_Dup2( HFILE16 hFile1, HFILE16 hFile2 )
1148 HANDLE new_handle;
1150 if (hFile1 < 5 && !dos_handles[hFile1]) FILE_InitProcessDosHandles();
1152 if ((hFile1 >= DOS_TABLE_SIZE) || (hFile2 >= DOS_TABLE_SIZE) || !dos_handles[hFile1])
1154 SetLastError( ERROR_INVALID_HANDLE );
1155 return HFILE_ERROR16;
1157 if (hFile2 < 5)
1159 FIXME("stdio handle closed, need proper conversion\n" );
1160 SetLastError( ERROR_INVALID_HANDLE );
1161 return HFILE_ERROR16;
1163 if (!DuplicateHandle( GetCurrentProcess(), dos_handles[hFile1],
1164 GetCurrentProcess(), &new_handle,
1165 0, FALSE, DUPLICATE_SAME_ACCESS ))
1166 return HFILE_ERROR16;
1167 if (dos_handles[hFile2]) CloseHandle( dos_handles[hFile2] );
1168 dos_handles[hFile2] = new_handle;
1169 return hFile2;
1173 /***********************************************************************
1174 * _lclose (KERNEL.81)
1176 HFILE16 WINAPI _lclose16( HFILE16 hFile )
1178 if (hFile < 5)
1180 FIXME("stdio handle closed, need proper conversion\n" );
1181 SetLastError( ERROR_INVALID_HANDLE );
1182 return HFILE_ERROR16;
1184 if ((hFile >= DOS_TABLE_SIZE) || !dos_handles[hFile])
1186 SetLastError( ERROR_INVALID_HANDLE );
1187 return HFILE_ERROR16;
1189 TRACE("%d (handle32=%d)\n", hFile, dos_handles[hFile] );
1190 CloseHandle( dos_handles[hFile] );
1191 dos_handles[hFile] = 0;
1192 return 0;
1196 /***********************************************************************
1197 * _lclose (KERNEL32.@)
1199 HFILE WINAPI _lclose( HFILE hFile )
1201 TRACE("handle %d\n", hFile );
1202 return CloseHandle( hFile ) ? 0 : HFILE_ERROR;
1205 /***********************************************************************
1206 * GetOverlappedResult (KERNEL32.@)
1208 * Check the result of an Asynchronous data transfer from a file.
1210 * RETURNS
1211 * TRUE on success
1212 * FALSE on failure
1214 * If successful (and relevant) lpTransferred will hold the number of
1215 * bytes transferred during the async operation.
1217 * BUGS
1219 * Currently only works for WaitCommEvent, ReadFile, WriteFile
1220 * with communications ports.
1223 BOOL WINAPI GetOverlappedResult(
1224 HANDLE hFile, /* [in] handle of file to check on */
1225 LPOVERLAPPED lpOverlapped, /* [in/out] pointer to overlapped */
1226 LPDWORD lpTransferred, /* [in/out] number of bytes transferred */
1227 BOOL bWait /* [in] wait for the transfer to complete ? */
1229 DWORD r;
1231 TRACE("(%d %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait);
1233 if(lpOverlapped==NULL)
1235 ERR("lpOverlapped was null\n");
1236 return FALSE;
1238 if(!lpOverlapped->hEvent)
1240 ERR("lpOverlapped->hEvent was null\n");
1241 return FALSE;
1244 do {
1245 TRACE("waiting on %p\n",lpOverlapped);
1246 r = WaitForSingleObjectEx(lpOverlapped->hEvent, bWait?INFINITE:0, TRUE);
1247 TRACE("wait on %p returned %ld\n",lpOverlapped,r);
1248 } while (r==STATUS_USER_APC);
1250 if(lpTransferred)
1251 *lpTransferred = lpOverlapped->InternalHigh;
1253 SetLastError(lpOverlapped->Internal);
1255 return (r==WAIT_OBJECT_0);
1259 /***********************************************************************
1260 * CancelIo (KERNEL32.@)
1262 BOOL WINAPI CancelIo(HANDLE handle)
1264 FIXME("(%d) stub\n",handle);
1265 return FALSE;
1268 /***********************************************************************
1269 * FILE_AsyncReadService (INTERNAL)
1271 * This function is called while the client is waiting on the
1272 * server, so we can't make any server calls here.
1274 static void FILE_AsyncReadService(async_private *ovp, int events)
1276 LPOVERLAPPED lpOverlapped = ovp->lpOverlapped;
1277 int result, r;
1279 TRACE("%p %p %08x\n", lpOverlapped, ovp->buffer, events );
1281 /* if POLLNVAL, then our fd was closed or we have the wrong fd */
1282 if(events&POLLNVAL)
1284 ERR("fd %d invalid for %p\n",ovp->fd,ovp);
1285 r = STATUS_UNSUCCESSFUL;
1286 goto async_end;
1289 /* if there are no events, it must be a timeout */
1290 if(events==0)
1292 TRACE("read timed out\n");
1293 r = STATUS_TIMEOUT;
1294 goto async_end;
1297 /* check to see if the data is ready (non-blocking) */
1298 result = read(ovp->fd, &ovp->buffer[lpOverlapped->InternalHigh],
1299 ovp->count - lpOverlapped->InternalHigh);
1301 if ( (result<0) && ((errno == EAGAIN) || (errno == EINTR)))
1303 TRACE("Deferred read %d\n",errno);
1304 r = STATUS_PENDING;
1305 goto async_end;
1308 /* check to see if the transfer is complete */
1309 if(result<0)
1311 TRACE("read returned errno %d\n",errno);
1312 r = STATUS_UNSUCCESSFUL;
1313 goto async_end;
1316 lpOverlapped->InternalHigh += result;
1317 TRACE("read %d more bytes %ld/%d so far\n",result,lpOverlapped->InternalHigh,ovp->count);
1319 if(lpOverlapped->InternalHigh < ovp->count)
1320 r = STATUS_PENDING;
1321 else
1322 r = STATUS_SUCCESS;
1324 async_end:
1325 lpOverlapped->Internal = r;
1328 /* flogged from wineserver */
1329 /* add a timeout in milliseconds to an absolute time */
1330 static void add_timeout( struct timeval *when, int timeout )
1332 if (timeout)
1334 long sec = timeout / 1000;
1335 if ((when->tv_usec += (timeout - 1000*sec) * 1000) >= 1000000)
1337 when->tv_usec -= 1000000;
1338 when->tv_sec++;
1340 when->tv_sec += sec;
1344 /***********************************************************************
1345 * FILE_GetTimeout (INTERNAL)
1347 static BOOL FILE_GetTimeout(HANDLE hFile, DWORD txcount, DWORD type, int *timeout)
1349 BOOL ret;
1350 SERVER_START_REQ(create_async)
1352 req->count = txcount;
1353 req->type = type;
1354 req->file_handle = hFile;
1355 ret = SERVER_CALL();
1356 if(timeout)
1357 *timeout = req->timeout;
1359 SERVER_END_REQ;
1360 return !ret;
1363 /***********************************************************************
1364 * FILE_ReadFileEx (INTERNAL)
1366 static BOOL FILE_ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
1367 LPOVERLAPPED overlapped,
1368 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
1370 async_private *ovp;
1371 int fd, timeout=0;
1373 TRACE("file %d to buf %p num %ld %p func %p\n",
1374 hFile, buffer, bytesToRead, overlapped, lpCompletionRoutine);
1376 /* check that there is an overlapped struct with an event flag */
1377 if ( (overlapped==NULL) || NtResetEvent( overlapped->hEvent, NULL ) )
1379 TRACE("Overlapped not specified or invalid event flag\n");
1380 SetLastError(ERROR_INVALID_PARAMETER);
1381 return FALSE;
1384 if ( !FILE_GetTimeout(hFile, bytesToRead, ASYNC_TYPE_READ, &timeout ) )
1386 TRACE("FILE_GetTimeout failed\n");
1387 return FALSE;
1390 fd = FILE_GetUnixHandle( hFile, GENERIC_READ );
1391 if(fd<0)
1393 TRACE("Couldn't get FD\n");
1394 return FALSE;
1397 ovp = (async_private *) HeapAlloc(GetProcessHeap(), 0, sizeof (async_private));
1398 if(!ovp)
1400 TRACE("HeapAlloc Failed\n");
1401 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1402 close(fd);
1403 return FALSE;
1405 ovp->lpOverlapped = overlapped;
1406 ovp->count = bytesToRead;
1407 ovp->completion_func = lpCompletionRoutine;
1408 ovp->timeout = timeout;
1409 gettimeofday(&ovp->tv,NULL);
1410 add_timeout(&ovp->tv,timeout);
1411 ovp->event = POLLIN;
1412 ovp->func = FILE_AsyncReadService;
1413 ovp->buffer = buffer;
1414 ovp->fd = fd;
1416 /* hook this overlap into the pending async operation list */
1417 ovp->next = NtCurrentTeb()->pending_list;
1418 ovp->prev = NULL;
1419 if(ovp->next)
1420 ovp->next->prev = ovp;
1421 NtCurrentTeb()->pending_list = ovp;
1423 return TRUE;
1426 /***********************************************************************
1427 * ReadFileEx (KERNEL32.@)
1429 BOOL WINAPI ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
1430 LPOVERLAPPED overlapped,
1431 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
1433 /* FIXME: MS docs say we shouldn't set overlapped->hEvent */
1434 overlapped->Internal = STATUS_PENDING;
1435 overlapped->InternalHigh = 0;
1436 return FILE_ReadFileEx(hFile,buffer,bytesToRead,overlapped,lpCompletionRoutine);
1439 /***********************************************************************
1440 * ReadFile (KERNEL32.@)
1442 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
1443 LPDWORD bytesRead, LPOVERLAPPED overlapped )
1445 int unix_handle, result;
1446 DWORD type;
1448 TRACE("%d %p %ld %p %p\n", hFile, buffer, bytesToRead,
1449 bytesRead, overlapped );
1451 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
1452 if (!bytesToRead) return TRUE;
1454 unix_handle = FILE_GetUnixHandleType( hFile, GENERIC_READ, &type );
1455 if (unix_handle == -1)
1456 return FALSE;
1458 switch(type)
1460 case FD_TYPE_OVERLAPPED:
1461 if(!overlapped)
1463 close(unix_handle);
1464 SetLastError(ERROR_INVALID_PARAMETER);
1465 return FALSE;
1468 /* see if we can read some data already (this shouldn't block) */
1469 result = read( unix_handle, buffer, bytesToRead );
1470 close(unix_handle);
1472 if(result<0)
1474 FILE_SetDosError();
1475 return FALSE;
1478 /* if we read enough to keep the app happy, then return now */
1479 if(result>=bytesToRead)
1481 *bytesRead = result;
1482 return TRUE;
1485 /* at last resort, do an overlapped read */
1486 overlapped->Internal = STATUS_PENDING;
1487 overlapped->InternalHigh = result;
1489 if(!FILE_ReadFileEx(hFile, buffer, bytesToRead, overlapped, NULL))
1490 return FALSE;
1492 /* fail on return, with ERROR_IO_PENDING */
1493 SetLastError(ERROR_IO_PENDING);
1494 return FALSE;
1496 default:
1497 if(overlapped)
1499 close(unix_handle);
1500 SetLastError(ERROR_INVALID_PARAMETER);
1501 return FALSE;
1503 break;
1506 /* code for synchronous reads */
1507 while ((result = read( unix_handle, buffer, bytesToRead )) == -1)
1509 if ((errno == EAGAIN) || (errno == EINTR)) continue;
1510 if ((errno == EFAULT) && !IsBadWritePtr( buffer, bytesToRead )) continue;
1511 FILE_SetDosError();
1512 break;
1514 close( unix_handle );
1515 if (result == -1) return FALSE;
1516 if (bytesRead) *bytesRead = result;
1517 return TRUE;
1521 /***********************************************************************
1522 * FILE_AsyncWriteService (INTERNAL)
1524 * This function is called while the client is waiting on the
1525 * server, so we can't make any server calls here.
1527 static void FILE_AsyncWriteService(struct async_private *ovp, int events)
1529 LPOVERLAPPED lpOverlapped = ovp->lpOverlapped;
1530 int result, r;
1532 TRACE("(%p %p %08x)\n",lpOverlapped,ovp->buffer,events);
1534 /* if POLLNVAL, then our fd was closed or we have the wrong fd */
1535 if(events&POLLNVAL)
1537 ERR("fd %d invalid for %p\n",ovp->fd,ovp);
1538 r = STATUS_UNSUCCESSFUL;
1539 goto async_end;
1542 /* if there are no events, it must be a timeout */
1543 if(events==0)
1545 TRACE("write timed out\n");
1546 r = STATUS_TIMEOUT;
1547 goto async_end;
1550 /* write some data (non-blocking) */
1551 result = write(ovp->fd, &ovp->buffer[lpOverlapped->InternalHigh],
1552 ovp->count-lpOverlapped->InternalHigh);
1554 if ( (result<0) && ((errno == EAGAIN) || (errno == EINTR)))
1556 r = STATUS_PENDING;
1557 goto async_end;
1560 /* check to see if the transfer is complete */
1561 if(result<0)
1563 r = STATUS_UNSUCCESSFUL;
1564 goto async_end;
1567 lpOverlapped->InternalHigh += result;
1569 TRACE("wrote %d more bytes %ld/%d so far\n",result,lpOverlapped->InternalHigh,ovp->count);
1571 if(lpOverlapped->InternalHigh < ovp->count)
1572 r = STATUS_PENDING;
1573 else
1574 r = STATUS_SUCCESS;
1576 async_end:
1577 lpOverlapped->Internal = r;
1580 /***********************************************************************
1581 * WriteFileEx (KERNEL32.@)
1583 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
1584 LPOVERLAPPED overlapped,
1585 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
1587 async_private *ovp;
1588 int timeout=0;
1590 TRACE("file %d to buf %p num %ld %p func %p stub\n",
1591 hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
1593 if ( (overlapped == NULL) || NtResetEvent( overlapped->hEvent, NULL ) )
1595 SetLastError(ERROR_INVALID_PARAMETER);
1596 return FALSE;
1599 overlapped->Internal = STATUS_PENDING;
1600 overlapped->InternalHigh = 0;
1602 if (!FILE_GetTimeout(hFile, bytesToWrite, ASYNC_TYPE_WRITE, &timeout))
1604 TRACE("FILE_GetTimeout failed\n");
1605 return FALSE;
1608 ovp = (async_private*) HeapAlloc(GetProcessHeap(), 0, sizeof (async_private));
1609 if(!ovp)
1611 TRACE("HeapAlloc Failed\n");
1612 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1613 return FALSE;
1615 ovp->lpOverlapped = overlapped;
1616 ovp->timeout = timeout;
1617 gettimeofday(&ovp->tv,NULL);
1618 add_timeout(&ovp->tv,timeout);
1619 ovp->event = POLLOUT;
1620 ovp->func = FILE_AsyncWriteService;
1621 ovp->buffer = (LPVOID) buffer;
1622 ovp->count = bytesToWrite;
1623 ovp->completion_func = lpCompletionRoutine;
1624 ovp->fd = FILE_GetUnixHandle( hFile, GENERIC_WRITE );
1625 if(ovp->fd <0)
1627 HeapFree(GetProcessHeap(), 0, ovp);
1628 return FALSE;
1631 /* hook this overlap into the pending async operation list */
1632 ovp->next = NtCurrentTeb()->pending_list;
1633 ovp->prev = NULL;
1634 if(ovp->next)
1635 ovp->next->prev = ovp;
1636 NtCurrentTeb()->pending_list = ovp;
1638 SetLastError(ERROR_IO_PENDING);
1640 /* always fail on return, either ERROR_IO_PENDING or other error */
1641 return FALSE;
1644 /***********************************************************************
1645 * WriteFile (KERNEL32.@)
1647 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
1648 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
1650 int unix_handle, result;
1652 TRACE("%d %p %ld %p %p\n", hFile, buffer, bytesToWrite,
1653 bytesWritten, overlapped );
1655 if (bytesWritten) *bytesWritten = 0; /* Do this before anything else */
1656 if (!bytesToWrite) return TRUE;
1658 /* this will only have impact if the overlappd structure is specified */
1659 if ( overlapped )
1660 return WriteFileEx(hFile, buffer, bytesToWrite, overlapped, NULL);
1662 unix_handle = FILE_GetUnixHandle( hFile, GENERIC_WRITE );
1663 if (unix_handle == -1) return FALSE;
1665 /* synchronous file write */
1666 while ((result = write( unix_handle, buffer, bytesToWrite )) == -1)
1668 if ((errno == EAGAIN) || (errno == EINTR)) continue;
1669 if ((errno == EFAULT) && !IsBadReadPtr( buffer, bytesToWrite )) continue;
1670 if (errno == ENOSPC)
1671 SetLastError( ERROR_DISK_FULL );
1672 else
1673 FILE_SetDosError();
1674 break;
1676 close( unix_handle );
1677 if (result == -1) return FALSE;
1678 if (bytesWritten) *bytesWritten = result;
1679 return TRUE;
1683 /***********************************************************************
1684 * _hread (KERNEL.349)
1686 LONG WINAPI WIN16_hread( HFILE16 hFile, SEGPTR buffer, LONG count )
1688 LONG maxlen;
1690 TRACE("%d %08lx %ld\n",
1691 hFile, (DWORD)buffer, count );
1693 /* Some programs pass a count larger than the allocated buffer */
1694 maxlen = GetSelectorLimit16( SELECTOROF(buffer) ) - OFFSETOF(buffer) + 1;
1695 if (count > maxlen) count = maxlen;
1696 return _lread(DosFileHandleToWin32Handle(hFile), MapSL(buffer), count );
1700 /***********************************************************************
1701 * _lread (KERNEL.82)
1703 UINT16 WINAPI WIN16_lread( HFILE16 hFile, SEGPTR buffer, UINT16 count )
1705 return (UINT16)WIN16_hread( hFile, buffer, (LONG)count );
1709 /***********************************************************************
1710 * _lread (KERNEL32.@)
1712 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
1714 DWORD result;
1715 if (!ReadFile( handle, buffer, count, &result, NULL )) return -1;
1716 return result;
1720 /***********************************************************************
1721 * _lread16 (KERNEL.82)
1723 UINT16 WINAPI _lread16( HFILE16 hFile, LPVOID buffer, UINT16 count )
1725 return (UINT16)_lread(DosFileHandleToWin32Handle(hFile), buffer, (LONG)count );
1729 /***********************************************************************
1730 * _lcreat (KERNEL.83)
1732 HFILE16 WINAPI _lcreat16( LPCSTR path, INT16 attr )
1734 return Win32HandleToDosFileHandle( _lcreat( path, attr ) );
1738 /***********************************************************************
1739 * _lcreat (KERNEL32.@)
1741 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
1743 /* Mask off all flags not explicitly allowed by the doc */
1744 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
1745 TRACE("%s %02x\n", path, attr );
1746 return CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
1747 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1748 CREATE_ALWAYS, attr, 0 );
1752 /***********************************************************************
1753 * SetFilePointer (KERNEL32.@)
1755 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword,
1756 DWORD method )
1758 DWORD ret = 0xffffffff;
1760 TRACE("handle %d offset %ld high %ld origin %ld\n",
1761 hFile, distance, highword?*highword:0, method );
1763 SERVER_START_REQ( set_file_pointer )
1765 req->handle = hFile;
1766 req->low = distance;
1767 req->high = highword ? *highword : (distance >= 0) ? 0 : -1;
1768 /* FIXME: assumes 1:1 mapping between Windows and Unix seek constants */
1769 req->whence = method;
1770 SetLastError( 0 );
1771 if (!SERVER_CALL_ERR())
1773 ret = req->new_low;
1774 if (highword) *highword = req->new_high;
1777 SERVER_END_REQ;
1778 return ret;
1782 /***********************************************************************
1783 * _llseek (KERNEL.84)
1785 * FIXME:
1786 * Seeking before the start of the file should be allowed for _llseek16,
1787 * but cause subsequent I/O operations to fail (cf. interrupt list)
1790 LONG WINAPI _llseek16( HFILE16 hFile, LONG lOffset, INT16 nOrigin )
1792 return SetFilePointer( DosFileHandleToWin32Handle(hFile), lOffset, NULL, nOrigin );
1796 /***********************************************************************
1797 * _llseek (KERNEL32.@)
1799 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
1801 return SetFilePointer( hFile, lOffset, NULL, nOrigin );
1805 /***********************************************************************
1806 * _lopen (KERNEL.85)
1808 HFILE16 WINAPI _lopen16( LPCSTR path, INT16 mode )
1810 return Win32HandleToDosFileHandle( _lopen( path, mode ) );
1814 /***********************************************************************
1815 * _lopen (KERNEL32.@)
1817 HFILE WINAPI _lopen( LPCSTR path, INT mode )
1819 DWORD access, sharing;
1821 TRACE("('%s',%04x)\n", path, mode );
1822 FILE_ConvertOFMode( mode, &access, &sharing );
1823 return CreateFileA( path, access, sharing, NULL, OPEN_EXISTING, 0, 0 );
1827 /***********************************************************************
1828 * _lwrite (KERNEL.86)
1830 UINT16 WINAPI _lwrite16( HFILE16 hFile, LPCSTR buffer, UINT16 count )
1832 return (UINT16)_hwrite( DosFileHandleToWin32Handle(hFile), buffer, (LONG)count );
1835 /***********************************************************************
1836 * _lwrite (KERNEL32.@)
1838 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
1840 return (UINT)_hwrite( hFile, buffer, (LONG)count );
1844 /***********************************************************************
1845 * _hread16 (KERNEL.349)
1847 LONG WINAPI _hread16( HFILE16 hFile, LPVOID buffer, LONG count)
1849 return _lread( DosFileHandleToWin32Handle(hFile), buffer, count );
1853 /***********************************************************************
1854 * _hread (KERNEL32.@)
1856 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
1858 return _lread( hFile, buffer, count );
1862 /***********************************************************************
1863 * _hwrite (KERNEL.350)
1865 LONG WINAPI _hwrite16( HFILE16 hFile, LPCSTR buffer, LONG count )
1867 return _hwrite( DosFileHandleToWin32Handle(hFile), buffer, count );
1871 /***********************************************************************
1872 * _hwrite (KERNEL32.@)
1874 * experimentation yields that _lwrite:
1875 * o truncates the file at the current position with
1876 * a 0 len write
1877 * o returns 0 on a 0 length write
1878 * o works with console handles
1881 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
1883 DWORD result;
1885 TRACE("%d %p %ld\n", handle, buffer, count );
1887 if (!count)
1889 /* Expand or truncate at current position */
1890 if (!SetEndOfFile( handle )) return HFILE_ERROR;
1891 return 0;
1893 if (!WriteFile( handle, buffer, count, &result, NULL ))
1894 return HFILE_ERROR;
1895 return result;
1899 /***********************************************************************
1900 * SetHandleCount (KERNEL.199)
1902 UINT16 WINAPI SetHandleCount16( UINT16 count )
1904 return SetHandleCount( count );
1908 /*************************************************************************
1909 * SetHandleCount (KERNEL32.@)
1911 UINT WINAPI SetHandleCount( UINT count )
1913 return min( 256, count );
1917 /***********************************************************************
1918 * FlushFileBuffers (KERNEL32.@)
1920 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
1922 BOOL ret;
1923 SERVER_START_REQ( flush_file )
1925 req->handle = hFile;
1926 ret = !SERVER_CALL_ERR();
1928 SERVER_END_REQ;
1929 return ret;
1933 /**************************************************************************
1934 * SetEndOfFile (KERNEL32.@)
1936 BOOL WINAPI SetEndOfFile( HANDLE hFile )
1938 BOOL ret;
1939 SERVER_START_REQ( truncate_file )
1941 req->handle = hFile;
1942 ret = !SERVER_CALL_ERR();
1944 SERVER_END_REQ;
1945 return ret;
1949 /***********************************************************************
1950 * DeleteFile (KERNEL.146)
1952 BOOL16 WINAPI DeleteFile16( LPCSTR path )
1954 return DeleteFileA( path );
1958 /***********************************************************************
1959 * DeleteFileA (KERNEL32.@)
1961 BOOL WINAPI DeleteFileA( LPCSTR path )
1963 DOS_FULL_NAME full_name;
1965 if (!path)
1967 SetLastError(ERROR_INVALID_PARAMETER);
1968 return FALSE;
1970 TRACE("'%s'\n", path );
1972 if (!*path)
1974 ERR("Empty path passed\n");
1975 return FALSE;
1977 if (DOSFS_GetDevice( path ))
1979 WARN("cannot remove DOS device '%s'!\n", path);
1980 SetLastError( ERROR_FILE_NOT_FOUND );
1981 return FALSE;
1984 if (!DOSFS_GetFullName( path, TRUE, &full_name )) return FALSE;
1985 if (unlink( full_name.long_name ) == -1)
1987 FILE_SetDosError();
1988 return FALSE;
1990 return TRUE;
1994 /***********************************************************************
1995 * DeleteFileW (KERNEL32.@)
1997 BOOL WINAPI DeleteFileW( LPCWSTR path )
1999 LPSTR xpath = HEAP_strdupWtoA( GetProcessHeap(), 0, path );
2000 BOOL ret = DeleteFileA( xpath );
2001 HeapFree( GetProcessHeap(), 0, xpath );
2002 return ret;
2006 /***********************************************************************
2007 * GetFileType (KERNEL32.@)
2009 DWORD WINAPI GetFileType( HANDLE hFile )
2011 DWORD ret = FILE_TYPE_UNKNOWN;
2012 SERVER_START_REQ( get_file_info )
2014 req->handle = hFile;
2015 if (!SERVER_CALL_ERR()) ret = req->type;
2017 SERVER_END_REQ;
2018 return ret;
2022 /* check if a file name is for an executable file (.exe or .com) */
2023 inline static BOOL is_executable( const char *name )
2025 int len = strlen(name);
2027 if (len < 4) return FALSE;
2028 return (!strcasecmp( name + len - 4, ".exe" ) ||
2029 !strcasecmp( name + len - 4, ".com" ));
2033 /**************************************************************************
2034 * MoveFileExA (KERNEL32.@)
2036 BOOL WINAPI MoveFileExA( LPCSTR fn1, LPCSTR fn2, DWORD flag )
2038 DOS_FULL_NAME full_name1, full_name2;
2040 TRACE("(%s,%s,%04lx)\n", fn1, fn2, flag);
2042 if (!fn1) {
2043 SetLastError(ERROR_INVALID_PARAMETER);
2044 return FALSE;
2047 if (!DOSFS_GetFullName( fn1, TRUE, &full_name1 )) return FALSE;
2049 if (fn2) /* !fn2 means delete fn1 */
2051 if (DOSFS_GetFullName( fn2, TRUE, &full_name2 ))
2053 /* target exists, check if we may overwrite */
2054 if (!(flag & MOVEFILE_REPLACE_EXISTING))
2056 /* FIXME: Use right error code */
2057 SetLastError( ERROR_ACCESS_DENIED );
2058 return FALSE;
2061 else if (!DOSFS_GetFullName( fn2, FALSE, &full_name2 )) return FALSE;
2063 /* Source name and target path are valid */
2065 if (flag & MOVEFILE_DELAY_UNTIL_REBOOT)
2067 /* FIXME: (bon@elektron.ikp.physik.th-darmstadt.de 970706)
2068 Perhaps we should queue these command and execute it
2069 when exiting... What about using on_exit(2)
2071 FIXME("Please move existing file '%s' to file '%s' when Wine has finished\n",
2072 full_name1.long_name, full_name2.long_name);
2073 return TRUE;
2076 if (full_name1.drive != full_name2.drive)
2078 /* use copy, if allowed */
2079 if (!(flag & MOVEFILE_COPY_ALLOWED))
2081 /* FIXME: Use right error code */
2082 SetLastError( ERROR_FILE_EXISTS );
2083 return FALSE;
2085 return CopyFileA( fn1, fn2, !(flag & MOVEFILE_REPLACE_EXISTING) );
2087 if (rename( full_name1.long_name, full_name2.long_name ) == -1)
2089 FILE_SetDosError();
2090 return FALSE;
2092 if (is_executable( full_name1.long_name ) != is_executable( full_name2.long_name ))
2094 struct stat fstat;
2095 if (stat( full_name2.long_name, &fstat ) != -1)
2097 if (is_executable( full_name2.long_name ))
2098 /* set executable bit where read bit is set */
2099 fstat.st_mode |= (fstat.st_mode & 0444) >> 2;
2100 else
2101 fstat.st_mode &= ~0111;
2102 chmod( full_name2.long_name, fstat.st_mode );
2105 return TRUE;
2107 else /* fn2 == NULL means delete source */
2109 if (flag & MOVEFILE_DELAY_UNTIL_REBOOT)
2111 if (flag & MOVEFILE_COPY_ALLOWED) {
2112 WARN("Illegal flag\n");
2113 SetLastError( ERROR_GEN_FAILURE );
2114 return FALSE;
2116 /* FIXME: (bon@elektron.ikp.physik.th-darmstadt.de 970706)
2117 Perhaps we should queue these command and execute it
2118 when exiting... What about using on_exit(2)
2120 FIXME("Please delete file '%s' when Wine has finished\n",
2121 full_name1.long_name);
2122 return TRUE;
2125 if (unlink( full_name1.long_name ) == -1)
2127 FILE_SetDosError();
2128 return FALSE;
2130 return TRUE; /* successfully deleted */
2134 /**************************************************************************
2135 * MoveFileExW (KERNEL32.@)
2137 BOOL WINAPI MoveFileExW( LPCWSTR fn1, LPCWSTR fn2, DWORD flag )
2139 LPSTR afn1 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn1 );
2140 LPSTR afn2 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn2 );
2141 BOOL res = MoveFileExA( afn1, afn2, flag );
2142 HeapFree( GetProcessHeap(), 0, afn1 );
2143 HeapFree( GetProcessHeap(), 0, afn2 );
2144 return res;
2148 /**************************************************************************
2149 * MoveFileA (KERNEL32.@)
2151 * Move file or directory
2153 BOOL WINAPI MoveFileA( LPCSTR fn1, LPCSTR fn2 )
2155 DOS_FULL_NAME full_name1, full_name2;
2156 struct stat fstat;
2158 TRACE("(%s,%s)\n", fn1, fn2 );
2160 if (!DOSFS_GetFullName( fn1, TRUE, &full_name1 )) return FALSE;
2161 if (DOSFS_GetFullName( fn2, TRUE, &full_name2 )) {
2162 /* The new name must not already exist */
2163 SetLastError(ERROR_ALREADY_EXISTS);
2164 return FALSE;
2166 if (!DOSFS_GetFullName( fn2, FALSE, &full_name2 )) return FALSE;
2168 if (full_name1.drive == full_name2.drive) /* move */
2169 return MoveFileExA( fn1, fn2, MOVEFILE_COPY_ALLOWED );
2171 /* copy */
2172 if (stat( full_name1.long_name, &fstat ))
2174 WARN("Invalid source file %s\n",
2175 full_name1.long_name);
2176 FILE_SetDosError();
2177 return FALSE;
2179 if (S_ISDIR(fstat.st_mode)) {
2180 /* No Move for directories across file systems */
2181 /* FIXME: Use right error code */
2182 SetLastError( ERROR_GEN_FAILURE );
2183 return FALSE;
2185 return CopyFileA(fn1, fn2, TRUE); /*fail, if exist */
2189 /**************************************************************************
2190 * MoveFileW (KERNEL32.@)
2192 BOOL WINAPI MoveFileW( LPCWSTR fn1, LPCWSTR fn2 )
2194 LPSTR afn1 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn1 );
2195 LPSTR afn2 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn2 );
2196 BOOL res = MoveFileA( afn1, afn2 );
2197 HeapFree( GetProcessHeap(), 0, afn1 );
2198 HeapFree( GetProcessHeap(), 0, afn2 );
2199 return res;
2203 /**************************************************************************
2204 * CopyFileA (KERNEL32.@)
2206 BOOL WINAPI CopyFileA( LPCSTR source, LPCSTR dest, BOOL fail_if_exists )
2208 HFILE h1, h2;
2209 BY_HANDLE_FILE_INFORMATION info;
2210 UINT count;
2211 BOOL ret = FALSE;
2212 int mode;
2213 char buffer[2048];
2215 if ((h1 = _lopen( source, OF_READ )) == HFILE_ERROR) return FALSE;
2216 if (!GetFileInformationByHandle( h1, &info ))
2218 CloseHandle( h1 );
2219 return FALSE;
2221 mode = (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY) ? 0444 : 0666;
2222 if ((h2 = CreateFileA( dest, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
2223 fail_if_exists ? CREATE_NEW : CREATE_ALWAYS,
2224 info.dwFileAttributes, h1 )) == INVALID_HANDLE_VALUE)
2226 CloseHandle( h1 );
2227 return FALSE;
2229 while ((count = _lread( h1, buffer, sizeof(buffer) )) > 0)
2231 char *p = buffer;
2232 while (count > 0)
2234 INT res = _lwrite( h2, p, count );
2235 if (res <= 0) goto done;
2236 p += res;
2237 count -= res;
2240 ret = TRUE;
2241 done:
2242 CloseHandle( h1 );
2243 CloseHandle( h2 );
2244 return ret;
2248 /**************************************************************************
2249 * CopyFileW (KERNEL32.@)
2251 BOOL WINAPI CopyFileW( LPCWSTR source, LPCWSTR dest, BOOL fail_if_exists)
2253 LPSTR sourceA = HEAP_strdupWtoA( GetProcessHeap(), 0, source );
2254 LPSTR destA = HEAP_strdupWtoA( GetProcessHeap(), 0, dest );
2255 BOOL ret = CopyFileA( sourceA, destA, fail_if_exists );
2256 HeapFree( GetProcessHeap(), 0, sourceA );
2257 HeapFree( GetProcessHeap(), 0, destA );
2258 return ret;
2262 /**************************************************************************
2263 * CopyFileExA (KERNEL32.@)
2265 * This implementation ignores most of the extra parameters passed-in into
2266 * the "ex" version of the method and calls the CopyFile method.
2267 * It will have to be fixed eventually.
2269 BOOL WINAPI CopyFileExA(LPCSTR sourceFilename,
2270 LPCSTR destFilename,
2271 LPPROGRESS_ROUTINE progressRoutine,
2272 LPVOID appData,
2273 LPBOOL cancelFlagPointer,
2274 DWORD copyFlags)
2276 BOOL failIfExists = FALSE;
2279 * Interpret the only flag that CopyFile can interpret.
2281 if ( (copyFlags & COPY_FILE_FAIL_IF_EXISTS) != 0)
2283 failIfExists = TRUE;
2286 return CopyFileA(sourceFilename, destFilename, failIfExists);
2289 /**************************************************************************
2290 * CopyFileExW (KERNEL32.@)
2292 BOOL WINAPI CopyFileExW(LPCWSTR sourceFilename,
2293 LPCWSTR destFilename,
2294 LPPROGRESS_ROUTINE progressRoutine,
2295 LPVOID appData,
2296 LPBOOL cancelFlagPointer,
2297 DWORD copyFlags)
2299 LPSTR sourceA = HEAP_strdupWtoA( GetProcessHeap(), 0, sourceFilename );
2300 LPSTR destA = HEAP_strdupWtoA( GetProcessHeap(), 0, destFilename );
2302 BOOL ret = CopyFileExA(sourceA,
2303 destA,
2304 progressRoutine,
2305 appData,
2306 cancelFlagPointer,
2307 copyFlags);
2309 HeapFree( GetProcessHeap(), 0, sourceA );
2310 HeapFree( GetProcessHeap(), 0, destA );
2312 return ret;
2316 /***********************************************************************
2317 * SetFileTime (KERNEL32.@)
2319 BOOL WINAPI SetFileTime( HANDLE hFile,
2320 const FILETIME *lpCreationTime,
2321 const FILETIME *lpLastAccessTime,
2322 const FILETIME *lpLastWriteTime )
2324 BOOL ret;
2325 SERVER_START_REQ( set_file_time )
2327 req->handle = hFile;
2328 if (lpLastAccessTime)
2329 RtlTimeToSecondsSince1970( lpLastAccessTime, (DWORD *)&req->access_time );
2330 else
2331 req->access_time = 0; /* FIXME */
2332 if (lpLastWriteTime)
2333 RtlTimeToSecondsSince1970( lpLastWriteTime, (DWORD *)&req->write_time );
2334 else
2335 req->write_time = 0; /* FIXME */
2336 ret = !SERVER_CALL_ERR();
2338 SERVER_END_REQ;
2339 return ret;
2343 /**************************************************************************
2344 * LockFile (KERNEL32.@)
2346 BOOL WINAPI LockFile( HANDLE hFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh,
2347 DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh )
2349 BOOL ret;
2350 SERVER_START_REQ( lock_file )
2352 req->handle = hFile;
2353 req->offset_low = dwFileOffsetLow;
2354 req->offset_high = dwFileOffsetHigh;
2355 req->count_low = nNumberOfBytesToLockLow;
2356 req->count_high = nNumberOfBytesToLockHigh;
2357 ret = !SERVER_CALL_ERR();
2359 SERVER_END_REQ;
2360 return ret;
2363 /**************************************************************************
2364 * LockFileEx [KERNEL32.@]
2366 * Locks a byte range within an open file for shared or exclusive access.
2368 * RETURNS
2369 * success: TRUE
2370 * failure: FALSE
2372 * NOTES
2373 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
2375 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
2376 DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh,
2377 LPOVERLAPPED pOverlapped )
2379 FIXME("hFile=%d,flags=%ld,reserved=%ld,lowbytes=%ld,highbytes=%ld,overlapped=%p: stub.\n",
2380 hFile, flags, reserved, nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh,
2381 pOverlapped);
2382 if (reserved == 0)
2383 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2384 else
2386 ERR("reserved == %ld: Supposed to be 0??\n", reserved);
2387 SetLastError(ERROR_INVALID_PARAMETER);
2390 return FALSE;
2394 /**************************************************************************
2395 * UnlockFile (KERNEL32.@)
2397 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh,
2398 DWORD nNumberOfBytesToUnlockLow, DWORD nNumberOfBytesToUnlockHigh )
2400 BOOL ret;
2401 SERVER_START_REQ( unlock_file )
2403 req->handle = hFile;
2404 req->offset_low = dwFileOffsetLow;
2405 req->offset_high = dwFileOffsetHigh;
2406 req->count_low = nNumberOfBytesToUnlockLow;
2407 req->count_high = nNumberOfBytesToUnlockHigh;
2408 ret = !SERVER_CALL_ERR();
2410 SERVER_END_REQ;
2411 return ret;
2415 /**************************************************************************
2416 * UnlockFileEx (KERNEL32.@)
2418 BOOL WINAPI UnlockFileEx(
2419 HFILE hFile,
2420 DWORD dwReserved,
2421 DWORD nNumberOfBytesToUnlockLow,
2422 DWORD nNumberOfBytesToUnlockHigh,
2423 LPOVERLAPPED lpOverlapped
2426 FIXME("hFile=%d,reserved=%ld,lowbytes=%ld,highbytes=%ld,overlapped=%p: stub.\n",
2427 hFile, dwReserved, nNumberOfBytesToUnlockLow, nNumberOfBytesToUnlockHigh,
2428 lpOverlapped);
2429 if (dwReserved == 0)
2430 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2431 else
2433 ERR("reserved == %ld: Supposed to be 0??\n", dwReserved);
2434 SetLastError(ERROR_INVALID_PARAMETER);
2437 return FALSE;
2441 #if 0
2443 struct DOS_FILE_LOCK {
2444 struct DOS_FILE_LOCK * next;
2445 DWORD base;
2446 DWORD len;
2447 DWORD processId;
2448 FILE_OBJECT * dos_file;
2449 /* char * unix_name;*/
2452 typedef struct DOS_FILE_LOCK DOS_FILE_LOCK;
2454 static DOS_FILE_LOCK *locks = NULL;
2455 static void DOS_RemoveFileLocks(FILE_OBJECT *file);
2458 /* Locks need to be mirrored because unix file locking is based
2459 * on the pid. Inside of wine there can be multiple WINE processes
2460 * that share the same unix pid.
2461 * Read's and writes should check these locks also - not sure
2462 * how critical that is at this point (FIXME).
2465 static BOOL DOS_AddLock(FILE_OBJECT *file, struct flock *f)
2467 DOS_FILE_LOCK *curr;
2468 DWORD processId;
2470 processId = GetCurrentProcessId();
2472 /* check if lock overlaps a current lock for the same file */
2473 #if 0
2474 for (curr = locks; curr; curr = curr->next) {
2475 if (strcmp(curr->unix_name, file->unix_name) == 0) {
2476 if ((f->l_start == curr->base) && (f->l_len == curr->len))
2477 return TRUE;/* region is identic */
2478 if ((f->l_start < (curr->base + curr->len)) &&
2479 ((f->l_start + f->l_len) > curr->base)) {
2480 /* region overlaps */
2481 return FALSE;
2485 #endif
2487 curr = HeapAlloc( GetProcessHeap(), 0, sizeof(DOS_FILE_LOCK) );
2488 curr->processId = GetCurrentProcessId();
2489 curr->base = f->l_start;
2490 curr->len = f->l_len;
2491 /* curr->unix_name = HEAP_strdupA( GetProcessHeap(), 0, file->unix_name);*/
2492 curr->next = locks;
2493 curr->dos_file = file;
2494 locks = curr;
2495 return TRUE;
2498 static void DOS_RemoveFileLocks(FILE_OBJECT *file)
2500 DWORD processId;
2501 DOS_FILE_LOCK **curr;
2502 DOS_FILE_LOCK *rem;
2504 processId = GetCurrentProcessId();
2505 curr = &locks;
2506 while (*curr) {
2507 if ((*curr)->dos_file == file) {
2508 rem = *curr;
2509 *curr = (*curr)->next;
2510 /* HeapFree( GetProcessHeap(), 0, rem->unix_name );*/
2511 HeapFree( GetProcessHeap(), 0, rem );
2513 else
2514 curr = &(*curr)->next;
2518 static BOOL DOS_RemoveLock(FILE_OBJECT *file, struct flock *f)
2520 DWORD processId;
2521 DOS_FILE_LOCK **curr;
2522 DOS_FILE_LOCK *rem;
2524 processId = GetCurrentProcessId();
2525 for (curr = &locks; *curr; curr = &(*curr)->next) {
2526 if ((*curr)->processId == processId &&
2527 (*curr)->dos_file == file &&
2528 (*curr)->base == f->l_start &&
2529 (*curr)->len == f->l_len) {
2530 /* this is the same lock */
2531 rem = *curr;
2532 *curr = (*curr)->next;
2533 /* HeapFree( GetProcessHeap(), 0, rem->unix_name );*/
2534 HeapFree( GetProcessHeap(), 0, rem );
2535 return TRUE;
2538 /* no matching lock found */
2539 return FALSE;
2543 /**************************************************************************
2544 * LockFile (KERNEL32.@)
2546 BOOL WINAPI LockFile(
2547 HFILE hFile,DWORD dwFileOffsetLow,DWORD dwFileOffsetHigh,
2548 DWORD nNumberOfBytesToLockLow,DWORD nNumberOfBytesToLockHigh )
2550 struct flock f;
2551 FILE_OBJECT *file;
2553 TRACE("handle %d offsetlow=%ld offsethigh=%ld nbyteslow=%ld nbyteshigh=%ld\n",
2554 hFile, dwFileOffsetLow, dwFileOffsetHigh,
2555 nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh);
2557 if (dwFileOffsetHigh || nNumberOfBytesToLockHigh) {
2558 FIXME("Unimplemented bytes > 32bits\n");
2559 return FALSE;
2562 f.l_start = dwFileOffsetLow;
2563 f.l_len = nNumberOfBytesToLockLow;
2564 f.l_whence = SEEK_SET;
2565 f.l_pid = 0;
2566 f.l_type = F_WRLCK;
2568 if (!(file = FILE_GetFile(hFile,0,NULL))) return FALSE;
2570 /* shadow locks internally */
2571 if (!DOS_AddLock(file, &f)) {
2572 SetLastError( ERROR_LOCK_VIOLATION );
2573 return FALSE;
2576 /* FIXME: Unix locking commented out for now, doesn't work with Excel */
2577 #ifdef USE_UNIX_LOCKS
2578 if (fcntl(file->unix_handle, F_SETLK, &f) == -1) {
2579 if (errno == EACCES || errno == EAGAIN) {
2580 SetLastError( ERROR_LOCK_VIOLATION );
2582 else {
2583 FILE_SetDosError();
2585 /* remove our internal copy of the lock */
2586 DOS_RemoveLock(file, &f);
2587 return FALSE;
2589 #endif
2590 return TRUE;
2594 /**************************************************************************
2595 * UnlockFile (KERNEL32.@)
2597 BOOL WINAPI UnlockFile(
2598 HFILE hFile,DWORD dwFileOffsetLow,DWORD dwFileOffsetHigh,
2599 DWORD nNumberOfBytesToUnlockLow,DWORD nNumberOfBytesToUnlockHigh )
2601 FILE_OBJECT *file;
2602 struct flock f;
2604 TRACE("handle %d offsetlow=%ld offsethigh=%ld nbyteslow=%ld nbyteshigh=%ld\n",
2605 hFile, dwFileOffsetLow, dwFileOffsetHigh,
2606 nNumberOfBytesToUnlockLow, nNumberOfBytesToUnlockHigh);
2608 if (dwFileOffsetHigh || nNumberOfBytesToUnlockHigh) {
2609 WARN("Unimplemented bytes > 32bits\n");
2610 return FALSE;
2613 f.l_start = dwFileOffsetLow;
2614 f.l_len = nNumberOfBytesToUnlockLow;
2615 f.l_whence = SEEK_SET;
2616 f.l_pid = 0;
2617 f.l_type = F_UNLCK;
2619 if (!(file = FILE_GetFile(hFile,0,NULL))) return FALSE;
2621 DOS_RemoveLock(file, &f); /* ok if fails - may be another wine */
2623 /* FIXME: Unix locking commented out for now, doesn't work with Excel */
2624 #ifdef USE_UNIX_LOCKS
2625 if (fcntl(file->unix_handle, F_SETLK, &f) == -1) {
2626 FILE_SetDosError();
2627 return FALSE;
2629 #endif
2630 return TRUE;
2632 #endif
2634 /**************************************************************************
2635 * GetFileAttributesExA [KERNEL32.@]
2637 BOOL WINAPI GetFileAttributesExA(
2638 LPCSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId,
2639 LPVOID lpFileInformation)
2641 DOS_FULL_NAME full_name;
2642 BY_HANDLE_FILE_INFORMATION info;
2644 if (lpFileName == NULL) return FALSE;
2645 if (lpFileInformation == NULL) return FALSE;
2647 if (fInfoLevelId == GetFileExInfoStandard) {
2648 LPWIN32_FILE_ATTRIBUTE_DATA lpFad =
2649 (LPWIN32_FILE_ATTRIBUTE_DATA) lpFileInformation;
2650 if (!DOSFS_GetFullName( lpFileName, TRUE, &full_name )) return FALSE;
2651 if (!FILE_Stat( full_name.long_name, &info )) return FALSE;
2653 lpFad->dwFileAttributes = info.dwFileAttributes;
2654 lpFad->ftCreationTime = info.ftCreationTime;
2655 lpFad->ftLastAccessTime = info.ftLastAccessTime;
2656 lpFad->ftLastWriteTime = info.ftLastWriteTime;
2657 lpFad->nFileSizeHigh = info.nFileSizeHigh;
2658 lpFad->nFileSizeLow = info.nFileSizeLow;
2660 else {
2661 FIXME("invalid info level %d!\n", fInfoLevelId);
2662 return FALSE;
2665 return TRUE;
2669 /**************************************************************************
2670 * GetFileAttributesExW [KERNEL32.@]
2672 BOOL WINAPI GetFileAttributesExW(
2673 LPCWSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId,
2674 LPVOID lpFileInformation)
2676 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, lpFileName );
2677 BOOL res =
2678 GetFileAttributesExA( nameA, fInfoLevelId, lpFileInformation);
2679 HeapFree( GetProcessHeap(), 0, nameA );
2680 return res;