Removed some direct accesses to the 16-bit task structure.
[wine.git] / files / file.c
blob84c00014e2cf0554ade565c5080c8da2606a9fc0
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"
14 #include <assert.h>
15 #include <ctype.h>
16 #include <errno.h>
17 #include <fcntl.h>
18 #include <stdlib.h>
19 #include <stdio.h>
20 #include <string.h>
21 #ifdef HAVE_SYS_ERRNO_H
22 #include <sys/errno.h>
23 #endif
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #ifdef HAVE_SYS_MMAN_H
27 #include <sys/mman.h>
28 #endif
29 #include <sys/time.h>
30 #include <time.h>
31 #include <unistd.h>
32 #include <utime.h>
34 #include "winerror.h"
35 #include "windef.h"
36 #include "winbase.h"
37 #include "wine/winbase16.h"
38 #include "wine/port.h"
39 #include "drive.h"
40 #include "file.h"
41 #include "heap.h"
42 #include "msdos.h"
43 #include "wincon.h"
44 #include "debugtools.h"
46 #include "server.h"
48 DEFAULT_DEBUG_CHANNEL(file);
50 #if defined(MAP_ANONYMOUS) && !defined(MAP_ANON)
51 #define MAP_ANON MAP_ANONYMOUS
52 #endif
54 /* Size of per-process table of DOS handles */
55 #define DOS_TABLE_SIZE 256
57 static HANDLE dos_handles[DOS_TABLE_SIZE];
60 /***********************************************************************
61 * FILE_ConvertOFMode
63 * Convert OF_* mode into flags for CreateFile.
65 static void FILE_ConvertOFMode( INT mode, DWORD *access, DWORD *sharing )
67 switch(mode & 0x03)
69 case OF_READ: *access = GENERIC_READ; break;
70 case OF_WRITE: *access = GENERIC_WRITE; break;
71 case OF_READWRITE: *access = GENERIC_READ | GENERIC_WRITE; break;
72 default: *access = 0; break;
74 switch(mode & 0x70)
76 case OF_SHARE_EXCLUSIVE: *sharing = 0; break;
77 case OF_SHARE_DENY_WRITE: *sharing = FILE_SHARE_READ; break;
78 case OF_SHARE_DENY_READ: *sharing = FILE_SHARE_WRITE; break;
79 case OF_SHARE_DENY_NONE:
80 case OF_SHARE_COMPAT:
81 default: *sharing = FILE_SHARE_READ | FILE_SHARE_WRITE; break;
86 /***********************************************************************
87 * FILE_strcasecmp
89 * locale-independent case conversion for file I/O
91 int FILE_strcasecmp( const char *str1, const char *str2 )
93 for (;;)
95 int ret = FILE_toupper(*str1) - FILE_toupper(*str2);
96 if (ret || !*str1) return ret;
97 str1++;
98 str2++;
103 /***********************************************************************
104 * FILE_strncasecmp
106 * locale-independent case conversion for file I/O
108 int FILE_strncasecmp( const char *str1, const char *str2, int len )
110 int ret = 0;
111 for ( ; len > 0; len--, str1++, str2++)
112 if ((ret = FILE_toupper(*str1) - FILE_toupper(*str2)) || !*str1) break;
113 return ret;
117 /***********************************************************************
118 * FILE_SetDosError
120 * Set the DOS error code from errno.
122 void FILE_SetDosError(void)
124 int save_errno = errno; /* errno gets overwritten by printf */
126 TRACE("errno = %d %s\n", errno, strerror(errno));
127 switch (save_errno)
129 case EAGAIN:
130 SetLastError( ERROR_SHARING_VIOLATION );
131 break;
132 case EBADF:
133 SetLastError( ERROR_INVALID_HANDLE );
134 break;
135 case ENOSPC:
136 SetLastError( ERROR_HANDLE_DISK_FULL );
137 break;
138 case EACCES:
139 case EPERM:
140 case EROFS:
141 SetLastError( ERROR_ACCESS_DENIED );
142 break;
143 case EBUSY:
144 SetLastError( ERROR_LOCK_VIOLATION );
145 break;
146 case ENOENT:
147 SetLastError( ERROR_FILE_NOT_FOUND );
148 break;
149 case EISDIR:
150 SetLastError( ERROR_CANNOT_MAKE );
151 break;
152 case ENFILE:
153 case EMFILE:
154 SetLastError( ERROR_NO_MORE_FILES );
155 break;
156 case EEXIST:
157 SetLastError( ERROR_FILE_EXISTS );
158 break;
159 case EINVAL:
160 case ESPIPE:
161 SetLastError( ERROR_SEEK );
162 break;
163 case ENOTEMPTY:
164 SetLastError( ERROR_DIR_NOT_EMPTY );
165 break;
166 case ENOEXEC:
167 SetLastError( ERROR_BAD_FORMAT );
168 break;
169 default:
170 WARN( "unknown file error: %s", strerror(save_errno) );
171 SetLastError( ERROR_GEN_FAILURE );
172 break;
174 errno = save_errno;
178 /***********************************************************************
179 * FILE_DupUnixHandle
181 * Duplicate a Unix handle into a task handle.
182 * Returns 0 on failure.
184 HANDLE FILE_DupUnixHandle( int fd, DWORD access )
186 HANDLE ret;
187 SERVER_START_REQ
189 struct alloc_file_handle_request *req = server_alloc_req( sizeof(*req), 0 );
190 req->access = access;
191 server_call_fd( REQ_ALLOC_FILE_HANDLE, fd );
192 ret = req->handle;
194 SERVER_END_REQ;
195 return ret;
199 /***********************************************************************
200 * FILE_GetUnixHandle
202 * Retrieve the Unix handle corresponding to a file handle.
203 * Returns -1 on failure.
205 int FILE_GetUnixHandle( HANDLE handle, DWORD access )
207 int ret, fd = -1;
208 SERVER_START_REQ
210 struct get_handle_fd_request *req = wine_server_alloc_req( sizeof(*req), 0 );
211 req->handle = handle;
212 req->access = access;
213 if (!(ret = server_call( REQ_GET_HANDLE_FD ))) fd = req->fd;
215 SERVER_END_REQ;
216 if (!ret)
218 if (fd == -1) return wine_server_recv_fd( handle, 1 );
219 fd = dup(fd);
221 return fd;
225 /*************************************************************************
226 * FILE_OpenConsole
228 * Open a handle to the current process console.
229 * Returns 0 on failure.
231 static HANDLE FILE_OpenConsole( BOOL output, DWORD access, LPSECURITY_ATTRIBUTES sa )
233 HANDLE ret;
235 SERVER_START_REQ
237 struct open_console_request *req = server_alloc_req( sizeof(*req), 0 );
239 req->output = output;
240 req->access = access;
241 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
242 SetLastError(0);
243 server_call( REQ_OPEN_CONSOLE );
244 ret = req->handle;
246 SERVER_END_REQ;
247 return ret;
251 /***********************************************************************
252 * FILE_CreateFile
254 * Implementation of CreateFile. Takes a Unix path name.
255 * Returns 0 on failure.
257 HANDLE FILE_CreateFile( LPCSTR filename, DWORD access, DWORD sharing,
258 LPSECURITY_ATTRIBUTES sa, DWORD creation,
259 DWORD attributes, HANDLE template, BOOL fail_read_only )
261 DWORD err;
262 HANDLE ret;
263 size_t len = strlen(filename);
265 if (len > REQUEST_MAX_VAR_SIZE)
267 FIXME("filename '%s' too long\n", filename );
268 SetLastError( ERROR_INVALID_PARAMETER );
269 return 0;
272 restart:
273 SERVER_START_REQ
275 struct create_file_request *req = server_alloc_req( sizeof(*req), len );
276 req->access = access;
277 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
278 req->sharing = sharing;
279 req->create = creation;
280 req->attrs = attributes;
281 memcpy( server_data_ptr(req), filename, len );
282 SetLastError(0);
283 err = server_call( REQ_CREATE_FILE );
284 ret = req->handle;
286 SERVER_END_REQ;
288 /* If write access failed, retry without GENERIC_WRITE */
290 if (!ret && !fail_read_only && (access & GENERIC_WRITE))
292 if ((err == STATUS_MEDIA_WRITE_PROTECTED) || (err == STATUS_ACCESS_DENIED))
294 TRACE("Write access failed for file '%s', trying without "
295 "write access\n", filename);
296 access &= ~GENERIC_WRITE;
297 goto restart;
301 if (!ret)
302 WARN("Unable to create file '%s' (GLE %ld)\n", filename,
303 GetLastError());
305 return ret;
309 /***********************************************************************
310 * FILE_CreateDevice
312 * Same as FILE_CreateFile but for a device
313 * Returns 0 on failure.
315 HANDLE FILE_CreateDevice( int client_id, DWORD access, LPSECURITY_ATTRIBUTES sa )
317 HANDLE ret;
318 SERVER_START_REQ
320 struct create_device_request *req = server_alloc_req( sizeof(*req), 0 );
322 req->access = access;
323 req->inherit = (sa && (sa->nLength>=sizeof(*sa)) && sa->bInheritHandle);
324 req->id = client_id;
325 SetLastError(0);
326 server_call( REQ_CREATE_DEVICE );
327 ret = req->handle;
329 SERVER_END_REQ;
330 return ret;
334 /*************************************************************************
335 * CreateFileA [KERNEL32.45] Creates or opens a file or other object
337 * Creates or opens an object, and returns a handle that can be used to
338 * access that object.
340 * PARAMS
342 * filename [I] pointer to filename to be accessed
343 * access [I] access mode requested
344 * sharing [I] share mode
345 * sa [I] pointer to security attributes
346 * creation [I] how to create the file
347 * attributes [I] attributes for newly created file
348 * template [I] handle to file with extended attributes to copy
350 * RETURNS
351 * Success: Open handle to specified file
352 * Failure: INVALID_HANDLE_VALUE
354 * NOTES
355 * Should call SetLastError() on failure.
357 * BUGS
359 * Doesn't support character devices, pipes, template files, or a
360 * lot of the 'attributes' flags yet.
362 HANDLE WINAPI CreateFileA( LPCSTR filename, DWORD access, DWORD sharing,
363 LPSECURITY_ATTRIBUTES sa, DWORD creation,
364 DWORD attributes, HANDLE template )
366 DOS_FULL_NAME full_name;
367 HANDLE ret;
369 if (!filename)
371 SetLastError( ERROR_INVALID_PARAMETER );
372 return INVALID_HANDLE_VALUE;
374 TRACE("%s %s%s%s%s%s%s%s\n",filename,
375 ((access & GENERIC_READ)==GENERIC_READ)?"GENERIC_READ ":"",
376 ((access & GENERIC_WRITE)==GENERIC_WRITE)?"GENERIC_WRITE ":"",
377 (!access)?"QUERY_ACCESS ":"",
378 ((sharing & FILE_SHARE_READ)==FILE_SHARE_READ)?"FILE_SHARE_READ ":"",
379 ((sharing & FILE_SHARE_WRITE)==FILE_SHARE_WRITE)?"FILE_SHARE_WRITE ":"",
380 ((sharing & FILE_SHARE_DELETE)==FILE_SHARE_DELETE)?"FILE_SHARE_DELETE ":"",
381 (creation ==CREATE_NEW)?"CREATE_NEW":
382 (creation ==CREATE_ALWAYS)?"CREATE_ALWAYS ":
383 (creation ==OPEN_EXISTING)?"OPEN_EXISTING ":
384 (creation ==OPEN_ALWAYS)?"OPEN_ALWAYS ":
385 (creation ==TRUNCATE_EXISTING)?"TRUNCATE_EXISTING ":"");
387 /* If the name starts with '\\?\', ignore the first 4 chars. */
388 if (!strncmp(filename, "\\\\?\\", 4))
390 filename += 4;
391 if (!strncmp(filename, "UNC\\", 4))
393 FIXME("UNC name (%s) not supported.\n", filename );
394 SetLastError( ERROR_PATH_NOT_FOUND );
395 return INVALID_HANDLE_VALUE;
399 if (!strncmp(filename, "\\\\.\\", 4)) {
400 if (!DOSFS_GetDevice( filename ))
402 ret = DEVICE_Open( filename+4, access, sa );
403 goto done;
405 else
406 filename+=4; /* fall into DOSFS_Device case below */
409 /* If the name still starts with '\\', it's a UNC name. */
410 if (!strncmp(filename, "\\\\", 2))
412 FIXME("UNC name (%s) not supported.\n", filename );
413 SetLastError( ERROR_PATH_NOT_FOUND );
414 return INVALID_HANDLE_VALUE;
417 /* If the name contains a DOS wild card (* or ?), do no create a file */
418 if(strchr(filename,'*') || strchr(filename,'?'))
419 return INVALID_HANDLE_VALUE;
421 /* Open a console for CONIN$ or CONOUT$ */
422 if (!strcasecmp(filename, "CONIN$"))
424 ret = FILE_OpenConsole( FALSE, access, sa );
425 goto done;
427 if (!strcasecmp(filename, "CONOUT$"))
429 ret = FILE_OpenConsole( TRUE, access, sa );
430 goto done;
433 if (DOSFS_GetDevice( filename ))
435 TRACE("opening device '%s'\n", filename );
437 if (!(ret = DOSFS_OpenDevice( filename, access )))
439 /* Do not silence this please. It is a critical error. -MM */
440 ERR("Couldn't open device '%s'!\n",filename);
441 SetLastError( ERROR_FILE_NOT_FOUND );
443 goto done;
446 /* check for filename, don't check for last entry if creating */
447 if (!DOSFS_GetFullName( filename,
448 (creation == OPEN_EXISTING) ||
449 (creation == TRUNCATE_EXISTING),
450 &full_name )) {
451 WARN("Unable to get full filename from '%s' (GLE %ld)\n",
452 filename, GetLastError());
453 return INVALID_HANDLE_VALUE;
456 ret = FILE_CreateFile( full_name.long_name, access, sharing,
457 sa, creation, attributes, template,
458 DRIVE_GetFlags(full_name.drive) & DRIVE_FAIL_READ_ONLY );
459 done:
460 if (!ret) ret = INVALID_HANDLE_VALUE;
461 return ret;
466 /*************************************************************************
467 * CreateFileW (KERNEL32.48)
469 HANDLE WINAPI CreateFileW( LPCWSTR filename, DWORD access, DWORD sharing,
470 LPSECURITY_ATTRIBUTES sa, DWORD creation,
471 DWORD attributes, HANDLE template)
473 LPSTR afn = HEAP_strdupWtoA( GetProcessHeap(), 0, filename );
474 HANDLE res = CreateFileA( afn, access, sharing, sa, creation, attributes, template );
475 HeapFree( GetProcessHeap(), 0, afn );
476 return res;
480 /***********************************************************************
481 * FILE_FillInfo
483 * Fill a file information from a struct stat.
485 static void FILE_FillInfo( struct stat *st, BY_HANDLE_FILE_INFORMATION *info )
487 if (S_ISDIR(st->st_mode))
488 info->dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
489 else
490 info->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
491 if (!(st->st_mode & S_IWUSR))
492 info->dwFileAttributes |= FILE_ATTRIBUTE_READONLY;
494 RtlSecondsSince1970ToTime( st->st_mtime, &info->ftCreationTime );
495 RtlSecondsSince1970ToTime( st->st_mtime, &info->ftLastWriteTime );
496 RtlSecondsSince1970ToTime( st->st_atime, &info->ftLastAccessTime );
498 info->dwVolumeSerialNumber = 0; /* FIXME */
499 info->nFileSizeHigh = 0;
500 info->nFileSizeLow = S_ISDIR(st->st_mode) ? 0 : st->st_size;
501 info->nNumberOfLinks = st->st_nlink;
502 info->nFileIndexHigh = 0;
503 info->nFileIndexLow = st->st_ino;
507 /***********************************************************************
508 * FILE_Stat
510 * Stat a Unix path name. Return TRUE if OK.
512 BOOL FILE_Stat( LPCSTR unixName, BY_HANDLE_FILE_INFORMATION *info )
514 struct stat st;
516 if (lstat( unixName, &st ) == -1)
518 FILE_SetDosError();
519 return FALSE;
521 if (!S_ISLNK(st.st_mode)) FILE_FillInfo( &st, info );
522 else
524 /* do a "real" stat to find out
525 about the type of the symlink destination */
526 if (stat( unixName, &st ) == -1)
528 FILE_SetDosError();
529 return FALSE;
531 FILE_FillInfo( &st, info );
532 info->dwFileAttributes |= FILE_ATTRIBUTE_SYMLINK;
534 return TRUE;
538 /***********************************************************************
539 * GetFileInformationByHandle (KERNEL32.219)
541 DWORD WINAPI GetFileInformationByHandle( HANDLE hFile,
542 BY_HANDLE_FILE_INFORMATION *info )
544 DWORD ret;
545 if (!info) return 0;
547 SERVER_START_REQ
549 struct get_file_info_request *req = server_alloc_req( sizeof(*req), 0 );
550 req->handle = hFile;
551 if ((ret = !server_call( REQ_GET_FILE_INFO )))
553 RtlSecondsSince1970ToTime( req->write_time, &info->ftCreationTime );
554 RtlSecondsSince1970ToTime( req->write_time, &info->ftLastWriteTime );
555 RtlSecondsSince1970ToTime( req->access_time, &info->ftLastAccessTime );
556 info->dwFileAttributes = req->attr;
557 info->dwVolumeSerialNumber = req->serial;
558 info->nFileSizeHigh = req->size_high;
559 info->nFileSizeLow = req->size_low;
560 info->nNumberOfLinks = req->links;
561 info->nFileIndexHigh = req->index_high;
562 info->nFileIndexLow = req->index_low;
565 SERVER_END_REQ;
566 return ret;
570 /**************************************************************************
571 * GetFileAttributes16 (KERNEL.420)
573 DWORD WINAPI GetFileAttributes16( LPCSTR name )
575 return GetFileAttributesA( name );
579 /**************************************************************************
580 * GetFileAttributesA (KERNEL32.217)
582 DWORD WINAPI GetFileAttributesA( LPCSTR name )
584 DOS_FULL_NAME full_name;
585 BY_HANDLE_FILE_INFORMATION info;
587 if (name == NULL || *name=='\0') return -1;
589 if (!DOSFS_GetFullName( name, TRUE, &full_name )) return -1;
590 if (!FILE_Stat( full_name.long_name, &info )) return -1;
591 return info.dwFileAttributes;
595 /**************************************************************************
596 * GetFileAttributesW (KERNEL32.218)
598 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
600 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
601 DWORD res = GetFileAttributesA( nameA );
602 HeapFree( GetProcessHeap(), 0, nameA );
603 return res;
607 /***********************************************************************
608 * GetFileSize (KERNEL32.220)
610 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
612 BY_HANDLE_FILE_INFORMATION info;
613 if (!GetFileInformationByHandle( hFile, &info )) return 0;
614 if (filesizehigh) *filesizehigh = info.nFileSizeHigh;
615 return info.nFileSizeLow;
619 /***********************************************************************
620 * GetFileTime (KERNEL32.221)
622 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
623 FILETIME *lpLastAccessTime,
624 FILETIME *lpLastWriteTime )
626 BY_HANDLE_FILE_INFORMATION info;
627 if (!GetFileInformationByHandle( hFile, &info )) return FALSE;
628 if (lpCreationTime) *lpCreationTime = info.ftCreationTime;
629 if (lpLastAccessTime) *lpLastAccessTime = info.ftLastAccessTime;
630 if (lpLastWriteTime) *lpLastWriteTime = info.ftLastWriteTime;
631 return TRUE;
634 /***********************************************************************
635 * CompareFileTime (KERNEL32.28)
637 INT WINAPI CompareFileTime( LPFILETIME x, LPFILETIME y )
639 if (!x || !y) return -1;
641 if (x->dwHighDateTime > y->dwHighDateTime)
642 return 1;
643 if (x->dwHighDateTime < y->dwHighDateTime)
644 return -1;
645 if (x->dwLowDateTime > y->dwLowDateTime)
646 return 1;
647 if (x->dwLowDateTime < y->dwLowDateTime)
648 return -1;
649 return 0;
652 /***********************************************************************
653 * FILE_GetTempFileName : utility for GetTempFileName
655 static UINT FILE_GetTempFileName( LPCSTR path, LPCSTR prefix, UINT unique,
656 LPSTR buffer, BOOL isWin16 )
658 static UINT unique_temp;
659 DOS_FULL_NAME full_name;
660 int i;
661 LPSTR p;
662 UINT num;
664 if ( !path || !prefix || !buffer ) return 0;
666 if (!unique_temp) unique_temp = time(NULL) & 0xffff;
667 num = unique ? (unique & 0xffff) : (unique_temp++ & 0xffff);
669 strcpy( buffer, path );
670 p = buffer + strlen(buffer);
672 /* add a \, if there isn't one and path is more than just the drive letter ... */
673 if ( !((strlen(buffer) == 2) && (buffer[1] == ':'))
674 && ((p == buffer) || (p[-1] != '\\'))) *p++ = '\\';
676 if (isWin16) *p++ = '~';
677 for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
678 sprintf( p, "%04x.tmp", num );
680 /* Now try to create it */
682 if (!unique)
686 HFILE handle = CreateFileA( buffer, GENERIC_WRITE, 0, NULL,
687 CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
688 if (handle != INVALID_HANDLE_VALUE)
689 { /* We created it */
690 TRACE("created %s\n",
691 buffer);
692 CloseHandle( handle );
693 break;
695 if (GetLastError() != ERROR_FILE_EXISTS)
696 break; /* No need to go on */
697 num++;
698 sprintf( p, "%04x.tmp", num );
699 } while (num != (unique & 0xffff));
702 /* Get the full path name */
704 if (DOSFS_GetFullName( buffer, FALSE, &full_name ))
706 /* Check if we have write access in the directory */
707 if ((p = strrchr( full_name.long_name, '/' ))) *p = '\0';
708 if (access( full_name.long_name, W_OK ) == -1)
709 WARN("returns '%s', which doesn't seem to be writeable.\n",
710 buffer);
712 TRACE("returning %s\n", buffer );
713 return unique ? unique : num;
717 /***********************************************************************
718 * GetTempFileNameA (KERNEL32.290)
720 UINT WINAPI GetTempFileNameA( LPCSTR path, LPCSTR prefix, UINT unique,
721 LPSTR buffer)
723 return FILE_GetTempFileName(path, prefix, unique, buffer, FALSE);
726 /***********************************************************************
727 * GetTempFileNameW (KERNEL32.291)
729 UINT WINAPI GetTempFileNameW( LPCWSTR path, LPCWSTR prefix, UINT unique,
730 LPWSTR buffer )
732 LPSTR patha,prefixa;
733 char buffera[144];
734 UINT ret;
736 if (!path) return 0;
737 patha = HEAP_strdupWtoA( GetProcessHeap(), 0, path );
738 prefixa = HEAP_strdupWtoA( GetProcessHeap(), 0, prefix );
739 ret = FILE_GetTempFileName( patha, prefixa, unique, buffera, FALSE );
740 MultiByteToWideChar( CP_ACP, 0, buffera, -1, buffer, MAX_PATH );
741 HeapFree( GetProcessHeap(), 0, patha );
742 HeapFree( GetProcessHeap(), 0, prefixa );
743 return ret;
747 /***********************************************************************
748 * GetTempFileName16 (KERNEL.97)
750 UINT16 WINAPI GetTempFileName16( BYTE drive, LPCSTR prefix, UINT16 unique,
751 LPSTR buffer )
753 char temppath[144];
755 if (!(drive & ~TF_FORCEDRIVE)) /* drive 0 means current default drive */
756 drive |= DRIVE_GetCurrentDrive() + 'A';
758 if ((drive & TF_FORCEDRIVE) &&
759 !DRIVE_IsValid( toupper(drive & ~TF_FORCEDRIVE) - 'A' ))
761 drive &= ~TF_FORCEDRIVE;
762 WARN("invalid drive %d specified\n", drive );
765 if (drive & TF_FORCEDRIVE)
766 sprintf(temppath,"%c:", drive & ~TF_FORCEDRIVE );
767 else
768 GetTempPathA( 132, temppath );
769 return (UINT16)FILE_GetTempFileName( temppath, prefix, unique, buffer, TRUE );
772 /***********************************************************************
773 * FILE_DoOpenFile
775 * Implementation of OpenFile16() and OpenFile32().
777 static HFILE FILE_DoOpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode,
778 BOOL win32 )
780 HFILE hFileRet;
781 FILETIME filetime;
782 WORD filedatetime[2];
783 DOS_FULL_NAME full_name;
784 DWORD access, sharing;
785 char *p;
787 if (!ofs) return HFILE_ERROR;
789 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
790 ((mode & 0x3 )==OF_READ)?"OF_READ":
791 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
792 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
793 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
794 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
795 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
796 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
797 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
798 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
799 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
800 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
801 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
802 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
803 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
804 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
805 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
806 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
810 ofs->cBytes = sizeof(OFSTRUCT);
811 ofs->nErrCode = 0;
812 if (mode & OF_REOPEN) name = ofs->szPathName;
814 if (!name) {
815 ERR("called with `name' set to NULL ! Please debug.\n");
816 return HFILE_ERROR;
819 TRACE("%s %04x\n", name, mode );
821 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
822 Are there any cases where getting the path here is wrong?
823 Uwe Bonnes 1997 Apr 2 */
824 if (!GetFullPathNameA( name, sizeof(ofs->szPathName),
825 ofs->szPathName, NULL )) goto error;
826 FILE_ConvertOFMode( mode, &access, &sharing );
828 /* OF_PARSE simply fills the structure */
830 if (mode & OF_PARSE)
832 ofs->fFixedDisk = (GetDriveType16( ofs->szPathName[0]-'A' )
833 != DRIVE_REMOVABLE);
834 TRACE("(%s): OF_PARSE, res = '%s'\n",
835 name, ofs->szPathName );
836 return 0;
839 /* OF_CREATE is completely different from all other options, so
840 handle it first */
842 if (mode & OF_CREATE)
844 if ((hFileRet = CreateFileA( name, GENERIC_READ | GENERIC_WRITE,
845 sharing, NULL, CREATE_ALWAYS,
846 FILE_ATTRIBUTE_NORMAL, 0 ))== INVALID_HANDLE_VALUE)
847 goto error;
848 goto success;
851 /* If OF_SEARCH is set, ignore the given path */
853 if ((mode & OF_SEARCH) && !(mode & OF_REOPEN))
855 /* First try the file name as is */
856 if (DOSFS_GetFullName( name, TRUE, &full_name )) goto found;
857 /* Now remove the path */
858 if (name[0] && (name[1] == ':')) name += 2;
859 if ((p = strrchr( name, '\\' ))) name = p + 1;
860 if ((p = strrchr( name, '/' ))) name = p + 1;
861 if (!name[0]) goto not_found;
864 /* Now look for the file */
866 if (!DIR_SearchPath( NULL, name, NULL, &full_name, win32 )) goto not_found;
868 found:
869 TRACE("found %s = %s\n",
870 full_name.long_name, full_name.short_name );
871 lstrcpynA( ofs->szPathName, full_name.short_name,
872 sizeof(ofs->szPathName) );
874 if (mode & OF_SHARE_EXCLUSIVE)
875 /* Some InstallShield version uses OF_SHARE_EXCLUSIVE
876 on the file <tempdir>/_ins0432._mp to determine how
877 far installation has proceeded.
878 _ins0432._mp is an executable and while running the
879 application expects the open with OF_SHARE_ to fail*/
880 /* Probable FIXME:
881 As our loader closes the files after loading the executable,
882 we can't find the running executable with FILE_InUse.
883 Perhaps the loader should keep the file open.
884 Recheck against how Win handles that case */
886 char *last = strrchr(full_name.long_name,'/');
887 if (!last)
888 last = full_name.long_name - 1;
889 if (GetModuleHandle16(last+1))
891 TRACE("Denying shared open for %s\n",full_name.long_name);
892 return HFILE_ERROR;
896 if (mode & OF_DELETE)
898 if (unlink( full_name.long_name ) == -1) goto not_found;
899 TRACE("(%s): OF_DELETE return = OK\n", name);
900 return 1;
903 hFileRet = FILE_CreateFile( full_name.long_name, access, sharing,
904 NULL, OPEN_EXISTING, 0, 0,
905 DRIVE_GetFlags(full_name.drive) & DRIVE_FAIL_READ_ONLY );
906 if (!hFileRet) goto not_found;
908 GetFileTime( hFileRet, NULL, NULL, &filetime );
909 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
910 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
912 if (memcmp( ofs->reserved, filedatetime, sizeof(ofs->reserved) ))
914 CloseHandle( hFileRet );
915 WARN("(%s): OF_VERIFY failed\n", name );
916 /* FIXME: what error here? */
917 SetLastError( ERROR_FILE_NOT_FOUND );
918 goto error;
921 memcpy( ofs->reserved, filedatetime, sizeof(ofs->reserved) );
923 success: /* We get here if the open was successful */
924 TRACE("(%s): OK, return = %d\n", name, hFileRet );
925 if (win32)
927 if (mode & OF_EXIST) /* Return the handle, but close it first */
928 CloseHandle( hFileRet );
930 else
932 hFileRet = Win32HandleToDosFileHandle( hFileRet );
933 if (hFileRet == HFILE_ERROR16) goto error;
934 if (mode & OF_EXIST) /* Return the handle, but close it first */
935 _lclose16( hFileRet );
937 return hFileRet;
939 not_found: /* We get here if the file does not exist */
940 WARN("'%s' not found or sharing violation\n", name );
941 SetLastError( ERROR_FILE_NOT_FOUND );
942 /* fall through */
944 error: /* We get here if there was an error opening the file */
945 ofs->nErrCode = GetLastError();
946 WARN("(%s): return = HFILE_ERROR error= %d\n",
947 name,ofs->nErrCode );
948 return HFILE_ERROR;
952 /***********************************************************************
953 * OpenFile16 (KERNEL.74)
955 HFILE16 WINAPI OpenFile16( LPCSTR name, OFSTRUCT *ofs, UINT16 mode )
957 return FILE_DoOpenFile( name, ofs, mode, FALSE );
961 /***********************************************************************
962 * OpenFile (KERNEL32.396)
964 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
966 return FILE_DoOpenFile( name, ofs, mode, TRUE );
970 /***********************************************************************
971 * FILE_InitProcessDosHandles
973 * Allocates the default DOS handles for a process. Called either by
974 * Win32HandleToDosFileHandle below or by the DOSVM stuff.
976 static void FILE_InitProcessDosHandles( void )
978 dos_handles[0] = GetStdHandle(STD_INPUT_HANDLE);
979 dos_handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
980 dos_handles[2] = GetStdHandle(STD_ERROR_HANDLE);
981 dos_handles[3] = GetStdHandle(STD_ERROR_HANDLE);
982 dos_handles[4] = GetStdHandle(STD_ERROR_HANDLE);
985 /***********************************************************************
986 * Win32HandleToDosFileHandle (KERNEL32.21)
988 * Allocate a DOS handle for a Win32 handle. The Win32 handle is no
989 * longer valid after this function (even on failure).
991 * Note: this is not exactly right, since on Win95 the Win32 handles
992 * are on top of DOS handles and we do it the other way
993 * around. Should be good enough though.
995 HFILE WINAPI Win32HandleToDosFileHandle( HANDLE handle )
997 int i;
999 if (!handle || (handle == INVALID_HANDLE_VALUE))
1000 return HFILE_ERROR;
1002 for (i = 5; i < DOS_TABLE_SIZE; i++)
1003 if (!dos_handles[i])
1005 dos_handles[i] = handle;
1006 TRACE("Got %d for h32 %d\n", i, handle );
1007 return (HFILE)i;
1009 CloseHandle( handle );
1010 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1011 return HFILE_ERROR;
1015 /***********************************************************************
1016 * DosFileHandleToWin32Handle (KERNEL32.20)
1018 * Return the Win32 handle for a DOS handle.
1020 * Note: this is not exactly right, since on Win95 the Win32 handles
1021 * are on top of DOS handles and we do it the other way
1022 * around. Should be good enough though.
1024 HANDLE WINAPI DosFileHandleToWin32Handle( HFILE handle )
1026 HFILE16 hfile = (HFILE16)handle;
1027 if (hfile < 5 && !dos_handles[hfile]) FILE_InitProcessDosHandles();
1028 if ((hfile >= DOS_TABLE_SIZE) || !dos_handles[hfile])
1030 SetLastError( ERROR_INVALID_HANDLE );
1031 return INVALID_HANDLE_VALUE;
1033 return dos_handles[hfile];
1037 /***********************************************************************
1038 * DisposeLZ32Handle (KERNEL32.22)
1040 * Note: this is not entirely correct, we should only close the
1041 * 32-bit handle and not the 16-bit one, but we cannot do
1042 * this because of the way our DOS handles are implemented.
1043 * It shouldn't break anything though.
1045 void WINAPI DisposeLZ32Handle( HANDLE handle )
1047 int i;
1049 if (!handle || (handle == INVALID_HANDLE_VALUE)) return;
1051 for (i = 5; i < DOS_TABLE_SIZE; i++)
1052 if (dos_handles[i] == handle)
1054 dos_handles[i] = 0;
1055 CloseHandle( handle );
1056 break;
1061 /***********************************************************************
1062 * FILE_Dup2
1064 * dup2() function for DOS handles.
1066 HFILE16 FILE_Dup2( HFILE16 hFile1, HFILE16 hFile2 )
1068 HANDLE new_handle;
1070 if (hFile1 < 5 && !dos_handles[hFile1]) FILE_InitProcessDosHandles();
1072 if ((hFile1 >= DOS_TABLE_SIZE) || (hFile2 >= DOS_TABLE_SIZE) || !dos_handles[hFile1])
1074 SetLastError( ERROR_INVALID_HANDLE );
1075 return HFILE_ERROR16;
1077 if (hFile2 < 5)
1079 FIXME("stdio handle closed, need proper conversion\n" );
1080 SetLastError( ERROR_INVALID_HANDLE );
1081 return HFILE_ERROR16;
1083 if (!DuplicateHandle( GetCurrentProcess(), dos_handles[hFile1],
1084 GetCurrentProcess(), &new_handle,
1085 0, FALSE, DUPLICATE_SAME_ACCESS ))
1086 return HFILE_ERROR16;
1087 if (dos_handles[hFile2]) CloseHandle( dos_handles[hFile2] );
1088 dos_handles[hFile2] = new_handle;
1089 return hFile2;
1093 /***********************************************************************
1094 * _lclose16 (KERNEL.81)
1096 HFILE16 WINAPI _lclose16( HFILE16 hFile )
1098 if (hFile < 5)
1100 FIXME("stdio handle closed, need proper conversion\n" );
1101 SetLastError( ERROR_INVALID_HANDLE );
1102 return HFILE_ERROR16;
1104 if ((hFile >= DOS_TABLE_SIZE) || !dos_handles[hFile])
1106 SetLastError( ERROR_INVALID_HANDLE );
1107 return HFILE_ERROR16;
1109 TRACE("%d (handle32=%d)\n", hFile, dos_handles[hFile] );
1110 CloseHandle( dos_handles[hFile] );
1111 dos_handles[hFile] = 0;
1112 return 0;
1116 /***********************************************************************
1117 * _lclose (KERNEL32.592)
1119 HFILE WINAPI _lclose( HFILE hFile )
1121 TRACE("handle %d\n", hFile );
1122 return CloseHandle( hFile ) ? 0 : HFILE_ERROR;
1125 /***********************************************************************
1126 * GetOverlappedResult (KERNEL32.360)
1128 * Check the result of an Asynchronous data transfer from a file.
1130 * RETURNS
1131 * TRUE on success
1132 * FALSE on failure
1134 * If successful (and relevant) lpTransfered will hold the number of
1135 * bytes transfered during the async operation.
1137 * BUGS
1139 * Currently only works for WaitCommEvent, ReadFile, WriteFile
1140 * with communications ports.
1143 BOOL WINAPI GetOverlappedResult(
1144 HANDLE hFile, /* [I] handle of file to check on */
1145 LPOVERLAPPED lpOverlapped, /* [I/O] pointer to overlapped */
1146 LPDWORD lpTransferred, /* [I/O] number of bytes transfered */
1147 BOOL bWait /* [I] wait for the transfer to complete ? */
1149 DWORD r;
1151 TRACE("(%d %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait);
1153 if(lpOverlapped==NULL)
1155 ERR("lpOverlapped was null\n");
1156 return FALSE;
1158 if(!lpOverlapped->hEvent)
1160 ERR("lpOverlapped->hEvent was null\n");
1161 return FALSE;
1164 do {
1165 TRACE("waiting on %p\n",lpOverlapped);
1166 r = WaitForSingleObjectEx(lpOverlapped->hEvent, bWait?INFINITE:0, TRUE);
1167 TRACE("wait on %p returned %ld\n",lpOverlapped,r);
1168 } while (r==STATUS_USER_APC);
1170 if(lpTransferred)
1171 *lpTransferred = lpOverlapped->InternalHigh;
1173 SetLastError(lpOverlapped->Internal);
1175 return (r==WAIT_OBJECT_0);
1178 /***********************************************************************
1179 * FILE_AsyncResult (INTERNAL)
1181 static int FILE_AsyncResult(HANDLE hAsync, int result)
1183 int r;
1185 SERVER_START_REQ
1187 struct async_result_request *req = server_alloc_req(sizeof *req,0);
1189 req->ov_handle = hAsync;
1190 req->result = result;
1192 r = server_call( REQ_ASYNC_RESULT);
1194 SERVER_END_REQ
1196 return !r;
1199 /***********************************************************************
1200 * FILE_AsyncReadService (INTERNAL)
1202 static void FILE_AsyncReadService(void **args)
1204 LPOVERLAPPED lpOverlapped = (LPOVERLAPPED)args[0];
1205 LPDWORD buffer = (LPDWORD)args[1];
1206 DWORD events = (DWORD)args[2];
1207 int fd, result, r;
1209 TRACE("%p %p %08lx\n", lpOverlapped, buffer, events );
1211 /* if there are no events, it must be a timeout */
1212 if(events==0)
1214 TRACE("read timed out\n");
1215 /* r = STATUS_TIMEOUT; */
1216 r = STATUS_SUCCESS;
1217 goto async_end;
1220 fd = FILE_GetUnixHandle(lpOverlapped->Offset, GENERIC_READ);
1221 if(fd<0)
1223 TRACE("FILE_GetUnixHandle(%ld) failed \n",lpOverlapped->Offset);
1224 r = STATUS_UNSUCCESSFUL;
1225 goto async_end;
1228 /* check to see if the data is ready (non-blocking) */
1229 result = read(fd, &buffer[lpOverlapped->InternalHigh],
1230 lpOverlapped->OffsetHigh - lpOverlapped->InternalHigh);
1231 close(fd);
1233 if ( (result<0) && ((errno == EAGAIN) || (errno == EINTR)))
1235 TRACE("Deferred read %d\n",errno);
1236 r = STATUS_PENDING;
1237 goto async_end;
1240 /* check to see if the transfer is complete */
1241 if(result<0)
1243 TRACE("read returned errno %d\n",errno);
1244 r = STATUS_UNSUCCESSFUL;
1245 goto async_end;
1248 lpOverlapped->InternalHigh += result;
1249 TRACE("read %d more bytes %ld/%ld so far\n",result,lpOverlapped->InternalHigh,lpOverlapped->OffsetHigh);
1251 if(lpOverlapped->InternalHigh < lpOverlapped->OffsetHigh)
1252 r = STATUS_PENDING;
1253 else
1254 r = STATUS_SUCCESS;
1256 async_end:
1257 lpOverlapped->Internal = r;
1258 if ( (r!=STATUS_PENDING)
1259 || (!FILE_AsyncResult( lpOverlapped->InternalHigh, r)))
1261 /* close the handle to the async operation */
1262 if(lpOverlapped->Offset)
1263 CloseHandle(lpOverlapped->Offset);
1264 lpOverlapped->Offset = 0;
1266 NtSetEvent( lpOverlapped->hEvent, NULL );
1267 TRACE("set event flag\n");
1271 /***********************************************************************
1272 * FILE_StartAsyncRead (INTERNAL)
1274 static BOOL FILE_StartAsyncRead( HANDLE hFile, LPOVERLAPPED overlapped, LPVOID buffer, DWORD count)
1276 int r;
1278 SERVER_START_REQ
1280 struct create_async_request *req = server_alloc_req(sizeof *req,0);
1282 req->file_handle = hFile;
1283 req->overlapped = overlapped;
1284 req->buffer = buffer;
1285 req->count = count;
1286 req->func = FILE_AsyncReadService;
1287 req->type = ASYNC_TYPE_READ;
1289 r=server_call( REQ_CREATE_ASYNC );
1291 overlapped->Offset = req->ov_handle;
1293 SERVER_END_REQ
1295 if(!r)
1297 TRACE("ov=%ld IO is pending!!!\n",overlapped->Offset);
1298 SetLastError(ERROR_IO_PENDING);
1301 return !r;
1304 /***********************************************************************
1305 * ReadFile (KERNEL32.577)
1307 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
1308 LPDWORD bytesRead, LPOVERLAPPED overlapped )
1310 int unix_handle, result;
1312 TRACE("%d %p %ld %p %p\n", hFile, buffer, bytesToRead,
1313 bytesRead, overlapped );
1315 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
1316 if (!bytesToRead) return TRUE;
1318 /* this will only have impact if the overlapped structure is specified */
1319 if ( overlapped )
1321 /* if overlapped, check that there is an event flag */
1322 if ( (overlapped->hEvent == 0) ||
1323 (overlapped->hEvent == INVALID_HANDLE_VALUE) )
1325 return FALSE;
1328 overlapped->Offset = 0;
1329 overlapped->OffsetHigh = bytesToRead;
1330 overlapped->Internal = 0;
1331 overlapped->InternalHigh = 0;
1333 NtResetEvent( overlapped->hEvent, NULL );
1335 if(FILE_StartAsyncRead(hFile, overlapped, buffer, bytesToRead))
1337 overlapped->Internal = STATUS_PENDING;
1340 /* always fail on return, either ERROR_IO_PENDING or other error */
1341 return FALSE;
1344 unix_handle = FILE_GetUnixHandle( hFile, GENERIC_READ );
1345 if (unix_handle == -1) return FALSE;
1347 /* code for synchronous reads */
1348 while ((result = read( unix_handle, buffer, bytesToRead )) == -1)
1350 if ((errno == EAGAIN) || (errno == EINTR)) continue;
1351 if ((errno == EFAULT) && !IsBadWritePtr( buffer, bytesToRead )) continue;
1352 FILE_SetDosError();
1353 break;
1355 close( unix_handle );
1356 if (result == -1) return FALSE;
1357 if (bytesRead) *bytesRead = result;
1358 return TRUE;
1361 /***********************************************************************
1362 * FILE_AsyncWriteService (INTERNAL)
1364 static void FILE_AsyncWriteService(void **args)
1366 LPOVERLAPPED lpOverlapped = (LPOVERLAPPED)args[0];
1367 LPDWORD buffer = (LPDWORD)args[1];
1368 DWORD events = (DWORD)args[2];
1369 int fd, result, r;
1371 TRACE("(%p %p %lx)\n",lpOverlapped,buffer,events);
1373 /* if there are no events, it must be a timeout */
1374 if(events==0)
1376 TRACE("write timed out\n");
1377 r = STATUS_TIMEOUT;
1378 goto async_end;
1381 fd = FILE_GetUnixHandle(lpOverlapped->Offset, GENERIC_WRITE);
1382 if(fd<0)
1384 ERR("FILE_GetUnixHandle(%ld) failed \n",lpOverlapped->Offset);
1385 r = STATUS_UNSUCCESSFUL;
1386 goto async_end;
1389 /* write some data (non-blocking) */
1390 result = write(fd, &buffer[lpOverlapped->InternalHigh],
1391 lpOverlapped->OffsetHigh-lpOverlapped->InternalHigh);
1392 close(fd);
1394 if ( (result<0) && ((errno == EAGAIN) || (errno == EINTR)))
1396 r = STATUS_PENDING;
1397 goto async_end;
1400 /* check to see if the transfer is complete */
1401 if(result<0)
1403 r = STATUS_UNSUCCESSFUL;
1404 goto async_end;
1407 lpOverlapped->InternalHigh += result;
1409 if(lpOverlapped->InternalHigh < lpOverlapped->OffsetHigh)
1410 r = STATUS_PENDING;
1411 else
1412 r = STATUS_SUCCESS;
1414 async_end:
1415 lpOverlapped->Internal = r;
1416 if ( (r!=STATUS_PENDING)
1417 || (!FILE_AsyncResult( lpOverlapped->Offset, r)))
1419 /* close the handle to the async operation */
1420 CloseHandle(lpOverlapped->Offset);
1421 lpOverlapped->Offset = 0;
1423 NtSetEvent( lpOverlapped->hEvent, NULL );
1427 /***********************************************************************
1428 * FILE_StartAsyncWrite (INTERNAL)
1430 static BOOL FILE_StartAsyncWrite(HANDLE hFile, LPOVERLAPPED overlapped, LPCVOID buffer,DWORD count)
1432 int r;
1434 SERVER_START_REQ
1436 struct create_async_request *req = server_alloc_req( sizeof(*req), 0 );
1438 req->file_handle = hFile;
1439 req->buffer = (LPVOID)buffer;
1440 req->overlapped = overlapped;
1441 req->count = 0;
1442 req->func = FILE_AsyncWriteService;
1443 req->type = ASYNC_TYPE_WRITE;
1445 r = server_call( REQ_CREATE_ASYNC );
1447 overlapped->Offset = req->ov_handle;
1449 SERVER_END_REQ
1451 if(!r)
1453 SetLastError(ERROR_IO_PENDING);
1456 return !r;
1459 /***********************************************************************
1460 * WriteFile (KERNEL32.738)
1462 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
1463 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
1465 int unix_handle, result;
1467 TRACE("%d %p %ld %p %p\n", hFile, buffer, bytesToWrite,
1468 bytesWritten, overlapped );
1470 if (bytesWritten) *bytesWritten = 0; /* Do this before anything else */
1471 if (!bytesToWrite) return TRUE;
1473 /* this will only have impact if the overlappd structure is specified */
1474 if ( overlapped )
1476 if ( (overlapped->hEvent == 0) ||
1477 (overlapped->hEvent == INVALID_HANDLE_VALUE) )
1478 return FALSE;
1480 overlapped->Offset = 0;
1481 overlapped->OffsetHigh = bytesToWrite;
1482 overlapped->Internal = 0;
1483 overlapped->InternalHigh = 0;
1485 NtResetEvent( overlapped->hEvent, NULL );
1487 if (FILE_StartAsyncWrite(hFile, overlapped, buffer, bytesToWrite))
1489 overlapped->Internal = STATUS_PENDING;
1492 /* always fail on return, either ERROR_IO_PENDING or other error */
1493 return FALSE;
1496 unix_handle = FILE_GetUnixHandle( hFile, GENERIC_WRITE );
1497 if (unix_handle == -1) return FALSE;
1499 /* synchronous file write */
1500 while ((result = write( unix_handle, buffer, bytesToWrite )) == -1)
1502 if ((errno == EAGAIN) || (errno == EINTR)) continue;
1503 if ((errno == EFAULT) && !IsBadReadPtr( buffer, bytesToWrite )) continue;
1504 if (errno == ENOSPC)
1505 SetLastError( ERROR_DISK_FULL );
1506 else
1507 FILE_SetDosError();
1508 break;
1510 close( unix_handle );
1511 if (result == -1) return FALSE;
1512 if (bytesWritten) *bytesWritten = result;
1513 return TRUE;
1517 /***********************************************************************
1518 * WIN16_hread
1520 LONG WINAPI WIN16_hread( HFILE16 hFile, SEGPTR buffer, LONG count )
1522 LONG maxlen;
1524 TRACE("%d %08lx %ld\n",
1525 hFile, (DWORD)buffer, count );
1527 /* Some programs pass a count larger than the allocated buffer */
1528 maxlen = GetSelectorLimit16( SELECTOROF(buffer) ) - OFFSETOF(buffer) + 1;
1529 if (count > maxlen) count = maxlen;
1530 return _lread(DosFileHandleToWin32Handle(hFile), MapSL(buffer), count );
1534 /***********************************************************************
1535 * WIN16_lread
1537 UINT16 WINAPI WIN16_lread( HFILE16 hFile, SEGPTR buffer, UINT16 count )
1539 return (UINT16)WIN16_hread( hFile, buffer, (LONG)count );
1543 /***********************************************************************
1544 * _lread (KERNEL32.596)
1546 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
1548 DWORD result;
1549 if (!ReadFile( handle, buffer, count, &result, NULL )) return -1;
1550 return result;
1554 /***********************************************************************
1555 * _lread16 (KERNEL.82)
1557 UINT16 WINAPI _lread16( HFILE16 hFile, LPVOID buffer, UINT16 count )
1559 return (UINT16)_lread(DosFileHandleToWin32Handle(hFile), buffer, (LONG)count );
1563 /***********************************************************************
1564 * _lcreat16 (KERNEL.83)
1566 HFILE16 WINAPI _lcreat16( LPCSTR path, INT16 attr )
1568 return Win32HandleToDosFileHandle( _lcreat( path, attr ) );
1572 /***********************************************************************
1573 * _lcreat (KERNEL32.593)
1575 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
1577 /* Mask off all flags not explicitly allowed by the doc */
1578 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
1579 TRACE("%s %02x\n", path, attr );
1580 return CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
1581 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1582 CREATE_ALWAYS, attr, 0 );
1586 /***********************************************************************
1587 * SetFilePointer (KERNEL32.492)
1589 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword,
1590 DWORD method )
1592 DWORD ret = 0xffffffff;
1594 if (highword &&
1595 ((distance >= 0 && *highword != 0) || (distance < 0 && *highword != -1)))
1597 FIXME("64-bit offsets not supported yet\n"
1598 "SetFilePointer(%08x,%08lx,%08lx,%08lx)\n",
1599 hFile,distance,*highword,method);
1600 SetLastError( ERROR_INVALID_PARAMETER );
1601 return ret;
1603 TRACE("handle %d offset %ld origin %ld\n",
1604 hFile, distance, method );
1606 SERVER_START_REQ
1608 struct set_file_pointer_request *req = server_alloc_req( sizeof(*req), 0 );
1609 req->handle = hFile;
1610 req->low = distance;
1611 req->high = highword ? *highword : (distance >= 0) ? 0 : -1;
1612 /* FIXME: assumes 1:1 mapping between Windows and Unix seek constants */
1613 req->whence = method;
1614 SetLastError( 0 );
1615 if (!server_call( REQ_SET_FILE_POINTER ))
1617 ret = req->new_low;
1618 if (highword) *highword = req->new_high;
1621 SERVER_END_REQ;
1622 return ret;
1626 /***********************************************************************
1627 * _llseek16 (KERNEL.84)
1629 * FIXME:
1630 * Seeking before the start of the file should be allowed for _llseek16,
1631 * but cause subsequent I/O operations to fail (cf. interrupt list)
1634 LONG WINAPI _llseek16( HFILE16 hFile, LONG lOffset, INT16 nOrigin )
1636 return SetFilePointer( DosFileHandleToWin32Handle(hFile), lOffset, NULL, nOrigin );
1640 /***********************************************************************
1641 * _llseek (KERNEL32.594)
1643 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
1645 return SetFilePointer( hFile, lOffset, NULL, nOrigin );
1649 /***********************************************************************
1650 * _lopen16 (KERNEL.85)
1652 HFILE16 WINAPI _lopen16( LPCSTR path, INT16 mode )
1654 return Win32HandleToDosFileHandle( _lopen( path, mode ) );
1658 /***********************************************************************
1659 * _lopen (KERNEL32.595)
1661 HFILE WINAPI _lopen( LPCSTR path, INT mode )
1663 DWORD access, sharing;
1665 TRACE("('%s',%04x)\n", path, mode );
1666 FILE_ConvertOFMode( mode, &access, &sharing );
1667 return CreateFileA( path, access, sharing, NULL, OPEN_EXISTING, 0, 0 );
1671 /***********************************************************************
1672 * _lwrite16 (KERNEL.86)
1674 UINT16 WINAPI _lwrite16( HFILE16 hFile, LPCSTR buffer, UINT16 count )
1676 return (UINT16)_hwrite( DosFileHandleToWin32Handle(hFile), buffer, (LONG)count );
1679 /***********************************************************************
1680 * _lwrite (KERNEL32.761)
1682 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
1684 return (UINT)_hwrite( hFile, buffer, (LONG)count );
1688 /***********************************************************************
1689 * _hread16 (KERNEL.349)
1691 LONG WINAPI _hread16( HFILE16 hFile, LPVOID buffer, LONG count)
1693 return _lread( DosFileHandleToWin32Handle(hFile), buffer, count );
1697 /***********************************************************************
1698 * _hread (KERNEL32.590)
1700 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
1702 return _lread( hFile, buffer, count );
1706 /***********************************************************************
1707 * _hwrite16 (KERNEL.350)
1709 LONG WINAPI _hwrite16( HFILE16 hFile, LPCSTR buffer, LONG count )
1711 return _hwrite( DosFileHandleToWin32Handle(hFile), buffer, count );
1715 /***********************************************************************
1716 * _hwrite (KERNEL32.591)
1718 * experimentation yields that _lwrite:
1719 * o truncates the file at the current position with
1720 * a 0 len write
1721 * o returns 0 on a 0 length write
1722 * o works with console handles
1725 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
1727 DWORD result;
1729 TRACE("%d %p %ld\n", handle, buffer, count );
1731 if (!count)
1733 /* Expand or truncate at current position */
1734 if (!SetEndOfFile( handle )) return HFILE_ERROR;
1735 return 0;
1737 if (!WriteFile( handle, buffer, count, &result, NULL ))
1738 return HFILE_ERROR;
1739 return result;
1743 /***********************************************************************
1744 * SetHandleCount16 (KERNEL.199)
1746 UINT16 WINAPI SetHandleCount16( UINT16 count )
1748 return SetHandleCount( count );
1752 /*************************************************************************
1753 * SetHandleCount (KERNEL32.494)
1755 UINT WINAPI SetHandleCount( UINT count )
1757 return min( 256, count );
1761 /***********************************************************************
1762 * FlushFileBuffers (KERNEL32.133)
1764 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
1766 BOOL ret;
1767 SERVER_START_REQ
1769 struct flush_file_request *req = server_alloc_req( sizeof(*req), 0 );
1770 req->handle = hFile;
1771 ret = !server_call( REQ_FLUSH_FILE );
1773 SERVER_END_REQ;
1774 return ret;
1778 /**************************************************************************
1779 * SetEndOfFile (KERNEL32.483)
1781 BOOL WINAPI SetEndOfFile( HANDLE hFile )
1783 BOOL ret;
1784 SERVER_START_REQ
1786 struct truncate_file_request *req = server_alloc_req( sizeof(*req), 0 );
1787 req->handle = hFile;
1788 ret = !server_call( REQ_TRUNCATE_FILE );
1790 SERVER_END_REQ;
1791 return ret;
1795 /***********************************************************************
1796 * DeleteFile16 (KERNEL.146)
1798 BOOL16 WINAPI DeleteFile16( LPCSTR path )
1800 return DeleteFileA( path );
1804 /***********************************************************************
1805 * DeleteFileA (KERNEL32.71)
1807 BOOL WINAPI DeleteFileA( LPCSTR path )
1809 DOS_FULL_NAME full_name;
1811 TRACE("'%s'\n", path );
1813 if (!*path)
1815 ERR("Empty path passed\n");
1816 return FALSE;
1818 if (DOSFS_GetDevice( path ))
1820 WARN("cannot remove DOS device '%s'!\n", path);
1821 SetLastError( ERROR_FILE_NOT_FOUND );
1822 return FALSE;
1825 if (!DOSFS_GetFullName( path, TRUE, &full_name )) return FALSE;
1826 if (unlink( full_name.long_name ) == -1)
1828 FILE_SetDosError();
1829 return FALSE;
1831 return TRUE;
1835 /***********************************************************************
1836 * DeleteFileW (KERNEL32.72)
1838 BOOL WINAPI DeleteFileW( LPCWSTR path )
1840 LPSTR xpath = HEAP_strdupWtoA( GetProcessHeap(), 0, path );
1841 BOOL ret = DeleteFileA( xpath );
1842 HeapFree( GetProcessHeap(), 0, xpath );
1843 return ret;
1847 /***********************************************************************
1848 * GetFileType (KERNEL32.222)
1850 DWORD WINAPI GetFileType( HANDLE hFile )
1852 DWORD ret = FILE_TYPE_UNKNOWN;
1853 SERVER_START_REQ
1855 struct get_file_info_request *req = server_alloc_req( sizeof(*req), 0 );
1856 req->handle = hFile;
1857 if (!server_call( REQ_GET_FILE_INFO )) ret = req->type;
1859 SERVER_END_REQ;
1860 return ret;
1864 /**************************************************************************
1865 * MoveFileExA (KERNEL32.???)
1867 BOOL WINAPI MoveFileExA( LPCSTR fn1, LPCSTR fn2, DWORD flag )
1869 DOS_FULL_NAME full_name1, full_name2;
1871 TRACE("(%s,%s,%04lx)\n", fn1, fn2, flag);
1873 if (!DOSFS_GetFullName( fn1, TRUE, &full_name1 )) return FALSE;
1875 if (fn2) /* !fn2 means delete fn1 */
1877 if (DOSFS_GetFullName( fn2, TRUE, &full_name2 ))
1879 /* target exists, check if we may overwrite */
1880 if (!(flag & MOVEFILE_REPLACE_EXISTING))
1882 /* FIXME: Use right error code */
1883 SetLastError( ERROR_ACCESS_DENIED );
1884 return FALSE;
1887 else if (!DOSFS_GetFullName( fn2, FALSE, &full_name2 )) return FALSE;
1889 /* Source name and target path are valid */
1891 if (flag & MOVEFILE_DELAY_UNTIL_REBOOT)
1893 /* FIXME: (bon@elektron.ikp.physik.th-darmstadt.de 970706)
1894 Perhaps we should queue these command and execute it
1895 when exiting... What about using on_exit(2)
1897 FIXME("Please move existing file '%s' to file '%s' when Wine has finished\n",
1898 full_name1.long_name, full_name2.long_name);
1899 return TRUE;
1902 if (full_name1.drive != full_name2.drive)
1904 /* use copy, if allowed */
1905 if (!(flag & MOVEFILE_COPY_ALLOWED))
1907 /* FIXME: Use right error code */
1908 SetLastError( ERROR_FILE_EXISTS );
1909 return FALSE;
1911 return CopyFileA( fn1, fn2, !(flag & MOVEFILE_REPLACE_EXISTING) );
1913 if (rename( full_name1.long_name, full_name2.long_name ) == -1)
1915 FILE_SetDosError();
1916 return FALSE;
1918 return TRUE;
1920 else /* fn2 == NULL means delete source */
1922 if (flag & MOVEFILE_DELAY_UNTIL_REBOOT)
1924 if (flag & MOVEFILE_COPY_ALLOWED) {
1925 WARN("Illegal flag\n");
1926 SetLastError( ERROR_GEN_FAILURE );
1927 return FALSE;
1929 /* FIXME: (bon@elektron.ikp.physik.th-darmstadt.de 970706)
1930 Perhaps we should queue these command and execute it
1931 when exiting... What about using on_exit(2)
1933 FIXME("Please delete file '%s' when Wine has finished\n",
1934 full_name1.long_name);
1935 return TRUE;
1938 if (unlink( full_name1.long_name ) == -1)
1940 FILE_SetDosError();
1941 return FALSE;
1943 return TRUE; /* successfully deleted */
1947 /**************************************************************************
1948 * MoveFileExW (KERNEL32.???)
1950 BOOL WINAPI MoveFileExW( LPCWSTR fn1, LPCWSTR fn2, DWORD flag )
1952 LPSTR afn1 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn1 );
1953 LPSTR afn2 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn2 );
1954 BOOL res = MoveFileExA( afn1, afn2, flag );
1955 HeapFree( GetProcessHeap(), 0, afn1 );
1956 HeapFree( GetProcessHeap(), 0, afn2 );
1957 return res;
1961 /**************************************************************************
1962 * MoveFileA (KERNEL32.387)
1964 * Move file or directory
1966 BOOL WINAPI MoveFileA( LPCSTR fn1, LPCSTR fn2 )
1968 DOS_FULL_NAME full_name1, full_name2;
1969 struct stat fstat;
1971 TRACE("(%s,%s)\n", fn1, fn2 );
1973 if (!DOSFS_GetFullName( fn1, TRUE, &full_name1 )) return FALSE;
1974 if (DOSFS_GetFullName( fn2, TRUE, &full_name2 )) {
1975 /* The new name must not already exist */
1976 SetLastError(ERROR_ALREADY_EXISTS);
1977 return FALSE;
1979 if (!DOSFS_GetFullName( fn2, FALSE, &full_name2 )) return FALSE;
1981 if (full_name1.drive == full_name2.drive) /* move */
1982 if (rename( full_name1.long_name, full_name2.long_name ) == -1)
1984 FILE_SetDosError();
1985 return FALSE;
1987 else return TRUE;
1988 else /*copy */ {
1989 if (stat( full_name1.long_name, &fstat ))
1991 WARN("Invalid source file %s\n",
1992 full_name1.long_name);
1993 FILE_SetDosError();
1994 return FALSE;
1996 if (S_ISDIR(fstat.st_mode)) {
1997 /* No Move for directories across file systems */
1998 /* FIXME: Use right error code */
1999 SetLastError( ERROR_GEN_FAILURE );
2000 return FALSE;
2002 else
2003 return CopyFileA(fn1, fn2, TRUE); /*fail, if exist */
2008 /**************************************************************************
2009 * MoveFileW (KERNEL32.390)
2011 BOOL WINAPI MoveFileW( LPCWSTR fn1, LPCWSTR fn2 )
2013 LPSTR afn1 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn1 );
2014 LPSTR afn2 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn2 );
2015 BOOL res = MoveFileA( afn1, afn2 );
2016 HeapFree( GetProcessHeap(), 0, afn1 );
2017 HeapFree( GetProcessHeap(), 0, afn2 );
2018 return res;
2022 /**************************************************************************
2023 * CopyFileA (KERNEL32.36)
2025 BOOL WINAPI CopyFileA( LPCSTR source, LPCSTR dest, BOOL fail_if_exists )
2027 HFILE h1, h2;
2028 BY_HANDLE_FILE_INFORMATION info;
2029 UINT count;
2030 BOOL ret = FALSE;
2031 int mode;
2032 char buffer[2048];
2034 if ((h1 = _lopen( source, OF_READ )) == HFILE_ERROR) return FALSE;
2035 if (!GetFileInformationByHandle( h1, &info ))
2037 CloseHandle( h1 );
2038 return FALSE;
2040 mode = (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY) ? 0444 : 0666;
2041 if ((h2 = CreateFileA( dest, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
2042 fail_if_exists ? CREATE_NEW : CREATE_ALWAYS,
2043 info.dwFileAttributes, h1 )) == INVALID_HANDLE_VALUE)
2045 CloseHandle( h1 );
2046 return FALSE;
2048 while ((count = _lread( h1, buffer, sizeof(buffer) )) > 0)
2050 char *p = buffer;
2051 while (count > 0)
2053 INT res = _lwrite( h2, p, count );
2054 if (res <= 0) goto done;
2055 p += res;
2056 count -= res;
2059 ret = TRUE;
2060 done:
2061 CloseHandle( h1 );
2062 CloseHandle( h2 );
2063 return ret;
2067 /**************************************************************************
2068 * CopyFileW (KERNEL32.37)
2070 BOOL WINAPI CopyFileW( LPCWSTR source, LPCWSTR dest, BOOL fail_if_exists)
2072 LPSTR sourceA = HEAP_strdupWtoA( GetProcessHeap(), 0, source );
2073 LPSTR destA = HEAP_strdupWtoA( GetProcessHeap(), 0, dest );
2074 BOOL ret = CopyFileA( sourceA, destA, fail_if_exists );
2075 HeapFree( GetProcessHeap(), 0, sourceA );
2076 HeapFree( GetProcessHeap(), 0, destA );
2077 return ret;
2081 /**************************************************************************
2082 * CopyFileExA (KERNEL32.858)
2084 * This implementation ignores most of the extra parameters passed-in into
2085 * the "ex" version of the method and calls the CopyFile method.
2086 * It will have to be fixed eventually.
2088 BOOL WINAPI CopyFileExA(LPCSTR sourceFilename,
2089 LPCSTR destFilename,
2090 LPPROGRESS_ROUTINE progressRoutine,
2091 LPVOID appData,
2092 LPBOOL cancelFlagPointer,
2093 DWORD copyFlags)
2095 BOOL failIfExists = FALSE;
2098 * Interpret the only flag that CopyFile can interpret.
2100 if ( (copyFlags & COPY_FILE_FAIL_IF_EXISTS) != 0)
2102 failIfExists = TRUE;
2105 return CopyFileA(sourceFilename, destFilename, failIfExists);
2108 /**************************************************************************
2109 * CopyFileExW (KERNEL32.859)
2111 BOOL WINAPI CopyFileExW(LPCWSTR sourceFilename,
2112 LPCWSTR destFilename,
2113 LPPROGRESS_ROUTINE progressRoutine,
2114 LPVOID appData,
2115 LPBOOL cancelFlagPointer,
2116 DWORD copyFlags)
2118 LPSTR sourceA = HEAP_strdupWtoA( GetProcessHeap(), 0, sourceFilename );
2119 LPSTR destA = HEAP_strdupWtoA( GetProcessHeap(), 0, destFilename );
2121 BOOL ret = CopyFileExA(sourceA,
2122 destA,
2123 progressRoutine,
2124 appData,
2125 cancelFlagPointer,
2126 copyFlags);
2128 HeapFree( GetProcessHeap(), 0, sourceA );
2129 HeapFree( GetProcessHeap(), 0, destA );
2131 return ret;
2135 /***********************************************************************
2136 * SetFileTime (KERNEL32.650)
2138 BOOL WINAPI SetFileTime( HANDLE hFile,
2139 const FILETIME *lpCreationTime,
2140 const FILETIME *lpLastAccessTime,
2141 const FILETIME *lpLastWriteTime )
2143 BOOL ret;
2144 SERVER_START_REQ
2146 struct set_file_time_request *req = server_alloc_req( sizeof(*req), 0 );
2147 req->handle = hFile;
2148 if (lpLastAccessTime)
2149 RtlTimeToSecondsSince1970( lpLastAccessTime, (DWORD *)&req->access_time );
2150 else
2151 req->access_time = 0; /* FIXME */
2152 if (lpLastWriteTime)
2153 RtlTimeToSecondsSince1970( lpLastWriteTime, (DWORD *)&req->write_time );
2154 else
2155 req->write_time = 0; /* FIXME */
2156 ret = !server_call( REQ_SET_FILE_TIME );
2158 SERVER_END_REQ;
2159 return ret;
2163 /**************************************************************************
2164 * LockFile (KERNEL32.511)
2166 BOOL WINAPI LockFile( HANDLE hFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh,
2167 DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh )
2169 BOOL ret;
2170 SERVER_START_REQ
2172 struct lock_file_request *req = server_alloc_req( sizeof(*req), 0 );
2174 req->handle = hFile;
2175 req->offset_low = dwFileOffsetLow;
2176 req->offset_high = dwFileOffsetHigh;
2177 req->count_low = nNumberOfBytesToLockLow;
2178 req->count_high = nNumberOfBytesToLockHigh;
2179 ret = !server_call( REQ_LOCK_FILE );
2181 SERVER_END_REQ;
2182 return ret;
2185 /**************************************************************************
2186 * LockFileEx [KERNEL32.512]
2188 * Locks a byte range within an open file for shared or exclusive access.
2190 * RETURNS
2191 * success: TRUE
2192 * failure: FALSE
2193 * NOTES
2195 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
2197 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
2198 DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh,
2199 LPOVERLAPPED pOverlapped )
2201 FIXME("hFile=%d,flags=%ld,reserved=%ld,lowbytes=%ld,highbytes=%ld,overlapped=%p: stub.\n",
2202 hFile, flags, reserved, nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh,
2203 pOverlapped);
2204 if (reserved == 0)
2205 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2206 else
2208 ERR("reserved == %ld: Supposed to be 0??\n", reserved);
2209 SetLastError(ERROR_INVALID_PARAMETER);
2212 return FALSE;
2216 /**************************************************************************
2217 * UnlockFile (KERNEL32.703)
2219 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh,
2220 DWORD nNumberOfBytesToUnlockLow, DWORD nNumberOfBytesToUnlockHigh )
2222 BOOL ret;
2223 SERVER_START_REQ
2225 struct unlock_file_request *req = server_alloc_req( sizeof(*req), 0 );
2227 req->handle = hFile;
2228 req->offset_low = dwFileOffsetLow;
2229 req->offset_high = dwFileOffsetHigh;
2230 req->count_low = nNumberOfBytesToUnlockLow;
2231 req->count_high = nNumberOfBytesToUnlockHigh;
2232 ret = !server_call( REQ_UNLOCK_FILE );
2234 SERVER_END_REQ;
2235 return ret;
2239 /**************************************************************************
2240 * UnlockFileEx (KERNEL32.705)
2242 BOOL WINAPI UnlockFileEx(
2243 HFILE hFile,
2244 DWORD dwReserved,
2245 DWORD nNumberOfBytesToUnlockLow,
2246 DWORD nNumberOfBytesToUnlockHigh,
2247 LPOVERLAPPED lpOverlapped
2250 FIXME("hFile=%d,reserved=%ld,lowbytes=%ld,highbytes=%ld,overlapped=%p: stub.\n",
2251 hFile, dwReserved, nNumberOfBytesToUnlockLow, nNumberOfBytesToUnlockHigh,
2252 lpOverlapped);
2253 if (dwReserved == 0)
2254 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2255 else
2257 ERR("reserved == %ld: Supposed to be 0??\n", dwReserved);
2258 SetLastError(ERROR_INVALID_PARAMETER);
2261 return FALSE;
2265 #if 0
2267 struct DOS_FILE_LOCK {
2268 struct DOS_FILE_LOCK * next;
2269 DWORD base;
2270 DWORD len;
2271 DWORD processId;
2272 FILE_OBJECT * dos_file;
2273 /* char * unix_name;*/
2276 typedef struct DOS_FILE_LOCK DOS_FILE_LOCK;
2278 static DOS_FILE_LOCK *locks = NULL;
2279 static void DOS_RemoveFileLocks(FILE_OBJECT *file);
2282 /* Locks need to be mirrored because unix file locking is based
2283 * on the pid. Inside of wine there can be multiple WINE processes
2284 * that share the same unix pid.
2285 * Read's and writes should check these locks also - not sure
2286 * how critical that is at this point (FIXME).
2289 static BOOL DOS_AddLock(FILE_OBJECT *file, struct flock *f)
2291 DOS_FILE_LOCK *curr;
2292 DWORD processId;
2294 processId = GetCurrentProcessId();
2296 /* check if lock overlaps a current lock for the same file */
2297 #if 0
2298 for (curr = locks; curr; curr = curr->next) {
2299 if (strcmp(curr->unix_name, file->unix_name) == 0) {
2300 if ((f->l_start == curr->base) && (f->l_len == curr->len))
2301 return TRUE;/* region is identic */
2302 if ((f->l_start < (curr->base + curr->len)) &&
2303 ((f->l_start + f->l_len) > curr->base)) {
2304 /* region overlaps */
2305 return FALSE;
2309 #endif
2311 curr = HeapAlloc( GetProcessHeap(), 0, sizeof(DOS_FILE_LOCK) );
2312 curr->processId = GetCurrentProcessId();
2313 curr->base = f->l_start;
2314 curr->len = f->l_len;
2315 /* curr->unix_name = HEAP_strdupA( GetProcessHeap(), 0, file->unix_name);*/
2316 curr->next = locks;
2317 curr->dos_file = file;
2318 locks = curr;
2319 return TRUE;
2322 static void DOS_RemoveFileLocks(FILE_OBJECT *file)
2324 DWORD processId;
2325 DOS_FILE_LOCK **curr;
2326 DOS_FILE_LOCK *rem;
2328 processId = GetCurrentProcessId();
2329 curr = &locks;
2330 while (*curr) {
2331 if ((*curr)->dos_file == file) {
2332 rem = *curr;
2333 *curr = (*curr)->next;
2334 /* HeapFree( GetProcessHeap(), 0, rem->unix_name );*/
2335 HeapFree( GetProcessHeap(), 0, rem );
2337 else
2338 curr = &(*curr)->next;
2342 static BOOL DOS_RemoveLock(FILE_OBJECT *file, struct flock *f)
2344 DWORD processId;
2345 DOS_FILE_LOCK **curr;
2346 DOS_FILE_LOCK *rem;
2348 processId = GetCurrentProcessId();
2349 for (curr = &locks; *curr; curr = &(*curr)->next) {
2350 if ((*curr)->processId == processId &&
2351 (*curr)->dos_file == file &&
2352 (*curr)->base == f->l_start &&
2353 (*curr)->len == f->l_len) {
2354 /* this is the same lock */
2355 rem = *curr;
2356 *curr = (*curr)->next;
2357 /* HeapFree( GetProcessHeap(), 0, rem->unix_name );*/
2358 HeapFree( GetProcessHeap(), 0, rem );
2359 return TRUE;
2362 /* no matching lock found */
2363 return FALSE;
2367 /**************************************************************************
2368 * LockFile (KERNEL32.511)
2370 BOOL WINAPI LockFile(
2371 HFILE hFile,DWORD dwFileOffsetLow,DWORD dwFileOffsetHigh,
2372 DWORD nNumberOfBytesToLockLow,DWORD nNumberOfBytesToLockHigh )
2374 struct flock f;
2375 FILE_OBJECT *file;
2377 TRACE("handle %d offsetlow=%ld offsethigh=%ld nbyteslow=%ld nbyteshigh=%ld\n",
2378 hFile, dwFileOffsetLow, dwFileOffsetHigh,
2379 nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh);
2381 if (dwFileOffsetHigh || nNumberOfBytesToLockHigh) {
2382 FIXME("Unimplemented bytes > 32bits\n");
2383 return FALSE;
2386 f.l_start = dwFileOffsetLow;
2387 f.l_len = nNumberOfBytesToLockLow;
2388 f.l_whence = SEEK_SET;
2389 f.l_pid = 0;
2390 f.l_type = F_WRLCK;
2392 if (!(file = FILE_GetFile(hFile,0,NULL))) return FALSE;
2394 /* shadow locks internally */
2395 if (!DOS_AddLock(file, &f)) {
2396 SetLastError( ERROR_LOCK_VIOLATION );
2397 return FALSE;
2400 /* FIXME: Unix locking commented out for now, doesn't work with Excel */
2401 #ifdef USE_UNIX_LOCKS
2402 if (fcntl(file->unix_handle, F_SETLK, &f) == -1) {
2403 if (errno == EACCES || errno == EAGAIN) {
2404 SetLastError( ERROR_LOCK_VIOLATION );
2406 else {
2407 FILE_SetDosError();
2409 /* remove our internal copy of the lock */
2410 DOS_RemoveLock(file, &f);
2411 return FALSE;
2413 #endif
2414 return TRUE;
2418 /**************************************************************************
2419 * UnlockFile (KERNEL32.703)
2421 BOOL WINAPI UnlockFile(
2422 HFILE hFile,DWORD dwFileOffsetLow,DWORD dwFileOffsetHigh,
2423 DWORD nNumberOfBytesToUnlockLow,DWORD nNumberOfBytesToUnlockHigh )
2425 FILE_OBJECT *file;
2426 struct flock f;
2428 TRACE("handle %d offsetlow=%ld offsethigh=%ld nbyteslow=%ld nbyteshigh=%ld\n",
2429 hFile, dwFileOffsetLow, dwFileOffsetHigh,
2430 nNumberOfBytesToUnlockLow, nNumberOfBytesToUnlockHigh);
2432 if (dwFileOffsetHigh || nNumberOfBytesToUnlockHigh) {
2433 WARN("Unimplemented bytes > 32bits\n");
2434 return FALSE;
2437 f.l_start = dwFileOffsetLow;
2438 f.l_len = nNumberOfBytesToUnlockLow;
2439 f.l_whence = SEEK_SET;
2440 f.l_pid = 0;
2441 f.l_type = F_UNLCK;
2443 if (!(file = FILE_GetFile(hFile,0,NULL))) return FALSE;
2445 DOS_RemoveLock(file, &f); /* ok if fails - may be another wine */
2447 /* FIXME: Unix locking commented out for now, doesn't work with Excel */
2448 #ifdef USE_UNIX_LOCKS
2449 if (fcntl(file->unix_handle, F_SETLK, &f) == -1) {
2450 FILE_SetDosError();
2451 return FALSE;
2453 #endif
2454 return TRUE;
2456 #endif
2458 /**************************************************************************
2459 * GetFileAttributesExA [KERNEL32.874]
2461 BOOL WINAPI GetFileAttributesExA(
2462 LPCSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId,
2463 LPVOID lpFileInformation)
2465 DOS_FULL_NAME full_name;
2466 BY_HANDLE_FILE_INFORMATION info;
2468 if (lpFileName == NULL) return FALSE;
2469 if (lpFileInformation == NULL) return FALSE;
2471 if (fInfoLevelId == GetFileExInfoStandard) {
2472 LPWIN32_FILE_ATTRIBUTE_DATA lpFad =
2473 (LPWIN32_FILE_ATTRIBUTE_DATA) lpFileInformation;
2474 if (!DOSFS_GetFullName( lpFileName, TRUE, &full_name )) return FALSE;
2475 if (!FILE_Stat( full_name.long_name, &info )) return FALSE;
2477 lpFad->dwFileAttributes = info.dwFileAttributes;
2478 lpFad->ftCreationTime = info.ftCreationTime;
2479 lpFad->ftLastAccessTime = info.ftLastAccessTime;
2480 lpFad->ftLastWriteTime = info.ftLastWriteTime;
2481 lpFad->nFileSizeHigh = info.nFileSizeHigh;
2482 lpFad->nFileSizeLow = info.nFileSizeLow;
2484 else {
2485 FIXME("invalid info level %d!\n", fInfoLevelId);
2486 return FALSE;
2489 return TRUE;
2493 /**************************************************************************
2494 * GetFileAttributesExW [KERNEL32.875]
2496 BOOL WINAPI GetFileAttributesExW(
2497 LPCWSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId,
2498 LPVOID lpFileInformation)
2500 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, lpFileName );
2501 BOOL res =
2502 GetFileAttributesExA( nameA, fInfoLevelId, lpFileInformation);
2503 HeapFree( GetProcessHeap(), 0, nameA );
2504 return res;