OSDN Git Service

* path.cc (conv_path_list): Take cygwin_conv_path_t as third parameter.
[pf3gnuchains/pf3gnuchains4x.git] / winsup / cygwin / fhandler.cc
1 /* fhandler.cc.  See console.cc for fhandler_console functions.
2
3    Copyright 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4    2005, 2006, 2007, 2008, 2009, 2010, 2011 Red Hat, Inc.
5
6 This file is part of Cygwin.
7
8 This software is a copyrighted work licensed under the terms of the
9 Cygwin license.  Please consult the file "CYGWIN_LICENSE" for
10 details. */
11
12 #include "winsup.h"
13 #include <unistd.h>
14 #include <stdlib.h>
15 #include <sys/uio.h>
16 #include <sys/acl.h>
17 #include "cygerrno.h"
18 #include "perprocess.h"
19 #include "security.h"
20 #include "cygwin/version.h"
21 #include "path.h"
22 #include "fhandler.h"
23 #include "dtable.h"
24 #include "cygheap.h"
25 #include "pinfo.h"
26 #include <assert.h>
27 #include <winioctl.h>
28 #include "ntdll.h"
29 #include "cygtls.h"
30 #include "sigproc.h"
31 #include "shared_info.h"
32 #include <asm/socket.h>
33
34 #define MAX_OVERLAPPED_WRITE_LEN (64 * 1024 * 1024)
35 #define MIN_OVERLAPPED_WRITE_LEN (1 * 1024 * 1024)
36
37 static const int CHUNK_SIZE = 1024; /* Used for crlf conversions */
38
39 struct __cygwin_perfile *perfile_table;
40
41 HANDLE NO_COPY fhandler_base_overlapped::asio_done;
42 LONG NO_COPY fhandler_base_overlapped::asio_close_counter;
43
44 void
45 fhandler_base::reset (const fhandler_base *from)
46 {
47   pc << from->pc;
48   rabuf = NULL;
49   ralen = 0;
50   raixget = 0;
51   raixput = 0;
52   rabuflen = 0;
53 }
54
55 int
56 fhandler_base::puts_readahead (const char *s, size_t len)
57 {
58   int success = 1;
59   while ((len == (size_t) -1 ? *s : len--)
60          && (success = put_readahead (*s++) > 0))
61     continue;
62   return success;
63 }
64
65 int
66 fhandler_base::put_readahead (char value)
67 {
68   char *newrabuf;
69   if (raixput < rabuflen)
70     /* Nothing to do */;
71   else if ((newrabuf = (char *) realloc (rabuf, rabuflen += 32)))
72     rabuf = newrabuf;
73   else
74     return 0;
75
76   rabuf[raixput++] = value;
77   ralen++;
78   return 1;
79 }
80
81 int
82 fhandler_base::get_readahead ()
83 {
84   int chret = -1;
85   if (raixget < ralen)
86     chret = ((unsigned char) rabuf[raixget++]) & 0xff;
87   /* FIXME - not thread safe */
88   if (raixget >= ralen)
89     raixget = raixput = ralen = 0;
90   return chret;
91 }
92
93 int
94 fhandler_base::peek_readahead (int queryput)
95 {
96   int chret = -1;
97   if (!queryput && raixget < ralen)
98     chret = ((unsigned char) rabuf[raixget]) & 0xff;
99   else if (queryput && raixput > 0)
100     chret = ((unsigned char) rabuf[raixput - 1]) & 0xff;
101   return chret;
102 }
103
104 void
105 fhandler_base::set_readahead_valid (int val, int ch)
106 {
107   if (!val)
108     ralen = raixget = raixput = 0;
109   if (ch != -1)
110     put_readahead (ch);
111 }
112
113 int
114 fhandler_base::eat_readahead (int n)
115 {
116   int oralen = ralen;
117   if (n < 0)
118     n = ralen;
119   if (n > 0 && ralen)
120     {
121       if ((int) (ralen -= n) < 0)
122         ralen = 0;
123
124       if (raixget >= ralen)
125         raixget = raixput = ralen = 0;
126       else if (raixput > ralen)
127         raixput = ralen;
128     }
129
130   return oralen;
131 }
132
133 int
134 fhandler_base::get_readahead_into_buffer (char *buf, size_t buflen)
135 {
136   int ch;
137   int copied_chars = 0;
138
139   while (buflen)
140     if ((ch = get_readahead ()) < 0)
141       break;
142     else
143       {
144         buf[copied_chars++] = (unsigned char)(ch & 0xff);
145         buflen--;
146       }
147
148   return copied_chars;
149 }
150
151 /* Record the file name. and name hash */
152 void
153 fhandler_base::set_name (path_conv &in_pc)
154 {
155   pc << in_pc;
156 }
157
158 char *fhandler_base::get_proc_fd_name (char *buf)
159 {
160   if (get_name ())
161     return strcpy (buf, get_name ());
162   if (dev ().name)
163     return strcpy (buf, dev ().name);
164   return strcpy (buf, "");
165 }
166
167 /* Detect if we are sitting at EOF for conditions where Windows
168    returns an error but UNIX doesn't.  */
169 int __stdcall
170 is_at_eof (HANDLE h)
171 {
172   IO_STATUS_BLOCK io;
173   FILE_POSITION_INFORMATION fpi;
174   FILE_STANDARD_INFORMATION fsi;
175
176   if (NT_SUCCESS (NtQueryInformationFile (h, &io, &fsi, sizeof fsi,
177                                           FileStandardInformation))
178       && NT_SUCCESS (NtQueryInformationFile (h, &io, &fpi, sizeof fpi,
179                                              FilePositionInformation))
180       && fsi.EndOfFile.QuadPart == fpi.CurrentByteOffset.QuadPart)
181     return 1;
182   return 0;
183 }
184
185 void
186 fhandler_base::set_flags (int flags, int supplied_bin)
187 {
188   int bin;
189   int fmode;
190   debug_printf ("flags %p, supplied_bin %p", flags, supplied_bin);
191   if ((bin = flags & (O_BINARY | O_TEXT)))
192     debug_printf ("O_TEXT/O_BINARY set in flags %p", bin);
193   else if (rbinset () && wbinset ())
194     bin = rbinary () ? O_BINARY : O_TEXT;       // FIXME: Not quite right
195   else if ((fmode = get_default_fmode (flags)) & O_BINARY)
196     bin = O_BINARY;
197   else if (fmode & O_TEXT)
198     bin = O_TEXT;
199   else if (supplied_bin)
200     bin = supplied_bin;
201   else
202     bin = wbinary () || rbinary () ? O_BINARY : O_TEXT;
203
204   openflags = flags | bin;
205
206   bin &= O_BINARY;
207   rbinary (bin ? true : false);
208   wbinary (bin ? true : false);
209   syscall_printf ("filemode set to %s", bin ? "binary" : "text");
210 }
211
212 /* Normal file i/o handlers.  */
213
214 /* Cover function to ReadFile to achieve (as much as possible) Posix style
215    semantics and use of errno.  */
216 void __stdcall
217 fhandler_base::raw_read (void *ptr, size_t& ulen)
218 {
219 #define bytes_read ulen
220
221   int try_noreserve = 1;
222   DWORD len = ulen;
223
224 retry:
225   ulen = (size_t) -1;
226   BOOL res = ReadFile (get_handle (), ptr, len, (DWORD *) &ulen, NULL);
227   if (!res)
228     {
229       /* Some errors are not really errors.  Detect such cases here.  */
230
231       DWORD  errcode = GetLastError ();
232       switch (errcode)
233         {
234         case ERROR_BROKEN_PIPE:
235           /* This is really EOF.  */
236           bytes_read = 0;
237           break;
238         case ERROR_MORE_DATA:
239           /* `bytes_read' is supposedly valid.  */
240           break;
241         case ERROR_NOACCESS:
242           if (is_at_eof (get_handle ()))
243             {
244               bytes_read = 0;
245               break;
246             }
247           if (try_noreserve)
248             {
249               try_noreserve = 0;
250               switch (mmap_is_attached_or_noreserve (ptr, len))
251                 {
252                 case MMAP_NORESERVE_COMMITED:
253                   goto retry;
254                 case MMAP_RAISE_SIGBUS:
255                   raise(SIGBUS);
256                 case MMAP_NONE:
257                   break;
258                 }
259             }
260           /*FALLTHRU*/
261         case ERROR_INVALID_FUNCTION:
262         case ERROR_INVALID_PARAMETER:
263         case ERROR_INVALID_HANDLE:
264           if (pc.isdir ())
265             {
266               set_errno (EISDIR);
267               bytes_read = (size_t) -1;
268               break;
269             }
270         default:
271           syscall_printf ("ReadFile %s(%p) failed, %E", get_name (), get_handle ());
272           __seterrno_from_win_error (errcode);
273           bytes_read = (size_t) -1;
274           break;
275         }
276     }
277 #undef bytes_read
278 }
279
280 /* Cover function to WriteFile to provide Posix interface and semantics
281    (as much as possible).  */
282 ssize_t __stdcall
283 fhandler_base::raw_write (const void *ptr, size_t len)
284 {
285   NTSTATUS status;
286   IO_STATUS_BLOCK io;
287   static _RDATA LARGE_INTEGER off_current =
288                           { QuadPart:FILE_USE_FILE_POINTER_POSITION };
289   static _RDATA LARGE_INTEGER off_append =
290                           { QuadPart:FILE_WRITE_TO_END_OF_FILE };
291
292   status = NtWriteFile (get_output_handle (), NULL, NULL, NULL, &io,
293                         (PVOID) ptr, len,
294                         (get_flags () & O_APPEND) ? &off_append : &off_current,
295                         NULL);
296   if (!NT_SUCCESS (status))
297     {
298       __seterrno_from_nt_status (status);
299       if (get_errno () == EPIPE)
300         raise (SIGPIPE);
301       return -1;
302     }
303   return io.Information;
304 }
305
306 int
307 fhandler_base::get_default_fmode (int flags)
308 {
309   int fmode = __fmode;
310   if (perfile_table)
311     {
312       size_t nlen = strlen (get_name ());
313       unsigned accflags = (flags & O_ACCMODE);
314       for (__cygwin_perfile *pf = perfile_table; pf->name; pf++)
315         if (!*pf->name && (pf->flags & O_ACCMODE) == accflags)
316           {
317             fmode = pf->flags & ~O_ACCMODE;
318             break;
319           }
320         else
321           {
322             size_t pflen = strlen (pf->name);
323             const char *stem = get_name () + nlen - pflen;
324             if (pflen > nlen || (stem != get_name () && !isdirsep (stem[-1])))
325               continue;
326             else if ((pf->flags & O_ACCMODE) == accflags
327                      && pathmatch (stem, pf->name, !!pc.objcaseinsensitive ()))
328               {
329                 fmode = pf->flags & ~O_ACCMODE;
330                 break;
331               }
332           }
333     }
334   return fmode;
335 }
336
337 bool
338 fhandler_base::device_access_denied (int flags)
339 {
340   int mode = 0;
341
342   if (flags & O_RDWR)
343     mode |= R_OK | W_OK;
344   if (flags & (O_WRONLY | O_APPEND))
345     mode |= W_OK;
346   if (!mode)
347     mode |= R_OK;
348
349   return fhaccess (mode, true);
350 }
351
352 int
353 fhandler_base::fhaccess (int flags, bool effective)
354 {
355   int res = -1;
356   if (error ())
357     {
358       set_errno (error ());
359       goto done;
360     }
361
362   if (!exists ())
363     {
364       set_errno (ENOENT);
365       goto done;
366     }
367
368   if (!(flags & (R_OK | W_OK | X_OK)))
369     return 0;
370
371   if (is_fs_special ())
372     /* short circuit */;
373   else if (has_attribute (FILE_ATTRIBUTE_READONLY) && (flags & W_OK)
374            && !pc.isdir ())
375     goto eaccess_done;
376   else if (has_acls ())
377     {
378       res = check_file_access (pc, flags, effective);
379       goto done;
380     }
381   else if (get_device () == FH_REGISTRY && open (O_RDONLY, 0) && get_handle ())
382     {
383       res = check_registry_access (get_handle (), flags, effective);
384       close ();
385       return res;
386     }
387
388   struct __stat64 st;
389   if (fstat (&st))
390     goto done;
391
392   if (flags & R_OK)
393     {
394       if (st.st_uid == (effective ? myself->uid : cygheap->user.real_uid))
395         {
396           if (!(st.st_mode & S_IRUSR))
397             goto eaccess_done;
398         }
399       else if (st.st_gid == (effective ? myself->gid : cygheap->user.real_gid))
400         {
401           if (!(st.st_mode & S_IRGRP))
402             goto eaccess_done;
403         }
404       else if (!(st.st_mode & S_IROTH))
405         goto eaccess_done;
406     }
407
408   if (flags & W_OK)
409     {
410       if (st.st_uid == (effective ? myself->uid : cygheap->user.real_uid))
411         {
412           if (!(st.st_mode & S_IWUSR))
413             goto eaccess_done;
414         }
415       else if (st.st_gid == (effective ? myself->gid : cygheap->user.real_gid))
416         {
417           if (!(st.st_mode & S_IWGRP))
418             goto eaccess_done;
419         }
420       else if (!(st.st_mode & S_IWOTH))
421         goto eaccess_done;
422     }
423
424   if (flags & X_OK)
425     {
426       if (st.st_uid == (effective ? myself->uid : cygheap->user.real_uid))
427         {
428           if (!(st.st_mode & S_IXUSR))
429             goto eaccess_done;
430         }
431       else if (st.st_gid == (effective ? myself->gid : cygheap->user.real_gid))
432         {
433           if (!(st.st_mode & S_IXGRP))
434             goto eaccess_done;
435         }
436       else if (!(st.st_mode & S_IXOTH))
437         goto eaccess_done;
438     }
439
440   res = 0;
441   goto done;
442
443 eaccess_done:
444   set_errno (EACCES);
445 done:
446   if (!res && (flags & W_OK) && get_device () == FH_FS
447       && (pc.fs_flags () & FILE_READ_ONLY_VOLUME))
448     {
449       set_errno (EROFS);
450       res = -1;
451     }
452   debug_printf ("returning %d", res);
453   return res;
454 }
455
456 int
457 fhandler_base::open_with_arch (int flags, mode_t mode)
458 {
459   int res;
460   if (!(res = (archetype && archetype->io_handle)
461         || open (flags, (mode & 07777) & ~cygheap->umask)))
462     {
463       if (archetype)
464         delete archetype;
465     }
466   else if (archetype)
467     {
468       if (!archetype->get_io_handle ())
469         {
470           copyto (archetype);
471           archetype_usecount (1);
472           archetype->archetype = NULL;
473           usecount = 0;
474         }
475       else
476         {
477           char *name;
478           /* Preserve any name (like /dev/tty) derived from build_fh_pc. */
479           if (!get_name ())
480             name = NULL;
481           else
482             {
483               name = (char *) alloca (strlen (get_name ()) + 1);
484               strcpy (name, get_name ());
485             }
486           fhandler_base *arch = archetype;
487           archetype->copyto (this);
488           if (name)
489             set_name (name);
490           archetype = arch;
491           archetype_usecount (1);
492           usecount = 0;
493         }
494       open_setup (flags);
495     }
496
497   close_on_exec (flags & O_CLOEXEC);
498   return res;
499 }
500
501 /* Open system call handler function. */
502 int
503 fhandler_base::open (int flags, mode_t mode)
504 {
505   int res = 0;
506   HANDLE fh;
507   ULONG file_attributes = 0;
508   ULONG shared = (get_major () == DEV_TAPE_MAJOR ? 0 : FILE_SHARE_VALID_FLAGS);
509   ULONG create_disposition;
510   OBJECT_ATTRIBUTES attr;
511   IO_STATUS_BLOCK io;
512   NTSTATUS status;
513   PFILE_FULL_EA_INFORMATION p = NULL;
514   ULONG plen = 0;
515
516   syscall_printf ("(%S, %p)", pc.get_nt_native_path (), flags);
517
518   pc.get_object_attr (attr, *sec_none_cloexec (flags));
519
520   options = FILE_OPEN_FOR_BACKUP_INTENT;
521   switch (query_open ())
522     {
523       case query_read_control:
524         access = READ_CONTROL;
525         break;
526       case query_read_attributes:
527         access = READ_CONTROL | FILE_READ_ATTRIBUTES;
528         break;
529       case query_write_control:
530         access = READ_CONTROL | WRITE_OWNER | WRITE_DAC | FILE_WRITE_ATTRIBUTES;
531         break;
532       case query_write_dac:
533         access = READ_CONTROL | WRITE_DAC | FILE_WRITE_ATTRIBUTES;
534         break;
535       case query_write_attributes:
536         access = READ_CONTROL | FILE_WRITE_ATTRIBUTES;
537         break;
538       default:
539         if ((flags & O_ACCMODE) == O_RDONLY)
540           access = GENERIC_READ;
541         else if ((flags & O_ACCMODE) == O_WRONLY)
542           access = GENERIC_WRITE | READ_CONTROL | FILE_READ_ATTRIBUTES;
543         else
544           access = GENERIC_READ | GENERIC_WRITE;
545         if (flags & O_SYNC)
546           options |= FILE_WRITE_THROUGH;
547         if (flags & O_DIRECT)
548           options |= FILE_NO_INTERMEDIATE_BUFFERING;
549         if (get_major () != DEV_SERIAL_MAJOR && get_major () != DEV_TAPE_MAJOR)
550           {
551             options |= FILE_SYNCHRONOUS_IO_NONALERT;
552             access |= SYNCHRONIZE;
553           }
554         break;
555     }
556
557   /* Don't use the FILE_OVERWRITE{_IF} flags here.  See below for an
558      explanation, why that's not such a good idea. */
559   if ((flags & O_EXCL) && (flags & O_CREAT))
560     create_disposition = FILE_CREATE;
561   else
562     create_disposition = (flags & O_CREAT) ? FILE_OPEN_IF : FILE_OPEN;
563
564   if (get_device () == FH_FS)
565     {
566       /* Add the reparse point flag to native symlinks, otherwise we open the
567          target, not the symlink.  This would break lstat. */
568       if (pc.is_rep_symlink ())
569         options |= FILE_OPEN_REPARSE_POINT;
570
571       if (pc.fs_is_nfs ())
572         {
573           /* Make sure we can read EAs of files on an NFS share.  Also make
574              sure that we're going to act on the file itself, even if it's a
575              a symlink. */
576           access |= FILE_READ_EA;
577           if (query_open ())
578             {
579               if (query_open () >= query_write_control)
580                 access |=  FILE_WRITE_EA;
581               plen = sizeof nfs_aol_ffei;
582               p = (PFILE_FULL_EA_INFORMATION) &nfs_aol_ffei;
583             }
584         }
585
586       /* Starting with Windows 2000, when trying to overwrite an already
587          existing file with FILE_ATTRIBUTE_HIDDEN and/or FILE_ATTRIBUTE_SYSTEM
588          attribute set, CreateFile fails with ERROR_ACCESS_DENIED.
589          Per MSDN you have to create the file with the same attributes as
590          already specified for the file. */
591       if (((flags & O_CREAT) || create_disposition == FILE_OVERWRITE)
592           && has_attribute (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM))
593         file_attributes |= pc.file_attributes ();
594
595       if (flags & O_CREAT)
596         {
597           file_attributes |= FILE_ATTRIBUTE_NORMAL;
598
599           if (pc.fs_is_nfs ())
600             {
601               /* When creating a file on an NFS share, we have to set the
602                  file mode by writing a NFS fattr3 structure with the
603                  correct mode bits set. */
604               access |= FILE_WRITE_EA;
605               plen = sizeof (FILE_FULL_EA_INFORMATION) + sizeof (NFS_V3_ATTR)
606                      + sizeof (fattr3);
607               p = (PFILE_FULL_EA_INFORMATION) alloca (plen);
608               p->NextEntryOffset = 0;
609               p->Flags = 0;
610               p->EaNameLength = sizeof (NFS_V3_ATTR) - 1;
611               p->EaValueLength = sizeof (fattr3);
612               strcpy (p->EaName, NFS_V3_ATTR);
613               fattr3 *nfs_attr = (fattr3 *) (p->EaName
614                                              + p->EaNameLength + 1);
615               memset (nfs_attr, 0, sizeof (fattr3));
616               nfs_attr->type = NF3REG;
617               nfs_attr->mode = mode;
618             }
619           else if (!has_acls () && !(mode & (S_IWUSR | S_IWGRP | S_IWOTH)))
620             /* If mode has no write bits set, and ACLs are not used, we set
621                the DOS R/O attribute. */
622             file_attributes |= FILE_ATTRIBUTE_READONLY;
623           /* The file attributes are needed for later use in, e.g. fchmod. */
624           pc.file_attributes (file_attributes);
625           /* Never set the WRITE_DAC flag here.  Calls to fstat may return
626              wrong st_ctime information after calls to fchmod, fchown, etc
627              because Windows only gurantees to update the metadata when
628              the handle is closed or flushed.  However, flushing the file
629              on every fstat to enforce POSIXy stat behaviour is exceessivly
630              slow, compared to open/close the file when changing the file's
631              security descriptor. */
632         }
633     }
634
635   status = NtCreateFile (&fh, access, &attr, &io, NULL, file_attributes, shared,
636                          create_disposition, options, p, plen);
637   if (!NT_SUCCESS (status))
638     {
639       /* Trying to create a directory should return EISDIR, not ENOENT. */
640       PUNICODE_STRING upath = pc.get_nt_native_path ();
641       if (status == STATUS_OBJECT_NAME_INVALID && (flags & O_CREAT)
642           && upath->Buffer[upath->Length / sizeof (WCHAR) - 1] == '\\')
643         set_errno (EISDIR);
644       else
645         __seterrno_from_nt_status (status);
646       if (!nohandle ())
647         goto done;
648    }
649
650   /* Always create files using a NULL SD.  Create correct permission bits
651      afterwards, maintaining the owner and group information just like chmod.
652
653      This is done for two reasons.
654
655      On Windows filesystems we need to create the file with default
656      permissions to allow inheriting ACEs.  When providing an explicit DACL
657      in calls to [Nt]CreateFile, the created file will not inherit default
658      permissions from the parent object.  This breaks not only Windows
659      inheritance, but also POSIX ACL inheritance.
660
661      Another reason to do this are remote shares.  Files on a remote share
662      are created as the user used for authentication.  In a domain that's
663      usually the user you're logged in as.  Outside of a domain you're
664      authenticating using a local user account on the sharing machine.
665      If the SIDs of the client machine are used, that's entirely
666      unexpected behaviour.  Doing it like we do here creates the expected SD
667      in a domain as well as on standalone servers.
668      This is the result of a discussion on the samba-technical list, starting at
669      http://lists.samba.org/archive/samba-technical/2008-July/060247.html */
670   if (io.Information == FILE_CREATED && has_acls ())
671     set_file_attribute (fh, pc, ILLEGAL_UID, ILLEGAL_GID, S_JUSTCREATED | mode);
672
673   /* If you O_TRUNC a file on Linux, the data is truncated, but the EAs are
674      preserved.  If you open a file on Windows with FILE_OVERWRITE{_IF} or
675      FILE_SUPERSEDE, all streams are truncated, including the EAs.  So we don't
676      use the FILE_OVERWRITE{_IF} flags, but instead just open the file and set
677      the size of the data stream explicitely to 0.  Apart from being more Linux
678      compatible, this implementation has the pleasant side-effect to be more
679      than 5% faster than using FILE_OVERWRITE{_IF} (tested on W7 32 bit). */
680   if ((flags & O_TRUNC)
681       && (flags & O_ACCMODE) != O_RDONLY
682       && io.Information != FILE_CREATED
683       && get_device () == FH_FS)
684     {
685       FILE_END_OF_FILE_INFORMATION feofi = { EndOfFile:{ QuadPart:0 } };
686       status = NtSetInformationFile (fh, &io, &feofi, sizeof feofi,
687                                      FileEndOfFileInformation);
688       /* In theory, truncating the file should never fail, since the opened
689          handle has FILE_WRITE_DATA permissions, which is all you need to
690          be allowed to truncate a file.  Better safe than sorry. */
691       if (!NT_SUCCESS (status))
692         {
693           __seterrno_from_nt_status (status);
694           NtClose (fh);
695           goto done;
696         }
697     }
698
699   set_io_handle (fh);
700   set_flags (flags, pc.binmode ());
701
702   res = 1;
703   set_open_status ();
704 done:
705   debug_printf ("%x = NtCreateFile "
706                 "(%p, %x, %S, io, NULL, %x, %x, %x, %x, NULL, 0)",
707                 status, fh, access, pc.get_nt_native_path (), file_attributes,
708                 shared, create_disposition, options);
709
710   syscall_printf ("%d = fhandler_base::open (%S, %p)",
711                   res, pc.get_nt_native_path (), flags);
712   return res;
713 }
714
715 /* states:
716    open buffer in binary mode?  Just do the read.
717
718    open buffer in text mode?  Scan buffer for control zs and handle
719    the first one found.  Then scan buffer, converting every \r\n into
720    an \n.  If last char is an \r, look ahead one more char, if \n then
721    modify \r, if not, remember char.
722 */
723 void __stdcall
724 fhandler_base::read (void *in_ptr, size_t& len)
725 {
726   char *ptr = (char *) in_ptr;
727   ssize_t copied_chars = get_readahead_into_buffer (ptr, len);
728
729   if (copied_chars)
730     {
731       len = (size_t) copied_chars;
732       goto out;
733     }
734
735   len -= copied_chars;
736   if (!len)
737     {
738       len = (size_t) copied_chars;
739       goto out;
740     }
741
742   raw_read (ptr + copied_chars, len);
743   if (!copied_chars)
744     /* nothing */;
745   else if ((ssize_t) len > 0)
746     len += copied_chars;
747   else
748     len = copied_chars;
749
750   if (rbinary () || (ssize_t) len <= 0)
751     goto out;
752
753   /* Scan buffer and turn \r\n into \n */
754   char *src, *dst, *end;
755   src = (char *) ptr;
756   dst = (char *) ptr;
757   end = src + len - 1;
758
759   /* Read up to the last but one char - the last char needs special handling */
760   while (src < end)
761     {
762       if (*src == '\r' && src[1] == '\n')
763         src++;
764       *dst++ = *src++;
765     }
766
767   /* If not beyond end and last char is a '\r' then read one more
768      to see if we should translate this one too */
769   if (src > end)
770     /* nothing */;
771   else if (*src != '\r')
772     *dst++ = *src;
773   else
774     {
775       char c1;
776       size_t c1len = 1;
777       raw_read (&c1, c1len);
778       if (c1len <= 0)
779         /* nothing */;
780       else if (c1 == '\n')
781         *dst++ = '\n';
782       else
783         {
784           set_readahead_valid (1, c1);
785           *dst++ = *src;
786         }
787     }
788
789   len = dst - (char *) ptr;
790
791 #ifndef NOSTRACE
792   if (strace.active ())
793     {
794       char buf[16 * 6 + 1];
795       char *p = buf;
796
797       for (int i = 0; i < copied_chars && i < 16; ++i)
798         {
799           unsigned char c = ((unsigned char *) ptr)[i];
800           __small_sprintf (p, " %c", c);
801           p += strlen (p);
802         }
803       *p = '\0';
804       debug_printf ("read %d bytes (%s%s)", copied_chars, buf,
805                     copied_chars > 16 ? " ..." : "");
806     }
807 #endif
808
809 out:
810   debug_printf ("returning %d, %s mode", len, rbinary () ? "binary" : "text");
811 }
812
813 ssize_t __stdcall
814 fhandler_base::write (const void *ptr, size_t len)
815 {
816   int res;
817   IO_STATUS_BLOCK io;
818   FILE_POSITION_INFORMATION fpi;
819   FILE_STANDARD_INFORMATION fsi;
820
821   if (did_lseek ())
822     {
823       did_lseek (false); /* don't do it again */
824
825       if (!(get_flags () & O_APPEND)
826           && NT_SUCCESS (NtQueryInformationFile (get_output_handle (),
827                                                  &io, &fsi, sizeof fsi,
828                                                  FileStandardInformation))
829           && NT_SUCCESS (NtQueryInformationFile (get_output_handle (),
830                                                  &io, &fpi, sizeof fpi,
831                                                  FilePositionInformation))
832           && fpi.CurrentByteOffset.QuadPart
833              >= fsi.EndOfFile.QuadPart + (128 * 1024)
834           && (pc.fs_flags () & FILE_SUPPORTS_SPARSE_FILES))
835         {
836           /* If the file system supports sparse files and the application
837              is writing after a long seek beyond EOF, convert the file to
838              a sparse file. */
839           NTSTATUS status;
840           status = NtFsControlFile (get_output_handle (), NULL, NULL, NULL,
841                                     &io, FSCTL_SET_SPARSE, NULL, 0, NULL, 0);
842           syscall_printf ("%p = NtFsControlFile(%S, FSCTL_SET_SPARSE)",
843                           status, pc.get_nt_native_path ());
844         }
845     }
846
847   if (wbinary ())
848     {
849       debug_printf ("binary write");
850       res = raw_write (ptr, len);
851     }
852   else
853     {
854       debug_printf ("text write");
855       /* This is the Microsoft/DJGPP way.  Still not ideal, but it's
856          compatible.
857          Modified slightly by CGF 2000-10-07 */
858
859       int left_in_data = len;
860       char *data = (char *)ptr;
861       res = 0;
862
863       while (left_in_data > 0)
864         {
865           char buf[CHUNK_SIZE + 1], *buf_ptr = buf;
866           int left_in_buf = CHUNK_SIZE;
867
868           while (left_in_buf > 0 && left_in_data > 0)
869             {
870               char ch = *data++;
871               if (ch == '\n')
872                 {
873                   *buf_ptr++ = '\r';
874                   left_in_buf--;
875                 }
876               *buf_ptr++ = ch;
877               left_in_buf--;
878               left_in_data--;
879               if (left_in_data > 0 && ch == '\r' && *data == '\n')
880                 {
881                   *buf_ptr++ = *data++;
882                   left_in_buf--;
883                   left_in_data--;
884                 }
885             }
886
887           /* We've got a buffer-full, or we're out of data.  Write it out */
888           int nbytes;
889           int want = buf_ptr - buf;
890           if ((nbytes = raw_write (buf, want)) == want)
891             {
892               /* Keep track of how much written not counting additional \r's */
893               res = data - (char *)ptr;
894               continue;
895             }
896
897           if (nbytes == -1)
898             res = -1;           /* Error */
899           else
900             res += nbytes;      /* Partial write.  Return total bytes written. */
901           break;                /* All done */
902         }
903     }
904
905   return res;
906 }
907
908 ssize_t __stdcall
909 fhandler_base::readv (const struct iovec *const iov, const int iovcnt,
910                       ssize_t tot)
911 {
912   assert (iov);
913   assert (iovcnt >= 1);
914
915   size_t len = tot;
916   if (iovcnt == 1)
917     {
918       len = iov->iov_len;
919       read (iov->iov_base, len);
920       return len;
921     }
922
923   if (tot == -1)                // i.e. if not pre-calculated by the caller.
924     {
925       len = 0;
926       const struct iovec *iovptr = iov + iovcnt;
927       do
928         {
929           iovptr -= 1;
930           len += iovptr->iov_len;
931         }
932       while (iovptr != iov);
933     }
934
935   if (!len)
936     return 0;
937
938   char *buf = (char *) malloc (len);
939
940   if (!buf)
941     {
942       set_errno (ENOMEM);
943       return -1;
944     }
945
946   read (buf, len);
947   ssize_t nbytes = (ssize_t) len;
948
949   const struct iovec *iovptr = iov;
950
951   char *p = buf;
952   while (nbytes > 0)
953     {
954       const int frag = min (nbytes, (ssize_t) iovptr->iov_len);
955       memcpy (iovptr->iov_base, p, frag);
956       p += frag;
957       iovptr += 1;
958       nbytes -= frag;
959     }
960
961   free (buf);
962   return len;
963 }
964
965 ssize_t __stdcall
966 fhandler_base::writev (const struct iovec *const iov, const int iovcnt,
967                        ssize_t tot)
968 {
969   assert (iov);
970   assert (iovcnt >= 1);
971
972   if (iovcnt == 1)
973     return write (iov->iov_base, iov->iov_len);
974
975   if (tot == -1)                // i.e. if not pre-calculated by the caller.
976     {
977       tot = 0;
978       const struct iovec *iovptr = iov + iovcnt;
979       do
980         {
981           iovptr -= 1;
982           tot += iovptr->iov_len;
983         }
984       while (iovptr != iov);
985     }
986
987   assert (tot >= 0);
988
989   if (tot == 0)
990     return 0;
991
992   char *const buf = (char *) malloc (tot);
993
994   if (!buf)
995     {
996       set_errno (ENOMEM);
997       return -1;
998     }
999
1000   char *bufptr = buf;
1001   const struct iovec *iovptr = iov;
1002   int nbytes = tot;
1003
1004   while (nbytes != 0)
1005     {
1006       const int frag = min (nbytes, (ssize_t) iovptr->iov_len);
1007       memcpy (bufptr, iovptr->iov_base, frag);
1008       bufptr += frag;
1009       iovptr += 1;
1010       nbytes -= frag;
1011     }
1012   ssize_t ret = write (buf, tot);
1013   free (buf);
1014   return ret;
1015 }
1016
1017 _off64_t
1018 fhandler_base::lseek (_off64_t offset, int whence)
1019 {
1020   NTSTATUS status;
1021   IO_STATUS_BLOCK io;
1022   FILE_POSITION_INFORMATION fpi;
1023   FILE_STANDARD_INFORMATION fsi;
1024
1025   /* Seeks on text files is tough, we rewind and read till we get to the
1026      right place.  */
1027
1028   if (whence != SEEK_CUR || offset != 0)
1029     {
1030       if (whence == SEEK_CUR)
1031         offset -= ralen - raixget;
1032       set_readahead_valid (0);
1033     }
1034
1035   switch (whence)
1036     {
1037     case SEEK_SET:
1038       fpi.CurrentByteOffset.QuadPart = offset;
1039       break;
1040     case SEEK_CUR:
1041       status = NtQueryInformationFile (get_handle (), &io, &fpi, sizeof fpi,
1042                                        FilePositionInformation);
1043       if (!NT_SUCCESS (status))
1044         {
1045           __seterrno_from_nt_status (status);
1046           return -1;
1047         }
1048       fpi.CurrentByteOffset.QuadPart += offset;
1049       break;
1050     default: /* SEEK_END */
1051       status = NtQueryInformationFile (get_handle (), &io, &fsi, sizeof fsi,
1052                                        FileStandardInformation);
1053       if (!NT_SUCCESS (status))
1054         {
1055           __seterrno_from_nt_status (status);
1056           return -1;
1057         }
1058       fpi.CurrentByteOffset.QuadPart = fsi.EndOfFile.QuadPart + offset;
1059       break;
1060     }
1061
1062   debug_printf ("setting file pointer to %U", fpi.CurrentByteOffset.QuadPart);
1063   status = NtSetInformationFile (get_handle (), &io, &fpi, sizeof fpi,
1064                                  FilePositionInformation);
1065   if (!NT_SUCCESS (status))
1066     {
1067       __seterrno_from_nt_status (status);
1068       return -1;
1069     }
1070   _off64_t res = fpi.CurrentByteOffset.QuadPart;
1071
1072   /* When next we write(), we will check to see if *this* seek went beyond
1073      the end of the file and if so, potentially sparsify the file. */
1074   did_lseek (true);
1075
1076   /* If this was a SEEK_CUR with offset 0, we still might have
1077      readahead that we have to take into account when calculating
1078      the actual position for the application.  */
1079   if (whence == SEEK_CUR)
1080     res -= ralen - raixget;
1081
1082   return res;
1083 }
1084
1085 ssize_t __stdcall
1086 fhandler_base::pread (void *, size_t, _off64_t)
1087 {
1088   set_errno (ESPIPE);
1089   return -1;
1090 }
1091
1092 ssize_t __stdcall
1093 fhandler_base::pwrite (void *, size_t, _off64_t)
1094 {
1095   set_errno (ESPIPE);
1096   return -1;
1097 }
1098
1099 int
1100 fhandler_base::close_with_arch ()
1101 {
1102   int res;
1103   fhandler_base *fh;
1104   if (usecount)
1105     {
1106       if (!--usecount)
1107         debug_printf ("closing passed in archetype, usecount %d", usecount);
1108       else
1109         {
1110           debug_printf ("not closing passed in archetype, usecount %d", usecount);
1111           return 0;
1112         }
1113       fh = this;
1114     }
1115   else if (!archetype)
1116     fh = this;
1117   else
1118     {
1119       cleanup ();
1120       if (archetype_usecount (-1) == 0)
1121         {
1122           debug_printf ("closing archetype");
1123           fh = archetype;
1124         }
1125       else
1126         {
1127           debug_printf ("not closing archetype");
1128           return 0;
1129         }
1130     }
1131
1132   res = fh->close ();
1133   if (archetype)
1134     {
1135       cygheap->fdtab.delete_archetype (archetype);
1136       archetype = NULL;
1137     }
1138   return res;
1139 }
1140
1141 int
1142 fhandler_base::close ()
1143 {
1144   int res = -1;
1145
1146   syscall_printf ("closing '%s' handle %p", get_name (), get_handle ());
1147   if (nohandle () || CloseHandle (get_handle ()))
1148     res = 0;
1149   else
1150     {
1151       paranoid_printf ("CloseHandle (%d <%s>) failed", get_handle (),
1152                        get_name ());
1153
1154       __seterrno ();
1155     }
1156   return res;
1157 }
1158
1159 DWORD WINAPI
1160 flush_async_io (void *arg)
1161 {
1162   fhandler_base_overlapped *fh = (fhandler_base_overlapped *) arg;
1163   debug_only_printf ("waiting for %s I/O for %s",
1164                      (fh->get_access () & GENERIC_WRITE) ? "write" : "read",
1165                      fh->get_name ());
1166   SetEvent (fh->get_overlapped ()->hEvent); /* force has_ongoing_io to block */
1167   bool res = fh->has_ongoing_io ();
1168   debug_printf ("finished waiting for I/O from %s, res %d", fh->get_name (),
1169                 res);
1170   fh->close ();
1171   delete fh;
1172
1173   InterlockedDecrement (&fhandler_base_overlapped::asio_close_counter);
1174   SetEvent (fhandler_base_overlapped::asio_done);
1175
1176   _my_tls._ctinfo->auto_release ();
1177   return 0;
1178 }
1179
1180 void
1181 fhandler_base_overlapped::flush_all_async_io ()
1182 {
1183   while (asio_close_counter > 0)
1184     if (WaitForSingleObject (asio_done, INFINITE) != WAIT_OBJECT_0)
1185       {
1186         system_printf ("WaitForSingleObject failed, possible data loss in pipe, %E");
1187         break;
1188       }
1189   asio_close_counter = 0;
1190   if (asio_done)
1191     CloseHandle (asio_done);
1192 }
1193
1194 /* Start a thread to handle closing of overlapped asynchronous I/O since
1195    Windows amazingly does not seem to always flush I/O on close.  */
1196 void
1197 fhandler_base_overlapped::check_later ()
1198 {
1199   set_close_on_exec (true);
1200   char buf[MAX_PATH];
1201   if (!asio_done
1202       && !(asio_done = CreateEvent (&sec_none_nih, false, false,
1203                                     shared_name (buf, "asio",
1204                                                  GetCurrentProcessId ()))))
1205     api_fatal ("CreateEvent failed, %E");
1206
1207   InterlockedIncrement (&asio_close_counter);
1208   if (!new cygthread(flush_async_io, this, "flasio"))
1209     api_fatal ("couldn't create a thread to track async I/O, %E");
1210   debug_printf ("started thread to handle asynchronous closing for %s", get_name ());
1211 }
1212
1213 int
1214 fhandler_base_overlapped::close ()
1215 {
1216   int res;
1217   /* Need to treat non-blocking I/O specially because Windows appears to
1218      be brain-dead  */
1219   if (is_nonblocking () && has_ongoing_io ())
1220     {
1221       clone (HEAP_3_FHANDLER)->check_later ();
1222       res = 0;
1223     }
1224   else
1225     {
1226       destroy_overlapped ();
1227       res = fhandler_base::close ();
1228     }
1229   return res;
1230 }
1231
1232 int
1233 fhandler_base::ioctl (unsigned int cmd, void *buf)
1234 {
1235   int res;
1236
1237   switch (cmd)
1238     {
1239     case FIONBIO:
1240       set_nonblocking (*(int *) buf);
1241       res = 0;
1242       break;
1243     case FIONREAD:
1244     case TIOCSCTTY:
1245       set_errno (ENOTTY);
1246       res = -1;
1247       break;
1248     default:
1249       set_errno (EINVAL);
1250       res = -1;
1251       break;
1252     }
1253
1254   syscall_printf ("%d = ioctl (%x, %p)", res, cmd, buf);
1255   return res;
1256 }
1257
1258 int
1259 fhandler_base::lock (int, struct __flock64 *)
1260 {
1261   set_errno (EINVAL);
1262   return -1;
1263 }
1264
1265 int __stdcall
1266 fhandler_base::fstat (struct __stat64 *buf)
1267 {
1268   if (is_fs_special ())
1269     return fstat_fs (buf);
1270
1271   switch (get_device ())
1272     {
1273     case FH_PIPE:
1274       buf->st_mode = S_IFIFO | S_IRUSR | S_IWUSR;
1275       break;
1276     case FH_PIPEW:
1277       buf->st_mode = S_IFIFO | S_IWUSR;
1278       break;
1279     case FH_PIPER:
1280       buf->st_mode = S_IFIFO | S_IRUSR;
1281       break;
1282     case FH_FULL:
1283       buf->st_mode = S_IFCHR | S_IRUSR | S_IWUSR | S_IWGRP | S_IWOTH;
1284       break;
1285     default:
1286       buf->st_mode = S_IFCHR | STD_RBITS | STD_WBITS | S_IWGRP | S_IWOTH;
1287       break;
1288     }
1289
1290   buf->st_uid = geteuid32 ();
1291   buf->st_gid = getegid32 ();
1292   buf->st_nlink = 1;
1293   buf->st_blksize = PREFERRED_IO_BLKSIZE;
1294
1295   buf->st_ctim.tv_sec = 1164931200L;    /* Arbitrary value: 2006-12-01 */
1296   buf->st_ctim.tv_nsec = 0L;
1297   buf->st_birthtim = buf->st_ctim;
1298   buf->st_mtim.tv_sec = time (NULL);    /* Arbitrary value: current time,
1299                                            like Linux */
1300   buf->st_mtim.tv_nsec = 0L;
1301   buf->st_atim = buf->st_mtim;
1302
1303   return 0;
1304 }
1305
1306 int __stdcall
1307 fhandler_base::fstatvfs (struct statvfs *sfs)
1308 {
1309   /* If we hit this base implementation, it's some device in /dev.
1310      Just call statvfs on /dev for simplicity. */
1311   path_conv pc ("/dev", PC_KEEP_HANDLE);
1312   fhandler_disk_file fh (pc);
1313   return fh.fstatvfs (sfs);
1314 }
1315
1316 int
1317 fhandler_base::init (HANDLE f, DWORD a, mode_t bin)
1318 {
1319   set_io_handle (f);
1320   access = a;
1321   a &= GENERIC_READ | GENERIC_WRITE;
1322   int flags = 0;
1323   if (a == GENERIC_READ)
1324     flags = O_RDONLY;
1325   else if (a == GENERIC_WRITE)
1326     flags = O_WRONLY;
1327   else if (a == (GENERIC_READ | GENERIC_WRITE))
1328     flags = O_RDWR;
1329   set_flags (flags | bin);
1330   set_open_status ();
1331   debug_printf ("created new fhandler_base for handle %p, bin %d", f, rbinary ());
1332   return 1;
1333 }
1334
1335 int
1336 fhandler_base::dup (fhandler_base *child, int)
1337 {
1338   debug_printf ("in fhandler_base dup");
1339
1340   HANDLE nh;
1341   if (!nohandle () && !archetype)
1342     {
1343       if (!DuplicateHandle (GetCurrentProcess (), get_handle (),
1344                             GetCurrentProcess (), &nh,
1345                             0, TRUE, DUPLICATE_SAME_ACCESS))
1346         {
1347           debug_printf ("dup(%s) failed, handle %x, %E",
1348                         get_name (), get_handle ());
1349           __seterrno ();
1350           return -1;
1351         }
1352
1353       VerifyHandle (nh);
1354       child->set_io_handle (nh);
1355     }
1356   return 0;
1357 }
1358
1359 int
1360 fhandler_base_overlapped::dup (fhandler_base *child, int flags)
1361 {
1362   int res = fhandler_base::dup (child, flags) ||
1363             ((fhandler_base_overlapped *) child)->setup_overlapped ();
1364   return res;
1365 }
1366
1367 int fhandler_base::fcntl (int cmd, void *arg)
1368 {
1369   int res;
1370
1371   switch (cmd)
1372     {
1373     case F_GETFD:
1374       res = close_on_exec () ? FD_CLOEXEC : 0;
1375       break;
1376     case F_SETFD:
1377       set_close_on_exec (((int) arg & FD_CLOEXEC) ? 1 : 0);
1378       res = 0;
1379       break;
1380     case F_GETFL:
1381       res = get_flags ();
1382       debug_printf ("GETFL: %p", res);
1383       break;
1384     case F_SETFL:
1385       {
1386         /* Only O_APPEND, O_ASYNC and O_NONBLOCK/O_NDELAY are allowed.
1387            Each other flag will be ignored.
1388            Since O_ASYNC isn't defined in fcntl.h it's currently
1389            ignored as well.  */
1390         const int allowed_flags = O_APPEND | O_NONBLOCK_MASK;
1391         int new_flags = (int) arg & allowed_flags;
1392         /* Carefully test for the O_NONBLOCK or deprecated OLD_O_NDELAY flag.
1393            Set only the flag that has been passed in.  If both are set, just
1394            record O_NONBLOCK.   */
1395         if ((new_flags & OLD_O_NDELAY) && (new_flags & O_NONBLOCK))
1396           new_flags &= ~OLD_O_NDELAY;
1397         set_flags ((get_flags () & ~allowed_flags) | new_flags);
1398       }
1399       res = 0;
1400       break;
1401     default:
1402       set_errno (EINVAL);
1403       res = -1;
1404       break;
1405     }
1406   return res;
1407 }
1408
1409 /* Base terminal handlers.  These just return errors.  */
1410
1411 int
1412 fhandler_base::tcflush (int)
1413 {
1414   set_errno (ENOTTY);
1415   return -1;
1416 }
1417
1418 int
1419 fhandler_base::tcsendbreak (int)
1420 {
1421   set_errno (ENOTTY);
1422   return -1;
1423 }
1424
1425 int
1426 fhandler_base::tcdrain ()
1427 {
1428   set_errno (ENOTTY);
1429   return -1;
1430 }
1431
1432 int
1433 fhandler_base::tcflow (int)
1434 {
1435   set_errno (ENOTTY);
1436   return -1;
1437 }
1438
1439 int
1440 fhandler_base::tcsetattr (int, const struct termios *)
1441 {
1442   set_errno (ENOTTY);
1443   return -1;
1444 }
1445
1446 int
1447 fhandler_base::tcgetattr (struct termios *)
1448 {
1449   set_errno (ENOTTY);
1450   return -1;
1451 }
1452
1453 int
1454 fhandler_base::tcsetpgrp (const pid_t)
1455 {
1456   set_errno (ENOTTY);
1457   return -1;
1458 }
1459
1460 int
1461 fhandler_base::tcgetpgrp ()
1462 {
1463   set_errno (ENOTTY);
1464   return -1;
1465 }
1466
1467 int
1468 fhandler_base::tcgetsid ()
1469 {
1470   set_errno (ENOTTY);
1471   return -1;
1472 }
1473
1474 int
1475 fhandler_base::ptsname_r (char *, size_t)
1476 {
1477   set_errno (ENOTTY);
1478   return ENOTTY;
1479 }
1480
1481 /* Normal I/O constructor */
1482 fhandler_base::fhandler_base () :
1483   status (),
1484   open_status (),
1485   access (0),
1486   io_handle (NULL),
1487   ino (0),
1488   openflags (0),
1489   rabuf (NULL),
1490   ralen (0),
1491   raixget (0),
1492   raixput (0),
1493   rabuflen (0),
1494   unique_id (0),
1495   archetype (NULL),
1496   usecount (0)
1497 {
1498 }
1499
1500 /* Normal I/O destructor */
1501 fhandler_base::~fhandler_base ()
1502 {
1503   if (rabuf)
1504     free (rabuf);
1505 }
1506
1507 /**********************************************************************/
1508 /* /dev/null */
1509
1510 fhandler_dev_null::fhandler_dev_null () :
1511         fhandler_base ()
1512 {
1513 }
1514
1515 void
1516 fhandler_base::set_no_inheritance (HANDLE &h, bool not_inheriting)
1517 {
1518   if (!SetHandleInformation (h, HANDLE_FLAG_INHERIT,
1519                              not_inheriting ? 0 : HANDLE_FLAG_INHERIT))
1520     debug_printf ("SetHandleInformation failed, %E");
1521 #ifdef DEBUGGING_AND_FDS_PROTECTED
1522   if (h)
1523     setclexec (oh, h, not_inheriting);
1524 #endif
1525 }
1526
1527 bool
1528 fhandler_base::fork_fixup (HANDLE parent, HANDLE &h, const char *name)
1529 {
1530   HANDLE oh = h;
1531   bool res = false;
1532   if (/* !is_socket () && */ !close_on_exec ())
1533     debug_printf ("handle %p already opened", h);
1534   else if (!DuplicateHandle (parent, h, GetCurrentProcess (), &h,
1535                              0, !close_on_exec (), DUPLICATE_SAME_ACCESS))
1536     system_printf ("%s - %E, handle %s<%p>", get_name (), name, h);
1537   else
1538     {
1539       if (oh != h)
1540         VerifyHandle (h);
1541       res = true;
1542     }
1543   return res;
1544 }
1545
1546 void
1547 fhandler_base::set_close_on_exec (bool val)
1548 {
1549   if (!nohandle ())
1550     set_no_inheritance (io_handle, val);
1551   close_on_exec (val);
1552   debug_printf ("set close_on_exec for %s to %d", get_name (), val);
1553 }
1554
1555 void
1556 fhandler_base::fixup_after_fork (HANDLE parent)
1557 {
1558   debug_printf ("inheriting '%s' from parent", get_name ());
1559   if (!nohandle ())
1560     fork_fixup (parent, io_handle, "io_handle");
1561   /* POSIX locks are not inherited across fork. */
1562   if (unique_id)
1563     del_my_locks (after_fork);
1564 }
1565
1566 void
1567 fhandler_base_overlapped::fixup_after_fork (HANDLE parent)
1568 {
1569   setup_overlapped ();
1570   fhandler_base::fixup_after_fork (parent);
1571 }
1572
1573 void
1574 fhandler_base::fixup_after_exec ()
1575 {
1576   debug_printf ("here for '%s'", get_name ());
1577   if (unique_id && close_on_exec ())
1578     del_my_locks (after_exec);
1579 }
1580 void
1581 fhandler_base_overlapped::fixup_after_exec ()
1582 {
1583   setup_overlapped ();
1584   fhandler_base::fixup_after_exec ();
1585 }
1586
1587 bool
1588 fhandler_base::is_nonblocking ()
1589 {
1590   return (openflags & O_NONBLOCK_MASK) != 0;
1591 }
1592
1593 void
1594 fhandler_base::set_nonblocking (int yes)
1595 {
1596   int current = openflags & O_NONBLOCK_MASK;
1597   int new_flags = yes ? (!current ? O_NONBLOCK : current) : 0;
1598   openflags = (openflags & ~O_NONBLOCK_MASK) | new_flags;
1599 }
1600
1601 int
1602 fhandler_base::mkdir (mode_t)
1603 {
1604   if (exists ())
1605     set_errno (EEXIST);
1606   else
1607     set_errno (EROFS);
1608   return -1;
1609 }
1610
1611 int
1612 fhandler_base::rmdir ()
1613 {
1614   if (!exists ())
1615     set_errno (ENOENT);
1616   else if (!pc.isdir ())
1617     set_errno (ENOTDIR);
1618   else
1619     set_errno (EROFS);
1620   return -1;
1621 }
1622
1623 DIR *
1624 fhandler_base::opendir (int fd)
1625 {
1626   set_errno (ENOTDIR);
1627   return NULL;
1628 }
1629
1630 int
1631 fhandler_base::readdir (DIR *, dirent *)
1632 {
1633   return ENOTDIR;
1634 }
1635
1636 long
1637 fhandler_base::telldir (DIR *)
1638 {
1639   set_errno (ENOTDIR);
1640   return -1;
1641 }
1642
1643 void
1644 fhandler_base::seekdir (DIR *, long)
1645 {
1646   set_errno (ENOTDIR);
1647 }
1648
1649 void
1650 fhandler_base::rewinddir (DIR *)
1651 {
1652   set_errno (ENOTDIR);
1653 }
1654
1655 int
1656 fhandler_base::closedir (DIR *)
1657 {
1658   set_errno (ENOTDIR);
1659   return -1;
1660 }
1661
1662 int
1663 fhandler_base::fchmod (mode_t mode)
1664 {
1665   extern int chmod_device (path_conv& pc, mode_t mode);
1666   if (pc.is_fs_special ())
1667     return chmod_device (pc, mode);
1668   /* By default, just succeeds. */
1669   return 0;
1670 }
1671
1672 int
1673 fhandler_base::fchown (__uid32_t uid, __gid32_t gid)
1674 {
1675   if (pc.is_fs_special ())
1676     return ((fhandler_disk_file *) this)->fhandler_disk_file::fchown (uid, gid);
1677   /* By default, just succeeds. */
1678   return 0;
1679 }
1680
1681 int
1682 fhandler_base::facl (int cmd, int nentries, __aclent32_t *aclbufp)
1683 {
1684   int res = -1;
1685   switch (cmd)
1686     {
1687       case SETACL:
1688         /* By default, just succeeds. */
1689         res = 0;
1690         break;
1691       case GETACL:
1692         if (!aclbufp)
1693           set_errno(EFAULT);
1694         else if (nentries < MIN_ACL_ENTRIES)
1695           set_errno (ENOSPC);
1696         else
1697           {
1698             aclbufp[0].a_type = USER_OBJ;
1699             aclbufp[0].a_id = myself->uid;
1700             aclbufp[0].a_perm = (S_IRUSR | S_IWUSR) >> 6;
1701             aclbufp[1].a_type = GROUP_OBJ;
1702             aclbufp[1].a_id = myself->gid;
1703             aclbufp[1].a_perm = (S_IRGRP | S_IWGRP) >> 3;
1704             aclbufp[2].a_type = OTHER_OBJ;
1705             aclbufp[2].a_id = ILLEGAL_GID;
1706             aclbufp[2].a_perm = S_IROTH | S_IWOTH;
1707             aclbufp[3].a_type = CLASS_OBJ;
1708             aclbufp[3].a_id = ILLEGAL_GID;
1709             aclbufp[3].a_perm = S_IRWXU | S_IRWXG | S_IRWXO;
1710             res = MIN_ACL_ENTRIES;
1711           }
1712         break;
1713       case GETACLCNT:
1714         res = MIN_ACL_ENTRIES;
1715         break;
1716       default:
1717         set_errno (EINVAL);
1718         break;
1719     }
1720   return res;
1721 }
1722
1723 ssize_t
1724 fhandler_base::fgetxattr (const char *name, void *value, size_t size)
1725 {
1726   set_errno (ENOTSUP);
1727   return -1;
1728 }
1729
1730 int
1731 fhandler_base::fsetxattr (const char *name, const void *value, size_t size,
1732                           int flags)
1733 {
1734   set_errno (ENOTSUP);
1735   return -1;
1736 }
1737
1738 int
1739 fhandler_base::fadvise (_off64_t offset, _off64_t length, int advice)
1740 {
1741   set_errno (EINVAL);
1742   return -1;
1743 }
1744
1745 int
1746 fhandler_base::ftruncate (_off64_t length, bool allow_truncate)
1747 {
1748   set_errno (EINVAL);
1749   return -1;
1750 }
1751
1752 int
1753 fhandler_base::link (const char *newpath)
1754 {
1755   set_errno (EPERM);
1756   return -1;
1757 }
1758
1759 int
1760 fhandler_base::utimens (const struct timespec *tvp)
1761 {
1762   if (is_fs_special ())
1763     return utimens_fs (tvp);
1764
1765   set_errno (EINVAL);
1766   return -1;
1767 }
1768
1769 int
1770 fhandler_base::fsync ()
1771 {
1772   if (!get_handle () || nohandle ())
1773     {
1774       set_errno (EINVAL);
1775       return -1;
1776     }
1777   if (pc.isdir ()) /* Just succeed. */
1778     return 0;
1779   if (FlushFileBuffers (get_handle ()))
1780     return 0;
1781
1782   /* Ignore ERROR_INVALID_FUNCTION because FlushFileBuffers() always fails
1783      with this code on raw devices which are unbuffered by default.  */
1784   DWORD errcode = GetLastError();
1785   if (errcode == ERROR_INVALID_FUNCTION)
1786     return 0;
1787
1788   __seterrno_from_win_error (errcode);
1789   return -1;
1790 }
1791
1792 int
1793 fhandler_base::fpathconf (int v)
1794 {
1795   int ret;
1796
1797   switch (v)
1798     {
1799     case _PC_LINK_MAX:
1800       return pc.fs_is_ntfs () || pc.fs_is_samba () || pc.fs_is_nfs ()
1801              ? LINK_MAX : 1;
1802     case _PC_MAX_CANON:
1803       if (is_tty ())
1804         return MAX_CANON;
1805       set_errno (EINVAL);
1806       break;
1807     case _PC_MAX_INPUT:
1808       if (is_tty ())
1809         return MAX_INPUT;
1810       set_errno (EINVAL);
1811       break;
1812     case _PC_NAME_MAX:
1813       /* NAME_MAX is without trailing \0 */
1814       if (!pc.isdir ())
1815         return NAME_MAX;
1816       ret = NT_MAX_PATH - strlen (get_name ()) - 2;
1817       return ret < 0 ? 0 : ret > NAME_MAX ? NAME_MAX : ret;
1818     case _PC_PATH_MAX:
1819       /* PATH_MAX is with trailing \0 */
1820       if (!pc.isdir ())
1821         return PATH_MAX;
1822       ret = NT_MAX_PATH - strlen (get_name ()) - 1;
1823       return ret < 0 ? 0 : ret > PATH_MAX ? PATH_MAX : ret;
1824     case _PC_PIPE_BUF:
1825       if (pc.isdir ()
1826           || get_device () == FH_FIFO || get_device () == FH_PIPE
1827           || get_device () == FH_PIPER || get_device () == FH_PIPEW)
1828         return PIPE_BUF;
1829       set_errno (EINVAL);
1830       break;
1831     case _PC_CHOWN_RESTRICTED:
1832       return 1;
1833     case _PC_NO_TRUNC:
1834       return 1;
1835     case _PC_VDISABLE:
1836       if (is_tty ())
1837         return _POSIX_VDISABLE;
1838       set_errno (EINVAL);
1839       break;
1840     case _PC_ASYNC_IO:
1841     case _PC_PRIO_IO:
1842       break;
1843     case _PC_SYNC_IO:
1844       return 1;
1845     case _PC_FILESIZEBITS:
1846       return FILESIZEBITS;
1847     case _PC_2_SYMLINKS:
1848       return 1;
1849     case _PC_SYMLINK_MAX:
1850       return SYMLINK_MAX;
1851     case _PC_POSIX_PERMISSIONS:
1852     case _PC_POSIX_SECURITY:
1853       if (get_device () == FH_FS)
1854         return pc.has_acls () || pc.fs_is_nfs ();
1855       set_errno (EINVAL);
1856       break;
1857     default:
1858       set_errno (EINVAL);
1859       break;
1860     }
1861   return -1;
1862 }
1863
1864 /* Overlapped I/O */
1865
1866 int __stdcall __attribute__ ((regparm (1)))
1867 fhandler_base_overlapped::setup_overlapped ()
1868 {
1869   OVERLAPPED *ov = get_overlapped_buffer ();
1870   memset (ov, 0, sizeof (*ov));
1871   set_overlapped (ov);
1872   ov->hEvent = CreateEvent (&sec_none_nih, true, true, NULL);
1873   io_pending = false;
1874   return ov->hEvent ? 0 : -1;
1875 }
1876
1877 void __stdcall __attribute__ ((regparm (1)))
1878 fhandler_base_overlapped::destroy_overlapped ()
1879 {
1880   OVERLAPPED *ov = get_overlapped ();
1881   if (ov && ov->hEvent)
1882     {
1883       CloseHandle (ov->hEvent);
1884       ov->hEvent = NULL;
1885     }
1886   io_pending = false;
1887   get_overlapped () = NULL;
1888 }
1889
1890 bool __stdcall __attribute__ ((regparm (1)))
1891 fhandler_base_overlapped::has_ongoing_io ()
1892 {
1893   if (!io_pending)
1894     return false;
1895
1896   if (!IsEventSignalled (get_overlapped ()->hEvent))
1897     return true;
1898   io_pending = false;
1899   DWORD nbytes;
1900   GetOverlappedResult (get_output_handle (), get_overlapped (), &nbytes, true);
1901   return false;
1902 }
1903
1904 fhandler_base_overlapped::wait_return __stdcall __attribute__ ((regparm (3)))
1905 fhandler_base_overlapped::wait_overlapped (bool inres, bool writing, DWORD *bytes, bool nonblocking, DWORD len)
1906 {
1907   if (!get_overlapped ())
1908     return inres ? overlapped_success : overlapped_error;
1909
1910   wait_return res = overlapped_unknown;
1911   DWORD err;
1912   if (inres)
1913     /* handle below */;
1914   else if ((err = GetLastError ()) != ERROR_IO_PENDING)
1915     res = overlapped_error;
1916   else if (!nonblocking)
1917     /* handle below */;
1918   else if (!writing)
1919     SetEvent (get_overlapped ()->hEvent);       /* Force immediate WFMO return */
1920   else
1921     {
1922       *bytes = len;                             /* Assume that this worked */
1923       io_pending = true;                        /*  but don't allow subsequent */
1924       res = overlapped_success;                 /*  writes until completed */
1925     }
1926   if (res == overlapped_unknown)
1927     {
1928       HANDLE w4[3] = { get_overlapped ()->hEvent, signal_arrived,
1929                        pthread::get_cancel_event () };
1930       DWORD n = w4[2] ? 3 : 2;
1931       HANDLE h = writing ? get_output_handle () : get_handle ();
1932       DWORD wfres = WaitForMultipleObjects (n, w4, false, INFINITE);
1933       /* Cancelling here to prevent races.  It's possible that the I/O has
1934          completed already, in which case this is a no-op.  Otherwise,
1935          WFMO returned because 1) This is a non-blocking call, 2) a signal
1936          arrived, or 3) the operation was cancelled.  These cases may be
1937          overridden by the return of GetOverlappedResult which could detect
1938          that I/O completion occurred.  */
1939       CancelIo (h);
1940       BOOL wores = GetOverlappedResult (h, get_overlapped (), bytes, false);
1941       err = GetLastError ();
1942       ResetEvent (get_overlapped ()->hEvent);   /* Probably not needed but CYA */
1943       debug_printf ("wfres %d, wores %d, bytes %u", wfres, wores, *bytes);
1944       if (wores)
1945         res = overlapped_success;       /* operation succeeded */
1946       else if (wfres == WAIT_OBJECT_0 + 1)
1947         {
1948           if (_my_tls.call_signal_handler ())
1949             res = overlapped_signal;
1950           else
1951             {
1952               err = ERROR_INVALID_AT_INTERRUPT_TIME; /* forces an EINTR below */
1953               debug_printf ("unhandled signal");
1954               res = overlapped_error;
1955             }
1956         }
1957       else if (nonblocking)
1958         res = overlapped_nonblocking_no_data;   /* more handling below */
1959       else if (wfres == WAIT_OBJECT_0 + 2)
1960         pthread::static_cancel_self ();         /* never returns */
1961       else
1962         {
1963           debug_printf ("GetOverLappedResult failed, h %p, bytes %u, w4: %p, %p, %p %E", h, *bytes, w4[0], w4[1], w4[2]);
1964           res = overlapped_error;
1965         }
1966     }
1967
1968   if (res == overlapped_success)
1969     debug_printf ("normal %s, %u bytes", writing ? "write" : "read", *bytes);
1970   else if (res == overlapped_signal)
1971     debug_printf ("handled signal");
1972   else if (res == overlapped_nonblocking_no_data)
1973     {
1974       *bytes = (DWORD) -1;
1975       set_errno (EAGAIN);
1976       debug_printf ("no data to read for nonblocking I/O");
1977     }
1978   else if (err == ERROR_HANDLE_EOF || err == ERROR_BROKEN_PIPE)
1979     {
1980       debug_printf ("EOF, %E");
1981       *bytes = 0;
1982       res = overlapped_success;
1983       if (writing && err == ERROR_BROKEN_PIPE)
1984         raise (SIGPIPE);
1985     }
1986   else
1987     {
1988       debug_printf ("res %u, Win32 Error %u", (unsigned) res, err);
1989       *bytes = (DWORD) -1;
1990       __seterrno_from_win_error (err);
1991       if (writing && err == ERROR_NO_DATA)
1992         raise (SIGPIPE);
1993     }
1994
1995   return res;
1996 }
1997
1998 void __stdcall __attribute__ ((regparm (3)))
1999 fhandler_base_overlapped::raw_read (void *ptr, size_t& len)
2000 {
2001   DWORD nbytes;
2002   bool keep_looping;
2003   do
2004     {
2005       bool res = ReadFile (get_handle (), ptr, len, &nbytes,
2006                            get_overlapped ());
2007       switch (wait_overlapped (res, false, &nbytes, is_nonblocking ()))
2008         {
2009         case overlapped_signal:
2010           keep_looping = true;
2011           break;
2012         default:        /* Added to quiet gcc */
2013         case overlapped_success:
2014         case overlapped_error:
2015           keep_looping = false;
2016           break;
2017         }
2018     }
2019   while (keep_looping);
2020   len = (size_t) nbytes;
2021 }
2022
2023 ssize_t __stdcall __attribute__ ((regparm (3)))
2024 fhandler_base_overlapped::raw_write (const void *ptr, size_t len)
2025 {
2026   size_t nbytes;
2027   if (has_ongoing_io ())
2028     {
2029       set_errno (EAGAIN);
2030       nbytes = (DWORD) -1;
2031     }
2032   else
2033     {
2034       size_t chunk;
2035       if (!max_atomic_write || len < max_atomic_write)
2036         chunk = len;
2037       else if (is_nonblocking ())
2038         chunk = len = max_atomic_write;
2039       else
2040         chunk = max_atomic_write;
2041
2042       nbytes = 0;
2043       DWORD nbytes_now = 0;
2044       /* Write to fd in smaller chunks, accumlating a total.
2045          If there's an error, just return the accumulated total
2046          unless the first write fails, in which case return value
2047          from wait_overlapped(). */
2048       while (nbytes < len)
2049         {
2050           size_t left = len - nbytes;
2051           size_t len1;
2052           if (left > chunk)
2053             len1 = chunk;
2054           else
2055             len1 = left;
2056           bool res = WriteFile (get_output_handle (), ptr, len1, &nbytes_now,
2057                                 get_overlapped ());
2058           switch (wait_overlapped (res, true, &nbytes_now,
2059                                    is_nonblocking (), len1))
2060             {
2061             case overlapped_success:
2062               ptr = ((char *) ptr) + chunk;
2063               nbytes += nbytes_now;
2064               /* fall through intentionally */
2065             case overlapped_signal:
2066               break;                    /* keep looping */
2067             case overlapped_error:
2068               len = 0;          /* terminate loop */
2069             case overlapped_unknown:
2070             case overlapped_nonblocking_no_data:
2071               break;
2072             }
2073         }
2074       if (!nbytes)
2075         nbytes = nbytes_now;
2076     }
2077   return nbytes;
2078 }