oleaut32: Use a saner calling convention for the marshaller asm thunks.
[wine] / dlls / ntdll / file.c
1 /*
2  * Copyright 1999, 2000 Juergen Schmied
3  *
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.
8  *
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.
13  *
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
17  */
18
19 #include "config.h"
20 #include "wine/port.h"
21
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_TIME_H
40 # include <sys/time.h>
41 #endif
42 #ifdef HAVE_SYS_IOCTL_H
43 #include <sys/ioctl.h>
44 #endif
45 #ifdef HAVE_SYS_FILIO_H
46 # include <sys/filio.h>
47 #endif
48 #ifdef HAVE_POLL_H
49 #include <poll.h>
50 #endif
51 #ifdef HAVE_SYS_POLL_H
52 #include <sys/poll.h>
53 #endif
54 #ifdef HAVE_SYS_SOCKET_H
55 #include <sys/socket.h>
56 #endif
57 #ifdef HAVE_UTIME_H
58 # include <utime.h>
59 #endif
60 #ifdef HAVE_SYS_VFS_H
61 # include <sys/vfs.h>
62 #endif
63 #ifdef HAVE_SYS_MOUNT_H
64 # include <sys/mount.h>
65 #endif
66 #ifdef HAVE_SYS_STATFS_H
67 # include <sys/statfs.h>
68 #endif
69 #ifdef HAVE_VALGRIND_MEMCHECK_H
70 # include <valgrind/memcheck.h>
71 #endif
72
73 #define NONAMELESSUNION
74 #define NONAMELESSSTRUCT
75 #include "ntstatus.h"
76 #define WIN32_NO_STATUS
77 #include "wine/unicode.h"
78 #include "wine/debug.h"
79 #include "wine/server.h"
80 #include "ntdll_misc.h"
81
82 #include "winternl.h"
83 #include "winioctl.h"
84 #include "ddk/ntddk.h"
85 #include "ddk/ntddser.h"
86
87 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
88 WINE_DECLARE_DEBUG_CHANNEL(winediag);
89
90 mode_t FILE_umask = 0;
91
92 #define SECSPERDAY         86400
93 #define SECS_1601_TO_1970  ((369 * 365 + 89) * (ULONGLONG)SECSPERDAY)
94
95
96 /**************************************************************************
97  *                 FILE_CreateFile                    (internal)
98  * Open a file.
99  *
100  * Parameter set fully identical with NtCreateFile
101  */
102 static NTSTATUS FILE_CreateFile( PHANDLE handle, ACCESS_MASK access, POBJECT_ATTRIBUTES attr,
103                                  PIO_STATUS_BLOCK io, PLARGE_INTEGER alloc_size,
104                                  ULONG attributes, ULONG sharing, ULONG disposition,
105                                  ULONG options, PVOID ea_buffer, ULONG ea_length )
106 {
107     ANSI_STRING unix_name;
108     int created = FALSE;
109
110     TRACE("handle=%p access=%08x name=%s objattr=%08x root=%p sec=%p io=%p alloc_size=%p "
111           "attr=%08x sharing=%08x disp=%d options=%08x ea=%p.0x%08x\n",
112           handle, access, debugstr_us(attr->ObjectName), attr->Attributes,
113           attr->RootDirectory, attr->SecurityDescriptor, io, alloc_size,
114           attributes, sharing, disposition, options, ea_buffer, ea_length );
115
116     if (!attr || !attr->ObjectName) return STATUS_INVALID_PARAMETER;
117
118     if (alloc_size) FIXME( "alloc_size not supported\n" );
119
120     if (options & FILE_OPEN_BY_FILE_ID)
121         io->u.Status = file_id_to_unix_file_name( attr, &unix_name );
122     else
123         io->u.Status = nt_to_unix_file_name_attr( attr, &unix_name, disposition );
124
125     if (io->u.Status == STATUS_BAD_DEVICE_TYPE)
126     {
127         SERVER_START_REQ( open_file_object )
128         {
129             req->access     = access;
130             req->attributes = attr->Attributes;
131             req->rootdir    = wine_server_obj_handle( attr->RootDirectory );
132             req->sharing    = sharing;
133             req->options    = options;
134             wine_server_add_data( req, attr->ObjectName->Buffer, attr->ObjectName->Length );
135             io->u.Status = wine_server_call( req );
136             *handle = wine_server_ptr_handle( reply->handle );
137         }
138         SERVER_END_REQ;
139         if (io->u.Status == STATUS_SUCCESS) io->Information = FILE_OPENED;
140         return io->u.Status;
141     }
142
143     if (io->u.Status == STATUS_NO_SUCH_FILE &&
144         disposition != FILE_OPEN && disposition != FILE_OVERWRITE)
145     {
146         created = TRUE;
147         io->u.Status = STATUS_SUCCESS;
148     }
149
150     if (io->u.Status == STATUS_SUCCESS)
151     {
152         struct security_descriptor *sd;
153         struct object_attributes objattr;
154
155         objattr.rootdir = wine_server_obj_handle( attr->RootDirectory );
156         objattr.name_len = 0;
157         io->u.Status = NTDLL_create_struct_sd( attr->SecurityDescriptor, &sd, &objattr.sd_len );
158         if (io->u.Status != STATUS_SUCCESS)
159         {
160             RtlFreeAnsiString( &unix_name );
161             return io->u.Status;
162         }
163
164         SERVER_START_REQ( create_file )
165         {
166             req->access     = access;
167             req->attributes = attr->Attributes;
168             req->sharing    = sharing;
169             req->create     = disposition;
170             req->options    = options;
171             req->attrs      = attributes;
172             wine_server_add_data( req, &objattr, sizeof(objattr) );
173             if (objattr.sd_len) wine_server_add_data( req, sd, objattr.sd_len );
174             wine_server_add_data( req, unix_name.Buffer, unix_name.Length );
175             io->u.Status = wine_server_call( req );
176             *handle = wine_server_ptr_handle( reply->handle );
177         }
178         SERVER_END_REQ;
179         NTDLL_free_struct_sd( sd );
180         RtlFreeAnsiString( &unix_name );
181     }
182     else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), io->u.Status );
183
184     if (io->u.Status == STATUS_SUCCESS)
185     {
186         if (created) io->Information = FILE_CREATED;
187         else switch(disposition)
188         {
189         case FILE_SUPERSEDE:
190             io->Information = FILE_SUPERSEDED;
191             break;
192         case FILE_CREATE:
193             io->Information = FILE_CREATED;
194             break;
195         case FILE_OPEN:
196         case FILE_OPEN_IF:
197             io->Information = FILE_OPENED;
198             break;
199         case FILE_OVERWRITE:
200         case FILE_OVERWRITE_IF:
201             io->Information = FILE_OVERWRITTEN;
202             break;
203         }
204     }
205     else if (io->u.Status == STATUS_TOO_MANY_OPENED_FILES)
206     {
207         static int once;
208         if (!once++) ERR_(winediag)( "Too many open files, ulimit -n probably needs to be increased\n" );
209     }
210
211     return io->u.Status;
212 }
213
214 /**************************************************************************
215  *                 NtOpenFile                           [NTDLL.@]
216  *                 ZwOpenFile                           [NTDLL.@]
217  *
218  * Open a file.
219  *
220  * PARAMS
221  *  handle    [O] Variable that receives the file handle on return
222  *  access    [I] Access desired by the caller to the file
223  *  attr      [I] Structure describing the file to be opened
224  *  io        [O] Receives details about the result of the operation
225  *  sharing   [I] Type of shared access the caller requires
226  *  options   [I] Options for the file open
227  *
228  * RETURNS
229  *  Success: 0. FileHandle and IoStatusBlock are updated.
230  *  Failure: An NTSTATUS error code describing the error.
231  */
232 NTSTATUS WINAPI NtOpenFile( PHANDLE handle, ACCESS_MASK access,
233                             POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK io,
234                             ULONG sharing, ULONG options )
235 {
236     return FILE_CreateFile( handle, access, attr, io, NULL, 0,
237                             sharing, FILE_OPEN, options, NULL, 0 );
238 }
239
240 /**************************************************************************
241  *              NtCreateFile                            [NTDLL.@]
242  *              ZwCreateFile                            [NTDLL.@]
243  *
244  * Either create a new file or directory, or open an existing file, device,
245  * directory or volume.
246  *
247  * PARAMS
248  *      handle       [O] Points to a variable which receives the file handle on return
249  *      access       [I] Desired access to the file
250  *      attr         [I] Structure describing the file
251  *      io           [O] Receives information about the operation on return
252  *      alloc_size   [I] Initial size of the file in bytes
253  *      attributes   [I] Attributes to create the file with
254  *      sharing      [I] Type of shared access the caller would like to the file
255  *      disposition  [I] Specifies what to do, depending on whether the file already exists
256  *      options      [I] Options for creating a new file
257  *      ea_buffer    [I] Pointer to an extended attributes buffer
258  *      ea_length    [I] Length of ea_buffer
259  *
260  * RETURNS
261  *  Success: 0. handle and io are updated.
262  *  Failure: An NTSTATUS error code describing the error.
263  */
264 NTSTATUS WINAPI NtCreateFile( PHANDLE handle, ACCESS_MASK access, POBJECT_ATTRIBUTES attr,
265                               PIO_STATUS_BLOCK io, PLARGE_INTEGER alloc_size,
266                               ULONG attributes, ULONG sharing, ULONG disposition,
267                               ULONG options, PVOID ea_buffer, ULONG ea_length )
268 {
269     return FILE_CreateFile( handle, access, attr, io, alloc_size, attributes,
270                             sharing, disposition, options, ea_buffer, ea_length );
271 }
272
273 /***********************************************************************
274  *                  Asynchronous file I/O                              *
275  */
276
277 struct async_fileio
278 {
279     HANDLE              handle;
280     PIO_APC_ROUTINE     apc;
281     void               *apc_arg;
282 };
283
284 typedef struct
285 {
286     struct async_fileio io;
287     char*               buffer;
288     unsigned int        already;
289     unsigned int        count;
290     BOOL                avail_mode;
291 } async_fileio_read;
292
293 typedef struct
294 {
295     struct async_fileio io;
296     const char         *buffer;
297     unsigned int        already;
298     unsigned int        count;
299 } async_fileio_write;
300
301
302 /* callback for file I/O user APC */
303 static void WINAPI fileio_apc( void *arg, IO_STATUS_BLOCK *io, ULONG reserved )
304 {
305     struct async_fileio *async = arg;
306     if (async->apc) async->apc( async->apc_arg, io, reserved );
307     RtlFreeHeap( GetProcessHeap(), 0, async );
308 }
309
310 /***********************************************************************
311  *           FILE_GetNtStatus(void)
312  *
313  * Retrieve the Nt Status code from errno.
314  * Try to be consistent with FILE_SetDosError().
315  */
316 NTSTATUS FILE_GetNtStatus(void)
317 {
318     int err = errno;
319
320     TRACE( "errno = %d\n", errno );
321     switch (err)
322     {
323     case EAGAIN:    return STATUS_SHARING_VIOLATION;
324     case EBADF:     return STATUS_INVALID_HANDLE;
325     case EBUSY:     return STATUS_DEVICE_BUSY;
326     case ENOSPC:    return STATUS_DISK_FULL;
327     case EPERM:
328     case EROFS:
329     case EACCES:    return STATUS_ACCESS_DENIED;
330     case ENOTDIR:   return STATUS_OBJECT_PATH_NOT_FOUND;
331     case ENOENT:    return STATUS_OBJECT_NAME_NOT_FOUND;
332     case EISDIR:    return STATUS_FILE_IS_A_DIRECTORY;
333     case EMFILE:
334     case ENFILE:    return STATUS_TOO_MANY_OPENED_FILES;
335     case EINVAL:    return STATUS_INVALID_PARAMETER;
336     case ENOTEMPTY: return STATUS_DIRECTORY_NOT_EMPTY;
337     case EPIPE:     return STATUS_PIPE_DISCONNECTED;
338     case EIO:       return STATUS_DEVICE_NOT_READY;
339 #ifdef ENOMEDIUM
340     case ENOMEDIUM: return STATUS_NO_MEDIA_IN_DEVICE;
341 #endif
342     case ENXIO:     return STATUS_NO_SUCH_DEVICE;
343     case ENOTTY:
344     case EOPNOTSUPP:return STATUS_NOT_SUPPORTED;
345     case ECONNRESET:return STATUS_PIPE_DISCONNECTED;
346     case EFAULT:    return STATUS_ACCESS_VIOLATION;
347     case ESPIPE:    return STATUS_ILLEGAL_FUNCTION;
348 #ifdef ETIME /* Missing on FreeBSD */
349     case ETIME:     return STATUS_IO_TIMEOUT;
350 #endif
351     case ENOEXEC:   /* ?? */
352     case EEXIST:    /* ?? */
353     default:
354         FIXME( "Converting errno %d to STATUS_UNSUCCESSFUL\n", err );
355         return STATUS_UNSUCCESSFUL;
356     }
357 }
358
359 /***********************************************************************
360  *             FILE_AsyncReadService      (INTERNAL)
361  */
362 static NTSTATUS FILE_AsyncReadService(void *user, PIO_STATUS_BLOCK iosb, NTSTATUS status, void **apc)
363 {
364     async_fileio_read *fileio = user;
365     int fd, needs_close, result;
366
367     switch (status)
368     {
369     case STATUS_ALERTED: /* got some new data */
370         /* check to see if the data is ready (non-blocking) */
371         if ((status = server_get_unix_fd( fileio->io.handle, FILE_READ_DATA, &fd,
372                                           &needs_close, NULL, NULL )))
373             break;
374
375         result = read(fd, &fileio->buffer[fileio->already], fileio->count - fileio->already);
376         if (needs_close) close( fd );
377
378         if (result < 0)
379         {
380             if (errno == EAGAIN || errno == EINTR)
381                 status = STATUS_PENDING;
382             else /* check to see if the transfer is complete */
383                 status = FILE_GetNtStatus();
384         }
385         else if (result == 0)
386         {
387             status = fileio->already ? STATUS_SUCCESS : STATUS_PIPE_BROKEN;
388         }
389         else
390         {
391             fileio->already += result;
392             if (fileio->already >= fileio->count || fileio->avail_mode)
393                 status = STATUS_SUCCESS;
394             else
395             {
396                 /* if we only have to read the available data, and none is available,
397                  * simply cancel the request. If data was available, it has been read
398                  * while in by previous call (NtDelayExecution)
399                  */
400                 status = (fileio->avail_mode) ? STATUS_SUCCESS : STATUS_PENDING;
401             }
402         }
403         break;
404
405     case STATUS_TIMEOUT:
406     case STATUS_IO_TIMEOUT:
407         if (fileio->already) status = STATUS_SUCCESS;
408         break;
409     }
410     if (status != STATUS_PENDING)
411     {
412         iosb->u.Status = status;
413         iosb->Information = fileio->already;
414         *apc = fileio_apc;
415     }
416     return status;
417 }
418
419 struct io_timeouts
420 {
421     int interval;   /* max interval between two bytes */
422     int total;      /* total timeout for the whole operation */
423     int end_time;   /* absolute time of end of operation */
424 };
425
426 /* retrieve the I/O timeouts to use for a given handle */
427 static NTSTATUS get_io_timeouts( HANDLE handle, enum server_fd_type type, ULONG count, BOOL is_read,
428                                  struct io_timeouts *timeouts )
429 {
430     NTSTATUS status = STATUS_SUCCESS;
431
432     timeouts->interval = timeouts->total = -1;
433
434     switch(type)
435     {
436     case FD_TYPE_SERIAL:
437         {
438             /* GetCommTimeouts */
439             SERIAL_TIMEOUTS st;
440             IO_STATUS_BLOCK io;
441
442             status = NtDeviceIoControlFile( handle, NULL, NULL, NULL, &io,
443                                             IOCTL_SERIAL_GET_TIMEOUTS, NULL, 0, &st, sizeof(st) );
444             if (status) break;
445
446             if (is_read)
447             {
448                 if (st.ReadIntervalTimeout)
449                     timeouts->interval = st.ReadIntervalTimeout;
450
451                 if (st.ReadTotalTimeoutMultiplier || st.ReadTotalTimeoutConstant)
452                 {
453                     timeouts->total = st.ReadTotalTimeoutConstant;
454                     if (st.ReadTotalTimeoutMultiplier != MAXDWORD)
455                         timeouts->total += count * st.ReadTotalTimeoutMultiplier;
456                 }
457                 else if (st.ReadIntervalTimeout == MAXDWORD)
458                     timeouts->interval = timeouts->total = 0;
459             }
460             else  /* write */
461             {
462                 if (st.WriteTotalTimeoutMultiplier || st.WriteTotalTimeoutConstant)
463                 {
464                     timeouts->total = st.WriteTotalTimeoutConstant;
465                     if (st.WriteTotalTimeoutMultiplier != MAXDWORD)
466                         timeouts->total += count * st.WriteTotalTimeoutMultiplier;
467                 }
468             }
469         }
470         break;
471     case FD_TYPE_MAILSLOT:
472         if (is_read)
473         {
474             timeouts->interval = 0;  /* return as soon as we got something */
475             SERVER_START_REQ( set_mailslot_info )
476             {
477                 req->handle = wine_server_obj_handle( handle );
478                 req->flags = 0;
479                 if (!(status = wine_server_call( req )) &&
480                     reply->read_timeout != TIMEOUT_INFINITE)
481                     timeouts->total = reply->read_timeout / -10000;
482             }
483             SERVER_END_REQ;
484         }
485         break;
486     case FD_TYPE_SOCKET:
487     case FD_TYPE_PIPE:
488     case FD_TYPE_CHAR:
489         if (is_read) timeouts->interval = 0;  /* return as soon as we got something */
490         break;
491     default:
492         break;
493     }
494     if (timeouts->total != -1) timeouts->end_time = NtGetTickCount() + timeouts->total;
495     return STATUS_SUCCESS;
496 }
497
498
499 /* retrieve the timeout for the next wait, in milliseconds */
500 static inline int get_next_io_timeout( const struct io_timeouts *timeouts, ULONG already )
501 {
502     int ret = -1;
503
504     if (timeouts->total != -1)
505     {
506         ret = timeouts->end_time - NtGetTickCount();
507         if (ret < 0) ret = 0;
508     }
509     if (already && timeouts->interval != -1)
510     {
511         if (ret == -1 || ret > timeouts->interval) ret = timeouts->interval;
512     }
513     return ret;
514 }
515
516
517 /* retrieve the avail_mode flag for async reads */
518 static NTSTATUS get_io_avail_mode( HANDLE handle, enum server_fd_type type, BOOL *avail_mode )
519 {
520     NTSTATUS status = STATUS_SUCCESS;
521
522     switch(type)
523     {
524     case FD_TYPE_SERIAL:
525         {
526             /* GetCommTimeouts */
527             SERIAL_TIMEOUTS st;
528             IO_STATUS_BLOCK io;
529
530             status = NtDeviceIoControlFile( handle, NULL, NULL, NULL, &io,
531                                             IOCTL_SERIAL_GET_TIMEOUTS, NULL, 0, &st, sizeof(st) );
532             if (status) break;
533             *avail_mode = (!st.ReadTotalTimeoutMultiplier &&
534                            !st.ReadTotalTimeoutConstant &&
535                            st.ReadIntervalTimeout == MAXDWORD);
536         }
537         break;
538     case FD_TYPE_MAILSLOT:
539     case FD_TYPE_SOCKET:
540     case FD_TYPE_PIPE:
541     case FD_TYPE_CHAR:
542         *avail_mode = TRUE;
543         break;
544     default:
545         *avail_mode = FALSE;
546         break;
547     }
548     return status;
549 }
550
551
552 /******************************************************************************
553  *  NtReadFile                                  [NTDLL.@]
554  *  ZwReadFile                                  [NTDLL.@]
555  *
556  * Read from an open file handle.
557  *
558  * PARAMS
559  *  FileHandle    [I] Handle returned from ZwOpenFile() or ZwCreateFile()
560  *  Event         [I] Event to signal upon completion (or NULL)
561  *  ApcRoutine    [I] Callback to call upon completion (or NULL)
562  *  ApcContext    [I] Context for ApcRoutine (or NULL)
563  *  IoStatusBlock [O] Receives information about the operation on return
564  *  Buffer        [O] Destination for the data read
565  *  Length        [I] Size of Buffer
566  *  ByteOffset    [O] Destination for the new file pointer position (or NULL)
567  *  Key           [O] Function unknown (may be NULL)
568  *
569  * RETURNS
570  *  Success: 0. IoStatusBlock is updated, and the Information member contains
571  *           The number of bytes read.
572  *  Failure: An NTSTATUS error code describing the error.
573  */
574 NTSTATUS WINAPI NtReadFile(HANDLE hFile, HANDLE hEvent,
575                            PIO_APC_ROUTINE apc, void* apc_user,
576                            PIO_STATUS_BLOCK io_status, void* buffer, ULONG length,
577                            PLARGE_INTEGER offset, PULONG key)
578 {
579     int result, unix_handle, needs_close, timeout_init_done = 0;
580     unsigned int options;
581     struct io_timeouts timeouts;
582     NTSTATUS status;
583     ULONG total = 0;
584     enum server_fd_type type;
585     ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
586     BOOL send_completion = FALSE;
587
588     TRACE("(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p),partial stub!\n",
589           hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);
590
591     if (!io_status) return STATUS_ACCESS_VIOLATION;
592
593     status = server_get_unix_fd( hFile, FILE_READ_DATA, &unix_handle,
594                                  &needs_close, &type, &options );
595     if (status) return status;
596
597     if (!virtual_check_buffer_for_write( buffer, length ))
598     {
599         status = STATUS_ACCESS_VIOLATION;
600         goto done;
601     }
602
603     if (type == FD_TYPE_FILE && offset && offset->QuadPart != (LONGLONG)-2 /* FILE_USE_FILE_POINTER_POSITION */ )
604     {
605         /* async I/O doesn't make sense on regular files */
606         while ((result = pread( unix_handle, buffer, length, offset->QuadPart )) == -1)
607         {
608             if (errno != EINTR)
609             {
610                 status = FILE_GetNtStatus();
611                 goto done;
612             }
613         }
614         if (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT))
615             /* update file pointer position */
616             lseek( unix_handle, offset->QuadPart + result, SEEK_SET );
617
618         total = result;
619         status = total ? STATUS_SUCCESS : STATUS_END_OF_FILE;
620         goto done;
621     }
622
623     for (;;)
624     {
625         if ((result = read( unix_handle, (char *)buffer + total, length - total )) >= 0)
626         {
627             total += result;
628             if (!result || total == length)
629             {
630                 if (total)
631                 {
632                     status = STATUS_SUCCESS;
633                     goto done;
634                 }
635                 switch (type)
636                 {
637                 case FD_TYPE_FILE:
638                 case FD_TYPE_CHAR:
639                     status = STATUS_END_OF_FILE;
640                     goto done;
641                 case FD_TYPE_SERIAL:
642                     break;
643                 default:
644                     status = STATUS_PIPE_BROKEN;
645                     goto done;
646                 }
647             }
648             else if (type == FD_TYPE_FILE) continue;  /* no async I/O on regular files */
649         }
650         else if (errno != EAGAIN)
651         {
652             if (errno == EINTR) continue;
653             if (!total) status = FILE_GetNtStatus();
654             goto done;
655         }
656
657         if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
658         {
659             async_fileio_read *fileio;
660             BOOL avail_mode;
661
662             if ((status = get_io_avail_mode( hFile, type, &avail_mode )))
663                 goto err;
664             if (total && avail_mode)
665             {
666                 status = STATUS_SUCCESS;
667                 goto done;
668             }
669
670             if (!(fileio = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(*fileio))))
671             {
672                 status = STATUS_NO_MEMORY;
673                 goto err;
674             }
675             fileio->io.handle  = hFile;
676             fileio->io.apc     = apc;
677             fileio->io.apc_arg = apc_user;
678             fileio->already = total;
679             fileio->count = length;
680             fileio->buffer = buffer;
681             fileio->avail_mode = avail_mode;
682
683             SERVER_START_REQ( register_async )
684             {
685                 req->type   = ASYNC_TYPE_READ;
686                 req->count  = length;
687                 req->async.handle   = wine_server_obj_handle( hFile );
688                 req->async.event    = wine_server_obj_handle( hEvent );
689                 req->async.callback = wine_server_client_ptr( FILE_AsyncReadService );
690                 req->async.iosb     = wine_server_client_ptr( io_status );
691                 req->async.arg      = wine_server_client_ptr( fileio );
692                 req->async.cvalue   = cvalue;
693                 status = wine_server_call( req );
694             }
695             SERVER_END_REQ;
696
697             if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
698             goto err;
699         }
700         else  /* synchronous read, wait for the fd to become ready */
701         {
702             struct pollfd pfd;
703             int ret, timeout;
704
705             if (!timeout_init_done)
706             {
707                 timeout_init_done = 1;
708                 if ((status = get_io_timeouts( hFile, type, length, TRUE, &timeouts )))
709                     goto err;
710                 if (hEvent) NtResetEvent( hEvent, NULL );
711             }
712             timeout = get_next_io_timeout( &timeouts, total );
713
714             pfd.fd = unix_handle;
715             pfd.events = POLLIN;
716
717             if (!timeout || !(ret = poll( &pfd, 1, timeout )))
718             {
719                 if (total)  /* return with what we got so far */
720                     status = STATUS_SUCCESS;
721                 else
722                     status = (type == FD_TYPE_MAILSLOT) ? STATUS_IO_TIMEOUT : STATUS_TIMEOUT;
723                 goto done;
724             }
725             if (ret == -1 && errno != EINTR)
726             {
727                 status = FILE_GetNtStatus();
728                 goto done;
729             }
730             /* will now restart the read */
731         }
732     }
733
734 done:
735     send_completion = cvalue != 0;
736
737 err:
738     if (needs_close) close( unix_handle );
739     if (status == STATUS_SUCCESS)
740     {
741         io_status->u.Status = status;
742         io_status->Information = total;
743         TRACE("= SUCCESS (%u)\n", total);
744         if (hEvent) NtSetEvent( hEvent, NULL );
745         if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
746                                    (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
747     }
748     else
749     {
750         TRACE("= 0x%08x\n", status);
751         if (status != STATUS_PENDING && hEvent) NtResetEvent( hEvent, NULL );
752     }
753
754     if (send_completion) NTDLL_AddCompletion( hFile, cvalue, status, total );
755
756     return status;
757 }
758
759
760 /******************************************************************************
761  *  NtReadFileScatter   [NTDLL.@]
762  *  ZwReadFileScatter   [NTDLL.@]
763  */
764 NTSTATUS WINAPI NtReadFileScatter( HANDLE file, HANDLE event, PIO_APC_ROUTINE apc, void *apc_user,
765                                    PIO_STATUS_BLOCK io_status, FILE_SEGMENT_ELEMENT *segments,
766                                    ULONG length, PLARGE_INTEGER offset, PULONG key )
767 {
768     size_t page_size = getpagesize();
769     int result, unix_handle, needs_close;
770     unsigned int options;
771     NTSTATUS status;
772     ULONG pos = 0, total = 0;
773     enum server_fd_type type;
774     ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
775     BOOL send_completion = FALSE;
776
777     TRACE( "(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p),partial stub!\n",
778            file, event, apc, apc_user, io_status, segments, length, offset, key);
779
780     if (length % page_size) return STATUS_INVALID_PARAMETER;
781     if (!io_status) return STATUS_ACCESS_VIOLATION;
782
783     status = server_get_unix_fd( file, FILE_READ_DATA, &unix_handle,
784                                  &needs_close, &type, &options );
785     if (status) return status;
786
787     if ((type != FD_TYPE_FILE) ||
788         (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)) ||
789         !(options & FILE_NO_INTERMEDIATE_BUFFERING))
790     {
791         status = STATUS_INVALID_PARAMETER;
792         goto error;
793     }
794
795     while (length)
796     {
797         if (offset && offset->QuadPart != (LONGLONG)-2 /* FILE_USE_FILE_POINTER_POSITION */)
798             result = pread( unix_handle, (char *)segments->Buffer + pos,
799                             page_size - pos, offset->QuadPart + total );
800         else
801             result = read( unix_handle, (char *)segments->Buffer + pos, page_size - pos );
802
803         if (result == -1)
804         {
805             if (errno == EINTR) continue;
806             status = FILE_GetNtStatus();
807             break;
808         }
809         if (!result)
810         {
811             status = STATUS_END_OF_FILE;
812             break;
813         }
814         total += result;
815         length -= result;
816         if ((pos += result) == page_size)
817         {
818             pos = 0;
819             segments++;
820         }
821     }
822
823     send_completion = cvalue != 0;
824
825  error:
826     if (needs_close) close( unix_handle );
827     if (status == STATUS_SUCCESS)
828     {
829         io_status->u.Status = status;
830         io_status->Information = total;
831         TRACE("= SUCCESS (%u)\n", total);
832         if (event) NtSetEvent( event, NULL );
833         if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
834                                    (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
835     }
836     else
837     {
838         TRACE("= 0x%08x\n", status);
839         if (status != STATUS_PENDING && event) NtResetEvent( event, NULL );
840     }
841
842     if (send_completion) NTDLL_AddCompletion( file, cvalue, status, total );
843
844     return status;
845 }
846
847
848 /***********************************************************************
849  *             FILE_AsyncWriteService      (INTERNAL)
850  */
851 static NTSTATUS FILE_AsyncWriteService(void *user, IO_STATUS_BLOCK *iosb, NTSTATUS status, void **apc)
852 {
853     async_fileio_write *fileio = user;
854     int result, fd, needs_close;
855     enum server_fd_type type;
856
857     switch (status)
858     {
859     case STATUS_ALERTED:
860         /* write some data (non-blocking) */
861         if ((status = server_get_unix_fd( fileio->io.handle, FILE_WRITE_DATA, &fd,
862                                           &needs_close, &type, NULL )))
863             break;
864
865         if (!fileio->count && (type == FD_TYPE_MAILSLOT || type == FD_TYPE_PIPE || type == FD_TYPE_SOCKET))
866             result = send( fd, fileio->buffer, 0, 0 );
867         else
868             result = write( fd, &fileio->buffer[fileio->already], fileio->count - fileio->already );
869
870         if (needs_close) close( fd );
871
872         if (result < 0)
873         {
874             if (errno == EAGAIN || errno == EINTR) status = STATUS_PENDING;
875             else status = FILE_GetNtStatus();
876         }
877         else
878         {
879             fileio->already += result;
880             status = (fileio->already < fileio->count) ? STATUS_PENDING : STATUS_SUCCESS;
881         }
882         break;
883
884     case STATUS_TIMEOUT:
885     case STATUS_IO_TIMEOUT:
886         if (fileio->already) status = STATUS_SUCCESS;
887         break;
888     }
889     if (status != STATUS_PENDING)
890     {
891         iosb->u.Status = status;
892         iosb->Information = fileio->already;
893         *apc = fileio_apc;
894     }
895     return status;
896 }
897
898 /******************************************************************************
899  *  NtWriteFile                                 [NTDLL.@]
900  *  ZwWriteFile                                 [NTDLL.@]
901  *
902  * Write to an open file handle.
903  *
904  * PARAMS
905  *  FileHandle    [I] Handle returned from ZwOpenFile() or ZwCreateFile()
906  *  Event         [I] Event to signal upon completion (or NULL)
907  *  ApcRoutine    [I] Callback to call upon completion (or NULL)
908  *  ApcContext    [I] Context for ApcRoutine (or NULL)
909  *  IoStatusBlock [O] Receives information about the operation on return
910  *  Buffer        [I] Source for the data to write
911  *  Length        [I] Size of Buffer
912  *  ByteOffset    [O] Destination for the new file pointer position (or NULL)
913  *  Key           [O] Function unknown (may be NULL)
914  *
915  * RETURNS
916  *  Success: 0. IoStatusBlock is updated, and the Information member contains
917  *           The number of bytes written.
918  *  Failure: An NTSTATUS error code describing the error.
919  */
920 NTSTATUS WINAPI NtWriteFile(HANDLE hFile, HANDLE hEvent,
921                             PIO_APC_ROUTINE apc, void* apc_user,
922                             PIO_STATUS_BLOCK io_status, 
923                             const void* buffer, ULONG length,
924                             PLARGE_INTEGER offset, PULONG key)
925 {
926     int result, unix_handle, needs_close, timeout_init_done = 0;
927     unsigned int options;
928     struct io_timeouts timeouts;
929     NTSTATUS status;
930     ULONG total = 0;
931     enum server_fd_type type;
932     ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
933     BOOL send_completion = FALSE;
934
935     TRACE("(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p)!\n",
936           hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);
937
938     if (!io_status) return STATUS_ACCESS_VIOLATION;
939
940     status = server_get_unix_fd( hFile, FILE_WRITE_DATA, &unix_handle,
941                                  &needs_close, &type, &options );
942     if (status) return status;
943
944     if (!virtual_check_buffer_for_read( buffer, length ))
945     {
946         status = STATUS_INVALID_USER_BUFFER;
947         goto done;
948     }
949
950     if (type == FD_TYPE_FILE && offset && offset->QuadPart != (LONGLONG)-2 /* FILE_USE_FILE_POINTER_POSITION */ )
951     {
952         /* async I/O doesn't make sense on regular files */
953         while ((result = pwrite( unix_handle, buffer, length, offset->QuadPart )) == -1)
954         {
955             if (errno != EINTR)
956             {
957                 if (errno == EFAULT) status = STATUS_INVALID_USER_BUFFER;
958                 else status = FILE_GetNtStatus();
959                 goto done;
960             }
961         }
962
963         if (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT))
964             /* update file pointer position */
965             lseek( unix_handle, offset->QuadPart + result, SEEK_SET );
966
967         total = result;
968         status = STATUS_SUCCESS;
969         goto done;
970     }
971
972     for (;;)
973     {
974         /* zero-length writes on sockets may not work with plain write(2) */
975         if (!length && (type == FD_TYPE_MAILSLOT || type == FD_TYPE_PIPE || type == FD_TYPE_SOCKET))
976             result = send( unix_handle, buffer, 0, 0 );
977         else
978             result = write( unix_handle, (const char *)buffer + total, length - total );
979
980         if (result >= 0)
981         {
982             total += result;
983             if (total == length)
984             {
985                 status = STATUS_SUCCESS;
986                 goto done;
987             }
988             if (type == FD_TYPE_FILE) continue;  /* no async I/O on regular files */
989         }
990         else if (errno != EAGAIN)
991         {
992             if (errno == EINTR) continue;
993             if (!total)
994             {
995                 if (errno == EFAULT) status = STATUS_INVALID_USER_BUFFER;
996                 else status = FILE_GetNtStatus();
997             }
998             goto done;
999         }
1000
1001         if (!(options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)))
1002         {
1003             async_fileio_write *fileio;
1004
1005             if (!(fileio = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(*fileio))))
1006             {
1007                 status = STATUS_NO_MEMORY;
1008                 goto err;
1009             }
1010             fileio->io.handle  = hFile;
1011             fileio->io.apc     = apc;
1012             fileio->io.apc_arg = apc_user;
1013             fileio->already = total;
1014             fileio->count = length;
1015             fileio->buffer = buffer;
1016
1017             SERVER_START_REQ( register_async )
1018             {
1019                 req->type   = ASYNC_TYPE_WRITE;
1020                 req->count  = length;
1021                 req->async.handle   = wine_server_obj_handle( hFile );
1022                 req->async.event    = wine_server_obj_handle( hEvent );
1023                 req->async.callback = wine_server_client_ptr( FILE_AsyncWriteService );
1024                 req->async.iosb     = wine_server_client_ptr( io_status );
1025                 req->async.arg      = wine_server_client_ptr( fileio );
1026                 req->async.cvalue   = cvalue;
1027                 status = wine_server_call( req );
1028             }
1029             SERVER_END_REQ;
1030
1031             if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, fileio );
1032             goto err;
1033         }
1034         else  /* synchronous write, wait for the fd to become ready */
1035         {
1036             struct pollfd pfd;
1037             int ret, timeout;
1038
1039             if (!timeout_init_done)
1040             {
1041                 timeout_init_done = 1;
1042                 if ((status = get_io_timeouts( hFile, type, length, FALSE, &timeouts )))
1043                     goto err;
1044                 if (hEvent) NtResetEvent( hEvent, NULL );
1045             }
1046             timeout = get_next_io_timeout( &timeouts, total );
1047
1048             pfd.fd = unix_handle;
1049             pfd.events = POLLOUT;
1050
1051             if (!timeout || !(ret = poll( &pfd, 1, timeout )))
1052             {
1053                 /* return with what we got so far */
1054                 status = total ? STATUS_SUCCESS : STATUS_TIMEOUT;
1055                 goto done;
1056             }
1057             if (ret == -1 && errno != EINTR)
1058             {
1059                 status = FILE_GetNtStatus();
1060                 goto done;
1061             }
1062             /* will now restart the write */
1063         }
1064     }
1065
1066 done:
1067     send_completion = cvalue != 0;
1068
1069 err:
1070     if (needs_close) close( unix_handle );
1071     if (status == STATUS_SUCCESS)
1072     {
1073         io_status->u.Status = status;
1074         io_status->Information = total;
1075         TRACE("= SUCCESS (%u)\n", total);
1076         if (hEvent) NtSetEvent( hEvent, NULL );
1077         if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
1078                                    (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
1079     }
1080     else
1081     {
1082         TRACE("= 0x%08x\n", status);
1083         if (status != STATUS_PENDING && hEvent) NtResetEvent( hEvent, NULL );
1084     }
1085
1086     if (send_completion) NTDLL_AddCompletion( hFile, cvalue, status, total );
1087
1088     return status;
1089 }
1090
1091
1092 /******************************************************************************
1093  *  NtWriteFileGather   [NTDLL.@]
1094  *  ZwWriteFileGather   [NTDLL.@]
1095  */
1096 NTSTATUS WINAPI NtWriteFileGather( HANDLE file, HANDLE event, PIO_APC_ROUTINE apc, void *apc_user,
1097                                    PIO_STATUS_BLOCK io_status, FILE_SEGMENT_ELEMENT *segments,
1098                                    ULONG length, PLARGE_INTEGER offset, PULONG key )
1099 {
1100     size_t page_size = getpagesize();
1101     int result, unix_handle, needs_close;
1102     unsigned int options;
1103     NTSTATUS status;
1104     ULONG pos = 0, total = 0;
1105     enum server_fd_type type;
1106     ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_user;
1107     BOOL send_completion = FALSE;
1108
1109     TRACE( "(%p,%p,%p,%p,%p,%p,0x%08x,%p,%p),partial stub!\n",
1110            file, event, apc, apc_user, io_status, segments, length, offset, key);
1111
1112     if (length % page_size) return STATUS_INVALID_PARAMETER;
1113     if (!io_status) return STATUS_ACCESS_VIOLATION;
1114
1115     status = server_get_unix_fd( file, FILE_WRITE_DATA, &unix_handle,
1116                                  &needs_close, &type, &options );
1117     if (status) return status;
1118
1119     if ((type != FD_TYPE_FILE) ||
1120         (options & (FILE_SYNCHRONOUS_IO_ALERT | FILE_SYNCHRONOUS_IO_NONALERT)) ||
1121         !(options & FILE_NO_INTERMEDIATE_BUFFERING))
1122     {
1123         status = STATUS_INVALID_PARAMETER;
1124         goto error;
1125     }
1126
1127     while (length)
1128     {
1129         if (offset && offset->QuadPart != (LONGLONG)-2 /* FILE_USE_FILE_POINTER_POSITION */)
1130             result = pwrite( unix_handle, (char *)segments->Buffer + pos,
1131                              page_size - pos, offset->QuadPart + total );
1132         else
1133             result = write( unix_handle, (char *)segments->Buffer + pos, page_size - pos );
1134
1135         if (result == -1)
1136         {
1137             if (errno == EINTR) continue;
1138             if (errno == EFAULT)
1139             {
1140                 status = STATUS_INVALID_USER_BUFFER;
1141                 goto error;
1142             }
1143             status = FILE_GetNtStatus();
1144             break;
1145         }
1146         if (!result)
1147         {
1148             status = STATUS_DISK_FULL;
1149             break;
1150         }
1151         total += result;
1152         length -= result;
1153         if ((pos += result) == page_size)
1154         {
1155             pos = 0;
1156             segments++;
1157         }
1158     }
1159
1160     send_completion = cvalue != 0;
1161
1162  error:
1163     if (needs_close) close( unix_handle );
1164     if (status == STATUS_SUCCESS)
1165     {
1166         io_status->u.Status = status;
1167         io_status->Information = total;
1168         TRACE("= SUCCESS (%u)\n", total);
1169         if (event) NtSetEvent( event, NULL );
1170         if (apc) NtQueueApcThread( GetCurrentThread(), (PNTAPCFUNC)apc,
1171                                    (ULONG_PTR)apc_user, (ULONG_PTR)io_status, 0 );
1172     }
1173     else
1174     {
1175         TRACE("= 0x%08x\n", status);
1176         if (status != STATUS_PENDING && event) NtResetEvent( event, NULL );
1177     }
1178
1179     if (send_completion) NTDLL_AddCompletion( file, cvalue, status, total );
1180
1181     return status;
1182 }
1183
1184
1185 struct async_ioctl
1186 {
1187     HANDLE          handle;   /* handle to the device */
1188     HANDLE          event;    /* async event */
1189     void           *buffer;   /* buffer for output */
1190     ULONG           size;     /* size of buffer */
1191     PIO_APC_ROUTINE apc;      /* user apc params */
1192     void           *apc_arg;
1193 };
1194
1195 /* callback for ioctl user APC */
1196 static void WINAPI ioctl_apc( void *arg, IO_STATUS_BLOCK *io, ULONG reserved )
1197 {
1198     struct async_ioctl *async = arg;
1199     if (async->apc) async->apc( async->apc_arg, io, reserved );
1200     RtlFreeHeap( GetProcessHeap(), 0, async );
1201 }
1202
1203 /* callback for ioctl async I/O completion */
1204 static NTSTATUS ioctl_completion( void *arg, IO_STATUS_BLOCK *io, NTSTATUS status, void **apc )
1205 {
1206     struct async_ioctl *async = arg;
1207
1208     if (status == STATUS_ALERTED)
1209     {
1210         SERVER_START_REQ( get_ioctl_result )
1211         {
1212             req->handle   = wine_server_obj_handle( async->handle );
1213             req->user_arg = wine_server_client_ptr( async );
1214             wine_server_set_reply( req, async->buffer, async->size );
1215             status = wine_server_call( req );
1216             if (status != STATUS_PENDING) io->Information = wine_server_reply_size( reply );
1217         }
1218         SERVER_END_REQ;
1219     }
1220     if (status != STATUS_PENDING)
1221     {
1222         io->u.Status = status;
1223         if (async->apc || async->event) *apc = ioctl_apc;
1224     }
1225     return status;
1226 }
1227
1228 /* do a ioctl call through the server */
1229 static NTSTATUS server_ioctl_file( HANDLE handle, HANDLE event,
1230                                    PIO_APC_ROUTINE apc, PVOID apc_context,
1231                                    IO_STATUS_BLOCK *io, ULONG code,
1232                                    const void *in_buffer, ULONG in_size,
1233                                    PVOID out_buffer, ULONG out_size )
1234 {
1235     struct async_ioctl *async;
1236     NTSTATUS status;
1237     HANDLE wait_handle;
1238     ULONG options;
1239     ULONG_PTR cvalue = apc ? 0 : (ULONG_PTR)apc_context;
1240
1241     if (!(async = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*async) )))
1242         return STATUS_NO_MEMORY;
1243     async->handle  = handle;
1244     async->event   = event;
1245     async->buffer  = out_buffer;
1246     async->size    = out_size;
1247     async->apc     = apc;
1248     async->apc_arg = apc_context;
1249
1250     SERVER_START_REQ( ioctl )
1251     {
1252         req->code           = code;
1253         req->blocking       = !apc && !event && !cvalue;
1254         req->async.handle   = wine_server_obj_handle( handle );
1255         req->async.callback = wine_server_client_ptr( ioctl_completion );
1256         req->async.iosb     = wine_server_client_ptr( io );
1257         req->async.arg      = wine_server_client_ptr( async );
1258         req->async.event    = wine_server_obj_handle( event );
1259         req->async.cvalue   = cvalue;
1260         wine_server_add_data( req, in_buffer, in_size );
1261         wine_server_set_reply( req, out_buffer, out_size );
1262         status = wine_server_call( req );
1263         wait_handle = wine_server_ptr_handle( reply->wait );
1264         options     = reply->options;
1265         if (status != STATUS_PENDING) io->Information = wine_server_reply_size( reply );
1266     }
1267     SERVER_END_REQ;
1268
1269     if (status == STATUS_NOT_SUPPORTED)
1270         FIXME("Unsupported ioctl %x (device=%x access=%x func=%x method=%x)\n",
1271               code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
1272
1273     if (status != STATUS_PENDING) RtlFreeHeap( GetProcessHeap(), 0, async );
1274
1275     if (wait_handle)
1276     {
1277         NtWaitForSingleObject( wait_handle, (options & FILE_SYNCHRONOUS_IO_ALERT), NULL );
1278         status = io->u.Status;
1279         NtClose( wait_handle );
1280         RtlFreeHeap( GetProcessHeap(), 0, async );
1281     }
1282
1283     return status;
1284 }
1285
1286 /* Tell Valgrind to ignore any holes in structs we will be passing to the
1287  * server */
1288 static void ignore_server_ioctl_struct_holes (ULONG code, const void *in_buffer,
1289                                               ULONG in_size)
1290 {
1291 #ifdef VALGRIND_MAKE_MEM_DEFINED
1292 # define IGNORE_STRUCT_HOLE(buf, size, t, f1, f2) \
1293     do { \
1294         if (FIELD_OFFSET(t, f1) + sizeof(((t *)0)->f1) < FIELD_OFFSET(t, f2)) \
1295             if ((size) >= FIELD_OFFSET(t, f2)) \
1296                 VALGRIND_MAKE_MEM_DEFINED( \
1297                     (const char *)(buf) + FIELD_OFFSET(t, f1) + sizeof(((t *)0)->f1), \
1298                     FIELD_OFFSET(t, f2) - FIELD_OFFSET(t, f1) + sizeof(((t *)0)->f1)); \
1299     } while (0)
1300
1301     switch (code)
1302     {
1303     case FSCTL_PIPE_WAIT:
1304         IGNORE_STRUCT_HOLE(in_buffer, in_size, FILE_PIPE_WAIT_FOR_BUFFER, TimeoutSpecified, Name);
1305         break;
1306     }
1307 #endif
1308 }
1309
1310
1311 /**************************************************************************
1312  *              NtDeviceIoControlFile                   [NTDLL.@]
1313  *              ZwDeviceIoControlFile                   [NTDLL.@]
1314  *
1315  * Perform an I/O control operation on an open file handle.
1316  *
1317  * PARAMS
1318  *  handle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1319  *  event          [I] Event to signal upon completion (or NULL)
1320  *  apc            [I] Callback to call upon completion (or NULL)
1321  *  apc_context    [I] Context for ApcRoutine (or NULL)
1322  *  io             [O] Receives information about the operation on return
1323  *  code           [I] Control code for the operation to perform
1324  *  in_buffer      [I] Source for any input data required (or NULL)
1325  *  in_size        [I] Size of InputBuffer
1326  *  out_buffer     [O] Source for any output data returned (or NULL)
1327  *  out_size       [I] Size of OutputBuffer
1328  *
1329  * RETURNS
1330  *  Success: 0. IoStatusBlock is updated.
1331  *  Failure: An NTSTATUS error code describing the error.
1332  */
1333 NTSTATUS WINAPI NtDeviceIoControlFile(HANDLE handle, HANDLE event,
1334                                       PIO_APC_ROUTINE apc, PVOID apc_context,
1335                                       PIO_STATUS_BLOCK io, ULONG code,
1336                                       PVOID in_buffer, ULONG in_size,
1337                                       PVOID out_buffer, ULONG out_size)
1338 {
1339     ULONG device = (code >> 16);
1340     NTSTATUS status = STATUS_NOT_SUPPORTED;
1341
1342     TRACE("(%p,%p,%p,%p,%p,0x%08x,%p,0x%08x,%p,0x%08x)\n",
1343           handle, event, apc, apc_context, io, code,
1344           in_buffer, in_size, out_buffer, out_size);
1345
1346     switch(device)
1347     {
1348     case FILE_DEVICE_DISK:
1349     case FILE_DEVICE_CD_ROM:
1350     case FILE_DEVICE_DVD:
1351     case FILE_DEVICE_CONTROLLER:
1352     case FILE_DEVICE_MASS_STORAGE:
1353         status = CDROM_DeviceIoControl(handle, event, apc, apc_context, io, code,
1354                                        in_buffer, in_size, out_buffer, out_size);
1355         break;
1356     case FILE_DEVICE_SERIAL_PORT:
1357         status = COMM_DeviceIoControl(handle, event, apc, apc_context, io, code,
1358                                       in_buffer, in_size, out_buffer, out_size);
1359         break;
1360     case FILE_DEVICE_TAPE:
1361         status = TAPE_DeviceIoControl(handle, event, apc, apc_context, io, code,
1362                                       in_buffer, in_size, out_buffer, out_size);
1363         break;
1364     }
1365
1366     if (status == STATUS_NOT_SUPPORTED || status == STATUS_BAD_DEVICE_TYPE)
1367         status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1368                                     in_buffer, in_size, out_buffer, out_size );
1369
1370     if (status != STATUS_PENDING) io->u.Status = status;
1371     return status;
1372 }
1373
1374
1375 /**************************************************************************
1376  *              NtFsControlFile                 [NTDLL.@]
1377  *              ZwFsControlFile                 [NTDLL.@]
1378  *
1379  * Perform a file system control operation on an open file handle.
1380  *
1381  * PARAMS
1382  *  handle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1383  *  event          [I] Event to signal upon completion (or NULL)
1384  *  apc            [I] Callback to call upon completion (or NULL)
1385  *  apc_context    [I] Context for ApcRoutine (or NULL)
1386  *  io             [O] Receives information about the operation on return
1387  *  code           [I] Control code for the operation to perform
1388  *  in_buffer      [I] Source for any input data required (or NULL)
1389  *  in_size        [I] Size of InputBuffer
1390  *  out_buffer     [O] Source for any output data returned (or NULL)
1391  *  out_size       [I] Size of OutputBuffer
1392  *
1393  * RETURNS
1394  *  Success: 0. IoStatusBlock is updated.
1395  *  Failure: An NTSTATUS error code describing the error.
1396  */
1397 NTSTATUS WINAPI NtFsControlFile(HANDLE handle, HANDLE event, PIO_APC_ROUTINE apc,
1398                                 PVOID apc_context, PIO_STATUS_BLOCK io, ULONG code,
1399                                 PVOID in_buffer, ULONG in_size, PVOID out_buffer, ULONG out_size)
1400 {
1401     NTSTATUS status;
1402
1403     TRACE("(%p,%p,%p,%p,%p,0x%08x,%p,0x%08x,%p,0x%08x)\n",
1404           handle, event, apc, apc_context, io, code,
1405           in_buffer, in_size, out_buffer, out_size);
1406
1407     if (!io) return STATUS_INVALID_PARAMETER;
1408
1409     ignore_server_ioctl_struct_holes( code, in_buffer, in_size );
1410
1411     switch(code)
1412     {
1413     case FSCTL_DISMOUNT_VOLUME:
1414         status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1415                                     in_buffer, in_size, out_buffer, out_size );
1416         if (!status) status = DIR_unmount_device( handle );
1417         break;
1418
1419     case FSCTL_PIPE_PEEK:
1420         {
1421             FILE_PIPE_PEEK_BUFFER *buffer = out_buffer;
1422             int avail = 0, fd, needs_close;
1423
1424             if (out_size < FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data ))
1425             {
1426                 status = STATUS_INFO_LENGTH_MISMATCH;
1427                 break;
1428             }
1429
1430             if ((status = server_get_unix_fd( handle, FILE_READ_DATA, &fd, &needs_close, NULL, NULL )))
1431                 break;
1432
1433 #ifdef FIONREAD
1434             if (ioctl( fd, FIONREAD, &avail ) != 0)
1435             {
1436                 TRACE("FIONREAD failed reason: %s\n",strerror(errno));
1437                 if (needs_close) close( fd );
1438                 status = FILE_GetNtStatus();
1439                 break;
1440             }
1441 #endif
1442             if (!avail)  /* check for closed pipe */
1443             {
1444                 struct pollfd pollfd;
1445                 int ret;
1446
1447                 pollfd.fd = fd;
1448                 pollfd.events = POLLIN;
1449                 pollfd.revents = 0;
1450                 ret = poll( &pollfd, 1, 0 );
1451                 if (ret == -1 || (ret == 1 && (pollfd.revents & (POLLHUP|POLLERR))))
1452                 {
1453                     if (needs_close) close( fd );
1454                     status = STATUS_PIPE_BROKEN;
1455                     break;
1456                 }
1457             }
1458             buffer->NamedPipeState    = 0;  /* FIXME */
1459             buffer->ReadDataAvailable = avail;
1460             buffer->NumberOfMessages  = 0;  /* FIXME */
1461             buffer->MessageLength     = 0;  /* FIXME */
1462             io->Information = FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data );
1463             status = STATUS_SUCCESS;
1464             if (avail)
1465             {
1466                 ULONG data_size = out_size - FIELD_OFFSET( FILE_PIPE_PEEK_BUFFER, Data );
1467                 if (data_size)
1468                 {
1469                     int res = recv( fd, buffer->Data, data_size, MSG_PEEK );
1470                     if (res >= 0) io->Information += res;
1471                 }
1472             }
1473             if (needs_close) close( fd );
1474         }
1475         break;
1476
1477     case FSCTL_PIPE_DISCONNECT:
1478         status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1479                                     in_buffer, in_size, out_buffer, out_size );
1480         if (!status)
1481         {
1482             int fd = server_remove_fd_from_cache( handle );
1483             if (fd != -1) close( fd );
1484         }
1485         break;
1486
1487     case FSCTL_PIPE_IMPERSONATE:
1488         FIXME("FSCTL_PIPE_IMPERSONATE: impersonating self\n");
1489         status = RtlImpersonateSelf( SecurityImpersonation );
1490         break;
1491
1492     case FSCTL_LOCK_VOLUME:
1493     case FSCTL_UNLOCK_VOLUME:
1494         FIXME("stub! return success - Unsupported fsctl %x (device=%x access=%x func=%x method=%x)\n",
1495               code, code >> 16, (code >> 14) & 3, (code >> 2) & 0xfff, code & 3);
1496         status = STATUS_SUCCESS;
1497         break;
1498
1499     case FSCTL_GET_RETRIEVAL_POINTERS:
1500     {
1501         RETRIEVAL_POINTERS_BUFFER *buffer = (RETRIEVAL_POINTERS_BUFFER *)out_buffer;
1502
1503         FIXME("stub: FSCTL_GET_RETRIEVAL_POINTERS\n");
1504
1505         if (out_size >= sizeof(RETRIEVAL_POINTERS_BUFFER))
1506         {
1507             buffer->ExtentCount                 = 1;
1508             buffer->StartingVcn.QuadPart        = 1;
1509             buffer->Extents[0].NextVcn.QuadPart = 0;
1510             buffer->Extents[0].Lcn.QuadPart     = 0;
1511             io->Information = sizeof(RETRIEVAL_POINTERS_BUFFER);
1512             status = STATUS_SUCCESS;
1513         }
1514         else
1515         {
1516             io->Information = 0;
1517             status = STATUS_BUFFER_TOO_SMALL;
1518         }
1519         break;
1520     }
1521     case FSCTL_PIPE_LISTEN:
1522     case FSCTL_PIPE_WAIT:
1523     default:
1524         status = server_ioctl_file( handle, event, apc, apc_context, io, code,
1525                                     in_buffer, in_size, out_buffer, out_size );
1526         break;
1527     }
1528
1529     if (status != STATUS_PENDING) io->u.Status = status;
1530     return status;
1531 }
1532
1533 /******************************************************************************
1534  *  NtSetVolumeInformationFile          [NTDLL.@]
1535  *  ZwSetVolumeInformationFile          [NTDLL.@]
1536  *
1537  * Set volume information for an open file handle.
1538  *
1539  * PARAMS
1540  *  FileHandle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1541  *  IoStatusBlock      [O] Receives information about the operation on return
1542  *  FsInformation      [I] Source for volume information
1543  *  Length             [I] Size of FsInformation
1544  *  FsInformationClass [I] Type of volume information to set
1545  *
1546  * RETURNS
1547  *  Success: 0. IoStatusBlock is updated.
1548  *  Failure: An NTSTATUS error code describing the error.
1549  */
1550 NTSTATUS WINAPI NtSetVolumeInformationFile(
1551         IN HANDLE FileHandle,
1552         PIO_STATUS_BLOCK IoStatusBlock,
1553         PVOID FsInformation,
1554         ULONG Length,
1555         FS_INFORMATION_CLASS FsInformationClass)
1556 {
1557         FIXME("(%p,%p,%p,0x%08x,0x%08x) stub\n",
1558         FileHandle,IoStatusBlock,FsInformation,Length,FsInformationClass);
1559         return 0;
1560 }
1561
1562 static NTSTATUS set_file_times( int fd, const LARGE_INTEGER *mtime, const LARGE_INTEGER *atime )
1563 {
1564     NTSTATUS status = STATUS_SUCCESS;
1565
1566 #ifdef HAVE_FUTIMENS
1567     struct timespec tv[2];
1568
1569     tv[0].tv_sec = tv[1].tv_sec = 0;
1570     tv[0].tv_nsec = tv[1].tv_nsec = UTIME_OMIT;
1571     if (atime->QuadPart)
1572     {
1573         tv[0].tv_sec = atime->QuadPart / 10000000 - SECS_1601_TO_1970;
1574         tv[0].tv_nsec = (atime->QuadPart % 10000000) * 100;
1575     }
1576     if (mtime->QuadPart)
1577     {
1578         tv[1].tv_sec = mtime->QuadPart / 10000000 - SECS_1601_TO_1970;
1579         tv[1].tv_nsec = (mtime->QuadPart % 10000000) * 100;
1580     }
1581     if (futimens( fd, tv ) == -1) status = FILE_GetNtStatus();
1582
1583 #elif defined(HAVE_FUTIMES) || defined(HAVE_FUTIMESAT)
1584     struct timeval tv[2];
1585     struct stat st;
1586
1587     if (!atime->QuadPart || !mtime->QuadPart)
1588     {
1589
1590         tv[0].tv_sec = tv[0].tv_usec = 0;
1591         tv[1].tv_sec = tv[1].tv_usec = 0;
1592         if (!fstat( fd, &st ))
1593         {
1594             tv[0].tv_sec = st.st_atime;
1595             tv[1].tv_sec = st.st_mtime;
1596 #ifdef HAVE_STRUCT_STAT_ST_ATIM
1597             tv[0].tv_usec = st.st_atim.tv_nsec / 1000;
1598 #elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC)
1599             tv[0].tv_usec = st.st_atimespec.tv_nsec / 1000;
1600 #endif
1601 #ifdef HAVE_STRUCT_STAT_ST_MTIM
1602             tv[1].tv_usec = st.st_mtim.tv_nsec / 1000;
1603 #elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC)
1604             tv[1].tv_usec = st.st_mtimespec.tv_nsec / 1000;
1605 #endif
1606         }
1607     }
1608     if (atime->QuadPart)
1609     {
1610         tv[0].tv_sec = atime->QuadPart / 10000000 - SECS_1601_TO_1970;
1611         tv[0].tv_usec = (atime->QuadPart % 10000000) / 10;
1612     }
1613     if (mtime->QuadPart)
1614     {
1615         tv[1].tv_sec = mtime->QuadPart / 10000000 - SECS_1601_TO_1970;
1616         tv[1].tv_usec = (mtime->QuadPart % 10000000) / 10;
1617     }
1618 #ifdef HAVE_FUTIMES
1619     if (futimes( fd, tv ) == -1) status = FILE_GetNtStatus();
1620 #elif defined(HAVE_FUTIMESAT)
1621     if (futimesat( fd, NULL, tv ) == -1) status = FILE_GetNtStatus();
1622 #endif
1623
1624 #else  /* HAVE_FUTIMES || HAVE_FUTIMESAT */
1625     FIXME( "setting file times not supported\n" );
1626     status = STATUS_NOT_IMPLEMENTED;
1627 #endif
1628     return status;
1629 }
1630
1631 static inline void get_file_times( const struct stat *st, LARGE_INTEGER *mtime, LARGE_INTEGER *ctime,
1632                                    LARGE_INTEGER *atime, LARGE_INTEGER *creation )
1633 {
1634     RtlSecondsSince1970ToTime( st->st_mtime, mtime );
1635     RtlSecondsSince1970ToTime( st->st_ctime, ctime );
1636     RtlSecondsSince1970ToTime( st->st_atime, atime );
1637 #ifdef HAVE_STRUCT_STAT_ST_MTIM
1638     mtime->QuadPart += st->st_mtim.tv_nsec / 100;
1639 #elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC)
1640     mtime->QuadPart += st->st_mtimespec.tv_nsec / 100;
1641 #endif
1642 #ifdef HAVE_STRUCT_STAT_ST_CTIM
1643     ctime->QuadPart += st->st_ctim.tv_nsec / 100;
1644 #elif defined(HAVE_STRUCT_STAT_ST_CTIMESPEC)
1645     ctime->QuadPart += st->st_ctimespec.tv_nsec / 100;
1646 #endif
1647 #ifdef HAVE_STRUCT_STAT_ST_ATIM
1648     atime->QuadPart += st->st_atim.tv_nsec / 100;
1649 #elif defined(HAVE_STRUCT_STAT_ST_ATIMESPEC)
1650     atime->QuadPart += st->st_atimespec.tv_nsec / 100;
1651 #endif
1652 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIME
1653     RtlSecondsSince1970ToTime( st->st_birthtime, creation );
1654 #ifdef HAVE_STRUCT_STAT_ST_BIRTHTIM
1655     creation->QuadPart += st->st_birthtim.tv_nsec / 100;
1656 #elif defined(HAVE_STRUCT_STAT_ST_BIRTHTIMESPEC)
1657     creation->QuadPart += st->st_birthtimespec.tv_nsec / 100;
1658 #endif
1659 #elif defined(HAVE_STRUCT_STAT___ST_BIRTHTIME)
1660     RtlSecondsSince1970ToTime( st->__st_birthtime, creation );
1661 #ifdef HAVE_STRUCT_STAT___ST_BIRTHTIM
1662     creation->QuadPart += st->__st_birthtim.tv_nsec / 100;
1663 #endif
1664 #else
1665     *creation = *mtime;
1666 #endif
1667 }
1668
1669 /* fill in the file information that depends on the stat info */
1670 NTSTATUS fill_stat_info( const struct stat *st, void *ptr, FILE_INFORMATION_CLASS class )
1671 {
1672     switch (class)
1673     {
1674     case FileBasicInformation:
1675         {
1676             FILE_BASIC_INFORMATION *info = ptr;
1677
1678             get_file_times( st, &info->LastWriteTime, &info->ChangeTime,
1679                             &info->LastAccessTime, &info->CreationTime );
1680             if (S_ISDIR(st->st_mode)) info->FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
1681             else info->FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1682             if (!(st->st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
1683                 info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
1684         }
1685         break;
1686     case FileStandardInformation:
1687         {
1688             FILE_STANDARD_INFORMATION *info = ptr;
1689
1690             if ((info->Directory = S_ISDIR(st->st_mode)))
1691             {
1692                 info->AllocationSize.QuadPart = 0;
1693                 info->EndOfFile.QuadPart      = 0;
1694                 info->NumberOfLinks           = 1;
1695             }
1696             else
1697             {
1698                 info->AllocationSize.QuadPart = (ULONGLONG)st->st_blocks * 512;
1699                 info->EndOfFile.QuadPart      = st->st_size;
1700                 info->NumberOfLinks           = st->st_nlink;
1701             }
1702         }
1703         break;
1704     case FileInternalInformation:
1705         {
1706             FILE_INTERNAL_INFORMATION *info = ptr;
1707             info->IndexNumber.QuadPart = st->st_ino;
1708         }
1709         break;
1710     case FileEndOfFileInformation:
1711         {
1712             FILE_END_OF_FILE_INFORMATION *info = ptr;
1713             info->EndOfFile.QuadPart = S_ISDIR(st->st_mode) ? 0 : st->st_size;
1714         }
1715         break;
1716     case FileAllInformation:
1717         {
1718             FILE_ALL_INFORMATION *info = ptr;
1719             fill_stat_info( st, &info->BasicInformation, FileBasicInformation );
1720             fill_stat_info( st, &info->StandardInformation, FileStandardInformation );
1721             fill_stat_info( st, &info->InternalInformation, FileInternalInformation );
1722         }
1723         break;
1724     /* all directory structures start with the FileDirectoryInformation layout */
1725     case FileBothDirectoryInformation:
1726     case FileFullDirectoryInformation:
1727     case FileDirectoryInformation:
1728         {
1729             FILE_DIRECTORY_INFORMATION *info = ptr;
1730
1731             get_file_times( st, &info->LastWriteTime, &info->ChangeTime,
1732                             &info->LastAccessTime, &info->CreationTime );
1733             if (S_ISDIR(st->st_mode))
1734             {
1735                 info->AllocationSize.QuadPart = 0;
1736                 info->EndOfFile.QuadPart      = 0;
1737                 info->FileAttributes = FILE_ATTRIBUTE_DIRECTORY;
1738             }
1739             else
1740             {
1741                 info->AllocationSize.QuadPart = (ULONGLONG)st->st_blocks * 512;
1742                 info->EndOfFile.QuadPart      = st->st_size;
1743                 info->FileAttributes = FILE_ATTRIBUTE_ARCHIVE;
1744             }
1745             if (!(st->st_mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
1746                 info->FileAttributes |= FILE_ATTRIBUTE_READONLY;
1747         }
1748         break;
1749     case FileIdFullDirectoryInformation:
1750         {
1751             FILE_ID_FULL_DIRECTORY_INFORMATION *info = ptr;
1752             info->FileId.QuadPart = st->st_ino;
1753             fill_stat_info( st, info, FileDirectoryInformation );
1754         }
1755         break;
1756     case FileIdBothDirectoryInformation:
1757         {
1758             FILE_ID_BOTH_DIRECTORY_INFORMATION *info = ptr;
1759             info->FileId.QuadPart = st->st_ino;
1760             fill_stat_info( st, info, FileDirectoryInformation );
1761         }
1762         break;
1763
1764     default:
1765         return STATUS_INVALID_INFO_CLASS;
1766     }
1767     return STATUS_SUCCESS;
1768 }
1769
1770 NTSTATUS server_get_unix_name( HANDLE handle, ANSI_STRING *unix_name )
1771 {
1772     data_size_t size = 1024;
1773     NTSTATUS ret;
1774     char *name;
1775
1776     for (;;)
1777     {
1778         name = RtlAllocateHeap( GetProcessHeap(), 0, size + 1 );
1779         if (!name) return STATUS_NO_MEMORY;
1780         unix_name->MaximumLength = size + 1;
1781
1782         SERVER_START_REQ( get_handle_unix_name )
1783         {
1784             req->handle = wine_server_obj_handle( handle );
1785             wine_server_set_reply( req, name, size );
1786             ret = wine_server_call( req );
1787             size = reply->name_len;
1788         }
1789         SERVER_END_REQ;
1790
1791         if (!ret)
1792         {
1793             name[size] = 0;
1794             unix_name->Buffer = name;
1795             unix_name->Length = size;
1796             break;
1797         }
1798         RtlFreeHeap( GetProcessHeap(), 0, name );
1799         if (ret != STATUS_BUFFER_OVERFLOW) break;
1800     }
1801     return ret;
1802 }
1803
1804 static NTSTATUS fill_name_info( const ANSI_STRING *unix_name, FILE_NAME_INFORMATION *info, LONG *name_len )
1805 {
1806     UNICODE_STRING nt_name;
1807     NTSTATUS status;
1808
1809     if (!(status = wine_unix_to_nt_file_name( unix_name, &nt_name )))
1810     {
1811         const WCHAR *ptr = nt_name.Buffer;
1812         const WCHAR *end = ptr + (nt_name.Length / sizeof(WCHAR));
1813
1814         /* Skip the volume mount point. */
1815         while (ptr != end && *ptr == '\\') ++ptr;
1816         while (ptr != end && *ptr != '\\') ++ptr;
1817         while (ptr != end && *ptr == '\\') ++ptr;
1818         while (ptr != end && *ptr != '\\') ++ptr;
1819
1820         info->FileNameLength = (end - ptr) * sizeof(WCHAR);
1821         if (*name_len < info->FileNameLength) status = STATUS_BUFFER_OVERFLOW;
1822         else *name_len = info->FileNameLength;
1823
1824         memcpy( info->FileName, ptr, *name_len );
1825         RtlFreeUnicodeString( &nt_name );
1826     }
1827
1828     return status;
1829 }
1830
1831 /******************************************************************************
1832  *  NtQueryInformationFile              [NTDLL.@]
1833  *  ZwQueryInformationFile              [NTDLL.@]
1834  *
1835  * Get information about an open file handle.
1836  *
1837  * PARAMS
1838  *  hFile    [I] Handle returned from ZwOpenFile() or ZwCreateFile()
1839  *  io       [O] Receives information about the operation on return
1840  *  ptr      [O] Destination for file information
1841  *  len      [I] Size of FileInformation
1842  *  class    [I] Type of file information to get
1843  *
1844  * RETURNS
1845  *  Success: 0. IoStatusBlock and FileInformation are updated.
1846  *  Failure: An NTSTATUS error code describing the error.
1847  */
1848 NTSTATUS WINAPI NtQueryInformationFile( HANDLE hFile, PIO_STATUS_BLOCK io,
1849                                         PVOID ptr, LONG len, FILE_INFORMATION_CLASS class )
1850 {
1851     static const size_t info_sizes[] =
1852     {
1853         0,
1854         sizeof(FILE_DIRECTORY_INFORMATION),            /* FileDirectoryInformation */
1855         sizeof(FILE_FULL_DIRECTORY_INFORMATION),       /* FileFullDirectoryInformation */
1856         sizeof(FILE_BOTH_DIRECTORY_INFORMATION),       /* FileBothDirectoryInformation */
1857         sizeof(FILE_BASIC_INFORMATION),                /* FileBasicInformation */
1858         sizeof(FILE_STANDARD_INFORMATION),             /* FileStandardInformation */
1859         sizeof(FILE_INTERNAL_INFORMATION),             /* FileInternalInformation */
1860         sizeof(FILE_EA_INFORMATION),                   /* FileEaInformation */
1861         sizeof(FILE_ACCESS_INFORMATION),               /* FileAccessInformation */
1862         sizeof(FILE_NAME_INFORMATION),                 /* FileNameInformation */
1863         sizeof(FILE_RENAME_INFORMATION)-sizeof(WCHAR), /* FileRenameInformation */
1864         0,                                             /* FileLinkInformation */
1865         sizeof(FILE_NAMES_INFORMATION)-sizeof(WCHAR),  /* FileNamesInformation */
1866         sizeof(FILE_DISPOSITION_INFORMATION),          /* FileDispositionInformation */
1867         sizeof(FILE_POSITION_INFORMATION),             /* FilePositionInformation */
1868         sizeof(FILE_FULL_EA_INFORMATION),              /* FileFullEaInformation */
1869         sizeof(FILE_MODE_INFORMATION),                 /* FileModeInformation */
1870         sizeof(FILE_ALIGNMENT_INFORMATION),            /* FileAlignmentInformation */
1871         sizeof(FILE_ALL_INFORMATION),                  /* FileAllInformation */
1872         sizeof(FILE_ALLOCATION_INFORMATION),           /* FileAllocationInformation */
1873         sizeof(FILE_END_OF_FILE_INFORMATION),          /* FileEndOfFileInformation */
1874         0,                                             /* FileAlternateNameInformation */
1875         sizeof(FILE_STREAM_INFORMATION)-sizeof(WCHAR), /* FileStreamInformation */
1876         0,                                             /* FilePipeInformation */
1877         sizeof(FILE_PIPE_LOCAL_INFORMATION),           /* FilePipeLocalInformation */
1878         0,                                             /* FilePipeRemoteInformation */
1879         sizeof(FILE_MAILSLOT_QUERY_INFORMATION),       /* FileMailslotQueryInformation */
1880         0,                                             /* FileMailslotSetInformation */
1881         0,                                             /* FileCompressionInformation */
1882         0,                                             /* FileObjectIdInformation */
1883         0,                                             /* FileCompletionInformation */
1884         0,                                             /* FileMoveClusterInformation */
1885         0,                                             /* FileQuotaInformation */
1886         0,                                             /* FileReparsePointInformation */
1887         0,                                             /* FileNetworkOpenInformation */
1888         0,                                             /* FileAttributeTagInformation */
1889         0,                                             /* FileTrackingInformation */
1890         0,                                             /* FileIdBothDirectoryInformation */
1891         0,                                             /* FileIdFullDirectoryInformation */
1892         0,                                             /* FileValidDataLengthInformation */
1893         0,                                             /* FileShortNameInformation */
1894         0,
1895         0,
1896         0,
1897         0,                                             /* FileSfioReserveInformation */
1898         0,                                             /* FileSfioVolumeInformation */
1899         0,                                             /* FileHardLinkInformation */
1900         0,
1901         0,                                             /* FileNormalizedNameInformation */
1902         0,
1903         0,                                             /* FileIdGlobalTxDirectoryInformation */
1904         0,
1905         0,
1906         0,
1907         0                                              /* FileStandardLinkInformation */
1908     };
1909
1910     struct stat st;
1911     int fd, needs_close = FALSE;
1912
1913     TRACE("(%p,%p,%p,0x%08x,0x%08x)\n", hFile, io, ptr, len, class);
1914
1915     io->Information = 0;
1916
1917     if (class <= 0 || class >= FileMaximumInformation)
1918         return io->u.Status = STATUS_INVALID_INFO_CLASS;
1919     if (!info_sizes[class])
1920     {
1921         FIXME("Unsupported class (%d)\n", class);
1922         return io->u.Status = STATUS_NOT_IMPLEMENTED;
1923     }
1924     if (len < info_sizes[class])
1925         return io->u.Status = STATUS_INFO_LENGTH_MISMATCH;
1926
1927     if (class != FilePipeLocalInformation)
1928     {
1929         if ((io->u.Status = server_get_unix_fd( hFile, 0, &fd, &needs_close, NULL, NULL )))
1930             return io->u.Status;
1931     }
1932
1933     switch (class)
1934     {
1935     case FileBasicInformation:
1936         if (fstat( fd, &st ) == -1)
1937             io->u.Status = FILE_GetNtStatus();
1938         else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
1939             io->u.Status = STATUS_INVALID_INFO_CLASS;
1940         else
1941             fill_stat_info( &st, ptr, class );
1942         break;
1943     case FileStandardInformation:
1944         {
1945             FILE_STANDARD_INFORMATION *info = ptr;
1946
1947             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1948             else
1949             {
1950                 fill_stat_info( &st, info, class );
1951                 info->DeletePending = FALSE; /* FIXME */
1952             }
1953         }
1954         break;
1955     case FilePositionInformation:
1956         {
1957             FILE_POSITION_INFORMATION *info = ptr;
1958             off_t res = lseek( fd, 0, SEEK_CUR );
1959             if (res == (off_t)-1) io->u.Status = FILE_GetNtStatus();
1960             else info->CurrentByteOffset.QuadPart = res;
1961         }
1962         break;
1963     case FileInternalInformation:
1964         if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1965         else fill_stat_info( &st, ptr, class );
1966         break;
1967     case FileEaInformation:
1968         {
1969             FILE_EA_INFORMATION *info = ptr;
1970             info->EaSize = 0;
1971         }
1972         break;
1973     case FileEndOfFileInformation:
1974         if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1975         else fill_stat_info( &st, ptr, class );
1976         break;
1977     case FileAllInformation:
1978         {
1979             FILE_ALL_INFORMATION *info = ptr;
1980             ANSI_STRING unix_name;
1981
1982             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
1983             else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
1984                 io->u.Status = STATUS_INVALID_INFO_CLASS;
1985             else if (!(io->u.Status = server_get_unix_name( hFile, &unix_name )))
1986             {
1987                 LONG name_len = len - FIELD_OFFSET(FILE_ALL_INFORMATION, NameInformation.FileName);
1988
1989                 fill_stat_info( &st, info, FileAllInformation );
1990                 info->StandardInformation.DeletePending = FALSE; /* FIXME */
1991                 info->EaInformation.EaSize = 0;
1992                 info->AccessInformation.AccessFlags = 0;  /* FIXME */
1993                 info->PositionInformation.CurrentByteOffset.QuadPart = lseek( fd, 0, SEEK_CUR );
1994                 info->ModeInformation.Mode = 0;  /* FIXME */
1995                 info->AlignmentInformation.AlignmentRequirement = 1;  /* FIXME */
1996
1997                 io->u.Status = fill_name_info( &unix_name, &info->NameInformation, &name_len );
1998                 RtlFreeAnsiString( &unix_name );
1999                 io->Information = FIELD_OFFSET(FILE_ALL_INFORMATION, NameInformation.FileName) + name_len;
2000             }
2001         }
2002         break;
2003     case FileMailslotQueryInformation:
2004         {
2005             FILE_MAILSLOT_QUERY_INFORMATION *info = ptr;
2006
2007             SERVER_START_REQ( set_mailslot_info )
2008             {
2009                 req->handle = wine_server_obj_handle( hFile );
2010                 req->flags = 0;
2011                 io->u.Status = wine_server_call( req );
2012                 if( io->u.Status == STATUS_SUCCESS )
2013                 {
2014                     info->MaximumMessageSize = reply->max_msgsize;
2015                     info->MailslotQuota = 0;
2016                     info->NextMessageSize = 0;
2017                     info->MessagesAvailable = 0;
2018                     info->ReadTimeout.QuadPart = reply->read_timeout;
2019                 }
2020             }
2021             SERVER_END_REQ;
2022             if (!io->u.Status)
2023             {
2024                 char *tmpbuf;
2025                 ULONG size = info->MaximumMessageSize ? info->MaximumMessageSize : 0x10000;
2026                 if (size > 0x10000) size = 0x10000;
2027                 if ((tmpbuf = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2028                 {
2029                     int fd, needs_close;
2030                     if (!server_get_unix_fd( hFile, FILE_READ_DATA, &fd, &needs_close, NULL, NULL ))
2031                     {
2032                         int res = recv( fd, tmpbuf, size, MSG_PEEK );
2033                         info->MessagesAvailable = (res > 0);
2034                         info->NextMessageSize = (res >= 0) ? res : MAILSLOT_NO_MESSAGE;
2035                         if (needs_close) close( fd );
2036                     }
2037                     RtlFreeHeap( GetProcessHeap(), 0, tmpbuf );
2038                 }
2039             }
2040         }
2041         break;
2042     case FilePipeLocalInformation:
2043         {
2044             FILE_PIPE_LOCAL_INFORMATION* pli = ptr;
2045
2046             SERVER_START_REQ( get_named_pipe_info )
2047             {
2048                 req->handle = wine_server_obj_handle( hFile );
2049                 if (!(io->u.Status = wine_server_call( req )))
2050                 {
2051                     pli->NamedPipeType = (reply->flags & NAMED_PIPE_MESSAGE_STREAM_WRITE) ? 
2052                         FILE_PIPE_TYPE_MESSAGE : FILE_PIPE_TYPE_BYTE;
2053                     switch (reply->sharing)
2054                     {
2055                         case FILE_SHARE_READ:
2056                             pli->NamedPipeConfiguration = FILE_PIPE_OUTBOUND;
2057                             break;
2058                         case FILE_SHARE_WRITE:
2059                             pli->NamedPipeConfiguration = FILE_PIPE_INBOUND;
2060                             break;
2061                         case FILE_SHARE_READ | FILE_SHARE_WRITE:
2062                             pli->NamedPipeConfiguration = FILE_PIPE_FULL_DUPLEX;
2063                             break;
2064                     }
2065                     pli->MaximumInstances = reply->maxinstances;
2066                     pli->CurrentInstances = reply->instances;
2067                     pli->InboundQuota = reply->insize;
2068                     pli->ReadDataAvailable = 0; /* FIXME */
2069                     pli->OutboundQuota = reply->outsize;
2070                     pli->WriteQuotaAvailable = 0; /* FIXME */
2071                     pli->NamedPipeState = 0; /* FIXME */
2072                     pli->NamedPipeEnd = (reply->flags & NAMED_PIPE_SERVER_END) ?
2073                         FILE_PIPE_SERVER_END : FILE_PIPE_CLIENT_END;
2074                 }
2075             }
2076             SERVER_END_REQ;
2077         }
2078         break;
2079     case FileNameInformation:
2080         {
2081             FILE_NAME_INFORMATION *info = ptr;
2082             ANSI_STRING unix_name;
2083
2084             if (!(io->u.Status = server_get_unix_name( hFile, &unix_name )))
2085             {
2086                 LONG name_len = len - FIELD_OFFSET(FILE_NAME_INFORMATION, FileName);
2087                 io->u.Status = fill_name_info( &unix_name, info, &name_len );
2088                 RtlFreeAnsiString( &unix_name );
2089                 io->Information = FIELD_OFFSET(FILE_NAME_INFORMATION, FileName) + name_len;
2090             }
2091         }
2092         break;
2093     default:
2094         FIXME("Unsupported class (%d)\n", class);
2095         io->u.Status = STATUS_NOT_IMPLEMENTED;
2096         break;
2097     }
2098     if (needs_close) close( fd );
2099     if (io->u.Status == STATUS_SUCCESS && !io->Information) io->Information = info_sizes[class];
2100     return io->u.Status;
2101 }
2102
2103 /******************************************************************************
2104  *  NtSetInformationFile                [NTDLL.@]
2105  *  ZwSetInformationFile                [NTDLL.@]
2106  *
2107  * Set information about an open file handle.
2108  *
2109  * PARAMS
2110  *  handle  [I] Handle returned from ZwOpenFile() or ZwCreateFile()
2111  *  io      [O] Receives information about the operation on return
2112  *  ptr     [I] Source for file information
2113  *  len     [I] Size of FileInformation
2114  *  class   [I] Type of file information to set
2115  *
2116  * RETURNS
2117  *  Success: 0. io is updated.
2118  *  Failure: An NTSTATUS error code describing the error.
2119  */
2120 NTSTATUS WINAPI NtSetInformationFile(HANDLE handle, PIO_STATUS_BLOCK io,
2121                                      PVOID ptr, ULONG len, FILE_INFORMATION_CLASS class)
2122 {
2123     int fd, needs_close;
2124
2125     TRACE("(%p,%p,%p,0x%08x,0x%08x)\n", handle, io, ptr, len, class);
2126
2127     io->u.Status = STATUS_SUCCESS;
2128     switch (class)
2129     {
2130     case FileBasicInformation:
2131         if (len >= sizeof(FILE_BASIC_INFORMATION))
2132         {
2133             struct stat st;
2134             const FILE_BASIC_INFORMATION *info = ptr;
2135
2136             if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
2137                 return io->u.Status;
2138
2139             if (info->LastAccessTime.QuadPart || info->LastWriteTime.QuadPart)
2140                 io->u.Status = set_file_times( fd, &info->LastWriteTime, &info->LastAccessTime );
2141
2142             if (io->u.Status == STATUS_SUCCESS && info->FileAttributes)
2143             {
2144                 if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
2145                 else
2146                 {
2147                     if (info->FileAttributes & FILE_ATTRIBUTE_READONLY)
2148                     {
2149                         if (S_ISDIR( st.st_mode))
2150                             WARN("FILE_ATTRIBUTE_READONLY ignored for directory.\n");
2151                         else
2152                             st.st_mode &= ~0222; /* clear write permission bits */
2153                     }
2154                     else
2155                     {
2156                         /* add write permission only where we already have read permission */
2157                         st.st_mode |= (0600 | ((st.st_mode & 044) >> 1)) & (~FILE_umask);
2158                     }
2159                     if (fchmod( fd, st.st_mode ) == -1) io->u.Status = FILE_GetNtStatus();
2160                 }
2161             }
2162
2163             if (needs_close) close( fd );
2164         }
2165         else io->u.Status = STATUS_INVALID_PARAMETER_3;
2166         break;
2167
2168     case FilePositionInformation:
2169         if (len >= sizeof(FILE_POSITION_INFORMATION))
2170         {
2171             const FILE_POSITION_INFORMATION *info = ptr;
2172
2173             if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
2174                 return io->u.Status;
2175
2176             if (lseek( fd, info->CurrentByteOffset.QuadPart, SEEK_SET ) == (off_t)-1)
2177                 io->u.Status = FILE_GetNtStatus();
2178
2179             if (needs_close) close( fd );
2180         }
2181         else io->u.Status = STATUS_INVALID_PARAMETER_3;
2182         break;
2183
2184     case FileEndOfFileInformation:
2185         if (len >= sizeof(FILE_END_OF_FILE_INFORMATION))
2186         {
2187             struct stat st;
2188             const FILE_END_OF_FILE_INFORMATION *info = ptr;
2189
2190             if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )))
2191                 return io->u.Status;
2192
2193             /* first try normal truncate */
2194             if (ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
2195
2196             /* now check for the need to extend the file */
2197             if (fstat( fd, &st ) != -1 && (off_t)info->EndOfFile.QuadPart > st.st_size)
2198             {
2199                 static const char zero;
2200
2201                 /* extend the file one byte beyond the requested size and then truncate it */
2202                 /* this should work around ftruncate implementations that can't extend files */
2203                 if (pwrite( fd, &zero, 1, (off_t)info->EndOfFile.QuadPart ) != -1 &&
2204                     ftruncate( fd, (off_t)info->EndOfFile.QuadPart ) != -1) break;
2205             }
2206             io->u.Status = FILE_GetNtStatus();
2207
2208             if (needs_close) close( fd );
2209         }
2210         else io->u.Status = STATUS_INVALID_PARAMETER_3;
2211         break;
2212
2213     case FileMailslotSetInformation:
2214         {
2215             FILE_MAILSLOT_SET_INFORMATION *info = ptr;
2216
2217             SERVER_START_REQ( set_mailslot_info )
2218             {
2219                 req->handle = wine_server_obj_handle( handle );
2220                 req->flags = MAILSLOT_SET_READ_TIMEOUT;
2221                 req->read_timeout = info->ReadTimeout.QuadPart;
2222                 io->u.Status = wine_server_call( req );
2223             }
2224             SERVER_END_REQ;
2225         }
2226         break;
2227
2228     case FileCompletionInformation:
2229         if (len >= sizeof(FILE_COMPLETION_INFORMATION))
2230         {
2231             FILE_COMPLETION_INFORMATION *info = ptr;
2232
2233             SERVER_START_REQ( set_completion_info )
2234             {
2235                 req->handle   = wine_server_obj_handle( handle );
2236                 req->chandle  = wine_server_obj_handle( info->CompletionPort );
2237                 req->ckey     = info->CompletionKey;
2238                 io->u.Status  = wine_server_call( req );
2239             }
2240             SERVER_END_REQ;
2241         } else
2242             io->u.Status = STATUS_INVALID_PARAMETER_3;
2243         break;
2244
2245     case FileAllInformation:
2246         io->u.Status = STATUS_INVALID_INFO_CLASS;
2247         break;
2248
2249     case FileValidDataLengthInformation:
2250         if (len >= sizeof(FILE_VALID_DATA_LENGTH_INFORMATION))
2251         {
2252             struct stat st;
2253             const FILE_VALID_DATA_LENGTH_INFORMATION *info = ptr;
2254
2255             if ((io->u.Status = server_get_unix_fd( handle, FILE_WRITE_DATA, &fd, &needs_close, NULL, NULL )))
2256                 return io->u.Status;
2257
2258             if (fstat( fd, &st ) == -1) io->u.Status = FILE_GetNtStatus();
2259             else if (info->ValidDataLength.QuadPart <= 0 || (off_t)info->ValidDataLength.QuadPart > st.st_size)
2260                 io->u.Status = STATUS_INVALID_PARAMETER;
2261             else
2262             {
2263 #ifdef HAVE_FALLOCATE
2264                 if (fallocate( fd, 0, 0, (off_t)info->ValidDataLength.QuadPart ) == -1)
2265                 {
2266                     NTSTATUS status = FILE_GetNtStatus();
2267                     if (status == STATUS_NOT_SUPPORTED) WARN( "fallocate not supported on this filesystem\n" );
2268                     else io->u.Status = status;
2269                 }
2270 #else
2271                 FIXME( "setting valid data length not supported\n" );
2272 #endif
2273             }
2274             if (needs_close) close( fd );
2275         }
2276         else io->u.Status = STATUS_INVALID_PARAMETER_3;
2277         break;
2278
2279     default:
2280         FIXME("Unsupported class (%d)\n", class);
2281         io->u.Status = STATUS_NOT_IMPLEMENTED;
2282         break;
2283     }
2284     io->Information = 0;
2285     return io->u.Status;
2286 }
2287
2288
2289 /******************************************************************************
2290  *              NtQueryFullAttributesFile   (NTDLL.@)
2291  */
2292 NTSTATUS WINAPI NtQueryFullAttributesFile( const OBJECT_ATTRIBUTES *attr,
2293                                            FILE_NETWORK_OPEN_INFORMATION *info )
2294 {
2295     ANSI_STRING unix_name;
2296     NTSTATUS status;
2297
2298     if (!(status = nt_to_unix_file_name_attr( attr, &unix_name, FILE_OPEN )))
2299     {
2300         struct stat st;
2301
2302         if (stat( unix_name.Buffer, &st ) == -1)
2303             status = FILE_GetNtStatus();
2304         else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
2305             status = STATUS_INVALID_INFO_CLASS;
2306         else
2307         {
2308             FILE_BASIC_INFORMATION basic;
2309             FILE_STANDARD_INFORMATION std;
2310
2311             fill_stat_info( &st, &basic, FileBasicInformation );
2312             fill_stat_info( &st, &std, FileStandardInformation );
2313
2314             info->CreationTime   = basic.CreationTime;
2315             info->LastAccessTime = basic.LastAccessTime;
2316             info->LastWriteTime  = basic.LastWriteTime;
2317             info->ChangeTime     = basic.ChangeTime;
2318             info->AllocationSize = std.AllocationSize;
2319             info->EndOfFile      = std.EndOfFile;
2320             info->FileAttributes = basic.FileAttributes;
2321             if (DIR_is_hidden_file( attr->ObjectName ))
2322                 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
2323         }
2324         RtlFreeAnsiString( &unix_name );
2325     }
2326     else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), status );
2327     return status;
2328 }
2329
2330
2331 /******************************************************************************
2332  *              NtQueryAttributesFile   (NTDLL.@)
2333  *              ZwQueryAttributesFile   (NTDLL.@)
2334  */
2335 NTSTATUS WINAPI NtQueryAttributesFile( const OBJECT_ATTRIBUTES *attr, FILE_BASIC_INFORMATION *info )
2336 {
2337     ANSI_STRING unix_name;
2338     NTSTATUS status;
2339
2340     if (!(status = nt_to_unix_file_name_attr( attr, &unix_name, FILE_OPEN )))
2341     {
2342         struct stat st;
2343
2344         if (stat( unix_name.Buffer, &st ) == -1)
2345             status = FILE_GetNtStatus();
2346         else if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
2347             status = STATUS_INVALID_INFO_CLASS;
2348         else
2349         {
2350             status = fill_stat_info( &st, info, FileBasicInformation );
2351             if (DIR_is_hidden_file( attr->ObjectName ))
2352                 info->FileAttributes |= FILE_ATTRIBUTE_HIDDEN;
2353         }
2354         RtlFreeAnsiString( &unix_name );
2355     }
2356     else WARN("%s not found (%x)\n", debugstr_us(attr->ObjectName), status );
2357     return status;
2358 }
2359
2360
2361 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
2362 /* helper for FILE_GetDeviceInfo to hide some platform differences in fstatfs */
2363 static inline void get_device_info_fstatfs( FILE_FS_DEVICE_INFORMATION *info, const char *fstypename,
2364                                             unsigned int flags )
2365 {
2366     if (!strcmp("cd9660", fstypename) || !strcmp("udf", fstypename))
2367     {
2368         info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
2369         /* Don't assume read-only, let the mount options set it below */
2370         info->Characteristics |= FILE_REMOVABLE_MEDIA;
2371     }
2372     else if (!strcmp("nfs", fstypename) || !strcmp("nwfs", fstypename) ||
2373              !strcmp("smbfs", fstypename) || !strcmp("afpfs", fstypename))
2374     {
2375         info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
2376         info->Characteristics |= FILE_REMOTE_DEVICE;
2377     }
2378     else if (!strcmp("procfs", fstypename))
2379         info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
2380     else
2381         info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2382
2383     if (flags & MNT_RDONLY)
2384         info->Characteristics |= FILE_READ_ONLY_DEVICE;
2385
2386     if (!(flags & MNT_LOCAL))
2387     {
2388         info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
2389         info->Characteristics |= FILE_REMOTE_DEVICE;
2390     }
2391 }
2392 #endif
2393
2394 static inline int is_device_placeholder( int fd )
2395 {
2396     static const char wine_placeholder[] = "Wine device placeholder";
2397     char buffer[sizeof(wine_placeholder)-1];
2398
2399     if (pread( fd, buffer, sizeof(wine_placeholder) - 1, 0 ) != sizeof(wine_placeholder) - 1)
2400         return 0;
2401     return !memcmp( buffer, wine_placeholder, sizeof(wine_placeholder) - 1 );
2402 }
2403
2404 /******************************************************************************
2405  *              get_device_info
2406  *
2407  * Implementation of the FileFsDeviceInformation query for NtQueryVolumeInformationFile.
2408  */
2409 static NTSTATUS get_device_info( int fd, FILE_FS_DEVICE_INFORMATION *info )
2410 {
2411     struct stat st;
2412
2413     info->Characteristics = 0;
2414     if (fstat( fd, &st ) < 0) return FILE_GetNtStatus();
2415     if (S_ISCHR( st.st_mode ))
2416     {
2417         info->DeviceType = FILE_DEVICE_UNKNOWN;
2418 #ifdef linux
2419         switch(major(st.st_rdev))
2420         {
2421         case MEM_MAJOR:
2422             info->DeviceType = FILE_DEVICE_NULL;
2423             break;
2424         case TTY_MAJOR:
2425             info->DeviceType = FILE_DEVICE_SERIAL_PORT;
2426             break;
2427         case LP_MAJOR:
2428             info->DeviceType = FILE_DEVICE_PARALLEL_PORT;
2429             break;
2430         case SCSI_TAPE_MAJOR:
2431             info->DeviceType = FILE_DEVICE_TAPE;
2432             break;
2433         }
2434 #endif
2435     }
2436     else if (S_ISBLK( st.st_mode ))
2437     {
2438         info->DeviceType = FILE_DEVICE_DISK;
2439     }
2440     else if (S_ISFIFO( st.st_mode ) || S_ISSOCK( st.st_mode ))
2441     {
2442         info->DeviceType = FILE_DEVICE_NAMED_PIPE;
2443     }
2444     else if (is_device_placeholder( fd ))
2445     {
2446         info->DeviceType = FILE_DEVICE_DISK;
2447     }
2448     else  /* regular file or directory */
2449     {
2450 #if defined(linux) && defined(HAVE_FSTATFS)
2451         struct statfs stfs;
2452
2453         /* check for floppy disk */
2454         if (major(st.st_dev) == FLOPPY_MAJOR)
2455             info->Characteristics |= FILE_REMOVABLE_MEDIA;
2456
2457         if (fstatfs( fd, &stfs ) < 0) stfs.f_type = 0;
2458         switch (stfs.f_type)
2459         {
2460         case 0x9660:      /* iso9660 */
2461         case 0x9fa1:      /* supermount */
2462         case 0x15013346:  /* udf */
2463             info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
2464             info->Characteristics |= FILE_REMOVABLE_MEDIA|FILE_READ_ONLY_DEVICE;
2465             break;
2466         case 0x6969:  /* nfs */
2467         case 0x517B:  /* smbfs */
2468         case 0x564c:  /* ncpfs */
2469             info->DeviceType = FILE_DEVICE_NETWORK_FILE_SYSTEM;
2470             info->Characteristics |= FILE_REMOTE_DEVICE;
2471             break;
2472         case 0x01021994:  /* tmpfs */
2473         case 0x28cd3d45:  /* cramfs */
2474         case 0x1373:      /* devfs */
2475         case 0x9fa0:      /* procfs */
2476             info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
2477             break;
2478         default:
2479             info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2480             break;
2481         }
2482 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__OpenBSD__) || defined(__DragonFly__) || defined(__APPLE__)
2483         struct statfs stfs;
2484
2485         if (fstatfs( fd, &stfs ) < 0)
2486             info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2487         else
2488             get_device_info_fstatfs( info, stfs.f_fstypename, stfs.f_flags );
2489 #elif defined(__NetBSD__)
2490         struct statvfs stfs;
2491
2492         if (fstatvfs( fd, &stfs) < 0)
2493             info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2494         else
2495             get_device_info_fstatfs( info, stfs.f_fstypename, stfs.f_flag );
2496 #elif defined(sun)
2497         /* Use dkio to work out device types */
2498         {
2499 # include <sys/dkio.h>
2500 # include <sys/vtoc.h>
2501             struct dk_cinfo dkinf;
2502             int retval = ioctl(fd, DKIOCINFO, &dkinf);
2503             if(retval==-1){
2504                 WARN("Unable to get disk device type information - assuming a disk like device\n");
2505                 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2506             }
2507             switch (dkinf.dki_ctype)
2508             {
2509             case DKC_CDROM:
2510                 info->DeviceType = FILE_DEVICE_CD_ROM_FILE_SYSTEM;
2511                 info->Characteristics |= FILE_REMOVABLE_MEDIA|FILE_READ_ONLY_DEVICE;
2512                 break;
2513             case DKC_NCRFLOPPY:
2514             case DKC_SMSFLOPPY:
2515             case DKC_INTEL82072:
2516             case DKC_INTEL82077:
2517                 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2518                 info->Characteristics |= FILE_REMOVABLE_MEDIA;
2519                 break;
2520             case DKC_MD:
2521                 info->DeviceType = FILE_DEVICE_VIRTUAL_DISK;
2522                 break;
2523             default:
2524                 info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2525             }
2526         }
2527 #else
2528         static int warned;
2529         if (!warned++) FIXME( "device info not properly supported on this platform\n" );
2530         info->DeviceType = FILE_DEVICE_DISK_FILE_SYSTEM;
2531 #endif
2532         info->Characteristics |= FILE_DEVICE_IS_MOUNTED;
2533     }
2534     return STATUS_SUCCESS;
2535 }
2536
2537
2538 /******************************************************************************
2539  *  NtQueryVolumeInformationFile                [NTDLL.@]
2540  *  ZwQueryVolumeInformationFile                [NTDLL.@]
2541  *
2542  * Get volume information for an open file handle.
2543  *
2544  * PARAMS
2545  *  handle      [I] Handle returned from ZwOpenFile() or ZwCreateFile()
2546  *  io          [O] Receives information about the operation on return
2547  *  buffer      [O] Destination for volume information
2548  *  length      [I] Size of FsInformation
2549  *  info_class  [I] Type of volume information to set
2550  *
2551  * RETURNS
2552  *  Success: 0. io and buffer are updated.
2553  *  Failure: An NTSTATUS error code describing the error.
2554  */
2555 NTSTATUS WINAPI NtQueryVolumeInformationFile( HANDLE handle, PIO_STATUS_BLOCK io,
2556                                               PVOID buffer, ULONG length,
2557                                               FS_INFORMATION_CLASS info_class )
2558 {
2559     int fd, needs_close;
2560     struct stat st;
2561     static int once;
2562
2563     if ((io->u.Status = server_get_unix_fd( handle, 0, &fd, &needs_close, NULL, NULL )) != STATUS_SUCCESS)
2564         return io->u.Status;
2565
2566     io->u.Status = STATUS_NOT_IMPLEMENTED;
2567     io->Information = 0;
2568
2569     switch( info_class )
2570     {
2571     case FileFsVolumeInformation:
2572         if (!once++) FIXME( "%p: volume info not supported\n", handle );
2573         break;
2574     case FileFsLabelInformation:
2575         FIXME( "%p: label info not supported\n", handle );
2576         break;
2577     case FileFsSizeInformation:
2578         if (length < sizeof(FILE_FS_SIZE_INFORMATION))
2579             io->u.Status = STATUS_BUFFER_TOO_SMALL;
2580         else
2581         {
2582             FILE_FS_SIZE_INFORMATION *info = buffer;
2583
2584             if (fstat( fd, &st ) < 0)
2585             {
2586                 io->u.Status = FILE_GetNtStatus();
2587                 break;
2588             }
2589             if (!S_ISREG(st.st_mode) && !S_ISDIR(st.st_mode))
2590             {
2591                 io->u.Status = STATUS_INVALID_DEVICE_REQUEST;
2592             }
2593             else
2594             {
2595                 ULONGLONG bsize;
2596                 /* Linux's fstatvfs is buggy */
2597 #if !defined(linux) || !defined(HAVE_FSTATFS)
2598                 struct statvfs stfs;
2599
2600                 if (fstatvfs( fd, &stfs ) < 0)
2601                 {
2602                     io->u.Status = FILE_GetNtStatus();
2603                     break;
2604                 }
2605                 bsize = stfs.f_frsize;
2606 #else
2607                 struct statfs stfs;
2608                 if (fstatfs( fd, &stfs ) < 0)
2609                 {
2610                     io->u.Status = FILE_GetNtStatus();
2611                     break;
2612                 }
2613                 bsize = stfs.f_bsize;
2614 #endif
2615                 if (bsize == 2048)  /* assume CD-ROM */
2616                 {
2617                     info->BytesPerSector = 2048;
2618                     info->SectorsPerAllocationUnit = 1;
2619                 }
2620                 else
2621                 {
2622                     info->BytesPerSector = 512;
2623                     info->SectorsPerAllocationUnit = 8;
2624                 }
2625                 info->TotalAllocationUnits.QuadPart = bsize * stfs.f_blocks / (info->BytesPerSector * info->SectorsPerAllocationUnit);
2626                 info->AvailableAllocationUnits.QuadPart = bsize * stfs.f_bavail / (info->BytesPerSector * info->SectorsPerAllocationUnit);
2627                 io->Information = sizeof(*info);
2628                 io->u.Status = STATUS_SUCCESS;
2629             }
2630         }
2631         break;
2632     case FileFsDeviceInformation:
2633         if (length < sizeof(FILE_FS_DEVICE_INFORMATION))
2634             io->u.Status = STATUS_BUFFER_TOO_SMALL;
2635         else
2636         {
2637             FILE_FS_DEVICE_INFORMATION *info = buffer;
2638
2639             if ((io->u.Status = get_device_info( fd, info )) == STATUS_SUCCESS)
2640                 io->Information = sizeof(*info);
2641         }
2642         break;
2643     case FileFsAttributeInformation:
2644         FIXME( "%p: attribute info not supported\n", handle );
2645         break;
2646     case FileFsControlInformation:
2647         FIXME( "%p: control info not supported\n", handle );
2648         break;
2649     case FileFsFullSizeInformation:
2650         FIXME( "%p: full size info not supported\n", handle );
2651         break;
2652     case FileFsObjectIdInformation:
2653         FIXME( "%p: object id info not supported\n", handle );
2654         break;
2655     case FileFsMaximumInformation:
2656         FIXME( "%p: maximum info not supported\n", handle );
2657         break;
2658     default:
2659         io->u.Status = STATUS_INVALID_PARAMETER;
2660         break;
2661     }
2662     if (needs_close) close( fd );
2663     return io->u.Status;
2664 }
2665
2666
2667 /******************************************************************
2668  *              NtQueryEaFile  (NTDLL.@)
2669  *
2670  * Read extended attributes from NTFS files.
2671  *
2672  * PARAMS
2673  *  hFile         [I] File handle, must be opened with FILE_READ_EA access
2674  *  iosb          [O] Receives information about the operation on return
2675  *  buffer        [O] Output buffer
2676  *  length        [I] Length of output buffer
2677  *  single_entry  [I] Only read and return one entry
2678  *  ea_list       [I] Optional list with names of EAs to return
2679  *  ea_list_len   [I] Length of ea_list in bytes
2680  *  ea_index      [I] Optional pointer to 1-based index of attribute to return
2681  *  restart       [I] restart EA scan
2682  *
2683  * RETURNS
2684  *  Success: 0. Atrributes read into buffer
2685  *  Failure: An NTSTATUS error code describing the error.
2686  */
2687 NTSTATUS WINAPI NtQueryEaFile( HANDLE hFile, PIO_STATUS_BLOCK iosb, PVOID buffer, ULONG length,
2688                                BOOLEAN single_entry, PVOID ea_list, ULONG ea_list_len,
2689                                PULONG ea_index, BOOLEAN restart )
2690 {
2691     FIXME("(%p,%p,%p,%d,%d,%p,%d,%p,%d) stub\n",
2692             hFile, iosb, buffer, length, single_entry, ea_list,
2693             ea_list_len, ea_index, restart);
2694     return STATUS_ACCESS_DENIED;
2695 }
2696
2697
2698 /******************************************************************
2699  *              NtSetEaFile  (NTDLL.@)
2700  *
2701  * Update extended attributes for NTFS files.
2702  *
2703  * PARAMS
2704  *  hFile         [I] File handle, must be opened with FILE_READ_EA access
2705  *  iosb          [O] Receives information about the operation on return
2706  *  buffer        [I] Buffer with EA information
2707  *  length        [I] Length of buffer
2708  *
2709  * RETURNS
2710  *  Success: 0. Attributes are updated
2711  *  Failure: An NTSTATUS error code describing the error.
2712  */
2713 NTSTATUS WINAPI NtSetEaFile( HANDLE hFile, PIO_STATUS_BLOCK iosb, PVOID buffer, ULONG length )
2714 {
2715     FIXME("(%p,%p,%p,%d) stub\n", hFile, iosb, buffer, length);
2716     return STATUS_ACCESS_DENIED;
2717 }
2718
2719
2720 /******************************************************************
2721  *              NtFlushBuffersFile  (NTDLL.@)
2722  *
2723  * Flush any buffered data on an open file handle.
2724  *
2725  * PARAMS
2726  *  FileHandle         [I] Handle returned from ZwOpenFile() or ZwCreateFile()
2727  *  IoStatusBlock      [O] Receives information about the operation on return
2728  *
2729  * RETURNS
2730  *  Success: 0. IoStatusBlock is updated.
2731  *  Failure: An NTSTATUS error code describing the error.
2732  */
2733 NTSTATUS WINAPI NtFlushBuffersFile( HANDLE hFile, IO_STATUS_BLOCK* IoStatusBlock )
2734 {
2735     NTSTATUS ret;
2736     HANDLE hEvent = NULL;
2737
2738     SERVER_START_REQ( flush_file )
2739     {
2740         req->handle = wine_server_obj_handle( hFile );
2741         ret = wine_server_call( req );
2742         hEvent = wine_server_ptr_handle( reply->event );
2743     }
2744     SERVER_END_REQ;
2745     if (!ret && hEvent)
2746     {
2747         ret = NtWaitForSingleObject( hEvent, FALSE, NULL );
2748         NtClose( hEvent );
2749     }
2750     return ret;
2751 }
2752
2753 /******************************************************************
2754  *              NtLockFile       (NTDLL.@)
2755  *
2756  *
2757  */
2758 NTSTATUS WINAPI NtLockFile( HANDLE hFile, HANDLE lock_granted_event,
2759                             PIO_APC_ROUTINE apc, void* apc_user,
2760                             PIO_STATUS_BLOCK io_status, PLARGE_INTEGER offset,
2761                             PLARGE_INTEGER count, ULONG* key, BOOLEAN dont_wait,
2762                             BOOLEAN exclusive )
2763 {
2764     NTSTATUS    ret;
2765     HANDLE      handle;
2766     BOOLEAN     async;
2767     static BOOLEAN     warn = TRUE;
2768
2769     if (apc || io_status || key)
2770     {
2771         FIXME("Unimplemented yet parameter\n");
2772         return STATUS_NOT_IMPLEMENTED;
2773     }
2774
2775     if (apc_user && warn)
2776     {
2777         FIXME("I/O completion on lock not implemented yet\n");
2778         warn = FALSE;
2779     }
2780
2781     for (;;)
2782     {
2783         SERVER_START_REQ( lock_file )
2784         {
2785             req->handle      = wine_server_obj_handle( hFile );
2786             req->offset      = offset->QuadPart;
2787             req->count       = count->QuadPart;
2788             req->shared      = !exclusive;
2789             req->wait        = !dont_wait;
2790             ret = wine_server_call( req );
2791             handle = wine_server_ptr_handle( reply->handle );
2792             async  = reply->overlapped;
2793         }
2794         SERVER_END_REQ;
2795         if (ret != STATUS_PENDING)
2796         {
2797             if (!ret && lock_granted_event) NtSetEvent(lock_granted_event, NULL);
2798             return ret;
2799         }
2800
2801         if (async)
2802         {
2803             FIXME( "Async I/O lock wait not implemented, might deadlock\n" );
2804             if (handle) NtClose( handle );
2805             return STATUS_PENDING;
2806         }
2807         if (handle)
2808         {
2809             NtWaitForSingleObject( handle, FALSE, NULL );
2810             NtClose( handle );
2811         }
2812         else
2813         {
2814             LARGE_INTEGER time;
2815     
2816             /* Unix lock conflict, sleep a bit and retry */
2817             time.QuadPart = 100 * (ULONGLONG)10000;
2818             time.QuadPart = -time.QuadPart;
2819             NtDelayExecution( FALSE, &time );
2820         }
2821     }
2822 }
2823
2824
2825 /******************************************************************
2826  *              NtUnlockFile    (NTDLL.@)
2827  *
2828  *
2829  */
2830 NTSTATUS WINAPI NtUnlockFile( HANDLE hFile, PIO_STATUS_BLOCK io_status,
2831                               PLARGE_INTEGER offset, PLARGE_INTEGER count,
2832                               PULONG key )
2833 {
2834     NTSTATUS status;
2835
2836     TRACE( "%p %x%08x %x%08x\n",
2837            hFile, offset->u.HighPart, offset->u.LowPart, count->u.HighPart, count->u.LowPart );
2838
2839     if (io_status || key)
2840     {
2841         FIXME("Unimplemented yet parameter\n");
2842         return STATUS_NOT_IMPLEMENTED;
2843     }
2844
2845     SERVER_START_REQ( unlock_file )
2846     {
2847         req->handle = wine_server_obj_handle( hFile );
2848         req->offset = offset->QuadPart;
2849         req->count  = count->QuadPart;
2850         status = wine_server_call( req );
2851     }
2852     SERVER_END_REQ;
2853     return status;
2854 }
2855
2856 /******************************************************************
2857  *              NtCreateNamedPipeFile    (NTDLL.@)
2858  *
2859  *
2860  */
2861 NTSTATUS WINAPI NtCreateNamedPipeFile( PHANDLE handle, ULONG access,
2862                                        POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK iosb,
2863                                        ULONG sharing, ULONG dispo, ULONG options,
2864                                        ULONG pipe_type, ULONG read_mode, 
2865                                        ULONG completion_mode, ULONG max_inst,
2866                                        ULONG inbound_quota, ULONG outbound_quota,
2867                                        PLARGE_INTEGER timeout)
2868 {
2869     NTSTATUS    status;
2870
2871     TRACE("(%p %x %s %p %x %d %x %d %d %d %d %d %d %p)\n",
2872           handle, access, debugstr_w(attr->ObjectName->Buffer), iosb, sharing, dispo,
2873           options, pipe_type, read_mode, completion_mode, max_inst, inbound_quota,
2874           outbound_quota, timeout);
2875
2876     /* assume we only get relative timeout */
2877     if (timeout->QuadPart > 0)
2878         FIXME("Wrong time %s\n", wine_dbgstr_longlong(timeout->QuadPart));
2879
2880     SERVER_START_REQ( create_named_pipe )
2881     {
2882         req->access  = access;
2883         req->attributes = attr->Attributes;
2884         req->rootdir = wine_server_obj_handle( attr->RootDirectory );
2885         req->options = options;
2886         req->sharing = sharing;
2887         req->flags = 
2888             (pipe_type ? NAMED_PIPE_MESSAGE_STREAM_WRITE   : 0) |
2889             (read_mode ? NAMED_PIPE_MESSAGE_STREAM_READ    : 0) |
2890             (completion_mode ? NAMED_PIPE_NONBLOCKING_MODE : 0);
2891         req->maxinstances = max_inst;
2892         req->outsize = outbound_quota;
2893         req->insize  = inbound_quota;
2894         req->timeout = timeout->QuadPart;
2895         wine_server_add_data( req, attr->ObjectName->Buffer,
2896                               attr->ObjectName->Length );
2897         status = wine_server_call( req );
2898         if (!status) *handle = wine_server_ptr_handle( reply->handle );
2899     }
2900     SERVER_END_REQ;
2901     return status;
2902 }
2903
2904 /******************************************************************
2905  *              NtDeleteFile    (NTDLL.@)
2906  *
2907  *
2908  */
2909 NTSTATUS WINAPI NtDeleteFile( POBJECT_ATTRIBUTES ObjectAttributes )
2910 {
2911     NTSTATUS status;
2912     HANDLE hFile;
2913     IO_STATUS_BLOCK io;
2914
2915     TRACE("%p\n", ObjectAttributes);
2916     status = NtCreateFile( &hFile, GENERIC_READ | GENERIC_WRITE | DELETE,
2917                            ObjectAttributes, &io, NULL, 0,
2918                            FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 
2919                            FILE_OPEN, FILE_DELETE_ON_CLOSE, NULL, 0 );
2920     if (status == STATUS_SUCCESS) status = NtClose(hFile);
2921     return status;
2922 }
2923
2924 /******************************************************************
2925  *              NtCancelIoFileEx    (NTDLL.@)
2926  *
2927  *
2928  */
2929 NTSTATUS WINAPI NtCancelIoFileEx( HANDLE hFile, PIO_STATUS_BLOCK iosb, PIO_STATUS_BLOCK io_status )
2930 {
2931     LARGE_INTEGER timeout;
2932
2933     TRACE("%p %p %p\n", hFile, iosb, io_status );
2934
2935     SERVER_START_REQ( cancel_async )
2936     {
2937         req->handle      = wine_server_obj_handle( hFile );
2938         req->iosb        = wine_server_client_ptr( iosb );
2939         req->only_thread = FALSE;
2940         io_status->u.Status = wine_server_call( req );
2941     }
2942     SERVER_END_REQ;
2943     if (io_status->u.Status)
2944         return io_status->u.Status;
2945
2946     /* Let some APC be run, so that we can run the remaining APCs on hFile
2947      * either the cancelation of the pending one, but also the execution
2948      * of the queued APC, but not yet run. This is needed to ensure proper
2949      * clean-up of allocated data.
2950      */
2951     timeout.QuadPart = 0;
2952     NtDelayExecution( TRUE, &timeout );
2953     return io_status->u.Status;
2954 }
2955
2956 /******************************************************************
2957  *              NtCancelIoFile    (NTDLL.@)
2958  *
2959  *
2960  */
2961 NTSTATUS WINAPI NtCancelIoFile( HANDLE hFile, PIO_STATUS_BLOCK io_status )
2962 {
2963     LARGE_INTEGER timeout;
2964
2965     TRACE("%p %p\n", hFile, io_status );
2966
2967     SERVER_START_REQ( cancel_async )
2968     {
2969         req->handle      = wine_server_obj_handle( hFile );
2970         req->iosb        = 0;
2971         req->only_thread = TRUE;
2972         io_status->u.Status = wine_server_call( req );
2973     }
2974     SERVER_END_REQ;
2975     if (io_status->u.Status)
2976         return io_status->u.Status;
2977
2978     /* Let some APC be run, so that we can run the remaining APCs on hFile
2979      * either the cancelation of the pending one, but also the execution
2980      * of the queued APC, but not yet run. This is needed to ensure proper
2981      * clean-up of allocated data.
2982      */
2983     timeout.QuadPart = 0;
2984     NtDelayExecution( TRUE, &timeout );
2985     return io_status->u.Status;
2986 }
2987
2988 /******************************************************************************
2989  *  NtCreateMailslotFile        [NTDLL.@]
2990  *  ZwCreateMailslotFile        [NTDLL.@]
2991  *
2992  * PARAMS
2993  *  pHandle          [O] pointer to receive the handle created
2994  *  DesiredAccess    [I] access mode (read, write, etc)
2995  *  ObjectAttributes [I] fully qualified NT path of the mailslot
2996  *  IoStatusBlock    [O] receives completion status and other info
2997  *  CreateOptions    [I]
2998  *  MailslotQuota    [I]
2999  *  MaxMessageSize   [I]
3000  *  TimeOut          [I]
3001  *
3002  * RETURNS
3003  *  An NT status code
3004  */
3005 NTSTATUS WINAPI NtCreateMailslotFile(PHANDLE pHandle, ULONG DesiredAccess,
3006      POBJECT_ATTRIBUTES attr, PIO_STATUS_BLOCK IoStatusBlock,
3007      ULONG CreateOptions, ULONG MailslotQuota, ULONG MaxMessageSize,
3008      PLARGE_INTEGER TimeOut)
3009 {
3010     LARGE_INTEGER timeout;
3011     NTSTATUS ret;
3012
3013     TRACE("%p %08x %p %p %08x %08x %08x %p\n",
3014               pHandle, DesiredAccess, attr, IoStatusBlock,
3015               CreateOptions, MailslotQuota, MaxMessageSize, TimeOut);
3016
3017     if (!pHandle) return STATUS_ACCESS_VIOLATION;
3018     if (!attr) return STATUS_INVALID_PARAMETER;
3019     if (!attr->ObjectName) return STATUS_OBJECT_PATH_SYNTAX_BAD;
3020
3021     /*
3022      *  For a NULL TimeOut pointer set the default timeout value
3023      */
3024     if  (!TimeOut)
3025         timeout.QuadPart = -1;
3026     else
3027         timeout.QuadPart = TimeOut->QuadPart;
3028
3029     SERVER_START_REQ( create_mailslot )
3030     {
3031         req->access = DesiredAccess;
3032         req->attributes = attr->Attributes;
3033         req->rootdir = wine_server_obj_handle( attr->RootDirectory );
3034         req->max_msgsize = MaxMessageSize;
3035         req->read_timeout = timeout.QuadPart;
3036         wine_server_add_data( req, attr->ObjectName->Buffer,
3037                               attr->ObjectName->Length );
3038         ret = wine_server_call( req );
3039         if( ret == STATUS_SUCCESS )
3040             *pHandle = wine_server_ptr_handle( reply->handle );
3041     }
3042     SERVER_END_REQ;
3043  
3044     return ret;
3045 }