Added several file server requests
[wine/multimedia.git] / files / file.c
blob779c41b1165845a9f3e25f168e0ace2e2ebe276f
1 /*
2 * File handling functions
4 * Copyright 1993 John Burton
5 * Copyright 1996 Alexandre Julliard
7 * TODO:
8 * Fix the CopyFileEx methods to implement the "extented" functionality.
9 * Right now, they simply call the CopyFile method.
12 #include <assert.h>
13 #include <ctype.h>
14 #include <errno.h>
15 #include <fcntl.h>
16 #include <stdlib.h>
17 #include <string.h>
18 #include <sys/errno.h>
19 #include <sys/types.h>
20 #include <sys/stat.h>
21 #include <sys/mman.h>
22 #include <sys/time.h>
23 #include <time.h>
24 #include <unistd.h>
25 #include <utime.h>
27 #include "windows.h"
28 #include "winerror.h"
29 #include "drive.h"
30 #include "file.h"
31 #include "global.h"
32 #include "heap.h"
33 #include "msdos.h"
34 #include "options.h"
35 #include "ldt.h"
36 #include "process.h"
37 #include "task.h"
38 #include "async.h"
39 #include "debug.h"
41 #include "server/request.h"
42 #include "server.h"
44 #if defined(MAP_ANONYMOUS) && !defined(MAP_ANON)
45 #define MAP_ANON MAP_ANONYMOUS
46 #endif
48 static BOOL32 FILE_Signaled(K32OBJ *ptr, DWORD tid);
49 static BOOL32 FILE_Satisfied(K32OBJ *ptr, DWORD thread_id);
50 static void FILE_AddWait(K32OBJ *ptr, DWORD tid);
51 static void FILE_RemoveWait(K32OBJ *ptr, DWORD thread_id);
52 static BOOL32 FILE_Read(K32OBJ *ptr, LPVOID lpBuffer, DWORD nNumberOfChars,
53 LPDWORD lpNumberOfChars, LPOVERLAPPED lpOverlapped);
54 static BOOL32 FILE_Write(K32OBJ *ptr, LPCVOID lpBuffer, DWORD nNumberOfChars,
55 LPDWORD lpNumberOfChars, LPOVERLAPPED lpOverlapped);
56 static void FILE_Destroy( K32OBJ *obj );
58 const K32OBJ_OPS FILE_Ops =
60 FILE_Signaled, /* signaled */
61 FILE_Satisfied, /* satisfied */
62 FILE_AddWait, /* add_wait */
63 FILE_RemoveWait, /* remove_wait */
64 FILE_Read, /* read */
65 FILE_Write, /* write */
66 FILE_Destroy /* destroy */
69 struct DOS_FILE_LOCK {
70 struct DOS_FILE_LOCK * next;
71 DWORD base;
72 DWORD len;
73 DWORD processId;
74 FILE_OBJECT * dos_file;
75 char * unix_name;
78 typedef struct DOS_FILE_LOCK DOS_FILE_LOCK;
80 static DOS_FILE_LOCK *locks = NULL;
81 static void DOS_RemoveFileLocks(FILE_OBJECT *file);
83 /***********************************************************************
84 * FILE_Alloc
86 * Allocate a file. The unix_handle is closed.
88 HFILE32 FILE_Alloc( FILE_OBJECT **file, int unix_handle )
90 HFILE32 handle;
91 struct create_file_request req;
92 struct create_file_reply reply;
93 int len;
94 int fd = dup(unix_handle);
96 req.access = FILE_ALL_ACCESS | GENERIC_READ |
97 GENERIC_WRITE | GENERIC_EXECUTE; /* FIXME */
98 req.inherit = 1; /* FIXME */
99 CLIENT_SendRequest( REQ_CREATE_FILE, unix_handle, 1, &req, sizeof(req) );
100 CLIENT_WaitReply( &len, NULL, 1, &reply, sizeof(reply) );
101 CHECK_LEN( len, sizeof(reply) );
102 if (reply.handle == -1) return INVALID_HANDLE_VALUE32;
104 *file = HeapAlloc( SystemHeap, 0, sizeof(FILE_OBJECT) );
105 if (!*file)
107 DOS_ERROR( ER_TooManyOpenFiles, EC_ProgramError, SA_Abort, EL_Disk );
108 CLIENT_CloseHandle( reply.handle );
109 return (HFILE32)NULL;
111 (*file)->header.type = K32OBJ_FILE;
112 (*file)->header.refcount = 0;
113 (*file)->unix_name = NULL;
114 (*file)->unix_handle = fd;
115 (*file)->type = FILE_TYPE_DISK;
116 (*file)->pos = 0;
117 (*file)->mode = 0;
118 (*file)->wait_queue = NULL;
120 handle = HANDLE_Alloc( PROCESS_Current(), &(*file)->header, req.access,
121 req.inherit, reply.handle );
122 /* If the allocation failed, the object is already destroyed */
123 if (handle == INVALID_HANDLE_VALUE32) *file = NULL;
124 return handle;
127 /***********************************************************************
128 * FILE_async_handler [internal]
130 #if 1
131 static void
132 FILE_async_handler(int unixfd,void *private) {
133 FILE_OBJECT *file = (FILE_OBJECT*)private;
135 SYNC_WakeUp(&file->wait_queue,INFINITE32);
138 static BOOL32 FILE_Signaled(K32OBJ *ptr, DWORD thread_id)
140 fd_set fds,*readfds = NULL,*writefds = NULL;
141 struct timeval tv;
142 FILE_OBJECT *file = (FILE_OBJECT *)ptr;
144 FD_ZERO(&fds);
145 FD_SET(file->unix_handle,&fds);
146 if (file->mode == OF_READ) readfds = &fds;
147 if (file->mode == OF_WRITE) writefds = &fds;
148 if (file->mode == OF_READWRITE) {writefds = &fds; readfds = &fds;}
149 tv.tv_sec = 0;
150 tv.tv_usec = 0;
151 assert(readfds || writefds);
152 if (select(file->unix_handle+1,readfds,writefds,NULL,&tv)>0)
153 return TRUE; /* we triggered one fd. Whereever. */
154 return FALSE;
157 static void FILE_AddWait(K32OBJ *ptr, DWORD thread_id)
159 FILE_OBJECT *file = (FILE_OBJECT*)ptr;
160 if (!file->wait_queue)
161 ASYNC_RegisterFD(file->unix_handle,FILE_async_handler,file);
162 THREAD_AddQueue(&file->wait_queue,thread_id);
165 static void FILE_RemoveWait(K32OBJ *ptr, DWORD thread_id)
167 FILE_OBJECT *file = (FILE_OBJECT*)ptr;
168 THREAD_RemoveQueue(&file->wait_queue,thread_id);
169 if (!file->wait_queue)
170 ASYNC_UnregisterFD(file->unix_handle,FILE_async_handler);
173 static BOOL32 FILE_Satisfied(K32OBJ *ptr, DWORD thread_id)
175 return FALSE; /* not abandoned. Hmm? */
177 #endif
179 /* FIXME: lpOverlapped is ignored */
180 static BOOL32 FILE_Read(K32OBJ *ptr, LPVOID lpBuffer, DWORD nNumberOfChars,
181 LPDWORD lpNumberOfChars, LPOVERLAPPED lpOverlapped)
183 FILE_OBJECT *file = (FILE_OBJECT *)ptr;
184 int result;
186 TRACE(file, "%p %p %ld\n", ptr, lpBuffer,
187 nNumberOfChars);
189 if (nNumberOfChars == 0) {
190 *lpNumberOfChars = 0; /* FIXME: does this change */
191 return TRUE;
194 if ( (file->pos < 0) || /* workaround, see SetFilePointer */
195 ((result = read(file->unix_handle, lpBuffer, nNumberOfChars)) == -1) )
197 FILE_SetDosError();
198 return FALSE;
200 file->pos += result;
201 *lpNumberOfChars = result;
202 return TRUE;
206 * experimentation yields that WriteFile:
207 * o does not truncate on write of 0
208 * o always changes the *lpNumberOfChars to actual number of
209 * characters written
210 * o write of 0 nNumberOfChars returns TRUE
212 static BOOL32 FILE_Write(K32OBJ *ptr, LPCVOID lpBuffer, DWORD nNumberOfChars,
213 LPDWORD lpNumberOfChars, LPOVERLAPPED lpOverlapped)
215 FILE_OBJECT *file = (FILE_OBJECT *)ptr;
216 int result;
218 TRACE(file, "%p %p %ld\n", ptr, lpBuffer,
219 nNumberOfChars);
221 *lpNumberOfChars = 0;
224 * I assume this loop around EAGAIN is here because
225 * win32 doesn't have interrupted system calls
228 if (file->pos < 0) { /* workaround, see SetFilePointer */
229 FILE_SetDosError();
230 return FALSE;
233 for (;;)
235 result = write(file->unix_handle, lpBuffer, nNumberOfChars);
236 if (result != -1) {
237 *lpNumberOfChars = result;
238 file->pos += result;
239 return TRUE;
241 if (errno != EINTR) {
242 FILE_SetDosError();
243 return FALSE;
250 /***********************************************************************
251 * FILE_Destroy
253 * Destroy a DOS file.
255 static void FILE_Destroy( K32OBJ *ptr )
257 FILE_OBJECT *file = (FILE_OBJECT *)ptr;
258 assert( ptr->type == K32OBJ_FILE );
260 DOS_RemoveFileLocks(file);
262 if (file->unix_name) HeapFree( SystemHeap, 0, file->unix_name );
263 ptr->type = K32OBJ_UNKNOWN;
264 HeapFree( SystemHeap, 0, file );
268 /***********************************************************************
269 * FILE_GetFile
271 * Return the DOS file associated to a task file handle. FILE_ReleaseFile must
272 * be called to release the file.
274 FILE_OBJECT *FILE_GetFile( HFILE32 handle, DWORD access, int *server_handle )
276 return (FILE_OBJECT *)HANDLE_GetObjPtr( PROCESS_Current(), handle,
277 K32OBJ_FILE, access,
278 server_handle );
282 /***********************************************************************
283 * FILE_ReleaseFile
285 * Release a DOS file obtained with FILE_GetFile.
287 void FILE_ReleaseFile( FILE_OBJECT *file )
289 K32OBJ_DecCount( &file->header );
293 /***********************************************************************
294 * FILE_GetUnixHandle
296 * Return the Unix handle associated to a file handle.
297 * The Unix handle must be closed after use.
299 int FILE_GetUnixHandle( HFILE32 hFile, DWORD access )
301 FILE_OBJECT *file;
302 int unix_handle;
303 struct get_unix_handle_request req;
305 file = (FILE_OBJECT *)HANDLE_GetObjPtr( PROCESS_Current(), hFile,
306 K32OBJ_FILE, access, &req.handle );
307 if (!file) return -1;
308 req.access = access;
309 CLIENT_SendRequest( REQ_GET_UNIX_HANDLE, -1, 1, &req, sizeof(req) );
310 CLIENT_WaitReply( NULL, &unix_handle, 0 );
311 K32OBJ_DecCount( &file->header );
312 return unix_handle;
315 /***********************************************************************
316 * FILE_UnixToDosMode
318 * PARAMS
319 * unixmode[I]
320 * RETURNS
321 * dosmode
323 static int FILE_UnixToDosMode(int unixMode)
325 int dosMode;
326 switch(unixMode & 3)
328 case O_WRONLY:
329 dosMode = OF_WRITE;
330 break;
331 case O_RDWR:
332 dosMode =OF_READWRITE;
333 break;
334 case O_RDONLY:
335 default:
336 dosMode = OF_READ;
337 break;
339 return dosMode;
342 /***********************************************************************
343 * FILE_DOSToUnixMode
345 * PARAMS
346 * dosMode[I]
347 * RETURNS
348 * unixmode
350 static int FILE_DOSToUnixMode(int dosMode)
352 int unixMode;
353 switch(dosMode & 3)
355 case OF_WRITE:
356 unixMode = O_WRONLY; break;
357 case OF_READWRITE:
358 unixMode = O_RDWR; break;
359 case OF_READ:
360 default:
361 unixMode = O_RDONLY; break;
363 return unixMode;
366 /***********************************************************************
367 * FILE_ShareDeny
369 * PARAMS
370 * oldmode[I] mode how file was first opened
371 * mode[I] mode how the file should get opened
372 * RETURNS
373 * TRUE: deny open
374 * FALSE: allow open
376 * Look what we have to do with the given SHARE modes
378 * Ralph Brown's interrupt list gives following explication, I guess
379 * the same holds for Windows, DENY ALL should be OF_SHARE_COMPAT
381 * FIXME: Validate this function
382 ========from Ralph Brown's list =========
383 (Table 0750)
384 Values of DOS file sharing behavior:
385 | Second and subsequent Opens
386 First |Compat Deny Deny Deny Deny
387 Open | All Write Read None
388 |R W RW R W RW R W RW R W RW R W RW
389 - - - - -| - - - - - - - - - - - - - - - - -
390 Compat R |Y Y Y N N N 1 N N N N N 1 N N
391 W |Y Y Y N N N N N N N N N N N N
392 RW|Y Y Y N N N N N N N N N N N N
393 - - - - -|
394 Deny R |C C C N N N N N N N N N N N N
395 All W |C C C N N N N N N N N N N N N
396 RW|C C C N N N N N N N N N N N N
397 - - - - -|
398 Deny R |2 C C N N N Y N N N N N Y N N
399 Write W |C C C N N N N N N Y N N Y N N
400 RW|C C C N N N N N N N N N Y N N
401 - - - - -|
402 Deny R |C C C N N N N Y N N N N N Y N
403 Read W |C C C N N N N N N N Y N N Y N
404 RW|C C C N N N N N N N N N N Y N
405 - - - - -|
406 Deny R |2 C C N N N Y Y Y N N N Y Y Y
407 None W |C C C N N N N N N Y Y Y Y Y Y
408 RW|C C C N N N N N N N N N Y Y Y
409 Legend: Y = open succeeds, N = open fails with error code 05h
410 C = open fails, INT 24 generated
411 1 = open succeeds if file read-only, else fails with error code
412 2 = open succeeds if file read-only, else fails with INT 24
413 ========end of description from Ralph Brown's List =====
414 For every "Y" in the table we return FALSE
415 For every "N" we set the DOS_ERROR and return TRUE
416 For all other cases we barf,set the DOS_ERROR and return TRUE
419 static BOOL32 FILE_ShareDeny( int mode, int oldmode)
421 int oldsharemode = oldmode & 0x70;
422 int sharemode = mode & 0x70;
423 int oldopenmode = oldmode & 3;
424 int openmode = mode & 3;
426 switch (oldsharemode)
428 case OF_SHARE_COMPAT:
429 if (sharemode == OF_SHARE_COMPAT) return FALSE;
430 if (openmode == OF_READ) goto test_ro_err05 ;
431 goto fail_error05;
432 case OF_SHARE_EXCLUSIVE:
433 if (sharemode == OF_SHARE_COMPAT) goto fail_int24;
434 goto fail_error05;
435 case OF_SHARE_DENY_WRITE:
436 if (openmode != OF_READ)
438 if (sharemode == OF_SHARE_COMPAT) goto fail_int24;
439 goto fail_error05;
441 switch (sharemode)
443 case OF_SHARE_COMPAT:
444 if (oldopenmode == OF_READ) goto test_ro_int24 ;
445 goto fail_int24;
446 case OF_SHARE_DENY_NONE :
447 return FALSE;
448 case OF_SHARE_DENY_WRITE :
449 if (oldopenmode == OF_READ) return FALSE;
450 case OF_SHARE_DENY_READ :
451 if (oldopenmode == OF_WRITE) return FALSE;
452 case OF_SHARE_EXCLUSIVE:
453 default:
454 goto fail_error05;
456 break;
457 case OF_SHARE_DENY_READ:
458 if (openmode != OF_WRITE)
460 if (sharemode == OF_SHARE_COMPAT) goto fail_int24;
461 goto fail_error05;
463 switch (sharemode)
465 case OF_SHARE_COMPAT:
466 goto fail_int24;
467 case OF_SHARE_DENY_NONE :
468 return FALSE;
469 case OF_SHARE_DENY_WRITE :
470 if (oldopenmode == OF_READ) return FALSE;
471 case OF_SHARE_DENY_READ :
472 if (oldopenmode == OF_WRITE) return FALSE;
473 case OF_SHARE_EXCLUSIVE:
474 default:
475 goto fail_error05;
477 break;
478 case OF_SHARE_DENY_NONE:
479 switch (sharemode)
481 case OF_SHARE_COMPAT:
482 goto fail_int24;
483 case OF_SHARE_DENY_NONE :
484 return FALSE;
485 case OF_SHARE_DENY_WRITE :
486 if (oldopenmode == OF_READ) return FALSE;
487 case OF_SHARE_DENY_READ :
488 if (oldopenmode == OF_WRITE) return FALSE;
489 case OF_SHARE_EXCLUSIVE:
490 default:
491 goto fail_error05;
493 default:
494 ERR(file,"unknown mode\n");
496 ERR(file,"shouldn't happen\n");
497 ERR(file,"Please report to bon@elektron.ikp.physik.tu-darmstadt.de\n");
498 return TRUE;
500 test_ro_int24:
501 if (oldmode == OF_READ)
502 return FALSE;
503 /* Fall through */
504 fail_int24:
505 FIXME(file,"generate INT24 missing\n");
506 /* Is this the right error? */
507 DOS_ERROR( ER_AccessDenied, EC_AccessDenied, SA_Abort, EL_Disk );
508 return TRUE;
510 test_ro_err05:
511 if (oldmode == OF_READ)
512 return FALSE;
513 /* fall through */
514 fail_error05:
515 TRACE(file,"Access Denied, oldmode 0x%02x mode 0x%02x\n",oldmode,mode);
516 DOS_ERROR( ER_AccessDenied, EC_AccessDenied, SA_Abort, EL_Disk );
517 return TRUE;
522 /***********************************************************************
525 * Look if the File is in Use For the OF_SHARE_XXX options
527 * PARAMS
528 * name [I]: full unix name of the file that should be opened
529 * mode [O]: mode how the file was first opened
530 * RETURNS
531 * TRUE if the file was opened before
532 * FALSE if we open the file exclusive for this process
534 * Scope of the files we look for is only the current pdb
535 * Could we use /proc/self/? on Linux for this?
536 * Should we use flock? Should we create another structure?
537 * Searching through all files seem quite expensive for me, but
538 * I don't see any other way.
540 * FIXME: Extend scope to the whole Wine process
543 static BOOL32 FILE_InUse(char * name, int * mode)
545 FILE_OBJECT *file;
546 int i;
547 HGLOBAL16 hPDB = GetCurrentPDB();
548 PDB *pdb = (PDB *)GlobalLock16( hPDB );
550 if (!pdb) return 0;
551 for (i=0;i<pdb->nbFiles;i++)
553 file =FILE_GetFile( (HFILE32)i, 0, NULL );
554 if(file)
556 if(file->unix_name)
558 TRACE(file,"got %s at %d\n",file->unix_name,i);
559 if(!lstrcmp32A(file->unix_name,name))
561 *mode = file->mode;
562 FILE_ReleaseFile(file);
563 return TRUE;
566 FILE_ReleaseFile(file);
569 return FALSE;
572 /***********************************************************************
573 * FILE_SetDosError
575 * Set the DOS error code from errno.
577 void FILE_SetDosError(void)
579 int save_errno = errno; /* errno gets overwritten by printf */
581 TRACE(file, "errno = %d %s\n", errno, strerror(errno));
582 switch (save_errno)
584 case EAGAIN:
585 DOS_ERROR( ER_ShareViolation, EC_Temporary, SA_Retry, EL_Disk );
586 break;
587 case EBADF:
588 DOS_ERROR( ER_InvalidHandle, EC_ProgramError, SA_Abort, EL_Disk );
589 break;
590 case ENOSPC:
591 DOS_ERROR( ER_DiskFull, EC_MediaError, SA_Abort, EL_Disk );
592 break;
593 case EACCES:
594 case EPERM:
595 case EROFS:
596 DOS_ERROR( ER_AccessDenied, EC_AccessDenied, SA_Abort, EL_Disk );
597 break;
598 case EBUSY:
599 DOS_ERROR( ER_LockViolation, EC_AccessDenied, SA_Abort, EL_Disk );
600 break;
601 case ENOENT:
602 DOS_ERROR( ER_FileNotFound, EC_NotFound, SA_Abort, EL_Disk );
603 break;
604 case EISDIR:
605 DOS_ERROR( ER_CanNotMakeDir, EC_AccessDenied, SA_Abort, EL_Unknown );
606 break;
607 case ENFILE:
608 case EMFILE:
609 DOS_ERROR( ER_NoMoreFiles, EC_MediaError, SA_Abort, EL_Unknown );
610 break;
611 case EEXIST:
612 DOS_ERROR( ER_FileExists, EC_Exists, SA_Abort, EL_Disk );
613 break;
614 case EINVAL:
615 case ESPIPE:
616 DOS_ERROR( ER_SeekError, EC_NotFound, SA_Ignore, EL_Disk );
617 break;
618 case ENOTEMPTY:
619 DOS_ERROR( ERROR_DIR_NOT_EMPTY, EC_Exists, SA_Ignore, EL_Disk );
620 break;
621 default:
622 perror( "int21: unknown errno" );
623 DOS_ERROR( ER_GeneralFailure, EC_SystemFailure, SA_Abort, EL_Unknown );
624 break;
626 errno = save_errno;
630 /***********************************************************************
631 * FILE_DupUnixHandle
633 * Duplicate a Unix handle into a task handle.
635 HFILE32 FILE_DupUnixHandle( int fd )
637 int unix_handle;
638 FILE_OBJECT *file;
640 if ((unix_handle = dup(fd)) == -1)
642 FILE_SetDosError();
643 return INVALID_HANDLE_VALUE32;
645 return FILE_Alloc( &file, unix_handle );
649 /***********************************************************************
650 * FILE_OpenUnixFile
652 HFILE32 FILE_OpenUnixFile( const char *name, int mode )
654 HFILE32 handle;
655 int unix_handle;
656 FILE_OBJECT *file;
657 struct stat st;
659 if ((unix_handle = open( name, mode, 0666 )) == -1)
661 if (!Options.failReadOnly && (mode == O_RDWR))
662 unix_handle = open( name, O_RDONLY );
664 if ((unix_handle == -1) || (fstat( unix_handle, &st ) == -1))
666 FILE_SetDosError();
667 return INVALID_HANDLE_VALUE32;
669 if (S_ISDIR(st.st_mode))
671 DOS_ERROR( ER_AccessDenied, EC_AccessDenied, SA_Abort, EL_Disk );
672 close( unix_handle );
673 return INVALID_HANDLE_VALUE32;
676 /* File opened OK, now fill the FILE_OBJECT */
678 if ((handle = FILE_Alloc( &file, unix_handle )) == INVALID_HANDLE_VALUE32)
679 return INVALID_HANDLE_VALUE32;
680 file->unix_name = HEAP_strdupA( SystemHeap, 0, name );
681 return handle;
685 /***********************************************************************
686 * FILE_Open
688 * path[I] name of file to open
689 * mode[I] mode how to open, in unix notation
690 * shareMode[I] the sharing mode in the win OpenFile notation
693 HFILE32 FILE_Open( LPCSTR path, INT32 mode, INT32 shareMode )
695 DOS_FULL_NAME full_name;
696 const char *unixName;
697 int oldMode, dosMode; /* FIXME: Do we really need unixmode as argument for
698 FILE_Open */
699 FILE_OBJECT *file;
700 HFILE32 hFileRet;
701 BOOL32 fileInUse = FALSE;
703 TRACE(file, "'%s' %04x\n", path, mode );
705 if (!path) return HFILE_ERROR32;
707 if (DOSFS_GetDevice( path ))
709 HFILE32 ret;
711 TRACE(file, "opening device '%s'\n", path );
713 if (HFILE_ERROR32!=(ret=DOSFS_OpenDevice( path, mode )))
714 return ret;
716 /* Do not silence this please. It is a critical error. -MM */
717 ERR(file, "Couldn't open device '%s'!\n",path);
718 DOS_ERROR( ER_FileNotFound, EC_NotFound, SA_Abort, EL_Disk );
719 return HFILE_ERROR32;
722 else /* check for filename, don't check for last entry if creating */
724 if (!DOSFS_GetFullName( path, !(mode & O_CREAT), &full_name ))
725 return HFILE_ERROR32;
726 unixName = full_name.long_name;
729 dosMode = FILE_UnixToDosMode(mode)| shareMode;
730 fileInUse = FILE_InUse(full_name.long_name,&oldMode);
731 if(fileInUse)
733 TRACE(file, "found another instance with mode 0x%02x\n",oldMode&0x70);
734 if (FILE_ShareDeny(dosMode,oldMode)) return HFILE_ERROR32;
736 hFileRet = FILE_OpenUnixFile( unixName, mode );
737 /* we need to save the mode, but only if it is not in use yet*/
738 if ((hFileRet) && (!fileInUse) && ((file =FILE_GetFile(hFileRet, 0, NULL))))
740 file->mode=dosMode;
741 FILE_ReleaseFile(file);
743 return hFileRet;
748 /***********************************************************************
749 * FILE_Create
751 static HFILE32 FILE_Create( LPCSTR path, int mode, int unique )
753 HFILE32 handle;
754 int unix_handle;
755 FILE_OBJECT *file;
756 DOS_FULL_NAME full_name;
757 BOOL32 fileInUse = FALSE;
758 int oldMode,dosMode; /* FIXME: Do we really need unixmode as argument for
759 FILE_Create */;
761 TRACE(file, "'%s' %04x %d\n", path, mode, unique );
763 if (!path) return INVALID_HANDLE_VALUE32;
765 if (DOSFS_GetDevice( path ))
767 WARN(file, "cannot create DOS device '%s'!\n", path);
768 DOS_ERROR( ER_AccessDenied, EC_NotFound, SA_Abort, EL_Disk );
769 return INVALID_HANDLE_VALUE32;
772 if (!DOSFS_GetFullName( path, FALSE, &full_name )) return INVALID_HANDLE_VALUE32;
774 dosMode = FILE_UnixToDosMode(mode);
775 fileInUse = FILE_InUse(full_name.long_name,&oldMode);
776 if(fileInUse)
778 TRACE(file, "found another instance with mode 0x%02x\n",oldMode&0x70);
779 if (FILE_ShareDeny(dosMode,oldMode)) return INVALID_HANDLE_VALUE32;
782 if ((unix_handle = open( full_name.long_name,
783 O_CREAT | O_TRUNC | O_RDWR | (unique ? O_EXCL : 0),
784 mode )) == -1)
786 FILE_SetDosError();
787 return INVALID_HANDLE_VALUE32;
790 /* File created OK, now fill the FILE_OBJECT */
792 if ((handle = FILE_Alloc( &file, unix_handle )) == INVALID_HANDLE_VALUE32)
793 return INVALID_HANDLE_VALUE32;
794 file->unix_name = HEAP_strdupA( SystemHeap, 0, full_name.long_name );
795 file->mode = dosMode;
796 return handle;
800 /***********************************************************************
801 * FILE_FillInfo
803 * Fill a file information from a struct stat.
805 static void FILE_FillInfo( struct stat *st, BY_HANDLE_FILE_INFORMATION *info )
807 if (S_ISDIR(st->st_mode))
808 info->dwFileAttributes = FILE_ATTRIBUTE_DIRECTORY;
809 else
810 info->dwFileAttributes = FILE_ATTRIBUTE_ARCHIVE;
811 if (!(st->st_mode & S_IWUSR))
812 info->dwFileAttributes |= FILE_ATTRIBUTE_READONLY;
814 DOSFS_UnixTimeToFileTime( st->st_mtime, &info->ftCreationTime, 0 );
815 DOSFS_UnixTimeToFileTime( st->st_mtime, &info->ftLastWriteTime, 0 );
816 DOSFS_UnixTimeToFileTime( st->st_atime, &info->ftLastAccessTime, 0 );
818 info->dwVolumeSerialNumber = 0; /* FIXME */
819 info->nFileSizeHigh = 0;
820 info->nFileSizeLow = S_ISDIR(st->st_mode) ? 0 : st->st_size;
821 info->nNumberOfLinks = st->st_nlink;
822 info->nFileIndexHigh = 0;
823 info->nFileIndexLow = st->st_ino;
827 /***********************************************************************
828 * FILE_Stat
830 * Stat a Unix path name. Return TRUE if OK.
832 BOOL32 FILE_Stat( LPCSTR unixName, BY_HANDLE_FILE_INFORMATION *info )
834 struct stat st;
836 if (!unixName || !info) return FALSE;
838 if (stat( unixName, &st ) == -1)
840 FILE_SetDosError();
841 return FALSE;
843 FILE_FillInfo( &st, info );
844 return TRUE;
848 /***********************************************************************
849 * GetFileInformationByHandle (KERNEL32.219)
851 DWORD WINAPI GetFileInformationByHandle( HFILE32 hFile,
852 BY_HANDLE_FILE_INFORMATION *info )
854 FILE_OBJECT *file;
855 struct get_file_info_request req;
856 struct get_file_info_reply reply;
857 int len;
859 if (!info) return 0;
860 if (!(file = FILE_GetFile( hFile, 0, &req.handle ))) return 0;
861 CLIENT_SendRequest( REQ_GET_FILE_INFO, -1, 1, &req, sizeof(req) );
862 CLIENT_WaitReply( &len, NULL, 1, &reply, sizeof(reply) );
863 CHECK_LEN( len, sizeof(reply) );
864 FILE_ReleaseFile( file );
866 DOSFS_UnixTimeToFileTime( reply.write_time, &info->ftCreationTime, 0 );
867 DOSFS_UnixTimeToFileTime( reply.write_time, &info->ftLastWriteTime, 0 );
868 DOSFS_UnixTimeToFileTime( reply.access_time, &info->ftLastAccessTime, 0 );
869 info->dwFileAttributes = reply.attr;
870 info->dwVolumeSerialNumber = reply.serial;
871 info->nFileSizeHigh = reply.size_high;
872 info->nFileSizeLow = reply.size_low;
873 info->nNumberOfLinks = reply.links;
874 info->nFileIndexHigh = reply.index_high;
875 info->nFileIndexLow = reply.index_low;
876 return 1;
880 /**************************************************************************
881 * GetFileAttributes16 (KERNEL.420)
883 DWORD WINAPI GetFileAttributes16( LPCSTR name )
885 return GetFileAttributes32A( name );
889 /**************************************************************************
890 * GetFileAttributes32A (KERNEL32.217)
892 DWORD WINAPI GetFileAttributes32A( LPCSTR name )
894 DOS_FULL_NAME full_name;
895 BY_HANDLE_FILE_INFORMATION info;
897 if (name == NULL || *name=='\0') return -1;
899 if (!DOSFS_GetFullName( name, TRUE, &full_name )) return -1;
900 if (!FILE_Stat( full_name.long_name, &info )) return -1;
901 return info.dwFileAttributes;
905 /**************************************************************************
906 * GetFileAttributes32W (KERNEL32.218)
908 DWORD WINAPI GetFileAttributes32W( LPCWSTR name )
910 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, name );
911 DWORD res = GetFileAttributes32A( nameA );
912 HeapFree( GetProcessHeap(), 0, nameA );
913 return res;
917 /***********************************************************************
918 * GetFileSize (KERNEL32.220)
920 DWORD WINAPI GetFileSize( HFILE32 hFile, LPDWORD filesizehigh )
922 BY_HANDLE_FILE_INFORMATION info;
923 if (!GetFileInformationByHandle( hFile, &info )) return 0;
924 if (filesizehigh) *filesizehigh = info.nFileSizeHigh;
925 return info.nFileSizeLow;
929 /***********************************************************************
930 * GetFileTime (KERNEL32.221)
932 BOOL32 WINAPI GetFileTime( HFILE32 hFile, FILETIME *lpCreationTime,
933 FILETIME *lpLastAccessTime,
934 FILETIME *lpLastWriteTime )
936 BY_HANDLE_FILE_INFORMATION info;
937 if (!GetFileInformationByHandle( hFile, &info )) return FALSE;
938 if (lpCreationTime) *lpCreationTime = info.ftCreationTime;
939 if (lpLastAccessTime) *lpLastAccessTime = info.ftLastAccessTime;
940 if (lpLastWriteTime) *lpLastWriteTime = info.ftLastWriteTime;
941 return TRUE;
944 /***********************************************************************
945 * CompareFileTime (KERNEL32.28)
947 INT32 WINAPI CompareFileTime( LPFILETIME x, LPFILETIME y )
949 if (!x || !y) return -1;
951 if (x->dwHighDateTime > y->dwHighDateTime)
952 return 1;
953 if (x->dwHighDateTime < y->dwHighDateTime)
954 return -1;
955 if (x->dwLowDateTime > y->dwLowDateTime)
956 return 1;
957 if (x->dwLowDateTime < y->dwLowDateTime)
958 return -1;
959 return 0;
962 /***********************************************************************
963 * FILE_Dup
965 * dup() function for DOS handles.
967 HFILE32 FILE_Dup( HFILE32 hFile )
969 HFILE32 handle;
971 TRACE(file, "FILE_Dup for handle %d\n", hFile );
972 if (!DuplicateHandle( GetCurrentProcess(), hFile, GetCurrentProcess(),
973 &handle, FILE_ALL_ACCESS /* FIXME */, FALSE, 0 ))
974 handle = HFILE_ERROR32;
975 TRACE(file, "FILE_Dup return handle %d\n", handle );
976 return handle;
980 /***********************************************************************
981 * FILE_Dup2
983 * dup2() function for DOS handles.
985 HFILE32 FILE_Dup2( HFILE32 hFile1, HFILE32 hFile2 )
987 FILE_OBJECT *file;
989 TRACE(file, "FILE_Dup2 for handle %d\n", hFile1 );
990 /* FIXME: should use DuplicateHandle */
991 if (!(file = FILE_GetFile( hFile1, 0, NULL ))) return HFILE_ERROR32;
992 if (!HANDLE_SetObjPtr( PROCESS_Current(), hFile2, &file->header, 0 ))
993 hFile2 = HFILE_ERROR32;
994 FILE_ReleaseFile( file );
995 return hFile2;
999 /***********************************************************************
1000 * GetTempFileName16 (KERNEL.97)
1002 UINT16 WINAPI GetTempFileName16( BYTE drive, LPCSTR prefix, UINT16 unique,
1003 LPSTR buffer )
1005 char temppath[144];
1007 if (!(drive & ~TF_FORCEDRIVE)) /* drive 0 means current default drive */
1008 drive |= DRIVE_GetCurrentDrive() + 'A';
1010 if ((drive & TF_FORCEDRIVE) &&
1011 !DRIVE_IsValid( toupper(drive & ~TF_FORCEDRIVE) - 'A' ))
1013 drive &= ~TF_FORCEDRIVE;
1014 WARN(file, "invalid drive %d specified\n", drive );
1017 if (drive & TF_FORCEDRIVE)
1018 sprintf(temppath,"%c:", drive & ~TF_FORCEDRIVE );
1019 else
1020 GetTempPath32A( 132, temppath );
1021 return (UINT16)GetTempFileName32A( temppath, prefix, unique, buffer );
1025 /***********************************************************************
1026 * GetTempFileName32A (KERNEL32.290)
1028 UINT32 WINAPI GetTempFileName32A( LPCSTR path, LPCSTR prefix, UINT32 unique,
1029 LPSTR buffer)
1031 static UINT32 unique_temp;
1032 DOS_FULL_NAME full_name;
1033 int i;
1034 LPSTR p;
1035 UINT32 num;
1037 if ( !path || !prefix || !buffer ) return 0;
1039 if (!unique_temp) unique_temp = time(NULL) & 0xffff;
1040 num = unique ? (unique & 0xffff) : (unique_temp++ & 0xffff);
1042 strcpy( buffer, path );
1043 p = buffer + strlen(buffer);
1045 /* add a \, if there isn't one and path is more than just the drive letter ... */
1046 if ( !((strlen(buffer) == 2) && (buffer[1] == ':'))
1047 && ((p == buffer) || (p[-1] != '\\'))) *p++ = '\\';
1049 *p++ = '~';
1050 for (i = 3; (i > 0) && (*prefix); i--) *p++ = *prefix++;
1051 sprintf( p, "%04x.tmp", num );
1053 /* Now try to create it */
1055 if (!unique)
1059 HFILE32 handle = FILE_Create( buffer, 0666, TRUE );
1060 if (handle != INVALID_HANDLE_VALUE32)
1061 { /* We created it */
1062 TRACE(file, "created %s\n",
1063 buffer);
1064 CloseHandle( handle );
1065 break;
1067 if (DOS_ExtendedError != ER_FileExists)
1068 break; /* No need to go on */
1069 num++;
1070 sprintf( p, "%04x.tmp", num );
1071 } while (num != (unique & 0xffff));
1074 /* Get the full path name */
1076 if (DOSFS_GetFullName( buffer, FALSE, &full_name ))
1078 /* Check if we have write access in the directory */
1079 if ((p = strrchr( full_name.long_name, '/' ))) *p = '\0';
1080 if (access( full_name.long_name, W_OK ) == -1)
1081 WARN(file, "returns '%s', which doesn't seem to be writeable.\n",
1082 buffer);
1084 TRACE(file, "returning %s\n", buffer );
1085 return unique ? unique : num;
1089 /***********************************************************************
1090 * GetTempFileName32W (KERNEL32.291)
1092 UINT32 WINAPI GetTempFileName32W( LPCWSTR path, LPCWSTR prefix, UINT32 unique,
1093 LPWSTR buffer )
1095 LPSTR patha,prefixa;
1096 char buffera[144];
1097 UINT32 ret;
1099 if (!path) return 0;
1100 patha = HEAP_strdupWtoA( GetProcessHeap(), 0, path );
1101 prefixa = HEAP_strdupWtoA( GetProcessHeap(), 0, prefix );
1102 ret = GetTempFileName32A( patha, prefixa, unique, buffera );
1103 lstrcpyAtoW( buffer, buffera );
1104 HeapFree( GetProcessHeap(), 0, patha );
1105 HeapFree( GetProcessHeap(), 0, prefixa );
1106 return ret;
1110 /***********************************************************************
1111 * FILE_DoOpenFile
1113 * Implementation of OpenFile16() and OpenFile32().
1115 static HFILE32 FILE_DoOpenFile( LPCSTR name, OFSTRUCT *ofs, UINT32 mode,
1116 BOOL32 win32 )
1118 HFILE32 hFileRet;
1119 FILETIME filetime;
1120 WORD filedatetime[2];
1121 DOS_FULL_NAME full_name;
1122 char *p;
1123 int unixMode, oldMode;
1124 FILE_OBJECT *file;
1125 BOOL32 fileInUse = FALSE;
1127 if (!ofs) return HFILE_ERROR32;
1130 ofs->cBytes = sizeof(OFSTRUCT);
1131 ofs->nErrCode = 0;
1132 if (mode & OF_REOPEN) name = ofs->szPathName;
1134 if (!name) {
1135 ERR(file, "called with `name' set to NULL ! Please debug.\n");
1136 return HFILE_ERROR32;
1139 TRACE(file, "%s %04x\n", name, mode );
1141 /* the watcom 10.6 IDE relies on a valid path returned in ofs->szPathName
1142 Are there any cases where getting the path here is wrong?
1143 Uwe Bonnes 1997 Apr 2 */
1144 if (!GetFullPathName32A( name, sizeof(ofs->szPathName),
1145 ofs->szPathName, NULL )) goto error;
1147 /* OF_PARSE simply fills the structure */
1149 if (mode & OF_PARSE)
1151 ofs->fFixedDisk = (GetDriveType16( ofs->szPathName[0]-'A' )
1152 != DRIVE_REMOVABLE);
1153 TRACE(file, "(%s): OF_PARSE, res = '%s'\n",
1154 name, ofs->szPathName );
1155 return 0;
1158 /* OF_CREATE is completely different from all other options, so
1159 handle it first */
1161 if (mode & OF_CREATE)
1163 if ((hFileRet = FILE_Create(name,0666,FALSE))== INVALID_HANDLE_VALUE32)
1164 goto error;
1165 goto success;
1168 /* If OF_SEARCH is set, ignore the given path */
1170 if ((mode & OF_SEARCH) && !(mode & OF_REOPEN))
1172 /* First try the file name as is */
1173 if (DOSFS_GetFullName( name, TRUE, &full_name )) goto found;
1174 /* Now remove the path */
1175 if (name[0] && (name[1] == ':')) name += 2;
1176 if ((p = strrchr( name, '\\' ))) name = p + 1;
1177 if ((p = strrchr( name, '/' ))) name = p + 1;
1178 if (!name[0]) goto not_found;
1181 /* Now look for the file */
1183 if (!DIR_SearchPath( NULL, name, NULL, &full_name, win32 )) goto not_found;
1185 found:
1186 TRACE(file, "found %s = %s\n",
1187 full_name.long_name, full_name.short_name );
1188 lstrcpyn32A( ofs->szPathName, full_name.short_name,
1189 sizeof(ofs->szPathName) );
1191 fileInUse = FILE_InUse(full_name.long_name,&oldMode);
1192 if(fileInUse)
1194 TRACE(file, "found another instance with mode 0x%02x\n",oldMode&0x70);
1195 if (FILE_ShareDeny(mode,oldMode)) return HFILE_ERROR32;
1198 if (mode & OF_SHARE_EXCLUSIVE)
1199 /* Some InstallShield version uses OF_SHARE_EXCLUSIVE
1200 on the file <tempdir>/_ins0432._mp to determine how
1201 far installation has proceeded.
1202 _ins0432._mp is an executable and while running the
1203 application expects the open with OF_SHARE_ to fail*/
1204 /* Probable FIXME:
1205 As our loader closes the files after loading the executable,
1206 we can't find the running executable with FILE_InUse.
1207 Perhaps the loader should keep the file open.
1208 Recheck against how Win handles that case */
1210 char *last = strrchr(full_name.long_name,'/');
1211 if (!last)
1212 last = full_name.long_name - 1;
1213 if (GetModuleHandle16(last+1))
1215 TRACE(file,"Denying shared open for %s\n",full_name.long_name);
1216 return HFILE_ERROR32;
1220 if (mode & OF_DELETE)
1222 if (unlink( full_name.long_name ) == -1) goto not_found;
1223 TRACE(file, "(%s): OF_DELETE return = OK\n", name);
1224 return 1;
1227 unixMode=FILE_DOSToUnixMode(mode);
1229 hFileRet = FILE_OpenUnixFile( full_name.long_name, unixMode );
1230 if (hFileRet == HFILE_ERROR32) goto not_found;
1231 /* we need to save the mode, but only if it is not in use yet*/
1232 if( (!fileInUse) &&(file =FILE_GetFile(hFileRet,0,NULL)))
1234 file->mode=mode;
1235 FILE_ReleaseFile(file);
1238 GetFileTime( hFileRet, NULL, NULL, &filetime );
1239 FileTimeToDosDateTime( &filetime, &filedatetime[0], &filedatetime[1] );
1240 if ((mode & OF_VERIFY) && (mode & OF_REOPEN))
1242 if (memcmp( ofs->reserved, filedatetime, sizeof(ofs->reserved) ))
1244 CloseHandle( hFileRet );
1245 WARN(file, "(%s): OF_VERIFY failed\n", name );
1246 /* FIXME: what error here? */
1247 DOS_ERROR( ER_FileNotFound, EC_NotFound, SA_Abort, EL_Disk );
1248 goto error;
1251 memcpy( ofs->reserved, filedatetime, sizeof(ofs->reserved) );
1253 success: /* We get here if the open was successful */
1254 TRACE(file, "(%s): OK, return = %d\n", name, hFileRet );
1255 if (mode & OF_EXIST) /* Return the handle, but close it first */
1256 CloseHandle( hFileRet );
1257 return hFileRet;
1259 not_found: /* We get here if the file does not exist */
1260 WARN(file, "'%s' not found\n", name );
1261 DOS_ERROR( ER_FileNotFound, EC_NotFound, SA_Abort, EL_Disk );
1262 /* fall through */
1264 error: /* We get here if there was an error opening the file */
1265 ofs->nErrCode = DOS_ExtendedError;
1266 WARN(file, "(%s): return = HFILE_ERROR error= %d\n",
1267 name,ofs->nErrCode );
1268 return HFILE_ERROR32;
1272 /***********************************************************************
1273 * OpenFile16 (KERNEL.74)
1275 HFILE16 WINAPI OpenFile16( LPCSTR name, OFSTRUCT *ofs, UINT16 mode )
1277 TRACE(file,"OpenFile16(%s,%i)\n", name, mode);
1278 return HFILE32_TO_HFILE16(FILE_DoOpenFile( name, ofs, mode, FALSE ));
1282 /***********************************************************************
1283 * OpenFile32 (KERNEL32.396)
1285 HFILE32 WINAPI OpenFile32( LPCSTR name, OFSTRUCT *ofs, UINT32 mode )
1287 return FILE_DoOpenFile( name, ofs, mode, TRUE );
1291 /***********************************************************************
1292 * _lclose16 (KERNEL.81)
1294 HFILE16 WINAPI _lclose16( HFILE16 hFile )
1296 TRACE(file, "handle %d\n", hFile );
1297 return CloseHandle( HFILE16_TO_HFILE32( hFile ) ) ? 0 : HFILE_ERROR16;
1301 /***********************************************************************
1302 * _lclose32 (KERNEL32.592)
1304 HFILE32 WINAPI _lclose32( HFILE32 hFile )
1306 TRACE(file, "handle %d\n", hFile );
1307 return CloseHandle( hFile ) ? 0 : HFILE_ERROR32;
1311 /***********************************************************************
1312 * WIN16_hread
1314 LONG WINAPI WIN16_hread( HFILE16 hFile, SEGPTR buffer, LONG count )
1316 LONG maxlen;
1318 TRACE(file, "%d %08lx %ld\n",
1319 hFile, (DWORD)buffer, count );
1321 /* Some programs pass a count larger than the allocated buffer */
1322 maxlen = GetSelectorLimit( SELECTOROF(buffer) ) - OFFSETOF(buffer) + 1;
1323 if (count > maxlen) count = maxlen;
1324 return _lread32(HFILE16_TO_HFILE32(hFile), PTR_SEG_TO_LIN(buffer), count );
1328 /***********************************************************************
1329 * WIN16_lread
1331 UINT16 WINAPI WIN16_lread( HFILE16 hFile, SEGPTR buffer, UINT16 count )
1333 return (UINT16)WIN16_hread( hFile, buffer, (LONG)count );
1337 /***********************************************************************
1338 * _lread32 (KERNEL32.596)
1340 UINT32 WINAPI _lread32( HFILE32 handle, LPVOID buffer, UINT32 count )
1342 K32OBJ *ptr;
1343 DWORD numWritten;
1344 BOOL32 result = FALSE;
1346 TRACE( file, "%d %p %d\n", handle, buffer, count);
1347 if (!(ptr = HANDLE_GetObjPtr( PROCESS_Current(), handle,
1348 K32OBJ_UNKNOWN, 0, NULL))) return -1;
1349 if (K32OBJ_OPS(ptr)->read)
1350 result = K32OBJ_OPS(ptr)->read(ptr, buffer, count, &numWritten, NULL);
1351 K32OBJ_DecCount( ptr );
1352 if (!result) return -1;
1353 return (UINT32)numWritten;
1357 /***********************************************************************
1358 * _lread16 (KERNEL.82)
1360 UINT16 WINAPI _lread16( HFILE16 hFile, LPVOID buffer, UINT16 count )
1362 return (UINT16)_lread32(HFILE16_TO_HFILE32(hFile), buffer, (LONG)count );
1366 /***********************************************************************
1367 * _lcreat16 (KERNEL.83)
1369 HFILE16 WINAPI _lcreat16( LPCSTR path, INT16 attr )
1371 int mode = (attr & 1) ? 0444 : 0666;
1372 TRACE(file, "%s %02x\n", path, attr );
1373 return (HFILE16) HFILE32_TO_HFILE16(FILE_Create( path, mode, FALSE ));
1377 /***********************************************************************
1378 * _lcreat32 (KERNEL32.593)
1380 HFILE32 WINAPI _lcreat32( LPCSTR path, INT32 attr )
1382 int mode = (attr & 1) ? 0444 : 0666;
1383 TRACE(file, "%s %02x\n", path, attr );
1384 return FILE_Create( path, mode, FALSE );
1388 /***********************************************************************
1389 * _lcreat_uniq (Not a Windows API)
1391 HFILE32 _lcreat_uniq( LPCSTR path, INT32 attr )
1393 int mode = (attr & 1) ? 0444 : 0666;
1394 TRACE(file, "%s %02x\n", path, attr );
1395 return FILE_Create( path, mode, TRUE );
1399 /***********************************************************************
1400 * SetFilePointer (KERNEL32.492)
1402 DWORD WINAPI SetFilePointer( HFILE32 hFile, LONG distance, LONG *highword,
1403 DWORD method )
1405 FILE_OBJECT *file;
1406 DWORD result = 0xffffffff;
1407 int unix_handle;
1409 if (highword && *highword)
1411 FIXME(file, "64-bit offsets not supported yet\n");
1412 SetLastError( ERROR_INVALID_PARAMETER );
1413 return 0xffffffff;
1415 TRACE(file, "handle %d offset %ld origin %ld\n",
1416 hFile, distance, method );
1418 if (!(file = FILE_GetFile( hFile, 0, NULL ))) return 0xffffffff;
1419 if ((unix_handle = FILE_GetUnixHandle( hFile, 0 )) == -1)
1421 FILE_ReleaseFile( file );
1422 return 0xffffffff;
1425 /* the pointer may be positioned before the start of the file;
1426 no error is returned in that case,
1427 but subsequent attempts at I/O will produce errors.
1428 This is not allowed with Unix lseek(),
1429 so we'll need some emulation here */
1430 switch(method)
1432 case FILE_CURRENT:
1433 distance += file->pos; /* fall through */
1434 case FILE_BEGIN:
1435 if ((result = lseek(unix_handle, distance, SEEK_SET)) == -1)
1437 if ((INT32)distance < 0)
1438 file->pos = result = distance;
1440 else
1441 file->pos = result;
1442 break;
1443 case FILE_END:
1444 if ((result = lseek(unix_handle, distance, SEEK_END)) == -1)
1446 if ((INT32)distance < 0)
1448 /* get EOF */
1449 result = lseek(unix_handle, 0, SEEK_END);
1451 /* return to the old pos, as the first lseek failed */
1452 lseek(unix_handle, file->pos, SEEK_END);
1454 file->pos = (result += distance);
1456 else
1457 ERR(file, "lseek: unknown error. Please report.\n");
1459 else file->pos = result;
1460 break;
1461 default:
1462 ERR(file, "Unknown origin %ld !\n", method);
1465 if (result == -1)
1466 FILE_SetDosError();
1468 close( unix_handle );
1469 FILE_ReleaseFile( file );
1470 return result;
1474 /***********************************************************************
1475 * _llseek16 (KERNEL.84)
1477 LONG WINAPI _llseek16( HFILE16 hFile, LONG lOffset, INT16 nOrigin )
1479 return SetFilePointer( HFILE16_TO_HFILE32(hFile), lOffset, NULL, nOrigin );
1483 /***********************************************************************
1484 * _llseek32 (KERNEL32.594)
1486 LONG WINAPI _llseek32( HFILE32 hFile, LONG lOffset, INT32 nOrigin )
1488 return SetFilePointer( hFile, lOffset, NULL, nOrigin );
1492 /***********************************************************************
1493 * _lopen16 (KERNEL.85)
1495 HFILE16 WINAPI _lopen16( LPCSTR path, INT16 mode )
1497 return HFILE32_TO_HFILE16(_lopen32( path, mode ));
1501 /***********************************************************************
1502 * _lopen32 (KERNEL32.595)
1504 HFILE32 WINAPI _lopen32( LPCSTR path, INT32 mode )
1506 INT32 unixMode;
1508 TRACE(file, "('%s',%04x)\n", path, mode );
1510 unixMode= FILE_DOSToUnixMode(mode);
1511 return FILE_Open( path, unixMode , (mode & 0x70));
1515 /***********************************************************************
1516 * _lwrite16 (KERNEL.86)
1518 UINT16 WINAPI _lwrite16( HFILE16 hFile, LPCSTR buffer, UINT16 count )
1520 return (UINT16)_hwrite32( HFILE16_TO_HFILE32(hFile), buffer, (LONG)count );
1523 /***********************************************************************
1524 * _lwrite32 (KERNEL.86)
1526 UINT32 WINAPI _lwrite32( HFILE32 hFile, LPCSTR buffer, UINT32 count )
1528 return (UINT32)_hwrite32( hFile, buffer, (LONG)count );
1532 /***********************************************************************
1533 * _hread16 (KERNEL.349)
1535 LONG WINAPI _hread16( HFILE16 hFile, LPVOID buffer, LONG count)
1537 return _lread32( HFILE16_TO_HFILE32(hFile), buffer, count );
1541 /***********************************************************************
1542 * _hread32 (KERNEL32.590)
1544 LONG WINAPI _hread32( HFILE32 hFile, LPVOID buffer, LONG count)
1546 return _lread32( hFile, buffer, count );
1550 /***********************************************************************
1551 * _hwrite16 (KERNEL.350)
1553 LONG WINAPI _hwrite16( HFILE16 hFile, LPCSTR buffer, LONG count )
1555 return _hwrite32( HFILE16_TO_HFILE32(hFile), buffer, count );
1559 /***********************************************************************
1560 * _hwrite32 (KERNEL32.591)
1562 * experimenation yields that _lwrite:
1563 * o truncates the file at the current position with
1564 * a 0 len write
1565 * o returns 0 on a 0 length write
1566 * o works with console handles
1569 LONG WINAPI _hwrite32( HFILE32 handle, LPCSTR buffer, LONG count )
1571 K32OBJ *ioptr;
1572 DWORD result;
1573 BOOL32 status = FALSE;
1575 TRACE(file, "%d %p %ld\n", handle, buffer, count );
1577 if (count == 0) { /* Expand or truncate at current position */
1578 int unix_handle = FILE_GetUnixHandle( handle, GENERIC_WRITE );
1579 if ((unix_handle != -1) &&
1580 (ftruncate(unix_handle,
1581 lseek( unix_handle, 0, SEEK_CUR)) == 0 ))
1583 close( unix_handle );
1584 return 0;
1585 } else {
1586 FILE_SetDosError();
1587 close( unix_handle );
1588 return HFILE_ERROR32;
1592 if (!(ioptr = HANDLE_GetObjPtr( PROCESS_Current(), handle,
1593 K32OBJ_UNKNOWN, 0, NULL )))
1594 return HFILE_ERROR32;
1595 if (K32OBJ_OPS(ioptr)->write)
1596 status = K32OBJ_OPS(ioptr)->write(ioptr, buffer, count, &result, NULL);
1597 K32OBJ_DecCount( ioptr );
1598 if (!status) result = HFILE_ERROR32;
1599 return result;
1603 /***********************************************************************
1604 * SetHandleCount16 (KERNEL.199)
1606 UINT16 WINAPI SetHandleCount16( UINT16 count )
1608 HGLOBAL16 hPDB = GetCurrentPDB();
1609 PDB *pdb = (PDB *)GlobalLock16( hPDB );
1610 BYTE *files = PTR_SEG_TO_LIN( pdb->fileHandlesPtr );
1612 TRACE(file, "(%d)\n", count );
1614 if (count < 20) count = 20; /* No point in going below 20 */
1615 else if (count > 254) count = 254;
1617 if (count == 20)
1619 if (pdb->nbFiles > 20)
1621 memcpy( pdb->fileHandles, files, 20 );
1622 GlobalFree16( pdb->hFileHandles );
1623 pdb->fileHandlesPtr = (SEGPTR)MAKELONG( 0x18,
1624 GlobalHandleToSel( hPDB ) );
1625 pdb->hFileHandles = 0;
1626 pdb->nbFiles = 20;
1629 else /* More than 20, need a new file handles table */
1631 BYTE *newfiles;
1632 HGLOBAL16 newhandle = GlobalAlloc16( GMEM_MOVEABLE, count );
1633 if (!newhandle)
1635 DOS_ERROR( ER_OutOfMemory, EC_OutOfResource, SA_Abort, EL_Memory );
1636 return pdb->nbFiles;
1638 newfiles = (BYTE *)GlobalLock16( newhandle );
1640 if (count > pdb->nbFiles)
1642 memcpy( newfiles, files, pdb->nbFiles );
1643 memset( newfiles + pdb->nbFiles, 0xff, count - pdb->nbFiles );
1645 else memcpy( newfiles, files, count );
1646 if (pdb->nbFiles > 20) GlobalFree16( pdb->hFileHandles );
1647 pdb->fileHandlesPtr = WIN16_GlobalLock16( newhandle );
1648 pdb->hFileHandles = newhandle;
1649 pdb->nbFiles = count;
1651 return pdb->nbFiles;
1655 /*************************************************************************
1656 * SetHandleCount32 (KERNEL32.494)
1658 UINT32 WINAPI SetHandleCount32( UINT32 count )
1660 return MIN( 256, count );
1664 /***********************************************************************
1665 * FlushFileBuffers (KERNEL32.133)
1667 BOOL32 WINAPI FlushFileBuffers( HFILE32 hFile )
1669 int unix_handle;
1670 BOOL32 ret;
1672 TRACE(file, "(%d)\n", hFile );
1673 if ((unix_handle = FILE_GetUnixHandle( hFile, 0)) == -1) return FALSE;
1674 if (fsync( unix_handle ) != -1) ret = TRUE;
1675 else
1677 FILE_SetDosError();
1678 ret = FALSE;
1680 close( unix_handle );
1681 return ret;
1685 /**************************************************************************
1686 * SetEndOfFile (KERNEL32.483)
1688 BOOL32 WINAPI SetEndOfFile( HFILE32 hFile )
1690 int unix_handle;
1691 BOOL32 ret = TRUE;
1693 TRACE(file, "(%d)\n", hFile );
1694 if ((unix_handle = FILE_GetUnixHandle( hFile, GENERIC_WRITE )) == -1) return FALSE;
1695 if (ftruncate( unix_handle,
1696 lseek( unix_handle, 0, SEEK_CUR ) ))
1698 FILE_SetDosError();
1699 ret = FALSE;
1701 close( unix_handle );
1702 return ret;
1706 /***********************************************************************
1707 * DeleteFile16 (KERNEL.146)
1709 BOOL16 WINAPI DeleteFile16( LPCSTR path )
1711 return DeleteFile32A( path );
1715 /***********************************************************************
1716 * DeleteFile32A (KERNEL32.71)
1718 BOOL32 WINAPI DeleteFile32A( LPCSTR path )
1720 DOS_FULL_NAME full_name;
1722 TRACE(file, "'%s'\n", path );
1724 if (DOSFS_GetDevice( path ))
1726 WARN(file, "cannot remove DOS device '%s'!\n", path);
1727 DOS_ERROR( ER_FileNotFound, EC_NotFound, SA_Abort, EL_Disk );
1728 return FALSE;
1731 if (!DOSFS_GetFullName( path, TRUE, &full_name )) return FALSE;
1732 if (unlink( full_name.long_name ) == -1)
1734 FILE_SetDosError();
1735 return FALSE;
1737 return TRUE;
1741 /***********************************************************************
1742 * DeleteFile32W (KERNEL32.72)
1744 BOOL32 WINAPI DeleteFile32W( LPCWSTR path )
1746 LPSTR xpath = HEAP_strdupWtoA( GetProcessHeap(), 0, path );
1747 BOOL32 ret = DeleteFile32A( xpath );
1748 HeapFree( GetProcessHeap(), 0, xpath );
1749 return ret;
1753 /***********************************************************************
1754 * FILE_SetFileType
1756 BOOL32 FILE_SetFileType( HFILE32 hFile, DWORD type )
1758 FILE_OBJECT *file = FILE_GetFile( hFile, 0, NULL );
1759 if (!file) return FALSE;
1760 file->type = type;
1761 FILE_ReleaseFile( file );
1762 return TRUE;
1766 /***********************************************************************
1767 * FILE_mmap
1769 LPVOID FILE_mmap( HFILE32 hFile, LPVOID start,
1770 DWORD size_high, DWORD size_low,
1771 DWORD offset_high, DWORD offset_low,
1772 int prot, int flags )
1774 LPVOID ret;
1775 int unix_handle;
1776 FILE_OBJECT *file = FILE_GetFile( hFile, 0, NULL );
1777 if (!file) return (LPVOID)-1;
1778 if ((unix_handle = FILE_GetUnixHandle( hFile, 0 )) == -1) ret = (LPVOID)-1;
1779 else
1781 ret = FILE_dommap( file, unix_handle, start, size_high, size_low,
1782 offset_high, offset_low, prot, flags );
1783 close( unix_handle );
1785 FILE_ReleaseFile( file );
1786 return ret;
1790 /***********************************************************************
1791 * FILE_dommap
1793 LPVOID FILE_dommap( FILE_OBJECT *file, int unix_handle, LPVOID start,
1794 DWORD size_high, DWORD size_low,
1795 DWORD offset_high, DWORD offset_low,
1796 int prot, int flags )
1798 int fd = -1;
1799 int pos;
1800 LPVOID ret;
1802 if (size_high || offset_high)
1803 FIXME(file, "offsets larger than 4Gb not supported\n");
1805 if (!file)
1807 #ifdef MAP_ANON
1808 flags |= MAP_ANON;
1809 #else
1810 static int fdzero = -1;
1812 if (fdzero == -1)
1814 if ((fdzero = open( "/dev/zero", O_RDONLY )) == -1)
1816 perror( "/dev/zero: open" );
1817 exit(1);
1820 fd = fdzero;
1821 #endif /* MAP_ANON */
1822 /* Linux EINVAL's on us if we don't pass MAP_PRIVATE to an anon mmap */
1823 #ifdef MAP_SHARED
1824 flags &= ~MAP_SHARED;
1825 #endif
1826 #ifdef MAP_PRIVATE
1827 flags |= MAP_PRIVATE;
1828 #endif
1830 else fd = unix_handle;
1832 if ((ret = mmap( start, size_low, prot,
1833 flags, fd, offset_low )) != (LPVOID)-1)
1834 return ret;
1836 /* mmap() failed; if this is because the file offset is not */
1837 /* page-aligned (EINVAL), or because the underlying filesystem */
1838 /* does not support mmap() (ENOEXEC), we do it by hand. */
1840 if (!file) return ret;
1841 if ((errno != ENOEXEC) && (errno != EINVAL)) return ret;
1842 if (prot & PROT_WRITE)
1844 /* We cannot fake shared write mappings */
1845 #ifdef MAP_SHARED
1846 if (flags & MAP_SHARED) return ret;
1847 #endif
1848 #ifdef MAP_PRIVATE
1849 if (!(flags & MAP_PRIVATE)) return ret;
1850 #endif
1852 /* printf( "FILE_mmap: mmap failed (%d), faking it\n", errno );*/
1853 /* Reserve the memory with an anonymous mmap */
1854 ret = FILE_dommap( NULL, -1, start, size_high, size_low, 0, 0,
1855 PROT_READ | PROT_WRITE, flags );
1856 if (ret == (LPVOID)-1) return ret;
1857 /* Now read in the file */
1858 if ((pos = lseek( fd, offset_low, SEEK_SET )) == -1)
1860 FILE_munmap( ret, size_high, size_low );
1861 return (LPVOID)-1;
1863 read( fd, ret, size_low );
1864 lseek( fd, pos, SEEK_SET ); /* Restore the file pointer */
1865 mprotect( ret, size_low, prot ); /* Set the right protection */
1866 return ret;
1870 /***********************************************************************
1871 * FILE_munmap
1873 int FILE_munmap( LPVOID start, DWORD size_high, DWORD size_low )
1875 if (size_high)
1876 FIXME(file, "offsets larger than 4Gb not supported\n");
1877 return munmap( start, size_low );
1881 /***********************************************************************
1882 * GetFileType (KERNEL32.222)
1884 DWORD WINAPI GetFileType( HFILE32 hFile )
1886 FILE_OBJECT *file = FILE_GetFile(hFile, 0, NULL);
1887 if (!file) return FILE_TYPE_UNKNOWN; /* FIXME: correct? */
1888 FILE_ReleaseFile( file );
1889 return file->type;
1893 /**************************************************************************
1894 * MoveFileEx32A (KERNEL32.???)
1896 BOOL32 WINAPI MoveFileEx32A( LPCSTR fn1, LPCSTR fn2, DWORD flag )
1898 DOS_FULL_NAME full_name1, full_name2;
1899 int mode=0; /* mode == 1: use copy */
1901 TRACE(file, "(%s,%s,%04lx)\n", fn1, fn2, flag);
1903 if (!DOSFS_GetFullName( fn1, TRUE, &full_name1 )) return FALSE;
1904 if (fn2) { /* !fn2 means delete fn1 */
1905 if (!DOSFS_GetFullName( fn2, FALSE, &full_name2 )) return FALSE;
1906 /* Source name and target path are valid */
1907 if ( full_name1.drive != full_name2.drive)
1909 /* use copy, if allowed */
1910 if (!(flag & MOVEFILE_COPY_ALLOWED)) {
1911 /* FIXME: Use right error code */
1912 DOS_ERROR( ER_FileExists, EC_Exists, SA_Abort, EL_Disk );
1913 return FALSE;
1915 else mode =1;
1917 if (DOSFS_GetFullName( fn2, TRUE, &full_name2 ))
1918 /* target exists, check if we may overwrite */
1919 if (!(flag & MOVEFILE_REPLACE_EXISTING)) {
1920 /* FIXME: Use right error code */
1921 DOS_ERROR( ER_AccessDenied, EC_AccessDenied, SA_Abort, EL_Disk );
1922 return FALSE;
1925 else /* fn2 == NULL means delete source */
1926 if (flag & MOVEFILE_DELAY_UNTIL_REBOOT) {
1927 if (flag & MOVEFILE_COPY_ALLOWED) {
1928 WARN(file, "Illegal flag\n");
1929 DOS_ERROR( ER_GeneralFailure, EC_SystemFailure, SA_Abort,
1930 EL_Unknown );
1931 return FALSE;
1933 /* FIXME: (bon@elektron.ikp.physik.th-darmstadt.de 970706)
1934 Perhaps we should queue these command and execute it
1935 when exiting... What about using on_exit(2)
1937 FIXME(file, "Please delete file '%s' when Wine has finished\n",
1938 full_name1.long_name);
1939 return TRUE;
1941 else if (unlink( full_name1.long_name ) == -1)
1943 FILE_SetDosError();
1944 return FALSE;
1946 else return TRUE; /* successfully deleted */
1948 if (flag & MOVEFILE_DELAY_UNTIL_REBOOT) {
1949 /* FIXME: (bon@elektron.ikp.physik.th-darmstadt.de 970706)
1950 Perhaps we should queue these command and execute it
1951 when exiting... What about using on_exit(2)
1953 FIXME(file,"Please move existing file '%s' to file '%s'"
1954 "when Wine has finished\n",
1955 full_name1.long_name, full_name2.long_name);
1956 return TRUE;
1959 if (!mode) /* move the file */
1960 if (rename( full_name1.long_name, full_name2.long_name ) == -1)
1962 FILE_SetDosError();
1963 return FALSE;
1965 else return TRUE;
1966 else /* copy File */
1967 return CopyFile32A(fn1, fn2, (!(flag & MOVEFILE_REPLACE_EXISTING)));
1971 /**************************************************************************
1972 * MoveFileEx32W (KERNEL32.???)
1974 BOOL32 WINAPI MoveFileEx32W( LPCWSTR fn1, LPCWSTR fn2, DWORD flag )
1976 LPSTR afn1 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn1 );
1977 LPSTR afn2 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn2 );
1978 BOOL32 res = MoveFileEx32A( afn1, afn2, flag );
1979 HeapFree( GetProcessHeap(), 0, afn1 );
1980 HeapFree( GetProcessHeap(), 0, afn2 );
1981 return res;
1985 /**************************************************************************
1986 * MoveFile32A (KERNEL32.387)
1988 * Move file or directory
1990 BOOL32 WINAPI MoveFile32A( LPCSTR fn1, LPCSTR fn2 )
1992 DOS_FULL_NAME full_name1, full_name2;
1993 struct stat fstat;
1995 TRACE(file, "(%s,%s)\n", fn1, fn2 );
1997 if (!DOSFS_GetFullName( fn1, TRUE, &full_name1 )) return FALSE;
1998 if (DOSFS_GetFullName( fn2, TRUE, &full_name2 ))
1999 /* The new name must not already exist */
2000 return FALSE;
2001 if (!DOSFS_GetFullName( fn2, FALSE, &full_name2 )) return FALSE;
2003 if (full_name1.drive == full_name2.drive) /* move */
2004 if (rename( full_name1.long_name, full_name2.long_name ) == -1)
2006 FILE_SetDosError();
2007 return FALSE;
2009 else return TRUE;
2010 else /*copy */ {
2011 if (stat( full_name1.long_name, &fstat ))
2013 WARN(file, "Invalid source file %s\n",
2014 full_name1.long_name);
2015 FILE_SetDosError();
2016 return FALSE;
2018 if (S_ISDIR(fstat.st_mode)) {
2019 /* No Move for directories across file systems */
2020 /* FIXME: Use right error code */
2021 DOS_ERROR( ER_GeneralFailure, EC_SystemFailure, SA_Abort,
2022 EL_Unknown );
2023 return FALSE;
2025 else
2026 return CopyFile32A(fn1, fn2, TRUE); /*fail, if exist */
2031 /**************************************************************************
2032 * MoveFile32W (KERNEL32.390)
2034 BOOL32 WINAPI MoveFile32W( LPCWSTR fn1, LPCWSTR fn2 )
2036 LPSTR afn1 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn1 );
2037 LPSTR afn2 = HEAP_strdupWtoA( GetProcessHeap(), 0, fn2 );
2038 BOOL32 res = MoveFile32A( afn1, afn2 );
2039 HeapFree( GetProcessHeap(), 0, afn1 );
2040 HeapFree( GetProcessHeap(), 0, afn2 );
2041 return res;
2045 /**************************************************************************
2046 * CopyFile32A (KERNEL32.36)
2048 BOOL32 WINAPI CopyFile32A( LPCSTR source, LPCSTR dest, BOOL32 fail_if_exists )
2050 HFILE32 h1, h2;
2051 BY_HANDLE_FILE_INFORMATION info;
2052 UINT32 count;
2053 BOOL32 ret = FALSE;
2054 int mode;
2055 char buffer[2048];
2057 if ((h1 = _lopen32( source, OF_READ )) == HFILE_ERROR32) return FALSE;
2058 if (!GetFileInformationByHandle( h1, &info ))
2060 CloseHandle( h1 );
2061 return FALSE;
2063 mode = (info.dwFileAttributes & FILE_ATTRIBUTE_READONLY) ? 0444 : 0666;
2064 if ((h2 = FILE_Create( dest, mode, fail_if_exists )) == HFILE_ERROR32)
2066 CloseHandle( h1 );
2067 return FALSE;
2069 while ((count = _lread32( h1, buffer, sizeof(buffer) )) > 0)
2071 char *p = buffer;
2072 while (count > 0)
2074 INT32 res = _lwrite32( h2, p, count );
2075 if (res <= 0) goto done;
2076 p += res;
2077 count -= res;
2080 ret = TRUE;
2081 done:
2082 CloseHandle( h1 );
2083 CloseHandle( h2 );
2084 return ret;
2088 /**************************************************************************
2089 * CopyFile32W (KERNEL32.37)
2091 BOOL32 WINAPI CopyFile32W( LPCWSTR source, LPCWSTR dest, BOOL32 fail_if_exists)
2093 LPSTR sourceA = HEAP_strdupWtoA( GetProcessHeap(), 0, source );
2094 LPSTR destA = HEAP_strdupWtoA( GetProcessHeap(), 0, dest );
2095 BOOL32 ret = CopyFile32A( sourceA, destA, fail_if_exists );
2096 HeapFree( GetProcessHeap(), 0, sourceA );
2097 HeapFree( GetProcessHeap(), 0, destA );
2098 return ret;
2102 /**************************************************************************
2103 * CopyFileEx32A (KERNEL32.858)
2105 * This implementation ignores most of the extra parameters passed-in into
2106 * the "ex" version of the method and calls the CopyFile method.
2107 * It will have to be fixed eventually.
2109 BOOL32 WINAPI CopyFileEx32A(LPCSTR sourceFilename,
2110 LPCSTR destFilename,
2111 LPPROGRESS_ROUTINE progressRoutine,
2112 LPVOID appData,
2113 LPBOOL32 cancelFlagPointer,
2114 DWORD copyFlags)
2116 BOOL32 failIfExists = FALSE;
2119 * Interpret the only flag that CopyFile can interpret.
2121 if ( (copyFlags & COPY_FILE_FAIL_IF_EXISTS) != 0)
2123 failIfExists = TRUE;
2126 return CopyFile32A(sourceFilename, destFilename, failIfExists);
2129 /**************************************************************************
2130 * CopyFileEx32W (KERNEL32.859)
2132 BOOL32 WINAPI CopyFileEx32W(LPCWSTR sourceFilename,
2133 LPCWSTR destFilename,
2134 LPPROGRESS_ROUTINE progressRoutine,
2135 LPVOID appData,
2136 LPBOOL32 cancelFlagPointer,
2137 DWORD copyFlags)
2139 LPSTR sourceA = HEAP_strdupWtoA( GetProcessHeap(), 0, sourceFilename );
2140 LPSTR destA = HEAP_strdupWtoA( GetProcessHeap(), 0, destFilename );
2142 BOOL32 ret = CopyFileEx32A(sourceA,
2143 destA,
2144 progressRoutine,
2145 appData,
2146 cancelFlagPointer,
2147 copyFlags);
2149 HeapFree( GetProcessHeap(), 0, sourceA );
2150 HeapFree( GetProcessHeap(), 0, destA );
2152 return ret;
2156 /***********************************************************************
2157 * SetFileTime (KERNEL32.650)
2159 BOOL32 WINAPI SetFileTime( HFILE32 hFile,
2160 const FILETIME *lpCreationTime,
2161 const FILETIME *lpLastAccessTime,
2162 const FILETIME *lpLastWriteTime )
2164 FILE_OBJECT *file = FILE_GetFile(hFile, 0, NULL);
2165 struct utimbuf utimbuf;
2167 if (!file) return FILE_TYPE_UNKNOWN; /* FIXME: correct? */
2168 TRACE(file,"('%s',%p,%p,%p)\n",
2169 file->unix_name,
2170 lpCreationTime,
2171 lpLastAccessTime,
2172 lpLastWriteTime
2174 if (lpLastAccessTime)
2175 utimbuf.actime = DOSFS_FileTimeToUnixTime(lpLastAccessTime, NULL);
2176 else
2177 utimbuf.actime = 0; /* FIXME */
2178 if (lpLastWriteTime)
2179 utimbuf.modtime = DOSFS_FileTimeToUnixTime(lpLastWriteTime, NULL);
2180 else
2181 utimbuf.modtime = 0; /* FIXME */
2182 if (-1==utime(file->unix_name,&utimbuf))
2184 MSG("Couldn't set the time for file '%s'. Insufficient permissions !?\n", file->unix_name);
2185 FILE_ReleaseFile( file );
2186 FILE_SetDosError();
2187 return FALSE;
2189 FILE_ReleaseFile( file );
2190 return TRUE;
2193 /* Locks need to be mirrored because unix file locking is based
2194 * on the pid. Inside of wine there can be multiple WINE processes
2195 * that share the same unix pid.
2196 * Read's and writes should check these locks also - not sure
2197 * how critical that is at this point (FIXME).
2200 static BOOL32 DOS_AddLock(FILE_OBJECT *file, struct flock *f)
2202 DOS_FILE_LOCK *curr;
2203 DWORD processId;
2205 processId = GetCurrentProcessId();
2207 /* check if lock overlaps a current lock for the same file */
2208 for (curr = locks; curr; curr = curr->next) {
2209 if (strcmp(curr->unix_name, file->unix_name) == 0) {
2210 if ((f->l_start == curr->base) && (f->l_len == curr->len))
2211 return TRUE;/* region is identic */
2212 if ((f->l_start < (curr->base + curr->len)) &&
2213 ((f->l_start + f->l_len) > curr->base)) {
2214 /* region overlaps */
2215 return FALSE;
2220 curr = HeapAlloc( SystemHeap, 0, sizeof(DOS_FILE_LOCK) );
2221 curr->processId = GetCurrentProcessId();
2222 curr->base = f->l_start;
2223 curr->len = f->l_len;
2224 curr->unix_name = HEAP_strdupA( SystemHeap, 0, file->unix_name);
2225 curr->next = locks;
2226 curr->dos_file = file;
2227 locks = curr;
2228 return TRUE;
2231 static void DOS_RemoveFileLocks(FILE_OBJECT *file)
2233 DWORD processId;
2234 DOS_FILE_LOCK **curr;
2235 DOS_FILE_LOCK *rem;
2237 processId = GetCurrentProcessId();
2238 curr = &locks;
2239 while (*curr) {
2240 if ((*curr)->dos_file == file) {
2241 rem = *curr;
2242 *curr = (*curr)->next;
2243 HeapFree( SystemHeap, 0, rem->unix_name );
2244 HeapFree( SystemHeap, 0, rem );
2246 else
2247 curr = &(*curr)->next;
2251 static BOOL32 DOS_RemoveLock(FILE_OBJECT *file, struct flock *f)
2253 DWORD processId;
2254 DOS_FILE_LOCK **curr;
2255 DOS_FILE_LOCK *rem;
2257 processId = GetCurrentProcessId();
2258 for (curr = &locks; *curr; curr = &(*curr)->next) {
2259 if ((*curr)->processId == processId &&
2260 (*curr)->dos_file == file &&
2261 (*curr)->base == f->l_start &&
2262 (*curr)->len == f->l_len) {
2263 /* this is the same lock */
2264 rem = *curr;
2265 *curr = (*curr)->next;
2266 HeapFree( SystemHeap, 0, rem->unix_name );
2267 HeapFree( SystemHeap, 0, rem );
2268 return TRUE;
2271 /* no matching lock found */
2272 return FALSE;
2276 /**************************************************************************
2277 * LockFile (KERNEL32.511)
2279 BOOL32 WINAPI LockFile(
2280 HFILE32 hFile,DWORD dwFileOffsetLow,DWORD dwFileOffsetHigh,
2281 DWORD nNumberOfBytesToLockLow,DWORD nNumberOfBytesToLockHigh )
2283 struct flock f;
2284 FILE_OBJECT *file;
2286 TRACE(file, "handle %d offsetlow=%ld offsethigh=%ld nbyteslow=%ld nbyteshigh=%ld\n",
2287 hFile, dwFileOffsetLow, dwFileOffsetHigh,
2288 nNumberOfBytesToLockLow, nNumberOfBytesToLockHigh);
2290 if (dwFileOffsetHigh || nNumberOfBytesToLockHigh) {
2291 FIXME(file, "Unimplemented bytes > 32bits\n");
2292 return FALSE;
2295 f.l_start = dwFileOffsetLow;
2296 f.l_len = nNumberOfBytesToLockLow;
2297 f.l_whence = SEEK_SET;
2298 f.l_pid = 0;
2299 f.l_type = F_WRLCK;
2301 if (!(file = FILE_GetFile(hFile,0,NULL))) return FALSE;
2303 /* shadow locks internally */
2304 if (!DOS_AddLock(file, &f)) {
2305 DOS_ERROR( ER_LockViolation, EC_AccessDenied, SA_Ignore, EL_Disk );
2306 return FALSE;
2309 /* FIXME: Unix locking commented out for now, doesn't work with Excel */
2310 #ifdef USE_UNIX_LOCKS
2311 if (fcntl(file->unix_handle, F_SETLK, &f) == -1) {
2312 if (errno == EACCES || errno == EAGAIN) {
2313 DOS_ERROR( ER_LockViolation, EC_AccessDenied, SA_Ignore, EL_Disk );
2315 else {
2316 FILE_SetDosError();
2318 /* remove our internal copy of the lock */
2319 DOS_RemoveLock(file, &f);
2320 return FALSE;
2322 #endif
2323 return TRUE;
2327 /**************************************************************************
2328 * UnlockFile (KERNEL32.703)
2330 BOOL32 WINAPI UnlockFile(
2331 HFILE32 hFile,DWORD dwFileOffsetLow,DWORD dwFileOffsetHigh,
2332 DWORD nNumberOfBytesToUnlockLow,DWORD nNumberOfBytesToUnlockHigh )
2334 FILE_OBJECT *file;
2335 struct flock f;
2337 TRACE(file, "handle %d offsetlow=%ld offsethigh=%ld nbyteslow=%ld nbyteshigh=%ld\n",
2338 hFile, dwFileOffsetLow, dwFileOffsetHigh,
2339 nNumberOfBytesToUnlockLow, nNumberOfBytesToUnlockHigh);
2341 if (dwFileOffsetHigh || nNumberOfBytesToUnlockHigh) {
2342 WARN(file, "Unimplemented bytes > 32bits\n");
2343 return FALSE;
2346 f.l_start = dwFileOffsetLow;
2347 f.l_len = nNumberOfBytesToUnlockLow;
2348 f.l_whence = SEEK_SET;
2349 f.l_pid = 0;
2350 f.l_type = F_UNLCK;
2352 if (!(file = FILE_GetFile(hFile,0,NULL))) return FALSE;
2354 DOS_RemoveLock(file, &f); /* ok if fails - may be another wine */
2356 /* FIXME: Unix locking commented out for now, doesn't work with Excel */
2357 #ifdef USE_UNIX_LOCKS
2358 if (fcntl(file->unix_handle, F_SETLK, &f) == -1) {
2359 FILE_SetDosError();
2360 return FALSE;
2362 #endif
2363 return TRUE;
2366 /**************************************************************************
2367 * GetFileAttributesEx32A [KERNEL32.874]
2369 BOOL32 WINAPI GetFileAttributesEx32A(
2370 LPCSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId,
2371 LPVOID lpFileInformation)
2373 DOS_FULL_NAME full_name;
2374 BY_HANDLE_FILE_INFORMATION info;
2376 if (lpFileName == NULL) return FALSE;
2377 if (lpFileInformation == NULL) return FALSE;
2379 if (fInfoLevelId == GetFileExInfoStandard) {
2380 LPWIN32_FILE_ATTRIBUTE_DATA lpFad =
2381 (LPWIN32_FILE_ATTRIBUTE_DATA) lpFileInformation;
2382 if (!DOSFS_GetFullName( lpFileName, TRUE, &full_name )) return FALSE;
2383 if (!FILE_Stat( full_name.long_name, &info )) return FALSE;
2385 lpFad->dwFileAttributes = info.dwFileAttributes;
2386 lpFad->ftCreationTime = info.ftCreationTime;
2387 lpFad->ftLastAccessTime = info.ftLastAccessTime;
2388 lpFad->ftLastWriteTime = info.ftLastWriteTime;
2389 lpFad->nFileSizeHigh = info.nFileSizeHigh;
2390 lpFad->nFileSizeLow = info.nFileSizeLow;
2392 else {
2393 FIXME (file, "invalid info level %d!\n", fInfoLevelId);
2394 return FALSE;
2397 return TRUE;
2401 /**************************************************************************
2402 * GetFileAttributesEx32W [KERNEL32.875]
2404 BOOL32 WINAPI GetFileAttributesEx32W(
2405 LPCWSTR lpFileName, GET_FILEEX_INFO_LEVELS fInfoLevelId,
2406 LPVOID lpFileInformation)
2408 LPSTR nameA = HEAP_strdupWtoA( GetProcessHeap(), 0, lpFileName );
2409 BOOL32 res =
2410 GetFileAttributesEx32A( nameA, fInfoLevelId, lpFileInformation);
2411 HeapFree( GetProcessHeap(), 0, nameA );
2412 return res;