Fixed WM_GETTEXTLENGTH handling.
[wine/multimedia.git] / files / file.c
blob9d7c10c1190040f0cf97db81658ea558d1028958
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\n", 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 [in] pointer to filename to be accessed
343 * access [in] access mode requested
344 * sharing [in] share mode
345 * sa [in] pointer to security attributes
346 * creation [in] how to create the file
347 * attributes [in] attributes for newly created file
348 * template [in] 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)
589 SetLastError( ERROR_INVALID_PARAMETER );
590 return -1;
592 if (!*name || !DOSFS_GetFullName( name, TRUE, &full_name ))
594 SetLastError( ERROR_BAD_PATHNAME );
595 return -1;
597 if (!FILE_Stat( full_name.long_name, &info )) return -1;
598 return info.dwFileAttributes;
602 /**************************************************************************
603 * GetFileAttributesW (KERNEL32.218)
605 DWORD WINAPI GetFileAttributesW( LPCWSTR name )
607 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
608 DWORD res = GetFileAttributesA( nameA );
609 HeapFree( GetProcessHeap(), 0, nameA );
610 return res;
614 /***********************************************************************
615 * GetFileSize (KERNEL32.220)
617 DWORD WINAPI GetFileSize( HANDLE hFile, LPDWORD filesizehigh )
619 BY_HANDLE_FILE_INFORMATION info;
620 if (!GetFileInformationByHandle( hFile, &info )) return 0;
621 if (filesizehigh) *filesizehigh = info.nFileSizeHigh;
622 return info.nFileSizeLow;
626 /***********************************************************************
627 * GetFileTime (KERNEL32.221)
629 BOOL WINAPI GetFileTime( HANDLE hFile, FILETIME *lpCreationTime,
630 FILETIME *lpLastAccessTime,
631 FILETIME *lpLastWriteTime )
633 BY_HANDLE_FILE_INFORMATION info;
634 if (!GetFileInformationByHandle( hFile, &info )) return FALSE;
635 if (lpCreationTime) *lpCreationTime = info.ftCreationTime;
636 if (lpLastAccessTime) *lpLastAccessTime = info.ftLastAccessTime;
637 if (lpLastWriteTime) *lpLastWriteTime = info.ftLastWriteTime;
638 return TRUE;
641 /***********************************************************************
642 * CompareFileTime (KERNEL32.28)
644 INT WINAPI CompareFileTime( LPFILETIME x, LPFILETIME y )
646 if (!x || !y) return -1;
648 if (x->dwHighDateTime > y->dwHighDateTime)
649 return 1;
650 if (x->dwHighDateTime < y->dwHighDateTime)
651 return -1;
652 if (x->dwLowDateTime > y->dwLowDateTime)
653 return 1;
654 if (x->dwLowDateTime < y->dwLowDateTime)
655 return -1;
656 return 0;
659 /***********************************************************************
660 * FILE_GetTempFileName : utility for GetTempFileName
662 static UINT FILE_GetTempFileName( LPCSTR path, LPCSTR prefix, UINT unique,
663 LPSTR buffer, BOOL isWin16 )
665 static UINT unique_temp;
666 DOS_FULL_NAME full_name;
667 int i;
668 LPSTR p;
669 UINT num;
671 if ( !path || !prefix || !buffer ) return 0;
673 if (!unique_temp) unique_temp = time(NULL) & 0xffff;
674 num = unique ? (unique & 0xffff) : (unique_temp++ & 0xffff);
676 strcpy( buffer, path );
677 p = buffer + strlen(buffer);
679 /* add a \, if there isn't one and path is more than just the drive letter ... */
680 if ( !((strlen(buffer) == 2) && (buffer[1] == ':'))
681 && ((p == buffer) || (p[-1] != '\\'))) *p++ = '\\';
683 if (isWin16) *p++ = '~';
684 for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
685 sprintf( p, "%04x.tmp", num );
687 /* Now try to create it */
689 if (!unique)
693 HFILE handle = CreateFileA( buffer, GENERIC_WRITE, 0, NULL,
694 CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 );
695 if (handle != INVALID_HANDLE_VALUE)
696 { /* We created it */
697 TRACE("created %s\n",
698 buffer);
699 CloseHandle( handle );
700 break;
702 if (GetLastError() != ERROR_FILE_EXISTS)
703 break; /* No need to go on */
704 num++;
705 sprintf( p, "%04x.tmp", num );
706 } while (num != (unique & 0xffff));
709 /* Get the full path name */
711 if (DOSFS_GetFullName( buffer, FALSE, &full_name ))
713 /* Check if we have write access in the directory */
714 if ((p = strrchr( full_name.long_name, '/' ))) *p = '\0';
715 if (access( full_name.long_name, W_OK ) == -1)
716 WARN("returns '%s', which doesn't seem to be writeable.\n",
717 buffer);
719 TRACE("returning %s\n", buffer );
720 return unique ? unique : num;
724 /***********************************************************************
725 * GetTempFileNameA (KERNEL32.290)
727 UINT WINAPI GetTempFileNameA( LPCSTR path, LPCSTR prefix, UINT unique,
728 LPSTR buffer)
730 return FILE_GetTempFileName(path, prefix, unique, buffer, FALSE);
733 /***********************************************************************
734 * GetTempFileNameW (KERNEL32.291)
736 UINT WINAPI GetTempFileNameW( LPCWSTR path, LPCWSTR prefix, UINT unique,
737 LPWSTR buffer )
739 LPSTR patha,prefixa;
740 char buffera[144];
741 UINT ret;
743 if (!path) return 0;
744 patha = HEAP_strdupWtoA( GetProcessHeap(), 0, path );
745 prefixa = HEAP_strdupWtoA( GetProcessHeap(), 0, prefix );
746 ret = FILE_GetTempFileName( patha, prefixa, unique, buffera, FALSE );
747 MultiByteToWideChar( CP_ACP, 0, buffera, -1, buffer, MAX_PATH );
748 HeapFree( GetProcessHeap(), 0, patha );
749 HeapFree( GetProcessHeap(), 0, prefixa );
750 return ret;
754 /***********************************************************************
755 * GetTempFileName16 (KERNEL.97)
757 UINT16 WINAPI GetTempFileName16( BYTE drive, LPCSTR prefix, UINT16 unique,
758 LPSTR buffer )
760 char temppath[144];
762 if (!(drive & ~TF_FORCEDRIVE)) /* drive 0 means current default drive */
763 drive |= DRIVE_GetCurrentDrive() + 'A';
765 if ((drive & TF_FORCEDRIVE) &&
766 !DRIVE_IsValid( toupper(drive & ~TF_FORCEDRIVE) - 'A' ))
768 drive &= ~TF_FORCEDRIVE;
769 WARN("invalid drive %d specified\n", drive );
772 if (drive & TF_FORCEDRIVE)
773 sprintf(temppath,"%c:", drive & ~TF_FORCEDRIVE );
774 else
775 GetTempPathA( 132, temppath );
776 return (UINT16)FILE_GetTempFileName( temppath, prefix, unique, buffer, TRUE );
779 /***********************************************************************
780 * FILE_DoOpenFile
782 * Implementation of OpenFile16() and OpenFile32().
784 static HFILE FILE_DoOpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode,
785 BOOL win32 )
787 HFILE hFileRet;
788 FILETIME filetime;
789 WORD filedatetime[2];
790 DOS_FULL_NAME full_name;
791 DWORD access, sharing;
792 char *p;
794 if (!ofs) return HFILE_ERROR;
796 TRACE("%s %s %s %s%s%s%s%s%s%s%s%s\n",name,
797 ((mode & 0x3 )==OF_READ)?"OF_READ":
798 ((mode & 0x3 )==OF_WRITE)?"OF_WRITE":
799 ((mode & 0x3 )==OF_READWRITE)?"OF_READWRITE":"unknown",
800 ((mode & 0x70 )==OF_SHARE_COMPAT)?"OF_SHARE_COMPAT":
801 ((mode & 0x70 )==OF_SHARE_DENY_NONE)?"OF_SHARE_DENY_NONE":
802 ((mode & 0x70 )==OF_SHARE_DENY_READ)?"OF_SHARE_DENY_READ":
803 ((mode & 0x70 )==OF_SHARE_DENY_WRITE)?"OF_SHARE_DENY_WRITE":
804 ((mode & 0x70 )==OF_SHARE_EXCLUSIVE)?"OF_SHARE_EXCLUSIVE":"unknown",
805 ((mode & OF_PARSE )==OF_PARSE)?"OF_PARSE ":"",
806 ((mode & OF_DELETE )==OF_DELETE)?"OF_DELETE ":"",
807 ((mode & OF_VERIFY )==OF_VERIFY)?"OF_VERIFY ":"",
808 ((mode & OF_SEARCH )==OF_SEARCH)?"OF_SEARCH ":"",
809 ((mode & OF_CANCEL )==OF_CANCEL)?"OF_CANCEL ":"",
810 ((mode & OF_CREATE )==OF_CREATE)?"OF_CREATE ":"",
811 ((mode & OF_PROMPT )==OF_PROMPT)?"OF_PROMPT ":"",
812 ((mode & OF_EXIST )==OF_EXIST)?"OF_EXIST ":"",
813 ((mode & OF_REOPEN )==OF_REOPEN)?"OF_REOPEN ":""
817 ofs->cBytes = sizeof(OFSTRUCT);
818 ofs->nErrCode = 0;
819 if (mode & OF_REOPEN) name = ofs->szPathName;
821 if (!name) {
822 ERR("called with `name' set to NULL ! Please debug.\n");
823 return HFILE_ERROR;
826 TRACE("%s %04x\n", name, mode );
828 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
829 Are there any cases where getting the path here is wrong?
830 Uwe Bonnes 1997 Apr 2 */
831 if (!GetFullPathNameA( name, sizeof(ofs->szPathName),
832 ofs->szPathName, NULL )) goto error;
833 FILE_ConvertOFMode( mode, &access, &sharing );
835 /* OF_PARSE simply fills the structure */
837 if (mode & OF_PARSE)
839 ofs->fFixedDisk = (GetDriveType16( ofs->szPathName[0]-'A' )
840 != DRIVE_REMOVABLE);
841 TRACE("(%s): OF_PARSE, res = '%s'\n",
842 name, ofs->szPathName );
843 return 0;
846 /* OF_CREATE is completely different from all other options, so
847 handle it first */
849 if (mode & OF_CREATE)
851 if ((hFileRet = CreateFileA( name, GENERIC_READ | GENERIC_WRITE,
852 sharing, NULL, CREATE_ALWAYS,
853 FILE_ATTRIBUTE_NORMAL, 0 ))== INVALID_HANDLE_VALUE)
854 goto error;
855 goto success;
858 /* If OF_SEARCH is set, ignore the given path */
860 if ((mode & OF_SEARCH) && !(mode & OF_REOPEN))
862 /* First try the file name as is */
863 if (DOSFS_GetFullName( name, TRUE, &full_name )) goto found;
864 /* Now remove the path */
865 if (name[0] && (name[1] == ':')) name += 2;
866 if ((p = strrchr( name, '\\' ))) name = p + 1;
867 if ((p = strrchr( name, '/' ))) name = p + 1;
868 if (!name[0]) goto not_found;
871 /* Now look for the file */
873 if (!DIR_SearchPath( NULL, name, NULL, &full_name, win32 )) goto not_found;
875 found:
876 TRACE("found %s = %s\n",
877 full_name.long_name, full_name.short_name );
878 lstrcpynA( ofs->szPathName, full_name.short_name,
879 sizeof(ofs->szPathName) );
881 if (mode & OF_SHARE_EXCLUSIVE)
882 /* Some InstallShield version uses OF_SHARE_EXCLUSIVE
883 on the file <tempdir>/_ins0432._mp to determine how
884 far installation has proceeded.
885 _ins0432._mp is an executable and while running the
886 application expects the open with OF_SHARE_ to fail*/
887 /* Probable FIXME:
888 As our loader closes the files after loading the executable,
889 we can't find the running executable with FILE_InUse.
890 The loader should keep the file open, as Windows does that, too.
893 char *last = strrchr(full_name.long_name,'/');
894 if (!last)
895 last = full_name.long_name - 1;
896 if (GetModuleHandle16(last+1))
898 TRACE("Denying shared open for %s\n",full_name.long_name);
899 return HFILE_ERROR;
903 if (mode & OF_DELETE)
905 if (unlink( full_name.long_name ) == -1) goto not_found;
906 TRACE("(%s): OF_DELETE return = OK\n", name);
907 return 1;
910 hFileRet = FILE_CreateFile( full_name.long_name, access, sharing,
911 NULL, OPEN_EXISTING, 0, 0,
912 DRIVE_GetFlags(full_name.drive) & DRIVE_FAIL_READ_ONLY );
913 if (!hFileRet) goto not_found;
915 GetFileTime( hFileRet, NULL, NULL, &filetime );
916 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
917 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
919 if (memcmp( ofs->reserved, filedatetime, sizeof(ofs->reserved) ))
921 CloseHandle( hFileRet );
922 WARN("(%s): OF_VERIFY failed\n", name );
923 /* FIXME: what error here? */
924 SetLastError( ERROR_FILE_NOT_FOUND );
925 goto error;
928 memcpy( ofs->reserved, filedatetime, sizeof(ofs->reserved) );
930 success: /* We get here if the open was successful */
931 TRACE("(%s): OK, return = %d\n", name, hFileRet );
932 if (win32)
934 if (mode & OF_EXIST) /* Return the handle, but close it first */
935 CloseHandle( hFileRet );
937 else
939 hFileRet = Win32HandleToDosFileHandle( hFileRet );
940 if (hFileRet == HFILE_ERROR16) goto error;
941 if (mode & OF_EXIST) /* Return the handle, but close it first */
942 _lclose16( hFileRet );
944 return hFileRet;
946 not_found: /* We get here if the file does not exist */
947 WARN("'%s' not found or sharing violation\n", name );
948 SetLastError( ERROR_FILE_NOT_FOUND );
949 /* fall through */
951 error: /* We get here if there was an error opening the file */
952 ofs->nErrCode = GetLastError();
953 WARN("(%s): return = HFILE_ERROR error= %d\n",
954 name,ofs->nErrCode );
955 return HFILE_ERROR;
959 /***********************************************************************
960 * OpenFile16 (KERNEL.74)
962 HFILE16 WINAPI OpenFile16( LPCSTR name, OFSTRUCT *ofs, UINT16 mode )
964 return FILE_DoOpenFile( name, ofs, mode, FALSE );
968 /***********************************************************************
969 * OpenFile (KERNEL32.396)
971 HFILE WINAPI OpenFile( LPCSTR name, OFSTRUCT *ofs, UINT mode )
973 return FILE_DoOpenFile( name, ofs, mode, TRUE );
977 /***********************************************************************
978 * FILE_InitProcessDosHandles
980 * Allocates the default DOS handles for a process. Called either by
981 * Win32HandleToDosFileHandle below or by the DOSVM stuff.
983 static void FILE_InitProcessDosHandles( void )
985 dos_handles[0] = GetStdHandle(STD_INPUT_HANDLE);
986 dos_handles[1] = GetStdHandle(STD_OUTPUT_HANDLE);
987 dos_handles[2] = GetStdHandle(STD_ERROR_HANDLE);
988 dos_handles[3] = GetStdHandle(STD_ERROR_HANDLE);
989 dos_handles[4] = GetStdHandle(STD_ERROR_HANDLE);
992 /***********************************************************************
993 * Win32HandleToDosFileHandle (KERNEL32.21)
995 * Allocate a DOS handle for a Win32 handle. The Win32 handle is no
996 * longer valid after this function (even on failure).
998 * Note: this is not exactly right, since on Win95 the Win32 handles
999 * are on top of DOS handles and we do it the other way
1000 * around. Should be good enough though.
1002 HFILE WINAPI Win32HandleToDosFileHandle( HANDLE handle )
1004 int i;
1006 if (!handle || (handle == INVALID_HANDLE_VALUE))
1007 return HFILE_ERROR;
1009 for (i = 5; i < DOS_TABLE_SIZE; i++)
1010 if (!dos_handles[i])
1012 dos_handles[i] = handle;
1013 TRACE("Got %d for h32 %d\n", i, handle );
1014 return (HFILE)i;
1016 CloseHandle( handle );
1017 SetLastError( ERROR_TOO_MANY_OPEN_FILES );
1018 return HFILE_ERROR;
1022 /***********************************************************************
1023 * DosFileHandleToWin32Handle (KERNEL32.20)
1025 * Return the Win32 handle for a DOS handle.
1027 * Note: this is not exactly right, since on Win95 the Win32 handles
1028 * are on top of DOS handles and we do it the other way
1029 * around. Should be good enough though.
1031 HANDLE WINAPI DosFileHandleToWin32Handle( HFILE handle )
1033 HFILE16 hfile = (HFILE16)handle;
1034 if (hfile < 5 && !dos_handles[hfile]) FILE_InitProcessDosHandles();
1035 if ((hfile >= DOS_TABLE_SIZE) || !dos_handles[hfile])
1037 SetLastError( ERROR_INVALID_HANDLE );
1038 return INVALID_HANDLE_VALUE;
1040 return dos_handles[hfile];
1044 /***********************************************************************
1045 * DisposeLZ32Handle (KERNEL32.22)
1047 * Note: this is not entirely correct, we should only close the
1048 * 32-bit handle and not the 16-bit one, but we cannot do
1049 * this because of the way our DOS handles are implemented.
1050 * It shouldn't break anything though.
1052 void WINAPI DisposeLZ32Handle( HANDLE handle )
1054 int i;
1056 if (!handle || (handle == INVALID_HANDLE_VALUE)) return;
1058 for (i = 5; i < DOS_TABLE_SIZE; i++)
1059 if (dos_handles[i] == handle)
1061 dos_handles[i] = 0;
1062 CloseHandle( handle );
1063 break;
1068 /***********************************************************************
1069 * FILE_Dup2
1071 * dup2() function for DOS handles.
1073 HFILE16 FILE_Dup2( HFILE16 hFile1, HFILE16 hFile2 )
1075 HANDLE new_handle;
1077 if (hFile1 < 5 && !dos_handles[hFile1]) FILE_InitProcessDosHandles();
1079 if ((hFile1 >= DOS_TABLE_SIZE) || (hFile2 >= DOS_TABLE_SIZE) || !dos_handles[hFile1])
1081 SetLastError( ERROR_INVALID_HANDLE );
1082 return HFILE_ERROR16;
1084 if (hFile2 < 5)
1086 FIXME("stdio handle closed, need proper conversion\n" );
1087 SetLastError( ERROR_INVALID_HANDLE );
1088 return HFILE_ERROR16;
1090 if (!DuplicateHandle( GetCurrentProcess(), dos_handles[hFile1],
1091 GetCurrentProcess(), &new_handle,
1092 0, FALSE, DUPLICATE_SAME_ACCESS ))
1093 return HFILE_ERROR16;
1094 if (dos_handles[hFile2]) CloseHandle( dos_handles[hFile2] );
1095 dos_handles[hFile2] = new_handle;
1096 return hFile2;
1100 /***********************************************************************
1101 * _lclose16 (KERNEL.81)
1103 HFILE16 WINAPI _lclose16( HFILE16 hFile )
1105 if (hFile < 5)
1107 FIXME("stdio handle closed, need proper conversion\n" );
1108 SetLastError( ERROR_INVALID_HANDLE );
1109 return HFILE_ERROR16;
1111 if ((hFile >= DOS_TABLE_SIZE) || !dos_handles[hFile])
1113 SetLastError( ERROR_INVALID_HANDLE );
1114 return HFILE_ERROR16;
1116 TRACE("%d (handle32=%d)\n", hFile, dos_handles[hFile] );
1117 CloseHandle( dos_handles[hFile] );
1118 dos_handles[hFile] = 0;
1119 return 0;
1123 /***********************************************************************
1124 * _lclose (KERNEL32.592)
1126 HFILE WINAPI _lclose( HFILE hFile )
1128 TRACE("handle %d\n", hFile );
1129 return CloseHandle( hFile ) ? 0 : HFILE_ERROR;
1132 /***********************************************************************
1133 * GetOverlappedResult (KERNEL32.360)
1135 * Check the result of an Asynchronous data transfer from a file.
1137 * RETURNS
1138 * TRUE on success
1139 * FALSE on failure
1141 * If successful (and relevant) lpTransfered will hold the number of
1142 * bytes transfered during the async operation.
1144 * BUGS
1146 * Currently only works for WaitCommEvent, ReadFile, WriteFile
1147 * with communications ports.
1150 BOOL WINAPI GetOverlappedResult(
1151 HANDLE hFile, /* [in] handle of file to check on */
1152 LPOVERLAPPED lpOverlapped, /* [in/out] pointer to overlapped */
1153 LPDWORD lpTransferred, /* [in/out] number of bytes transfered */
1154 BOOL bWait /* [in] wait for the transfer to complete ? */
1156 DWORD r;
1158 TRACE("(%d %p %p %x)\n", hFile, lpOverlapped, lpTransferred, bWait);
1160 if(lpOverlapped==NULL)
1162 ERR("lpOverlapped was null\n");
1163 return FALSE;
1165 if(!lpOverlapped->hEvent)
1167 ERR("lpOverlapped->hEvent was null\n");
1168 return FALSE;
1171 do {
1172 TRACE("waiting on %p\n",lpOverlapped);
1173 r = WaitForSingleObjectEx(lpOverlapped->hEvent, bWait?INFINITE:0, TRUE);
1174 TRACE("wait on %p returned %ld\n",lpOverlapped,r);
1175 } while (r==STATUS_USER_APC);
1177 if(lpTransferred)
1178 *lpTransferred = lpOverlapped->InternalHigh;
1180 SetLastError(lpOverlapped->Internal);
1182 return (r==WAIT_OBJECT_0);
1185 /***********************************************************************
1186 * FILE_AsyncResult (INTERNAL)
1188 static int FILE_AsyncResult(HANDLE hAsync, int result)
1190 int r;
1192 SERVER_START_REQ
1194 struct async_result_request *req = server_alloc_req(sizeof *req,0);
1196 req->ov_handle = hAsync;
1197 req->result = result;
1199 r = server_call( REQ_ASYNC_RESULT);
1201 SERVER_END_REQ
1203 return !r;
1206 /***********************************************************************
1207 * FILE_AsyncReadService (INTERNAL)
1209 static void FILE_AsyncReadService(void **args)
1211 LPOVERLAPPED lpOverlapped = (LPOVERLAPPED)args[0];
1212 LPDWORD buffer = (LPDWORD)args[1];
1213 DWORD events = (DWORD)args[2];
1214 int fd, result, r;
1216 TRACE("%p %p %08lx\n", lpOverlapped, buffer, events );
1218 /* if there are no events, it must be a timeout */
1219 if(events==0)
1221 TRACE("read timed out\n");
1222 /* r = STATUS_TIMEOUT; */
1223 r = STATUS_SUCCESS;
1224 goto async_end;
1227 fd = FILE_GetUnixHandle(lpOverlapped->Offset, GENERIC_READ);
1228 if(fd<0)
1230 TRACE("FILE_GetUnixHandle(%ld) failed \n",lpOverlapped->Offset);
1231 r = STATUS_UNSUCCESSFUL;
1232 goto async_end;
1235 /* check to see if the data is ready (non-blocking) */
1236 result = read(fd, &buffer[lpOverlapped->InternalHigh],
1237 lpOverlapped->OffsetHigh - lpOverlapped->InternalHigh);
1238 close(fd);
1240 if ( (result<0) && ((errno == EAGAIN) || (errno == EINTR)))
1242 TRACE("Deferred read %d\n",errno);
1243 r = STATUS_PENDING;
1244 goto async_end;
1247 /* check to see if the transfer is complete */
1248 if(result<0)
1250 TRACE("read returned errno %d\n",errno);
1251 r = STATUS_UNSUCCESSFUL;
1252 goto async_end;
1255 lpOverlapped->InternalHigh += result;
1256 TRACE("read %d more bytes %ld/%ld so far\n",result,lpOverlapped->InternalHigh,lpOverlapped->OffsetHigh);
1258 if(lpOverlapped->InternalHigh < lpOverlapped->OffsetHigh)
1259 r = STATUS_PENDING;
1260 else
1261 r = STATUS_SUCCESS;
1263 async_end:
1264 lpOverlapped->Internal = r;
1265 if ( (r!=STATUS_PENDING)
1266 || (!FILE_AsyncResult( lpOverlapped->InternalHigh, r)))
1268 /* close the handle to the async operation */
1269 if(lpOverlapped->Offset)
1270 CloseHandle(lpOverlapped->Offset);
1271 lpOverlapped->Offset = 0;
1273 NtSetEvent( lpOverlapped->hEvent, NULL );
1274 TRACE("set event flag\n");
1278 /***********************************************************************
1279 * FILE_StartAsyncRead (INTERNAL)
1281 static BOOL FILE_StartAsyncRead( HANDLE hFile, LPOVERLAPPED overlapped, LPVOID buffer, DWORD count)
1283 int r;
1285 SERVER_START_REQ
1287 struct create_async_request *req = server_alloc_req(sizeof *req,0);
1289 req->file_handle = hFile;
1290 req->overlapped = overlapped;
1291 req->buffer = buffer;
1292 req->count = count;
1293 req->func = FILE_AsyncReadService;
1294 req->type = ASYNC_TYPE_READ;
1296 r=server_call( REQ_CREATE_ASYNC );
1298 overlapped->Offset = req->ov_handle;
1300 SERVER_END_REQ
1302 if(!r)
1304 TRACE("ov=%ld IO is pending!!!\n",overlapped->Offset);
1305 SetLastError(ERROR_IO_PENDING);
1308 return !r;
1311 /***********************************************************************
1312 * ReadFile (KERNEL32.577)
1314 BOOL WINAPI ReadFile( HANDLE hFile, LPVOID buffer, DWORD bytesToRead,
1315 LPDWORD bytesRead, LPOVERLAPPED overlapped )
1317 int unix_handle, result;
1319 TRACE("%d %p %ld %p %p\n", hFile, buffer, bytesToRead,
1320 bytesRead, overlapped );
1322 if (bytesRead) *bytesRead = 0; /* Do this before anything else */
1323 if (!bytesToRead) return TRUE;
1325 /* this will only have impact if the overlapped structure is specified */
1326 if ( overlapped )
1328 /* if overlapped, check that there is an event flag */
1329 if ( (overlapped->hEvent == 0) ||
1330 (overlapped->hEvent == INVALID_HANDLE_VALUE) )
1332 return FALSE;
1335 overlapped->Offset = 0;
1336 overlapped->OffsetHigh = bytesToRead;
1337 overlapped->Internal = 0;
1338 overlapped->InternalHigh = 0;
1340 NtResetEvent( overlapped->hEvent, NULL );
1342 if(FILE_StartAsyncRead(hFile, overlapped, buffer, bytesToRead))
1344 overlapped->Internal = STATUS_PENDING;
1347 /* always fail on return, either ERROR_IO_PENDING or other error */
1348 return FALSE;
1351 unix_handle = FILE_GetUnixHandle( hFile, GENERIC_READ );
1352 if (unix_handle == -1) return FALSE;
1354 /* code for synchronous reads */
1355 while ((result = read( unix_handle, buffer, bytesToRead )) == -1)
1357 if ((errno == EAGAIN) || (errno == EINTR)) continue;
1358 if ((errno == EFAULT) && !IsBadWritePtr( buffer, bytesToRead )) continue;
1359 FILE_SetDosError();
1360 break;
1362 close( unix_handle );
1363 if (result == -1) return FALSE;
1364 if (bytesRead) *bytesRead = result;
1365 return TRUE;
1368 /***********************************************************************
1369 * FILE_AsyncWriteService (INTERNAL)
1371 static void FILE_AsyncWriteService(void **args)
1373 LPOVERLAPPED lpOverlapped = (LPOVERLAPPED)args[0];
1374 LPDWORD buffer = (LPDWORD)args[1];
1375 DWORD events = (DWORD)args[2];
1376 int fd, result, r;
1378 TRACE("(%p %p %lx)\n",lpOverlapped,buffer,events);
1380 /* if there are no events, it must be a timeout */
1381 if(events==0)
1383 TRACE("write timed out\n");
1384 r = STATUS_TIMEOUT;
1385 goto async_end;
1388 fd = FILE_GetUnixHandle(lpOverlapped->Offset, GENERIC_WRITE);
1389 if(fd<0)
1391 ERR("FILE_GetUnixHandle(%ld) failed \n",lpOverlapped->Offset);
1392 r = STATUS_UNSUCCESSFUL;
1393 goto async_end;
1396 /* write some data (non-blocking) */
1397 result = write(fd, &buffer[lpOverlapped->InternalHigh],
1398 lpOverlapped->OffsetHigh-lpOverlapped->InternalHigh);
1399 close(fd);
1401 if ( (result<0) && ((errno == EAGAIN) || (errno == EINTR)))
1403 r = STATUS_PENDING;
1404 goto async_end;
1407 /* check to see if the transfer is complete */
1408 if(result<0)
1410 r = STATUS_UNSUCCESSFUL;
1411 goto async_end;
1414 lpOverlapped->InternalHigh += result;
1416 if(lpOverlapped->InternalHigh < lpOverlapped->OffsetHigh)
1417 r = STATUS_PENDING;
1418 else
1419 r = STATUS_SUCCESS;
1421 async_end:
1422 lpOverlapped->Internal = r;
1423 if ( (r!=STATUS_PENDING)
1424 || (!FILE_AsyncResult( lpOverlapped->Offset, r)))
1426 /* close the handle to the async operation */
1427 CloseHandle(lpOverlapped->Offset);
1428 lpOverlapped->Offset = 0;
1430 NtSetEvent( lpOverlapped->hEvent, NULL );
1434 /***********************************************************************
1435 * FILE_StartAsyncWrite (INTERNAL)
1437 static BOOL FILE_StartAsyncWrite(HANDLE hFile, LPOVERLAPPED overlapped, LPCVOID buffer,DWORD count)
1439 int r;
1441 SERVER_START_REQ
1443 struct create_async_request *req = server_alloc_req( sizeof(*req), 0 );
1445 req->file_handle = hFile;
1446 req->buffer = (LPVOID)buffer;
1447 req->overlapped = overlapped;
1448 req->count = 0;
1449 req->func = FILE_AsyncWriteService;
1450 req->type = ASYNC_TYPE_WRITE;
1452 r = server_call( REQ_CREATE_ASYNC );
1454 overlapped->Offset = req->ov_handle;
1456 SERVER_END_REQ
1458 if(!r)
1460 SetLastError(ERROR_IO_PENDING);
1463 return !r;
1466 /***********************************************************************
1467 * WriteFile (KERNEL32.738)
1469 BOOL WINAPI WriteFile( HANDLE hFile, LPCVOID buffer, DWORD bytesToWrite,
1470 LPDWORD bytesWritten, LPOVERLAPPED overlapped )
1472 int unix_handle, result;
1474 TRACE("%d %p %ld %p %p\n", hFile, buffer, bytesToWrite,
1475 bytesWritten, overlapped );
1477 if (bytesWritten) *bytesWritten = 0; /* Do this before anything else */
1478 if (!bytesToWrite) return TRUE;
1480 /* this will only have impact if the overlappd structure is specified */
1481 if ( overlapped )
1483 if ( (overlapped->hEvent == 0) ||
1484 (overlapped->hEvent == INVALID_HANDLE_VALUE) )
1485 return FALSE;
1487 overlapped->Offset = 0;
1488 overlapped->OffsetHigh = bytesToWrite;
1489 overlapped->Internal = 0;
1490 overlapped->InternalHigh = 0;
1492 NtResetEvent( overlapped->hEvent, NULL );
1494 if (FILE_StartAsyncWrite(hFile, overlapped, buffer, bytesToWrite))
1496 overlapped->Internal = STATUS_PENDING;
1499 /* always fail on return, either ERROR_IO_PENDING or other error */
1500 return FALSE;
1503 unix_handle = FILE_GetUnixHandle( hFile, GENERIC_WRITE );
1504 if (unix_handle == -1) return FALSE;
1506 /* synchronous file write */
1507 while ((result = write( unix_handle, buffer, bytesToWrite )) == -1)
1509 if ((errno == EAGAIN) || (errno == EINTR)) continue;
1510 if ((errno == EFAULT) && !IsBadReadPtr( buffer, bytesToWrite )) continue;
1511 if (errno == ENOSPC)
1512 SetLastError( ERROR_DISK_FULL );
1513 else
1514 FILE_SetDosError();
1515 break;
1517 close( unix_handle );
1518 if (result == -1) return FALSE;
1519 if (bytesWritten) *bytesWritten = result;
1520 return TRUE;
1524 /***********************************************************************
1525 * WIN16_hread
1527 LONG WINAPI WIN16_hread( HFILE16 hFile, SEGPTR buffer, LONG count )
1529 LONG maxlen;
1531 TRACE("%d %08lx %ld\n",
1532 hFile, (DWORD)buffer, count );
1534 /* Some programs pass a count larger than the allocated buffer */
1535 maxlen = GetSelectorLimit16( SELECTOROF(buffer) ) - OFFSETOF(buffer) + 1;
1536 if (count > maxlen) count = maxlen;
1537 return _lread(DosFileHandleToWin32Handle(hFile), MapSL(buffer), count );
1541 /***********************************************************************
1542 * WIN16_lread
1544 UINT16 WINAPI WIN16_lread( HFILE16 hFile, SEGPTR buffer, UINT16 count )
1546 return (UINT16)WIN16_hread( hFile, buffer, (LONG)count );
1550 /***********************************************************************
1551 * _lread (KERNEL32.596)
1553 UINT WINAPI _lread( HFILE handle, LPVOID buffer, UINT count )
1555 DWORD result;
1556 if (!ReadFile( handle, buffer, count, &result, NULL )) return -1;
1557 return result;
1561 /***********************************************************************
1562 * _lread16 (KERNEL.82)
1564 UINT16 WINAPI _lread16( HFILE16 hFile, LPVOID buffer, UINT16 count )
1566 return (UINT16)_lread(DosFileHandleToWin32Handle(hFile), buffer, (LONG)count );
1570 /***********************************************************************
1571 * _lcreat16 (KERNEL.83)
1573 HFILE16 WINAPI _lcreat16( LPCSTR path, INT16 attr )
1575 return Win32HandleToDosFileHandle( _lcreat( path, attr ) );
1579 /***********************************************************************
1580 * _lcreat (KERNEL32.593)
1582 HFILE WINAPI _lcreat( LPCSTR path, INT attr )
1584 /* Mask off all flags not explicitly allowed by the doc */
1585 attr &= FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
1586 TRACE("%s %02x\n", path, attr );
1587 return CreateFileA( path, GENERIC_READ | GENERIC_WRITE,
1588 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
1589 CREATE_ALWAYS, attr, 0 );
1593 /***********************************************************************
1594 * SetFilePointer (KERNEL32.492)
1596 DWORD WINAPI SetFilePointer( HANDLE hFile, LONG distance, LONG *highword,
1597 DWORD method )
1599 DWORD ret = 0xffffffff;
1601 if (highword &&
1602 ((distance >= 0 && *highword != 0) || (distance < 0 && *highword != -1)))
1604 FIXME("64-bit offsets not supported yet\n"
1605 "SetFilePointer(%08x,%08lx,%08lx,%08lx)\n",
1606 hFile,distance,*highword,method);
1607 SetLastError( ERROR_INVALID_PARAMETER );
1608 return ret;
1610 TRACE("handle %d offset %ld origin %ld\n",
1611 hFile, distance, method );
1613 SERVER_START_REQ
1615 struct set_file_pointer_request *req = server_alloc_req( sizeof(*req), 0 );
1616 req->handle = hFile;
1617 req->low = distance;
1618 req->high = highword ? *highword : (distance >= 0) ? 0 : -1;
1619 /* FIXME: assumes 1:1 mapping between Windows and Unix seek constants */
1620 req->whence = method;
1621 SetLastError( 0 );
1622 if (!server_call( REQ_SET_FILE_POINTER ))
1624 ret = req->new_low;
1625 if (highword) *highword = req->new_high;
1628 SERVER_END_REQ;
1629 return ret;
1633 /***********************************************************************
1634 * _llseek16 (KERNEL.84)
1636 * FIXME:
1637 * Seeking before the start of the file should be allowed for _llseek16,
1638 * but cause subsequent I/O operations to fail (cf. interrupt list)
1641 LONG WINAPI _llseek16( HFILE16 hFile, LONG lOffset, INT16 nOrigin )
1643 return SetFilePointer( DosFileHandleToWin32Handle(hFile), lOffset, NULL, nOrigin );
1647 /***********************************************************************
1648 * _llseek (KERNEL32.594)
1650 LONG WINAPI _llseek( HFILE hFile, LONG lOffset, INT nOrigin )
1652 return SetFilePointer( hFile, lOffset, NULL, nOrigin );
1656 /***********************************************************************
1657 * _lopen16 (KERNEL.85)
1659 HFILE16 WINAPI _lopen16( LPCSTR path, INT16 mode )
1661 return Win32HandleToDosFileHandle( _lopen( path, mode ) );
1665 /***********************************************************************
1666 * _lopen (KERNEL32.595)
1668 HFILE WINAPI _lopen( LPCSTR path, INT mode )
1670 DWORD access, sharing;
1672 TRACE("('%s',%04x)\n", path, mode );
1673 FILE_ConvertOFMode( mode, &access, &sharing );
1674 return CreateFileA( path, access, sharing, NULL, OPEN_EXISTING, 0, 0 );
1678 /***********************************************************************
1679 * _lwrite16 (KERNEL.86)
1681 UINT16 WINAPI _lwrite16( HFILE16 hFile, LPCSTR buffer, UINT16 count )
1683 return (UINT16)_hwrite( DosFileHandleToWin32Handle(hFile), buffer, (LONG)count );
1686 /***********************************************************************
1687 * _lwrite (KERNEL32.761)
1689 UINT WINAPI _lwrite( HFILE hFile, LPCSTR buffer, UINT count )
1691 return (UINT)_hwrite( hFile, buffer, (LONG)count );
1695 /***********************************************************************
1696 * _hread16 (KERNEL.349)
1698 LONG WINAPI _hread16( HFILE16 hFile, LPVOID buffer, LONG count)
1700 return _lread( DosFileHandleToWin32Handle(hFile), buffer, count );
1704 /***********************************************************************
1705 * _hread (KERNEL32.590)
1707 LONG WINAPI _hread( HFILE hFile, LPVOID buffer, LONG count)
1709 return _lread( hFile, buffer, count );
1713 /***********************************************************************
1714 * _hwrite16 (KERNEL.350)
1716 LONG WINAPI _hwrite16( HFILE16 hFile, LPCSTR buffer, LONG count )
1718 return _hwrite( DosFileHandleToWin32Handle(hFile), buffer, count );
1722 /***********************************************************************
1723 * _hwrite (KERNEL32.591)
1725 * experimentation yields that _lwrite:
1726 * o truncates the file at the current position with
1727 * a 0 len write
1728 * o returns 0 on a 0 length write
1729 * o works with console handles
1732 LONG WINAPI _hwrite( HFILE handle, LPCSTR buffer, LONG count )
1734 DWORD result;
1736 TRACE("%d %p %ld\n", handle, buffer, count );
1738 if (!count)
1740 /* Expand or truncate at current position */
1741 if (!SetEndOfFile( handle )) return HFILE_ERROR;
1742 return 0;
1744 if (!WriteFile( handle, buffer, count, &result, NULL ))
1745 return HFILE_ERROR;
1746 return result;
1750 /***********************************************************************
1751 * SetHandleCount16 (KERNEL.199)
1753 UINT16 WINAPI SetHandleCount16( UINT16 count )
1755 return SetHandleCount( count );
1759 /*************************************************************************
1760 * SetHandleCount (KERNEL32.494)
1762 UINT WINAPI SetHandleCount( UINT count )
1764 return min( 256, count );
1768 /***********************************************************************
1769 * FlushFileBuffers (KERNEL32.133)
1771 BOOL WINAPI FlushFileBuffers( HANDLE hFile )
1773 BOOL ret;
1774 SERVER_START_REQ
1776 struct flush_file_request *req = server_alloc_req( sizeof(*req), 0 );
1777 req->handle = hFile;
1778 ret = !server_call( REQ_FLUSH_FILE );
1780 SERVER_END_REQ;
1781 return ret;
1785 /**************************************************************************
1786 * SetEndOfFile (KERNEL32.483)
1788 BOOL WINAPI SetEndOfFile( HANDLE hFile )
1790 BOOL ret;
1791 SERVER_START_REQ
1793 struct truncate_file_request *req = server_alloc_req( sizeof(*req), 0 );
1794 req->handle = hFile;
1795 ret = !server_call( REQ_TRUNCATE_FILE );
1797 SERVER_END_REQ;
1798 return ret;
1802 /***********************************************************************
1803 * DeleteFile16 (KERNEL.146)
1805 BOOL16 WINAPI DeleteFile16( LPCSTR path )
1807 return DeleteFileA( path );
1811 /***********************************************************************
1812 * DeleteFileA (KERNEL32.71)
1814 BOOL WINAPI DeleteFileA( LPCSTR path )
1816 DOS_FULL_NAME full_name;
1818 TRACE("'%s'\n", path );
1820 if (!*path)
1822 ERR("Empty path passed\n");
1823 return FALSE;
1825 if (DOSFS_GetDevice( path ))
1827 WARN("cannot remove DOS device '%s'!\n", path);
1828 SetLastError( ERROR_FILE_NOT_FOUND );
1829 return FALSE;
1832 if (!DOSFS_GetFullName( path, TRUE, &full_name )) return FALSE;
1833 if (unlink( full_name.long_name ) == -1)
1835 FILE_SetDosError();
1836 return FALSE;
1838 return TRUE;
1842 /***********************************************************************
1843 * DeleteFileW (KERNEL32.72)
1845 BOOL WINAPI DeleteFileW( LPCWSTR path )
1847 LPSTR xpath = HEAP_strdupWtoA( GetProcessHeap(), 0, path );
1848 BOOL ret = DeleteFileA( xpath );
1849 HeapFree( GetProcessHeap(), 0, xpath );
1850 return ret;
1854 /***********************************************************************
1855 * GetFileType (KERNEL32.222)
1857 DWORD WINAPI GetFileType( HANDLE hFile )
1859 DWORD ret = FILE_TYPE_UNKNOWN;
1860 SERVER_START_REQ
1862 struct get_file_info_request *req = server_alloc_req( sizeof(*req), 0 );
1863 req->handle = hFile;
1864 if (!server_call( REQ_GET_FILE_INFO )) ret = req->type;
1866 SERVER_END_REQ;
1867 return ret;
1871 /**************************************************************************
1872 * MoveFileExA (KERNEL32.???)
1874 BOOL WINAPI MoveFileExA( LPCSTR fn1, LPCSTR fn2, DWORD flag )
1876 DOS_FULL_NAME full_name1, full_name2;
1878 TRACE("(%s,%s,%04lx)\n", fn1, fn2, flag);
1880 if (!DOSFS_GetFullName( fn1, TRUE, &full_name1 )) return FALSE;
1882 if (fn2) /* !fn2 means delete fn1 */
1884 if (DOSFS_GetFullName( fn2, TRUE, &full_name2 ))
1886 /* target exists, check if we may overwrite */
1887 if (!(flag & MOVEFILE_REPLACE_EXISTING))
1889 /* FIXME: Use right error code */
1890 SetLastError( ERROR_ACCESS_DENIED );
1891 return FALSE;
1894 else if (!DOSFS_GetFullName( fn2, FALSE, &full_name2 )) return FALSE;
1896 /* Source name and target path are valid */
1898 if (flag & MOVEFILE_DELAY_UNTIL_REBOOT)
1900 /* FIXME: (bon@elektron.ikp.physik.th-darmstadt.de 970706)
1901 Perhaps we should queue these command and execute it
1902 when exiting... What about using on_exit(2)
1904 FIXME("Please move existing file '%s' to file '%s' when Wine has finished\n",
1905 full_name1.long_name, full_name2.long_name);
1906 return TRUE;
1909 if (full_name1.drive != full_name2.drive)
1911 /* use copy, if allowed */
1912 if (!(flag & MOVEFILE_COPY_ALLOWED))
1914 /* FIXME: Use right error code */
1915 SetLastError( ERROR_FILE_EXISTS );
1916 return FALSE;
1918 return CopyFileA( fn1, fn2, !(flag & MOVEFILE_REPLACE_EXISTING) );
1920 if (rename( full_name1.long_name, full_name2.long_name ) == -1)
1922 FILE_SetDosError();
1923 return FALSE;
1925 return TRUE;
1927 else /* fn2 == NULL means delete source */
1929 if (flag & MOVEFILE_DELAY_UNTIL_REBOOT)
1931 if (flag & MOVEFILE_COPY_ALLOWED) {
1932 WARN("Illegal flag\n");
1933 SetLastError( ERROR_GEN_FAILURE );
1934 return FALSE;
1936 /* FIXME: (bon@elektron.ikp.physik.th-darmstadt.de 970706)
1937 Perhaps we should queue these command and execute it
1938 when exiting... What about using on_exit(2)
1940 FIXME("Please delete file '%s' when Wine has finished\n",
1941 full_name1.long_name);
1942 return TRUE;
1945 if (unlink( full_name1.long_name ) == -1)
1947 FILE_SetDosError();
1948 return FALSE;
1950 return TRUE; /* successfully deleted */
1954 /**************************************************************************
1955 * MoveFileExW (KERNEL32.???)
1957 BOOL WINAPI MoveFileExW( LPCWSTR fn1, LPCWSTR fn2, DWORD flag )
1959 LPSTR afn1 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn1 );
1960 LPSTR afn2 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn2 );
1961 BOOL res = MoveFileExA( afn1, afn2, flag );
1962 HeapFree( GetProcessHeap(), 0, afn1 );
1963 HeapFree( GetProcessHeap(), 0, afn2 );
1964 return res;
1968 /**************************************************************************
1969 * MoveFileA (KERNEL32.387)
1971 * Move file or directory
1973 BOOL WINAPI MoveFileA( LPCSTR fn1, LPCSTR fn2 )
1975 DOS_FULL_NAME full_name1, full_name2;
1976 struct stat fstat;
1978 TRACE("(%s,%s)\n", fn1, fn2 );
1980 if (!DOSFS_GetFullName( fn1, TRUE, &full_name1 )) return FALSE;
1981 if (DOSFS_GetFullName( fn2, TRUE, &full_name2 )) {
1982 /* The new name must not already exist */
1983 SetLastError(ERROR_ALREADY_EXISTS);
1984 return FALSE;
1986 if (!DOSFS_GetFullName( fn2, FALSE, &full_name2 )) return FALSE;
1988 if (full_name1.drive == full_name2.drive) /* move */
1989 if (rename( full_name1.long_name, full_name2.long_name ) == -1)
1991 FILE_SetDosError();
1992 return FALSE;
1994 else return TRUE;
1995 else /*copy */ {
1996 if (stat( full_name1.long_name, &fstat ))
1998 WARN("Invalid source file %s\n",
1999 full_name1.long_name);
2000 FILE_SetDosError();
2001 return FALSE;
2003 if (S_ISDIR(fstat.st_mode)) {
2004 /* No Move for directories across file systems */
2005 /* FIXME: Use right error code */
2006 SetLastError( ERROR_GEN_FAILURE );
2007 return FALSE;
2009 else
2010 return CopyFileA(fn1, fn2, TRUE); /*fail, if exist */
2015 /**************************************************************************
2016 * MoveFileW (KERNEL32.390)
2018 BOOL WINAPI MoveFileW( LPCWSTR fn1, LPCWSTR fn2 )
2020 LPSTR afn1 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn1 );
2021 LPSTR afn2 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn2 );
2022 BOOL res = MoveFileA( afn1, afn2 );
2023 HeapFree( GetProcessHeap(), 0, afn1 );
2024 HeapFree( GetProcessHeap(), 0, afn2 );
2025 return res;
2029 /**************************************************************************
2030 * CopyFileA (KERNEL32.36)
2032 BOOL WINAPI CopyFileA( LPCSTR source, LPCSTR dest, BOOL fail_if_exists )
2034 HFILE h1, h2;
2035 BY_HANDLE_FILE_INFORMATION info;
2036 UINT count;
2037 BOOL ret = FALSE;
2038 int mode;
2039 char buffer[2048];
2041 if ((h1 = _lopen( source, OF_READ )) == HFILE_ERROR) return FALSE;
2042 if (!GetFileInformationByHandle( h1, &info ))
2044 CloseHandle( h1 );
2045 return FALSE;
2047 mode = (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY) ? 0444 : 0666;
2048 if ((h2 = CreateFileA( dest, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
2049 fail_if_exists ? CREATE_NEW : CREATE_ALWAYS,
2050 info.dwFileAttributes, h1 )) == INVALID_HANDLE_VALUE)
2052 CloseHandle( h1 );
2053 return FALSE;
2055 while ((count = _lread( h1, buffer, sizeof(buffer) )) > 0)
2057 char *p = buffer;
2058 while (count > 0)
2060 INT res = _lwrite( h2, p, count );
2061 if (res <= 0) goto done;
2062 p += res;
2063 count -= res;
2066 ret = TRUE;
2067 done:
2068 CloseHandle( h1 );
2069 CloseHandle( h2 );
2070 return ret;
2074 /**************************************************************************
2075 * CopyFileW (KERNEL32.37)
2077 BOOL WINAPI CopyFileW( LPCWSTR source, LPCWSTR dest, BOOL fail_if_exists)
2079 LPSTR sourceA = HEAP_strdupWtoA( GetProcessHeap(), 0, source );
2080 LPSTR destA = HEAP_strdupWtoA( GetProcessHeap(), 0, dest );
2081 BOOL ret = CopyFileA( sourceA, destA, fail_if_exists );
2082 HeapFree( GetProcessHeap(), 0, sourceA );
2083 HeapFree( GetProcessHeap(), 0, destA );
2084 return ret;
2088 /**************************************************************************
2089 * CopyFileExA (KERNEL32.858)
2091 * This implementation ignores most of the extra parameters passed-in into
2092 * the "ex" version of the method and calls the CopyFile method.
2093 * It will have to be fixed eventually.
2095 BOOL WINAPI CopyFileExA(LPCSTR sourceFilename,
2096 LPCSTR destFilename,
2097 LPPROGRESS_ROUTINE progressRoutine,
2098 LPVOID appData,
2099 LPBOOL cancelFlagPointer,
2100 DWORD copyFlags)
2102 BOOL failIfExists = FALSE;
2105 * Interpret the only flag that CopyFile can interpret.
2107 if ( (copyFlags & COPY_FILE_FAIL_IF_EXISTS) != 0)
2109 failIfExists = TRUE;
2112 return CopyFileA(sourceFilename, destFilename, failIfExists);
2115 /**************************************************************************
2116 * CopyFileExW (KERNEL32.859)
2118 BOOL WINAPI CopyFileExW(LPCWSTR sourceFilename,
2119 LPCWSTR destFilename,
2120 LPPROGRESS_ROUTINE progressRoutine,
2121 LPVOID appData,
2122 LPBOOL cancelFlagPointer,
2123 DWORD copyFlags)
2125 LPSTR sourceA = HEAP_strdupWtoA( GetProcessHeap(), 0, sourceFilename );
2126 LPSTR destA = HEAP_strdupWtoA( GetProcessHeap(), 0, destFilename );
2128 BOOL ret = CopyFileExA(sourceA,
2129 destA,
2130 progressRoutine,
2131 appData,
2132 cancelFlagPointer,
2133 copyFlags);
2135 HeapFree( GetProcessHeap(), 0, sourceA );
2136 HeapFree( GetProcessHeap(), 0, destA );
2138 return ret;
2142 /***********************************************************************
2143 * SetFileTime (KERNEL32.650)
2145 BOOL WINAPI SetFileTime( HANDLE hFile,
2146 const FILETIME *lpCreationTime,
2147 const FILETIME *lpLastAccessTime,
2148 const FILETIME *lpLastWriteTime )
2150 BOOL ret;
2151 SERVER_START_REQ
2153 struct set_file_time_request *req = server_alloc_req( sizeof(*req), 0 );
2154 req->handle = hFile;
2155 if (lpLastAccessTime)
2156 RtlTimeToSecondsSince1970( lpLastAccessTime, (DWORD *)&req->access_time );
2157 else
2158 req->access_time = 0; /* FIXME */
2159 if (lpLastWriteTime)
2160 RtlTimeToSecondsSince1970( lpLastWriteTime, (DWORD *)&req->write_time );
2161 else
2162 req->write_time = 0; /* FIXME */
2163 ret = !server_call( REQ_SET_FILE_TIME );
2165 SERVER_END_REQ;
2166 return ret;
2170 /**************************************************************************
2171 * LockFile (KERNEL32.511)
2173 BOOL WINAPI LockFile( HANDLE hFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh,
2174 DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh )
2176 BOOL ret;
2177 SERVER_START_REQ
2179 struct lock_file_request *req = server_alloc_req( sizeof(*req), 0 );
2181 req->handle = hFile;
2182 req->offset_low = dwFileOffsetLow;
2183 req->offset_high = dwFileOffsetHigh;
2184 req->count_low = nNumberOfBytesToLockLow;
2185 req->count_high = nNumberOfBytesToLockHigh;
2186 ret = !server_call( REQ_LOCK_FILE );
2188 SERVER_END_REQ;
2189 return ret;
2192 /**************************************************************************
2193 * LockFileEx [KERNEL32.512]
2195 * Locks a byte range within an open file for shared or exclusive access.
2197 * RETURNS
2198 * success: TRUE
2199 * failure: FALSE
2201 * NOTES
2202 * Per Microsoft docs, the third parameter (reserved) must be set to 0.
2204 BOOL WINAPI LockFileEx( HANDLE hFile, DWORD flags, DWORD reserved,
2205 DWORD nNumberOfBytesToLockLow, DWORD nNumberOfBytesToLockHigh,
2206 LPOVERLAPPED pOverlapped )
2208 FIXME("hFile=%d,flags=%ld,reserved=%ld,lowbytes=%ld,highbytes=%ld,overlapped=%p: stub.\n",
2209 hFile, flags, reserved, nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh,
2210 pOverlapped);
2211 if (reserved == 0)
2212 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2213 else
2215 ERR("reserved == %ld: Supposed to be 0??\n", reserved);
2216 SetLastError(ERROR_INVALID_PARAMETER);
2219 return FALSE;
2223 /**************************************************************************
2224 * UnlockFile (KERNEL32.703)
2226 BOOL WINAPI UnlockFile( HANDLE hFile, DWORD dwFileOffsetLow, DWORD dwFileOffsetHigh,
2227 DWORD nNumberOfBytesToUnlockLow, DWORD nNumberOfBytesToUnlockHigh )
2229 BOOL ret;
2230 SERVER_START_REQ
2232 struct unlock_file_request *req = server_alloc_req( sizeof(*req), 0 );
2234 req->handle = hFile;
2235 req->offset_low = dwFileOffsetLow;
2236 req->offset_high = dwFileOffsetHigh;
2237 req->count_low = nNumberOfBytesToUnlockLow;
2238 req->count_high = nNumberOfBytesToUnlockHigh;
2239 ret = !server_call( REQ_UNLOCK_FILE );
2241 SERVER_END_REQ;
2242 return ret;
2246 /**************************************************************************
2247 * UnlockFileEx (KERNEL32.705)
2249 BOOL WINAPI UnlockFileEx(
2250 HFILE hFile,
2251 DWORD dwReserved,
2252 DWORD nNumberOfBytesToUnlockLow,
2253 DWORD nNumberOfBytesToUnlockHigh,
2254 LPOVERLAPPED lpOverlapped
2257 FIXME("hFile=%d,reserved=%ld,lowbytes=%ld,highbytes=%ld,overlapped=%p: stub.\n",
2258 hFile, dwReserved, nNumberOfBytesToUnlockLow, nNumberOfBytesToUnlockHigh,
2259 lpOverlapped);
2260 if (dwReserved == 0)
2261 SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
2262 else
2264 ERR("reserved == %ld: Supposed to be 0??\n", dwReserved);
2265 SetLastError(ERROR_INVALID_PARAMETER);
2268 return FALSE;
2272 #if 0
2274 struct DOS_FILE_LOCK {
2275 struct DOS_FILE_LOCK * next;
2276 DWORD base;
2277 DWORD len;
2278 DWORD processId;
2279 FILE_OBJECT * dos_file;
2280 /* char * unix_name;*/
2283 typedef struct DOS_FILE_LOCK DOS_FILE_LOCK;
2285 static DOS_FILE_LOCK *locks = NULL;
2286 static void DOS_RemoveFileLocks(FILE_OBJECT *file);
2289 /* Locks need to be mirrored because unix file locking is based
2290 * on the pid. Inside of wine there can be multiple WINE processes
2291 * that share the same unix pid.
2292 * Read's and writes should check these locks also - not sure
2293 * how critical that is at this point (FIXME).
2296 static BOOL DOS_AddLock(FILE_OBJECT *file, struct flock *f)
2298 DOS_FILE_LOCK *curr;
2299 DWORD processId;
2301 processId = GetCurrentProcessId();
2303 /* check if lock overlaps a current lock for the same file */
2304 #if 0
2305 for (curr = locks; curr; curr = curr->next) {
2306 if (strcmp(curr->unix_name, file->unix_name) == 0) {
2307 if ((f->l_start == curr->base) && (f->l_len == curr->len))
2308 return TRUE;/* region is identic */
2309 if ((f->l_start < (curr->base + curr->len)) &&
2310 ((f->l_start + f->l_len) > curr->base)) {
2311 /* region overlaps */
2312 return FALSE;
2316 #endif
2318 curr = HeapAlloc( GetProcessHeap(), 0, sizeof(DOS_FILE_LOCK) );
2319 curr->processId = GetCurrentProcessId();
2320 curr->base = f->l_start;
2321 curr->len = f->l_len;
2322 /* curr->unix_name = HEAP_strdupA( GetProcessHeap(), 0, file->unix_name);*/
2323 curr->next = locks;
2324 curr->dos_file = file;
2325 locks = curr;
2326 return TRUE;
2329 static void DOS_RemoveFileLocks(FILE_OBJECT *file)
2331 DWORD processId;
2332 DOS_FILE_LOCK **curr;
2333 DOS_FILE_LOCK *rem;
2335 processId = GetCurrentProcessId();
2336 curr = &locks;
2337 while (*curr) {
2338 if ((*curr)->dos_file == file) {
2339 rem = *curr;
2340 *curr = (*curr)->next;
2341 /* HeapFree( GetProcessHeap(), 0, rem->unix_name );*/
2342 HeapFree( GetProcessHeap(), 0, rem );
2344 else
2345 curr = &(*curr)->next;
2349 static BOOL DOS_RemoveLock(FILE_OBJECT *file, struct flock *f)
2351 DWORD processId;
2352 DOS_FILE_LOCK **curr;
2353 DOS_FILE_LOCK *rem;
2355 processId = GetCurrentProcessId();
2356 for (curr = &locks; *curr; curr = &(*curr)->next) {
2357 if ((*curr)->processId == processId &&
2358 (*curr)->dos_file == file &&
2359 (*curr)->base == f->l_start &&
2360 (*curr)->len == f->l_len) {
2361 /* this is the same lock */
2362 rem = *curr;
2363 *curr = (*curr)->next;
2364 /* HeapFree( GetProcessHeap(), 0, rem->unix_name );*/
2365 HeapFree( GetProcessHeap(), 0, rem );
2366 return TRUE;
2369 /* no matching lock found */
2370 return FALSE;
2374 /**************************************************************************
2375 * LockFile (KERNEL32.511)
2377 BOOL WINAPI LockFile(
2378 HFILE hFile,DWORD dwFileOffsetLow,DWORD dwFileOffsetHigh,
2379 DWORD nNumberOfBytesToLockLow,DWORD nNumberOfBytesToLockHigh )
2381 struct flock f;
2382 FILE_OBJECT *file;
2384 TRACE("handle %d offsetlow=%ld offsethigh=%ld nbyteslow=%ld nbyteshigh=%ld\n",
2385 hFile, dwFileOffsetLow, dwFileOffsetHigh,
2386 nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh);
2388 if (dwFileOffsetHigh || nNumberOfBytesToLockHigh) {
2389 FIXME("Unimplemented bytes > 32bits\n");
2390 return FALSE;
2393 f.l_start = dwFileOffsetLow;
2394 f.l_len = nNumberOfBytesToLockLow;
2395 f.l_whence = SEEK_SET;
2396 f.l_pid = 0;
2397 f.l_type = F_WRLCK;
2399 if (!(file = FILE_GetFile(hFile,0,NULL))) return FALSE;
2401 /* shadow locks internally */
2402 if (!DOS_AddLock(file, &f)) {
2403 SetLastError( ERROR_LOCK_VIOLATION );
2404 return FALSE;
2407 /* FIXME: Unix locking commented out for now, doesn't work with Excel */
2408 #ifdef USE_UNIX_LOCKS
2409 if (fcntl(file->unix_handle, F_SETLK, &f) == -1) {
2410 if (errno == EACCES || errno == EAGAIN) {
2411 SetLastError( ERROR_LOCK_VIOLATION );
2413 else {
2414 FILE_SetDosError();
2416 /* remove our internal copy of the lock */
2417 DOS_RemoveLock(file, &f);
2418 return FALSE;
2420 #endif
2421 return TRUE;
2425 /**************************************************************************
2426 * UnlockFile (KERNEL32.703)
2428 BOOL WINAPI UnlockFile(
2429 HFILE hFile,DWORD dwFileOffsetLow,DWORD dwFileOffsetHigh,
2430 DWORD nNumberOfBytesToUnlockLow,DWORD nNumberOfBytesToUnlockHigh )
2432 FILE_OBJECT *file;
2433 struct flock f;
2435 TRACE("handle %d offsetlow=%ld offsethigh=%ld nbyteslow=%ld nbyteshigh=%ld\n",
2436 hFile, dwFileOffsetLow, dwFileOffsetHigh,
2437 nNumberOfBytesToUnlockLow, nNumberOfBytesToUnlockHigh);
2439 if (dwFileOffsetHigh || nNumberOfBytesToUnlockHigh) {
2440 WARN("Unimplemented bytes > 32bits\n");
2441 return FALSE;
2444 f.l_start = dwFileOffsetLow;
2445 f.l_len = nNumberOfBytesToUnlockLow;
2446 f.l_whence = SEEK_SET;
2447 f.l_pid = 0;
2448 f.l_type = F_UNLCK;
2450 if (!(file = FILE_GetFile(hFile,0,NULL))) return FALSE;
2452 DOS_RemoveLock(file, &f); /* ok if fails - may be another wine */
2454 /* FIXME: Unix locking commented out for now, doesn't work with Excel */
2455 #ifdef USE_UNIX_LOCKS
2456 if (fcntl(file->unix_handle, F_SETLK, &f) == -1) {
2457 FILE_SetDosError();
2458 return FALSE;
2460 #endif
2461 return TRUE;
2463 #endif
2465 /**************************************************************************
2466 * GetFileAttributesExA [KERNEL32.874]
2468 BOOL WINAPI GetFileAttributesExA(
2469 LPCSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId,
2470 LPVOID lpFileInformation)
2472 DOS_FULL_NAME full_name;
2473 BY_HANDLE_FILE_INFORMATION info;
2475 if (lpFileName == NULL) return FALSE;
2476 if (lpFileInformation == NULL) return FALSE;
2478 if (fInfoLevelId == GetFileExInfoStandard) {
2479 LPWIN32_FILE_ATTRIBUTE_DATA lpFad =
2480 (LPWIN32_FILE_ATTRIBUTE_DATA) lpFileInformation;
2481 if (!DOSFS_GetFullName( lpFileName, TRUE, &full_name )) return FALSE;
2482 if (!FILE_Stat( full_name.long_name, &info )) return FALSE;
2484 lpFad->dwFileAttributes = info.dwFileAttributes;
2485 lpFad->ftCreationTime = info.ftCreationTime;
2486 lpFad->ftLastAccessTime = info.ftLastAccessTime;
2487 lpFad->ftLastWriteTime = info.ftLastWriteTime;
2488 lpFad->nFileSizeHigh = info.nFileSizeHigh;
2489 lpFad->nFileSizeLow = info.nFileSizeLow;
2491 else {
2492 FIXME("invalid info level %d!\n", fInfoLevelId);
2493 return FALSE;
2496 return TRUE;
2500 /**************************************************************************
2501 * GetFileAttributesExW [KERNEL32.875]
2503 BOOL WINAPI GetFileAttributesExW(
2504 LPCWSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId,
2505 LPVOID lpFileInformation)
2507 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, lpFileName );
2508 BOOL res =
2509 GetFileAttributesExA( nameA, fInfoLevelId, lpFileInformation);
2510 HeapFree( GetProcessHeap(), 0, nameA );
2511 return res;