ntdll: Fallback to server calls for read and write on objects without a file descriptor.
[wine.git] / dlls / ntdll / file.c
blobe43ef41985b2af261c0e2ef1ee08c52640ddfd1f
1 /*
2 * Copyright 1999, 2000 Juergen Schmied
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19 #include "config.h"
20 #include "wine/port.h"
22 #include <stdlib.h>
23 #include <string.h>
24 #include <stdio.h>
25 #include <errno.h>
26 #include <assert.h>
27 #ifdef HAVE_UNISTD_H
28 # include <unistd.h>
29 #endif
30 #ifdef HAVE_LINUX_MAJOR_H
31 # include <linux/major.h>
32 #endif
33 #ifdef HAVE_SYS_STATVFS_H
34 # include <sys/statvfs.h>
35 #endif
36 #ifdef HAVE_SYS_PARAM_H
37 # include <sys/param.h>
38 #endif
39 #ifdef HAVE_SYS_SYSCALL_H
40 # include <sys/syscall.h>
41 #endif
42 #ifdef HAVE_SYS_TIME_H
43 # include <sys/time.h>
44 #endif
45 #ifdef HAVE_SYS_IOCTL_H
46 #include <sys/ioctl.h>
47 #endif
48 #ifdef HAVE_SYS_FILIO_H
49 # include <sys/filio.h>
50 #endif
51 #ifdef HAVE_POLL_H
52 #include <poll.h>
53 #endif
54 #ifdef HAVE_SYS_POLL_H
55 #include <sys/poll.h>
56 #endif
57 #ifdef HAVE_SYS_SOCKET_H
58 #include <sys/socket.h>
59 #endif
60 #ifdef HAVE_UTIME_H
61 # include <utime.h>
62 #endif
63 #ifdef HAVE_SYS_VFS_H
64 # include <sys/vfs.h>
65 #endif
66 #ifdef HAVE_SYS_MOUNT_H
67 # include <sys/mount.h>
68 #endif
69 #ifdef HAVE_SYS_STATFS_H
70 # include <sys/statfs.h>
71 #endif
72 #ifdef HAVE_TERMIOS_H
73 #include <termios.h>
74 #endif
75 #ifdef HAVE_VALGRIND_MEMCHECK_H
76 # include <valgrind/memcheck.h>
77 #endif
79 #include "ntstatus.h"
80 #define WIN32_NO_STATUS
81 #define NONAMELESSUNION
82 #include "wine/unicode.h"
83 #include "wine/debug.h"
84 #include "wine/server.h"
85 #include "ntdll_misc.h"
87 #include "winternl.h"
88 #include "winioctl.h"
89 #include "ddk/ntddk.h"
90 #include "ddk/ntddser.h"
92 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
93 WINE_DECLARE_DEBUG_CHANNEL(winediag);
95 mode_t FILE_umask = 0;
97 #define SECSPERDAY 86400
98 #define SECS_1601_TO_1970 ((369 * 365 + 89) * (ULONGLONG)SECSPERDAY)
100 #define FILE_WRITE_TO_END_OF_FILE ((LONGLONG)-1)
101 #define FILE_USE_FILE_POINTER_POSITION ((LONGLONG)-2)
103 static const WCHAR ntfsW[] = {'N','T','F','S'};
105 /* fetch the attributes of a file */
106 static inline ULONG get_file_attributes( const struct stat *st )
108 ULONG attr;
110 if (S_ISDIR(st->st_mode))
111 attr = FILE_ATTRIBUTE_DIRECTORY;
112 else
113 attr = FILE_ATTRIBUTE_ARCHIVE;
114 if (!(st->st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
115 attr |= FILE_ATTRIBUTE_READONLY;
116 return attr;
119 /* get the stat info and file attributes for a file (by file descriptor) */
120 int fd_get_file_info( int fd, struct stat *st, ULONG *attr )
122 int ret;
124 *attr = 0;
125 ret = fstat( fd, st );
126 if (ret == -1) return ret;
127 *attr |= get_file_attributes( st );
128 return ret;
131 /* get the stat info and file attributes for a file (by name) */
132 int get_file_info( const char *path, struct stat *st, ULONG *attr )
134 int ret;
136 *attr = 0;
137 ret = lstat( path, st );
138 if (ret == -1) return ret;
139 if (S_ISLNK( st->st_mode ))
141 ret = stat( path, st );
142 if (ret == -1) return ret;
143 /* is a symbolic link and a directory, consider these "reparse points" */
144 if (S_ISDIR( st->st_mode )) *attr |= FILE_ATTRIBUTE_REPARSE_POINT;
146 *attr |= get_file_attributes( st );
147 return ret;
150 /**************************************************************************
151 * FILE_CreateFile (internal)
152 * Open a file.
154 * Parameter set fully identical with NtCreateFile
156 static NTSTATUS FILE_CreateFile( PHANDLE handle, ACCESS_MASK access, POBJECT_ATTRIBUTES attr,
157 PIO_STATUS_BLOCK io, PLARGE_INTEGER alloc_size,
158 ULONG attributes, ULONG sharing, ULONG disposition,
159 ULONG options, PVOID ea_buffer, ULONG ea_length )
161 ANSI_STRING unix_name;
162 BOOL created = FALSE;
164 TRACE("handle=%p access=%08x name=%s objattr=%08x root=%p sec=%p io=%p alloc_size=%p "
165 "attr=%08x sharing=%08x disp=%d options=%08x ea=%p.0x%08x\n",
166 handle, access, debugstr_us(attr->ObjectName), attr->Attributes,
167 attr->RootDirectory, attr->SecurityDescriptor, io, alloc_size,
168 attributes, sharing, disposition, options, ea_buffer, ea_length );
170 if (!attr || !attr->ObjectName) return STATUS_INVALID_PARAMETER;
172 if (alloc_size) FIXME( "alloc_size not supported\n" );
174 if (options & FILE_OPEN_BY_FILE_ID)
175 io->u.Status = file_id_to_unix_file_name( attr, &unix_name );
176 else
177 io->u.Status = nt_to_unix_file_name_attr( attr, &unix_name, disposition );
179 if (io->u.Status == STATUS_BAD_DEVICE_TYPE)
181 SERVER_START_REQ( open_file_object )
183 req->access = access;
184 req->attributes = attr->Attributes;
185 req->rootdir = wine_server_obj_handle( attr->RootDirectory );
186 req->sharing = sharing;
187 req->options = options;
188 wine_server_add_data( req, attr->ObjectName->Buffer, attr->ObjectName->Length );
189 io->u.Status = wine_server_call( req );
190 *handle = wine_server_ptr_handle( reply->handle );
192 SERVER_END_REQ;
193 if (io->u.Status == STATUS_SUCCESS) io->Information = FILE_OPENED;
194 return io->u.Status;
197 if (io->u.Status == STATUS_NO_SUCH_FILE &&
198 disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
200 created = TRUE;
201 io->u.Status = STATUS_SUCCESS;
204 if (io->u.Status == STATUS_SUCCESS)
206 struct security_descriptor *sd;
207 struct object_attributes objattr;
209 objattr.rootdir = wine_server_obj_handle( attr->RootDirectory );
210 objattr.name_len = 0;
211 io->u.Status = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
212 if (io->u.Status != STATUS_SUCCESS)
214 RtlFreeAnsiString( &unix_name );
215 return io->u.Status;
218 SERVER_START_REQ( create_file )
220 req->access = access;
221 req->attributes = attr->Attributes;
222 req->sharing = sharing;
223 req->create = disposition;
224 req->options = options;
225 req->attrs = attributes;
226 wine_server_add_data( req, &objattr, sizeof(objattr) );
227 if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
228 wine_server_add_data( req, unix_name.Buffer, unix_name.Length );
229 io->u.Status = wine_server_call( req );
230 *handle = wine_server_ptr_handle( reply->handle );
232 SERVER_END_REQ;
233 NTDLL_free_struct_sd( sd );
234 RtlFreeAnsiString( &unix_name );
236 else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), io->u.Status );
238 if (io->u.Status == STATUS_SUCCESS)
240 if (created) io->Information = FILE_CREATED;
241 else switch(disposition)
243 case FILE_SUPERSEDE:
244 io->Information = FILE_SUPERSEDED;
245 break;
246 case FILE_CREATE:
247 io->Information = FILE_CREATED;
248 break;
249 case FILE_OPEN:
250 case FILE_OPEN_IF:
251 io->Information = FILE_OPENED;
252 break;
253 case FILE_OVERWRITE:
254 case FILE_OVERWRITE_IF:
255 io->Information = FILE_OVERWRITTEN;
256 break;
259 else if (io->u.Status == STATUS_TOO_MANY_OPENED_FILES)
261 static int once;
262 if (!once++) ERR_(winediag)( "Too many open files, ulimit -n probably needs to be increased\n" );
265 return io->u.Status;
268 /**************************************************************************
269 * NtOpenFile [NTDLL.@]
270 * ZwOpenFile [NTDLL.@]
272 * Open a file.
274 * PARAMS
275 * handle [O] Variable that receives the file handle on return
276 * access [I] Access desired by the caller to the file
277 * attr [I] Structure describing the file to be opened
278 * io [O] Receives details about the result of the operation
279 * sharing [I] Type of shared access the caller requires
280 * options [I] Options for the file open
282 * RETURNS
283 * Success: 0. FileHandle and IoStatusBlock are updated.
284 * Failure: An NTSTATUS error code describing the error.
286 NTSTATUS WINAPI NtOpenFile( PHANDLE handle, ACCESS_MASK access,
287 POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK io,
288 ULONG sharing, ULONG options )
290 return FILE_CreateFile( handle, access, attr, io, NULL, 0,
291 sharing, FILE_OPEN, options, NULL, 0 );
294 /**************************************************************************
295 * NtCreateFile [NTDLL.@]
296 * ZwCreateFile [NTDLL.@]
298 * Either create a new file or directory, or open an existing file, device,
299 * directory or volume.
301 * PARAMS
302 * handle [O] Points to a variable which receives the file handle on return
303 * access [I] Desired access to the file
304 * attr [I] Structure describing the file
305 * io [O] Receives information about the operation on return
306 * alloc_size [I] Initial size of the file in bytes
307 * attributes [I] Attributes to create the file with
308 * sharing [I] Type of shared access the caller would like to the file
309 * disposition [I] Specifies what to do, depending on whether the file already exists
310 * options [I] Options for creating a new file
311 * ea_buffer [I] Pointer to an extended attributes buffer
312 * ea_length [I] Length of ea_buffer
314 * RETURNS
315 * Success: 0. handle and io are updated.
316 * Failure: An NTSTATUS error code describing the error.
318 NTSTATUS WINAPI NtCreateFile( PHANDLE handle, ACCESS_MASK access, POBJECT_ATTRIBUTES attr,
319 PIO_STATUS_BLOCK io, PLARGE_INTEGER alloc_size,
320 ULONG attributes, ULONG sharing, ULONG disposition,
321 ULONG options, PVOID ea_buffer, ULONG ea_length )
323 return FILE_CreateFile( handle, access, attr, io, alloc_size, attributes,
324 sharing, disposition, options, ea_buffer, ea_length );
327 /***********************************************************************
328 * Asynchronous file I/O *
331 struct async_fileio
333 struct async_fileio *next;
334 HANDLE handle;
335 PIO_APC_ROUTINE apc;
336 void *apc_arg;
339 struct async_fileio_read
341 struct async_fileio io;
342 char* buffer;
343 unsigned int already;
344 unsigned int count;
345 BOOL avail_mode;
348 struct async_fileio_write
350 struct async_fileio io;
351 const char *buffer;
352 unsigned int already;
353 unsigned int count;
356 struct async_irp
358 struct async_fileio io;
359 HANDLE event; /* async event */
360 void *buffer; /* buffer for output */
361 ULONG size; /* size of buffer */
364 static struct async_fileio *fileio_freelist;
366 static void release_fileio( struct async_fileio *io )
368 for (;;)
370 struct async_fileio *next = fileio_freelist;
371 io->next = next;
372 if (interlocked_cmpxchg_ptr( (void **)&fileio_freelist, io, next ) == next) return;
376 static struct async_fileio *alloc_fileio( DWORD size, HANDLE handle, PIO_APC_ROUTINE apc, void *arg )
378 /* first free remaining previous fileinfos */
380 struct async_fileio *io = interlocked_xchg_ptr( (void **)&fileio_freelist, NULL );
382 while (io)
384 struct async_fileio *next = io->next;
385 RtlFreeHeap( GetProcessHeap(), 0, io );
386 io = next;
389 if ((io = RtlAllocateHeap( GetProcessHeap(), 0, size )))
391 io->handle = handle;
392 io->apc = apc;
393 io->apc_arg = arg;
395 return io;
398 /* callback for irp async I/O completion */
399 static NTSTATUS irp_completion( void *user, IO_STATUS_BLOCK *io, NTSTATUS status, void **apc, void **arg )
401 struct async_irp *async = user;
403 if (status == STATUS_ALERTED)
405 SERVER_START_REQ( get_irp_result )
407 req->handle = wine_server_obj_handle( async->io.handle );
408 req->user_arg = wine_server_client_ptr( async );
409 wine_server_set_reply( req, async->buffer, async->size );
410 status = wine_server_call( req );
411 if (status != STATUS_PENDING) io->Information = reply->size;
413 SERVER_END_REQ;
415 if (status != STATUS_PENDING)
417 io->u.Status = status;
418 *apc = async->io.apc;
419 *arg = async->io.apc_arg;
420 release_fileio( &async->io );
422 return status;
425 /***********************************************************************
426 * FILE_GetNtStatus(void)
428 * Retrieve the Nt Status code from errno.
429 * Try to be consistent with FILE_SetDosError().
431 NTSTATUS FILE_GetNtStatus(void)
433 int err = errno;
435 TRACE( "errno = %d\n", errno );
436 switch (err)
438 case EAGAIN: return STATUS_SHARING_VIOLATION;
439 case EBADF: return STATUS_INVALID_HANDLE;
440 case EBUSY: return STATUS_DEVICE_BUSY;
441 case ENOSPC: return STATUS_DISK_FULL;
442 case EPERM:
443 case EROFS:
444 case EACCES: return STATUS_ACCESS_DENIED;
445 case ENOTDIR: return STATUS_OBJECT_PATH_NOT_FOUND;
446 case ENOENT: return STATUS_OBJECT_NAME_NOT_FOUND;
447 case EISDIR: return STATUS_FILE_IS_A_DIRECTORY;
448 case EMFILE:
449 case ENFILE: return STATUS_TOO_MANY_OPENED_FILES;
450 case EINVAL: return STATUS_INVALID_PARAMETER;
451 case ENOTEMPTY: return STATUS_DIRECTORY_NOT_EMPTY;
452 case EPIPE: return STATUS_PIPE_DISCONNECTED;
453 case EIO: return STATUS_DEVICE_NOT_READY;
454 #ifdef ENOMEDIUM
455 case ENOMEDIUM: return STATUS_NO_MEDIA_IN_DEVICE;
456 #endif
457 case ENXIO: return STATUS_NO_SUCH_DEVICE;
458 case ENOTTY:
459 case EOPNOTSUPP:return STATUS_NOT_SUPPORTED;
460 case ECONNRESET:return STATUS_PIPE_DISCONNECTED;
461 case EFAULT: return STATUS_ACCESS_VIOLATION;
462 case ESPIPE: return STATUS_ILLEGAL_FUNCTION;
463 #ifdef ETIME /* Missing on FreeBSD */
464 case ETIME: return STATUS_IO_TIMEOUT;
465 #endif
466 case ENOEXEC: /* ?? */
467 case EEXIST: /* ?? */
468 default:
469 FIXME( "Converting errno %d to STATUS_UNSUCCESSFUL\n", err );
470 return STATUS_UNSUCCESSFUL;
474 /***********************************************************************
475 * FILE_AsyncReadService (INTERNAL)
477 static NTSTATUS FILE_AsyncReadService( void *user, IO_STATUS_BLOCK *iosb,
478 NTSTATUS status, void **apc, void **arg )
480 struct async_fileio_read *fileio = user;
481 int fd, needs_close, result;
483 switch (status)
485 case STATUS_ALERTED: /* got some new data */
486 /* check to see if the data is ready (non-blocking) */
487 if ((status = server_get_unix_fd( fileio->io.handle, FILE_READ_DATA, &fd,
488 &needs_close, NULL, NULL )))
489 break;
491 result = read(fd, &fileio->buffer[fileio->already], fileio->count - fileio->already);
492 if (needs_close) close( fd );
494 if (result < 0)
496 if (errno == EAGAIN || errno == EINTR)
497 status = STATUS_PENDING;
498 else /* check to see if the transfer is complete */
499 status = FILE_GetNtStatus();
501 else if (result == 0)
503 status = fileio->already ? STATUS_SUCCESS : STATUS_PIPE_BROKEN;
505 else
507 fileio->already += result;
508 if (fileio->already >= fileio->count || fileio->avail_mode)
509 status = STATUS_SUCCESS;
510 else
512 /* if we only have to read the available data, and none is available,
513 * simply cancel the request. If data was available, it has been read
514 * while in by previous call (NtDelayExecution)
516 status = (fileio->avail_mode) ? STATUS_SUCCESS : STATUS_PENDING;
519 break;
521 case STATUS_TIMEOUT:
522 case STATUS_IO_TIMEOUT:
523 if (fileio->already) status = STATUS_SUCCESS;
524 break;
526 if (status != STATUS_PENDING)
528 iosb->u.Status = status;
529 iosb->Information = fileio->already;
530 *apc = fileio->io.apc;
531 *arg = fileio->io.apc_arg;
532 release_fileio( &fileio->io );
534 return status;
537 /* do a read call through the server */
538 static NTSTATUS server_read_file( HANDLE handle, HANDLE event, PIO_APC_ROUTINE apc, void *apc_context,
539 IO_STATUS_BLOCK *io, void *buffer, ULONG size,
540 LARGE_INTEGER *offset, ULONG *key )
542 struct async_irp *async;
543 NTSTATUS status;
544 HANDLE wait_handle;
545 ULONG options;
546 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_context;
548 if (!(async = (struct async_irp *)alloc_fileio( sizeof(*async), handle, apc, apc_context )))
549 return STATUS_NO_MEMORY;
551 async->event = event;
552 async->buffer = buffer;
553 async->size = size;
555 SERVER_START_REQ( read )
557 req->blocking = !apc && !event && !cvalue;
558 req->async.handle = wine_server_obj_handle( handle );
559 req->async.callback = wine_server_client_ptr( irp_completion );
560 req->async.iosb = wine_server_client_ptr( io );
561 req->async.arg = wine_server_client_ptr( async );
562 req->async.event = wine_server_obj_handle( event );
563 req->async.cvalue = cvalue;
564 req->pos = offset ? offset->QuadPart : 0;
565 wine_server_set_reply( req, buffer, size );
566 status = wine_server_call( req );
567 wait_handle = wine_server_ptr_handle( reply->wait );
568 options = reply->options;
569 if (status != STATUS_PENDING) io->Information = wine_server_reply_size( reply );
571 SERVER_END_REQ;
573 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, async );
575 if (wait_handle)
577 NtWaitForSingleObject( wait_handle, (options & FILE_SYNCHRONOUS_IO_ALERT), NULL );
578 status = io->u.Status;
579 NtClose( wait_handle );
582 return status;
585 /* do a write call through the server */
586 static NTSTATUS server_write_file( HANDLE handle, HANDLE event, PIO_APC_ROUTINE apc, void *apc_context,
587 IO_STATUS_BLOCK *io, const void *buffer, ULONG size,
588 LARGE_INTEGER *offset, ULONG *key )
590 struct async_irp *async;
591 NTSTATUS status;
592 HANDLE wait_handle;
593 ULONG options;
594 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_context;
596 if (!(async = (struct async_irp *)alloc_fileio( sizeof(*async), handle, apc, apc_context )))
597 return STATUS_NO_MEMORY;
599 async->event = event;
600 async->buffer = NULL;
601 async->size = 0;
603 SERVER_START_REQ( write )
605 req->blocking = !apc && !event && !cvalue;
606 req->async.handle = wine_server_obj_handle( handle );
607 req->async.callback = wine_server_client_ptr( irp_completion );
608 req->async.iosb = wine_server_client_ptr( io );
609 req->async.arg = wine_server_client_ptr( async );
610 req->async.event = wine_server_obj_handle( event );
611 req->async.cvalue = cvalue;
612 req->pos = offset ? offset->QuadPart : 0;
613 wine_server_add_data( req, buffer, size );
614 status = wine_server_call( req );
615 wait_handle = wine_server_ptr_handle( reply->wait );
616 options = reply->options;
617 if (status != STATUS_PENDING) io->Information = reply->size;
619 SERVER_END_REQ;
621 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, async );
623 if (wait_handle)
625 NtWaitForSingleObject( wait_handle, (options & FILE_SYNCHRONOUS_IO_ALERT), NULL );
626 status = io->u.Status;
627 NtClose( wait_handle );
630 return status;
633 struct io_timeouts
635 int interval; /* max interval between two bytes */
636 int total; /* total timeout for the whole operation */
637 int end_time; /* absolute time of end of operation */
640 /* retrieve the I/O timeouts to use for a given handle */
641 static NTSTATUS get_io_timeouts( HANDLE handle, enum server_fd_type type, ULONG count, BOOL is_read,
642 struct io_timeouts *timeouts )
644 NTSTATUS status = STATUS_SUCCESS;
646 timeouts->interval = timeouts->total = -1;
648 switch(type)
650 case FD_TYPE_SERIAL:
652 /* GetCommTimeouts */
653 SERIAL_TIMEOUTS st;
654 IO_STATUS_BLOCK io;
656 status = NtDeviceIoControlFile( handle, NULL, NULL, NULL, &io,
657 IOCTL_SERIAL_GET_TIMEOUTS, NULL, 0, &st, sizeof(st) );
658 if (status) break;
660 if (is_read)
662 if (st.ReadIntervalTimeout)
663 timeouts->interval = st.ReadIntervalTimeout;
665 if (st.ReadTotalTimeoutMultiplier || st.ReadTotalTimeoutConstant)
667 timeouts->total = st.ReadTotalTimeoutConstant;
668 if (st.ReadTotalTimeoutMultiplier != MAXDWORD)
669 timeouts->total += count * st.ReadTotalTimeoutMultiplier;
671 else if (st.ReadIntervalTimeout == MAXDWORD)
672 timeouts->interval = timeouts->total = 0;
674 else /* write */
676 if (st.WriteTotalTimeoutMultiplier || st.WriteTotalTimeoutConstant)
678 timeouts->total = st.WriteTotalTimeoutConstant;
679 if (st.WriteTotalTimeoutMultiplier != MAXDWORD)
680 timeouts->total += count * st.WriteTotalTimeoutMultiplier;
684 break;
685 case FD_TYPE_MAILSLOT:
686 if (is_read)
688 timeouts->interval = 0; /* return as soon as we got something */
689 SERVER_START_REQ( set_mailslot_info )
691 req->handle = wine_server_obj_handle( handle );
692 req->flags = 0;
693 if (!(status = wine_server_call( req )) &&
694 reply->read_timeout != TIMEOUT_INFINITE)
695 timeouts->total = reply->read_timeout / -10000;
697 SERVER_END_REQ;
699 break;
700 case FD_TYPE_SOCKET:
701 case FD_TYPE_PIPE:
702 case FD_TYPE_CHAR:
703 if (is_read) timeouts->interval = 0; /* return as soon as we got something */
704 break;
705 default:
706 break;
708 if (timeouts->total != -1) timeouts->end_time = NtGetTickCount() + timeouts->total;
709 return STATUS_SUCCESS;
713 /* retrieve the timeout for the next wait, in milliseconds */
714 static inline int get_next_io_timeout( const struct io_timeouts *timeouts, ULONG already )
716 int ret = -1;
718 if (timeouts->total != -1)
720 ret = timeouts->end_time - NtGetTickCount();
721 if (ret < 0) ret = 0;
723 if (already && timeouts->interval != -1)
725 if (ret == -1 || ret > timeouts->interval) ret = timeouts->interval;
727 return ret;
731 /* retrieve the avail_mode flag for async reads */
732 static NTSTATUS get_io_avail_mode( HANDLE handle, enum server_fd_type type, BOOL *avail_mode )
734 NTSTATUS status = STATUS_SUCCESS;
736 switch(type)
738 case FD_TYPE_SERIAL:
740 /* GetCommTimeouts */
741 SERIAL_TIMEOUTS st;
742 IO_STATUS_BLOCK io;
744 status = NtDeviceIoControlFile( handle, NULL, NULL, NULL, &io,
745 IOCTL_SERIAL_GET_TIMEOUTS, NULL, 0, &st, sizeof(st) );
746 if (status) break;
747 *avail_mode = (!st.ReadTotalTimeoutMultiplier &&
748 !st.ReadTotalTimeoutConstant &&
749 st.ReadIntervalTimeout == MAXDWORD);
751 break;
752 case FD_TYPE_MAILSLOT:
753 case FD_TYPE_SOCKET:
754 case FD_TYPE_PIPE:
755 case FD_TYPE_CHAR:
756 *avail_mode = TRUE;
757 break;
758 default:
759 *avail_mode = FALSE;
760 break;
762 return status;
766 /******************************************************************************
767 * NtReadFile [NTDLL.@]
768 * ZwReadFile [NTDLL.@]
770 * Read from an open file handle.
772 * PARAMS
773 * FileHandle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
774 * Event [I] Event to signal upon completion (or NULL)
775 * ApcRoutine [I] Callback to call upon completion (or NULL)
776 * ApcContext [I] Context for ApcRoutine (or NULL)
777 * IoStatusBlock [O] Receives information about the operation on return
778 * Buffer [O] Destination for the data read
779 * Length [I] Size of Buffer
780 * ByteOffset [O] Destination for the new file pointer position (or NULL)
781 * Key [O] Function unknown (may be NULL)
783 * RETURNS
784 * Success: 0. IoStatusBlock is updated, and the Information member contains
785 * The number of bytes read.
786 * Failure: An NTSTATUS error code describing the error.
788 NTSTATUS WINAPI NtReadFile(HANDLE hFile, HANDLE hEvent,
789 PIO_APC_ROUTINE apc, void* apc_user,
790 PIO_STATUS_BLOCK io_status, void* buffer, ULONG length,
791 PLARGE_INTEGER offset, PULONG key)
793 int result, unix_handle, needs_close;
794 unsigned int options;
795 struct io_timeouts timeouts;
796 NTSTATUS status;
797 ULONG total = 0;
798 enum server_fd_type type;
799 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
800 BOOL send_completion = FALSE, async_read, timeout_init_done = FALSE;
802 TRACE("(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p),partial stub!\n",
803 hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);
805 if (!io_status) return STATUS_ACCESS_VIOLATION;
807 status = server_get_unix_fd( hFile, FILE_READ_DATA, &unix_handle,
808 &needs_close, &type, &options );
809 if (status == STATUS_BAD_DEVICE_TYPE)
810 return server_read_file( hFile, hEvent, apc, apc_user, io_status, buffer, length, offset, key );
812 if (status) return status;
814 async_read = !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
816 if (!virtual_check_buffer_for_write( buffer, length ))
818 status = STATUS_ACCESS_VIOLATION;
819 goto done;
822 if (type == FD_TYPE_FILE)
824 if (async_read && (!offset || offset->QuadPart < 0))
826 status = STATUS_INVALID_PARAMETER;
827 goto done;
830 if (offset && offset->QuadPart != FILE_USE_FILE_POINTER_POSITION)
832 /* async I/O doesn't make sense on regular files */
833 while ((result = pread( unix_handle, buffer, length, offset->QuadPart )) == -1)
835 if (errno != EINTR)
837 status = FILE_GetNtStatus();
838 goto done;
841 if (!async_read)
842 /* update file pointer position */
843 lseek( unix_handle, offset->QuadPart + result, SEEK_SET );
845 total = result;
846 status = (total || !length) ? STATUS_SUCCESS : STATUS_END_OF_FILE;
847 goto done;
850 else if (type == FD_TYPE_SERIAL)
852 if (async_read && (!offset || offset->QuadPart < 0))
854 status = STATUS_INVALID_PARAMETER;
855 goto done;
859 for (;;)
861 if ((result = read( unix_handle, (char *)buffer + total, length - total )) >= 0)
863 total += result;
864 if (!result || total == length)
866 if (total)
868 status = STATUS_SUCCESS;
869 goto done;
871 switch (type)
873 case FD_TYPE_FILE:
874 case FD_TYPE_CHAR:
875 status = length ? STATUS_END_OF_FILE : STATUS_SUCCESS;
876 goto done;
877 case FD_TYPE_SERIAL:
878 break;
879 default:
880 status = STATUS_PIPE_BROKEN;
881 goto done;
884 else if (type == FD_TYPE_FILE) continue; /* no async I/O on regular files */
886 else if (errno != EAGAIN)
888 if (errno == EINTR) continue;
889 if (!total) status = FILE_GetNtStatus();
890 goto done;
893 if (async_read)
895 struct async_fileio_read *fileio;
896 BOOL avail_mode;
898 if ((status = get_io_avail_mode( hFile, type, &avail_mode )))
899 goto err;
900 if (total && avail_mode)
902 status = STATUS_SUCCESS;
903 goto done;
906 fileio = (struct async_fileio_read *)alloc_fileio( sizeof(*fileio), hFile, apc, apc_user );
907 if (!fileio)
909 status = STATUS_NO_MEMORY;
910 goto err;
912 fileio->already = total;
913 fileio->count = length;
914 fileio->buffer = buffer;
915 fileio->avail_mode = avail_mode;
917 SERVER_START_REQ( register_async )
919 req->type = ASYNC_TYPE_READ;
920 req->count = length;
921 req->async.handle = wine_server_obj_handle( hFile );
922 req->async.event = wine_server_obj_handle( hEvent );
923 req->async.callback = wine_server_client_ptr( FILE_AsyncReadService );
924 req->async.iosb = wine_server_client_ptr( io_status );
925 req->async.arg = wine_server_client_ptr( fileio );
926 req->async.cvalue = cvalue;
927 status = wine_server_call( req );
929 SERVER_END_REQ;
931 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
932 goto err;
934 else /* synchronous read, wait for the fd to become ready */
936 struct pollfd pfd;
937 int ret, timeout;
939 if (!timeout_init_done)
941 timeout_init_done = TRUE;
942 if ((status = get_io_timeouts( hFile, type, length, TRUE, &timeouts )))
943 goto err;
944 if (hEvent) NtResetEvent( hEvent, NULL );
946 timeout = get_next_io_timeout( &timeouts, total );
948 pfd.fd = unix_handle;
949 pfd.events = POLLIN;
951 if (!timeout || !(ret = poll( &pfd, 1, timeout )))
953 if (total) /* return with what we got so far */
954 status = STATUS_SUCCESS;
955 else
956 status = (type == FD_TYPE_MAILSLOT) ? STATUS_IO_TIMEOUT : STATUS_TIMEOUT;
957 goto done;
959 if (ret == -1 && errno != EINTR)
961 status = FILE_GetNtStatus();
962 goto done;
964 /* will now restart the read */
968 done:
969 send_completion = cvalue != 0;
971 err:
972 if (needs_close) close( unix_handle );
973 if (status == STATUS_SUCCESS || (status == STATUS_END_OF_FILE && !async_read))
975 io_status->u.Status = status;
976 io_status->Information = total;
977 TRACE("= SUCCESS (%u)\n", total);
978 if (hEvent) NtSetEvent( hEvent, NULL );
979 if (apc && !status) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
980 (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
982 else
984 TRACE("= 0x%08x\n", status);
985 if (status != STATUS_PENDING && hEvent) NtResetEvent( hEvent, NULL );
988 if (send_completion) NTDLL_AddCompletion( hFile, cvalue, status, total );
990 return status;
994 /******************************************************************************
995 * NtReadFileScatter [NTDLL.@]
996 * ZwReadFileScatter [NTDLL.@]
998 NTSTATUS WINAPI NtReadFileScatter( HANDLE file, HANDLE event, PIO_APC_ROUTINE apc, void *apc_user,
999 PIO_STATUS_BLOCK io_status, FILE_SEGMENT_ELEMENT *segments,
1000 ULONG length, PLARGE_INTEGER offset, PULONG key )
1002 int result, unix_handle, needs_close;
1003 unsigned int options;
1004 NTSTATUS status;
1005 ULONG pos = 0, total = 0;
1006 enum server_fd_type type;
1007 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
1008 BOOL send_completion = FALSE;
1010 TRACE( "(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p),partial stub!\n",
1011 file, event, apc, apc_user, io_status, segments, length, offset, key);
1013 if (length % page_size) return STATUS_INVALID_PARAMETER;
1014 if (!io_status) return STATUS_ACCESS_VIOLATION;
1016 status = server_get_unix_fd( file, FILE_READ_DATA, &unix_handle,
1017 &needs_close, &type, &options );
1018 if (status) return status;
1020 if ((type != FD_TYPE_FILE) ||
1021 (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)) ||
1022 !(options & FILE_NO_INTERMEDIATE_BUFFERING))
1024 status = STATUS_INVALID_PARAMETER;
1025 goto error;
1028 while (length)
1030 if (offset && offset->QuadPart != FILE_USE_FILE_POINTER_POSITION)
1031 result = pread( unix_handle, (char *)segments->Buffer + pos,
1032 page_size - pos, offset->QuadPart + total );
1033 else
1034 result = read( unix_handle, (char *)segments->Buffer + pos, page_size - pos );
1036 if (result == -1)
1038 if (errno == EINTR) continue;
1039 status = FILE_GetNtStatus();
1040 break;
1042 if (!result)
1044 status = STATUS_END_OF_FILE;
1045 break;
1047 total += result;
1048 length -= result;
1049 if ((pos += result) == page_size)
1051 pos = 0;
1052 segments++;
1056 send_completion = cvalue != 0;
1058 error:
1059 if (needs_close) close( unix_handle );
1060 if (status == STATUS_SUCCESS)
1062 io_status->u.Status = status;
1063 io_status->Information = total;
1064 TRACE("= SUCCESS (%u)\n", total);
1065 if (event) NtSetEvent( event, NULL );
1066 if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
1067 (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
1069 else
1071 TRACE("= 0x%08x\n", status);
1072 if (status != STATUS_PENDING && event) NtResetEvent( event, NULL );
1075 if (send_completion) NTDLL_AddCompletion( file, cvalue, status, total );
1077 return status;
1081 /***********************************************************************
1082 * FILE_AsyncWriteService (INTERNAL)
1084 static NTSTATUS FILE_AsyncWriteService( void *user, IO_STATUS_BLOCK *iosb,
1085 NTSTATUS status, void **apc, void **arg )
1087 struct async_fileio_write *fileio = user;
1088 int result, fd, needs_close;
1089 enum server_fd_type type;
1091 switch (status)
1093 case STATUS_ALERTED:
1094 /* write some data (non-blocking) */
1095 if ((status = server_get_unix_fd( fileio->io.handle, FILE_WRITE_DATA, &fd,
1096 &needs_close, &type, NULL )))
1097 break;
1099 if (!fileio->count && (type == FD_TYPE_MAILSLOT || type == FD_TYPE_PIPE || type == FD_TYPE_SOCKET))
1100 result = send( fd, fileio->buffer, 0, 0 );
1101 else
1102 result = write( fd, &fileio->buffer[fileio->already], fileio->count - fileio->already );
1104 if (needs_close) close( fd );
1106 if (result < 0)
1108 if (errno == EAGAIN || errno == EINTR) status = STATUS_PENDING;
1109 else status = FILE_GetNtStatus();
1111 else
1113 fileio->already += result;
1114 status = (fileio->already < fileio->count) ? STATUS_PENDING : STATUS_SUCCESS;
1116 break;
1118 case STATUS_TIMEOUT:
1119 case STATUS_IO_TIMEOUT:
1120 if (fileio->already) status = STATUS_SUCCESS;
1121 break;
1123 if (status != STATUS_PENDING)
1125 iosb->u.Status = status;
1126 iosb->Information = fileio->already;
1127 *apc = fileio->io.apc;
1128 *arg = fileio->io.apc_arg;
1129 release_fileio( &fileio->io );
1131 return status;
1134 static NTSTATUS set_pending_write( HANDLE device )
1136 NTSTATUS status;
1138 SERVER_START_REQ( set_serial_info )
1140 req->handle = wine_server_obj_handle( device );
1141 req->flags = SERIALINFO_PENDING_WRITE;
1142 status = wine_server_call( req );
1144 SERVER_END_REQ;
1145 return status;
1148 /******************************************************************************
1149 * NtWriteFile [NTDLL.@]
1150 * ZwWriteFile [NTDLL.@]
1152 * Write to an open file handle.
1154 * PARAMS
1155 * FileHandle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1156 * Event [I] Event to signal upon completion (or NULL)
1157 * ApcRoutine [I] Callback to call upon completion (or NULL)
1158 * ApcContext [I] Context for ApcRoutine (or NULL)
1159 * IoStatusBlock [O] Receives information about the operation on return
1160 * Buffer [I] Source for the data to write
1161 * Length [I] Size of Buffer
1162 * ByteOffset [O] Destination for the new file pointer position (or NULL)
1163 * Key [O] Function unknown (may be NULL)
1165 * RETURNS
1166 * Success: 0. IoStatusBlock is updated, and the Information member contains
1167 * The number of bytes written.
1168 * Failure: An NTSTATUS error code describing the error.
1170 NTSTATUS WINAPI NtWriteFile(HANDLE hFile, HANDLE hEvent,
1171 PIO_APC_ROUTINE apc, void* apc_user,
1172 PIO_STATUS_BLOCK io_status,
1173 const void* buffer, ULONG length,
1174 PLARGE_INTEGER offset, PULONG key)
1176 int result, unix_handle, needs_close;
1177 unsigned int options;
1178 struct io_timeouts timeouts;
1179 NTSTATUS status;
1180 ULONG total = 0;
1181 enum server_fd_type type;
1182 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
1183 BOOL send_completion = FALSE, async_write, append_write = FALSE, timeout_init_done = FALSE;
1184 LARGE_INTEGER offset_eof;
1186 TRACE("(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p)!\n",
1187 hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);
1189 if (!io_status) return STATUS_ACCESS_VIOLATION;
1191 status = server_get_unix_fd( hFile, FILE_WRITE_DATA, &unix_handle,
1192 &needs_close, &type, &options );
1193 if (status == STATUS_BAD_DEVICE_TYPE)
1194 return server_write_file( hFile, hEvent, apc, apc_user, io_status, buffer, length, offset, key );
1196 if (status == STATUS_ACCESS_DENIED)
1198 status = server_get_unix_fd( hFile, FILE_APPEND_DATA, &unix_handle,
1199 &needs_close, &type, &options );
1200 append_write = TRUE;
1202 if (status) return status;
1204 if (!virtual_check_buffer_for_read( buffer, length ))
1206 status = STATUS_INVALID_USER_BUFFER;
1207 goto done;
1210 async_write = !(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT));
1212 if (type == FD_TYPE_FILE)
1214 if (async_write &&
1215 (!offset || (offset->QuadPart < 0 && offset->QuadPart != FILE_WRITE_TO_END_OF_FILE)))
1217 status = STATUS_INVALID_PARAMETER;
1218 goto done;
1221 if (append_write)
1223 offset_eof.QuadPart = FILE_WRITE_TO_END_OF_FILE;
1224 offset = &offset_eof;
1227 if (offset && offset->QuadPart != FILE_USE_FILE_POINTER_POSITION)
1229 off_t off = offset->QuadPart;
1231 if (offset->QuadPart == FILE_WRITE_TO_END_OF_FILE)
1233 struct stat st;
1235 if (fstat( unix_handle, &st ) == -1)
1237 status = FILE_GetNtStatus();
1238 goto done;
1240 off = st.st_size;
1242 else if (offset->QuadPart < 0)
1244 status = STATUS_INVALID_PARAMETER;
1245 goto done;
1248 /* async I/O doesn't make sense on regular files */
1249 while ((result = pwrite( unix_handle, buffer, length, off )) == -1)
1251 if (errno != EINTR)
1253 if (errno == EFAULT) status = STATUS_INVALID_USER_BUFFER;
1254 else status = FILE_GetNtStatus();
1255 goto done;
1259 if (!async_write)
1260 /* update file pointer position */
1261 lseek( unix_handle, off + result, SEEK_SET );
1263 total = result;
1264 status = STATUS_SUCCESS;
1265 goto done;
1268 else if (type == FD_TYPE_SERIAL)
1270 if (async_write &&
1271 (!offset || (offset->QuadPart < 0 && offset->QuadPart != FILE_WRITE_TO_END_OF_FILE)))
1273 status = STATUS_INVALID_PARAMETER;
1274 goto done;
1278 for (;;)
1280 /* zero-length writes on sockets may not work with plain write(2) */
1281 if (!length && (type == FD_TYPE_MAILSLOT || type == FD_TYPE_PIPE || type == FD_TYPE_SOCKET))
1282 result = send( unix_handle, buffer, 0, 0 );
1283 else
1284 result = write( unix_handle, (const char *)buffer + total, length - total );
1286 if (result >= 0)
1288 total += result;
1289 if (total == length)
1291 status = STATUS_SUCCESS;
1292 goto done;
1294 if (type == FD_TYPE_FILE) continue; /* no async I/O on regular files */
1296 else if (errno != EAGAIN)
1298 if (errno == EINTR) continue;
1299 if (!total)
1301 if (errno == EFAULT) status = STATUS_INVALID_USER_BUFFER;
1302 else status = FILE_GetNtStatus();
1304 goto done;
1307 if (async_write)
1309 struct async_fileio_write *fileio;
1311 fileio = (struct async_fileio_write *)alloc_fileio( sizeof(*fileio), hFile, apc, apc_user );
1312 if (!fileio)
1314 status = STATUS_NO_MEMORY;
1315 goto err;
1317 fileio->already = total;
1318 fileio->count = length;
1319 fileio->buffer = buffer;
1321 SERVER_START_REQ( register_async )
1323 req->type = ASYNC_TYPE_WRITE;
1324 req->count = length;
1325 req->async.handle = wine_server_obj_handle( hFile );
1326 req->async.event = wine_server_obj_handle( hEvent );
1327 req->async.callback = wine_server_client_ptr( FILE_AsyncWriteService );
1328 req->async.iosb = wine_server_client_ptr( io_status );
1329 req->async.arg = wine_server_client_ptr( fileio );
1330 req->async.cvalue = cvalue;
1331 status = wine_server_call( req );
1333 SERVER_END_REQ;
1335 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
1336 goto err;
1338 else /* synchronous write, wait for the fd to become ready */
1340 struct pollfd pfd;
1341 int ret, timeout;
1343 if (!timeout_init_done)
1345 timeout_init_done = TRUE;
1346 if ((status = get_io_timeouts( hFile, type, length, FALSE, &timeouts )))
1347 goto err;
1348 if (hEvent) NtResetEvent( hEvent, NULL );
1350 timeout = get_next_io_timeout( &timeouts, total );
1352 pfd.fd = unix_handle;
1353 pfd.events = POLLOUT;
1355 if (!timeout || !(ret = poll( &pfd, 1, timeout )))
1357 /* return with what we got so far */
1358 status = total ? STATUS_SUCCESS : STATUS_TIMEOUT;
1359 goto done;
1361 if (ret == -1 && errno != EINTR)
1363 status = FILE_GetNtStatus();
1364 goto done;
1366 /* will now restart the write */
1370 done:
1371 send_completion = cvalue != 0;
1373 err:
1374 if (needs_close) close( unix_handle );
1376 if (type == FD_TYPE_SERIAL && (status == STATUS_SUCCESS || status == STATUS_PENDING))
1377 set_pending_write( hFile );
1379 if (status == STATUS_SUCCESS)
1381 io_status->u.Status = status;
1382 io_status->Information = total;
1383 TRACE("= SUCCESS (%u)\n", total);
1384 if (hEvent) NtSetEvent( hEvent, NULL );
1385 if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
1386 (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
1388 else
1390 TRACE("= 0x%08x\n", status);
1391 if (status != STATUS_PENDING && hEvent) NtResetEvent( hEvent, NULL );
1394 if (send_completion) NTDLL_AddCompletion( hFile, cvalue, status, total );
1396 return status;
1400 /******************************************************************************
1401 * NtWriteFileGather [NTDLL.@]
1402 * ZwWriteFileGather [NTDLL.@]
1404 NTSTATUS WINAPI NtWriteFileGather( HANDLE file, HANDLE event, PIO_APC_ROUTINE apc, void *apc_user,
1405 PIO_STATUS_BLOCK io_status, FILE_SEGMENT_ELEMENT *segments,
1406 ULONG length, PLARGE_INTEGER offset, PULONG key )
1408 int result, unix_handle, needs_close;
1409 unsigned int options;
1410 NTSTATUS status;
1411 ULONG pos = 0, total = 0;
1412 enum server_fd_type type;
1413 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
1414 BOOL send_completion = FALSE;
1416 TRACE( "(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p),partial stub!\n",
1417 file, event, apc, apc_user, io_status, segments, length, offset, key);
1419 if (length % page_size) return STATUS_INVALID_PARAMETER;
1420 if (!io_status) return STATUS_ACCESS_VIOLATION;
1422 status = server_get_unix_fd( file, FILE_WRITE_DATA, &unix_handle,
1423 &needs_close, &type, &options );
1424 if (status) return status;
1426 if ((type != FD_TYPE_FILE) ||
1427 (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)) ||
1428 !(options & FILE_NO_INTERMEDIATE_BUFFERING))
1430 status = STATUS_INVALID_PARAMETER;
1431 goto error;
1434 while (length)
1436 if (offset && offset->QuadPart != FILE_USE_FILE_POINTER_POSITION)
1437 result = pwrite( unix_handle, (char *)segments->Buffer + pos,
1438 page_size - pos, offset->QuadPart + total );
1439 else
1440 result = write( unix_handle, (char *)segments->Buffer + pos, page_size - pos );
1442 if (result == -1)
1444 if (errno == EINTR) continue;
1445 if (errno == EFAULT)
1447 status = STATUS_INVALID_USER_BUFFER;
1448 goto error;
1450 status = FILE_GetNtStatus();
1451 break;
1453 if (!result)
1455 status = STATUS_DISK_FULL;
1456 break;
1458 total += result;
1459 length -= result;
1460 if ((pos += result) == page_size)
1462 pos = 0;
1463 segments++;
1467 send_completion = cvalue != 0;
1469 error:
1470 if (needs_close) close( unix_handle );
1471 if (status == STATUS_SUCCESS)
1473 io_status->u.Status = status;
1474 io_status->Information = total;
1475 TRACE("= SUCCESS (%u)\n", total);
1476 if (event) NtSetEvent( event, NULL );
1477 if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
1478 (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
1480 else
1482 TRACE("= 0x%08x\n", status);
1483 if (status != STATUS_PENDING && event) NtResetEvent( event, NULL );
1486 if (send_completion) NTDLL_AddCompletion( file, cvalue, status, total );
1488 return status;
1492 /* do an ioctl call through the server */
1493 static NTSTATUS server_ioctl_file( HANDLE handle, HANDLE event,
1494 PIO_APC_ROUTINE apc, PVOID apc_context,
1495 IO_STATUS_BLOCK *io, ULONG code,
1496 const void *in_buffer, ULONG in_size,
1497 PVOID out_buffer, ULONG out_size )
1499 struct async_irp *async;
1500 NTSTATUS status;
1501 HANDLE wait_handle;
1502 ULONG options;
1503 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_context;
1505 if (!(async = (struct async_irp *)alloc_fileio( sizeof(*async), handle, apc, apc_context )))
1506 return STATUS_NO_MEMORY;
1507 async->event = event;
1508 async->buffer = out_buffer;
1509 async->size = out_size;
1511 SERVER_START_REQ( ioctl )
1513 req->code = code;
1514 req->blocking = !apc && !event && !cvalue;
1515 req->async.handle = wine_server_obj_handle( handle );
1516 req->async.callback = wine_server_client_ptr( irp_completion );
1517 req->async.iosb = wine_server_client_ptr( io );
1518 req->async.arg = wine_server_client_ptr( async );
1519 req->async.event = wine_server_obj_handle( event );
1520 req->async.cvalue = cvalue;
1521 wine_server_add_data( req, in_buffer, in_size );
1522 wine_server_set_reply( req, out_buffer, out_size );
1523 status = wine_server_call( req );
1524 wait_handle = wine_server_ptr_handle( reply->wait );
1525 options = reply->options;
1526 if (status != STATUS_PENDING) io->Information = wine_server_reply_size( reply );
1528 SERVER_END_REQ;
1530 if (status == STATUS_NOT_SUPPORTED)
1531 FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
1532 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
1534 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, async );
1536 if (wait_handle)
1538 NtWaitForSingleObject( wait_handle, (options & FILE_SYNCHRONOUS_IO_ALERT), NULL );
1539 status = io->u.Status;
1540 NtClose( wait_handle );
1543 return status;
1546 /* Tell Valgrind to ignore any holes in structs we will be passing to the
1547 * server */
1548 static void ignore_server_ioctl_struct_holes (ULONG code, const void *in_buffer,
1549 ULONG in_size)
1551 #ifdef VALGRIND_MAKE_MEM_DEFINED
1552 # define IGNORE_STRUCT_HOLE(buf, size, t, f1, f2) \
1553 do { \
1554 if (FIELD_OFFSET(t, f1) + sizeof(((t *)0)->f1) < FIELD_OFFSET(t, f2)) \
1555 if ((size) >= FIELD_OFFSET(t, f2)) \
1556 VALGRIND_MAKE_MEM_DEFINED( \
1557 (const char *)(buf) + FIELD_OFFSET(t, f1) + sizeof(((t *)0)->f1), \
1558 FIELD_OFFSET(t, f2) - FIELD_OFFSET(t, f1) + sizeof(((t *)0)->f1)); \
1559 } while (0)
1561 switch (code)
1563 case FSCTL_PIPE_WAIT:
1564 IGNORE_STRUCT_HOLE(in_buffer, in_size, FILE_PIPE_WAIT_FOR_BUFFER, TimeoutSpecified, Name);
1565 break;
1567 #endif
1571 /**************************************************************************
1572 * NtDeviceIoControlFile [NTDLL.@]
1573 * ZwDeviceIoControlFile [NTDLL.@]
1575 * Perform an I/O control operation on an open file handle.
1577 * PARAMS
1578 * handle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1579 * event [I] Event to signal upon completion (or NULL)
1580 * apc [I] Callback to call upon completion (or NULL)
1581 * apc_context [I] Context for ApcRoutine (or NULL)
1582 * io [O] Receives information about the operation on return
1583 * code [I] Control code for the operation to perform
1584 * in_buffer [I] Source for any input data required (or NULL)
1585 * in_size [I] Size of InputBuffer
1586 * out_buffer [O] Source for any output data returned (or NULL)
1587 * out_size [I] Size of OutputBuffer
1589 * RETURNS
1590 * Success: 0. IoStatusBlock is updated.
1591 * Failure: An NTSTATUS error code describing the error.
1593 NTSTATUS WINAPI NtDeviceIoControlFile(HANDLE handle, HANDLE event,
1594 PIO_APC_ROUTINE apc, PVOID apc_context,
1595 PIO_STATUS_BLOCK io, ULONG code,
1596 PVOID in_buffer, ULONG in_size,
1597 PVOID out_buffer, ULONG out_size)
1599 ULONG device = (code >> 16);
1600 NTSTATUS status = STATUS_NOT_SUPPORTED;
1602 TRACE("(%p,%p,%p,%p,%p,0x%08x,%p,0x%08x,%p,0x%08x)\n",
1603 handle, event, apc, apc_context, io, code,
1604 in_buffer, in_size, out_buffer, out_size);
1606 switch(device)
1608 case FILE_DEVICE_DISK:
1609 case FILE_DEVICE_CD_ROM:
1610 case FILE_DEVICE_DVD:
1611 case FILE_DEVICE_CONTROLLER:
1612 case FILE_DEVICE_MASS_STORAGE:
1613 status = CDROM_DeviceIoControl(handle, event, apc, apc_context, io, code,
1614 in_buffer, in_size, out_buffer, out_size);
1615 break;
1616 case FILE_DEVICE_SERIAL_PORT:
1617 status = COMM_DeviceIoControl(handle, event, apc, apc_context, io, code,
1618 in_buffer, in_size, out_buffer, out_size);
1619 break;
1620 case FILE_DEVICE_TAPE:
1621 status = TAPE_DeviceIoControl(handle, event, apc, apc_context, io, code,
1622 in_buffer, in_size, out_buffer, out_size);
1623 break;
1626 if (status == STATUS_NOT_SUPPORTED || status == STATUS_BAD_DEVICE_TYPE)
1627 status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1628 in_buffer, in_size, out_buffer, out_size );
1630 if (status != STATUS_PENDING) io->u.Status = status;
1631 return status;
1635 /**************************************************************************
1636 * NtFsControlFile [NTDLL.@]
1637 * ZwFsControlFile [NTDLL.@]
1639 * Perform a file system control operation on an open file handle.
1641 * PARAMS
1642 * handle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1643 * event [I] Event to signal upon completion (or NULL)
1644 * apc [I] Callback to call upon completion (or NULL)
1645 * apc_context [I] Context for ApcRoutine (or NULL)
1646 * io [O] Receives information about the operation on return
1647 * code [I] Control code for the operation to perform
1648 * in_buffer [I] Source for any input data required (or NULL)
1649 * in_size [I] Size of InputBuffer
1650 * out_buffer [O] Source for any output data returned (or NULL)
1651 * out_size [I] Size of OutputBuffer
1653 * RETURNS
1654 * Success: 0. IoStatusBlock is updated.
1655 * Failure: An NTSTATUS error code describing the error.
1657 NTSTATUS WINAPI NtFsControlFile(HANDLE handle, HANDLE event, PIO_APC_ROUTINE apc,
1658 PVOID apc_context, PIO_STATUS_BLOCK io, ULONG code,
1659 PVOID in_buffer, ULONG in_size, PVOID out_buffer, ULONG out_size)
1661 NTSTATUS status;
1663 TRACE("(%p,%p,%p,%p,%p,0x%08x,%p,0x%08x,%p,0x%08x)\n",
1664 handle, event, apc, apc_context, io, code,
1665 in_buffer, in_size, out_buffer, out_size);
1667 if (!io) return STATUS_INVALID_PARAMETER;
1669 ignore_server_ioctl_struct_holes( code, in_buffer, in_size );
1671 switch(code)
1673 case FSCTL_DISMOUNT_VOLUME:
1674 status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1675 in_buffer, in_size, out_buffer, out_size );
1676 if (!status) status = DIR_unmount_device( handle );
1677 break;
1679 case FSCTL_PIPE_PEEK:
1681 FILE_PIPE_PEEK_BUFFER *buffer = out_buffer;
1682 int avail = 0, fd, needs_close;
1684 if (out_size < FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data ))
1686 status = STATUS_INFO_LENGTH_MISMATCH;
1687 break;
1690 if ((status = server_get_unix_fd( handle, FILE_READ_DATA, &fd, &needs_close, NULL, NULL )))
1691 break;
1693 #ifdef FIONREAD
1694 if (ioctl( fd, FIONREAD, &avail ) != 0)
1696 TRACE("FIONREAD failed reason: %s\n",strerror(errno));
1697 if (needs_close) close( fd );
1698 status = FILE_GetNtStatus();
1699 break;
1701 #endif
1702 if (!avail) /* check for closed pipe */
1704 struct pollfd pollfd;
1705 int ret;
1707 pollfd.fd = fd;
1708 pollfd.events = POLLIN;
1709 pollfd.revents = 0;
1710 ret = poll( &pollfd, 1, 0 );
1711 if (ret == -1 || (ret == 1 && (pollfd.revents & (POLLHUP|POLLERR))))
1713 if (needs_close) close( fd );
1714 status = STATUS_PIPE_BROKEN;
1715 break;
1718 buffer->NamedPipeState = 0; /* FIXME */
1719 buffer->ReadDataAvailable = avail;
1720 buffer->NumberOfMessages = 0; /* FIXME */
1721 buffer->MessageLength = 0; /* FIXME */
1722 io->Information = FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data );
1723 status = STATUS_SUCCESS;
1724 if (avail)
1726 ULONG data_size = out_size - FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data );
1727 if (data_size)
1729 int res = recv( fd, buffer->Data, data_size, MSG_PEEK );
1730 if (res >= 0) io->Information += res;
1733 if (needs_close) close( fd );
1735 break;
1737 case FSCTL_PIPE_DISCONNECT:
1738 status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1739 in_buffer, in_size, out_buffer, out_size );
1740 if (!status)
1742 int fd = server_remove_fd_from_cache( handle );
1743 if (fd != -1) close( fd );
1745 break;
1747 case FSCTL_PIPE_IMPERSONATE:
1748 FIXME("FSCTL_PIPE_IMPERSONATE: impersonating self\n");
1749 status = RtlImpersonateSelf( SecurityImpersonation );
1750 break;
1752 case FSCTL_IS_VOLUME_MOUNTED:
1753 case FSCTL_LOCK_VOLUME:
1754 case FSCTL_UNLOCK_VOLUME:
1755 FIXME("stub! return success - Unsupported fsctl %x (device=%x access=%x func=%x method=%x)\n",
1756 code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
1757 status = STATUS_SUCCESS;
1758 break;
1760 case FSCTL_GET_RETRIEVAL_POINTERS:
1762 RETRIEVAL_POINTERS_BUFFER *buffer = (RETRIEVAL_POINTERS_BUFFER *)out_buffer;
1764 FIXME("stub: FSCTL_GET_RETRIEVAL_POINTERS\n");
1766 if (out_size >= sizeof(RETRIEVAL_POINTERS_BUFFER))
1768 buffer->ExtentCount = 1;
1769 buffer->StartingVcn.QuadPart = 1;
1770 buffer->Extents[0].NextVcn.QuadPart = 0;
1771 buffer->Extents[0].Lcn.QuadPart = 0;
1772 io->Information = sizeof(RETRIEVAL_POINTERS_BUFFER);
1773 status = STATUS_SUCCESS;
1775 else
1777 io->Information = 0;
1778 status = STATUS_BUFFER_TOO_SMALL;
1780 break;
1782 case FSCTL_PIPE_LISTEN:
1783 case FSCTL_PIPE_WAIT:
1784 default:
1785 status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1786 in_buffer, in_size, out_buffer, out_size );
1787 break;
1790 if (status != STATUS_PENDING) io->u.Status = status;
1791 return status;
1795 struct read_changes_fileio
1797 struct async_fileio io;
1798 void *buffer;
1799 ULONG buffer_size;
1800 ULONG data_size;
1801 char data[1];
1804 static NTSTATUS read_changes_apc( void *user, IO_STATUS_BLOCK *iosb,
1805 NTSTATUS status, void **apc, void **arg )
1807 struct read_changes_fileio *fileio = user;
1808 NTSTATUS ret;
1809 int size;
1811 SERVER_START_REQ( read_change )
1813 req->handle = wine_server_obj_handle( fileio->io.handle );
1814 wine_server_set_reply( req, fileio->data, fileio->data_size );
1815 ret = wine_server_call( req );
1816 size = wine_server_reply_size( reply );
1818 SERVER_END_REQ;
1820 if (ret == STATUS_SUCCESS && fileio->buffer)
1822 FILE_NOTIFY_INFORMATION *pfni = fileio->buffer;
1823 int i, left = fileio->buffer_size;
1824 DWORD *last_entry_offset = NULL;
1825 struct filesystem_event *event = (struct filesystem_event*)fileio->data;
1827 while (size && left >= sizeof(*pfni))
1829 /* convert to an NT style path */
1830 for (i=0; i<event->len; i++)
1831 if (event->name[i] == '/') event->name[i] = '\\';
1833 pfni->Action = event->action;
1834 pfni->FileNameLength = ntdll_umbstowcs( 0, event->name, event->len, pfni->FileName,
1835 (left - offsetof(FILE_NOTIFY_INFORMATION, FileName)) / sizeof(WCHAR));
1836 last_entry_offset = &pfni->NextEntryOffset;
1838 if (pfni->FileNameLength == -1 || pfni->FileNameLength == -2) break;
1840 i = offsetof(FILE_NOTIFY_INFORMATION, FileName[pfni->FileNameLength]);
1841 pfni->FileNameLength *= sizeof(WCHAR);
1842 pfni->NextEntryOffset = i;
1843 pfni = (FILE_NOTIFY_INFORMATION*)((char*)pfni + i);
1844 left -= i;
1846 i = (offsetof(struct filesystem_event, name[event->len])
1847 + sizeof(int)-1) / sizeof(int) * sizeof(int);
1848 event = (struct filesystem_event*)((char*)event + i);
1849 size -= i;
1852 if (size)
1854 ret = STATUS_NOTIFY_ENUM_DIR;
1855 size = 0;
1857 else
1859 *last_entry_offset = 0;
1860 size = fileio->buffer_size - left;
1863 else
1865 ret = STATUS_NOTIFY_ENUM_DIR;
1866 size = 0;
1869 iosb->u.Status = ret;
1870 iosb->Information = size;
1871 *apc = fileio->io.apc;
1872 *arg = fileio->io.apc_arg;
1873 release_fileio( &fileio->io );
1874 return ret;
1877 #define FILE_NOTIFY_ALL ( \
1878 FILE_NOTIFY_CHANGE_FILE_NAME | \
1879 FILE_NOTIFY_CHANGE_DIR_NAME | \
1880 FILE_NOTIFY_CHANGE_ATTRIBUTES | \
1881 FILE_NOTIFY_CHANGE_SIZE | \
1882 FILE_NOTIFY_CHANGE_LAST_WRITE | \
1883 FILE_NOTIFY_CHANGE_LAST_ACCESS | \
1884 FILE_NOTIFY_CHANGE_CREATION | \
1885 FILE_NOTIFY_CHANGE_SECURITY )
1887 /******************************************************************************
1888 * NtNotifyChangeDirectoryFile [NTDLL.@]
1890 NTSTATUS WINAPI NtNotifyChangeDirectoryFile( HANDLE handle, HANDLE event, PIO_APC_ROUTINE apc,
1891 void *apc_context, PIO_STATUS_BLOCK iosb, void *buffer,
1892 ULONG buffer_size, ULONG filter, BOOLEAN subtree )
1894 struct read_changes_fileio *fileio;
1895 NTSTATUS status;
1896 ULONG size = max( 4096, buffer_size );
1897 ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_context;
1899 TRACE( "%p %p %p %p %p %p %u %u %d\n",
1900 handle, event, apc, apc_context, iosb, buffer, buffer_size, filter, subtree );
1902 if (!iosb) return STATUS_ACCESS_VIOLATION;
1903 if (filter == 0 || (filter & ~FILE_NOTIFY_ALL)) return STATUS_INVALID_PARAMETER;
1905 fileio = (struct read_changes_fileio *)alloc_fileio( offsetof(struct read_changes_fileio, data[size]),
1906 handle, apc, apc_context );
1907 if (!fileio) return STATUS_NO_MEMORY;
1909 fileio->buffer = buffer;
1910 fileio->buffer_size = buffer_size;
1911 fileio->data_size = size;
1913 SERVER_START_REQ( read_directory_changes )
1915 req->filter = filter;
1916 req->want_data = (buffer != NULL);
1917 req->subtree = subtree;
1918 req->async.handle = wine_server_obj_handle( handle );
1919 req->async.callback = wine_server_client_ptr( read_changes_apc );
1920 req->async.iosb = wine_server_client_ptr( iosb );
1921 req->async.arg = wine_server_client_ptr( fileio );
1922 req->async.event = wine_server_obj_handle( event );
1923 req->async.cvalue = cvalue;
1924 status = wine_server_call( req );
1926 SERVER_END_REQ;
1928 if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
1929 return status;
1932 /******************************************************************************
1933 * NtSetVolumeInformationFile [NTDLL.@]
1934 * ZwSetVolumeInformationFile [NTDLL.@]
1936 * Set volume information for an open file handle.
1938 * PARAMS
1939 * FileHandle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1940 * IoStatusBlock [O] Receives information about the operation on return
1941 * FsInformation [I] Source for volume information
1942 * Length [I] Size of FsInformation
1943 * FsInformationClass [I] Type of volume information to set
1945 * RETURNS
1946 * Success: 0. IoStatusBlock is updated.
1947 * Failure: An NTSTATUS error code describing the error.
1949 NTSTATUS WINAPI NtSetVolumeInformationFile(
1950 IN HANDLE FileHandle,
1951 PIO_STATUS_BLOCK IoStatusBlock,
1952 PVOID FsInformation,
1953 ULONG Length,
1954 FS_INFORMATION_CLASS FsInformationClass)
1956 FIXME("(%p,%p,%p,0x%08x,0x%08x) stub\n",
1957 FileHandle,IoStatusBlock,FsInformation,Length,FsInformationClass);
1958 return 0;
1961 #if defined(__ANDROID__) && !defined(HAVE_FUTIMENS)
1962 static int futimens( int fd, const struct timespec spec[2] )
1964 return syscall( __NR_utimensat, fd, NULL, spec, 0 );
1966 #define HAVE_FUTIMENS
1967 #endif /* __ANDROID__ */
1969 #ifndef UTIME_OMIT
1970 #define UTIME_OMIT ((1 << 30) - 2)
1971 #endif
1973 static NTSTATUS set_file_times( int fd, const LARGE_INTEGER *mtime, const LARGE_INTEGER *atime )
1975 NTSTATUS status = STATUS_SUCCESS;
1977 #ifdef HAVE_FUTIMENS
1978 struct timespec tv[2];
1980 tv[0].tv_sec = tv[1].tv_sec = 0;
1981 tv[0].tv_nsec = tv[1].tv_nsec = UTIME_OMIT;
1982 if (atime->QuadPart)
1984 tv[0].tv_sec = atime->QuadPart / 10000000 - SECS_1601_TO_1970;
1985 tv[0].tv_nsec = (atime->QuadPart % 10000000) * 100;
1987 if (mtime->QuadPart)
1989 tv[1].tv_sec = mtime->QuadPart / 10000000 - SECS_1601_TO_1970;
1990 tv[1].tv_nsec = (mtime->QuadPart % 10000000) * 100;
1992 if (futimens( fd, tv ) == -1) status = FILE_GetNtStatus();
1994 #elif defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT)
1995 struct timeval tv[2];
1996 struct stat st;
1998 if (!atime->QuadPart || !mtime->QuadPart)
2001 tv[0].tv_sec = tv[0].tv_usec = 0;
2002 tv[1].tv_sec = tv[1].tv_usec = 0;
2003 if (!fstat( fd, &st ))
2005 tv[0].tv_sec = st.st_atime;
2006 tv[1].tv_sec = st.st_mtime;
2007 #ifdef HAVE_STRUCT_STAT_ST_ATIM
2008 tv[0].tv_usec = st.st_atim.tv_nsec / 1000;
2009 #elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC)
2010 tv[0].tv_usec = st.st_atimespec.tv_nsec / 1000;
2011 #endif
2012 #ifdef HAVE_STRUCT_STAT_ST_MTIM
2013 tv[1].tv_usec = st.st_mtim.tv_nsec / 1000;
2014 #elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC)
2015 tv[1].tv_usec = st.st_mtimespec.tv_nsec / 1000;
2016 #endif
2019 if (atime->QuadPart)
2021 tv[0].tv_sec = atime->QuadPart / 10000000 - SECS_1601_TO_1970;
2022 tv[0].tv_usec = (atime->QuadPart % 10000000) / 10;
2024 if (mtime->QuadPart)
2026 tv[1].tv_sec = mtime->QuadPart / 10000000 - SECS_1601_TO_1970;
2027 tv[1].tv_usec = (mtime->QuadPart % 10000000) / 10;
2029 #ifdef HAVE_FUTIMES
2030 if (futimes( fd, tv ) == -1) status = FILE_GetNtStatus();
2031 #elif defined(HAVE_FUTIMESAT)
2032 if (futimesat( fd, NULL, tv ) == -1) status = FILE_GetNtStatus();
2033 #endif
2035 #else /* HAVE_FUTIMES || HAVE_FUTIMESAT */
2036 FIXME( "setting file times not supported\n" );
2037 status = STATUS_NOT_IMPLEMENTED;
2038 #endif
2039 return status;
2042 static inline void get_file_times( const struct stat *st, LARGE_INTEGER *mtime, LARGE_INTEGER *ctime,
2043 LARGE_INTEGER *atime, LARGE_INTEGER *creation )
2045 RtlSecondsSince1970ToTime( st->st_mtime, mtime );
2046 RtlSecondsSince1970ToTime( st->st_ctime, ctime );
2047 RtlSecondsSince1970ToTime( st->st_atime, atime );
2048 #ifdef HAVE_STRUCT_STAT_ST_MTIM
2049 mtime->QuadPart += st->st_mtim.tv_nsec / 100;
2050 #elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC)
2051 mtime->QuadPart += st->st_mtimespec.tv_nsec / 100;
2052 #endif
2053 #ifdef HAVE_STRUCT_STAT_ST_CTIM
2054 ctime->QuadPart += st->st_ctim.tv_nsec / 100;
2055 #elif defined(HAVE_STRUCT_STAT_ST_CTIMESPEC)
2056 ctime->QuadPart += st->st_ctimespec.tv_nsec / 100;
2057 #endif
2058 #ifdef HAVE_STRUCT_STAT_ST_ATIM
2059 atime->QuadPart += st->st_atim.tv_nsec / 100;
2060 #elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC)
2061 atime->QuadPart += st->st_atimespec.tv_nsec / 100;
2062 #endif
2063 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
2064 RtlSecondsSince1970ToTime( st->st_birthtime, creation );
2065 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIM
2066 creation->QuadPart += st->st_birthtim.tv_nsec / 100;
2067 #elif defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC)
2068 creation->QuadPart += st->st_birthtimespec.tv_nsec / 100;
2069 #endif
2070 #elif defined(HAVE_STRUCT_STAT___ST_BIRTHTIME)
2071 RtlSecondsSince1970ToTime( st->__st_birthtime, creation );
2072 #ifdef HAVE_STRUCT_STAT___ST_BIRTHTIM
2073 creation->QuadPart += st->__st_birthtim.tv_nsec / 100;
2074 #endif
2075 #else
2076 *creation = *mtime;
2077 #endif
2080 /* fill in the file information that depends on the stat and attribute info */
2081 NTSTATUS fill_file_info( const struct stat *st, ULONG attr, void *ptr,
2082 FILE_INFORMATION_CLASS class )
2084 switch (class)
2086 case FileBasicInformation:
2088 FILE_BASIC_INFORMATION *info = ptr;
2090 get_file_times( st, &info->LastWriteTime, &info->ChangeTime,
2091 &info->LastAccessTime, &info->CreationTime );
2092 info->FileAttributes = attr;
2094 break;
2095 case FileStandardInformation:
2097 FILE_STANDARD_INFORMATION *info = ptr;
2099 if ((info->Directory = S_ISDIR(st->st_mode)))
2101 info->AllocationSize.QuadPart = 0;
2102 info->EndOfFile.QuadPart = 0;
2103 info->NumberOfLinks = 1;
2105 else
2107 info->AllocationSize.QuadPart = (ULONGLONG)st->st_blocks * 512;
2108 info->EndOfFile.QuadPart = st->st_size;
2109 info->NumberOfLinks = st->st_nlink;
2112 break;
2113 case FileInternalInformation:
2115 FILE_INTERNAL_INFORMATION *info = ptr;
2116 info->IndexNumber.QuadPart = st->st_ino;
2118 break;
2119 case FileEndOfFileInformation:
2121 FILE_END_OF_FILE_INFORMATION *info = ptr;
2122 info->EndOfFile.QuadPart = S_ISDIR(st->st_mode) ? 0 : st->st_size;
2124 break;
2125 case FileAllInformation:
2127 FILE_ALL_INFORMATION *info = ptr;
2128 fill_file_info( st, attr, &info->BasicInformation, FileBasicInformation );
2129 fill_file_info( st, attr, &info->StandardInformation, FileStandardInformation );
2130 fill_file_info( st, attr, &info->InternalInformation, FileInternalInformation );
2132 break;
2133 /* all directory structures start with the FileDirectoryInformation layout */
2134 case FileBothDirectoryInformation:
2135 case FileFullDirectoryInformation:
2136 case FileDirectoryInformation:
2138 FILE_DIRECTORY_INFORMATION *info = ptr;
2140 get_file_times( st, &info->LastWriteTime, &info->ChangeTime,
2141 &info->LastAccessTime, &info->CreationTime );
2142 if (S_ISDIR(st->st_mode))
2144 info->AllocationSize.QuadPart = 0;
2145 info->EndOfFile.QuadPart = 0;
2147 else
2149 info->AllocationSize.QuadPart = (ULONGLONG)st->st_blocks * 512;
2150 info->EndOfFile.QuadPart = st->st_size;
2152 info->FileAttributes = attr;
2154 break;
2155 case FileIdFullDirectoryInformation:
2157 FILE_ID_FULL_DIRECTORY_INFORMATION *info = ptr;
2158 info->FileId.QuadPart = st->st_ino;
2159 fill_file_info( st, attr, info, FileDirectoryInformation );
2161 break;
2162 case FileIdBothDirectoryInformation:
2164 FILE_ID_BOTH_DIRECTORY_INFORMATION *info = ptr;
2165 info->FileId.QuadPart = st->st_ino;
2166 fill_file_info( st, attr, info, FileDirectoryInformation );
2168 break;
2170 default:
2171 return STATUS_INVALID_INFO_CLASS;
2173 return STATUS_SUCCESS;
2176 NTSTATUS server_get_unix_name( HANDLE handle, ANSI_STRING *unix_name )
2178 data_size_t size = 1024;
2179 NTSTATUS ret;
2180 char *name;
2182 for (;;)
2184 name = RtlAllocateHeap( GetProcessHeap(), 0, size + 1 );
2185 if (!name) return STATUS_NO_MEMORY;
2186 unix_name->MaximumLength = size + 1;
2188 SERVER_START_REQ( get_handle_unix_name )
2190 req->handle = wine_server_obj_handle( handle );
2191 wine_server_set_reply( req, name, size );
2192 ret = wine_server_call( req );
2193 size = reply->name_len;
2195 SERVER_END_REQ;
2197 if (!ret)
2199 name[size] = 0;
2200 unix_name->Buffer = name;
2201 unix_name->Length = size;
2202 break;
2204 RtlFreeHeap( GetProcessHeap(), 0, name );
2205 if (ret != STATUS_BUFFER_OVERFLOW) break;
2207 return ret;
2210 static NTSTATUS fill_name_info( const ANSI_STRING *unix_name, FILE_NAME_INFORMATION *info, LONG *name_len )
2212 UNICODE_STRING nt_name;
2213 NTSTATUS status;
2215 if (!(status = wine_unix_to_nt_file_name( unix_name, &nt_name )))
2217 const WCHAR *ptr = nt_name.Buffer;
2218 const WCHAR *end = ptr + (nt_name.Length / sizeof(WCHAR));
2220 /* Skip the volume mount point. */
2221 while (ptr != end && *ptr == '\\') ++ptr;
2222 while (ptr != end && *ptr != '\\') ++ptr;
2223 while (ptr != end && *ptr == '\\') ++ptr;
2224 while (ptr != end && *ptr != '\\') ++ptr;
2226 info->FileNameLength = (end - ptr) * sizeof(WCHAR);
2227 if (*name_len < info->FileNameLength) status = STATUS_BUFFER_OVERFLOW;
2228 else *name_len = info->FileNameLength;
2230 memcpy( info->FileName, ptr, *name_len );
2231 RtlFreeUnicodeString( &nt_name );
2234 return status;
2237 /******************************************************************************
2238 * NtQueryInformationFile [NTDLL.@]
2239 * ZwQueryInformationFile [NTDLL.@]
2241 * Get information about an open file handle.
2243 * PARAMS
2244 * hFile [I] Handle returned from ZwOpenFile() or ZwCreateFile()
2245 * io [O] Receives information about the operation on return
2246 * ptr [O] Destination for file information
2247 * len [I] Size of FileInformation
2248 * class [I] Type of file information to get
2250 * RETURNS
2251 * Success: 0. IoStatusBlock and FileInformation are updated.
2252 * Failure: An NTSTATUS error code describing the error.
2254 NTSTATUS WINAPI NtQueryInformationFile( HANDLE hFile, PIO_STATUS_BLOCK io,
2255 PVOID ptr, LONG len, FILE_INFORMATION_CLASS class )
2257 static const size_t info_sizes[] =
2260 sizeof(FILE_DIRECTORY_INFORMATION), /* FileDirectoryInformation */
2261 sizeof(FILE_FULL_DIRECTORY_INFORMATION), /* FileFullDirectoryInformation */
2262 sizeof(FILE_BOTH_DIRECTORY_INFORMATION), /* FileBothDirectoryInformation */
2263 sizeof(FILE_BASIC_INFORMATION), /* FileBasicInformation */
2264 sizeof(FILE_STANDARD_INFORMATION), /* FileStandardInformation */
2265 sizeof(FILE_INTERNAL_INFORMATION), /* FileInternalInformation */
2266 sizeof(FILE_EA_INFORMATION), /* FileEaInformation */
2267 sizeof(FILE_ACCESS_INFORMATION), /* FileAccessInformation */
2268 sizeof(FILE_NAME_INFORMATION), /* FileNameInformation */
2269 sizeof(FILE_RENAME_INFORMATION)-sizeof(WCHAR), /* FileRenameInformation */
2270 0, /* FileLinkInformation */
2271 sizeof(FILE_NAMES_INFORMATION)-sizeof(WCHAR), /* FileNamesInformation */
2272 sizeof(FILE_DISPOSITION_INFORMATION), /* FileDispositionInformation */
2273 sizeof(FILE_POSITION_INFORMATION), /* FilePositionInformation */
2274 sizeof(FILE_FULL_EA_INFORMATION), /* FileFullEaInformation */
2275 sizeof(FILE_MODE_INFORMATION), /* FileModeInformation */
2276 sizeof(FILE_ALIGNMENT_INFORMATION), /* FileAlignmentInformation */
2277 sizeof(FILE_ALL_INFORMATION), /* FileAllInformation */
2278 sizeof(FILE_ALLOCATION_INFORMATION), /* FileAllocationInformation */
2279 sizeof(FILE_END_OF_FILE_INFORMATION), /* FileEndOfFileInformation */
2280 0, /* FileAlternateNameInformation */
2281 sizeof(FILE_STREAM_INFORMATION)-sizeof(WCHAR), /* FileStreamInformation */
2282 sizeof(FILE_PIPE_INFORMATION), /* FilePipeInformation */
2283 sizeof(FILE_PIPE_LOCAL_INFORMATION), /* FilePipeLocalInformation */
2284 0, /* FilePipeRemoteInformation */
2285 sizeof(FILE_MAILSLOT_QUERY_INFORMATION), /* FileMailslotQueryInformation */
2286 0, /* FileMailslotSetInformation */
2287 0, /* FileCompressionInformation */
2288 0, /* FileObjectIdInformation */
2289 0, /* FileCompletionInformation */
2290 0, /* FileMoveClusterInformation */
2291 0, /* FileQuotaInformation */
2292 0, /* FileReparsePointInformation */
2293 sizeof(FILE_NETWORK_OPEN_INFORMATION), /* FileNetworkOpenInformation */
2294 0, /* FileAttributeTagInformation */
2295 0, /* FileTrackingInformation */
2296 0, /* FileIdBothDirectoryInformation */
2297 0, /* FileIdFullDirectoryInformation */
2298 0, /* FileValidDataLengthInformation */
2299 0, /* FileShortNameInformation */
2300 0, /* FileIoCompletionNotificationInformation, */
2301 0, /* FileIoStatusBlockRangeInformation */
2302 0, /* FileIoPriorityHintInformation */
2303 0, /* FileSfioReserveInformation */
2304 0, /* FileSfioVolumeInformation */
2305 0, /* FileHardLinkInformation */
2306 0, /* FileProcessIdsUsingFileInformation */
2307 0, /* FileNormalizedNameInformation */
2308 0, /* FileNetworkPhysicalNameInformation */
2309 0, /* FileIdGlobalTxDirectoryInformation */
2310 0, /* FileIsRemoteDeviceInformation */
2311 0, /* FileAttributeCacheInformation */
2312 0, /* FileNumaNodeInformation */
2313 0, /* FileStandardLinkInformation */
2314 0, /* FileRemoteProtocolInformation */
2315 0, /* FileReplaceCompletionInformation */
2318 struct stat st;
2319 int fd, needs_close = FALSE;
2320 ULONG attr;
2322 TRACE("(%p,%p,%p,0x%08x,0x%08x)\n", hFile, io, ptr, len, class);
2324 io->Information = 0;
2326 if (class <= 0 || class >= FileMaximumInformation)
2327 return io->u.Status = STATUS_INVALID_INFO_CLASS;
2328 if (!info_sizes[class])
2330 FIXME("Unsupported class (%d)\n", class);
2331 return io->u.Status = STATUS_NOT_IMPLEMENTED;
2333 if (len < info_sizes[class])
2334 return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
2336 if (class != FilePipeInformation && class != FilePipeLocalInformation)
2338 if ((io->u.Status = server_get_unix_fd( hFile, 0, &fd, &needs_close, NULL, NULL )))
2339 return io->u.Status;
2342 switch (class)
2344 case FileBasicInformation:
2345 if (fd_get_file_info( fd, &st, &attr ) == -1)
2346 io->u.Status = FILE_GetNtStatus();
2347 else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
2348 io->u.Status = STATUS_INVALID_INFO_CLASS;
2349 else
2350 fill_file_info( &st, attr, ptr, class );
2351 break;
2352 case FileStandardInformation:
2354 FILE_STANDARD_INFORMATION *info = ptr;
2356 if (fd_get_file_info( fd, &st, &attr ) == -1) io->u.Status = FILE_GetNtStatus();
2357 else
2359 fill_file_info( &st, attr, info, class );
2360 info->DeletePending = FALSE; /* FIXME */
2363 break;
2364 case FilePositionInformation:
2366 FILE_POSITION_INFORMATION *info = ptr;
2367 off_t res = lseek( fd, 0, SEEK_CUR );
2368 if (res == (off_t)-1) io->u.Status = FILE_GetNtStatus();
2369 else info->CurrentByteOffset.QuadPart = res;
2371 break;
2372 case FileInternalInformation:
2373 if (fd_get_file_info( fd, &st, &attr ) == -1) io->u.Status = FILE_GetNtStatus();
2374 else fill_file_info( &st, attr, ptr, class );
2375 break;
2376 case FileEaInformation:
2378 FILE_EA_INFORMATION *info = ptr;
2379 info->EaSize = 0;
2381 break;
2382 case FileEndOfFileInformation:
2383 if (fd_get_file_info( fd, &st, &attr ) == -1) io->u.Status = FILE_GetNtStatus();
2384 else fill_file_info( &st, attr, ptr, class );
2385 break;
2386 case FileAllInformation:
2388 FILE_ALL_INFORMATION *info = ptr;
2389 ANSI_STRING unix_name;
2391 if (fd_get_file_info( fd, &st, &attr ) == -1) io->u.Status = FILE_GetNtStatus();
2392 else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
2393 io->u.Status = STATUS_INVALID_INFO_CLASS;
2394 else if (!(io->u.Status = server_get_unix_name( hFile, &unix_name )))
2396 LONG name_len = len - FIELD_OFFSET(FILE_ALL_INFORMATION, NameInformation.FileName);
2398 fill_file_info( &st, attr, info, FileAllInformation );
2399 info->StandardInformation.DeletePending = FALSE; /* FIXME */
2400 info->EaInformation.EaSize = 0;
2401 info->AccessInformation.AccessFlags = 0; /* FIXME */
2402 info->PositionInformation.CurrentByteOffset.QuadPart = lseek( fd, 0, SEEK_CUR );
2403 info->ModeInformation.Mode = 0; /* FIXME */
2404 info->AlignmentInformation.AlignmentRequirement = 1; /* FIXME */
2406 io->u.Status = fill_name_info( &unix_name, &info->NameInformation, &name_len );
2407 RtlFreeAnsiString( &unix_name );
2408 io->Information = FIELD_OFFSET(FILE_ALL_INFORMATION, NameInformation.FileName) + name_len;
2411 break;
2412 case FileMailslotQueryInformation:
2414 FILE_MAILSLOT_QUERY_INFORMATION *info = ptr;
2416 SERVER_START_REQ( set_mailslot_info )
2418 req->handle = wine_server_obj_handle( hFile );
2419 req->flags = 0;
2420 io->u.Status = wine_server_call( req );
2421 if( io->u.Status == STATUS_SUCCESS )
2423 info->MaximumMessageSize = reply->max_msgsize;
2424 info->MailslotQuota = 0;
2425 info->NextMessageSize = 0;
2426 info->MessagesAvailable = 0;
2427 info->ReadTimeout.QuadPart = reply->read_timeout;
2430 SERVER_END_REQ;
2431 if (!io->u.Status)
2433 char *tmpbuf;
2434 ULONG size = info->MaximumMessageSize ? info->MaximumMessageSize : 0x10000;
2435 if (size > 0x10000) size = 0x10000;
2436 if ((tmpbuf = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2438 if (!server_get_unix_fd( hFile, FILE_READ_DATA, &fd, &needs_close, NULL, NULL ))
2440 int res = recv( fd, tmpbuf, size, MSG_PEEK );
2441 info->MessagesAvailable = (res > 0);
2442 info->NextMessageSize = (res >= 0) ? res : MAILSLOT_NO_MESSAGE;
2443 if (needs_close) close( fd );
2445 RtlFreeHeap( GetProcessHeap(), 0, tmpbuf );
2449 break;
2450 case FilePipeInformation:
2452 FILE_PIPE_INFORMATION* pi = ptr;
2454 SERVER_START_REQ( get_named_pipe_info )
2456 req->handle = wine_server_obj_handle( hFile );
2457 if (!(io->u.Status = wine_server_call( req )))
2459 pi->ReadMode = (reply->flags & NAMED_PIPE_MESSAGE_STREAM_READ) ?
2460 FILE_PIPE_MESSAGE_MODE : FILE_PIPE_BYTE_STREAM_MODE;
2461 pi->CompletionMode = (reply->flags & NAMED_PIPE_NONBLOCKING_MODE) ?
2462 FILE_PIPE_COMPLETE_OPERATION : FILE_PIPE_QUEUE_OPERATION;
2465 SERVER_END_REQ;
2467 break;
2468 case FilePipeLocalInformation:
2470 FILE_PIPE_LOCAL_INFORMATION* pli = ptr;
2472 SERVER_START_REQ( get_named_pipe_info )
2474 req->handle = wine_server_obj_handle( hFile );
2475 if (!(io->u.Status = wine_server_call( req )))
2477 pli->NamedPipeType = (reply->flags & NAMED_PIPE_MESSAGE_STREAM_WRITE) ?
2478 FILE_PIPE_TYPE_MESSAGE : FILE_PIPE_TYPE_BYTE;
2479 switch (reply->sharing)
2481 case FILE_SHARE_READ:
2482 pli->NamedPipeConfiguration = FILE_PIPE_OUTBOUND;
2483 break;
2484 case FILE_SHARE_WRITE:
2485 pli->NamedPipeConfiguration = FILE_PIPE_INBOUND;
2486 break;
2487 case FILE_SHARE_READ | FILE_SHARE_WRITE:
2488 pli->NamedPipeConfiguration = FILE_PIPE_FULL_DUPLEX;
2489 break;
2491 pli->MaximumInstances = reply->maxinstances;
2492 pli->CurrentInstances = reply->instances;
2493 pli->InboundQuota = reply->insize;
2494 pli->ReadDataAvailable = 0; /* FIXME */
2495 pli->OutboundQuota = reply->outsize;
2496 pli->WriteQuotaAvailable = 0; /* FIXME */
2497 pli->NamedPipeState = 0; /* FIXME */
2498 pli->NamedPipeEnd = (reply->flags & NAMED_PIPE_SERVER_END) ?
2499 FILE_PIPE_SERVER_END : FILE_PIPE_CLIENT_END;
2502 SERVER_END_REQ;
2504 break;
2505 case FileNameInformation:
2507 FILE_NAME_INFORMATION *info = ptr;
2508 ANSI_STRING unix_name;
2510 if (!(io->u.Status = server_get_unix_name( hFile, &unix_name )))
2512 LONG name_len = len - FIELD_OFFSET(FILE_NAME_INFORMATION, FileName);
2513 io->u.Status = fill_name_info( &unix_name, info, &name_len );
2514 RtlFreeAnsiString( &unix_name );
2515 io->Information = FIELD_OFFSET(FILE_NAME_INFORMATION, FileName) + name_len;
2518 break;
2519 case FileNetworkOpenInformation:
2521 FILE_NETWORK_OPEN_INFORMATION *info = ptr;
2522 ANSI_STRING unix_name;
2524 if (!(io->u.Status = server_get_unix_name( hFile, &unix_name )))
2526 ULONG attributes;
2527 struct stat st;
2529 if (get_file_info( unix_name.Buffer, &st, &attributes ) == -1)
2530 io->u.Status = FILE_GetNtStatus();
2531 else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
2532 io->u.Status = STATUS_INVALID_INFO_CLASS;
2533 else
2535 FILE_BASIC_INFORMATION basic;
2536 FILE_STANDARD_INFORMATION std;
2538 fill_file_info( &st, attributes, &basic, FileBasicInformation );
2539 fill_file_info( &st, attributes, &std, FileStandardInformation );
2541 info->CreationTime = basic.CreationTime;
2542 info->LastAccessTime = basic.LastAccessTime;
2543 info->LastWriteTime = basic.LastWriteTime;
2544 info->ChangeTime = basic.ChangeTime;
2545 info->AllocationSize = std.AllocationSize;
2546 info->EndOfFile = std.EndOfFile;
2547 info->FileAttributes = basic.FileAttributes;
2549 RtlFreeAnsiString( &unix_name );
2552 break;
2553 default:
2554 FIXME("Unsupported class (%d)\n", class);
2555 io->u.Status = STATUS_NOT_IMPLEMENTED;
2556 break;
2558 if (needs_close) close( fd );
2559 if (io->u.Status == STATUS_SUCCESS && !io->Information) io->Information = info_sizes[class];
2560 return io->u.Status;
2563 /******************************************************************************
2564 * NtSetInformationFile [NTDLL.@]
2565 * ZwSetInformationFile [NTDLL.@]
2567 * Set information about an open file handle.
2569 * PARAMS
2570 * handle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
2571 * io [O] Receives information about the operation on return
2572 * ptr [I] Source for file information
2573 * len [I] Size of FileInformation
2574 * class [I] Type of file information to set
2576 * RETURNS
2577 * Success: 0. io is updated.
2578 * Failure: An NTSTATUS error code describing the error.
2580 NTSTATUS WINAPI NtSetInformationFile(HANDLE handle, PIO_STATUS_BLOCK io,
2581 PVOID ptr, ULONG len, FILE_INFORMATION_CLASS class)
2583 int fd, needs_close;
2585 TRACE("(%p,%p,%p,0x%08x,0x%08x)\n", handle, io, ptr, len, class);
2587 io->u.Status = STATUS_SUCCESS;
2588 switch (class)
2590 case FileBasicInformation:
2591 if (len >= sizeof(FILE_BASIC_INFORMATION))
2593 struct stat st;
2594 const FILE_BASIC_INFORMATION *info = ptr;
2596 if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
2597 return io->u.Status;
2599 if (info->LastAccessTime.QuadPart || info->LastWriteTime.QuadPart)
2600 io->u.Status = set_file_times( fd, &info->LastWriteTime, &info->LastAccessTime );
2602 if (io->u.Status == STATUS_SUCCESS && info->FileAttributes)
2604 if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
2605 else
2607 if (info->FileAttributes & FILE_ATTRIBUTE_READONLY)
2609 if (S_ISDIR( st.st_mode))
2610 WARN("FILE_ATTRIBUTE_READONLY ignored for directory.\n");
2611 else
2612 st.st_mode &= ~0222; /* clear write permission bits */
2614 else
2616 /* add write permission only where we already have read permission */
2617 st.st_mode |= (0600 | ((st.st_mode & 044) >> 1)) & (~FILE_umask);
2619 if (fchmod( fd, st.st_mode ) == -1) io->u.Status = FILE_GetNtStatus();
2623 if (needs_close) close( fd );
2625 else io->u.Status = STATUS_INVALID_PARAMETER_3;
2626 break;
2628 case FilePositionInformation:
2629 if (len >= sizeof(FILE_POSITION_INFORMATION))
2631 const FILE_POSITION_INFORMATION *info = ptr;
2633 if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
2634 return io->u.Status;
2636 if (lseek( fd, info->CurrentByteOffset.QuadPart, SEEK_SET ) == (off_t)-1)
2637 io->u.Status = FILE_GetNtStatus();
2639 if (needs_close) close( fd );
2641 else io->u.Status = STATUS_INVALID_PARAMETER_3;
2642 break;
2644 case FileEndOfFileInformation:
2645 if (len >= sizeof(FILE_END_OF_FILE_INFORMATION))
2647 struct stat st;
2648 const FILE_END_OF_FILE_INFORMATION *info = ptr;
2650 if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
2651 return io->u.Status;
2653 /* first try normal truncate */
2654 if (ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
2656 /* now check for the need to extend the file */
2657 if (fstat( fd, &st ) != -1 && (off_t)info->EndOfFile.QuadPart > st.st_size)
2659 static const char zero;
2661 /* extend the file one byte beyond the requested size and then truncate it */
2662 /* this should work around ftruncate implementations that can't extend files */
2663 if (pwrite( fd, &zero, 1, (off_t)info->EndOfFile.QuadPart ) != -1 &&
2664 ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
2666 io->u.Status = FILE_GetNtStatus();
2668 if (needs_close) close( fd );
2670 else io->u.Status = STATUS_INVALID_PARAMETER_3;
2671 break;
2673 case FilePipeInformation:
2674 if (len >= sizeof(FILE_PIPE_INFORMATION))
2676 FILE_PIPE_INFORMATION *info = ptr;
2678 if ((info->CompletionMode | info->ReadMode) & ~1)
2680 io->u.Status = STATUS_INVALID_PARAMETER;
2681 break;
2684 SERVER_START_REQ( set_named_pipe_info )
2686 req->handle = wine_server_obj_handle( handle );
2687 req->flags = (info->CompletionMode ? NAMED_PIPE_NONBLOCKING_MODE : 0) |
2688 (info->ReadMode ? NAMED_PIPE_MESSAGE_STREAM_READ : 0);
2689 io->u.Status = wine_server_call( req );
2691 SERVER_END_REQ;
2693 else io->u.Status = STATUS_INVALID_PARAMETER_3;
2694 break;
2696 case FileMailslotSetInformation:
2698 FILE_MAILSLOT_SET_INFORMATION *info = ptr;
2700 SERVER_START_REQ( set_mailslot_info )
2702 req->handle = wine_server_obj_handle( handle );
2703 req->flags = MAILSLOT_SET_READ_TIMEOUT;
2704 req->read_timeout = info->ReadTimeout.QuadPart;
2705 io->u.Status = wine_server_call( req );
2707 SERVER_END_REQ;
2709 break;
2711 case FileCompletionInformation:
2712 if (len >= sizeof(FILE_COMPLETION_INFORMATION))
2714 FILE_COMPLETION_INFORMATION *info = ptr;
2716 SERVER_START_REQ( set_completion_info )
2718 req->handle = wine_server_obj_handle( handle );
2719 req->chandle = wine_server_obj_handle( info->CompletionPort );
2720 req->ckey = info->CompletionKey;
2721 io->u.Status = wine_server_call( req );
2723 SERVER_END_REQ;
2724 } else
2725 io->u.Status = STATUS_INVALID_PARAMETER_3;
2726 break;
2728 case FileAllInformation:
2729 io->u.Status = STATUS_INVALID_INFO_CLASS;
2730 break;
2732 case FileValidDataLengthInformation:
2733 if (len >= sizeof(FILE_VALID_DATA_LENGTH_INFORMATION))
2735 struct stat st;
2736 const FILE_VALID_DATA_LENGTH_INFORMATION *info = ptr;
2738 if ((io->u.Status = server_get_unix_fd( handle, FILE_WRITE_DATA, &fd, &needs_close, NULL, NULL )))
2739 return io->u.Status;
2741 if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
2742 else if (info->ValidDataLength.QuadPart <= 0 || (off_t)info->ValidDataLength.QuadPart > st.st_size)
2743 io->u.Status = STATUS_INVALID_PARAMETER;
2744 else
2746 #ifdef HAVE_FALLOCATE
2747 if (fallocate( fd, 0, 0, (off_t)info->ValidDataLength.QuadPart ) == -1)
2749 NTSTATUS status = FILE_GetNtStatus();
2750 if (status == STATUS_NOT_SUPPORTED) WARN( "fallocate not supported on this filesystem\n" );
2751 else io->u.Status = status;
2753 #else
2754 FIXME( "setting valid data length not supported\n" );
2755 #endif
2757 if (needs_close) close( fd );
2759 else io->u.Status = STATUS_INVALID_PARAMETER_3;
2760 break;
2762 default:
2763 FIXME("Unsupported class (%d)\n", class);
2764 io->u.Status = STATUS_NOT_IMPLEMENTED;
2765 break;
2767 io->Information = 0;
2768 return io->u.Status;
2772 /******************************************************************************
2773 * NtQueryFullAttributesFile (NTDLL.@)
2775 NTSTATUS WINAPI NtQueryFullAttributesFile( const OBJECT_ATTRIBUTES *attr,
2776 FILE_NETWORK_OPEN_INFORMATION *info )
2778 ANSI_STRING unix_name;
2779 NTSTATUS status;
2781 if (!(status = nt_to_unix_file_name_attr( attr, &unix_name, FILE_OPEN )))
2783 ULONG attributes;
2784 struct stat st;
2786 if (get_file_info( unix_name.Buffer, &st, &attributes ) == -1)
2787 status = FILE_GetNtStatus();
2788 else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
2789 status = STATUS_INVALID_INFO_CLASS;
2790 else
2792 FILE_BASIC_INFORMATION basic;
2793 FILE_STANDARD_INFORMATION std;
2795 fill_file_info( &st, attributes, &basic, FileBasicInformation );
2796 fill_file_info( &st, attributes, &std, FileStandardInformation );
2798 info->CreationTime = basic.CreationTime;
2799 info->LastAccessTime = basic.LastAccessTime;
2800 info->LastWriteTime = basic.LastWriteTime;
2801 info->ChangeTime = basic.ChangeTime;
2802 info->AllocationSize = std.AllocationSize;
2803 info->EndOfFile = std.EndOfFile;
2804 info->FileAttributes = basic.FileAttributes;
2805 if (DIR_is_hidden_file( attr->ObjectName ))
2806 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
2808 RtlFreeAnsiString( &unix_name );
2810 else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), status );
2811 return status;
2815 /******************************************************************************
2816 * NtQueryAttributesFile (NTDLL.@)
2817 * ZwQueryAttributesFile (NTDLL.@)
2819 NTSTATUS WINAPI NtQueryAttributesFile( const OBJECT_ATTRIBUTES *attr, FILE_BASIC_INFORMATION *info )
2821 ANSI_STRING unix_name;
2822 NTSTATUS status;
2824 if (!(status = nt_to_unix_file_name_attr( attr, &unix_name, FILE_OPEN )))
2826 ULONG attributes;
2827 struct stat st;
2829 if (get_file_info( unix_name.Buffer, &st, &attributes ) == -1)
2830 status = FILE_GetNtStatus();
2831 else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
2832 status = STATUS_INVALID_INFO_CLASS;
2833 else
2835 status = fill_file_info( &st, attributes, info, FileBasicInformation );
2836 if (DIR_is_hidden_file( attr->ObjectName ))
2837 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
2839 RtlFreeAnsiString( &unix_name );
2841 else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), status );
2842 return status;
2846 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
2847 /* helper for FILE_GetDeviceInfo to hide some platform differences in fstatfs */
2848 static inline void get_device_info_fstatfs( FILE_FS_DEVICE_INFORMATION *info, const char *fstypename,
2849 unsigned int flags )
2851 if (!strcmp("cd9660", fstypename) || !strcmp("udf", fstypename))
2853 info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
2854 /* Don't assume read-only, let the mount options set it below */
2855 info->Characteristics |= FILE_REMOVABLE_MEDIA;
2857 else if (!strcmp("nfs", fstypename) || !strcmp("nwfs", fstypename) ||
2858 !strcmp("smbfs", fstypename) || !strcmp("afpfs", fstypename))
2860 info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
2861 info->Characteristics |= FILE_REMOTE_DEVICE;
2863 else if (!strcmp("procfs", fstypename))
2864 info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
2865 else
2866 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2868 if (flags & MNT_RDONLY)
2869 info->Characteristics |= FILE_READ_ONLY_DEVICE;
2871 if (!(flags & MNT_LOCAL))
2873 info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
2874 info->Characteristics |= FILE_REMOTE_DEVICE;
2877 #endif
2879 static inline BOOL is_device_placeholder( int fd )
2881 static const char wine_placeholder[] = "Wine device placeholder";
2882 char buffer[sizeof(wine_placeholder)-1];
2884 if (pread( fd, buffer, sizeof(wine_placeholder) - 1, 0 ) != sizeof(wine_placeholder) - 1)
2885 return FALSE;
2886 return !memcmp( buffer, wine_placeholder, sizeof(wine_placeholder) - 1 );
2889 /******************************************************************************
2890 * get_device_info
2892 * Implementation of the FileFsDeviceInformation query for NtQueryVolumeInformationFile.
2894 static NTSTATUS get_device_info( int fd, FILE_FS_DEVICE_INFORMATION *info )
2896 struct stat st;
2898 info->Characteristics = 0;
2899 if (fstat( fd, &st ) < 0) return FILE_GetNtStatus();
2900 if (S_ISCHR( st.st_mode ))
2902 info->DeviceType = FILE_DEVICE_UNKNOWN;
2903 #ifdef linux
2904 switch(major(st.st_rdev))
2906 case MEM_MAJOR:
2907 info->DeviceType = FILE_DEVICE_NULL;
2908 break;
2909 case TTY_MAJOR:
2910 info->DeviceType = FILE_DEVICE_SERIAL_PORT;
2911 break;
2912 case LP_MAJOR:
2913 info->DeviceType = FILE_DEVICE_PARALLEL_PORT;
2914 break;
2915 case SCSI_TAPE_MAJOR:
2916 info->DeviceType = FILE_DEVICE_TAPE;
2917 break;
2919 #endif
2921 else if (S_ISBLK( st.st_mode ))
2923 info->DeviceType = FILE_DEVICE_DISK;
2925 else if (S_ISFIFO( st.st_mode ) || S_ISSOCK( st.st_mode ))
2927 info->DeviceType = FILE_DEVICE_NAMED_PIPE;
2929 else if (is_device_placeholder( fd ))
2931 info->DeviceType = FILE_DEVICE_DISK;
2933 else /* regular file or directory */
2935 #if defined(linux) && defined(HAVE_FSTATFS)
2936 struct statfs stfs;
2938 /* check for floppy disk */
2939 if (major(st.st_dev) == FLOPPY_MAJOR)
2940 info->Characteristics |= FILE_REMOVABLE_MEDIA;
2942 if (fstatfs( fd, &stfs ) < 0) stfs.f_type = 0;
2943 switch (stfs.f_type)
2945 case 0x9660: /* iso9660 */
2946 case 0x9fa1: /* supermount */
2947 case 0x15013346: /* udf */
2948 info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
2949 info->Characteristics |= FILE_REMOVABLE_MEDIA|FILE_READ_ONLY_DEVICE;
2950 break;
2951 case 0x6969: /* nfs */
2952 case 0x517B: /* smbfs */
2953 case 0x564c: /* ncpfs */
2954 info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
2955 info->Characteristics |= FILE_REMOTE_DEVICE;
2956 break;
2957 case 0x01021994: /* tmpfs */
2958 case 0x28cd3d45: /* cramfs */
2959 case 0x1373: /* devfs */
2960 case 0x9fa0: /* procfs */
2961 info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
2962 break;
2963 default:
2964 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2965 break;
2967 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
2968 struct statfs stfs;
2970 if (fstatfs( fd, &stfs ) < 0)
2971 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2972 else
2973 get_device_info_fstatfs( info, stfs.f_fstypename, stfs.f_flags );
2974 #elif defined(__NetBSD__)
2975 struct statvfs stfs;
2977 if (fstatvfs( fd, &stfs) < 0)
2978 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2979 else
2980 get_device_info_fstatfs( info, stfs.f_fstypename, stfs.f_flag );
2981 #elif defined(sun)
2982 /* Use dkio to work out device types */
2984 # include <sys/dkio.h>
2985 # include <sys/vtoc.h>
2986 struct dk_cinfo dkinf;
2987 int retval = ioctl(fd, DKIOCINFO, &dkinf);
2988 if(retval==-1){
2989 WARN("Unable to get disk device type information - assuming a disk like device\n");
2990 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2992 switch (dkinf.dki_ctype)
2994 case DKC_CDROM:
2995 info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
2996 info->Characteristics |= FILE_REMOVABLE_MEDIA|FILE_READ_ONLY_DEVICE;
2997 break;
2998 case DKC_NCRFLOPPY:
2999 case DKC_SMSFLOPPY:
3000 case DKC_INTEL82072:
3001 case DKC_INTEL82077:
3002 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
3003 info->Characteristics |= FILE_REMOVABLE_MEDIA;
3004 break;
3005 case DKC_MD:
3006 info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
3007 break;
3008 default:
3009 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
3012 #else
3013 static int warned;
3014 if (!warned++) FIXME( "device info not properly supported on this platform\n" );
3015 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
3016 #endif
3017 info->Characteristics |= FILE_DEVICE_IS_MOUNTED;
3019 return STATUS_SUCCESS;
3023 /******************************************************************************
3024 * NtQueryVolumeInformationFile [NTDLL.@]
3025 * ZwQueryVolumeInformationFile [NTDLL.@]
3027 * Get volume information for an open file handle.
3029 * PARAMS
3030 * handle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
3031 * io [O] Receives information about the operation on return
3032 * buffer [O] Destination for volume information
3033 * length [I] Size of FsInformation
3034 * info_class [I] Type of volume information to set
3036 * RETURNS
3037 * Success: 0. io and buffer are updated.
3038 * Failure: An NTSTATUS error code describing the error.
3040 NTSTATUS WINAPI NtQueryVolumeInformationFile( HANDLE handle, PIO_STATUS_BLOCK io,
3041 PVOID buffer, ULONG length,
3042 FS_INFORMATION_CLASS info_class )
3044 int fd, needs_close;
3045 struct stat st;
3046 static int once;
3048 if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
3049 return io->u.Status;
3051 io->u.Status = STATUS_NOT_IMPLEMENTED;
3052 io->Information = 0;
3054 switch( info_class )
3056 case FileFsVolumeInformation:
3057 if (!once++) FIXME( "%p: volume info not supported\n", handle );
3058 break;
3059 case FileFsLabelInformation:
3060 FIXME( "%p: label info not supported\n", handle );
3061 break;
3062 case FileFsSizeInformation:
3063 if (length < sizeof(FILE_FS_SIZE_INFORMATION))
3064 io->u.Status = STATUS_BUFFER_TOO_SMALL;
3065 else
3067 FILE_FS_SIZE_INFORMATION *info = buffer;
3069 if (fstat( fd, &st ) < 0)
3071 io->u.Status = FILE_GetNtStatus();
3072 break;
3074 if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
3076 io->u.Status = STATUS_INVALID_DEVICE_REQUEST;
3078 else
3080 ULONGLONG bsize;
3081 /* Linux's fstatvfs is buggy */
3082 #if !defined(linux) || !defined(HAVE_FSTATFS)
3083 struct statvfs stfs;
3085 if (fstatvfs( fd, &stfs ) < 0)
3087 io->u.Status = FILE_GetNtStatus();
3088 break;
3090 bsize = stfs.f_frsize;
3091 #else
3092 struct statfs stfs;
3093 if (fstatfs( fd, &stfs ) < 0)
3095 io->u.Status = FILE_GetNtStatus();
3096 break;
3098 bsize = stfs.f_bsize;
3099 #endif
3100 if (bsize == 2048) /* assume CD-ROM */
3102 info->BytesPerSector = 2048;
3103 info->SectorsPerAllocationUnit = 1;
3105 else
3107 info->BytesPerSector = 512;
3108 info->SectorsPerAllocationUnit = 8;
3110 info->TotalAllocationUnits.QuadPart = bsize * stfs.f_blocks / (info->BytesPerSector * info->SectorsPerAllocationUnit);
3111 info->AvailableAllocationUnits.QuadPart = bsize * stfs.f_bavail / (info->BytesPerSector * info->SectorsPerAllocationUnit);
3112 io->Information = sizeof(*info);
3113 io->u.Status = STATUS_SUCCESS;
3116 break;
3117 case FileFsDeviceInformation:
3118 if (length < sizeof(FILE_FS_DEVICE_INFORMATION))
3119 io->u.Status = STATUS_BUFFER_TOO_SMALL;
3120 else
3122 FILE_FS_DEVICE_INFORMATION *info = buffer;
3124 if ((io->u.Status = get_device_info( fd, info )) == STATUS_SUCCESS)
3125 io->Information = sizeof(*info);
3127 break;
3128 case FileFsAttributeInformation:
3129 if (length < offsetof( FILE_FS_ATTRIBUTE_INFORMATION, FileSystemName[sizeof(ntfsW)/sizeof(WCHAR)] ))
3130 io->u.Status = STATUS_BUFFER_TOO_SMALL;
3131 else
3133 FILE_FS_ATTRIBUTE_INFORMATION *info = buffer;
3135 FIXME( "%p: faking attribute info\n", handle );
3136 info->FileSystemAttribute = FILE_SUPPORTS_ENCRYPTION | FILE_FILE_COMPRESSION |
3137 FILE_PERSISTENT_ACLS | FILE_UNICODE_ON_DISK |
3138 FILE_CASE_PRESERVED_NAMES | FILE_CASE_SENSITIVE_SEARCH;
3139 info->MaximumComponentNameLength = MAXIMUM_FILENAME_LENGTH - 1;
3140 info->FileSystemNameLength = sizeof(ntfsW);
3141 memcpy(info->FileSystemName, ntfsW, sizeof(ntfsW));
3143 io->Information = sizeof(*info);
3144 io->u.Status = STATUS_SUCCESS;
3146 break;
3147 case FileFsControlInformation:
3148 FIXME( "%p: control info not supported\n", handle );
3149 break;
3150 case FileFsFullSizeInformation:
3151 FIXME( "%p: full size info not supported\n", handle );
3152 break;
3153 case FileFsObjectIdInformation:
3154 FIXME( "%p: object id info not supported\n", handle );
3155 break;
3156 case FileFsMaximumInformation:
3157 FIXME( "%p: maximum info not supported\n", handle );
3158 break;
3159 default:
3160 io->u.Status = STATUS_INVALID_PARAMETER;
3161 break;
3163 if (needs_close) close( fd );
3164 return io->u.Status;
3168 /******************************************************************
3169 * NtQueryEaFile (NTDLL.@)
3171 * Read extended attributes from NTFS files.
3173 * PARAMS
3174 * hFile [I] File handle, must be opened with FILE_READ_EA access
3175 * iosb [O] Receives information about the operation on return
3176 * buffer [O] Output buffer
3177 * length [I] Length of output buffer
3178 * single_entry [I] Only read and return one entry
3179 * ea_list [I] Optional list with names of EAs to return
3180 * ea_list_len [I] Length of ea_list in bytes
3181 * ea_index [I] Optional pointer to 1-based index of attribute to return
3182 * restart [I] restart EA scan
3184 * RETURNS
3185 * Success: 0. Atrributes read into buffer
3186 * Failure: An NTSTATUS error code describing the error.
3188 NTSTATUS WINAPI NtQueryEaFile( HANDLE hFile, PIO_STATUS_BLOCK iosb, PVOID buffer, ULONG length,
3189 BOOLEAN single_entry, PVOID ea_list, ULONG ea_list_len,
3190 PULONG ea_index, BOOLEAN restart )
3192 FIXME("(%p,%p,%p,%d,%d,%p,%d,%p,%d) stub\n",
3193 hFile, iosb, buffer, length, single_entry, ea_list,
3194 ea_list_len, ea_index, restart);
3195 return STATUS_ACCESS_DENIED;
3199 /******************************************************************
3200 * NtSetEaFile (NTDLL.@)
3202 * Update extended attributes for NTFS files.
3204 * PARAMS
3205 * hFile [I] File handle, must be opened with FILE_READ_EA access
3206 * iosb [O] Receives information about the operation on return
3207 * buffer [I] Buffer with EA information
3208 * length [I] Length of buffer
3210 * RETURNS
3211 * Success: 0. Attributes are updated
3212 * Failure: An NTSTATUS error code describing the error.
3214 NTSTATUS WINAPI NtSetEaFile( HANDLE hFile, PIO_STATUS_BLOCK iosb, PVOID buffer, ULONG length )
3216 FIXME("(%p,%p,%p,%d) stub\n", hFile, iosb, buffer, length);
3217 return STATUS_ACCESS_DENIED;
3221 /******************************************************************
3222 * NtFlushBuffersFile (NTDLL.@)
3224 * Flush any buffered data on an open file handle.
3226 * PARAMS
3227 * FileHandle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
3228 * IoStatusBlock [O] Receives information about the operation on return
3230 * RETURNS
3231 * Success: 0. IoStatusBlock is updated.
3232 * Failure: An NTSTATUS error code describing the error.
3234 NTSTATUS WINAPI NtFlushBuffersFile( HANDLE hFile, IO_STATUS_BLOCK* IoStatusBlock )
3236 NTSTATUS ret;
3237 HANDLE hEvent = NULL;
3238 enum server_fd_type type;
3239 int fd, needs_close;
3241 ret = server_get_unix_fd( hFile, FILE_WRITE_DATA, &fd, &needs_close, &type, NULL );
3243 if (!ret && type == FD_TYPE_SERIAL)
3245 ret = COMM_FlushBuffersFile( fd );
3247 else
3249 SERVER_START_REQ( flush )
3251 req->blocking = 1; /* always blocking */
3252 req->async.handle = wine_server_obj_handle( hFile );
3253 req->async.iosb = wine_server_client_ptr( IoStatusBlock );
3254 ret = wine_server_call( req );
3255 hEvent = wine_server_ptr_handle( reply->event );
3257 SERVER_END_REQ;
3259 if (hEvent)
3261 NtWaitForSingleObject( hEvent, FALSE, NULL );
3262 NtClose( hEvent );
3263 ret = STATUS_SUCCESS;
3267 if (needs_close) close( fd );
3268 return ret;
3271 /******************************************************************
3272 * NtLockFile (NTDLL.@)
3276 NTSTATUS WINAPI NtLockFile( HANDLE hFile, HANDLE lock_granted_event,
3277 PIO_APC_ROUTINE apc, void* apc_user,
3278 PIO_STATUS_BLOCK io_status, PLARGE_INTEGER offset,
3279 PLARGE_INTEGER count, ULONG* key, BOOLEAN dont_wait,
3280 BOOLEAN exclusive )
3282 NTSTATUS ret;
3283 HANDLE handle;
3284 BOOLEAN async;
3285 static BOOLEAN warn = TRUE;
3287 if (apc || io_status || key)
3289 FIXME("Unimplemented yet parameter\n");
3290 return STATUS_NOT_IMPLEMENTED;
3293 if (apc_user && warn)
3295 FIXME("I/O completion on lock not implemented yet\n");
3296 warn = FALSE;
3299 for (;;)
3301 SERVER_START_REQ( lock_file )
3303 req->handle = wine_server_obj_handle( hFile );
3304 req->offset = offset->QuadPart;
3305 req->count = count->QuadPart;
3306 req->shared = !exclusive;
3307 req->wait = !dont_wait;
3308 ret = wine_server_call( req );
3309 handle = wine_server_ptr_handle( reply->handle );
3310 async = reply->overlapped;
3312 SERVER_END_REQ;
3313 if (ret != STATUS_PENDING)
3315 if (!ret && lock_granted_event) NtSetEvent(lock_granted_event, NULL);
3316 return ret;
3319 if (async)
3321 FIXME( "Async I/O lock wait not implemented, might deadlock\n" );
3322 if (handle) NtClose( handle );
3323 return STATUS_PENDING;
3325 if (handle)
3327 NtWaitForSingleObject( handle, FALSE, NULL );
3328 NtClose( handle );
3330 else
3332 LARGE_INTEGER time;
3334 /* Unix lock conflict, sleep a bit and retry */
3335 time.QuadPart = 100 * (ULONGLONG)10000;
3336 time.QuadPart = -time.QuadPart;
3337 NtDelayExecution( FALSE, &time );
3343 /******************************************************************
3344 * NtUnlockFile (NTDLL.@)
3348 NTSTATUS WINAPI NtUnlockFile( HANDLE hFile, PIO_STATUS_BLOCK io_status,
3349 PLARGE_INTEGER offset, PLARGE_INTEGER count,
3350 PULONG key )
3352 NTSTATUS status;
3354 TRACE( "%p %x%08x %x%08x\n",
3355 hFile, offset->u.HighPart, offset->u.LowPart, count->u.HighPart, count->u.LowPart );
3357 if (io_status || key)
3359 FIXME("Unimplemented yet parameter\n");
3360 return STATUS_NOT_IMPLEMENTED;
3363 SERVER_START_REQ( unlock_file )
3365 req->handle = wine_server_obj_handle( hFile );
3366 req->offset = offset->QuadPart;
3367 req->count = count->QuadPart;
3368 status = wine_server_call( req );
3370 SERVER_END_REQ;
3371 return status;
3374 /******************************************************************
3375 * NtCreateNamedPipeFile (NTDLL.@)
3379 NTSTATUS WINAPI NtCreateNamedPipeFile( PHANDLE handle, ULONG access,
3380 POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK iosb,
3381 ULONG sharing, ULONG dispo, ULONG options,
3382 ULONG pipe_type, ULONG read_mode,
3383 ULONG completion_mode, ULONG max_inst,
3384 ULONG inbound_quota, ULONG outbound_quota,
3385 PLARGE_INTEGER timeout)
3387 struct security_descriptor *sd = NULL;
3388 struct object_attributes objattr;
3389 NTSTATUS status;
3391 TRACE("(%p %x %s %p %x %d %x %d %d %d %d %d %d %p)\n",
3392 handle, access, debugstr_w(attr->ObjectName->Buffer), iosb, sharing, dispo,
3393 options, pipe_type, read_mode, completion_mode, max_inst, inbound_quota,
3394 outbound_quota, timeout);
3396 /* assume we only get relative timeout */
3397 if (timeout->QuadPart > 0)
3398 FIXME("Wrong time %s\n", wine_dbgstr_longlong(timeout->QuadPart));
3400 objattr.rootdir = wine_server_obj_handle( attr->RootDirectory );
3401 objattr.sd_len = 0;
3402 objattr.name_len = attr->ObjectName->Length;
3404 status = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
3405 if (status != STATUS_SUCCESS) return status;
3407 SERVER_START_REQ( create_named_pipe )
3409 req->access = access;
3410 req->attributes = attr->Attributes;
3411 req->options = options;
3412 req->sharing = sharing;
3413 req->flags =
3414 (pipe_type ? NAMED_PIPE_MESSAGE_STREAM_WRITE : 0) |
3415 (read_mode ? NAMED_PIPE_MESSAGE_STREAM_READ : 0) |
3416 (completion_mode ? NAMED_PIPE_NONBLOCKING_MODE : 0);
3417 req->maxinstances = max_inst;
3418 req->outsize = outbound_quota;
3419 req->insize = inbound_quota;
3420 req->timeout = timeout->QuadPart;
3421 wine_server_add_data( req, &objattr, sizeof(objattr) );
3422 if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
3423 wine_server_add_data( req, attr->ObjectName->Buffer, attr->ObjectName->Length );
3424 status = wine_server_call( req );
3425 if (!status) *handle = wine_server_ptr_handle( reply->handle );
3427 SERVER_END_REQ;
3429 NTDLL_free_struct_sd( sd );
3430 return status;
3433 /******************************************************************
3434 * NtDeleteFile (NTDLL.@)
3438 NTSTATUS WINAPI NtDeleteFile( POBJECT_ATTRIBUTES ObjectAttributes )
3440 NTSTATUS status;
3441 HANDLE hFile;
3442 IO_STATUS_BLOCK io;
3444 TRACE("%p\n", ObjectAttributes);
3445 status = NtCreateFile( &hFile, GENERIC_READ | GENERIC_WRITE | DELETE,
3446 ObjectAttributes, &io, NULL, 0,
3447 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
3448 FILE_OPEN, FILE_DELETE_ON_CLOSE, NULL, 0 );
3449 if (status == STATUS_SUCCESS) status = NtClose(hFile);
3450 return status;
3453 /******************************************************************
3454 * NtCancelIoFileEx (NTDLL.@)
3458 NTSTATUS WINAPI NtCancelIoFileEx( HANDLE hFile, PIO_STATUS_BLOCK iosb, PIO_STATUS_BLOCK io_status )
3460 LARGE_INTEGER timeout;
3462 TRACE("%p %p %p\n", hFile, iosb, io_status );
3464 SERVER_START_REQ( cancel_async )
3466 req->handle = wine_server_obj_handle( hFile );
3467 req->iosb = wine_server_client_ptr( iosb );
3468 req->only_thread = FALSE;
3469 io_status->u.Status = wine_server_call( req );
3471 SERVER_END_REQ;
3472 if (io_status->u.Status)
3473 return io_status->u.Status;
3475 /* Let some APC be run, so that we can run the remaining APCs on hFile
3476 * either the cancelation of the pending one, but also the execution
3477 * of the queued APC, but not yet run. This is needed to ensure proper
3478 * clean-up of allocated data.
3480 timeout.QuadPart = 0;
3481 NtDelayExecution( TRUE, &timeout );
3482 return io_status->u.Status;
3485 /******************************************************************
3486 * NtCancelIoFile (NTDLL.@)
3490 NTSTATUS WINAPI NtCancelIoFile( HANDLE hFile, PIO_STATUS_BLOCK io_status )
3492 LARGE_INTEGER timeout;
3494 TRACE("%p %p\n", hFile, io_status );
3496 SERVER_START_REQ( cancel_async )
3498 req->handle = wine_server_obj_handle( hFile );
3499 req->iosb = 0;
3500 req->only_thread = TRUE;
3501 io_status->u.Status = wine_server_call( req );
3503 SERVER_END_REQ;
3504 if (io_status->u.Status)
3505 return io_status->u.Status;
3507 /* Let some APC be run, so that we can run the remaining APCs on hFile
3508 * either the cancelation of the pending one, but also the execution
3509 * of the queued APC, but not yet run. This is needed to ensure proper
3510 * clean-up of allocated data.
3512 timeout.QuadPart = 0;
3513 NtDelayExecution( TRUE, &timeout );
3514 return io_status->u.Status;
3517 /******************************************************************************
3518 * NtCreateMailslotFile [NTDLL.@]
3519 * ZwCreateMailslotFile [NTDLL.@]
3521 * PARAMS
3522 * pHandle [O] pointer to receive the handle created
3523 * DesiredAccess [I] access mode (read, write, etc)
3524 * ObjectAttributes [I] fully qualified NT path of the mailslot
3525 * IoStatusBlock [O] receives completion status and other info
3526 * CreateOptions [I]
3527 * MailslotQuota [I]
3528 * MaxMessageSize [I]
3529 * TimeOut [I]
3531 * RETURNS
3532 * An NT status code
3534 NTSTATUS WINAPI NtCreateMailslotFile(PHANDLE pHandle, ULONG DesiredAccess,
3535 POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK IoStatusBlock,
3536 ULONG CreateOptions, ULONG MailslotQuota, ULONG MaxMessageSize,
3537 PLARGE_INTEGER TimeOut)
3539 LARGE_INTEGER timeout;
3540 NTSTATUS ret;
3542 TRACE("%p %08x %p %p %08x %08x %08x %p\n",
3543 pHandle, DesiredAccess, attr, IoStatusBlock,
3544 CreateOptions, MailslotQuota, MaxMessageSize, TimeOut);
3546 if (!pHandle) return STATUS_ACCESS_VIOLATION;
3547 if (!attr) return STATUS_INVALID_PARAMETER;
3548 if (!attr->ObjectName) return STATUS_OBJECT_PATH_SYNTAX_BAD;
3551 * For a NULL TimeOut pointer set the default timeout value
3553 if (!TimeOut)
3554 timeout.QuadPart = -1;
3555 else
3556 timeout.QuadPart = TimeOut->QuadPart;
3558 SERVER_START_REQ( create_mailslot )
3560 req->access = DesiredAccess;
3561 req->attributes = attr->Attributes;
3562 req->rootdir = wine_server_obj_handle( attr->RootDirectory );
3563 req->max_msgsize = MaxMessageSize;
3564 req->read_timeout = timeout.QuadPart;
3565 wine_server_add_data( req, attr->ObjectName->Buffer,
3566 attr->ObjectName->Length );
3567 ret = wine_server_call( req );
3568 if( ret == STATUS_SUCCESS )
3569 *pHandle = wine_server_ptr_handle( reply->handle );
3571 SERVER_END_REQ;
3573 return ret;