Release 980215
[wine] / files / file.c
1 /*
2  * File handling functions
3  *
4  * Copyright 1993 John Burton
5  * Copyright 1996 Alexandre Julliard
6  */
7
8 #include <assert.h>
9 #include <ctype.h>
10 #include <errno.h>
11 #include <fcntl.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <sys/errno.h>
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #include <sys/mman.h>
19 #include <time.h>
20 #include <unistd.h>
21 #include <utime.h>
22
23 #include "windows.h"
24 #include "winerror.h"
25 #include "drive.h"
26 #include "file.h"
27 #include "global.h"
28 #include "heap.h"
29 #include "msdos.h"
30 #include "options.h"
31 #include "ldt.h"
32 #include "process.h"
33 #include "task.h"
34 #include "stddebug.h"
35 #include "debug.h"
36
37 #if defined(MAP_ANONYMOUS) && !defined(MAP_ANON)
38 #define MAP_ANON MAP_ANONYMOUS
39 #endif
40
41 static void FILE_Destroy( K32OBJ *obj );
42
43 const K32OBJ_OPS FILE_Ops =
44 {
45     /* Object cannot be waited upon (FIXME: for now) */
46     NULL,              /* signaled */
47     NULL,              /* satisfied */
48     NULL,              /* add_wait */
49     NULL,              /* remove_wait */
50     FILE_Destroy       /* destroy */
51 };
52
53 struct DOS_FILE_LOCK {
54   struct DOS_FILE_LOCK *        next;
55   DWORD                         base;
56   DWORD                         len;
57   DWORD                         processId;
58   FILE_OBJECT *                 dos_file;
59   char *                        unix_name;
60 };
61
62 typedef struct DOS_FILE_LOCK DOS_FILE_LOCK;
63
64 static DOS_FILE_LOCK *locks = NULL;
65 static void DOS_RemoveFileLocks(FILE_OBJECT *file);
66
67 /***********************************************************************
68  *           FILE_Alloc
69  *
70  * Allocate a file.
71  */
72 static HFILE32 FILE_Alloc( FILE_OBJECT **file )
73 {
74     HFILE32 handle;
75     *file = HeapAlloc( SystemHeap, 0, sizeof(FILE_OBJECT) );
76     if (!*file)
77     {
78         DOS_ERROR( ER_TooManyOpenFiles, EC_ProgramError, SA_Abort, EL_Disk );
79         return NULL;
80     }
81     (*file)->header.type = K32OBJ_FILE;
82     (*file)->header.refcount = 0;
83     (*file)->unix_handle = -1;
84     (*file)->unix_name = NULL;
85     (*file)->type = FILE_TYPE_DISK;
86
87     handle = HANDLE_Alloc( &(*file)->header, FILE_ALL_ACCESS | GENERIC_READ |
88                            GENERIC_WRITE | GENERIC_EXECUTE /*FIXME*/, FALSE );
89     /* If the allocation failed, the object is already destroyed */
90     if (handle == INVALID_HANDLE_VALUE32) *file = NULL;
91     return handle;
92 }
93
94
95 /***********************************************************************
96  *           FILE_Destroy
97  *
98  * Destroy a DOS file.
99  */
100 static void FILE_Destroy( K32OBJ *ptr )
101 {
102     FILE_OBJECT *file = (FILE_OBJECT *)ptr;
103     assert( ptr->type == K32OBJ_FILE );
104
105     DOS_RemoveFileLocks(file);
106
107     if (file->unix_handle != -1) close( file->unix_handle );
108     if (file->unix_name) HeapFree( SystemHeap, 0, file->unix_name );
109     ptr->type = K32OBJ_UNKNOWN;
110     HeapFree( SystemHeap, 0, file );
111 }
112
113
114 /***********************************************************************
115  *           FILE_GetFile
116  *
117  * Return the DOS file associated to a task file handle. FILE_ReleaseFile must
118  * be called to release the file.
119  */
120 static FILE_OBJECT *FILE_GetFile( HFILE32 handle )
121 {
122     return (FILE_OBJECT *)HANDLE_GetObjPtr( handle, K32OBJ_FILE, 0 /*FIXME*/ );
123 }
124
125
126 /***********************************************************************
127  *           FILE_ReleaseFile
128  *
129  * Release a DOS file obtained with FILE_GetFile.
130  */
131 static void FILE_ReleaseFile( FILE_OBJECT *file )
132 {
133     K32OBJ_DecCount( &file->header );
134 }
135
136
137 /***********************************************************************
138  *           FILE_GetUnixHandle
139  *
140  * Return the Unix handle associated to a file handle.
141  */
142 int FILE_GetUnixHandle( HFILE32 hFile )
143 {
144     FILE_OBJECT *file;
145     int ret;
146
147     if (!(file = FILE_GetFile( hFile ))) return -1;
148     ret = file->unix_handle;
149     FILE_ReleaseFile( file );
150     return ret;
151 }
152
153
154 /***********************************************************************
155  *           FILE_SetDosError
156  *
157  * Set the DOS error code from errno.
158  */
159 void FILE_SetDosError(void)
160 {
161     int save_errno = errno; /* errno gets overwritten by printf */
162
163     dprintf_file(stddeb, "FILE_SetDosError: errno = %d %s\n", errno,
164                  strerror(errno) );
165     switch (save_errno)
166     {
167     case EAGAIN:
168         DOS_ERROR( ER_ShareViolation, EC_Temporary, SA_Retry, EL_Disk );
169         break;
170     case EBADF:
171         DOS_ERROR( ER_InvalidHandle, EC_ProgramError, SA_Abort, EL_Disk );
172         break;
173     case ENOSPC:
174         DOS_ERROR( ER_DiskFull, EC_MediaError, SA_Abort, EL_Disk );
175         break;
176     case EACCES:
177     case EPERM:
178     case EROFS:
179         DOS_ERROR( ER_AccessDenied, EC_AccessDenied, SA_Abort, EL_Disk );
180         break;
181     case EBUSY:
182         DOS_ERROR( ER_LockViolation, EC_AccessDenied, SA_Abort, EL_Disk );
183         break;
184     case ENOENT:
185         DOS_ERROR( ER_FileNotFound, EC_NotFound, SA_Abort, EL_Disk );
186         break;
187     case EISDIR:
188         DOS_ERROR( ER_CanNotMakeDir, EC_AccessDenied, SA_Abort, EL_Unknown );
189         break;
190     case ENFILE:
191     case EMFILE:
192         DOS_ERROR( ER_NoMoreFiles, EC_MediaError, SA_Abort, EL_Unknown );
193         break;
194     case EEXIST:
195         DOS_ERROR( ER_FileExists, EC_Exists, SA_Abort, EL_Disk );
196         break;
197     case EINVAL:
198         DOS_ERROR( ER_SeekError, EC_NotFound, SA_Ignore, EL_Disk );
199         break;
200     case ENOTEMPTY:
201         DOS_ERROR( ERROR_DIR_NOT_EMPTY, EC_Exists, SA_Ignore, EL_Disk );
202         break;
203     default:
204         perror( "int21: unknown errno" );
205         DOS_ERROR( ER_GeneralFailure, EC_SystemFailure, SA_Abort, EL_Unknown );
206         break;
207     }
208     errno = save_errno;
209 }
210
211
212 /***********************************************************************
213  *           FILE_DupUnixHandle
214  *
215  * Duplicate a Unix handle into a task handle.
216  */
217 HFILE32 FILE_DupUnixHandle( int fd )
218 {
219     HFILE32 handle;
220     FILE_OBJECT *file;
221
222     if ((handle = FILE_Alloc( &file )) != INVALID_HANDLE_VALUE32)
223     {
224         if ((file->unix_handle = dup(fd)) == -1)
225         {
226             FILE_SetDosError();
227             CloseHandle( handle );
228             return INVALID_HANDLE_VALUE32;
229         }
230     }
231     return handle;
232 }
233
234
235 /***********************************************************************
236  *           FILE_OpenUnixFile
237  */
238 static HFILE32 FILE_OpenUnixFile( const char *name, int mode )
239 {
240     HFILE32 handle;
241     FILE_OBJECT *file;
242     struct stat st;
243
244     if ((handle = FILE_Alloc( &file )) == INVALID_HANDLE_VALUE32)
245         return INVALID_HANDLE_VALUE32;
246
247     if ((file->unix_handle = open( name, mode, 0666 )) == -1)
248     {
249         if (!Options.failReadOnly && (mode == O_RDWR))
250             file->unix_handle = open( name, O_RDONLY );
251     }
252     if ((file->unix_handle == -1) || (fstat( file->unix_handle, &st ) == -1))
253     {
254         FILE_SetDosError();
255         CloseHandle( handle );
256         return INVALID_HANDLE_VALUE32;
257     }
258     if (S_ISDIR(st.st_mode))
259     {
260         DOS_ERROR( ER_AccessDenied, EC_AccessDenied, SA_Abort, EL_Disk );
261         CloseHandle( handle );
262         return INVALID_HANDLE_VALUE32;
263     }
264
265     /* File opened OK, now fill the FILE_OBJECT */
266
267     file->unix_name = HEAP_strdupA( SystemHeap, 0, name );
268     return handle;
269 }
270
271
272 /***********************************************************************
273  *           FILE_Open
274  */
275 HFILE32 FILE_Open( LPCSTR path, INT32 mode )
276 {
277     DOS_FULL_NAME full_name;
278     const char *unixName;
279
280     dprintf_file(stddeb, "FILE_Open: '%s' %04x\n", path, mode );
281
282     if (!path) return HFILE_ERROR32;
283
284     if ((unixName = DOSFS_IsDevice( path )) != NULL)
285     {
286         dprintf_file( stddeb, "FILE_Open: opening device '%s'\n", unixName );
287         if (!unixName[0])  /* Non-existing device */
288         {
289             dprintf_file(stddeb, "FILE_Open: Non-existing device\n");
290             DOS_ERROR( ER_FileNotFound, EC_NotFound, SA_Abort, EL_Disk );
291             return HFILE_ERROR32;
292         }
293     }
294     else /* check for filename, don't check for last entry if creating */
295     {
296         if (!DOSFS_GetFullName( path, !(mode & O_CREAT), &full_name ))
297             return HFILE_ERROR32;
298         unixName = full_name.long_name;
299     }
300     return FILE_OpenUnixFile( unixName, mode );
301 }
302
303
304 /***********************************************************************
305  *           FILE_Create
306  */
307 static HFILE32 FILE_Create( LPCSTR path, int mode, int unique )
308 {
309     HFILE32 handle;
310     FILE_OBJECT *file;
311     const char *unixName;
312     DOS_FULL_NAME full_name;
313
314     dprintf_file(stddeb, "FILE_Create: '%s' %04x %d\n", path, mode, unique );
315
316     if (!path) return INVALID_HANDLE_VALUE32;
317
318     if ((unixName = DOSFS_IsDevice( path )) != NULL)
319     {
320         dprintf_file(stddeb, "FILE_Create: creating device '%s'!\n", unixName);
321         DOS_ERROR( ER_AccessDenied, EC_NotFound, SA_Abort, EL_Disk );
322         return INVALID_HANDLE_VALUE32;
323     }
324
325     if ((handle = FILE_Alloc( &file )) == INVALID_HANDLE_VALUE32)
326         return INVALID_HANDLE_VALUE32;
327
328     if (!DOSFS_GetFullName( path, FALSE, &full_name ))
329     {
330         CloseHandle( handle );
331         return INVALID_HANDLE_VALUE32;
332     }
333     if ((file->unix_handle = open( full_name.long_name,
334                            O_CREAT | O_TRUNC | O_RDWR | (unique ? O_EXCL : 0),
335                            mode )) == -1)
336     {
337         FILE_SetDosError();
338         CloseHandle( handle );
339         return INVALID_HANDLE_VALUE32;
340     } 
341
342     /* File created OK, now fill the FILE_OBJECT */
343
344     file->unix_name = HEAP_strdupA( SystemHeap, 0, full_name.long_name );
345     return handle;
346 }
347
348
349 /***********************************************************************
350  *           FILE_FillInfo
351  *
352  * Fill a file information from a struct stat.
353  */
354 static void FILE_FillInfo( struct stat *st, BY_HANDLE_FILE_INFORMATION *info )
355 {
356     if (S_ISDIR(st->st_mode))
357         info->dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
358     else
359         info->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
360     if (!(st->st_mode & S_IWUSR))
361         info->dwFileAttributes |= FILE_ATTRIBUTE_READONLY;
362
363     DOSFS_UnixTimeToFileTime( st->st_mtime, &info->ftCreationTime, 0 );
364     DOSFS_UnixTimeToFileTime( st->st_mtime, &info->ftLastWriteTime, 0 );
365     DOSFS_UnixTimeToFileTime( st->st_atime, &info->ftLastAccessTime, 0 );
366
367     info->dwVolumeSerialNumber = 0;  /* FIXME */
368     info->nFileSizeHigh = 0;
369     info->nFileSizeLow  = S_ISDIR(st->st_mode) ? 0 : st->st_size;
370     info->nNumberOfLinks = st->st_nlink;
371     info->nFileIndexHigh = 0;
372     info->nFileIndexLow  = st->st_ino;
373 }
374
375
376 /***********************************************************************
377  *           FILE_Stat
378  *
379  * Stat a Unix path name. Return TRUE if OK.
380  */
381 BOOL32 FILE_Stat( LPCSTR unixName, BY_HANDLE_FILE_INFORMATION *info )
382 {
383     struct stat st;
384
385     if (!unixName || !info) return FALSE;
386
387     if (stat( unixName, &st ) == -1)
388     {
389         FILE_SetDosError();
390         return FALSE;
391     }
392     FILE_FillInfo( &st, info );
393     return TRUE;
394 }
395
396
397 /***********************************************************************
398  *             GetFileInformationByHandle   (KERNEL32.219)
399  */
400 DWORD WINAPI GetFileInformationByHandle( HFILE32 hFile,
401                                          BY_HANDLE_FILE_INFORMATION *info )
402 {
403     FILE_OBJECT *file;
404     DWORD ret = 0;
405     struct stat st;
406
407     if (!info) return 0;
408
409     if (!(file = FILE_GetFile( hFile ))) return 0;
410     if (fstat( file->unix_handle, &st ) == -1) FILE_SetDosError();
411     else
412     {
413         FILE_FillInfo( &st, info );
414         ret = 1;
415     }
416     FILE_ReleaseFile( file );
417     return ret;
418 }
419
420
421 /**************************************************************************
422  *           GetFileAttributes16   (KERNEL.420)
423  */
424 DWORD WINAPI GetFileAttributes16( LPCSTR name )
425 {
426     return GetFileAttributes32A( name );
427 }
428
429
430 /**************************************************************************
431  *           GetFileAttributes32A   (KERNEL32.217)
432  */
433 DWORD WINAPI GetFileAttributes32A( LPCSTR name )
434 {
435     DOS_FULL_NAME full_name;
436     BY_HANDLE_FILE_INFORMATION info;
437
438     if (name == NULL) return -1;
439
440     if (!DOSFS_GetFullName( name, TRUE, &full_name )) return -1;
441     if (!FILE_Stat( full_name.long_name, &info )) return -1;
442     return info.dwFileAttributes;
443 }
444
445
446 /**************************************************************************
447  *           GetFileAttributes32W   (KERNEL32.218)
448  */
449 DWORD WINAPI GetFileAttributes32W( LPCWSTR name )
450 {
451     LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
452     DWORD res = GetFileAttributes32A( nameA );
453     HeapFree( GetProcessHeap(), 0, nameA );
454     return res;
455 }
456
457
458 /***********************************************************************
459  *           GetFileSize   (KERNEL32.220)
460  */
461 DWORD WINAPI GetFileSize( HFILE32 hFile, LPDWORD filesizehigh )
462 {
463     BY_HANDLE_FILE_INFORMATION info;
464     if (!GetFileInformationByHandle( hFile, &info )) return 0;
465     if (filesizehigh) *filesizehigh = info.nFileSizeHigh;
466     return info.nFileSizeLow;
467 }
468
469
470 /***********************************************************************
471  *           GetFileTime   (KERNEL32.221)
472  */
473 BOOL32 WINAPI GetFileTime( HFILE32 hFile, FILETIME *lpCreationTime,
474                            FILETIME *lpLastAccessTime,
475                            FILETIME *lpLastWriteTime )
476 {
477     BY_HANDLE_FILE_INFORMATION info;
478     if (!GetFileInformationByHandle( hFile, &info )) return FALSE;
479     if (lpCreationTime)   *lpCreationTime   = info.ftCreationTime;
480     if (lpLastAccessTime) *lpLastAccessTime = info.ftLastAccessTime;
481     if (lpLastWriteTime)  *lpLastWriteTime  = info.ftLastWriteTime;
482     return TRUE;
483 }
484
485 /***********************************************************************
486  *           CompareFileTime   (KERNEL32.28)
487  */
488 INT32 WINAPI CompareFileTime( LPFILETIME x, LPFILETIME y )
489 {
490         if (!x || !y) return -1;
491
492         if (x->dwHighDateTime > y->dwHighDateTime)
493                 return 1;
494         if (x->dwHighDateTime < y->dwHighDateTime)
495                 return -1;
496         if (x->dwLowDateTime > y->dwLowDateTime)
497                 return 1;
498         if (x->dwLowDateTime < y->dwLowDateTime)
499                 return -1;
500         return 0;
501 }
502
503 /***********************************************************************
504  *           FILE_Dup
505  *
506  * dup() function for DOS handles.
507  */
508 HFILE32 FILE_Dup( HFILE32 hFile )
509 {
510     FILE_OBJECT *file;
511     HFILE32 handle;
512
513     dprintf_file( stddeb, "FILE_Dup for handle %d\n", hFile );
514     if (!(file = FILE_GetFile( hFile ))) return HFILE_ERROR32;
515     handle = HANDLE_Alloc( &file->header, FILE_ALL_ACCESS /*FIXME*/, FALSE );
516     FILE_ReleaseFile( file );
517     dprintf_file( stddeb, "FILE_Dup return handle %d\n", handle );
518     return handle;
519 }
520
521
522 /***********************************************************************
523  *           FILE_Dup2
524  *
525  * dup2() function for DOS handles.
526  */
527 HFILE32 FILE_Dup2( HFILE32 hFile1, HFILE32 hFile2 )
528 {
529     FILE_OBJECT *file;
530
531     dprintf_file( stddeb, "FILE_Dup2 for handle %d\n", hFile1 );
532     /* FIXME: should use DuplicateHandle */
533     if (!(file = FILE_GetFile( hFile1 ))) return HFILE_ERROR32;
534     if (!HANDLE_SetObjPtr( hFile2, &file->header, 0 )) hFile2 = HFILE_ERROR32;
535     FILE_ReleaseFile( file );
536     return hFile2;
537 }
538
539
540 /***********************************************************************
541  *           GetTempFileName16   (KERNEL.97)
542  */
543 UINT16 WINAPI GetTempFileName16( BYTE drive, LPCSTR prefix, UINT16 unique,
544                                  LPSTR buffer )
545 {
546     char temppath[144];
547
548     if (!(drive & ~TF_FORCEDRIVE)) /* drive 0 means current default drive */
549         drive |= DRIVE_GetCurrentDrive() + 'A';
550
551     if ((drive & TF_FORCEDRIVE) &&
552         !DRIVE_IsValid( toupper(drive & ~TF_FORCEDRIVE) - 'A' ))
553     {
554         drive &= ~TF_FORCEDRIVE;
555         fprintf( stderr, "Warning: GetTempFileName: invalid drive %d specified\n",
556                  drive );
557     }
558
559     if (drive & TF_FORCEDRIVE)
560         sprintf(temppath,"%c:", drive & ~TF_FORCEDRIVE );
561     else
562     {
563         GetTempPath32A( 132, temppath );
564         strcat( temppath, "\\" );
565     }
566     return (UINT16)GetTempFileName32A( temppath, prefix, unique, buffer );
567 }
568
569
570 /***********************************************************************
571  *           GetTempFileName32A   (KERNEL32.290)
572  */
573 UINT32 WINAPI GetTempFileName32A( LPCSTR path, LPCSTR prefix, UINT32 unique,
574                                   LPSTR buffer)
575 {
576     DOS_FULL_NAME full_name;
577     int i;
578     LPSTR p;
579     UINT32 num = unique ? (unique & 0xffff) : time(NULL) & 0xffff;
580
581     if ( !path || !prefix || !buffer ) return 0;
582
583     strcpy( buffer, path );
584     p = buffer + strlen(buffer);
585
586     /* add a \, if there isn't one and path is more than just the drive letter ... */
587     if ( !((strlen(buffer) == 2) && (buffer[1] == ':')) 
588         && ((p == buffer) || (p[-1] != '\\'))) *p++ = '\\';
589
590     *p++ = '~';
591     for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
592     sprintf( p, "%04x.tmp", num );
593
594     /* Now try to create it */
595
596     if (!unique)
597     {
598         do
599         {
600             HFILE32 handle = FILE_Create( buffer, 0666, TRUE );
601             if (handle != INVALID_HANDLE_VALUE32)
602             {  /* We created it */
603                 dprintf_file( stddeb, "GetTempFileName32A: created %s\n",
604                               buffer);
605                 CloseHandle( handle );
606                 break;
607             }
608             if (DOS_ExtendedError != ER_FileExists)
609                 break;  /* No need to go on */
610             num++;
611             sprintf( p, "%04x.tmp", num );
612         } while (num != (unique & 0xffff));
613     }
614
615     /* Get the full path name */
616
617     if (DOSFS_GetFullName( buffer, FALSE, &full_name ))
618     {
619         /* Check if we have write access in the directory */
620         if ((p = strrchr( full_name.long_name, '/' ))) *p = '\0';
621         if (access( full_name.long_name, W_OK ) == -1)
622             fprintf( stderr,
623                      "Warning: GetTempFileName returns '%s', which doesn't seem to be writeable.\n"
624                      "Please check your configuration file if this generates a failure.\n",
625                      buffer);
626     }
627     dprintf_file( stddeb, "GetTempFileName32A: returning %s\n", buffer );
628     return unique ? unique : num;
629 }
630
631
632 /***********************************************************************
633  *           GetTempFileName32W   (KERNEL32.291)
634  */
635 UINT32 WINAPI GetTempFileName32W( LPCWSTR path, LPCWSTR prefix, UINT32 unique,
636                                   LPWSTR buffer )
637 {
638     LPSTR   patha,prefixa;
639     char    buffera[144];
640     UINT32  ret;
641
642     if (!path) return 0;
643     patha   = HEAP_strdupWtoA( GetProcessHeap(), 0, path );
644     prefixa = HEAP_strdupWtoA( GetProcessHeap(), 0, prefix );
645     ret     = GetTempFileName32A( patha, prefixa, unique, buffera );
646     lstrcpyAtoW( buffer, buffera );
647     HeapFree( GetProcessHeap(), 0, patha );
648     HeapFree( GetProcessHeap(), 0, prefixa );
649     return ret;
650 }
651
652
653 /***********************************************************************
654  *           FILE_DoOpenFile
655  *
656  * Implementation of OpenFile16() and OpenFile32().
657  */
658 static HFILE32 FILE_DoOpenFile( LPCSTR name, OFSTRUCT *ofs, UINT32 mode,
659                                 BOOL32 win32 )
660 {
661     HFILE32 hFileRet;
662     FILETIME filetime;
663     WORD filedatetime[2];
664     DOS_FULL_NAME full_name;
665     char *p;
666     int unixMode;
667
668     if (!ofs) return HFILE_ERROR32;
669
670
671     ofs->cBytes = sizeof(OFSTRUCT);
672     ofs->nErrCode = 0;
673     if (mode & OF_REOPEN) name = ofs->szPathName;
674
675     if (!name) {
676         fprintf(stderr, "ERROR: FILE_DoOpenFile() called with `name' set to NULL ! Please debug.\n");
677  
678         return HFILE_ERROR32;
679     }
680
681     dprintf_file( stddeb, "OpenFile: %s %04x\n", name, mode );
682
683     /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
684        Are there any cases where getting the path here is wrong? 
685        Uwe Bonnes 1997 Apr 2 */
686     if (!GetFullPathName32A( name, sizeof(ofs->szPathName),
687                              ofs->szPathName, NULL )) goto error;
688
689     /* OF_PARSE simply fills the structure */
690
691     if (mode & OF_PARSE)
692     {
693         ofs->fFixedDisk = (GetDriveType16( ofs->szPathName[0]-'A' )
694                            != DRIVE_REMOVABLE);
695         dprintf_file( stddeb, "OpenFile(%s): OF_PARSE, res = '%s'\n",
696                       name, ofs->szPathName );
697         return 0;
698     }
699
700     /* OF_CREATE is completely different from all other options, so
701        handle it first */
702
703     if (mode & OF_CREATE)
704     {
705         if ((hFileRet = FILE_Create(name,0666,FALSE))== INVALID_HANDLE_VALUE32)
706             goto error;
707         goto success;
708     }
709
710     /* If OF_SEARCH is set, ignore the given path */
711
712     if ((mode & OF_SEARCH) && !(mode & OF_REOPEN))
713     {
714         /* First try the file name as is */
715         if (DOSFS_GetFullName( name, TRUE, &full_name )) goto found;
716         /* Now remove the path */
717         if (name[0] && (name[1] == ':')) name += 2;
718         if ((p = strrchr( name, '\\' ))) name = p + 1;
719         if ((p = strrchr( name, '/' ))) name = p + 1;
720         if (!name[0]) goto not_found;
721     }
722
723     /* Now look for the file */
724
725     if (!DIR_SearchPath( NULL, name, NULL, &full_name, win32 )) goto not_found;
726
727 found:
728     dprintf_file( stddeb, "OpenFile: found %s = %s\n",
729                   full_name.long_name, full_name.short_name );
730     lstrcpyn32A( ofs->szPathName, full_name.short_name,
731                  sizeof(ofs->szPathName) );
732
733     if (mode & OF_DELETE)
734     {
735         if (unlink( full_name.long_name ) == -1) goto not_found;
736         dprintf_file( stddeb, "OpenFile(%s): OF_DELETE return = OK\n", name);
737         return 1;
738     }
739
740     switch(mode & 3)
741     {
742     case OF_WRITE:
743         unixMode = O_WRONLY; break;
744     case OF_READWRITE:
745         unixMode = O_RDWR; break;
746     case OF_READ:
747     default:
748         unixMode = O_RDONLY; break;
749     }
750
751     hFileRet = FILE_OpenUnixFile( full_name.long_name, unixMode );
752     if (hFileRet == HFILE_ERROR32) goto not_found;
753     GetFileTime( hFileRet, NULL, NULL, &filetime );
754     FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
755     if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
756     {
757         if (memcmp( ofs->reserved, filedatetime, sizeof(ofs->reserved) ))
758         {
759             CloseHandle( hFileRet );
760             dprintf_file( stddeb, "OpenFile(%s): OF_VERIFY failed\n", name );
761             /* FIXME: what error here? */
762             DOS_ERROR( ER_FileNotFound, EC_NotFound, SA_Abort, EL_Disk );
763             goto error;
764         }
765     }
766     memcpy( ofs->reserved, filedatetime, sizeof(ofs->reserved) );
767
768 success:  /* We get here if the open was successful */
769     dprintf_file( stddeb, "OpenFile(%s): OK, return = %d\n", name, hFileRet );
770     if (mode & OF_EXIST) /* Return the handle, but close it first */
771         CloseHandle( hFileRet );
772     return hFileRet;
773
774 not_found:  /* We get here if the file does not exist */
775     dprintf_file( stddeb, "OpenFile: '%s' not found\n", name );
776     DOS_ERROR( ER_FileNotFound, EC_NotFound, SA_Abort, EL_Disk );
777     /* fall through */
778
779 error:  /* We get here if there was an error opening the file */
780     ofs->nErrCode = DOS_ExtendedError;
781     dprintf_file( stddeb, "OpenFile(%s): return = HFILE_ERROR error= %d\n", 
782                   name,ofs->nErrCode );
783     return HFILE_ERROR32;
784 }
785
786
787 /***********************************************************************
788  *           OpenFile16   (KERNEL.74)
789  */
790 HFILE16 WINAPI OpenFile16( LPCSTR name, OFSTRUCT *ofs, UINT16 mode )
791 {
792     return FILE_DoOpenFile( name, ofs, mode, FALSE );
793 }
794
795
796 /***********************************************************************
797  *           OpenFile32   (KERNEL32.396)
798  */
799 HFILE32 WINAPI OpenFile32( LPCSTR name, OFSTRUCT *ofs, UINT32 mode )
800 {
801     return FILE_DoOpenFile( name, ofs, mode, TRUE );
802 }
803
804
805 /***********************************************************************
806  *           _lclose16   (KERNEL.81)
807  */
808 HFILE16 WINAPI _lclose16( HFILE16 hFile )
809 {
810     dprintf_file( stddeb, "_lclose16: handle %d\n", hFile );
811     return CloseHandle( hFile ) ? 0 : HFILE_ERROR16;
812 }
813
814
815 /***********************************************************************
816  *           _lclose32   (KERNEL32.592)
817  */
818 HFILE32 WINAPI _lclose32( HFILE32 hFile )
819 {
820     dprintf_file( stddeb, "_lclose32: handle %d\n", hFile );
821     return CloseHandle( hFile ) ? 0 : HFILE_ERROR32;
822 }
823
824
825 /***********************************************************************
826  *           WIN16_hread
827  */
828 LONG WINAPI WIN16_hread( HFILE16 hFile, SEGPTR buffer, LONG count )
829 {
830     LONG maxlen;
831
832     dprintf_file( stddeb, "WIN16_hread: %d %08lx %ld\n",
833                   hFile, (DWORD)buffer, count );
834
835     /* Some programs pass a count larger than the allocated buffer */
836     maxlen = GetSelectorLimit( SELECTOROF(buffer) ) - OFFSETOF(buffer) + 1;
837     if (count > maxlen) count = maxlen;
838     return _lread32( hFile, PTR_SEG_TO_LIN(buffer), count );
839 }
840
841
842 /***********************************************************************
843  *           WIN16_lread
844  */
845 UINT16 WINAPI WIN16_lread( HFILE16 hFile, SEGPTR buffer, UINT16 count )
846 {
847     return (UINT16)WIN16_hread( hFile, buffer, (LONG)count );
848 }
849
850
851 /***********************************************************************
852  *           _lread32   (KERNEL32.596)
853  */
854 UINT32 WINAPI _lread32( HFILE32 hFile, LPVOID buffer, UINT32 count )
855 {
856     FILE_OBJECT *file;
857     UINT32 result;
858
859     dprintf_file( stddeb, "_lread32: %d %p %d\n", hFile, buffer, count );
860     if (!(file = FILE_GetFile( hFile ))) return -1;
861     if (!count) result = 0;
862     else if ((result = read( file->unix_handle, buffer, count )) == -1)
863         FILE_SetDosError();
864     FILE_ReleaseFile( file );
865     return result;
866 }
867
868
869 /***********************************************************************
870  *           _lread16   (KERNEL.82)
871  */
872 UINT16 WINAPI _lread16( HFILE16 hFile, LPVOID buffer, UINT16 count )
873 {
874     return (UINT16)_lread32( hFile, buffer, (LONG)count );
875 }
876
877
878 /***********************************************************************
879  *           _lcreat16   (KERNEL.83)
880  */
881 HFILE16 WINAPI _lcreat16( LPCSTR path, INT16 attr )
882 {
883     int mode = (attr & 1) ? 0444 : 0666;
884     dprintf_file( stddeb, "_lcreat16: %s %02x\n", path, attr );
885     return (HFILE16)FILE_Create( path, mode, FALSE );
886 }
887
888
889 /***********************************************************************
890  *           _lcreat32   (KERNEL32.593)
891  */
892 HFILE32 WINAPI _lcreat32( LPCSTR path, INT32 attr )
893 {
894     int mode = (attr & 1) ? 0444 : 0666;
895     dprintf_file( stddeb, "_lcreat32: %s %02x\n", path, attr );
896     return FILE_Create( path, mode, FALSE );
897 }
898
899
900 /***********************************************************************
901  *           _lcreat_uniq   (Not a Windows API)
902  */
903 HFILE32 _lcreat_uniq( LPCSTR path, INT32 attr )
904 {
905     int mode = (attr & 1) ? 0444 : 0666;
906     dprintf_file( stddeb, "_lcreat_uniq: %s %02x\n", path, attr );
907     return FILE_Create( path, mode, TRUE );
908 }
909
910
911 /***********************************************************************
912  *           SetFilePointer   (KERNEL32.492)
913  */
914 DWORD WINAPI SetFilePointer( HFILE32 hFile, LONG distance, LONG *highword,
915                              DWORD method )
916 {
917     FILE_OBJECT *file;
918     int origin, result;
919
920     if (highword && *highword)
921     {
922         fprintf( stderr, "SetFilePointer: 64-bit offsets not supported yet\n");
923         SetLastError( ERROR_INVALID_PARAMETER );
924         return 0xffffffff;
925     }
926     dprintf_file( stddeb, "SetFilePointer: handle %d offset %ld origin %ld\n",
927                   hFile, distance, method );
928
929     if (!(file = FILE_GetFile( hFile ))) return 0xffffffff;
930     switch(method)
931     {
932         case FILE_CURRENT: origin = SEEK_CUR; break;
933         case FILE_END:     origin = SEEK_END; break;
934         default:           origin = SEEK_SET; break;
935     }
936
937     if ((result = lseek( file->unix_handle, distance, origin )) == -1)
938         FILE_SetDosError();
939     FILE_ReleaseFile( file );
940     return (DWORD)result;
941 }
942
943
944 /***********************************************************************
945  *           _llseek16   (KERNEL.84)
946  */
947 LONG WINAPI _llseek16( HFILE16 hFile, LONG lOffset, INT16 nOrigin )
948 {
949     return SetFilePointer( hFile, lOffset, NULL, nOrigin );
950 }
951
952
953 /***********************************************************************
954  *           _llseek32   (KERNEL32.594)
955  */
956 LONG WINAPI _llseek32( HFILE32 hFile, LONG lOffset, INT32 nOrigin )
957 {
958     return SetFilePointer( hFile, lOffset, NULL, nOrigin );
959 }
960
961
962 /***********************************************************************
963  *           _lopen16   (KERNEL.85)
964  */
965 HFILE16 WINAPI _lopen16( LPCSTR path, INT16 mode )
966 {
967     return _lopen32( path, mode );
968 }
969
970
971 /***********************************************************************
972  *           _lopen32   (KERNEL32.595)
973  */
974 HFILE32 WINAPI _lopen32( LPCSTR path, INT32 mode )
975 {
976     INT32 unixMode;
977
978     dprintf_file(stddeb, "_lopen32('%s',%04x)\n", path, mode );
979
980     switch(mode & 3)
981     {
982     case OF_WRITE:
983         unixMode = O_WRONLY;
984         break;
985     case OF_READWRITE:
986         unixMode = O_RDWR;
987         break;
988     case OF_READ:
989     default:
990         unixMode = O_RDONLY;
991         break;
992     }
993     return FILE_Open( path, unixMode );
994 }
995
996
997 /***********************************************************************
998  *           _lwrite16   (KERNEL.86)
999  */
1000 UINT16 WINAPI _lwrite16( HFILE16 hFile, LPCSTR buffer, UINT16 count )
1001 {
1002     return (UINT16)_hwrite32( hFile, buffer, (LONG)count );
1003 }
1004
1005 /***********************************************************************
1006  *           _lwrite32   (KERNEL.86)
1007  */
1008 UINT32 WINAPI _lwrite32( HFILE32 hFile, LPCSTR buffer, UINT32 count )
1009 {
1010     return (UINT32)_hwrite32( hFile, buffer, (LONG)count );
1011 }
1012
1013
1014 /***********************************************************************
1015  *           _hread16   (KERNEL.349)
1016  */
1017 LONG WINAPI _hread16( HFILE16 hFile, LPVOID buffer, LONG count)
1018 {
1019     return _lread32( hFile, buffer, count );
1020 }
1021
1022
1023 /***********************************************************************
1024  *           _hread32   (KERNEL32.590)
1025  */
1026 LONG WINAPI _hread32( HFILE32 hFile, LPVOID buffer, LONG count)
1027 {
1028     return _lread32( hFile, buffer, count );
1029 }
1030
1031
1032 /***********************************************************************
1033  *           _hwrite16   (KERNEL.350)
1034  */
1035 LONG WINAPI _hwrite16( HFILE16 hFile, LPCSTR buffer, LONG count )
1036 {
1037     return _hwrite32( hFile, buffer, count );
1038 }
1039
1040
1041 /***********************************************************************
1042  *           _hwrite32   (KERNEL32.591)
1043  */
1044 LONG WINAPI _hwrite32( HFILE32 hFile, LPCSTR buffer, LONG count )
1045 {
1046     FILE_OBJECT *file;
1047     LONG result;
1048
1049     dprintf_file( stddeb, "_hwrite32: %d %p %ld\n", hFile, buffer, count );
1050
1051     if (!(file = FILE_GetFile( hFile ))) return HFILE_ERROR32;
1052     if (count == 0)  /* Expand or truncate at current position */
1053         result = ftruncate( file->unix_handle,
1054                             lseek( file->unix_handle, 0, SEEK_CUR ) );
1055     else for (;;)
1056     {
1057         result = write( file->unix_handle, buffer, count );
1058         if (result != -1) break;
1059         if (errno != EINTR)
1060         {
1061             FILE_SetDosError();
1062             break;
1063         }
1064     }
1065
1066     FILE_ReleaseFile( file );
1067     return result;
1068 }
1069
1070
1071 /***********************************************************************
1072  *           SetHandleCount16   (KERNEL.199)
1073  */
1074 UINT16 WINAPI SetHandleCount16( UINT16 count )
1075 {
1076     HGLOBAL16 hPDB = GetCurrentPDB();
1077     PDB *pdb = (PDB *)GlobalLock16( hPDB );
1078     BYTE *files = PTR_SEG_TO_LIN( pdb->fileHandlesPtr );
1079
1080     dprintf_file( stddeb, "SetHandleCount16(%d)\n", count );
1081
1082     if (count < 20) count = 20;  /* No point in going below 20 */
1083     else if (count > 254) count = 254;
1084
1085     if (count == 20)
1086     {
1087         if (pdb->nbFiles > 20)
1088         {
1089             memcpy( pdb->fileHandles, files, 20 );
1090             GlobalFree16( pdb->hFileHandles );
1091             pdb->fileHandlesPtr = (SEGPTR)MAKELONG( 0x18,
1092                                                    GlobalHandleToSel( hPDB ) );
1093             pdb->hFileHandles = 0;
1094             pdb->nbFiles = 20;
1095         }
1096     }
1097     else  /* More than 20, need a new file handles table */
1098     {
1099         BYTE *newfiles;
1100         HGLOBAL16 newhandle = GlobalAlloc16( GMEM_MOVEABLE, count );
1101         if (!newhandle)
1102         {
1103             DOS_ERROR( ER_OutOfMemory, EC_OutOfResource, SA_Abort, EL_Memory );
1104             return pdb->nbFiles;
1105         }
1106         newfiles = (BYTE *)GlobalLock16( newhandle );
1107
1108         if (count > pdb->nbFiles)
1109         {
1110             memcpy( newfiles, files, pdb->nbFiles );
1111             memset( newfiles + pdb->nbFiles, 0xff, count - pdb->nbFiles );
1112         }
1113         else memcpy( newfiles, files, count );
1114         if (pdb->nbFiles > 20) GlobalFree16( pdb->hFileHandles );
1115         pdb->fileHandlesPtr = WIN16_GlobalLock16( newhandle );
1116         pdb->hFileHandles   = newhandle;
1117         pdb->nbFiles = count;
1118     }
1119     return pdb->nbFiles;
1120 }
1121
1122
1123 /*************************************************************************
1124  *           SetHandleCount32   (KERNEL32.494)
1125  */
1126 UINT32 WINAPI SetHandleCount32( UINT32 count )
1127 {
1128     return MIN( 256, count );
1129 }
1130
1131
1132 /***********************************************************************
1133  *           FlushFileBuffers   (KERNEL32.133)
1134  */
1135 BOOL32 WINAPI FlushFileBuffers( HFILE32 hFile )
1136 {
1137     FILE_OBJECT *file;
1138     BOOL32 ret;
1139
1140     dprintf_file( stddeb, "FlushFileBuffers(%d)\n", hFile );
1141     if (!(file = FILE_GetFile( hFile ))) return FALSE;
1142     if (fsync( file->unix_handle ) != -1) ret = TRUE;
1143     else
1144     {
1145         FILE_SetDosError();
1146         ret = FALSE;
1147     }
1148     FILE_ReleaseFile( file );
1149     return ret;
1150 }
1151
1152
1153 /**************************************************************************
1154  *           SetEndOfFile   (KERNEL32.483)
1155  */
1156 BOOL32 WINAPI SetEndOfFile( HFILE32 hFile )
1157 {
1158     FILE_OBJECT *file;
1159     BOOL32 ret = TRUE;
1160
1161     dprintf_file( stddeb, "SetEndOfFile(%d)\n", hFile );
1162     if (!(file = FILE_GetFile( hFile ))) return FALSE;
1163     if (ftruncate( file->unix_handle,
1164                    lseek( file->unix_handle, 0, SEEK_CUR ) ))
1165     {
1166         FILE_SetDosError();
1167         ret = FALSE;
1168     }
1169     FILE_ReleaseFile( file );
1170     return ret;
1171 }
1172
1173
1174 /***********************************************************************
1175  *           DeleteFile16   (KERNEL.146)
1176  */
1177 BOOL16 WINAPI DeleteFile16( LPCSTR path )
1178 {
1179     return DeleteFile32A( path );
1180 }
1181
1182
1183 /***********************************************************************
1184  *           DeleteFile32A   (KERNEL32.71)
1185  */
1186 BOOL32 WINAPI DeleteFile32A( LPCSTR path )
1187 {
1188     DOS_FULL_NAME full_name;
1189     const char *unixName;
1190
1191     dprintf_file(stddeb, "DeleteFile: '%s'\n", path );
1192
1193     if ((unixName = DOSFS_IsDevice( path )) != NULL)
1194     {
1195         dprintf_file(stddeb, "DeleteFile: removing device '%s'!\n", unixName);
1196         DOS_ERROR( ER_FileNotFound, EC_NotFound, SA_Abort, EL_Disk );
1197         return FALSE;
1198     }
1199
1200     if (!DOSFS_GetFullName( path, TRUE, &full_name )) return FALSE;
1201     if (unlink( full_name.long_name ) == -1)
1202     {
1203         FILE_SetDosError();
1204         return FALSE;
1205     }
1206     return TRUE;
1207 }
1208
1209
1210 /***********************************************************************
1211  *           DeleteFile32W   (KERNEL32.72)
1212  */
1213 BOOL32 WINAPI DeleteFile32W( LPCWSTR path )
1214 {
1215     LPSTR xpath = HEAP_strdupWtoA( GetProcessHeap(), 0, path );
1216     BOOL32 ret = DeleteFile32A( xpath );
1217     HeapFree( GetProcessHeap(), 0, xpath );
1218     return ret;
1219 }
1220
1221
1222 /***********************************************************************
1223  *           FILE_SetFileType
1224  */
1225 BOOL32 FILE_SetFileType( HFILE32 hFile, DWORD type )
1226 {
1227     FILE_OBJECT *file = FILE_GetFile( hFile );
1228     if (!file) return FALSE;
1229     file->type = type;
1230     FILE_ReleaseFile( file );
1231     return TRUE;
1232 }
1233
1234
1235 /***********************************************************************
1236  *           FILE_mmap
1237  */
1238 LPVOID FILE_mmap( HFILE32 hFile, LPVOID start,
1239                   DWORD size_high, DWORD size_low,
1240                   DWORD offset_high, DWORD offset_low,
1241                   int prot, int flags )
1242 {
1243     LPVOID ret;
1244     FILE_OBJECT *file = FILE_GetFile( hFile );
1245     if (!file) return (LPVOID)-1;
1246     ret = FILE_dommap( file, start, size_high, size_low,
1247                        offset_high, offset_low, prot, flags );
1248     FILE_ReleaseFile( file );
1249     return ret;
1250 }
1251
1252
1253 /***********************************************************************
1254  *           FILE_dommap
1255  */
1256 LPVOID FILE_dommap( FILE_OBJECT *file, LPVOID start,
1257                     DWORD size_high, DWORD size_low,
1258                     DWORD offset_high, DWORD offset_low,
1259                     int prot, int flags )
1260 {
1261     int fd = -1;
1262     int pos;
1263     LPVOID ret;
1264
1265     if (size_high || offset_high)
1266         fprintf( stderr, "FILE_mmap: offsets larger than 4Gb not supported\n");
1267
1268     if (!file)
1269     {
1270 #ifdef MAP_ANON
1271         flags |= MAP_ANON;
1272 #else
1273         static int fdzero = -1;
1274
1275         if (fdzero == -1)
1276         {
1277             if ((fdzero = open( "/dev/zero", O_RDONLY )) == -1)
1278             {
1279                 perror( "/dev/zero: open" );
1280                 exit(1);
1281             }
1282         }
1283         fd = fdzero;
1284 #endif  /* MAP_ANON */
1285         /* Linux EINVAL's on us if we don't pass MAP_PRIVATE to an anon mmap */
1286 #ifdef MAP_SHARED
1287         flags &= ~MAP_SHARED;
1288 #endif
1289 #ifdef MAP_PRIVATE
1290         flags |= MAP_PRIVATE;
1291 #endif
1292     }
1293     else fd = file->unix_handle;
1294
1295     if ((ret = mmap( start, size_low, prot,
1296                      flags, fd, offset_low )) != (LPVOID)-1)
1297         return ret;
1298
1299     /* mmap() failed; if this is because the file offset is not    */
1300     /* page-aligned (EINVAL), or because the underlying filesystem */
1301     /* does not support mmap() (ENOEXEC), we do it by hand.        */
1302
1303     if (!file) return ret;
1304     if ((errno != ENOEXEC) && (errno != EINVAL)) return ret;
1305     if (prot & PROT_WRITE)
1306     {
1307         /* We cannot fake shared write mappings */
1308 #ifdef MAP_SHARED
1309         if (flags & MAP_SHARED) return ret;
1310 #endif
1311 #ifdef MAP_PRIVATE
1312         if (!(flags & MAP_PRIVATE)) return ret;
1313 #endif
1314     }
1315 /*    printf( "FILE_mmap: mmap failed (%d), faking it\n", errno );*/
1316     /* Reserve the memory with an anonymous mmap */
1317     ret = FILE_dommap( NULL, start, size_high, size_low, 0, 0,
1318                        PROT_READ | PROT_WRITE, flags );
1319     if (ret == (LPVOID)-1) return ret;
1320     /* Now read in the file */
1321     if ((pos = lseek( fd, offset_low, SEEK_SET )) == -1)
1322     {
1323         FILE_munmap( ret, size_high, size_low );
1324         return (LPVOID)-1;
1325     }
1326     read( fd, ret, size_low );
1327     lseek( fd, pos, SEEK_SET );  /* Restore the file pointer */
1328     mprotect( ret, size_low, prot );  /* Set the right protection */
1329     return ret;
1330 }
1331
1332
1333 /***********************************************************************
1334  *           FILE_munmap
1335  */
1336 int FILE_munmap( LPVOID start, DWORD size_high, DWORD size_low )
1337 {
1338     if (size_high)
1339       fprintf( stderr, "FILE_munmap: offsets larger than 4Gb not supported\n");
1340     return munmap( start, size_low );
1341 }
1342
1343
1344 /***********************************************************************
1345  *           GetFileType   (KERNEL32.222)
1346  */
1347 DWORD WINAPI GetFileType( HFILE32 hFile )
1348 {
1349     FILE_OBJECT *file = FILE_GetFile(hFile);
1350     if (!file) return FILE_TYPE_UNKNOWN; /* FIXME: correct? */
1351     FILE_ReleaseFile( file );
1352     return file->type;
1353 }
1354
1355
1356 /**************************************************************************
1357  *           MoveFileEx32A   (KERNEL32.???)
1358  */
1359 BOOL32 WINAPI MoveFileEx32A( LPCSTR fn1, LPCSTR fn2, DWORD flag )
1360 {
1361     DOS_FULL_NAME full_name1, full_name2;
1362     int mode=0; /* mode == 1: use copy */
1363
1364     dprintf_file( stddeb, "MoveFileEx32A(%s,%s,%04lx)\n", fn1, fn2, flag);
1365
1366     if (!DOSFS_GetFullName( fn1, TRUE, &full_name1 )) return FALSE;
1367     if (fn2) { /* !fn2 means delete fn1 */
1368       if (!DOSFS_GetFullName( fn2, FALSE, &full_name2 )) return FALSE;
1369       /* Source name and target path are valid */
1370       if ( full_name1.drive != full_name2.drive)
1371         /* use copy, if allowed */
1372         if (!(flag & MOVEFILE_COPY_ALLOWED)) {
1373           /* FIXME: Use right error code */
1374           DOS_ERROR( ER_FileExists, EC_Exists, SA_Abort, EL_Disk );
1375           return FALSE;
1376         }
1377         else mode =1;
1378       if (DOSFS_GetFullName( fn2, TRUE, &full_name2 )) 
1379         /* target exists, check if we may overwrite */
1380         if (!(flag & MOVEFILE_REPLACE_EXISTING)) {
1381           /* FIXME: Use right error code */
1382           DOS_ERROR( ER_AccessDenied, EC_AccessDenied, SA_Abort, EL_Disk );
1383           return FALSE;
1384         }
1385     }
1386     else /* fn2 == NULL means delete source */
1387       if (flag & MOVEFILE_DELAY_UNTIL_REBOOT) {
1388         if (flag & MOVEFILE_COPY_ALLOWED) {  
1389           fprintf( stderr,
1390                    "MoveFileEx32A: Illegal flag\n");
1391           DOS_ERROR( ER_GeneralFailure, EC_SystemFailure, SA_Abort,
1392                      EL_Unknown );
1393           return FALSE;
1394         }
1395         /* FIXME: (bon@elektron.ikp.physik.th-darmstadt.de 970706)
1396            Perhaps we should queue these command and execute it 
1397            when exiting... What about using on_exit(2)
1398            */
1399         fprintf( stderr,"MoveFileEx32A: Please delete file %s\n",
1400                  full_name1.long_name);
1401         fprintf( stderr,"               when Wine has finished\n");
1402         fprintf( stderr,"               like \"rm %s\"\n",
1403                  full_name1.long_name);
1404         return TRUE;
1405       }
1406       else if (unlink( full_name1.long_name ) == -1)
1407       {
1408         FILE_SetDosError();
1409         return FALSE;
1410       }
1411       else  return TRUE; /* successfully deleted */
1412
1413     if (flag & MOVEFILE_DELAY_UNTIL_REBOOT) {
1414         /* FIXME: (bon@elektron.ikp.physik.th-darmstadt.de 970706)
1415            Perhaps we should queue these command and execute it 
1416            when exiting... What about using on_exit(2)
1417            */
1418         fprintf( stderr,"MoveFileEx32A: Please move existing file %s\n"
1419                  ,full_name1.long_name);
1420         fprintf( stderr,"               to file %s\n"
1421                  ,full_name2.long_name);
1422         fprintf( stderr,"               when Wine has finished\n");
1423         fprintf( stderr,"               like \" mv %s %s\"\n",
1424                  full_name1.long_name,full_name2.long_name);
1425         return TRUE;
1426     }
1427
1428     if (!mode) /* move the file */
1429       if (rename( full_name1.long_name, full_name2.long_name ) == -1)
1430         {
1431           FILE_SetDosError();
1432           return FALSE;
1433         }
1434       else return TRUE;
1435     else /* copy File */
1436       return CopyFile32A(fn1, fn2, (!(flag & MOVEFILE_REPLACE_EXISTING))); 
1437     
1438 }
1439
1440 /**************************************************************************
1441  *           MoveFileEx32W   (KERNEL32.???)
1442  */
1443 BOOL32 WINAPI MoveFileEx32W( LPCWSTR fn1, LPCWSTR fn2, DWORD flag )
1444 {
1445     LPSTR afn1 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn1 );
1446     LPSTR afn2 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn2 );
1447     BOOL32 res = MoveFileEx32A( afn1, afn2, flag );
1448     HeapFree( GetProcessHeap(), 0, afn1 );
1449     HeapFree( GetProcessHeap(), 0, afn2 );
1450     return res;
1451 }
1452
1453
1454 /**************************************************************************
1455  *           MoveFile32A   (KERNEL32.387)
1456  *
1457  *  Move file or directory
1458  */
1459 BOOL32 WINAPI MoveFile32A( LPCSTR fn1, LPCSTR fn2 )
1460 {
1461     DOS_FULL_NAME full_name1, full_name2;
1462     struct stat fstat;
1463
1464     dprintf_file( stddeb, "MoveFile32A(%s,%s)\n", fn1, fn2 );
1465
1466     if (!DOSFS_GetFullName( fn1, TRUE, &full_name1 )) return FALSE;
1467     if (DOSFS_GetFullName( fn2, TRUE, &full_name2 )) 
1468       /* The new name must not already exist */ 
1469       return FALSE;
1470     if (!DOSFS_GetFullName( fn2, FALSE, &full_name2 )) return FALSE;
1471
1472     if (full_name1.drive == full_name2.drive) /* move */
1473     if (rename( full_name1.long_name, full_name2.long_name ) == -1)
1474     {
1475         FILE_SetDosError();
1476         return FALSE;
1477     }
1478       else return TRUE;
1479     else /*copy */ {
1480       if (stat(  full_name1.long_name, &fstat ))
1481         {
1482           dprintf_file( stddeb, "Invalid source file %s\n",
1483                         full_name1.long_name);
1484           FILE_SetDosError();
1485           return FALSE;
1486         }
1487       if (S_ISDIR(fstat.st_mode)) {
1488         /* No Move for directories across file systems */
1489         /* FIXME: Use right error code */
1490         DOS_ERROR( ER_GeneralFailure, EC_SystemFailure, SA_Abort,
1491                    EL_Unknown );
1492         return FALSE;
1493       }
1494       else
1495         return CopyFile32A(fn1, fn2, TRUE); /*fail, if exist */ 
1496     }
1497 }
1498
1499
1500 /**************************************************************************
1501  *           MoveFile32W   (KERNEL32.390)
1502  */
1503 BOOL32 WINAPI MoveFile32W( LPCWSTR fn1, LPCWSTR fn2 )
1504 {
1505     LPSTR afn1 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn1 );
1506     LPSTR afn2 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn2 );
1507     BOOL32 res = MoveFile32A( afn1, afn2 );
1508     HeapFree( GetProcessHeap(), 0, afn1 );
1509     HeapFree( GetProcessHeap(), 0, afn2 );
1510     return res;
1511 }
1512
1513
1514 /**************************************************************************
1515  *           CopyFile32A   (KERNEL32.36)
1516  */
1517 BOOL32 WINAPI CopyFile32A( LPCSTR source, LPCSTR dest, BOOL32 fail_if_exists )
1518 {
1519     HFILE32 h1, h2;
1520     BY_HANDLE_FILE_INFORMATION info;
1521     UINT32 count;
1522     BOOL32 ret = FALSE;
1523     int mode;
1524     char buffer[2048];
1525
1526     if ((h1 = _lopen32( source, OF_READ )) == HFILE_ERROR32) return FALSE;
1527     if (!GetFileInformationByHandle( h1, &info ))
1528     {
1529         CloseHandle( h1 );
1530         return FALSE;
1531     }
1532     mode = (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY) ? 0444 : 0666;
1533     if ((h2 = FILE_Create( dest, mode, fail_if_exists )) == HFILE_ERROR32)
1534     {
1535         CloseHandle( h1 );
1536         return FALSE;
1537     }
1538     while ((count = _lread32( h2, buffer, sizeof(buffer) )) > 0)
1539     {
1540         char *p = buffer;
1541         while (count > 0)
1542         {
1543             INT32 res = _lwrite32( h2, p, count );
1544             if (res <= 0) goto done;
1545             p += res;
1546             count -= res;
1547         }
1548     }
1549     ret =  TRUE;
1550 done:
1551     CloseHandle( h1 );
1552     CloseHandle( h2 );
1553     return ret;
1554 }
1555
1556
1557 /**************************************************************************
1558  *           CopyFile32W   (KERNEL32.37)
1559  */
1560 BOOL32 WINAPI CopyFile32W( LPCWSTR source, LPCWSTR dest, BOOL32 fail_if_exists)
1561 {
1562     LPSTR sourceA = HEAP_strdupWtoA( GetProcessHeap(), 0, source );
1563     LPSTR destA   = HEAP_strdupWtoA( GetProcessHeap(), 0, dest );
1564     BOOL32 ret = CopyFile32A( sourceA, destA, fail_if_exists );
1565     HeapFree( GetProcessHeap(), 0, sourceA );
1566     HeapFree( GetProcessHeap(), 0, destA );
1567     return ret;
1568 }
1569
1570
1571 /***********************************************************************
1572  *              SetFileTime   (KERNEL32.493)
1573  */
1574 BOOL32 WINAPI SetFileTime( HFILE32 hFile,
1575                            const FILETIME *lpCreationTime,
1576                            const FILETIME *lpLastAccessTime,
1577                            const FILETIME *lpLastWriteTime )
1578 {
1579     FILE_OBJECT *file = FILE_GetFile(hFile);
1580     struct utimbuf utimbuf;
1581     
1582     if (!file) return FILE_TYPE_UNKNOWN; /* FIXME: correct? */
1583     dprintf_file(stddeb,"SetFileTime(%s,%p,%p,%p)\n",
1584         file->unix_name,
1585         lpCreationTime,
1586         lpLastAccessTime,
1587         lpLastWriteTime
1588     );
1589     if (lpLastAccessTime)
1590         utimbuf.actime  = DOSFS_FileTimeToUnixTime(lpLastAccessTime, NULL);
1591     else
1592         utimbuf.actime  = 0; /* FIXME */
1593     if (lpLastWriteTime)
1594         utimbuf.modtime = DOSFS_FileTimeToUnixTime(lpLastWriteTime, NULL);
1595     else
1596         utimbuf.modtime = 0; /* FIXME */
1597     if (-1==utime(file->unix_name,&utimbuf))
1598     {
1599         FILE_ReleaseFile( file );
1600         FILE_SetDosError();
1601         return FALSE;
1602     }
1603     FILE_ReleaseFile( file );
1604     return TRUE;
1605 }
1606
1607 /* Locks need to be mirrored because unix file locking is based
1608  * on the pid. Inside of wine there can be multiple WINE processes
1609  * that share the same unix pid.
1610  * Read's and writes should check these locks also - not sure
1611  * how critical that is at this point (FIXME).
1612  */
1613
1614 static BOOL32 DOS_AddLock(FILE_OBJECT *file, struct flock *f)
1615 {
1616   DOS_FILE_LOCK *curr;
1617   DWORD         processId;
1618
1619   processId = GetCurrentProcessId();
1620
1621   /* check if lock overlaps a current lock for the same file */
1622   for (curr = locks; curr; curr = curr->next) {
1623     if (strcmp(curr->unix_name, file->unix_name) == 0) {
1624       if ((f->l_start == curr->base) && (f->l_len == curr->len))
1625         return TRUE;/* region is identic */
1626       if ((f->l_start < (curr->base + curr->len)) &&
1627           ((f->l_start + f->l_len) > curr->base)) {
1628         /* region overlaps */
1629         return FALSE;
1630       }
1631     }
1632   }
1633
1634   curr = HeapAlloc( SystemHeap, 0, sizeof(DOS_FILE_LOCK) );
1635   curr->processId = GetCurrentProcessId();
1636   curr->base = f->l_start;
1637   curr->len = f->l_len;
1638   curr->unix_name = HEAP_strdupA( SystemHeap, 0, file->unix_name);
1639   curr->next = locks;
1640   curr->dos_file = file;
1641   locks = curr;
1642   return TRUE;
1643 }
1644
1645 static void DOS_RemoveFileLocks(FILE_OBJECT *file)
1646 {
1647   DWORD         processId;
1648   DOS_FILE_LOCK **curr;
1649   DOS_FILE_LOCK *rem;
1650
1651   processId = GetCurrentProcessId();
1652   curr = &locks;
1653   while (*curr) {
1654     if ((*curr)->dos_file == file) {
1655       rem = *curr;
1656       *curr = (*curr)->next;
1657       HeapFree( SystemHeap, 0, rem->unix_name );
1658       HeapFree( SystemHeap, 0, rem );
1659     }
1660     else
1661       curr = &(*curr)->next;
1662   }
1663 }
1664
1665 static BOOL32 DOS_RemoveLock(FILE_OBJECT *file, struct flock *f)
1666 {
1667   DWORD         processId;
1668   DOS_FILE_LOCK **curr;
1669   DOS_FILE_LOCK *rem;
1670
1671   processId = GetCurrentProcessId();
1672   for (curr = &locks; *curr; curr = &(*curr)->next) {
1673     if ((*curr)->processId == processId &&
1674         (*curr)->dos_file == file &&
1675         (*curr)->base == f->l_start &&
1676         (*curr)->len == f->l_len) {
1677       /* this is the same lock */
1678       rem = *curr;
1679       *curr = (*curr)->next;
1680       HeapFree( SystemHeap, 0, rem->unix_name );
1681       HeapFree( SystemHeap, 0, rem );
1682       return TRUE;
1683     }
1684   }
1685   /* no matching lock found */
1686   return FALSE;
1687 }
1688
1689
1690 /**************************************************************************
1691  *           LockFile   (KERNEL32.511)
1692  */
1693 BOOL32 WINAPI LockFile(
1694         HFILE32 hFile,DWORD dwFileOffsetLow,DWORD dwFileOffsetHigh,
1695         DWORD nNumberOfBytesToLockLow,DWORD nNumberOfBytesToLockHigh )
1696 {
1697   struct flock f;
1698   FILE_OBJECT *file;
1699
1700   dprintf_file(stddeb, "LockFile32: handle %d offsetlow=%ld offsethigh=%ld nbyteslow=%ld nbyteshigh=%ld\n",
1701                hFile, dwFileOffsetLow, dwFileOffsetHigh,
1702                nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh);
1703
1704   if (dwFileOffsetHigh || nNumberOfBytesToLockHigh) {
1705     dprintf_file(stddeb, "LockFile32: Unimplemented bytes > 32bits\n");
1706     return FALSE;
1707   }
1708
1709   f.l_start = dwFileOffsetLow;
1710   f.l_len = nNumberOfBytesToLockLow;
1711   f.l_whence = SEEK_SET;
1712   f.l_pid = 0;
1713   f.l_type = F_WRLCK;
1714
1715   if (!(file = FILE_GetFile(hFile))) return FALSE;
1716
1717   /* shadow locks internally */
1718   if (!DOS_AddLock(file, &f)) {
1719     DOS_ERROR( ER_LockViolation, EC_AccessDenied, SA_Ignore, EL_Disk );
1720     return FALSE;
1721   }
1722
1723   /* FIXME: Unix locking commented out for now, doesn't work with Excel */
1724 #ifdef USE_UNIX_LOCKS
1725   if (fcntl(file->unix_handle, F_SETLK, &f) == -1) {
1726     if (errno == EACCES || errno == EAGAIN) {
1727       DOS_ERROR( ER_LockViolation, EC_AccessDenied, SA_Ignore, EL_Disk );
1728     }
1729     else {
1730       FILE_SetDosError();
1731     }
1732     /* remove our internal copy of the lock */
1733     DOS_RemoveLock(file, &f);
1734     return FALSE;
1735   }
1736 #endif
1737   return TRUE;
1738 }
1739
1740
1741 /**************************************************************************
1742  *           UnlockFile   (KERNEL32.703)
1743  */
1744 BOOL32 WINAPI UnlockFile(
1745         HFILE32 hFile,DWORD dwFileOffsetLow,DWORD dwFileOffsetHigh,
1746         DWORD nNumberOfBytesToUnlockLow,DWORD nNumberOfBytesToUnlockHigh )
1747 {
1748   FILE_OBJECT *file;
1749   struct flock f;
1750
1751   dprintf_file(stddeb, "UnlockFile32: handle %d offsetlow=%ld offsethigh=%ld nbyteslow=%ld nbyteshigh=%ld\n",
1752                hFile, dwFileOffsetLow, dwFileOffsetHigh,
1753                nNumberOfBytesToUnlockLow, nNumberOfBytesToUnlockHigh);
1754
1755   if (dwFileOffsetHigh || nNumberOfBytesToUnlockHigh) {
1756     dprintf_file(stddeb, "UnlockFile32: Unimplemented bytes > 32bits\n");
1757     return FALSE;
1758   }
1759
1760   f.l_start = dwFileOffsetLow;
1761   f.l_len = nNumberOfBytesToUnlockLow;
1762   f.l_whence = SEEK_SET;
1763   f.l_pid = 0;
1764   f.l_type = F_UNLCK;
1765
1766   if (!(file = FILE_GetFile(hFile))) return FALSE;
1767
1768   DOS_RemoveLock(file, &f);     /* ok if fails - may be another wine */
1769
1770   /* FIXME: Unix locking commented out for now, doesn't work with Excel */
1771 #ifdef USE_UNIX_LOCKS
1772   if (fcntl(file->unix_handle, F_SETLK, &f) == -1) {
1773     FILE_SetDosError();
1774     return FALSE;
1775   }
1776 #endif
1777   return TRUE;
1778 }
1779