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