Fixed some places where whitespace was not handled correctly.
[wine/wine-kai.git] / files / file.c
blob3ceb98e2f3d91117ca78fd31ec215da0404cf3ba
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, BOOL inherit )
187 HANDLE ret;
189 wine_server_send_fd( fd );
191 SERVER_START_REQ( alloc_file_handle )
193 req->access = access;
194 req->inherit = inherit;
195 req->fd = fd;
196 wine_server_call( req );
197 ret = reply->handle;
199 SERVER_END_REQ;
200 return ret;
204 /***********************************************************************
205 * FILE_GetUnixHandleType
207 * Retrieve the Unix handle corresponding to a file handle.
208 * Returns -1 on failure.
210 int FILE_GetUnixHandleType( HANDLE handle, DWORD access, DWORD *type )
212 int ret, fd = -1;
216 SERVER_START_REQ( get_handle_fd )
218 req->handle = handle;
219 req->access = access;
220 if (!(ret = wine_server_call_err( req )))
222 fd = reply->fd;
224 if (type) *type = reply->type;
226 SERVER_END_REQ;
227 if (ret) return -1;
229 if (fd == -1) /* it wasn't in the cache, get it from the server */
230 fd = wine_server_recv_fd( handle );
232 } while (fd == -2); /* -2 means race condition, so restart from scratch */
234 if (fd != -1)
236 if ((fd = dup(fd)) == -1)
237 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
239 return fd;
242 /***********************************************************************
243 * FILE_GetUnixHandle
245 * Retrieve the Unix handle corresponding to a file handle.
246 * Returns -1 on failure.
248 int FILE_GetUnixHandle( HANDLE handle, DWORD access )
250 return FILE_GetUnixHandleType(handle, access, NULL);
253 /*************************************************************************
254 * FILE_OpenConsole
256 * Open a handle to the current process console.
257 * Returns 0 on failure.
259 static HANDLE FILE_OpenConsole( BOOL output, DWORD access, DWORD sharing, LPSECURITY_ATTRIBUTES sa )
261 HANDLE ret;
263 SERVER_START_REQ( open_console )
265 req->from = output;
266 req->access = access;
267 req->share = sharing;
268 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
269 SetLastError(0);
270 wine_server_call_err( req );
271 ret = reply->handle;
273 SERVER_END_REQ;
274 return ret;
278 /***********************************************************************
279 * FILE_CreateFile
281 * Implementation of CreateFile. Takes a Unix path name.
282 * Returns 0 on failure.
284 HANDLE FILE_CreateFile( LPCSTR filename, DWORD access, DWORD sharing,
285 LPSECURITY_ATTRIBUTES sa, DWORD creation,
286 DWORD attributes, HANDLE template, BOOL fail_read_only,
287 UINT drive_type )
289 unsigned int err;
290 HANDLE ret;
292 for (;;)
294 SERVER_START_REQ( create_file )
296 req->access = access;
297 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
298 req->sharing = sharing;
299 req->create = creation;
300 req->attrs = attributes;
301 req->drive_type = drive_type;
302 wine_server_add_data( req, filename, strlen(filename) );
303 SetLastError(0);
304 err = wine_server_call( req );
305 ret = reply->handle;
307 SERVER_END_REQ;
309 /* If write access failed, retry without GENERIC_WRITE */
311 if (!ret && !fail_read_only && (access & GENERIC_WRITE))
313 if ((err == STATUS_MEDIA_WRITE_PROTECTED) || (err == STATUS_ACCESS_DENIED))
315 TRACE("Write access failed for file '%s', trying without "
316 "write access\n", filename);
317 access &= ~GENERIC_WRITE;
318 continue;
322 if (err) SetLastError( RtlNtStatusToDosError(err) );
324 if (!ret) WARN("Unable to create file '%s' (GLE %ld)\n", filename, GetLastError());
325 return ret;
330 /***********************************************************************
331 * FILE_CreateDevice
333 * Same as FILE_CreateFile but for a device
334 * Returns 0 on failure.
336 HANDLE FILE_CreateDevice( int client_id, DWORD access, LPSECURITY_ATTRIBUTES sa )
338 HANDLE ret;
339 SERVER_START_REQ( create_device )
341 req->access = access;
342 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
343 req->id = client_id;
344 SetLastError(0);
345 wine_server_call_err( req );
346 ret = reply->handle;
348 SERVER_END_REQ;
349 return ret;
352 static HANDLE FILE_OpenPipe(LPCSTR name, DWORD access)
354 WCHAR buffer[MAX_PATH];
355 HANDLE ret;
356 DWORD len = 0;
358 if (name && !(len = MultiByteToWideChar( CP_ACP, 0, name, strlen(name), buffer, MAX_PATH )))
360 SetLastError( ERROR_FILENAME_EXCED_RANGE );
361 return 0;
363 SERVER_START_REQ( open_named_pipe )
365 req->access = access;
366 SetLastError(0);
367 wine_server_add_data( req, buffer, len * sizeof(WCHAR) );
368 wine_server_call_err( req );
369 ret = reply->handle;
371 SERVER_END_REQ;
372 TRACE("Returned %d\n",ret);
373 return ret;
376 /*************************************************************************
377 * CreateFileA [KERNEL32.@] Creates or opens a file or other object
379 * Creates or opens an object, and returns a handle that can be used to
380 * access that object.
382 * PARAMS
384 * filename [in] pointer to filename to be accessed
385 * access [in] access mode requested
386 * sharing [in] share mode
387 * sa [in] pointer to security attributes
388 * creation [in] how to create the file
389 * attributes [in] attributes for newly created file
390 * template [in] handle to file with extended attributes to copy
392 * RETURNS
393 * Success: Open handle to specified file
394 * Failure: INVALID_HANDLE_VALUE
396 * NOTES
397 * Should call SetLastError() on failure.
399 * BUGS
401 * Doesn't support character devices, template files, or a
402 * lot of the 'attributes' flags yet.
404 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
405 LPSECURITY_ATTRIBUTES sa, DWORD creation,
406 DWORD attributes, HANDLE template )
408 DOS_FULL_NAME full_name;
409 HANDLE ret;
411 if (!filename)
413 SetLastError( ERROR_INVALID_PARAMETER );
414 return INVALID_HANDLE_VALUE;
416 TRACE("%s %s%s%s%s%s%s%s\n",filename,
417 ((access & GENERIC_READ)==GENERIC_READ)?"GENERIC_READ ":"",
418 ((access & GENERIC_WRITE)==GENERIC_WRITE)?"GENERIC_WRITE ":"",
419 (!access)?"QUERY_ACCESS ":"",
420 ((sharing & FILE_SHARE_READ)==FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
421 ((sharing & FILE_SHARE_WRITE)==FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
422 ((sharing & FILE_SHARE_DELETE)==FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
423 (creation ==CREATE_NEW)?"CREATE_NEW":
424 (creation ==CREATE_ALWAYS)?"CREATE_ALWAYS ":
425 (creation ==OPEN_EXISTING)?"OPEN_EXISTING ":
426 (creation ==OPEN_ALWAYS)?"OPEN_ALWAYS ":
427 (creation ==TRUNCATE_EXISTING)?"TRUNCATE_EXISTING ":"");
429 /* If the name starts with '\\?\', ignore the first 4 chars. */
430 if (!strncmp(filename, "\\\\?\\", 4))
432 filename += 4;
433 if (!strncmp(filename, "UNC\\", 4))
435 FIXME("UNC name (%s) not supported.\n", filename );
436 SetLastError( ERROR_PATH_NOT_FOUND );
437 return INVALID_HANDLE_VALUE;
441 if (!strncmp(filename, "\\\\.\\", 4)) {
442 if(!strncasecmp(&filename[4],"pipe\\",5))
444 TRACE("Opening a pipe: %s\n",filename);
445 ret = FILE_OpenPipe(filename,access);
446 goto done;
448 else if (!DOSFS_GetDevice( filename ))
450 ret = DEVICE_Open( filename+4, access, sa );
451 goto done;
453 else
454 filename+=4; /* fall into DOSFS_Device case below */
457 /* If the name still starts with '\\', it's a UNC name. */
458 if (!strncmp(filename, "\\\\", 2))
460 FIXME("UNC name (%s) not supported.\n", filename );
461 SetLastError( ERROR_PATH_NOT_FOUND );
462 return INVALID_HANDLE_VALUE;
465 /* If the name contains a DOS wild card (* or ?), do no create a file */
466 if(strchr(filename,'*') || strchr(filename,'?'))
467 return INVALID_HANDLE_VALUE;
469 /* Open a console for CONIN$ or CONOUT$ */
470 if (!strcasecmp(filename, "CONIN$"))
472 ret = FILE_OpenConsole( FALSE, access, sharing, sa );
473 goto done;
475 if (!strcasecmp(filename, "CONOUT$"))
477 ret = FILE_OpenConsole( TRUE, access, sharing, sa );
478 goto done;
481 if (DOSFS_GetDevice( filename ))
483 TRACE("opening device '%s'\n", filename );
485 if (!(ret = DOSFS_OpenDevice( filename, access, attributes, sa )))
487 /* Do not silence this please. It is a critical error. -MM */
488 ERR("Couldn't open device '%s'!\n",filename);
489 SetLastError( ERROR_FILE_NOT_FOUND );
491 goto done;
494 /* check for filename, don't check for last entry if creating */
495 if (!DOSFS_GetFullName( filename,
496 (creation == OPEN_EXISTING) ||
497 (creation == TRUNCATE_EXISTING),
498 &full_name )) {
499 WARN("Unable to get full filename from '%s' (GLE %ld)\n",
500 filename, GetLastError());
501 return INVALID_HANDLE_VALUE;
504 ret = FILE_CreateFile( full_name.long_name, access, sharing,
505 sa, creation, attributes, template,
506 DRIVE_GetFlags(full_name.drive) & DRIVE_FAIL_READ_ONLY,
507 GetDriveTypeA( full_name.short_name ) );
508 done:
509 if (!ret) ret = INVALID_HANDLE_VALUE;
510 return ret;
515 /*************************************************************************
516 * CreateFileW (KERNEL32.@)
518 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
519 LPSECURITY_ATTRIBUTES sa, DWORD creation,
520 DWORD attributes, HANDLE template)
522 LPSTR afn = HEAP_strdupWtoA( GetProcessHeap(), 0, filename );
523 HANDLE res = CreateFileA( afn, access, sharing, sa, creation, attributes, template );
524 HeapFree( GetProcessHeap(), 0, afn );
525 return res;
529 /***********************************************************************
530 * FILE_FillInfo
532 * Fill a file information from a struct stat.
534 static void FILE_FillInfo( struct stat *st, BY_HANDLE_FILE_INFORMATION *info )
536 if (S_ISDIR(st->st_mode))
537 info->dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
538 else
539 info->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
540 if (!(st->st_mode & S_IWUSR))
541 info->dwFileAttributes |= FILE_ATTRIBUTE_READONLY;
543 RtlSecondsSince1970ToTime( st->st_mtime, &info->ftCreationTime );
544 RtlSecondsSince1970ToTime( st->st_mtime, &info->ftLastWriteTime );
545 RtlSecondsSince1970ToTime( st->st_atime, &info->ftLastAccessTime );
547 info->dwVolumeSerialNumber = 0; /* FIXME */
548 info->nFileSizeHigh = 0;
549 info->nFileSizeLow = 0;
550 if (!S_ISDIR(st->st_mode)) {
551 info->nFileSizeHigh = st->st_size >> 32;
552 info->nFileSizeLow = st->st_size & 0xffffffff;
554 info->nNumberOfLinks = st->st_nlink;
555 info->nFileIndexHigh = 0;
556 info->nFileIndexLow = st->st_ino;
560 /***********************************************************************
561 * FILE_Stat
563 * Stat a Unix path name. Return TRUE if OK.
565 BOOL FILE_Stat( LPCSTR unixName, BY_HANDLE_FILE_INFORMATION *info )
567 struct stat st;
569 if (lstat( unixName, &st ) == -1)
571 FILE_SetDosError();
572 return FALSE;
574 if (!S_ISLNK(st.st_mode)) FILE_FillInfo( &st, info );
575 else
577 /* do a "real" stat to find out
578 about the type of the symlink destination */
579 if (stat( unixName, &st ) == -1)
581 FILE_SetDosError();
582 return FALSE;
584 FILE_FillInfo( &st, info );
585 info->dwFileAttributes |= FILE_ATTRIBUTE_SYMLINK;
587 return TRUE;
591 /***********************************************************************
592 * GetFileInformationByHandle (KERNEL32.@)
594 DWORD WINAPI GetFileInformationByHandle( HANDLE hFile,
595 BY_HANDLE_FILE_INFORMATION *info )
597 DWORD ret;
598 if (!info) return 0;
600 SERVER_START_REQ( get_file_info )
602 req->handle = hFile;
603 if ((ret = !wine_server_call_err( req )))
605 /* FIXME: which file types are supported ?
606 * Serial ports (FILE_TYPE_CHAR) are not,
607 * and MSDN also says that pipes are not supported.
608 * FILE_TYPE_REMOTE seems to be supported according to
609 * MSDN q234741.txt */
610 if ((reply->type == FILE_TYPE_DISK) || (reply->type == FILE_TYPE_REMOTE))
612 RtlSecondsSince1970ToTime( reply->write_time, &info->ftCreationTime );
613 RtlSecondsSince1970ToTime( reply->write_time, &info->ftLastWriteTime );
614 RtlSecondsSince1970ToTime( reply->access_time, &info->ftLastAccessTime );
615 info->dwFileAttributes = reply->attr;
616 info->dwVolumeSerialNumber = reply->serial;
617 info->nFileSizeHigh = reply->size_high;
618 info->nFileSizeLow = reply->size_low;
619 info->nNumberOfLinks = reply->links;
620 info->nFileIndexHigh = reply->index_high;
621 info->nFileIndexLow = reply->index_low;
623 else
625 SetLastError(ERROR_NOT_SUPPORTED);
626 ret = 0;
630 SERVER_END_REQ;
631 return ret;
635 /**************************************************************************
636 * GetFileAttributes (KERNEL.420)
638 DWORD WINAPI GetFileAttributes16( LPCSTR name )
640 return GetFileAttributesA( name );
644 /**************************************************************************
645 * GetFileAttributesA (KERNEL32.@)
647 DWORD WINAPI GetFileAttributesA( LPCSTR name )
649 DOS_FULL_NAME full_name;
650 BY_HANDLE_FILE_INFORMATION info;
652 if (name == NULL)
654 SetLastError( ERROR_INVALID_PARAMETER );
655 return -1;
657 if (!DOSFS_GetFullName( name, TRUE, &full_name) )
658 return -1;
659 if (!FILE_Stat( full_name.long_name, &info )) return -1;
660 return info.dwFileAttributes;
664 /**************************************************************************
665 * GetFileAttributesW (KERNEL32.@)
667 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
669 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
670 DWORD res = GetFileAttributesA( nameA );
671 HeapFree( GetProcessHeap(), 0, nameA );
672 return res;
676 /***********************************************************************
677 * GetFileSize (KERNEL32.@)
679 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
681 BY_HANDLE_FILE_INFORMATION info;
682 if (!GetFileInformationByHandle( hFile, &info )) return -1;
683 if (filesizehigh) *filesizehigh = info.nFileSizeHigh;
684 return info.nFileSizeLow;
688 /***********************************************************************
689 * GetFileTime (KERNEL32.@)
691 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
692 FILETIME *lpLastAccessTime,
693 FILETIME *lpLastWriteTime )
695 BY_HANDLE_FILE_INFORMATION info;
696 if (!GetFileInformationByHandle( hFile, &info )) return FALSE;
697 if (lpCreationTime) *lpCreationTime = info.ftCreationTime;
698 if (lpLastAccessTime) *lpLastAccessTime = info.ftLastAccessTime;
699 if (lpLastWriteTime) *lpLastWriteTime = info.ftLastWriteTime;
700 return TRUE;
703 /***********************************************************************
704 * CompareFileTime (KERNEL32.@)
706 INT WINAPI CompareFileTime( LPFILETIME x, LPFILETIME y )
708 if (!x || !y) return -1;
710 if (x->dwHighDateTime > y->dwHighDateTime)
711 return 1;
712 if (x->dwHighDateTime < y->dwHighDateTime)
713 return -1;
714 if (x->dwLowDateTime > y->dwLowDateTime)
715 return 1;
716 if (x->dwLowDateTime < y->dwLowDateTime)
717 return -1;
718 return 0;
721 /***********************************************************************
722 * FILE_GetTempFileName : utility for GetTempFileName
724 static UINT FILE_GetTempFileName( LPCSTR path, LPCSTR prefix, UINT unique,
725 LPSTR buffer, BOOL isWin16 )
727 static UINT unique_temp;
728 DOS_FULL_NAME full_name;
729 int i;
730 LPSTR p;
731 UINT num;
733 if ( !path || !prefix || !buffer ) return 0;
735 if (!unique_temp) unique_temp = time(NULL) & 0xffff;
736 num = unique ? (unique & 0xffff) : (unique_temp++ & 0xffff);
738 strcpy( buffer, path );
739 p = buffer + strlen(buffer);
741 /* add a \, if there isn't one and path is more than just the drive letter ... */
742 if ( !((strlen(buffer) == 2) && (buffer[1] == ':'))
743 && ((p == buffer) || (p[-1] != '\\'))) *p++ = '\\';
745 if (isWin16) *p++ = '~';
746 for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
747 sprintf( p, "%04x.tmp", num );
749 /* Now try to create it */
751 if (!unique)
755 HFILE handle = CreateFileA( buffer, GENERIC_WRITE, 0, NULL,
756 CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
757 if (handle != INVALID_HANDLE_VALUE)
758 { /* We created it */
759 TRACE("created %s\n",
760 buffer);
761 CloseHandle( handle );
762 break;
764 if (GetLastError() != ERROR_FILE_EXISTS)
765 break; /* No need to go on */
766 num++;
767 sprintf( p, "%04x.tmp", num );
768 } while (num != (unique & 0xffff));
771 /* Get the full path name */
773 if (DOSFS_GetFullName( buffer, FALSE, &full_name ))
775 /* Check if we have write access in the directory */
776 if ((p = strrchr( full_name.long_name, '/' ))) *p = '\0';
777 if (access( full_name.long_name, W_OK ) == -1)
778 WARN("returns '%s', which doesn't seem to be writeable.\n",
779 buffer);
781 TRACE("returning %s\n", buffer );
782 return unique ? unique : num;
786 /***********************************************************************
787 * GetTempFileNameA (KERNEL32.@)
789 UINT WINAPI GetTempFileNameA( LPCSTR path, LPCSTR prefix, UINT unique,
790 LPSTR buffer)
792 return FILE_GetTempFileName(path, prefix, unique, buffer, FALSE);
795 /***********************************************************************
796 * GetTempFileNameW (KERNEL32.@)
798 UINT WINAPI GetTempFileNameW( LPCWSTR path, LPCWSTR prefix, UINT unique,
799 LPWSTR buffer )
801 LPSTR patha,prefixa;
802 char buffera[144];
803 UINT ret;
805 if (!path) return 0;
806 patha = HEAP_strdupWtoA( GetProcessHeap(), 0, path );
807 prefixa = HEAP_strdupWtoA( GetProcessHeap(), 0, prefix );
808 ret = FILE_GetTempFileName( patha, prefixa, unique, buffera, FALSE );
809 MultiByteToWideChar( CP_ACP, 0, buffera, -1, buffer, MAX_PATH );
810 HeapFree( GetProcessHeap(), 0, patha );
811 HeapFree( GetProcessHeap(), 0, prefixa );
812 return ret;
816 /***********************************************************************
817 * GetTempFileName (KERNEL.97)
819 UINT16 WINAPI GetTempFileName16( BYTE drive, LPCSTR prefix, UINT16 unique,
820 LPSTR buffer )
822 char temppath[144];
824 if (!(drive & ~TF_FORCEDRIVE)) /* drive 0 means current default drive */
825 drive |= DRIVE_GetCurrentDrive() + 'A';
827 if ((drive & TF_FORCEDRIVE) &&
828 !DRIVE_IsValid( toupper(drive & ~TF_FORCEDRIVE) - 'A' ))
830 drive &= ~TF_FORCEDRIVE;
831 WARN("invalid drive %d specified\n", drive );
834 if (drive & TF_FORCEDRIVE)
835 sprintf(temppath,"%c:", drive & ~TF_FORCEDRIVE );
836 else
837 GetTempPathA( 132, temppath );
838 return (UINT16)FILE_GetTempFileName( temppath, prefix, unique, buffer, TRUE );
841 /***********************************************************************
842 * FILE_DoOpenFile
844 * Implementation of OpenFile16() and OpenFile32().
846 static HFILE FILE_DoOpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode,
847 BOOL win32 )
849 HFILE hFileRet;
850 FILETIME filetime;
851 WORD filedatetime[2];
852 DOS_FULL_NAME full_name;
853 DWORD access, sharing;
854 char *p;
856 if (!ofs) return HFILE_ERROR;
858 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
859 ((mode & 0x3 )==OF_READ)?"OF_READ":
860 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
861 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
862 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
863 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
864 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
865 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
866 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
867 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
868 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
869 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
870 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
871 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
872 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
873 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
874 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
875 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
879 ofs->cBytes = sizeof(OFSTRUCT);
880 ofs->nErrCode = 0;
881 if (mode & OF_REOPEN) name = ofs->szPathName;
883 if (!name) {
884 ERR("called with `name' set to NULL ! Please debug.\n");
885 return HFILE_ERROR;
888 TRACE("%s %04x\n", name, mode );
890 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
891 Are there any cases where getting the path here is wrong?
892 Uwe Bonnes 1997 Apr 2 */
893 if (!GetFullPathNameA( name, sizeof(ofs->szPathName),
894 ofs->szPathName, NULL )) goto error;
895 FILE_ConvertOFMode( mode, &access, &sharing );
897 /* OF_PARSE simply fills the structure */
899 if (mode & OF_PARSE)
901 ofs->fFixedDisk = (GetDriveType16( ofs->szPathName[0]-'A' )
902 != DRIVE_REMOVABLE);
903 TRACE("(%s): OF_PARSE, res = '%s'\n",
904 name, ofs->szPathName );
905 return 0;
908 /* OF_CREATE is completely different from all other options, so
909 handle it first */
911 if (mode & OF_CREATE)
913 if ((hFileRet = CreateFileA( name, GENERIC_READ | GENERIC_WRITE,
914 sharing, NULL, CREATE_ALWAYS,
915 FILE_ATTRIBUTE_NORMAL, 0 ))== INVALID_HANDLE_VALUE)
916 goto error;
917 goto success;
920 /* If OF_SEARCH is set, ignore the given path */
922 if ((mode & OF_SEARCH) && !(mode & OF_REOPEN))
924 /* First try the file name as is */
925 if (DOSFS_GetFullName( name, TRUE, &full_name )) goto found;
926 /* Now remove the path */
927 if (name[0] && (name[1] == ':')) name += 2;
928 if ((p = strrchr( name, '\\' ))) name = p + 1;
929 if ((p = strrchr( name, '/' ))) name = p + 1;
930 if (!name[0]) goto not_found;
933 /* Now look for the file */
935 if (!DIR_SearchPath( NULL, name, NULL, &full_name, win32 )) goto not_found;
937 found:
938 TRACE("found %s = %s\n",
939 full_name.long_name, full_name.short_name );
940 lstrcpynA( ofs->szPathName, full_name.short_name,
941 sizeof(ofs->szPathName) );
943 if (mode & OF_SHARE_EXCLUSIVE)
944 /* Some InstallShield version uses OF_SHARE_EXCLUSIVE
945 on the file <tempdir>/_ins0432._mp to determine how
946 far installation has proceeded.
947 _ins0432._mp is an executable and while running the
948 application expects the open with OF_SHARE_ to fail*/
949 /* Probable FIXME:
950 As our loader closes the files after loading the executable,
951 we can't find the running executable with FILE_InUse.
952 The loader should keep the file open, as Windows does that, too.
955 char *last = strrchr(full_name.long_name,'/');
956 if (!last)
957 last = full_name.long_name - 1;
958 if (GetModuleHandle16(last+1))
960 TRACE("Denying shared open for %s\n",full_name.long_name);
961 return HFILE_ERROR;
965 if (mode & OF_DELETE)
967 if (unlink( full_name.long_name ) == -1) goto not_found;
968 TRACE("(%s): OF_DELETE return = OK\n", name);
969 return 1;
972 hFileRet = FILE_CreateFile( full_name.long_name, access, sharing,
973 NULL, OPEN_EXISTING, 0, 0,
974 DRIVE_GetFlags(full_name.drive) & DRIVE_FAIL_READ_ONLY,
975 GetDriveTypeA( full_name.short_name ) );
976 if (!hFileRet) goto not_found;
978 GetFileTime( hFileRet, NULL, NULL, &filetime );
979 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
980 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
982 if (memcmp( ofs->reserved, filedatetime, sizeof(ofs->reserved) ))
984 CloseHandle( hFileRet );
985 WARN("(%s): OF_VERIFY failed\n", name );
986 /* FIXME: what error here? */
987 SetLastError( ERROR_FILE_NOT_FOUND );
988 goto error;
991 memcpy( ofs->reserved, filedatetime, sizeof(ofs->reserved) );
993 success: /* We get here if the open was successful */
994 TRACE("(%s): OK, return = %d\n", name, hFileRet );
995 if (win32)
997 if (mode & OF_EXIST) /* Return the handle, but close it first */
998 CloseHandle( hFileRet );
1000 else
1002 hFileRet = Win32HandleToDosFileHandle( hFileRet );
1003 if (hFileRet == HFILE_ERROR16) goto error;
1004 if (mode & OF_EXIST) /* Return the handle, but close it first */
1005 _lclose16( hFileRet );
1007 return hFileRet;
1009 not_found: /* We get here if the file does not exist */
1010 WARN("'%s' not found or sharing violation\n", name );
1011 SetLastError( ERROR_FILE_NOT_FOUND );
1012 /* fall through */
1014 error: /* We get here if there was an error opening the file */
1015 ofs->nErrCode = GetLastError();
1016 WARN("(%s): return = HFILE_ERROR error= %d\n",
1017 name,ofs->nErrCode );
1018 return HFILE_ERROR;
1022 /***********************************************************************
1023 * OpenFile (KERNEL.74)
1024 * OpenFileEx (KERNEL.360)
1026 HFILE16 WINAPI OpenFile16( LPCSTR name, OFSTRUCT *ofs, UINT16 mode )
1028 return FILE_DoOpenFile( name, ofs, mode, FALSE );
1032 /***********************************************************************
1033 * OpenFile (KERNEL32.@)
1035 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
1037 return FILE_DoOpenFile( name, ofs, mode, TRUE );
1041 /***********************************************************************
1042 * FILE_InitProcessDosHandles
1044 * Allocates the default DOS handles for a process. Called either by
1045 * Win32HandleToDosFileHandle below or by the DOSVM stuff.
1047 static void FILE_InitProcessDosHandles( void )
1049 dos_handles[0] = GetStdHandle(STD_INPUT_HANDLE);
1050 dos_handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
1051 dos_handles[2] = GetStdHandle(STD_ERROR_HANDLE);
1052 dos_handles[3] = GetStdHandle(STD_ERROR_HANDLE);
1053 dos_handles[4] = GetStdHandle(STD_ERROR_HANDLE);
1056 /***********************************************************************
1057 * Win32HandleToDosFileHandle (KERNEL32.21)
1059 * Allocate a DOS handle for a Win32 handle. The Win32 handle is no
1060 * longer valid after this function (even on failure).
1062 * Note: this is not exactly right, since on Win95 the Win32 handles
1063 * are on top of DOS handles and we do it the other way
1064 * around. Should be good enough though.
1066 HFILE WINAPI Win32HandleToDosFileHandle( HANDLE handle )
1068 int i;
1070 if (!handle || (handle == INVALID_HANDLE_VALUE))
1071 return HFILE_ERROR;
1073 for (i = 5; i < DOS_TABLE_SIZE; i++)
1074 if (!dos_handles[i])
1076 dos_handles[i] = handle;
1077 TRACE("Got %d for h32 %d\n", i, handle );
1078 return (HFILE)i;
1080 CloseHandle( handle );
1081 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1082 return HFILE_ERROR;
1086 /***********************************************************************
1087 * DosFileHandleToWin32Handle (KERNEL32.20)
1089 * Return the Win32 handle for a DOS handle.
1091 * Note: this is not exactly right, since on Win95 the Win32 handles
1092 * are on top of DOS handles and we do it the other way
1093 * around. Should be good enough though.
1095 HANDLE WINAPI DosFileHandleToWin32Handle( HFILE handle )
1097 HFILE16 hfile = (HFILE16)handle;
1098 if (hfile < 5 && !dos_handles[hfile]) FILE_InitProcessDosHandles();
1099 if ((hfile >= DOS_TABLE_SIZE) || !dos_handles[hfile])
1101 SetLastError( ERROR_INVALID_HANDLE );
1102 return INVALID_HANDLE_VALUE;
1104 return dos_handles[hfile];
1108 /***********************************************************************
1109 * DisposeLZ32Handle (KERNEL32.22)
1111 * Note: this is not entirely correct, we should only close the
1112 * 32-bit handle and not the 16-bit one, but we cannot do
1113 * this because of the way our DOS handles are implemented.
1114 * It shouldn't break anything though.
1116 void WINAPI DisposeLZ32Handle( HANDLE handle )
1118 int i;
1120 if (!handle || (handle == INVALID_HANDLE_VALUE)) return;
1122 for (i = 5; i < DOS_TABLE_SIZE; i++)
1123 if (dos_handles[i] == handle)
1125 dos_handles[i] = 0;
1126 CloseHandle( handle );
1127 break;
1132 /***********************************************************************
1133 * FILE_Dup2
1135 * dup2() function for DOS handles.
1137 HFILE16 FILE_Dup2( HFILE16 hFile1, HFILE16 hFile2 )
1139 HANDLE new_handle;
1141 if (hFile1 < 5 && !dos_handles[hFile1]) FILE_InitProcessDosHandles();
1143 if ((hFile1 >= DOS_TABLE_SIZE) || (hFile2 >= DOS_TABLE_SIZE) || !dos_handles[hFile1])
1145 SetLastError( ERROR_INVALID_HANDLE );
1146 return HFILE_ERROR16;
1148 if (hFile2 < 5)
1150 FIXME("stdio handle closed, need proper conversion\n" );
1151 SetLastError( ERROR_INVALID_HANDLE );
1152 return HFILE_ERROR16;
1154 if (!DuplicateHandle( GetCurrentProcess(), dos_handles[hFile1],
1155 GetCurrentProcess(), &new_handle,
1156 0, FALSE, DUPLICATE_SAME_ACCESS ))
1157 return HFILE_ERROR16;
1158 if (dos_handles[hFile2]) CloseHandle( dos_handles[hFile2] );
1159 dos_handles[hFile2] = new_handle;
1160 return hFile2;
1164 /***********************************************************************
1165 * _lclose (KERNEL.81)
1167 HFILE16 WINAPI _lclose16( HFILE16 hFile )
1169 if (hFile < 5)
1171 FIXME("stdio handle closed, need proper conversion\n" );
1172 SetLastError( ERROR_INVALID_HANDLE );
1173 return HFILE_ERROR16;
1175 if ((hFile >= DOS_TABLE_SIZE) || !dos_handles[hFile])
1177 SetLastError( ERROR_INVALID_HANDLE );
1178 return HFILE_ERROR16;
1180 TRACE("%d (handle32=%d)\n", hFile, dos_handles[hFile] );
1181 CloseHandle( dos_handles[hFile] );
1182 dos_handles[hFile] = 0;
1183 return 0;
1187 /***********************************************************************
1188 * _lclose (KERNEL32.@)
1190 HFILE WINAPI _lclose( HFILE hFile )
1192 TRACE("handle %d\n", hFile );
1193 return CloseHandle( hFile ) ? 0 : HFILE_ERROR;
1196 /***********************************************************************
1197 * GetOverlappedResult (KERNEL32.@)
1199 * Check the result of an Asynchronous data transfer from a file.
1201 * RETURNS
1202 * TRUE on success
1203 * FALSE on failure
1205 * If successful (and relevant) lpTransferred will hold the number of
1206 * bytes transferred during the async operation.
1208 * BUGS
1210 * Currently only works for WaitCommEvent, ReadFile, WriteFile
1211 * with communications ports.
1214 BOOL WINAPI GetOverlappedResult(
1215 HANDLE hFile, /* [in] handle of file to check on */
1216 LPOVERLAPPED lpOverlapped, /* [in/out] pointer to overlapped */
1217 LPDWORD lpTransferred, /* [in/out] number of bytes transferred */
1218 BOOL bWait /* [in] wait for the transfer to complete ? */
1220 DWORD r;
1222 TRACE("(%d %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait);
1224 if(lpOverlapped==NULL)
1226 ERR("lpOverlapped was null\n");
1227 return FALSE;
1229 if(!lpOverlapped->hEvent)
1231 ERR("lpOverlapped->hEvent was null\n");
1232 return FALSE;
1235 do {
1236 TRACE("waiting on %p\n",lpOverlapped);
1237 r = WaitForSingleObjectEx(lpOverlapped->hEvent, bWait?INFINITE:0, TRUE);
1238 TRACE("wait on %p returned %ld\n",lpOverlapped,r);
1239 } while (r==STATUS_USER_APC);
1241 if(lpTransferred)
1242 *lpTransferred = lpOverlapped->InternalHigh;
1244 SetLastError(lpOverlapped->Internal);
1246 return (r==WAIT_OBJECT_0);
1250 /***********************************************************************
1251 * CancelIo (KERNEL32.@)
1253 BOOL WINAPI CancelIo(HANDLE handle)
1255 FIXME("(%d) stub\n",handle);
1256 return FALSE;
1259 /***********************************************************************
1260 * FILE_AsyncReadService (INTERNAL)
1262 * This function is called while the client is waiting on the
1263 * server, so we can't make any server calls here.
1265 static void FILE_AsyncReadService(async_private *ovp, int events)
1267 LPOVERLAPPED lpOverlapped = ovp->lpOverlapped;
1268 int result, r;
1270 TRACE("%p %p %08x\n", lpOverlapped, ovp->buffer, events );
1272 /* if POLLNVAL, then our fd was closed or we have the wrong fd */
1273 if(events&POLLNVAL)
1275 ERR("fd %d invalid for %p\n",ovp->fd,ovp);
1276 r = STATUS_UNSUCCESSFUL;
1277 goto async_end;
1280 /* if there are no events, it must be a timeout */
1281 if(events==0)
1283 TRACE("read timed out\n");
1284 r = STATUS_TIMEOUT;
1285 goto async_end;
1288 /* check to see if the data is ready (non-blocking) */
1289 result = read(ovp->fd, &ovp->buffer[lpOverlapped->InternalHigh],
1290 ovp->count - lpOverlapped->InternalHigh);
1292 if ( (result<0) && ((errno == EAGAIN) || (errno == EINTR)))
1294 TRACE("Deferred read %d\n",errno);
1295 r = STATUS_PENDING;
1296 goto async_end;
1299 /* check to see if the transfer is complete */
1300 if(result<0)
1302 TRACE("read returned errno %d\n",errno);
1303 r = STATUS_UNSUCCESSFUL;
1304 goto async_end;
1307 lpOverlapped->InternalHigh += result;
1308 TRACE("read %d more bytes %ld/%d so far\n",result,lpOverlapped->InternalHigh,ovp->count);
1310 if(lpOverlapped->InternalHigh < ovp->count)
1311 r = STATUS_PENDING;
1312 else
1313 r = STATUS_SUCCESS;
1315 async_end:
1316 lpOverlapped->Internal = r;
1319 /* flogged from wineserver */
1320 /* add a timeout in milliseconds to an absolute time */
1321 static void add_timeout( struct timeval *when, int timeout )
1323 if (timeout)
1325 long sec = timeout / 1000;
1326 if ((when->tv_usec += (timeout - 1000*sec) * 1000) >= 1000000)
1328 when->tv_usec -= 1000000;
1329 when->tv_sec++;
1331 when->tv_sec += sec;
1335 /***********************************************************************
1336 * FILE_GetTimeout (INTERNAL)
1338 static BOOL FILE_GetTimeout(HANDLE hFile, DWORD txcount, DWORD type, int *timeout)
1340 BOOL ret;
1341 SERVER_START_REQ(create_async)
1343 req->count = txcount;
1344 req->type = type;
1345 req->file_handle = hFile;
1346 ret = wine_server_call( req );
1347 if(timeout)
1348 *timeout = reply->timeout;
1350 SERVER_END_REQ;
1351 return !ret;
1354 /***********************************************************************
1355 * FILE_ReadFileEx (INTERNAL)
1357 static BOOL FILE_ReadFileEx(HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
1358 LPOVERLAPPED overlapped,
1359 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
1361 async_private *ovp;
1362 int fd, timeout=0;
1364 TRACE("file %d to buf %p num %ld %p func %p\n",
1365 hFile, buffer, bytesToRead, overlapped, lpCompletionRoutine);
1367 /* check that there is an overlapped struct with an event flag */
1368 if ( (overlapped==NULL) || NtResetEvent( overlapped->hEvent, NULL ) )
1370 TRACE("Overlapped not specified or invalid event flag\n");
1371 SetLastError(ERROR_INVALID_PARAMETER);
1372 return FALSE;
1375 if ( !FILE_GetTimeout(hFile, bytesToRead, ASYNC_TYPE_READ, &timeout ) )
1377 TRACE("FILE_GetTimeout 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 );
1447 switch (type)
1449 case FD_TYPE_OVERLAPPED:
1450 if (unix_handle == -1) return FALSE;
1451 if (!overlapped)
1453 close(unix_handle);
1454 SetLastError(ERROR_INVALID_PARAMETER);
1455 return FALSE;
1458 /* see if we can read some data already (this shouldn't block) */
1459 result = read( unix_handle, buffer, bytesToRead );
1460 close(unix_handle);
1462 if(result<0)
1464 FILE_SetDosError();
1465 return FALSE;
1468 /* if we read enough to keep the app happy, then return now */
1469 if(result>=bytesToRead)
1471 *bytesRead = result;
1472 return TRUE;
1475 /* at last resort, do an overlapped read */
1476 overlapped->Internal = STATUS_PENDING;
1477 overlapped->InternalHigh = result;
1479 if(!FILE_ReadFileEx(hFile, buffer, bytesToRead, overlapped, NULL))
1480 return FALSE;
1482 /* fail on return, with ERROR_IO_PENDING */
1483 SetLastError(ERROR_IO_PENDING);
1484 return FALSE;
1486 case FD_TYPE_CONSOLE:
1487 return ReadConsoleA(hFile, buffer, bytesToRead, bytesRead, NULL);
1488 default:
1489 /* normal unix files */
1490 if (unix_handle == -1)
1491 return FALSE;
1492 if (overlapped)
1494 close(unix_handle);
1495 SetLastError(ERROR_INVALID_PARAMETER);
1496 return FALSE;
1498 break;
1501 /* code for synchronous reads */
1502 while ((result = read( unix_handle, buffer, bytesToRead )) == -1)
1504 if ((errno == EAGAIN) || (errno == EINTR)) continue;
1505 if ((errno == EFAULT) && !IsBadWritePtr( buffer, bytesToRead )) continue;
1506 FILE_SetDosError();
1507 break;
1509 close( unix_handle );
1510 if (result == -1) return FALSE;
1511 if (bytesRead) *bytesRead = result;
1512 return TRUE;
1516 /***********************************************************************
1517 * FILE_AsyncWriteService (INTERNAL)
1519 * This function is called while the client is waiting on the
1520 * server, so we can't make any server calls here.
1522 static void FILE_AsyncWriteService(struct async_private *ovp, int events)
1524 LPOVERLAPPED lpOverlapped = ovp->lpOverlapped;
1525 int result, r;
1527 TRACE("(%p %p %08x)\n",lpOverlapped,ovp->buffer,events);
1529 /* if POLLNVAL, then our fd was closed or we have the wrong fd */
1530 if(events&POLLNVAL)
1532 ERR("fd %d invalid for %p\n",ovp->fd,ovp);
1533 r = STATUS_UNSUCCESSFUL;
1534 goto async_end;
1537 /* if there are no events, it must be a timeout */
1538 if(events==0)
1540 TRACE("write timed out\n");
1541 r = STATUS_TIMEOUT;
1542 goto async_end;
1545 /* write some data (non-blocking) */
1546 result = write(ovp->fd, &ovp->buffer[lpOverlapped->InternalHigh],
1547 ovp->count-lpOverlapped->InternalHigh);
1549 if ( (result<0) && ((errno == EAGAIN) || (errno == EINTR)))
1551 r = STATUS_PENDING;
1552 goto async_end;
1555 /* check to see if the transfer is complete */
1556 if(result<0)
1558 r = STATUS_UNSUCCESSFUL;
1559 goto async_end;
1562 lpOverlapped->InternalHigh += result;
1564 TRACE("wrote %d more bytes %ld/%d so far\n",result,lpOverlapped->InternalHigh,ovp->count);
1566 if(lpOverlapped->InternalHigh < ovp->count)
1567 r = STATUS_PENDING;
1568 else
1569 r = STATUS_SUCCESS;
1571 async_end:
1572 lpOverlapped->Internal = r;
1575 /***********************************************************************
1576 * WriteFileEx (KERNEL32.@)
1578 BOOL WINAPI WriteFileEx(HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
1579 LPOVERLAPPED overlapped,
1580 LPOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine)
1582 async_private *ovp;
1583 int timeout=0;
1585 TRACE("file %d to buf %p num %ld %p func %p stub\n",
1586 hFile, buffer, bytesToWrite, overlapped, lpCompletionRoutine);
1588 if ( (overlapped == NULL) || NtResetEvent( overlapped->hEvent, NULL ) )
1590 SetLastError(ERROR_INVALID_PARAMETER);
1591 return FALSE;
1594 overlapped->Internal = STATUS_PENDING;
1595 overlapped->InternalHigh = 0;
1597 if (!FILE_GetTimeout(hFile, bytesToWrite, ASYNC_TYPE_WRITE, &timeout))
1599 TRACE("FILE_GetTimeout failed\n");
1600 return FALSE;
1603 ovp = (async_private*) HeapAlloc(GetProcessHeap(), 0, sizeof (async_private));
1604 if(!ovp)
1606 TRACE("HeapAlloc Failed\n");
1607 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
1608 return FALSE;
1610 ovp->lpOverlapped = overlapped;
1611 ovp->timeout = timeout;
1612 gettimeofday(&ovp->tv,NULL);
1613 add_timeout(&ovp->tv,timeout);
1614 ovp->event = POLLOUT;
1615 ovp->func = FILE_AsyncWriteService;
1616 ovp->buffer = (LPVOID) buffer;
1617 ovp->count = bytesToWrite;
1618 ovp->completion_func = lpCompletionRoutine;
1619 ovp->fd = FILE_GetUnixHandle( hFile, GENERIC_WRITE );
1620 if(ovp->fd <0)
1622 HeapFree(GetProcessHeap(), 0, ovp);
1623 return FALSE;
1626 /* hook this overlap into the pending async operation list */
1627 ovp->next = NtCurrentTeb()->pending_list;
1628 ovp->prev = NULL;
1629 if(ovp->next)
1630 ovp->next->prev = ovp;
1631 NtCurrentTeb()->pending_list = ovp;
1633 SetLastError(ERROR_IO_PENDING);
1635 /* always fail on return, either ERROR_IO_PENDING or other error */
1636 return FALSE;
1639 /***********************************************************************
1640 * WriteFile (KERNEL32.@)
1642 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
1643 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
1645 int unix_handle, result;
1646 DWORD type;
1648 TRACE("%d %p %ld %p %p\n", hFile, buffer, bytesToWrite,
1649 bytesWritten, overlapped );
1651 if (bytesWritten) *bytesWritten = 0; /* Do this before anything else */
1652 if (!bytesToWrite) return TRUE;
1654 /* this will only have impact if the overlappd structure is specified */
1655 if ( overlapped )
1656 return WriteFileEx(hFile, buffer, bytesToWrite, overlapped, NULL);
1658 unix_handle = FILE_GetUnixHandleType( hFile, GENERIC_WRITE, &type );
1660 switch (type)
1662 case FD_TYPE_CONSOLE:
1663 TRACE("%d %s %ld %p %p\n", hFile, debugstr_an(buffer, bytesToWrite), bytesToWrite,
1664 bytesWritten, overlapped );
1665 return WriteConsoleA(hFile, buffer, bytesToWrite, bytesWritten, NULL);
1666 default:
1667 if (unix_handle == -1)
1668 return FALSE;
1671 /* synchronous file write */
1672 while ((result = write( unix_handle, buffer, bytesToWrite )) == -1)
1674 if ((errno == EAGAIN) || (errno == EINTR)) continue;
1675 if ((errno == EFAULT) && !IsBadReadPtr( buffer, bytesToWrite )) continue;
1676 if (errno == ENOSPC)
1677 SetLastError( ERROR_DISK_FULL );
1678 else
1679 FILE_SetDosError();
1680 break;
1682 close( unix_handle );
1683 if (result == -1) return FALSE;
1684 if (bytesWritten) *bytesWritten = result;
1685 return TRUE;
1689 /***********************************************************************
1690 * _hread (KERNEL.349)
1692 LONG WINAPI WIN16_hread( HFILE16 hFile, SEGPTR buffer, LONG count )
1694 LONG maxlen;
1696 TRACE("%d %08lx %ld\n",
1697 hFile, (DWORD)buffer, count );
1699 /* Some programs pass a count larger than the allocated buffer */
1700 maxlen = GetSelectorLimit16( SELECTOROF(buffer) ) - OFFSETOF(buffer) + 1;
1701 if (count > maxlen) count = maxlen;
1702 return _lread(DosFileHandleToWin32Handle(hFile), MapSL(buffer), count );
1706 /***********************************************************************
1707 * _lread (KERNEL.82)
1709 UINT16 WINAPI WIN16_lread( HFILE16 hFile, SEGPTR buffer, UINT16 count )
1711 return (UINT16)WIN16_hread( hFile, buffer, (LONG)count );
1715 /***********************************************************************
1716 * _lread (KERNEL32.@)
1718 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
1720 DWORD result;
1721 if (!ReadFile( handle, buffer, count, &result, NULL )) return -1;
1722 return result;
1726 /***********************************************************************
1727 * _lread16 (KERNEL.82)
1729 UINT16 WINAPI _lread16( HFILE16 hFile, LPVOID buffer, UINT16 count )
1731 return (UINT16)_lread(DosFileHandleToWin32Handle(hFile), buffer, (LONG)count );
1735 /***********************************************************************
1736 * _lcreat (KERNEL.83)
1738 HFILE16 WINAPI _lcreat16( LPCSTR path, INT16 attr )
1740 return Win32HandleToDosFileHandle( _lcreat( path, attr ) );
1744 /***********************************************************************
1745 * _lcreat (KERNEL32.@)
1747 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
1749 /* Mask off all flags not explicitly allowed by the doc */
1750 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
1751 TRACE("%s %02x\n", path, attr );
1752 return CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
1753 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1754 CREATE_ALWAYS, attr, 0 );
1758 /***********************************************************************
1759 * SetFilePointer (KERNEL32.@)
1761 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword,
1762 DWORD method )
1764 DWORD ret = 0xffffffff;
1766 TRACE("handle %d offset %ld high %ld origin %ld\n",
1767 hFile, distance, highword?*highword:0, method );
1769 SERVER_START_REQ( set_file_pointer )
1771 req->handle = hFile;
1772 req->low = distance;
1773 req->high = highword ? *highword : (distance >= 0) ? 0 : -1;
1774 /* FIXME: assumes 1:1 mapping between Windows and Unix seek constants */
1775 req->whence = method;
1776 SetLastError( 0 );
1777 if (!wine_server_call_err( req ))
1779 ret = reply->new_low;
1780 if (highword) *highword = reply->new_high;
1783 SERVER_END_REQ;
1784 return ret;
1788 /***********************************************************************
1789 * _llseek (KERNEL.84)
1791 * FIXME:
1792 * Seeking before the start of the file should be allowed for _llseek16,
1793 * but cause subsequent I/O operations to fail (cf. interrupt list)
1796 LONG WINAPI _llseek16( HFILE16 hFile, LONG lOffset, INT16 nOrigin )
1798 return SetFilePointer( DosFileHandleToWin32Handle(hFile), lOffset, NULL, nOrigin );
1802 /***********************************************************************
1803 * _llseek (KERNEL32.@)
1805 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
1807 return SetFilePointer( hFile, lOffset, NULL, nOrigin );
1811 /***********************************************************************
1812 * _lopen (KERNEL.85)
1814 HFILE16 WINAPI _lopen16( LPCSTR path, INT16 mode )
1816 return Win32HandleToDosFileHandle( _lopen( path, mode ) );
1820 /***********************************************************************
1821 * _lopen (KERNEL32.@)
1823 HFILE WINAPI _lopen( LPCSTR path, INT mode )
1825 DWORD access, sharing;
1827 TRACE("('%s',%04x)\n", path, mode );
1828 FILE_ConvertOFMode( mode, &access, &sharing );
1829 return CreateFileA( path, access, sharing, NULL, OPEN_EXISTING, 0, 0 );
1833 /***********************************************************************
1834 * _lwrite (KERNEL.86)
1836 UINT16 WINAPI _lwrite16( HFILE16 hFile, LPCSTR buffer, UINT16 count )
1838 return (UINT16)_hwrite( DosFileHandleToWin32Handle(hFile), buffer, (LONG)count );
1841 /***********************************************************************
1842 * _lwrite (KERNEL32.@)
1844 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
1846 return (UINT)_hwrite( hFile, buffer, (LONG)count );
1850 /***********************************************************************
1851 * _hread16 (KERNEL.349)
1853 LONG WINAPI _hread16( HFILE16 hFile, LPVOID buffer, LONG count)
1855 return _lread( DosFileHandleToWin32Handle(hFile), buffer, count );
1859 /***********************************************************************
1860 * _hread (KERNEL32.@)
1862 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
1864 return _lread( hFile, buffer, count );
1868 /***********************************************************************
1869 * _hwrite (KERNEL.350)
1871 LONG WINAPI _hwrite16( HFILE16 hFile, LPCSTR buffer, LONG count )
1873 return _hwrite( DosFileHandleToWin32Handle(hFile), buffer, count );
1877 /***********************************************************************
1878 * _hwrite (KERNEL32.@)
1880 * experimentation yields that _lwrite:
1881 * o truncates the file at the current position with
1882 * a 0 len write
1883 * o returns 0 on a 0 length write
1884 * o works with console handles
1887 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
1889 DWORD result;
1891 TRACE("%d %p %ld\n", handle, buffer, count );
1893 if (!count)
1895 /* Expand or truncate at current position */
1896 if (!SetEndOfFile( handle )) return HFILE_ERROR;
1897 return 0;
1899 if (!WriteFile( handle, buffer, count, &result, NULL ))
1900 return HFILE_ERROR;
1901 return result;
1905 /***********************************************************************
1906 * SetHandleCount (KERNEL.199)
1908 UINT16 WINAPI SetHandleCount16( UINT16 count )
1910 return SetHandleCount( count );
1914 /*************************************************************************
1915 * SetHandleCount (KERNEL32.@)
1917 UINT WINAPI SetHandleCount( UINT count )
1919 return min( 256, count );
1923 /***********************************************************************
1924 * FlushFileBuffers (KERNEL32.@)
1926 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
1928 BOOL ret;
1929 SERVER_START_REQ( flush_file )
1931 req->handle = hFile;
1932 ret = !wine_server_call_err( req );
1934 SERVER_END_REQ;
1935 return ret;
1939 /**************************************************************************
1940 * SetEndOfFile (KERNEL32.@)
1942 BOOL WINAPI SetEndOfFile( HANDLE hFile )
1944 BOOL ret;
1945 SERVER_START_REQ( truncate_file )
1947 req->handle = hFile;
1948 ret = !wine_server_call_err( req );
1950 SERVER_END_REQ;
1951 return ret;
1955 /***********************************************************************
1956 * DeleteFile (KERNEL.146)
1958 BOOL16 WINAPI DeleteFile16( LPCSTR path )
1960 return DeleteFileA( path );
1964 /***********************************************************************
1965 * DeleteFileA (KERNEL32.@)
1967 BOOL WINAPI DeleteFileA( LPCSTR path )
1969 DOS_FULL_NAME full_name;
1971 if (!path)
1973 SetLastError(ERROR_INVALID_PARAMETER);
1974 return FALSE;
1976 TRACE("'%s'\n", path );
1978 if (!*path)
1980 ERR("Empty path passed\n");
1981 return FALSE;
1983 if (DOSFS_GetDevice( path ))
1985 WARN("cannot remove DOS device '%s'!\n", path);
1986 SetLastError( ERROR_FILE_NOT_FOUND );
1987 return FALSE;
1990 if (!DOSFS_GetFullName( path, TRUE, &full_name )) return FALSE;
1991 if (unlink( full_name.long_name ) == -1)
1993 FILE_SetDosError();
1994 return FALSE;
1996 return TRUE;
2000 /***********************************************************************
2001 * DeleteFileW (KERNEL32.@)
2003 BOOL WINAPI DeleteFileW( LPCWSTR path )
2005 LPSTR xpath = HEAP_strdupWtoA( GetProcessHeap(), 0, path );
2006 BOOL ret = DeleteFileA( xpath );
2007 HeapFree( GetProcessHeap(), 0, xpath );
2008 return ret;
2012 /***********************************************************************
2013 * GetFileType (KERNEL32.@)
2015 DWORD WINAPI GetFileType( HANDLE hFile )
2017 DWORD ret = FILE_TYPE_UNKNOWN;
2018 SERVER_START_REQ( get_file_info )
2020 req->handle = hFile;
2021 if (!wine_server_call_err( req )) ret = reply->type;
2023 SERVER_END_REQ;
2024 return ret;
2028 /* check if a file name is for an executable file (.exe or .com) */
2029 inline static BOOL is_executable( const char *name )
2031 int len = strlen(name);
2033 if (len < 4) return FALSE;
2034 return (!strcasecmp( name + len - 4, ".exe" ) ||
2035 !strcasecmp( name + len - 4, ".com" ));
2039 /**************************************************************************
2040 * MoveFileExA (KERNEL32.@)
2042 BOOL WINAPI MoveFileExA( LPCSTR fn1, LPCSTR fn2, DWORD flag )
2044 DOS_FULL_NAME full_name1, full_name2;
2046 TRACE("(%s,%s,%04lx)\n", fn1, fn2, flag);
2048 if (!fn1) {
2049 SetLastError(ERROR_INVALID_PARAMETER);
2050 return FALSE;
2053 if (!DOSFS_GetFullName( fn1, TRUE, &full_name1 )) return FALSE;
2055 if (fn2) /* !fn2 means delete fn1 */
2057 if (DOSFS_GetFullName( fn2, TRUE, &full_name2 ))
2059 /* target exists, check if we may overwrite */
2060 if (!(flag & MOVEFILE_REPLACE_EXISTING))
2062 /* FIXME: Use right error code */
2063 SetLastError( ERROR_ACCESS_DENIED );
2064 return FALSE;
2067 else if (!DOSFS_GetFullName( fn2, FALSE, &full_name2 )) return FALSE;
2069 /* Source name and target path are valid */
2071 if (flag & MOVEFILE_DELAY_UNTIL_REBOOT)
2073 /* FIXME: (bon@elektron.ikp.physik.th-darmstadt.de 970706)
2074 Perhaps we should queue these command and execute it
2075 when exiting... What about using on_exit(2)
2077 FIXME("Please move existing file '%s' to file '%s' when Wine has finished\n",
2078 full_name1.long_name, full_name2.long_name);
2079 return TRUE;
2082 if (full_name1.drive != full_name2.drive)
2084 /* use copy, if allowed */
2085 if (!(flag & MOVEFILE_COPY_ALLOWED))
2087 /* FIXME: Use right error code */
2088 SetLastError( ERROR_FILE_EXISTS );
2089 return FALSE;
2091 return CopyFileA( fn1, fn2, !(flag & MOVEFILE_REPLACE_EXISTING) );
2093 if (rename( full_name1.long_name, full_name2.long_name ) == -1)
2095 FILE_SetDosError();
2096 return FALSE;
2098 if (is_executable( full_name1.long_name ) != is_executable( full_name2.long_name ))
2100 struct stat fstat;
2101 if (stat( full_name2.long_name, &fstat ) != -1)
2103 if (is_executable( full_name2.long_name ))
2104 /* set executable bit where read bit is set */
2105 fstat.st_mode |= (fstat.st_mode & 0444) >> 2;
2106 else
2107 fstat.st_mode &= ~0111;
2108 chmod( full_name2.long_name, fstat.st_mode );
2111 return TRUE;
2113 else /* fn2 == NULL means delete source */
2115 if (flag & MOVEFILE_DELAY_UNTIL_REBOOT)
2117 if (flag & MOVEFILE_COPY_ALLOWED) {
2118 WARN("Illegal flag\n");
2119 SetLastError( ERROR_GEN_FAILURE );
2120 return FALSE;
2122 /* FIXME: (bon@elektron.ikp.physik.th-darmstadt.de 970706)
2123 Perhaps we should queue these command and execute it
2124 when exiting... What about using on_exit(2)
2126 FIXME("Please delete file '%s' when Wine has finished\n",
2127 full_name1.long_name);
2128 return TRUE;
2131 if (unlink( full_name1.long_name ) == -1)
2133 FILE_SetDosError();
2134 return FALSE;
2136 return TRUE; /* successfully deleted */
2140 /**************************************************************************
2141 * MoveFileExW (KERNEL32.@)
2143 BOOL WINAPI MoveFileExW( LPCWSTR fn1, LPCWSTR fn2, DWORD flag )
2145 LPSTR afn1 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn1 );
2146 LPSTR afn2 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn2 );
2147 BOOL res = MoveFileExA( afn1, afn2, flag );
2148 HeapFree( GetProcessHeap(), 0, afn1 );
2149 HeapFree( GetProcessHeap(), 0, afn2 );
2150 return res;
2154 /**************************************************************************
2155 * MoveFileA (KERNEL32.@)
2157 * Move file or directory
2159 BOOL WINAPI MoveFileA( LPCSTR fn1, LPCSTR fn2 )
2161 DOS_FULL_NAME full_name1, full_name2;
2162 struct stat fstat;
2164 TRACE("(%s,%s)\n", fn1, fn2 );
2166 if (!DOSFS_GetFullName( fn1, TRUE, &full_name1 )) return FALSE;
2167 if (DOSFS_GetFullName( fn2, TRUE, &full_name2 )) {
2168 /* The new name must not already exist */
2169 SetLastError(ERROR_ALREADY_EXISTS);
2170 return FALSE;
2172 if (!DOSFS_GetFullName( fn2, FALSE, &full_name2 )) return FALSE;
2174 if (full_name1.drive == full_name2.drive) /* move */
2175 return MoveFileExA( fn1, fn2, MOVEFILE_COPY_ALLOWED );
2177 /* copy */
2178 if (stat( full_name1.long_name, &fstat ))
2180 WARN("Invalid source file %s\n",
2181 full_name1.long_name);
2182 FILE_SetDosError();
2183 return FALSE;
2185 if (S_ISDIR(fstat.st_mode)) {
2186 /* No Move for directories across file systems */
2187 /* FIXME: Use right error code */
2188 SetLastError( ERROR_GEN_FAILURE );
2189 return FALSE;
2191 return CopyFileA(fn1, fn2, TRUE); /*fail, if exist */
2195 /**************************************************************************
2196 * MoveFileW (KERNEL32.@)
2198 BOOL WINAPI MoveFileW( LPCWSTR fn1, LPCWSTR fn2 )
2200 LPSTR afn1 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn1 );
2201 LPSTR afn2 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn2 );
2202 BOOL res = MoveFileA( afn1, afn2 );
2203 HeapFree( GetProcessHeap(), 0, afn1 );
2204 HeapFree( GetProcessHeap(), 0, afn2 );
2205 return res;
2209 /**************************************************************************
2210 * CopyFileA (KERNEL32.@)
2212 BOOL WINAPI CopyFileA( LPCSTR source, LPCSTR dest, BOOL fail_if_exists )
2214 HFILE h1, h2;
2215 BY_HANDLE_FILE_INFORMATION info;
2216 UINT count;
2217 BOOL ret = FALSE;
2218 int mode;
2219 char buffer[2048];
2221 if ((h1 = _lopen( source, OF_READ )) == HFILE_ERROR) return FALSE;
2222 if (!GetFileInformationByHandle( h1, &info ))
2224 CloseHandle( h1 );
2225 return FALSE;
2227 mode = (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY) ? 0444 : 0666;
2228 if ((h2 = CreateFileA( dest, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
2229 fail_if_exists ? CREATE_NEW : CREATE_ALWAYS,
2230 info.dwFileAttributes, h1 )) == INVALID_HANDLE_VALUE)
2232 CloseHandle( h1 );
2233 return FALSE;
2235 while ((count = _lread( h1, buffer, sizeof(buffer) )) > 0)
2237 char *p = buffer;
2238 while (count > 0)
2240 INT res = _lwrite( h2, p, count );
2241 if (res <= 0) goto done;
2242 p += res;
2243 count -= res;
2246 ret = TRUE;
2247 done:
2248 CloseHandle( h1 );
2249 CloseHandle( h2 );
2250 return ret;
2254 /**************************************************************************
2255 * CopyFileW (KERNEL32.@)
2257 BOOL WINAPI CopyFileW( LPCWSTR source, LPCWSTR dest, BOOL fail_if_exists)
2259 LPSTR sourceA = HEAP_strdupWtoA( GetProcessHeap(), 0, source );
2260 LPSTR destA = HEAP_strdupWtoA( GetProcessHeap(), 0, dest );
2261 BOOL ret = CopyFileA( sourceA, destA, fail_if_exists );
2262 HeapFree( GetProcessHeap(), 0, sourceA );
2263 HeapFree( GetProcessHeap(), 0, destA );
2264 return ret;
2268 /**************************************************************************
2269 * CopyFileExA (KERNEL32.@)
2271 * This implementation ignores most of the extra parameters passed-in into
2272 * the "ex" version of the method and calls the CopyFile method.
2273 * It will have to be fixed eventually.
2275 BOOL WINAPI CopyFileExA(LPCSTR sourceFilename,
2276 LPCSTR destFilename,
2277 LPPROGRESS_ROUTINE progressRoutine,
2278 LPVOID appData,
2279 LPBOOL cancelFlagPointer,
2280 DWORD copyFlags)
2282 BOOL failIfExists = FALSE;
2285 * Interpret the only flag that CopyFile can interpret.
2287 if ( (copyFlags & COPY_FILE_FAIL_IF_EXISTS) != 0)
2289 failIfExists = TRUE;
2292 return CopyFileA(sourceFilename, destFilename, failIfExists);
2295 /**************************************************************************
2296 * CopyFileExW (KERNEL32.@)
2298 BOOL WINAPI CopyFileExW(LPCWSTR sourceFilename,
2299 LPCWSTR destFilename,
2300 LPPROGRESS_ROUTINE progressRoutine,
2301 LPVOID appData,
2302 LPBOOL cancelFlagPointer,
2303 DWORD copyFlags)
2305 LPSTR sourceA = HEAP_strdupWtoA( GetProcessHeap(), 0, sourceFilename );
2306 LPSTR destA = HEAP_strdupWtoA( GetProcessHeap(), 0, destFilename );
2308 BOOL ret = CopyFileExA(sourceA,
2309 destA,
2310 progressRoutine,
2311 appData,
2312 cancelFlagPointer,
2313 copyFlags);
2315 HeapFree( GetProcessHeap(), 0, sourceA );
2316 HeapFree( GetProcessHeap(), 0, destA );
2318 return ret;
2322 /***********************************************************************
2323 * SetFileTime (KERNEL32.@)
2325 BOOL WINAPI SetFileTime( HANDLE hFile,
2326 const FILETIME *lpCreationTime,
2327 const FILETIME *lpLastAccessTime,
2328 const FILETIME *lpLastWriteTime )
2330 BOOL ret;
2331 SERVER_START_REQ( set_file_time )
2333 req->handle = hFile;
2334 if (lpLastAccessTime)
2335 RtlTimeToSecondsSince1970( lpLastAccessTime, (DWORD *)&req->access_time );
2336 else
2337 req->access_time = 0; /* FIXME */
2338 if (lpLastWriteTime)
2339 RtlTimeToSecondsSince1970( lpLastWriteTime, (DWORD *)&req->write_time );
2340 else
2341 req->write_time = 0; /* FIXME */
2342 ret = !wine_server_call_err( req );
2344 SERVER_END_REQ;
2345 return ret;
2349 /**************************************************************************
2350 * LockFile (KERNEL32.@)
2352 BOOL WINAPI LockFile( HANDLE hFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh,
2353 DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh )
2355 BOOL ret;
2356 SERVER_START_REQ( lock_file )
2358 req->handle = hFile;
2359 req->offset_low = dwFileOffsetLow;
2360 req->offset_high = dwFileOffsetHigh;
2361 req->count_low = nNumberOfBytesToLockLow;
2362 req->count_high = nNumberOfBytesToLockHigh;
2363 ret = !wine_server_call_err( req );
2365 SERVER_END_REQ;
2366 return ret;
2369 /**************************************************************************
2370 * LockFileEx [KERNEL32.@]
2372 * Locks a byte range within an open file for shared or exclusive access.
2374 * RETURNS
2375 * success: TRUE
2376 * failure: FALSE
2378 * NOTES
2379 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
2381 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
2382 DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh,
2383 LPOVERLAPPED pOverlapped )
2385 FIXME("hFile=%d,flags=%ld,reserved=%ld,lowbytes=%ld,highbytes=%ld,overlapped=%p: stub.\n",
2386 hFile, flags, reserved, nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh,
2387 pOverlapped);
2388 if (reserved == 0)
2389 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2390 else
2392 ERR("reserved == %ld: Supposed to be 0??\n", reserved);
2393 SetLastError(ERROR_INVALID_PARAMETER);
2396 return FALSE;
2400 /**************************************************************************
2401 * UnlockFile (KERNEL32.@)
2403 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh,
2404 DWORD nNumberOfBytesToUnlockLow, DWORD nNumberOfBytesToUnlockHigh )
2406 BOOL ret;
2407 SERVER_START_REQ( unlock_file )
2409 req->handle = hFile;
2410 req->offset_low = dwFileOffsetLow;
2411 req->offset_high = dwFileOffsetHigh;
2412 req->count_low = nNumberOfBytesToUnlockLow;
2413 req->count_high = nNumberOfBytesToUnlockHigh;
2414 ret = !wine_server_call_err( req );
2416 SERVER_END_REQ;
2417 return ret;
2421 /**************************************************************************
2422 * UnlockFileEx (KERNEL32.@)
2424 BOOL WINAPI UnlockFileEx(
2425 HFILE hFile,
2426 DWORD dwReserved,
2427 DWORD nNumberOfBytesToUnlockLow,
2428 DWORD nNumberOfBytesToUnlockHigh,
2429 LPOVERLAPPED lpOverlapped
2432 FIXME("hFile=%d,reserved=%ld,lowbytes=%ld,highbytes=%ld,overlapped=%p: stub.\n",
2433 hFile, dwReserved, nNumberOfBytesToUnlockLow, nNumberOfBytesToUnlockHigh,
2434 lpOverlapped);
2435 if (dwReserved == 0)
2436 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2437 else
2439 ERR("reserved == %ld: Supposed to be 0??\n", dwReserved);
2440 SetLastError(ERROR_INVALID_PARAMETER);
2443 return FALSE;
2447 #if 0
2449 struct DOS_FILE_LOCK {
2450 struct DOS_FILE_LOCK * next;
2451 DWORD base;
2452 DWORD len;
2453 DWORD processId;
2454 FILE_OBJECT * dos_file;
2455 /* char * unix_name;*/
2458 typedef struct DOS_FILE_LOCK DOS_FILE_LOCK;
2460 static DOS_FILE_LOCK *locks = NULL;
2461 static void DOS_RemoveFileLocks(FILE_OBJECT *file);
2464 /* Locks need to be mirrored because unix file locking is based
2465 * on the pid. Inside of wine there can be multiple WINE processes
2466 * that share the same unix pid.
2467 * Read's and writes should check these locks also - not sure
2468 * how critical that is at this point (FIXME).
2471 static BOOL DOS_AddLock(FILE_OBJECT *file, struct flock *f)
2473 DOS_FILE_LOCK *curr;
2474 DWORD processId;
2476 processId = GetCurrentProcessId();
2478 /* check if lock overlaps a current lock for the same file */
2479 #if 0
2480 for (curr = locks; curr; curr = curr->next) {
2481 if (strcmp(curr->unix_name, file->unix_name) == 0) {
2482 if ((f->l_start == curr->base) && (f->l_len == curr->len))
2483 return TRUE;/* region is identic */
2484 if ((f->l_start < (curr->base + curr->len)) &&
2485 ((f->l_start + f->l_len) > curr->base)) {
2486 /* region overlaps */
2487 return FALSE;
2491 #endif
2493 curr = HeapAlloc( GetProcessHeap(), 0, sizeof(DOS_FILE_LOCK) );
2494 curr->processId = GetCurrentProcessId();
2495 curr->base = f->l_start;
2496 curr->len = f->l_len;
2497 /* curr->unix_name = HEAP_strdupA( GetProcessHeap(), 0, file->unix_name);*/
2498 curr->next = locks;
2499 curr->dos_file = file;
2500 locks = curr;
2501 return TRUE;
2504 static void DOS_RemoveFileLocks(FILE_OBJECT *file)
2506 DWORD processId;
2507 DOS_FILE_LOCK **curr;
2508 DOS_FILE_LOCK *rem;
2510 processId = GetCurrentProcessId();
2511 curr = &locks;
2512 while (*curr) {
2513 if ((*curr)->dos_file == file) {
2514 rem = *curr;
2515 *curr = (*curr)->next;
2516 /* HeapFree( GetProcessHeap(), 0, rem->unix_name );*/
2517 HeapFree( GetProcessHeap(), 0, rem );
2519 else
2520 curr = &(*curr)->next;
2524 static BOOL DOS_RemoveLock(FILE_OBJECT *file, struct flock *f)
2526 DWORD processId;
2527 DOS_FILE_LOCK **curr;
2528 DOS_FILE_LOCK *rem;
2530 processId = GetCurrentProcessId();
2531 for (curr = &locks; *curr; curr = &(*curr)->next) {
2532 if ((*curr)->processId == processId &&
2533 (*curr)->dos_file == file &&
2534 (*curr)->base == f->l_start &&
2535 (*curr)->len == f->l_len) {
2536 /* this is the same lock */
2537 rem = *curr;
2538 *curr = (*curr)->next;
2539 /* HeapFree( GetProcessHeap(), 0, rem->unix_name );*/
2540 HeapFree( GetProcessHeap(), 0, rem );
2541 return TRUE;
2544 /* no matching lock found */
2545 return FALSE;
2549 /**************************************************************************
2550 * LockFile (KERNEL32.@)
2552 BOOL WINAPI LockFile(
2553 HFILE hFile,DWORD dwFileOffsetLow,DWORD dwFileOffsetHigh,
2554 DWORD nNumberOfBytesToLockLow,DWORD nNumberOfBytesToLockHigh )
2556 struct flock f;
2557 FILE_OBJECT *file;
2559 TRACE("handle %d offsetlow=%ld offsethigh=%ld nbyteslow=%ld nbyteshigh=%ld\n",
2560 hFile, dwFileOffsetLow, dwFileOffsetHigh,
2561 nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh);
2563 if (dwFileOffsetHigh || nNumberOfBytesToLockHigh) {
2564 FIXME("Unimplemented bytes > 32bits\n");
2565 return FALSE;
2568 f.l_start = dwFileOffsetLow;
2569 f.l_len = nNumberOfBytesToLockLow;
2570 f.l_whence = SEEK_SET;
2571 f.l_pid = 0;
2572 f.l_type = F_WRLCK;
2574 if (!(file = FILE_GetFile(hFile,0,NULL))) return FALSE;
2576 /* shadow locks internally */
2577 if (!DOS_AddLock(file, &f)) {
2578 SetLastError( ERROR_LOCK_VIOLATION );
2579 return FALSE;
2582 /* FIXME: Unix locking commented out for now, doesn't work with Excel */
2583 #ifdef USE_UNIX_LOCKS
2584 if (fcntl(file->unix_handle, F_SETLK, &f) == -1) {
2585 if (errno == EACCES || errno == EAGAIN) {
2586 SetLastError( ERROR_LOCK_VIOLATION );
2588 else {
2589 FILE_SetDosError();
2591 /* remove our internal copy of the lock */
2592 DOS_RemoveLock(file, &f);
2593 return FALSE;
2595 #endif
2596 return TRUE;
2600 /**************************************************************************
2601 * UnlockFile (KERNEL32.@)
2603 BOOL WINAPI UnlockFile(
2604 HFILE hFile,DWORD dwFileOffsetLow,DWORD dwFileOffsetHigh,
2605 DWORD nNumberOfBytesToUnlockLow,DWORD nNumberOfBytesToUnlockHigh )
2607 FILE_OBJECT *file;
2608 struct flock f;
2610 TRACE("handle %d offsetlow=%ld offsethigh=%ld nbyteslow=%ld nbyteshigh=%ld\n",
2611 hFile, dwFileOffsetLow, dwFileOffsetHigh,
2612 nNumberOfBytesToUnlockLow, nNumberOfBytesToUnlockHigh);
2614 if (dwFileOffsetHigh || nNumberOfBytesToUnlockHigh) {
2615 WARN("Unimplemented bytes > 32bits\n");
2616 return FALSE;
2619 f.l_start = dwFileOffsetLow;
2620 f.l_len = nNumberOfBytesToUnlockLow;
2621 f.l_whence = SEEK_SET;
2622 f.l_pid = 0;
2623 f.l_type = F_UNLCK;
2625 if (!(file = FILE_GetFile(hFile,0,NULL))) return FALSE;
2627 DOS_RemoveLock(file, &f); /* ok if fails - may be another wine */
2629 /* FIXME: Unix locking commented out for now, doesn't work with Excel */
2630 #ifdef USE_UNIX_LOCKS
2631 if (fcntl(file->unix_handle, F_SETLK, &f) == -1) {
2632 FILE_SetDosError();
2633 return FALSE;
2635 #endif
2636 return TRUE;
2638 #endif
2640 /**************************************************************************
2641 * GetFileAttributesExA [KERNEL32.@]
2643 BOOL WINAPI GetFileAttributesExA(
2644 LPCSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId,
2645 LPVOID lpFileInformation)
2647 DOS_FULL_NAME full_name;
2648 BY_HANDLE_FILE_INFORMATION info;
2650 if (lpFileName == NULL) return FALSE;
2651 if (lpFileInformation == NULL) return FALSE;
2653 if (fInfoLevelId == GetFileExInfoStandard) {
2654 LPWIN32_FILE_ATTRIBUTE_DATA lpFad =
2655 (LPWIN32_FILE_ATTRIBUTE_DATA) lpFileInformation;
2656 if (!DOSFS_GetFullName( lpFileName, TRUE, &full_name )) return FALSE;
2657 if (!FILE_Stat( full_name.long_name, &info )) return FALSE;
2659 lpFad->dwFileAttributes = info.dwFileAttributes;
2660 lpFad->ftCreationTime = info.ftCreationTime;
2661 lpFad->ftLastAccessTime = info.ftLastAccessTime;
2662 lpFad->ftLastWriteTime = info.ftLastWriteTime;
2663 lpFad->nFileSizeHigh = info.nFileSizeHigh;
2664 lpFad->nFileSizeLow = info.nFileSizeLow;
2666 else {
2667 FIXME("invalid info level %d!\n", fInfoLevelId);
2668 return FALSE;
2671 return TRUE;
2675 /**************************************************************************
2676 * GetFileAttributesExW [KERNEL32.@]
2678 BOOL WINAPI GetFileAttributesExW(
2679 LPCWSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId,
2680 LPVOID lpFileInformation)
2682 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, lpFileName );
2683 BOOL res =
2684 GetFileAttributesExA( nameA, fInfoLevelId, lpFileInformation);
2685 HeapFree( GetProcessHeap(), 0, nameA );
2686 return res;