Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / native_client / src / shared / platform / win / nacl_host_desc.c
1 /*
2  * Copyright (c) 2012 The Native Client Authors. All rights reserved.
3  * Use of this source code is governed by a BSD-style license that can be
4  * found in the LICENSE file.
5  */
6
7 /*
8  * NaCl Service Runtime.  I/O Descriptor / Handle abstraction.  Memory
9  * mapping using descriptors.
10  */
11 #include "native_client/src/include/portability.h"
12 #include "native_client/src/include/portability_io.h"
13
14 #include <windows.h>
15 #include <direct.h>
16 #include <io.h>
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <share.h>
20
21 #include "native_client/src/include/nacl_macros.h"
22 #include "native_client/src/include/nacl_platform.h"
23 #include "native_client/src/shared/platform/nacl_check.h"
24 #include "native_client/src/shared/platform/nacl_find_addrsp.h"
25 #include "native_client/src/shared/platform/nacl_host_desc.h"
26 #include "native_client/src/shared/platform/nacl_log.h"
27 #include "native_client/src/shared/platform/nacl_sync.h"
28 #include "native_client/src/shared/platform/nacl_sync_checked.h"
29 #include "native_client/src/shared/platform/win/xlate_system_error.h"
30 #include "native_client/src/trusted/desc/nacl_desc_effector.h"
31
32 #include "native_client/src/trusted/service_runtime/nacl_config.h"
33 #include "native_client/src/trusted/service_runtime/internal_errno.h"
34 #include "native_client/src/trusted/service_runtime/sel_util-inl.h"
35
36 #include "native_client/src/trusted/service_runtime/include/bits/mman.h"
37 #include "native_client/src/trusted/service_runtime/include/sys/errno.h"
38 #include "native_client/src/trusted/service_runtime/include/sys/fcntl.h"
39 #include "native_client/src/trusted/service_runtime/include/sys/stat.h"
40 #include "native_client/src/trusted/service_runtime/include/sys/unistd.h"
41
42 #define OFFSET_FOR_FILEPOS_LOCK (GG_LONGLONG(0x7000000000000000))
43
44 /*
45  * By convention, we use locking the byte at OFFSET_FOR_FILEPOS_LOCK
46  * as locking for the implicit file position associated with a file
47  * handle.  According to MSDN, LockFileEx of a byte range that does
48  * not (yet) exist in a file is not an error, which makes sense in
49  * that one might want to have exclusive access to a file region that
50  * is beyond the end of the file before populating it.  We assume that
51  * OFFSET_FOR_FILEPOS_LOCK is large enough that no real file will
52  * actually be that big (even if sparse) and cause problems.
53  *
54  * One drawback of this is that two independent file handles on the
55  * same file will share the same lock.  If this leads to actual
56  * contention issues, we can use the following randomized approach,
57  * ASSUMING that each file handle / posix-level host descriptor is
58  * introduced to NaCl at most once (e.g., no dup'ing and invoking
59  * NaClHostDescPosixTake multiple times): we pick a random offset from
60  * OFFSET_FOR_FILEPOS_LOCK, and make sure we transfer that with the
61  * file handle in the nrd_xfer protocol.  This way, we use a range of
62  * byte offsets for locking files and avoid false contention.  We
63  * would be subject to the birthday paradox, of course, so if we
64  * picked a 16-bit random offset to use, then if a file is opened ~256
65  * times we would start seeing performance issues caused by
66  * contention, which is probably acceptable; a 32-bit nonce would be
67  * plenty.
68  *
69  * On Windows, fcntl is not available.  A very similar function to
70  * lockf, _locking, exists in the Windows CRT.  It does not permit
71  * specification of the start of a region, only size (just like lockf)
72  * -- implicitly from the current position -- which is less than
73  * useful for our purposes.
74  */
75 static void NaClTakeFilePosLock(HANDLE hFile) {
76   OVERLAPPED overlap;
77   DWORD err;
78
79   memset(&overlap, 0, sizeof overlap);
80   overlap.Offset = (DWORD) OFFSET_FOR_FILEPOS_LOCK;
81   overlap.OffsetHigh = (DWORD) (OFFSET_FOR_FILEPOS_LOCK >> 32);
82   /*
83    * LockFileEx should never fail -- untrusted code cannot cause hFile
84    * to become invalid, since all NaClHostDesc objects are wrapped in
85    * NaClDesc objects and all uses of NaClDesc objects take a
86    * reference before use, so a threading race that closes a
87    * descriptor at the untrusted code level will only dereference the
88    * NaClDesc (and make it unavailable to the untrusted code), but the
89    * object will not be destroyed until after the NaClDesc-level
90    * operation (which in turn invokes the NaClHostDesc level
91    * operation) completes.  Only after the operation completes will
92    * the reference to the NaClDesc be drop by the syscall handler.
93    */
94   if (!LockFileEx(hFile, LOCKFILE_EXCLUSIVE_LOCK,
95                   /* dwReserved= */ 0,
96                   /* nNumberOfBytesToLockLow= */ 1,
97                   /* nNumberOfBytesToLockHigh= */ 0,
98                   &overlap)) {
99     err = GetLastError();
100     NaClLog(LOG_FATAL, "NaClTakeFilePosLock: LockFileEx failed, error %u\n",
101             err);
102   }
103 }
104
105 /*
106  * Map our ABI to the host OS's ABI.
107  * Note: there is no X bit equivalent on windows so NACL_ABI_S_IXUSR
108  * is ignored.
109  */
110 static INLINE mode_t NaClMapMode(nacl_abi_mode_t abi_mode) {
111   mode_t m = 0;
112   if (0 != (abi_mode & NACL_ABI_S_IRUSR))
113     m |= _S_IREAD;
114   if (0 != (abi_mode & NACL_ABI_S_IWUSR))
115     m |= _S_IWRITE;
116   return m;
117 }
118
119 /* Windows doesn't define R_OK or W_OK macros but expects these constants */
120 #define WIN_F_OK 0
121 #define WIN_R_OK 4
122 #define WIN_W_OK 2
123
124 /*
125  * Map our ABI to the host OS's ABI.
126  * There is no X_OK (0x1) on win32 so we ignore
127  * NACL_ABI_X_OK and report everything that exists
128  * as being executable.
129  */
130 static INLINE int NaClMapAccessMode(int nacl_mode) {
131   int mode = 0;
132   if (nacl_mode == NACL_ABI_F_OK) {
133     mode = WIN_F_OK;
134   } else {
135     if (nacl_mode & NACL_ABI_R_OK)
136       mode |= WIN_R_OK;
137     if (nacl_mode & NACL_ABI_W_OK)
138       mode |= WIN_W_OK;
139   }
140   return mode;
141 }
142
143 static void NaClDropFilePosLock(HANDLE hFile) {
144   OVERLAPPED overlap;
145   DWORD err;
146
147   memset(&overlap, 0, sizeof overlap);
148   overlap.Offset = (DWORD) OFFSET_FOR_FILEPOS_LOCK;
149   overlap.OffsetHigh = (DWORD) (OFFSET_FOR_FILEPOS_LOCK >> 32);
150   if (!UnlockFileEx(hFile,
151                     /* dwReserved= */ 0,
152                     /* nNumberOfBytesToLockLow= */ 1,
153                     /* nNumberOfBytesToLockHigh= */ 0,
154                     &overlap)) {
155     err = GetLastError();
156     NaClLog(LOG_FATAL, "NaClDropFilePosLock: UnlockFileEx failed, error %u\n",
157             err);
158   }
159 }
160
161 static nacl_off64_t NaClLockAndGetCurrentFilePos(HANDLE hFile) {
162   LARGE_INTEGER to_move;
163   LARGE_INTEGER cur_pos;
164   DWORD err;
165
166   NaClTakeFilePosLock(hFile);
167   to_move.QuadPart = 0;
168   if (!SetFilePointerEx(hFile, to_move, &cur_pos, FILE_CURRENT)) {
169     err = GetLastError();
170     NaClLog(LOG_FATAL,
171             "NaClLockAndGetCurrentFilePos: SetFilePointerEx failed, error %u\n",
172             err);
173   }
174   return cur_pos.QuadPart;
175 }
176
177 static void NaClSetCurrentFilePosAndUnlock(HANDLE hFile,
178                                            nacl_off64_t pos) {
179   LARGE_INTEGER to_move;
180   DWORD err;
181
182   to_move.QuadPart = pos;
183   if (!SetFilePointerEx(hFile, to_move, (LARGE_INTEGER *) NULL, FILE_BEGIN)) {
184     err = GetLastError();
185     NaClLog(LOG_FATAL,
186             "NaClSetCurrentFilePosAndUnlock: SetFilePointerEx failed:"
187             " error %d\n",
188             err);
189   }
190   NaClDropFilePosLock(hFile);
191 }
192
193 /*
194  * WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
195  *
196  * The implementation of the host descriptor abstractions will
197  * probably change.  In particularly, blocking I/O calls must be
198  * interruptible in order to implement the address-space move
199  * mechanism for mmap error recovery, and the it seems that the only
200  * way that this would be feasible is to do the following: instead of
201  * using the POSIX abstraction layer, do the I/O using Windows file
202  * handles opened for asynchronous operations.  When a potentially
203  * blocking system call (e.g., read or write) is performed, use
204  * overlapped I/O via ReadFile/WriteFile to initiate the I/O operation
205  * in a non-blocking manner, and use a separate event object, so that
206  * the thread can, after initiating the I/O, perform
207  * WaitForMultipleObjects on both I/O completion (event in the
208  * OVERLAPPED structure) and on mmap-generated interrupts.  The event
209  * can be signalled via SetEvent by any other thread that wish to
210  * perform a safe mmap operation.
211  *
212  * When the safe mmap is to occur, all other application threads are
213  * stopped (beware, of course, of the race condition where two threads
214  * try to do mmap), and the remaining running thread performs
215  * VirtualFree and MapViewOfFileEx.  If a thread (from some injected
216  * DLL) puts some memory in the hole created by VirtualFree before the
217  * MapViewOfFileEx runs, then we have to move the entire address space
218  * to avoid allowing the untrusted NaCl app from touching this
219  * innocent thread's memory.
220  *
221  * What this implies is that a mechanism must exist in order for the
222  * mmapping thread to stop all other application threads, and this is
223  * why the blocking syscalls must be interruptible.  When interrupted,
224  * the thread that initiated the I/O must perform CancelIo and check,
225  * via GetOverlappedResult, to see how much have completed, etc, then
226  * put itself into a restartable state -- we might simply return EINTR
227  * if no work has been dnoe and require libc to restart the syscall in
228  * the SysV style, though it should be possible to just restart the
229  * syscall in the BSD style -- and to signal the mmapping thread that
230  * it is ready.
231  *
232  * Alternatively, these interrupted operations can return a private
233  * version of EAGAIN, so that the code calling the host descriptor
234  * (syscall handler) can quiesce the thread and restart the I/O
235  * operation once the address space move is complete.
236  *
237  * WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
238  */
239
240 /*
241  * TODO(bsy, gregoryd): check that _get_errno is indeed a thread-safe way
242  * to get the error from the last 'syscall' into the posix layer.
243  */
244 int GetErrno(void) {
245   int thread_errno;
246
247   (void) _get_errno(&thread_errno);
248   return NaClXlateErrno(thread_errno);
249 }
250
251 static INLINE size_t size_min(size_t a, size_t b) {
252   return (a < b) ? a : b;
253 }
254
255 /*
256  * The mapping and unmapping code work in 64K chunks rather than a
257  * single large allocation because all of our uses will use 64K
258  * chunks.  Higher level code keeps track of whether memory came from
259  * VirtualAlloc or NaClHostDescMap, and will call the appropriate
260  * deallocation functions.
261  *
262  * NB: if prot is NACL_ABI_PROT_NONE, then the memory should be
263  * deallocated via VirtualFree as if it came from paging file rather
264  * than via a file mapping object representing the paging file (and
265  * thus UnmapViewOfFile).
266  */
267
268 /*
269  * out_flProtect == 0 means error, and the error string can be used
270  * for a logging message (except for the cases that the caller should
271  * be checking for).
272  *
273  * in parameters are all NACL_ABI_ values or bool (0/1).
274  *
275  * accmode may be NACL_ABI_O_RDONLY or NACL_ABI_O_RDWR, but not
276  * NACL_ABI_O_WRONLY (see below).
277  *
278  * Caller should check for:
279  *
280  * - PROT_NONE -> special case handling,
281  * - NACL_ABI_O_APPEND and PROT_WRITE -> EACCES,
282  * - accmode is O_WRONLY -> EACCES,
283  *
284  * The interpretation here is that PROT_EXEC or PROT_WRITE implies
285  * asking for PROT_READ, since most hardware behaves this way.  So if
286  * the descriptor is O_WRONLY, we generally refuse.
287  *
288  * The file mapping object created by CreateFileMapping's flProtect
289  * argument specifies the MAXIMUM protection, and MapViewOfFileEx will
290  * request a lesser level of access.  We should always
291  * CreateFileMapping with a high level of access so that
292  * VirtualProtect (used by mprotect) can be used to turn on write when
293  * the initial mmap had read-only mappings.
294  *
295  * BUG(phosek): Due to Windows XP limitation, in particular the missing
296  * PAGE_EXECUTE_WRITECOPY protection support for file mapping objects,
297  * we cannot mmap r/o file as private, read/write and later make it
298  * executable or vice versa mmap r/o file as private, read/execute and
299  * later make it writable. This is a platform difference, but since
300  * untrusted code is not allowed to mmap files as write/execute, this
301  * difference is invisible to application developers and will therefore
302  * likely remain unresolved as the solution would likely be very
303  * expensive. Furthemore, after dropping the support for Windows XP, this
304  * difference can be easily resolved by updating the flag mapping.
305  */
306 void NaClflProtectAndDesiredAccessMap(int prot,
307                                       int is_private,
308                                       int accmode,
309                                       DWORD *out_flMappingProtect,
310                                       DWORD *out_flProtect,
311                                       DWORD *out_dwDesiredAccess,
312                                       char const **out_msg) {
313 #define M(mp,p,da,err) { mp, p, da, err, #mp, #p, #da }
314   static struct {
315     DWORD flMappingProtect;
316     DWORD flProtect;
317     DWORD dwDesiredAccess;
318     char const *err;
319     char const *flMappingProtect_str;
320     char const *flProtect_str;
321     char const *dwDesiredAccess_str;
322   } table[] = {
323     /* RDONLY */
324     /* shared */
325     /* PROT_NONE */
326     M(PAGE_EXECUTE_READ, PAGE_NOACCESS, FILE_MAP_READ, NULL),
327     /* PROT_READ */
328     M(PAGE_EXECUTE_READ, PAGE_READONLY, FILE_MAP_READ, NULL),
329     /* PROT_WRITE */
330     M(0, 0, 0, "file open for read only; no shared write allowed"),
331     /* PROT_READ | PROT_WRITE */
332     M(0, 0, 0, "file open for read only; no shared read/write allowed"),
333     /* PROT_EXEC */
334     M(PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE,
335       FILE_MAP_READ | FILE_MAP_EXECUTE, NULL),
336     /* PROT_READ | PROT_EXEC */
337     M(PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READ,
338       FILE_MAP_READ | FILE_MAP_EXECUTE, NULL),
339     /* PROT_WRITE | PROT_EXEC */
340     M(0, 0, 0, "file open for read only; no shared write/exec allowed"),
341     /* PROT_READ | PROT_WRITE | PROT_EXEC */
342     M(0, 0, 0, "file open for read only; no shared read/write/exec allowed"),
343
344     /* is_private */
345     /* PROT_NONE */
346     M(PAGE_EXECUTE_READ, PAGE_NOACCESS, FILE_MAP_READ, NULL),
347     /* PROT_READ */
348     M(PAGE_EXECUTE_READ, PAGE_READONLY, FILE_MAP_READ, NULL),
349     /* PROT_WRITE */
350     M(PAGE_EXECUTE_READ, PAGE_WRITECOPY, FILE_MAP_COPY, NULL),
351     /* PROT_READ | PROT_WRITE */
352     M(PAGE_EXECUTE_READ, PAGE_WRITECOPY, FILE_MAP_COPY, NULL),
353
354     /*
355      * NB: PAGE_EXECUTE_WRITECOPY is not supported on Server 2003 or
356      * XP, which means that the mmap will fail.  In this case we fallback
357      * to PAGE_EXECUTE_READ.
358      *
359      * Even with PAGE_EXECUTE_WRITECOPY, the PROT_WRITE | PROT_EXEC
360      * case where we are asking for FILE_MAP_COPY | FILE_MAP_EXECUTE
361      * seems to always fail, with GetLastError() yielding 87
362      * (ERROR_INVALID_PARAMETER).  This may be due to antivirus.
363      */
364
365     /* PROT_EXEC */
366     M(PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE,
367       FILE_MAP_READ | FILE_MAP_EXECUTE, NULL),
368     /* PROT_READ | PROT_EXEC */
369     M(PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_READ,
370       FILE_MAP_READ | FILE_MAP_EXECUTE, NULL),
371     /* PROT_WRITE | PROT_EXEC */
372     M(PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_WRITECOPY,
373       FILE_MAP_COPY | FILE_MAP_EXECUTE, NULL),
374     /* PROT_READ | PROT_WRITE | PROT_EXEC */
375     M(PAGE_EXECUTE_WRITECOPY, PAGE_EXECUTE_WRITECOPY,
376       FILE_MAP_COPY | FILE_MAP_EXECUTE, NULL),
377
378     /* RDWR */
379     /* shared */
380     /* PROT_NONE */
381     M(PAGE_EXECUTE_READWRITE, PAGE_NOACCESS, FILE_MAP_READ, NULL),
382     /* PROT_READ */
383     M(PAGE_EXECUTE_READWRITE, PAGE_READONLY, FILE_MAP_READ, NULL),
384     /* PROT_WRITE */
385     M(PAGE_EXECUTE_READWRITE, PAGE_READWRITE, FILE_MAP_WRITE, NULL),
386     /* PROT_READ | PROT_WRITE */
387     M(PAGE_EXECUTE_READWRITE, PAGE_READWRITE, FILE_MAP_WRITE, NULL),
388
389     /* PROT_EXEC */
390     M(PAGE_EXECUTE_READWRITE, PAGE_EXECUTE,
391       FILE_MAP_READ | FILE_MAP_EXECUTE, NULL),
392     /* PROT_READ | PROT_EXEC */
393     M(PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_READ,
394       FILE_MAP_READ | FILE_MAP_EXECUTE, NULL),
395     /* PROT_WRITE | PROT_EXEC */
396     M(PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_READWRITE,
397       FILE_MAP_WRITE | FILE_MAP_EXECUTE, NULL),
398     /* PROT_READ | PROT_WRITE | PROT_EXEC */
399     M(PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_READWRITE,
400       FILE_MAP_WRITE | FILE_MAP_EXECUTE, NULL),
401
402     /* is_private */
403     /* PROT_NONE */
404     M(PAGE_EXECUTE_READWRITE, PAGE_NOACCESS, FILE_MAP_READ, NULL),
405     /* PROT_READ */
406     M(PAGE_EXECUTE_READWRITE, PAGE_READONLY, FILE_MAP_READ, NULL),
407     /* PROT_WRITE */
408     M(PAGE_EXECUTE_READWRITE, PAGE_WRITECOPY, FILE_MAP_COPY, NULL),
409     /* PROT_READ | PROT_WRITE */
410     M(PAGE_EXECUTE_READWRITE, PAGE_WRITECOPY, FILE_MAP_COPY, NULL),
411
412     /* PROT_EXEC */
413     M(PAGE_EXECUTE_READWRITE, PAGE_EXECUTE,
414       FILE_MAP_WRITE | FILE_MAP_EXECUTE, NULL),
415     /* PROT_READ | PROT_EXEC */
416     M(PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_READ,
417       FILE_MAP_WRITE | FILE_MAP_EXECUTE, NULL),
418     /* PROT_WRITE | PROT_EXEC */
419     M(PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY,
420       FILE_MAP_WRITE | FILE_MAP_EXECUTE, NULL),
421     /* PROT_READ | PROT_WRITE | PROT_EXEC */
422     M(PAGE_EXECUTE_READWRITE, PAGE_EXECUTE_WRITECOPY,
423       FILE_MAP_WRITE | FILE_MAP_EXECUTE, NULL),
424   };
425 #undef M
426
427   size_t ix;
428
429   NaClLog(3,
430           "NaClflProtectAndDesiredAccessMap(prot 0x%x,"
431           " priv 0x%x, accmode 0x%x, ...)\n",
432           prot, is_private, accmode);
433
434   NACL_COMPILE_TIME_ASSERT(NACL_ABI_O_RDONLY == 0);
435   NACL_COMPILE_TIME_ASSERT(NACL_ABI_O_RDWR == 2);
436   NACL_COMPILE_TIME_ASSERT(NACL_ABI_PROT_NONE == 0);
437   NACL_COMPILE_TIME_ASSERT(NACL_ABI_PROT_READ == 1);
438   NACL_COMPILE_TIME_ASSERT(NACL_ABI_PROT_WRITE == 2);
439   NACL_COMPILE_TIME_ASSERT(NACL_ABI_PROT_EXEC == 4);
440
441   CHECK(accmode != NACL_ABI_O_WRONLY);
442
443   /*
444    * NACL_ABI_O_RDONLY == 0, NACL_ABI_O_RDWR == 2, so multiplying by 8
445    * yields a base separation of 8 for the 16 element subtable indexed
446    * by the NACL_ABI_PROT_{READ|WRITE|EXEC} and is_private values.
447    */
448   ix = ((prot & NACL_ABI_PROT_MASK) +
449         (is_private << 3) +
450         ((accmode & NACL_ABI_O_ACCMODE) << 3));
451
452   CHECK(ix < NACL_ARRAY_SIZE(table));  /* compiler should elide this */
453
454   if (NULL != out_flMappingProtect) {
455     *out_flMappingProtect = table[ix].flMappingProtect;
456   }
457   if (NULL != out_flProtect) {
458     *out_flProtect = table[ix].flProtect;
459   }
460   if (NULL != out_dwDesiredAccess) {
461     *out_dwDesiredAccess = table[ix].dwDesiredAccess;
462   }
463   if (NULL != out_msg) {
464     *out_msg = table[ix].err;
465   }
466
467   NaClLog(3, "NaClflProtectAndDesiredAccessMap: %s %s %s\n",
468           table[ix].flMappingProtect_str,
469           table[ix].flProtect_str,
470           table[ix].dwDesiredAccess_str);
471 }
472
473 /*
474  * Returns flProtect flags for VirtualAlloc'd memory, file based
475  * mappings should always use NaClflProtectAndDesiredAccessMap.
476  */
477 DWORD NaClflProtectMap(int prot) {
478 #define M(p) { p, #p }
479   static struct {
480     DWORD flProtect;
481     char const *flProtect_str;
482   } table[] = {
483     /* PROT_NONE */
484     M(PAGE_NOACCESS),
485     /* PROT_READ */
486     M(PAGE_READONLY),
487     /* PROT_WRITE */
488     M(PAGE_READWRITE),
489     /* PROT_READ | PROT_WRITE */
490     M(PAGE_READWRITE),
491
492     /* PROT_EXEC */
493     M(PAGE_EXECUTE),
494     /* PROT_READ | PROT_EXEC */
495     M(PAGE_EXECUTE_READ),
496     /* PROT_WRITE | PROT_EXEC */
497     M(PAGE_EXECUTE_READWRITE),
498     /* PROT_READ | PROT_WRITE | PROT_EXEC */
499     M(PAGE_EXECUTE_READWRITE),
500   };
501 #undef M
502
503   size_t ix;
504
505   NaClLog(3, "NaClflProtectMap(prot 0x%x)\n", prot);
506
507   NACL_COMPILE_TIME_ASSERT(NACL_ABI_PROT_NONE == 0);
508   NACL_COMPILE_TIME_ASSERT(NACL_ABI_PROT_READ == 1);
509   NACL_COMPILE_TIME_ASSERT(NACL_ABI_PROT_WRITE == 2);
510   NACL_COMPILE_TIME_ASSERT(NACL_ABI_PROT_EXEC == 4);
511
512   ix = (prot & NACL_ABI_PROT_MASK);
513   CHECK(ix < NACL_ARRAY_SIZE(table));  /* compiler should elide this */
514
515   NaClLog(3, "NaClflProtectMap: %s\n", table[ix].flProtect_str);
516
517   return table[ix].flProtect;
518 }
519
520 /*
521  * Unfortunately, when the descriptor is imported via
522  * NaClHostDescPosixTake or NaClHostDescPosixDup, the underlying file
523  * handle may not have GENERIC_EXECUTE permission associated with it,
524  * unlike the files open using NaClHostDescOpen.  This means that the
525  * CreateFileMapping with flMappingProtect that specifies PAGE_EXECUTE_*
526  * will fail. Since we don't know whether GENERIC_EXECUTE without doing
527  * a query, we instead lazily determine the need by detecting the
528  * CreateFileMapping error and retrying using a fallback
529  * flMappingProtect that does not have EXECUTE rights.  We record this
530  * in the descriptor so that the next time we do not have to try with
531  * the PAGE_EXECUTE_* and have it deterministically fail.
532  *
533  * This function is also used when mapping in anonymous memory.  We
534  * assume that we never map anonymous executable memory -- mmap of
535  * executable data is always from a file, and the page will be
536  * non-writable -- and we ensure that anonymous memory is never
537  * executable.
538  */
539 static DWORD NaClflProtectRemoveExecute(DWORD flProtect) {
540   switch (flProtect) {
541     case PAGE_EXECUTE:
542       return PAGE_NOACCESS;
543     case PAGE_EXECUTE_READ:
544       return PAGE_READONLY;
545     case PAGE_EXECUTE_READWRITE:
546       return PAGE_READWRITE;
547     case PAGE_EXECUTE_WRITECOPY:
548       return PAGE_WRITECOPY;
549   }
550   return flProtect;
551 }
552
553 /* Check if flProtect has executable permission. */
554 static int NaClflProtectHasExecute(DWORD flProtect) {
555   return flProtect == PAGE_EXECUTE ||
556          flProtect == PAGE_EXECUTE_READ ||
557          flProtect == PAGE_EXECUTE_READWRITE ||
558          flProtect == PAGE_EXECUTE_WRITECOPY;
559 }
560
561 /*
562  * TODO(mseaborn): Reduce duplication between this function and
563  * nacl::Map()/NaClMap().
564  */
565 uintptr_t NaClHostDescMap(struct NaClHostDesc *d,
566                           struct NaClDescEffector *effp,
567                           void                *start_addr,
568                           size_t              len,
569                           int                 prot,
570                           int                 flags,
571                           nacl_off64_t        offset) {
572   uintptr_t retval;
573   uintptr_t addr;
574   int       desc_flags;
575   HANDLE    hFile;
576   HANDLE    hMap;
577   int       retry_fallback;
578   DWORD     flMappingProtect;
579   DWORD     dwDesiredAccess;
580   DWORD     flProtect;
581   DWORD     flOldProtect;
582   char const *err_msg;
583   DWORD     dwMaximumSizeHigh;
584   DWORD     dwMaximumSizeLow;
585   uintptr_t map_result;
586   size_t    chunk_offset;
587   size_t    chunk_size;
588
589   if (NULL == d && 0 == (flags & NACL_ABI_MAP_ANONYMOUS)) {
590     NaClLog(LOG_FATAL, "NaClHostDescMap: 'this' is NULL and not anon map\n");
591   }
592   if (NULL != d && -1 == d->d) {
593     NaClLog(LOG_FATAL, "NaClHostDescMap: already closed\n");
594   }
595   if ((0 == (flags & NACL_ABI_MAP_SHARED)) ==
596       (0 == (flags & NACL_ABI_MAP_PRIVATE))) {
597     NaClLog(LOG_FATAL,
598             "NaClHostDescMap: exactly one of NACL_ABI_MAP_SHARED"
599             " and NACL_ABI_MAP_PRIVATE must be set.\n");
600   }
601   addr = (uintptr_t) start_addr;
602   prot &= NACL_ABI_PROT_MASK;
603
604   /*
605    * Check that if FIXED, start_addr is not NULL.
606    * Use platform free address space locator to set start_addr if NULL and
607    * not FIXED.
608    */
609   if (0 == (flags & NACL_ABI_MAP_FIXED)) {
610     /*
611      * Not fixed, addr is a hint... which we ignore.  We cannot just
612      * let windows pick, since we are mapping memory in chunks of
613      * 64-kB to permit piecewise unmapping.
614      */
615     if (!NaClFindAddressSpace(&addr, len)) {
616       NaClLog(LOG_ERROR,
617               "NaClHostDescMap: not fixed, and could not find space\n");
618       return (uintptr_t) -NACL_ABI_ENOMEM;
619     }
620
621     NaClLog(4,
622             "NaClHostDescMap: NOT FIXED, found space at %"NACL_PRIxPTR"\n",
623             addr);
624
625     start_addr = (void *) addr;
626   }
627
628   flProtect = 0;
629   dwDesiredAccess = 0;
630
631   if (0 != (flags & NACL_ABI_MAP_ANONYMOUS)) {
632     /*
633      * anonymous memory must be free'able later via VirtualFree
634      */
635     NaClLog(3, "NaClHostDescMap: anonymous mapping\n");
636
637     flProtect = NaClflProtectMap(prot & (~PROT_EXEC));
638     NaClLog(3, "NaClHostDescMap: flProtect 0x%x\n", flProtect);
639
640     for (chunk_offset = 0;
641          chunk_offset < len;
642          chunk_offset += NACL_MAP_PAGESIZE) {
643       uintptr_t chunk_addr = addr + chunk_offset;
644
645       (*effp->vtbl->UnmapMemory)(effp, chunk_addr, NACL_MAP_PAGESIZE);
646
647       NaClLog(3,
648               "NaClHostDescMap: VirtualAlloc(0x%08x,,%x,%x)\n",
649               (void *) (addr + chunk_offset),
650               MEM_COMMIT | MEM_RESERVE,
651               flProtect);
652       map_result = (uintptr_t) VirtualAlloc((void *) chunk_addr,
653                                             NACL_MAP_PAGESIZE,
654                                             MEM_COMMIT | MEM_RESERVE,
655                                             flProtect);
656       if (map_result != addr + chunk_offset) {
657         NaClLog(LOG_FATAL,
658                 ("Could not VirtualAlloc anonymous memory at"
659                  " addr 0x%08x with prot %x\n"),
660                 addr + chunk_offset, flProtect);
661       }
662     }
663     NaClLog(3, "NaClHostDescMap: (anon) returning 0x%08"NACL_PRIxPTR"\n",
664             start_addr);
665     return (uintptr_t) start_addr;
666   }
667
668   if (NULL == d) {
669     desc_flags = NACL_ABI_O_RDWR;
670   } else {
671     desc_flags = d->flags;
672   }
673
674   if (0 != (desc_flags & NACL_ABI_O_APPEND) &&
675       0 != (prot & NACL_ABI_PROT_WRITE)) {
676     return (uintptr_t) -NACL_ABI_EACCES;
677   }
678   if (NACL_ABI_O_WRONLY == (desc_flags & NACL_ABI_O_ACCMODE)) {
679     return (uintptr_t) -NACL_ABI_EACCES;
680   }
681   NaClflProtectAndDesiredAccessMap(prot,
682                                    0 != (flags & NACL_ABI_MAP_PRIVATE),
683                                    (desc_flags & NACL_ABI_O_ACCMODE),
684                                    &flMappingProtect,
685                                    &flProtect,
686                                    &dwDesiredAccess,
687                                    &err_msg);
688   if (0 == flProtect) {
689     NaClLog(3, "NaClHostDescMap: %s\n", err_msg);
690     return (uintptr_t) -NACL_ABI_EACCES;
691   }
692   NaClLog(3,
693           "NaClHostDescMap: flMappingProtect 0x%x,"
694           " dwDesiredAccess 0x%x, flProtect 0x%x\n",
695           flMappingProtect, dwDesiredAccess, flProtect);
696
697   hFile = (HANDLE) _get_osfhandle(d->d);
698   dwMaximumSizeLow = 0;
699   dwMaximumSizeHigh = 0;
700
701   /*
702    * Ensure consistency of the d->flMappingProtect access.
703    */
704   NaClFastMutexLock(&d->mu);
705   if (0 != d->flMappingProtect) {
706     flMappingProtect = d->flMappingProtect;
707     retry_fallback = 0;
708   } else {
709     retry_fallback = 1;
710   }
711   NaClFastMutexUnlock(&d->mu);
712
713   /*
714    * Finite retry cycle.  We can fallback from PAGE_EXECUTE_WRITECOPY to
715    * PAGE_EXECUTE_READ and from having executable permissions to not having
716    * them.
717    */
718   while (1) {
719     /*
720      * If hFile is INVALID_HANDLE_VALUE, the memory is backed by the
721      * system paging file.  Why does it returns NULL instead of
722      * INVALID_HANDLE_VALUE when there is an error?
723      */
724     hMap = CreateFileMapping(hFile,
725                              NULL,
726                              flMappingProtect,
727                              dwMaximumSizeHigh,
728                              dwMaximumSizeLow,
729                              NULL);
730     if (NULL == hMap && retry_fallback) {
731       /*
732        * PAGE_EXECUTE_WRITECOPY is not supported on Windows XP so we fallback
733        * to PAGE_EXECUTE_READ.
734        */
735       if (PAGE_EXECUTE_WRITECOPY == flMappingProtect) {
736         NaClLog(3,
737                 "NaClHostDescMap: CreateFileMapping failed, retrying with"
738                 " PAGE_EXECUTE_READ instead of PAGE_EXECUTE_WRITECOPY\n");
739         flMappingProtect = PAGE_EXECUTE_READ;
740         continue;
741       }
742       if (0 == (prot & NACL_ABI_PROT_EXEC) &&
743           NaClflProtectHasExecute(flMappingProtect)) {
744         NaClLog(3,
745                 "NaClHostDescMap: CreateFileMapping failed, retrying without"
746                 " execute permission.  Original flMappingProtect 0x%x\n",
747                 flMappingProtect);
748         NaClflProtectAndDesiredAccessMap(prot & (~PROT_EXEC),
749                                          0 != (flags & NACL_ABI_MAP_PRIVATE),
750                                          (desc_flags & NACL_ABI_O_ACCMODE),
751                                          &flMappingProtect,
752                                          &flProtect,
753                                          &dwDesiredAccess,
754                                          &err_msg);
755         if (0 == flProtect) {
756           NaClLog(3, "NaClHostDescMap: %s\n", err_msg);
757           return (uintptr_t) -NACL_ABI_EACCES;
758         }
759         flMappingProtect = NaClflProtectRemoveExecute(flMappingProtect);
760         NaClLog(3,
761                 "NaClHostDescMap: fallback flMappingProtect 0x%x,"
762                 " dwDesiredAccess 0x%x, flProtect 0x%x\n",
763                 flMappingProtect, dwDesiredAccess, flProtect);
764         continue;
765       }
766       NaClLog(3,
767               "NaClHostDescMap: not retrying, since caller explicitly asked"
768               " for NACL_ABI_PROT_EXEC\n");
769       break;
770     }
771     /*
772      * Remember successful flProtect used.  Note that this just
773      * ensures reads of d->flMappingProtect gets a consistent value;
774      * we have a potential race where two threads perform mmap and in
775      * parallel determine the replacement flProtect value.  This is
776      * okay, since those two threads should arrive at the same
777      * replacement value.  This could be replaced with an atomic
778      * word.
779      */
780     NaClFastMutexLock(&d->mu);
781     d->flMappingProtect = flMappingProtect;
782     NaClFastMutexUnlock(&d->mu);
783     break;
784   }
785
786   if (NULL == hMap) {
787     DWORD err = GetLastError();
788     NaClLog(LOG_INFO,
789             "NaClHostDescMap: CreateFileMapping failed: %d\n",
790             err);
791     return -NaClXlateSystemError(err);
792   }
793   NaClLog(3, "NaClHostDescMap: CreateFileMapping got handle %d\n", (int) hMap);
794   NaClLog(3, "NaClHostDescMap: dwDesiredAccess 0x%x\n", dwDesiredAccess);
795
796   retval = (uintptr_t) -NACL_ABI_EINVAL;
797
798   for (chunk_offset = 0;
799        chunk_offset < len;
800        chunk_offset += NACL_MAP_PAGESIZE) {
801     uintptr_t chunk_addr = addr + chunk_offset;
802     nacl_off64_t net_offset;
803     uint32_t net_offset_high;
804     uint32_t net_offset_low;
805
806     (*effp->vtbl->UnmapMemory)(effp, chunk_addr, NACL_MAP_PAGESIZE);
807
808     chunk_size = size_min(len - chunk_offset, NACL_MAP_PAGESIZE);
809     /* in case MapViewOfFile cares that we exceed the file size */
810     net_offset = offset + chunk_offset;
811     net_offset_high = (uint32_t) (net_offset >> 32);
812     net_offset_low = (uint32_t) net_offset;
813     NaClLog(4,
814             "NaClHostDescMap: MapViewOfFileEx(hMap=%d, dwDesiredAccess=0x%x,"
815             " net_offset_high = 0x%08x, net_offset_low = 0x%08x,"
816             " chunk_size = 0x%"NACL_PRIxS", chunk_addr = 0x%"NACL_PRIxPTR"\n",
817             hMap, dwDesiredAccess, net_offset_high, net_offset_low,
818             chunk_size, chunk_addr);
819     map_result = (uintptr_t) MapViewOfFileEx(hMap,
820                                              dwDesiredAccess,
821                                              net_offset_high,
822                                              net_offset_low,
823                                              chunk_size,
824                                              (void *) chunk_addr);
825     NaClLog(3,
826             "NaClHostDescMap: map_result %"NACL_PRIxPTR
827             ", chunk_addr %"NACL_PRIxPTR
828             ", addr + chunk_offset %"NACL_PRIxPTR"\n",
829             map_result, chunk_addr, (addr + chunk_offset));
830     if ((addr + chunk_offset) != map_result) {
831       DWORD err = GetLastError();
832       NaClLog(LOG_FATAL,
833               "MapViewOfFileEx failed at 0x%08"NACL_PRIxPTR
834               ", got 0x%08"NACL_PRIxPTR", err %x\n",
835               addr + chunk_offset,
836               map_result,
837               err);
838     }
839     if (!VirtualProtect((void *) map_result,
840                         NaClRoundPage(chunk_size),
841                         flProtect,
842                         &flOldProtect)) {
843         DWORD err = GetLastError();
844         NaClLog(LOG_INFO,
845                 "VirtualProtect failed at 0x%08x, err %x\n",
846                 addr, err);
847         retval = (uintptr_t) -NaClXlateSystemError(err);
848         goto cleanup;
849     }
850   }
851   retval = (uintptr_t) start_addr;
852 cleanup:
853   (void) CloseHandle(hMap);
854   NaClLog(3, "NaClHostDescMap: returning %"NACL_PRIxPTR"\n", retval);
855   return retval;
856 }
857
858 int NaClHostDescUnmapUnsafe(void    *start_addr,
859                             size_t  len) {
860   uintptr_t addr;
861   size_t    off;
862
863   addr = (uintptr_t) start_addr;
864
865   for (off = 0; off < len; off += NACL_MAP_PAGESIZE) {
866     if (!UnmapViewOfFile((void *) (addr + off))) {
867       NaClLog(LOG_ERROR,
868               "NaClHostDescUnmap: UnmapViewOfFile(0x%08x) failed\n",
869               addr + off);
870       return -NACL_ABI_EINVAL;
871     }
872   }
873   return 0;
874 }
875
876 static void NaClHostDescCtorIntern(struct NaClHostDesc *hd,
877                                    int posix_d,
878                                    int flags) {
879   nacl_host_stat_t stbuf;
880
881   hd->d = posix_d;
882   hd->flags = flags;
883   hd->flMappingProtect = 0;
884   if (_fstat64(posix_d, &stbuf) != 0) {
885     /* inherited non-fstat'able are IPC channels, e.g., for bootstrap channel */
886     NaClLog(4,
887             "NaClHostDescCtorIntern: could not _fstat64,"
888             " assuming non-seekable\n");
889     hd->protect_filepos = 0;
890   } else {
891     int file_type = stbuf.st_mode & S_IFMT;
892     /*
893      * Inherited stdio are console handles and are not seekable.
894      *
895      * Posix descriptors (wrapping Windows HANDLES) opened for
896      * O_WRONLY | O_APPEND cannot have byte range locks applied, which
897      * is how the protect_filepos mechanism is implemented.  Luckily,
898      * this is only needed for O_RDWR | O_APPEND or non-append
899      * descriptor.
900      */
901     hd->protect_filepos = (((S_IFREG == file_type) ||
902                            (S_IFDIR == file_type)) &&
903                            !((flags & NACL_ABI_O_APPEND) != 0 &&
904                              (flags & NACL_ABI_O_ACCMODE) ==
905                              NACL_ABI_O_WRONLY));
906   }
907   if (!NaClFastMutexCtor(&hd->mu)) {
908     NaClLog(LOG_FATAL, "NaClHostDescCtorIntern: NaClFastMutexCtor failed\n");
909   }
910 }
911
912 int NaClHostDescOpen(struct NaClHostDesc  *d,
913                      char const           *path,
914                      int                  flags,
915                      int                  perms) {
916   DWORD dwDesiredAccess;
917   DWORD dwCreationDisposition;
918   DWORD dwFlagsAndAttributes;
919   int oflags;
920   int truncate_after_open = 0;
921   HANDLE hFile;
922   DWORD err;
923   int fd;
924
925   if (NULL == d) {
926     NaClLog(LOG_FATAL, "NaClHostDescOpen: 'this' is NULL\n");
927   }
928
929   /*
930    * Sanitize access flags.
931    */
932   if (0 != (flags & ~NACL_ALLOWED_OPEN_FLAGS)) {
933     return -NACL_ABI_EINVAL;
934   }
935
936   switch (flags & NACL_ABI_O_ACCMODE) {
937     case NACL_ABI_O_RDONLY:
938       dwDesiredAccess = GENERIC_READ | GENERIC_EXECUTE;
939       oflags = _O_RDONLY | _O_BINARY;
940       break;
941     case NACL_ABI_O_RDWR:
942       oflags = _O_RDWR | _O_BINARY;
943       dwDesiredAccess = GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE;
944       break;
945     case NACL_ABI_O_WRONLY:  /* Enforced in the Read call */
946       oflags = _O_WRONLY | _O_BINARY;
947       dwDesiredAccess = GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE;
948       break;
949     default:
950       NaClLog(LOG_ERROR,
951               "NaClHostDescOpen: bad access flags 0x%x.\n",
952               flags);
953       return -NACL_ABI_EINVAL;
954   }
955   /*
956    * Possibly make the file read-only.  The file attribute only
957    * applies if the file is created; if it pre-exists, the attributes
958    * from the file is combined with the FILE_FLAG_* values.
959    */
960   if (0 == (perms & NACL_ABI_S_IWUSR)) {
961     dwFlagsAndAttributes = (FILE_ATTRIBUTE_READONLY |
962                             FILE_FLAG_POSIX_SEMANTICS);
963   } else {
964     dwFlagsAndAttributes = (FILE_ATTRIBUTE_NORMAL |
965                             FILE_FLAG_POSIX_SEMANTICS);
966   }
967   /*
968    * Postcondition: flags & NACL_ABI_O_ACCMODE is one of the three
969    * allowed values.
970    */
971   switch (flags & (NACL_ABI_O_CREAT | NACL_ABI_O_TRUNC)) {
972     case 0:
973       dwCreationDisposition = OPEN_EXISTING;
974       break;
975     case NACL_ABI_O_CREAT:
976       dwCreationDisposition = OPEN_ALWAYS;
977       break;
978     case NACL_ABI_O_TRUNC:
979       dwCreationDisposition = TRUNCATE_EXISTING;
980       truncate_after_open = 1;
981       break;
982     case NACL_ABI_O_CREAT | NACL_ABI_O_TRUNC:
983       dwCreationDisposition = OPEN_ALWAYS;
984       truncate_after_open = 1;
985   }
986   if (0 != (flags & NACL_ABI_O_APPEND)) {
987     oflags |= _O_APPEND;
988   }
989
990   NaClLog(1,
991           "NaClHostDescOpen: CreateFileA(path=%s, desired_access=0x%x,"
992           " share_mode=ALL, security_attributes=NULL, creation_disposition=%d,"
993           " flags_and_attributes=%d, template_file=NULL)\n",
994           path, dwDesiredAccess, dwCreationDisposition, dwFlagsAndAttributes);
995
996   hFile = CreateFileA(path, dwDesiredAccess,
997                       (FILE_SHARE_DELETE |
998                        FILE_SHARE_READ |
999                        FILE_SHARE_WRITE),
1000                       NULL,
1001                       dwCreationDisposition,
1002                       dwFlagsAndAttributes,
1003                       NULL);
1004   if (INVALID_HANDLE_VALUE == hFile) {
1005     err = GetLastError();
1006     NaClLog(3, "NaClHostDescOpen: CreateFile failed %d\n", err);
1007     return -NaClXlateSystemError(err);
1008   }
1009   if (truncate_after_open &&
1010       NACL_ABI_O_RDONLY != (flags & NACL_ABI_O_ACCMODE)) {
1011     NaClLog(4, "NaClHostDescOpen: Truncating file\n");
1012     if (!SetEndOfFile(hFile)) {
1013       err = GetLastError();
1014       NaClLog(LOG_ERROR,
1015               "NaClHostDescOpen: could not truncate file:"
1016               " last error %d.\n",
1017               err);
1018       if (err == ERROR_USER_MAPPED_FILE) {
1019         NaClLog(LOG_ERROR,
1020                 "NaClHostDescOpen: this is due to an existing mapping"
1021                 " of the same file.\n");
1022       }
1023     }
1024   }
1025   fd = _open_osfhandle((intptr_t) hFile, oflags);
1026   /*
1027    * oflags _O_APPEND, _O_RDONLY, and _O_TEXT are meaningful; unclear
1028    * whether _O_RDWR, _O_WRONLY, etc has any effect.
1029    */
1030   if (-1 == fd) {
1031     NaClLog(LOG_FATAL, "NaClHostDescOpen failed: err %d\n",
1032             GetLastError());
1033   }
1034   NaClHostDescCtorIntern(d, fd, flags);
1035   return 0;
1036 }
1037
1038 int NaClHostDescPosixDup(struct NaClHostDesc  *d,
1039                          int                  posix_d,
1040                          int                  flags) {
1041   int host_desc;
1042
1043   NaClLog(3, "NaClHostDescPosixDup(0x%08x, %d, 0%o)\n",
1044           (uintptr_t) d, posix_d, flags);
1045   if (NULL == d) {
1046     NaClLog(LOG_FATAL, "NaClHostDescPosixDup: 'this' is NULL\n");
1047   }
1048   /*
1049    * Sanitize access flags.
1050    */
1051   if (0 != (flags & ~NACL_ALLOWED_OPEN_FLAGS)) {
1052     return -NACL_ABI_EINVAL;
1053   }
1054   switch (flags & NACL_ABI_O_ACCMODE) {
1055     case NACL_ABI_O_RDONLY:
1056     case NACL_ABI_O_WRONLY:
1057     case NACL_ABI_O_RDWR:
1058       break;
1059     default:
1060       NaClLog(LOG_ERROR,
1061               "NaClHostDescOpen: bad access flags 0x%x.\n",
1062               flags);
1063       return -NACL_ABI_EINVAL;
1064   }
1065
1066   host_desc = _dup(posix_d);
1067   if (-1 == host_desc) {
1068     return -GetErrno();
1069   }
1070   NaClHostDescCtorIntern(d, host_desc, flags);
1071   return 0;
1072 }
1073
1074 int NaClHostDescPosixTake(struct NaClHostDesc *d,
1075                           int                 posix_d,
1076                           int                 flags) {
1077   if (NULL == d) {
1078     NaClLog(LOG_FATAL, "NaClHostDescPosixTake: 'this' is NULL\n");
1079   }
1080   /*
1081    * Sanitize access flags.
1082    */
1083   if (0 != (flags & ~NACL_ALLOWED_OPEN_FLAGS)) {
1084     return -NACL_ABI_EINVAL;
1085   }
1086   switch (flags & NACL_ABI_O_ACCMODE) {
1087     case NACL_ABI_O_RDONLY:
1088     case NACL_ABI_O_WRONLY:
1089     case NACL_ABI_O_RDWR:
1090       break;
1091     default:
1092       NaClLog(LOG_ERROR,
1093               "NaClHostDescOpen: bad access flags 0x%x.\n",
1094               flags);
1095       return -NACL_ABI_EINVAL;
1096   }
1097   NaClHostDescCtorIntern(d, posix_d, flags);
1098   return 0;
1099 }
1100
1101 ssize_t NaClHostDescRead(struct NaClHostDesc  *d,
1102                          void                 *buf,
1103                          size_t               len) {
1104   /* Windows ReadFile only supports DWORD, so we need
1105    * to clamp the length. */
1106   unsigned int actual_len;
1107   HANDLE fh;
1108   DWORD bytes_received;
1109   DWORD err;
1110
1111   if (len < UINT_MAX) {
1112     actual_len = (unsigned int) len;
1113   } else {
1114     actual_len = UINT_MAX;
1115   }
1116
1117   NaClHostDescCheckValidity("NaClHostDescRead", d);
1118   if (NACL_ABI_O_WRONLY == (d->flags & NACL_ABI_O_ACCMODE)) {
1119     NaClLog(3, "NaClHostDescRead: WRONLY file\n");
1120     return -NACL_ABI_EBADF;
1121   }
1122   /*
1123    * We drop into using Windows ReadFile rather than using _read from
1124    * the POSIX compatibility layer here.  The reason for this is
1125    * because the pread/pwrite implementation uses ReadFile/WriteFile,
1126    * it would be more consistent with the pread/pwrite implementation
1127    * to just also use ReadFile/WriteFile directly here as well.
1128    *
1129    * NB: contrary to the documentation available on MSDN, operations
1130    * on synchronous files with non-NULL LPOVERLAPPED arguments result
1131    * in the *implicit* file position getting updated before the
1132    * ReadFile/WriteFile returning, rather than the Offset/OffsetHigh
1133    * members of the explicit OVERLAPPED structure (!).  In order to
1134    * support mixed read/pread syscall sequences (and similarly mixed
1135    * write/pwrite sequences) we must effectively lock the file
1136    * position from access by other threads and then read/write, so
1137    * that when pread/pwrite mess up the implicit file position
1138    * temporarily, it would not be visible.
1139    */
1140   fh = (HANDLE) _get_osfhandle(d->d);
1141   CHECK(INVALID_HANDLE_VALUE != fh);
1142
1143   /*
1144    * Ensure that we do not corrupt shared implicit file position.
1145    */
1146   if (d->protect_filepos) {
1147     NaClTakeFilePosLock(fh);
1148   }
1149   if (!ReadFile(fh, buf, actual_len, &bytes_received, NULL)) {
1150     err = GetLastError();
1151     if (ERROR_HANDLE_EOF == err) {
1152       bytes_received = 0;
1153     } else {
1154       NaClLog(4, "NaClHostDescRead: ReadFile error %d\n", err);
1155       bytes_received = -NaClXlateSystemError(err);
1156     }
1157   }
1158   if (d->protect_filepos) {
1159     NaClDropFilePosLock(fh);
1160   }
1161
1162   return bytes_received;
1163 }
1164
1165 ssize_t NaClHostDescWrite(struct NaClHostDesc *d,
1166                           void const          *buf,
1167                           size_t              len) {
1168   /*
1169    * Windows WriteFile only supports DWORD uint, so we need to clamp
1170    * the length.
1171    */
1172   unsigned int actual_len;
1173   HANDLE fh;
1174   DWORD bytes_written;
1175   DWORD err;
1176   OVERLAPPED overlap;
1177   OVERLAPPED *overlap_ptr = NULL;
1178
1179   if (NACL_ABI_O_RDONLY == (d->flags & NACL_ABI_O_ACCMODE)) {
1180     NaClLog(3, "NaClHostDescWrite: RDONLY file\n");
1181     return -NACL_ABI_EBADF;
1182   }
1183   if (len < UINT_MAX) {
1184     actual_len = (unsigned int) len;
1185   } else {
1186     actual_len = UINT_MAX;
1187   }
1188
1189   NaClHostDescCheckValidity("NaClHostDescWrite", d);
1190   /*
1191    * See discussion in NaClHostDescRead above wrt why we use WriteFile
1192    * instead of _write below.
1193    */
1194   if (0 != (NACL_ABI_O_APPEND & d->flags)) {
1195     nacl_off64_t offset = GG_LONGLONG(0xffffffffffffffff);
1196     memset(&overlap, 0, sizeof overlap);
1197     overlap.Offset = (DWORD) offset;
1198     overlap.OffsetHigh = (DWORD) (offset >> 32);
1199     overlap_ptr = &overlap;
1200   }
1201   fh = (HANDLE) _get_osfhandle(d->d);
1202   CHECK(INVALID_HANDLE_VALUE != fh);
1203   /*
1204    * Ensure that we do not corrupt shared implicit file position.
1205    */
1206   if (d->protect_filepos) {
1207     NaClTakeFilePosLock(fh);
1208   }
1209   if (!WriteFile(fh, buf, actual_len, &bytes_written, overlap_ptr)) {
1210     err = GetLastError();
1211     NaClLog(4, "NaClHostDescWrite: WriteFile error %d\n", err);
1212
1213     bytes_written = -NaClXlateSystemError(err);
1214   }
1215   if (d->protect_filepos) {
1216     NaClDropFilePosLock(fh);
1217   }
1218
1219   return bytes_written;
1220 }
1221
1222 nacl_off64_t NaClHostDescSeek(struct NaClHostDesc  *d,
1223                               nacl_off64_t         offset,
1224                               int                  whence) {
1225   HANDLE hFile;
1226   nacl_off64_t retval;
1227
1228   NaClHostDescCheckValidity("NaClHostDescSeek", d);
1229   hFile = (HANDLE) _get_osfhandle(d->d);
1230   CHECK(INVALID_HANDLE_VALUE != hFile);
1231   if (d->protect_filepos) {
1232     NaClTakeFilePosLock(hFile);
1233   }
1234   retval = _lseeki64(d->d, offset, whence);
1235   if (d->protect_filepos) {
1236     NaClDropFilePosLock(hFile);
1237   }
1238   return (-1 == retval) ? -errno : retval;
1239 }
1240
1241 ssize_t NaClHostDescPRead(struct NaClHostDesc *d,
1242                           void *buf,
1243                           size_t len,
1244                           nacl_off64_t offset) {
1245   HANDLE fh;
1246   OVERLAPPED overlap;
1247   DWORD bytes_received;
1248   DWORD err;
1249   nacl_off64_t orig_pos = 0;
1250
1251   NaClHostDescCheckValidity("NaClHostDescPRead", d);
1252   if (NACL_ABI_O_WRONLY == (d->flags & NACL_ABI_O_ACCMODE)) {
1253     NaClLog(3, "NaClHostDescPRead: WRONLY file\n");
1254     return -NACL_ABI_EBADF;
1255   }
1256   if (offset < 0) {
1257     return -NACL_ABI_EINVAL;
1258   }
1259   /*
1260    * There are reports of driver issues that may require clamping len
1261    * to a megabyte or so, lest ReadFile returns an error with
1262    * GetLastError() returning ERROR_INVALID_PARAMETER, but since we
1263    * do not expect to ever read from / write to anything other than
1264    * filesystem files, we do not clamp.
1265    */
1266   fh = (HANDLE) _get_osfhandle(d->d);
1267   CHECK(INVALID_HANDLE_VALUE != fh);
1268   memset(&overlap, 0, sizeof overlap);
1269   overlap.Offset = (DWORD) offset;
1270   overlap.OffsetHigh = (DWORD) (offset >> 32);
1271   if (len > UINT_MAX) {
1272     len = UINT_MAX;
1273   }
1274   if (d->protect_filepos) {
1275     orig_pos = NaClLockAndGetCurrentFilePos(fh);
1276   }
1277   if (!ReadFile(fh, buf, (DWORD) len, &bytes_received, &overlap)) {
1278     err = GetLastError();
1279     if (ERROR_HANDLE_EOF == err) {
1280       bytes_received = 0;
1281       /* handle as if returned true. */
1282     } else {
1283       NaClLog(4, "NaClHostDescPRead: ReadFile failed, error %d\n", err);
1284       NaClSetCurrentFilePosAndUnlock(fh, orig_pos);
1285       bytes_received = -NaClXlateSystemError(err);
1286     }
1287   }
1288   if (d->protect_filepos) {
1289     NaClSetCurrentFilePosAndUnlock(fh, orig_pos);
1290   }
1291   return bytes_received;
1292 }
1293
1294 ssize_t NaClHostDescPWrite(struct NaClHostDesc *d,
1295                            void const *buf,
1296                            size_t len,
1297                            nacl_off64_t offset) {
1298   HANDLE fh;
1299   OVERLAPPED overlap;
1300   DWORD bytes_sent;
1301   DWORD err;
1302   nacl_off64_t orig_pos = 0;
1303
1304   NaClHostDescCheckValidity("NaClHostDescPWrite", d);
1305   if (NACL_ABI_O_RDONLY == (d->flags & NACL_ABI_O_ACCMODE)) {
1306     NaClLog(3, "NaClHostDescPWrite: RDONLY file\n");
1307     return -NACL_ABI_EBADF;
1308   }
1309   if (offset < 0) {
1310     /*
1311      * This also avoids the case where having 0xffffffff in both
1312      * overlap.Offset and overlap.OffsetHigh means append to the file.
1313      * In Posix, offset does not permit special meanings being encoded
1314      * like this.
1315      */
1316     return -NACL_ABI_EINVAL;
1317   }
1318   fh = (HANDLE) _get_osfhandle(d->d);
1319   CHECK(INVALID_HANDLE_VALUE != fh);
1320   memset(&overlap, 0, sizeof overlap);
1321   overlap.Offset = (DWORD) offset;
1322   overlap.OffsetHigh = (DWORD) (offset >> 32);
1323   if (len > UINT_MAX) {
1324     len = UINT_MAX;
1325   }
1326   if (d->protect_filepos) {
1327     orig_pos = NaClLockAndGetCurrentFilePos(fh);
1328   }
1329   if (!WriteFile(fh, buf, (DWORD) len, &bytes_sent, &overlap)) {
1330     err = GetLastError();
1331     if (ERROR_HANDLE_EOF == err) {
1332       bytes_sent = 0;
1333       /* handle as if returned true. */
1334     } else {
1335       NaClLog(4,
1336               "NaClHostDescPWrite: WriteFile failed, error %d\n", err);
1337       bytes_sent = -NaClXlateSystemError(err);
1338     }
1339   }
1340   if (d->protect_filepos) {
1341     NaClSetCurrentFilePosAndUnlock(fh, orig_pos);
1342   }
1343   return bytes_sent;
1344 }
1345
1346 int NaClHostDescFstat(struct NaClHostDesc   *d,
1347                       nacl_host_stat_t      *nasp) {
1348   NaClHostDescCheckValidity("NaClHostDescFstat", d);
1349   if (NACL_HOST_FSTAT64(d->d, nasp) == -1) {
1350     return -GetErrno();
1351   }
1352
1353   return 0;
1354 }
1355
1356 int NaClHostDescIsatty(struct NaClHostDesc *d) {
1357   int retval;
1358
1359   NaClHostDescCheckValidity("NaClHostDescIsatty", d);
1360   retval = _isatty(d->d);
1361   /* When windows _isatty fails it returns zero, but does not set errno. */
1362   return (0 == retval) ? -NACL_ABI_ENOTTY : 1;
1363 }
1364
1365 int NaClHostDescClose(struct NaClHostDesc *d) {
1366   int retval;
1367
1368   NaClHostDescCheckValidity("NaClHostDescClose", d);
1369   if (-1 != d->d) {
1370     retval = _close(d->d);
1371     if (-1 == retval) {
1372       return -GetErrno();
1373     }
1374     d->d = -1;
1375   }
1376   NaClFastMutexDtor(&d->mu);
1377   return 0;
1378 }
1379
1380 /*
1381  * This is not a host descriptor function, but is closely related to
1382  * fstat and should behave similarly.
1383  */
1384 int NaClHostDescStat(char const *path, nacl_host_stat_t *nhsp) {
1385   if (NACL_HOST_STAT64(path, nhsp) == -1) {
1386     return -GetErrno();
1387   }
1388
1389   return 0;
1390 }
1391
1392 int NaClHostDescMkdir(const char *path, int mode) {
1393   UNREFERENCED_PARAMETER(mode);
1394   if (_mkdir(path) != 0)
1395     return -NaClXlateErrno(errno);
1396   return 0;
1397 }
1398
1399 int NaClHostDescRmdir(const char *path) {
1400   if (_rmdir(path) != 0)
1401     return -NaClXlateErrno(errno);
1402   return 0;
1403 }
1404
1405 int NaClHostDescChdir(const char *path) {
1406   if (_chdir(path) != 0)
1407     return -NaClXlateErrno(errno);
1408   return 0;
1409 }
1410
1411 int NaClHostDescGetcwd(char *path, size_t len) {
1412   if (_getcwd(path, (int) len) == NULL)
1413     return -NaClXlateErrno(errno);
1414   return 0;
1415 }
1416
1417 int NaClHostDescUnlink(const char *path) {
1418   /*
1419    * If the file exists and is not writable we make it writeable
1420    * before calling _unlink() to match the POSIX semantics where
1421    * unlink(2) can remove readonly files.
1422    */
1423   if (_access(path, WIN_F_OK) == 0 && _access(path, WIN_W_OK) != 0) {
1424     if (_chmod(path, _S_IREAD | S_IWRITE) != 0) {
1425       /* If _chmod fails just log it and contine on to call _unlink anyway */
1426       NaClLog(3, "NaClHostDescUnlink: _chmod failed: %d\n", errno);
1427     }
1428   }
1429
1430   if (_unlink(path) != 0)
1431     return -NaClXlateErrno(errno);
1432
1433   return 0;
1434 }
1435
1436 int NaClHostDescTruncate(char const *path, nacl_abi_off_t length) {
1437   LARGE_INTEGER win_length;
1438   DWORD err;
1439
1440   HANDLE hfile = CreateFileA(path,
1441       GENERIC_READ | GENERIC_WRITE,
1442       FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
1443       NULL,
1444       OPEN_EXISTING,
1445       FILE_ATTRIBUTE_NORMAL | FILE_FLAG_POSIX_SEMANTICS,
1446       NULL);
1447
1448   if (INVALID_HANDLE_VALUE == hfile) {
1449     err = GetLastError();
1450     NaClLog(3, "NaClHostDescTruncate: CreateFile failed %d\n", err);
1451     return -NaClXlateSystemError(err);
1452   }
1453
1454   win_length.QuadPart = length;
1455   if (!SetFilePointerEx(hfile, win_length, NULL, FILE_BEGIN)) {
1456     err = GetLastError();
1457     NaClLog(LOG_ERROR,
1458             "NaClHostDescTruncate: SetFilePointerEx failed:"
1459             " last error %d.\n", err);
1460     return -NaClXlateSystemError(err);
1461   }
1462
1463   if (!SetEndOfFile(hfile)) {
1464     err = GetLastError();
1465     NaClLog(LOG_ERROR,
1466             "NaClHostDescTruncate: could not truncate file:"
1467             " last error %d.\n", err);
1468     if (err == ERROR_USER_MAPPED_FILE) {
1469       NaClLog(LOG_ERROR,
1470               "NaClHostDescTruncate: this is due to an existing"
1471               " mapping of the same file.\n");
1472     }
1473     return -NaClXlateSystemError(err);
1474   }
1475
1476   return 0;
1477 }
1478
1479 int NaClHostDescLstat(char const *path, nacl_host_stat_t *nhsp) {
1480   /*
1481    * Since symlinks don't exist on windows, stat() and lstat()
1482    * are equivalent.
1483    */
1484   return NaClHostDescStat(path, nhsp);
1485 }
1486
1487 int NaClHostDescLink(const char *oldpath, const char *newpath) {
1488   /*
1489    * Hard linking not implemented for win32
1490    */
1491   NaClLog(1, "NaClHostDescLink: hard linking not supported on windows.\n");
1492   return -NACL_ABI_ENOSYS;
1493 }
1494
1495 int NaClHostDescRename(const char *oldpath, const char *newpath) {
1496   if (rename(oldpath, newpath) != 0)
1497     return -NaClXlateErrno(errno);
1498   return 0;
1499 }
1500
1501 int NaClHostDescSymlink(const char *oldpath, const char *newpath) {
1502   /*
1503    * Symlinks are not supported on win32.
1504    */
1505   NaClLog(1, "NaClHostDescSymlink: symbolic links not supported on windows.\n");
1506   return -NACL_ABI_ENOSYS;
1507 }
1508
1509 int NaClHostDescChmod(const char *path, nacl_abi_mode_t mode) {
1510   if (_chmod(path, NaClMapMode(mode)) != 0)
1511     return -NaClXlateErrno(errno);
1512   return 0;
1513 }
1514
1515 int NaClHostDescAccess(const char *path, int amode) {
1516   if (_access(path, NaClMapAccessMode(amode)) != 0)
1517     return -NaClXlateErrno(errno);
1518   return 0;
1519 }
1520
1521 int NaClHostDescReadlink(const char *path, char *buf, size_t bufsize) {
1522   /*
1523    * readlink(2) sets errno to EINVAL when the file in question is
1524    * not a symlink.  Since win32 does not support symlinks we simply
1525    * return EINVAL in all cases here.
1526    */
1527   NaClLog(1,
1528           "NaClHostDescReadlink: symbolic links not supported on Windows.\n");
1529   return -NACL_ABI_EINVAL;
1530 }