VirtualBox

source: kBuild/trunk/src/kash/shfile.c@ 2653

最後變更 在這個檔案從2653是 2653,由 bird 提交於 13 年 前

kash: fixed shfile_opendir on windows, and thereby argument expansion.

  • 屬性 svn:eol-style 設為 LF
  • 屬性 svn:keywords 設為 Id
檔案大小: 57.2 KB
 
1/* $Id: shfile.c 2653 2012-09-09 18:02:54Z bird $ */
2/** @file
3 *
4 * File management.
5 *
6 * Copyright (c) 2007-2010 knut st. osmundsen <[email protected]>
7 *
8 *
9 * This file is part of kBuild.
10 *
11 * kBuild is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * kBuild is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with kBuild; if not, write to the Free Software
23 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 *
25 */
26
27/*******************************************************************************
28* Header Files *
29*******************************************************************************/
30#include "shfile.h"
31#include "shinstance.h" /* TRACE2 */
32#include <stdlib.h>
33#include <stdio.h>
34#include <string.h>
35#include <assert.h>
36
37#if K_OS == K_OS_WINDOWS
38# include <limits.h>
39# ifndef PIPE_BUF
40# define PIPE_BUF 512
41# endif
42# include <ntstatus.h>
43# define WIN32_NO_STATUS
44# include <Windows.h>
45# if !defined(_WIN32_WINNT)
46# define _WIN32_WINNT 0x0502 /* Windows Server 2003 */
47# endif
48# include <winternl.h> //NTSTATUS
49#else
50# include <unistd.h>
51# include <fcntl.h>
52# include <dirent.h>
53#endif
54
55
56/*******************************************************************************
57* Defined Constants And Macros *
58*******************************************************************************/
59/** @def SHFILE_IN_USE
60 * Whether the file descriptor table stuff is actually in use or not.
61 */
62#if K_OS == K_OS_WINDOWS \
63 || K_OS == K_OS_OPENBSD /* because of ugly pthread library pipe hacks */ \
64 || !defined(SH_FORKED_MODE)
65# define SHFILE_IN_USE
66#endif
67/** The max file table size. */
68#define SHFILE_MAX 1024
69/** The file table growth rate. */
70#define SHFILE_GROW 64
71/** The min native unix file descriptor. */
72#define SHFILE_UNIX_MIN_FD 32
73/** The path buffer size we use. */
74#define SHFILE_MAX_PATH 4096
75
76/** Set errno and return. Doing a trace in debug build. */
77#define RETURN_ERROR(rc, err, msg) \
78 do { \
79 TRACE2((NULL, "%s: " ## msg ## " - returning %d / %d\n", __FUNCTION__, (rc), (err))); \
80 errno = (err); \
81 return (rc); \
82 } while (0)
83
84#if K_OS == K_OS_WINDOWS
85 /* See msdos.h for description. */
86# define FOPEN 0x01
87# define FEOFLAG 0x02
88# define FCRLF 0x04
89# define FPIPE 0x08
90# define FNOINHERIT 0x10
91# define FAPPEND 0x20
92# define FDEV 0x40
93# define FTEXT 0x80
94
95# define MY_ObjectBasicInformation 0
96# define MY_FileNamesInformation 12
97
98typedef struct
99{
100 ULONG Attributes;
101 ACCESS_MASK GrantedAccess;
102 ULONG HandleCount;
103 ULONG PointerCount;
104 ULONG PagedPoolUsage;
105 ULONG NonPagedPoolUsage;
106 ULONG Reserved[3];
107 ULONG NameInformationLength;
108 ULONG TypeInformationLength;
109 ULONG SecurityDescriptorLength;
110 LARGE_INTEGER CreateTime;
111} MY_OBJECT_BASIC_INFORMATION;
112
113#if 0
114typedef struct
115{
116 union
117 {
118 LONG Status;
119 PVOID Pointer;
120 };
121 ULONG_PTR Information;
122} MY_IO_STATUS_BLOCK;
123#else
124typedef IO_STATUS_BLOCK MY_IO_STATUS_BLOCK;
125#endif
126typedef MY_IO_STATUS_BLOCK *PMY_IO_STATUS_BLOCK;
127
128typedef struct
129{
130 ULONG NextEntryOffset;
131 ULONG FileIndex;
132 ULONG FileNameLength;
133 WCHAR FileName[1];
134} MY_FILE_NAMES_INFORMATION, *PMY_FILE_NAMES_INFORMATION;
135
136typedef NTSTATUS (NTAPI * PFN_NtQueryObject)(HANDLE, int, void *, size_t, size_t *);
137typedef NTSTATUS (NTAPI * PFN_NtQueryDirectoryFile)(HANDLE, HANDLE, void *, void *, PMY_IO_STATUS_BLOCK, void *,
138 ULONG, int, int, PUNICODE_STRING, int);
139typedef NTSTATUS (NTAPI * PFN_RtlUnicodeStringToAnsiString)(PANSI_STRING, PCUNICODE_STRING, int);
140
141
142#endif /* K_OS_WINDOWS */
143
144
145/*******************************************************************************
146* Global Variables *
147*******************************************************************************/
148#if K_OS == K_OS_WINDOWS
149static int g_shfile_globals_initialized = 0;
150static PFN_NtQueryObject g_pfnNtQueryObject = NULL;
151static PFN_NtQueryDirectoryFile g_pfnNtQueryDirectoryFile = NULL;
152static PFN_RtlUnicodeStringToAnsiString g_pfnRtlUnicodeStringToAnsiString = NULL;
153#endif /* K_OS_WINDOWS */
154
155
156#ifdef SHFILE_IN_USE
157
158/**
159 * Close the specified native handle.
160 *
161 * @param native The native file handle.
162 * @param flags The flags in case they might come in handy later.
163 */
164static void shfile_native_close(intptr_t native, unsigned flags)
165{
166# if K_OS == K_OS_WINDOWS
167 BOOL fRc = CloseHandle((HANDLE)native);
168 assert(fRc); (void)fRc;
169# else
170 int s = errno;
171 close(native);
172 errno = s;
173# endif
174 (void)flags;
175}
176
177/**
178 * Grows the descriptor table, making sure that it can hold @a fdMin,
179 *
180 * @returns The max(fdMin, fdFirstNew) on success, -1 on failure.
181 * @param pfdtab The table to grow.
182 * @param fdMin Grow to include this index.
183 */
184static int shfile_grow_tab_locked(shfdtab *pfdtab, int fdMin)
185{
186 /*
187 * Grow the descriptor table.
188 */
189 int fdRet = -1;
190 shfile *new_tab;
191 int new_size = pfdtab->size + SHFILE_GROW;
192 while (new_size < fdMin)
193 new_size += SHFILE_GROW;
194 new_tab = sh_realloc(shthread_get_shell(), pfdtab->tab, new_size * sizeof(shfile));
195 if (new_tab)
196 {
197 int i;
198 for (i = pfdtab->size; i < new_size; i++)
199 {
200 new_tab[i].fd = -1;
201 new_tab[i].oflags = 0;
202 new_tab[i].shflags = 0;
203 new_tab[i].native = -1;
204 }
205
206 fdRet = pfdtab->size;
207 if (fdRet < fdMin)
208 fdRet = fdMin;
209
210 pfdtab->tab = new_tab;
211 pfdtab->size = new_size;
212 }
213
214 return fdRet;
215}
216
217/**
218 * Inserts the file into the descriptor table.
219 *
220 * If we're out of memory and cannot extend the table, we'll close the
221 * file, set errno to EMFILE and return -1.
222 *
223 * @returns The file descriptor number. -1 and errno on failure.
224 * @param pfdtab The file descriptor table.
225 * @param native The native file handle.
226 * @param oflags The flags the it was opened/created with.
227 * @param shflags The shell file flags.
228 * @param fdMin The minimum file descriptor number, pass -1 if any is ok.
229 * @param who Who we're doing this for (for logging purposes).
230 */
231static int shfile_insert(shfdtab *pfdtab, intptr_t native, unsigned oflags, unsigned shflags, int fdMin, const char *who)
232{
233 shmtxtmp tmp;
234 int fd;
235 int i;
236
237 /*
238 * Fend of bad stuff.
239 */
240 if (fdMin >= SHFILE_MAX)
241 {
242 errno = EMFILE;
243 return -1;
244 }
245# if K_OS != K_OS_WINDOWS
246 if (fcntl((int)native, F_SETFD, fcntl((int)native, F_GETFD, 0) | FD_CLOEXEC) == -1)
247 {
248 int e = errno;
249 close((int)native);
250 errno = e;
251 return -1;
252 }
253# endif
254
255 shmtx_enter(&pfdtab->mtx, &tmp);
256
257 /*
258 * Search for a fitting unused location.
259 */
260 fd = -1;
261 for (i = fdMin >= 0 ? fdMin : 0; (unsigned)i < pfdtab->size; i++)
262 if (pfdtab->tab[i].fd == -1)
263 {
264 fd = i;
265 break;
266 }
267 if (fd == -1)
268 fd = shfile_grow_tab_locked(pfdtab, fdMin);
269
270 /*
271 * Fill in the entry if we've found one.
272 */
273 if (fd != -1)
274 {
275 pfdtab->tab[fd].fd = fd;
276 pfdtab->tab[fd].oflags = oflags;
277 pfdtab->tab[fd].shflags = shflags;
278 pfdtab->tab[fd].native = native;
279 }
280 else
281 shfile_native_close(native, oflags);
282
283 shmtx_leave(&pfdtab->mtx, &tmp);
284
285 if (fd == -1)
286 errno = EMFILE;
287 (void)who;
288 return fd;
289}
290
291# if K_OS != K_OS_WINDOWS
292/**
293 * Makes a copy of the native file, closes the original, and inserts the copy
294 * into the descriptor table.
295 *
296 * If we're out of memory and cannot extend the table, we'll close the
297 * file, set errno to EMFILE and return -1.
298 *
299 * @returns The file descriptor number. -1 and errno on failure.
300 * @param pfdtab The file descriptor table.
301 * @param pnative The native file handle on input, -1 on output.
302 * @param oflags The flags the it was opened/created with.
303 * @param shflags The shell file flags.
304 * @param fdMin The minimum file descriptor number, pass -1 if any is ok.
305 * @param who Who we're doing this for (for logging purposes).
306 */
307static int shfile_copy_insert_and_close(shfdtab *pfdtab, int *pnative, unsigned oflags, unsigned shflags, int fdMin, const char *who)
308{
309 int fd = -1;
310 int s = errno;
311 int native_copy = fcntl(*pnative, F_DUPFD, SHFILE_UNIX_MIN_FD);
312 close(*pnative);
313 *pnative = -1;
314 errno = s;
315
316 if (native_copy != -1)
317 fd = shfile_insert(pfdtab, native_copy, oflags, shflags, fdMin, who);
318 return fd;
319}
320# endif /* !K_OS_WINDOWS */
321
322/**
323 * Gets a file descriptor and lock the file descriptor table.
324 *
325 * @returns Pointer to the file and table ownership on success,
326 * NULL and errno set to EBADF on failure.
327 * @param pfdtab The file descriptor table.
328 * @param fd The file descriptor number.
329 * @param ptmp See shmtx_enter.
330 */
331static shfile *shfile_get(shfdtab *pfdtab, int fd, shmtxtmp *ptmp)
332{
333 shfile *file = NULL;
334 if ( fd >= 0
335 && (unsigned)fd < pfdtab->size)
336 {
337 shmtx_enter(&pfdtab->mtx, ptmp);
338 if ((unsigned)fd < pfdtab->size
339 && pfdtab->tab[fd].fd != -1)
340 file = &pfdtab->tab[fd];
341 else
342 shmtx_leave(&pfdtab->mtx, ptmp);
343 }
344 if (!file)
345 errno = EBADF;
346 return file;
347}
348
349/**
350 * Puts back a file descriptor and releases the table ownership.
351 *
352 * @param pfdtab The file descriptor table.
353 * @param file The file.
354 * @param ptmp See shmtx_leave.
355 */
356static void shfile_put(shfdtab *pfdtab, shfile *file, shmtxtmp *ptmp)
357{
358 shmtx_leave(&pfdtab->mtx, ptmp);
359 assert(file);
360 (void)file;
361}
362
363/**
364 * Constructs a path from the current directory and the passed in path.
365 *
366 * @returns 0 on success, -1 and errno set to ENAMETOOLONG or EINVAL on failure.
367 *
368 * @param pfdtab The file descriptor table
369 * @param path The path the caller supplied.
370 * @param buf Where to put the path. This is assumed to be SHFILE_MAX_PATH
371 * chars in size.
372 */
373int shfile_make_path(shfdtab *pfdtab, const char *path, char *buf)
374{
375 size_t path_len = strlen(path);
376 if (path_len == 0)
377 {
378 errno = EINVAL;
379 return -1;
380 }
381 if (path_len >= SHFILE_MAX_PATH)
382 {
383 errno = ENAMETOOLONG;
384 return -1;
385 }
386 if ( *path == '/'
387# if K_OS == K_OS_WINDOWS || K_OS == K_OS_OS2
388 || *path == '\\'
389 || ( *path
390 && path[1] == ':'
391 && ( (*path >= 'A' && *path <= 'Z')
392 || (*path >= 'a' && *path <= 'z')))
393# endif
394 )
395 {
396 memcpy(buf, path, path_len + 1);
397 }
398 else
399 {
400 size_t cwd_len;
401 shmtxtmp tmp;
402
403 shmtx_enter(&pfdtab->mtx, &tmp);
404
405 cwd_len = strlen(pfdtab->cwd);
406 memcpy(buf, pfdtab->cwd, cwd_len);
407
408 shmtx_leave(&pfdtab->mtx, &tmp);
409
410 if (cwd_len + path_len + 1 >= SHFILE_MAX_PATH)
411 {
412 errno = ENAMETOOLONG;
413 return -1;
414 }
415 if ( !cwd_len
416 || buf[cwd_len - 1] != '/')
417 buf[cwd_len++] = '/';
418 memcpy(buf + cwd_len, path, path_len + 1);
419 }
420
421# if K_OS == K_OS_WINDOWS || K_OS == K_OS_OS2
422 if (!strcmp(buf, "/dev/null"))
423 strcpy(buf, "NUL");
424# endif
425 return 0;
426}
427
428# if K_OS == K_OS_WINDOWS
429
430/**
431 * Converts a DOS(/Windows) error code to errno,
432 * assigning it to errno.
433 *
434 * @returns -1
435 * @param err The DOS error.
436 */
437static int shfile_dos2errno(int err)
438{
439 switch (err)
440 {
441 case ERROR_BAD_ENVIRONMENT: errno = E2BIG; break;
442 case ERROR_ACCESS_DENIED: errno = EACCES; break;
443 case ERROR_CURRENT_DIRECTORY: errno = EACCES; break;
444 case ERROR_LOCK_VIOLATION: errno = EACCES; break;
445 case ERROR_NETWORK_ACCESS_DENIED: errno = EACCES; break;
446 case ERROR_CANNOT_MAKE: errno = EACCES; break;
447 case ERROR_FAIL_I24: errno = EACCES; break;
448 case ERROR_DRIVE_LOCKED: errno = EACCES; break;
449 case ERROR_SEEK_ON_DEVICE: errno = EACCES; break;
450 case ERROR_NOT_LOCKED: errno = EACCES; break;
451 case ERROR_LOCK_FAILED: errno = EACCES; break;
452 case ERROR_NO_PROC_SLOTS: errno = EAGAIN; break;
453 case ERROR_MAX_THRDS_REACHED: errno = EAGAIN; break;
454 case ERROR_NESTING_NOT_ALLOWED: errno = EAGAIN; break;
455 case ERROR_INVALID_HANDLE: errno = EBADF; break;
456 case ERROR_INVALID_TARGET_HANDLE: errno = EBADF; break;
457 case ERROR_DIRECT_ACCESS_HANDLE: errno = EBADF; break;
458 case ERROR_WAIT_NO_CHILDREN: errno = ECHILD; break;
459 case ERROR_CHILD_NOT_COMPLETE: errno = ECHILD; break;
460 case ERROR_FILE_EXISTS: errno = EEXIST; break;
461 case ERROR_ALREADY_EXISTS: errno = EEXIST; break;
462 case ERROR_INVALID_FUNCTION: errno = EINVAL; break;
463 case ERROR_INVALID_ACCESS: errno = EINVAL; break;
464 case ERROR_INVALID_DATA: errno = EINVAL; break;
465 case ERROR_INVALID_PARAMETER: errno = EINVAL; break;
466 case ERROR_NEGATIVE_SEEK: errno = EINVAL; break;
467 case ERROR_TOO_MANY_OPEN_FILES: errno = EMFILE; break;
468 case ERROR_FILE_NOT_FOUND: errno = ENOENT; break;
469 case ERROR_PATH_NOT_FOUND: errno = ENOENT; break;
470 case ERROR_INVALID_DRIVE: errno = ENOENT; break;
471 case ERROR_NO_MORE_FILES: errno = ENOENT; break;
472 case ERROR_BAD_NETPATH: errno = ENOENT; break;
473 case ERROR_BAD_NET_NAME: errno = ENOENT; break;
474 case ERROR_BAD_PATHNAME: errno = ENOENT; break;
475 case ERROR_FILENAME_EXCED_RANGE: errno = ENOENT; break;
476 case ERROR_BAD_FORMAT: errno = ENOEXEC; break;
477 case ERROR_ARENA_TRASHED: errno = ENOMEM; break;
478 case ERROR_NOT_ENOUGH_MEMORY: errno = ENOMEM; break;
479 case ERROR_INVALID_BLOCK: errno = ENOMEM; break;
480 case ERROR_NOT_ENOUGH_QUOTA: errno = ENOMEM; break;
481 case ERROR_DISK_FULL: errno = ENOSPC; break;
482 case ERROR_DIR_NOT_EMPTY: errno = ENOTEMPTY; break;
483 case ERROR_BROKEN_PIPE: errno = EPIPE; break;
484 case ERROR_NOT_SAME_DEVICE: errno = EXDEV; break;
485 default: errno = EINVAL; break;
486 }
487 return -1;
488}
489
490/**
491 * Converts an NT status code to errno,
492 * assigning it to errno.
493 *
494 * @returns -1
495 * @param rcNt The NT status code.
496 */
497static int shfile_nt2errno(NTSTATUS rcNt)
498{
499 switch (rcNt)
500 {
501 default: errno = EINVAL; break;
502 }
503 return -1;
504}
505
506DWORD shfile_query_handle_access_mask(HANDLE h, PACCESS_MASK pMask)
507{
508 MY_OBJECT_BASIC_INFORMATION BasicInfo;
509 NTSTATUS rcNt;
510
511 if (!g_pfnNtQueryObject)
512 return ERROR_NOT_SUPPORTED;
513
514 rcNt = g_pfnNtQueryObject(h, MY_ObjectBasicInformation, &BasicInfo, sizeof(BasicInfo), NULL);
515 if (rcNt >= 0)
516 {
517 *pMask = BasicInfo.GrantedAccess;
518 return NO_ERROR;
519 }
520 if (rcNt != STATUS_INVALID_HANDLE)
521 return ERROR_GEN_FAILURE;
522 return ERROR_INVALID_HANDLE;
523}
524
525# endif /* K_OS == K_OS_WINDOWS */
526
527#endif /* SHFILE_IN_USE */
528
529/**
530 * Converts DOS slashes to UNIX slashes if necessary.
531 *
532 * @param pszPath The path to fix.
533 */
534static void shfile_fix_slashes(char *pszPath)
535{
536#if K_OS == K_OS_WINDOWS || K_OS == K_OS_OS2
537 while ((pszPath = strchr(pszPath, '\\')))
538 *pszPath++ = '/';
539#else
540 (void)pszPath;
541#endif
542}
543
544/**
545 * Initializes the global variables in this file.
546 */
547static void shfile_init_globals(void)
548{
549#if K_OS == K_OS_WINDOWS
550 if (!g_shfile_globals_initialized)
551 {
552 HMODULE hNtDll = GetModuleHandle("NTDLL");
553 g_pfnNtQueryObject = (PFN_NtQueryObject) GetProcAddress(hNtDll, "NtQueryObject");
554 g_pfnNtQueryDirectoryFile = (PFN_NtQueryDirectoryFile)GetProcAddress(hNtDll, "NtQueryDirectoryFile");
555 g_pfnRtlUnicodeStringToAnsiString = (PFN_RtlUnicodeStringToAnsiString)GetProcAddress(hNtDll, "RtlUnicodeStringToAnsiString");
556 if ( !g_pfnRtlUnicodeStringToAnsiString
557 || !g_pfnNtQueryDirectoryFile)
558 {
559 /* fatal error */
560 }
561 g_shfile_globals_initialized = 1;
562 }
563#endif
564}
565
566/**
567 * Initializes a file descriptor table.
568 *
569 * @returns 0 on success, -1 and errno on failure.
570 * @param pfdtab The table to initialize.
571 * @param inherit File descriptor table to inherit from. If not specified
572 * we will inherit from the current process as it were.
573 */
574int shfile_init(shfdtab *pfdtab, shfdtab *inherit)
575{
576 int rc;
577
578 shfile_init_globals();
579
580 pfdtab->cwd = NULL;
581 pfdtab->size = 0;
582 pfdtab->tab = NULL;
583 rc = shmtx_init(&pfdtab->mtx);
584 if (!rc)
585 {
586#ifdef SHFILE_IN_USE
587 /* Get CWD with unix slashes. */
588 char buf[SHFILE_MAX_PATH];
589 if (getcwd(buf, sizeof(buf)))
590 {
591 shfile_fix_slashes(buf);
592
593 pfdtab->cwd = sh_strdup(NULL, buf);
594 if (!inherit)
595 {
596# if K_OS == K_OS_WINDOWS
597 static const struct
598 {
599 DWORD dwStdHandle;
600 unsigned fFlags;
601 } aStdHandles[3] =
602 {
603 { STD_INPUT_HANDLE, _O_RDONLY },
604 { STD_OUTPUT_HANDLE, _O_WRONLY },
605 { STD_ERROR_HANDLE, _O_WRONLY }
606 };
607 int i;
608 STARTUPINFO Info;
609 ACCESS_MASK Mask;
610 DWORD dwErr;
611
612 rc = 0;
613
614 /* Try pick up the Visual C++ CRT file descriptor info. */
615 __try {
616 GetStartupInfo(&Info);
617 } __except (EXCEPTION_EXECUTE_HANDLER) {
618 memset(&Info, 0, sizeof(Info));
619 }
620
621 if ( Info.cbReserved2 > sizeof(int)
622 && (uintptr_t)Info.lpReserved2 >= 0x1000
623 && (i = *(int *)Info.lpReserved2) >= 1
624 && i <= 2048
625 && ( Info.cbReserved2 == i * 5 + 4
626 //|| Info.cbReserved2 == i * 5 + 1 - check the cygwin sources.
627 || Info.cbReserved2 == i * 9 + 4))
628 {
629 uint8_t *paf = (uint8_t *)Info.lpReserved2 + sizeof(int);
630 int dwPerH = 1 + (Info.cbReserved2 == i * 9 + 4);
631 DWORD *ph = (DWORD *)(paf + i) + dwPerH * i;
632 HANDLE aStdHandles2[3];
633 int j;
634
635 //if (Info.cbReserved2 == i * 5 + 1) - check the cygwin sources.
636 // i--;
637
638 for (j = 0; j < 3; j++)
639 aStdHandles2[j] = GetStdHandle(aStdHandles[j].dwStdHandle);
640
641 while (i-- > 0)
642 {
643 ph -= dwPerH;
644
645 if ( (paf[i] & (FOPEN | FNOINHERIT)) == FOPEN
646 && *ph != (uint32_t)INVALID_HANDLE_VALUE)
647 {
648 HANDLE h = (HANDLE)(intptr_t)*ph;
649 int fd2;
650 int fFlags;
651 int fFlags2;
652
653 if ( h == aStdHandles2[j = 0]
654 || h == aStdHandles2[j = 1]
655 || h == aStdHandles2[j = 2])
656 fFlags = aStdHandles[j].fFlags;
657 else
658 {
659 dwErr = shfile_query_handle_access_mask(h, &Mask);
660 if (dwErr == ERROR_INVALID_HANDLE)
661 continue;
662 else if (dwErr == NO_ERROR)
663 {
664 fFlags = 0;
665 if ( (Mask & (GENERIC_READ | FILE_READ_DATA))
666 && (Mask & (GENERIC_WRITE | FILE_WRITE_DATA | FILE_APPEND_DATA)))
667 fFlags |= O_RDWR;
668 else if (Mask & (GENERIC_READ | FILE_READ_DATA))
669 fFlags |= O_RDONLY;
670 else if (Mask & (GENERIC_WRITE | FILE_WRITE_DATA | FILE_APPEND_DATA))
671 fFlags |= O_WRONLY;
672 else
673 fFlags |= O_RDWR;
674 if ((Mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) == FILE_APPEND_DATA)
675 fFlags |= O_APPEND;
676 }
677 else
678 fFlags = O_RDWR;
679 }
680
681 if (paf[i] & FPIPE)
682 fFlags2 = SHFILE_FLAGS_PIPE;
683 else if (paf[i] & FDEV)
684 fFlags2 = SHFILE_FLAGS_TTY;
685 else
686 fFlags2 = 0;
687
688 fd2 = shfile_insert(pfdtab, (intptr_t)h, fFlags, fFlags2, i, "shtab_init");
689 assert(fd2 == i); (void)fd2;
690 if (fd2 != i)
691 rc = -1;
692 }
693 }
694 }
695
696 /* Check the three standard handles. */
697 for (i = 0; i < 3; i++)
698 if ( (unsigned)i >= pfdtab->size
699 || pfdtab->tab[i].fd == -1)
700 {
701 HANDLE hFile = GetStdHandle(aStdHandles[i].dwStdHandle);
702 if (hFile != INVALID_HANDLE_VALUE)
703 {
704 DWORD dwType = GetFileType(hFile);
705 unsigned fFlags = aStdHandles[i].fFlags;
706 unsigned fFlags2;
707 int fd2;
708 if (dwType == FILE_TYPE_CHAR)
709 fFlags2 = SHFILE_FLAGS_TTY;
710 else if (dwType == FILE_TYPE_PIPE)
711 fFlags2 = SHFILE_FLAGS_PIPE;
712 else
713 fFlags2 = SHFILE_FLAGS_FILE;
714 fd2 = shfile_insert(pfdtab, (intptr_t)hFile, fFlags, fFlags2, i, "shtab_init");
715 assert(fd2 == i); (void)fd2;
716 if (fd2 != i)
717 rc = -1;
718 }
719 }
720# else
721 /*
722 * Annoying...
723 */
724 int fd;
725
726 for (fd = 0; fd < 10; fd++)
727 {
728 int oflags = fcntl(fd, F_GETFL, 0);
729 if (oflags != -1)
730 {
731 int cox = fcntl(fd, F_GETFD, 0);
732 struct stat st;
733 if ( cox != -1
734 && fstat(fd, &st) != -1)
735 {
736 int native;
737 int fd2;
738 int fFlags2 = 0;
739 if (cox & FD_CLOEXEC)
740 fFlags2 |= SHFILE_FLAGS_CLOSE_ON_EXEC;
741 if (S_ISREG(st.st_mode))
742 fFlags2 |= SHFILE_FLAGS_FILE;
743 else if (S_ISDIR(st.st_mode))
744 fFlags2 |= SHFILE_FLAGS_DIR;
745 else if (S_ISCHR(st.st_mode))
746 fFlags2 |= SHFILE_FLAGS_TTY;
747 else if (S_ISFIFO(st.st_mode))
748 fFlags2 |= SHFILE_FLAGS_PIPE;
749 else
750 fFlags2 |= SHFILE_FLAGS_TTY;
751
752 native = fcntl(fd, F_DUPFD, SHFILE_UNIX_MIN_FD);
753 if (native == -1)
754 native = fd;
755 fd2 = shfile_insert(pfdtab, native, oflags, fFlags2, fd, "shtab_init");
756 assert(fd2 == fd); (void)fd2;
757 if (fd2 != fd)
758 rc = -1;
759 if (native != fd)
760 close(fd);
761 }
762 }
763 }
764
765# endif
766 }
767 else
768 {
769 /** @todo */
770 errno = ENOSYS;
771 rc = -1;
772 }
773 }
774 else
775 rc = -1;
776#endif
777 }
778 return rc;
779}
780
781#if K_OS == K_OS_WINDOWS && defined(SHFILE_IN_USE)
782
783/**
784 * Changes the inheritability of a file descriptro, taking console handles into
785 * account.
786 *
787 * @note This MAY change the native handle for the entry.
788 *
789 * @returns The native handle.
790 * @param pfd The file descriptor to change.
791 * @param set If set, make child processes inherit the handle, if clear
792 * make them not inherit it.
793 */
794static HANDLE shfile_set_inherit_win(shfile *pfd, int set)
795{
796 HANDLE hFile = (HANDLE)pfd->native;
797 if (!SetHandleInformation(hFile, HANDLE_FLAG_INHERIT, set ? HANDLE_FLAG_INHERIT : 0))
798 {
799 /* SetHandleInformation doesn't work for console handles,
800 so we have to duplicate the handle to change the
801 inheritability. */
802 DWORD err = GetLastError();
803 if ( err == ERROR_INVALID_PARAMETER
804 && DuplicateHandle(GetCurrentProcess(),
805 hFile,
806 GetCurrentProcess(),
807 &hFile,
808 0,
809 set ? TRUE : FALSE /* bInheritHandle */,
810 DUPLICATE_SAME_ACCESS))
811 {
812 TRACE2((NULL, "shfile_set_inherit_win: %p -> %p (set=%d)\n", pfd->native, hFile, set));
813 if (!CloseHandle((HANDLE)pfd->native))
814 assert(0);
815 pfd->native = (intptr_t)hFile;
816 }
817 else
818 {
819 err = GetLastError();
820 assert(0);
821 hFile = (HANDLE)pfd->native;
822 }
823 }
824 return hFile;
825}
826
827/**
828 * Helper for shfork.
829 *
830 * @param pfdtab The file descriptor table.
831 * @param set Whether to make all handles inheritable (1) or
832 * to restore them to the rigth state (0).
833 * @param hndls Where to store the three standard handles.
834 */
835void shfile_fork_win(shfdtab *pfdtab, int set, intptr_t *hndls)
836{
837 shmtxtmp tmp;
838 unsigned i;
839
840 shmtx_enter(&pfdtab->mtx, &tmp);
841 TRACE2((NULL, "shfile_fork_win: set=%d\n", set));
842
843 i = pfdtab->size;
844 while (i-- > 0)
845 {
846 if (pfdtab->tab[i].fd == i)
847 {
848 shfile_set_inherit_win(&pfdtab->tab[i], set);
849 if (set)
850 TRACE2((NULL, " #%d: native=%#x oflags=%#x shflags=%#x\n",
851 i, pfdtab->tab[i].native, pfdtab->tab[i].oflags, pfdtab->tab[i].shflags));
852 }
853 }
854
855 if (hndls)
856 {
857 for (i = 0; i < 3; i++)
858 {
859 if ( pfdtab->size > i
860 && pfdtab->tab[i].fd == i)
861 hndls[i] = pfdtab->tab[i].native;
862 else
863 hndls[i] = (intptr_t)INVALID_HANDLE_VALUE;
864 TRACE2((NULL, "shfile_fork_win: i=%d size=%d fd=%d native=%d hndls[%d]=%p\n",
865 i, pfdtab->size, pfdtab->tab[i].fd, pfdtab->tab[i].native, i, hndls[i]));
866 }
867 }
868
869 shmtx_leave(&pfdtab->mtx, &tmp);
870}
871
872/**
873 * Helper for sh_execve.
874 *
875 * This is called before and after CreateProcess. On the first call it
876 * will mark the non-close-on-exec handles as inheritable and produce
877 * the startup info for the CRT. On the second call, after CreateProcess,
878 * it will restore the handle inheritability properties.
879 *
880 * @returns Pointer to CRT data if prepare is 1, NULL if prepare is 0.
881 * @param pfdtab The file descriptor table.
882 * @param prepare Which call, 1 if before and 0 if after.
883 * @param sizep Where to store the size of the returned data.
884 * @param hndls Where to store the three standard handles.
885 */
886void *shfile_exec_win(shfdtab *pfdtab, int prepare, unsigned short *sizep, intptr_t *hndls)
887{
888 void *pvRet;
889 shmtxtmp tmp;
890 unsigned count;
891 unsigned i;
892
893 shmtx_enter(&pfdtab->mtx, &tmp);
894 TRACE2((NULL, "shfile_exec_win: prepare=%p\n", prepare));
895
896 count = pfdtab->size < (0x10000-4) / (1 + sizeof(HANDLE))
897 ? pfdtab->size
898 : (0x10000-4) / (1 + sizeof(HANDLE));
899 while (count > 3 && pfdtab->tab[count - 1].fd == -1)
900 count--;
901
902 if (prepare)
903 {
904 size_t cbData = sizeof(int) + count * (1 + sizeof(HANDLE));
905 uint8_t *pbData = sh_malloc(shthread_get_shell(), cbData);
906 uint8_t *paf = pbData + sizeof(int);
907 HANDLE *pah = (HANDLE *)(paf + count);
908
909 *(int *)pbData = count;
910
911 i = count;
912 while (i-- > 0)
913 {
914 if ( pfdtab->tab[i].fd == i
915 && !(pfdtab->tab[i].shflags & SHFILE_FLAGS_CLOSE_ON_EXEC))
916 {
917 HANDLE hFile = shfile_set_inherit_win(&pfdtab->tab[i], 1);
918 TRACE2((NULL, " #%d: native=%#x oflags=%#x shflags=%#x\n",
919 i, hFile, pfdtab->tab[i].oflags, pfdtab->tab[i].shflags));
920 paf[i] = FOPEN;
921 if (pfdtab->tab[i].oflags & _O_APPEND)
922 paf[i] |= FAPPEND;
923 if (pfdtab->tab[i].oflags & _O_TEXT)
924 paf[i] |= FTEXT;
925 switch (pfdtab->tab[i].shflags & SHFILE_FLAGS_TYPE_MASK)
926 {
927 case SHFILE_FLAGS_TTY: paf[i] |= FDEV; break;
928 case SHFILE_FLAGS_PIPE: paf[i] |= FPIPE; break;
929 }
930 pah[i] = hFile;
931 }
932 else
933 {
934 paf[i] = 0;
935 pah[i] = INVALID_HANDLE_VALUE;
936 }
937 }
938
939 for (i = 0; i < 3; i++)
940 {
941 if ( i < count
942 && pfdtab->tab[i].fd == i)
943 hndls[i] = pfdtab->tab[i].native;
944 else
945 hndls[i] = (intptr_t)INVALID_HANDLE_VALUE;
946 TRACE2((NULL, "shfile_exec_win: i=%d count=%d fd=%d native=%d hndls[%d]=\n",
947 i, count, pfdtab->tab[i].fd, pfdtab->tab[i].native, i, hndls[i]));
948 }
949
950 *sizep = (unsigned short)cbData;
951 pvRet = pbData;
952 }
953 else
954 {
955 assert(!hndls);
956 assert(!sizep);
957 i = count;
958 while (i-- > 0)
959 {
960 if ( pfdtab->tab[i].fd == i
961 && !(pfdtab->tab[i].shflags & SHFILE_FLAGS_CLOSE_ON_EXEC))
962 shfile_set_inherit_win(&pfdtab->tab[i], 0);
963 }
964 pvRet = NULL;
965 }
966
967 shmtx_leave(&pfdtab->mtx, &tmp);
968 return pvRet;
969}
970
971#endif /* K_OS_WINDOWS */
972
973#if K_OS != K_OS_WINDOWS
974/**
975 * Prepare file handles for inherting before a execve call.
976 *
977 * This is only used in the normal mode, so we've forked and need not worry
978 * about cleaning anything up after us. Nor do we need think about locking.
979 *
980 * @returns 0 on success, -1 on failure.
981 */
982int shfile_exec_unix(shfdtab *pfdtab)
983{
984 int rc = 0;
985# ifdef SHFILE_IN_USE
986 unsigned fd;
987
988 for (fd = 0; fd < pfdtab->size; fd++)
989 {
990 if ( pfdtab->tab[fd].fd != -1
991 && !(pfdtab->tab[fd].shflags & SHFILE_FLAGS_CLOSE_ON_EXEC) )
992 {
993 TRACE2((NULL, "shfile_exec_unix: %d => %d\n", pfdtab->tab[fd].native, fd));
994 if (dup2(pfdtab->tab[fd].native, fd) < 0)
995 {
996 /* fatal_error(NULL, "shfile_exec_unix: failed to move %d to %d", pfdtab->tab[fd].fd, fd); */
997 rc = -1;
998 }
999 }
1000 }
1001# endif
1002 return rc;
1003}
1004#endif /* !K_OS_WINDOWS */
1005
1006/**
1007 * open().
1008 */
1009int shfile_open(shfdtab *pfdtab, const char *name, unsigned flags, mode_t mode)
1010{
1011 int fd;
1012#ifdef SHFILE_IN_USE
1013 char absname[SHFILE_MAX_PATH];
1014# if K_OS == K_OS_WINDOWS
1015 HANDLE hFile;
1016 DWORD dwDesiredAccess;
1017 DWORD dwShareMode;
1018 DWORD dwCreationDisposition;
1019 DWORD dwFlagsAndAttributes;
1020 SECURITY_ATTRIBUTES SecurityAttributes;
1021
1022# ifndef _O_ACCMODE
1023# define _O_ACCMODE (_O_RDONLY|_O_WRONLY|_O_RDWR)
1024# endif
1025 switch (flags & (_O_ACCMODE | _O_APPEND))
1026 {
1027 case _O_RDONLY: dwDesiredAccess = GENERIC_READ; break;
1028 case _O_RDONLY | _O_APPEND: dwDesiredAccess = GENERIC_READ; break;
1029 case _O_WRONLY: dwDesiredAccess = GENERIC_WRITE; break;
1030 case _O_WRONLY | _O_APPEND: dwDesiredAccess = (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA); break;
1031 case _O_RDWR: dwDesiredAccess = GENERIC_READ | GENERIC_WRITE; break;
1032 case _O_RDWR | _O_APPEND: dwDesiredAccess = GENERIC_READ | (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA); break;
1033
1034 default:
1035 RETURN_ERROR(-1, EINVAL, "invalid mode");
1036 }
1037
1038 dwShareMode = FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE;
1039
1040 SecurityAttributes.nLength = sizeof(SecurityAttributes);
1041 SecurityAttributes.lpSecurityDescriptor = NULL;
1042 SecurityAttributes.bInheritHandle = FALSE;
1043
1044 if (flags & _O_CREAT)
1045 {
1046 if ((flags & (_O_EXCL | _O_TRUNC)) == (_O_EXCL | _O_TRUNC))
1047 RETURN_ERROR(-1, EINVAL, "_O_EXCL | _O_TRUNC");
1048
1049 if (flags & _O_TRUNC)
1050 dwCreationDisposition = CREATE_ALWAYS; /* not 100%, but close enough */
1051 else if (flags & _O_EXCL)
1052 dwCreationDisposition = CREATE_NEW;
1053 else
1054 dwCreationDisposition = OPEN_ALWAYS;
1055 }
1056 else if (flags & _O_TRUNC)
1057 dwCreationDisposition = TRUNCATE_EXISTING;
1058 else
1059 dwCreationDisposition = OPEN_EXISTING;
1060
1061 if (!(flags & _O_CREAT) || (mode & 0222))
1062 dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
1063 else
1064 dwFlagsAndAttributes = FILE_ATTRIBUTE_READONLY;
1065
1066 fd = shfile_make_path(pfdtab, name, &absname[0]);
1067 if (!fd)
1068 {
1069 SetLastError(0);
1070 hFile = CreateFileA(absname,
1071 dwDesiredAccess,
1072 dwShareMode,
1073 &SecurityAttributes,
1074 dwCreationDisposition,
1075 dwFlagsAndAttributes,
1076 NULL /* hTemplateFile */);
1077 if (hFile != INVALID_HANDLE_VALUE)
1078 fd = shfile_insert(pfdtab, (intptr_t)hFile, flags, 0, -1, "shfile_open");
1079 else
1080 fd = shfile_dos2errno(GetLastError());
1081 }
1082
1083# else /* K_OS != K_OS_WINDOWS */
1084 fd = shfile_make_path(pfdtab, name, &absname[0]);
1085 if (!fd)
1086 {
1087 fd = open(absname, flags, mode);
1088 if (fd != -1)
1089 fd = shfile_copy_insert_and_close(pfdtab, &fd, flags, 0, -1, "shfile_open");
1090 }
1091
1092# endif /* K_OS != K_OS_WINDOWS */
1093
1094#else
1095 fd = open(name, flags, mode);
1096#endif
1097
1098 TRACE2((NULL, "shfile_open(%p:{%s}, %#x, 0%o) -> %d [%d]\n", name, name, flags, mode, fd, errno));
1099 return fd;
1100}
1101
1102int shfile_pipe(shfdtab *pfdtab, int fds[2])
1103{
1104 int rc = -1;
1105#ifdef SHFILE_IN_USE
1106# if K_OS == K_OS_WINDOWS
1107 HANDLE hRead = INVALID_HANDLE_VALUE;
1108 HANDLE hWrite = INVALID_HANDLE_VALUE;
1109 SECURITY_ATTRIBUTES SecurityAttributes;
1110
1111 SecurityAttributes.nLength = sizeof(SecurityAttributes);
1112 SecurityAttributes.lpSecurityDescriptor = NULL;
1113 SecurityAttributes.bInheritHandle = FALSE;
1114
1115 fds[1] = fds[0] = -1;
1116 if (CreatePipe(&hRead, &hWrite, &SecurityAttributes, 4096))
1117 {
1118 fds[0] = shfile_insert(pfdtab, (intptr_t)hRead, O_RDONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
1119 if (fds[0] != -1)
1120 {
1121 fds[1] = shfile_insert(pfdtab, (intptr_t)hWrite, O_WRONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
1122 if (fds[1] != -1)
1123 rc = 0;
1124 }
1125
1126# else
1127 int native_fds[2];
1128
1129 fds[1] = fds[0] = -1;
1130 if (!pipe(native_fds))
1131 {
1132 fds[0] = shfile_copy_insert_and_close(pfdtab, &native_fds[0], O_RDONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
1133 if (fds[0] != -1)
1134 {
1135 fds[1] = shfile_copy_insert_and_close(pfdtab, &native_fds[1], O_WRONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
1136 if (fds[1] != -1)
1137 rc = 0;
1138 }
1139# endif
1140 if (fds[1] == -1)
1141 {
1142 int s = errno;
1143 if (fds[0] != -1)
1144 {
1145 shmtxtmp tmp;
1146 shmtx_enter(&pfdtab->mtx, &tmp);
1147 rc = fds[0];
1148 pfdtab->tab[rc].fd = -1;
1149 pfdtab->tab[rc].oflags = 0;
1150 pfdtab->tab[rc].shflags = 0;
1151 pfdtab->tab[rc].native = -1;
1152 shmtx_leave(&pfdtab->mtx, &tmp);
1153 }
1154
1155# if K_OS == K_OS_WINDOWS
1156 CloseHandle(hRead);
1157 CloseHandle(hWrite);
1158# else
1159 close(native_fds[0]);
1160 close(native_fds[1]);
1161# endif
1162 fds[0] = fds[1] = -1;
1163 errno = s;
1164 rc = -1;
1165 }
1166 }
1167 else
1168 {
1169# if K_OS == K_OS_WINDOWS
1170 errno = shfile_dos2errno(GetLastError());
1171# endif
1172 rc = -1;
1173 }
1174
1175#else
1176 rc = pipe(fds);
1177#endif
1178
1179 TRACE2((NULL, "shfile_pipe() -> %d{%d,%d} [%d]\n", rc, fds[0], fds[1], errno));
1180 return rc;
1181}
1182
1183/**
1184 * dup().
1185 */
1186int shfile_dup(shfdtab *pfdtab, int fd)
1187{
1188 return shfile_fcntl(pfdtab,fd, F_DUPFD, 0);
1189}
1190
1191/**
1192 * Move the file descriptor, closing any existing descriptor at @a fdto.
1193 *
1194 * @returns fdto on success, -1 and errno on failure.
1195 * @param pfdtab The file descriptor table.
1196 * @param fdfrom The descriptor to move.
1197 * @param fdto Where to move it.
1198 */
1199int shfile_movefd(shfdtab *pfdtab, int fdfrom, int fdto)
1200{
1201#ifdef SHFILE_IN_USE
1202 int rc;
1203 shmtxtmp tmp;
1204 shfile *file = shfile_get(pfdtab, fdfrom, &tmp);
1205 if (file)
1206 {
1207 /* prepare the new entry */
1208 if (fdto >= (int)pfdtab->size)
1209 shfile_grow_tab_locked(pfdtab, fdto);
1210 if (fdto < (int)pfdtab->size)
1211 {
1212 if (pfdtab->tab[fdto].fd != -1)
1213 shfile_native_close(pfdtab->tab[fdto].native, pfdtab->tab[fdto].oflags);
1214
1215 /* setup the target. */
1216 pfdtab->tab[fdto].fd = fdto;
1217 pfdtab->tab[fdto].oflags = file->oflags;
1218 pfdtab->tab[fdto].shflags = file->shflags;
1219 pfdtab->tab[fdto].native = file->native;
1220
1221 /* close the source. */
1222 file->fd = -1;
1223 file->oflags = 0;
1224 file->shflags = 0;
1225 file->native = -1;
1226
1227 rc = fdto;
1228 }
1229 else
1230 {
1231 errno = EMFILE;
1232 rc = -1;
1233 }
1234
1235 shfile_put(pfdtab, file, &tmp);
1236 }
1237 else
1238 rc = -1;
1239 return rc;
1240
1241#else
1242 int fdnew = dup2(fdfrom, fdto);
1243 if (fdnew >= 0)
1244 close(fdfrom);
1245 return fdnew;
1246#endif
1247}
1248
1249/**
1250 * Move the file descriptor to somewhere at @a fdMin or above.
1251 *
1252 * @returns the new file descriptor success, -1 and errno on failure.
1253 * @param pfdtab The file descriptor table.
1254 * @param fdfrom The descriptor to move.
1255 * @param fdMin The minimum descriptor.
1256 */
1257int shfile_movefd_above(shfdtab *pfdtab, int fdfrom, int fdMin)
1258{
1259#ifdef SHFILE_IN_USE
1260 int fdto;
1261 shmtxtmp tmp;
1262 shfile *file = shfile_get(pfdtab, fdfrom, &tmp);
1263 if (file)
1264 {
1265 /* find a new place */
1266 int i;
1267 fdto = -1;
1268 for (i = fdMin; (unsigned)i < pfdtab->size; i++)
1269 if (pfdtab->tab[i].fd == -1)
1270 {
1271 fdto = i;
1272 break;
1273 }
1274 if (fdto == -1)
1275 fdto = shfile_grow_tab_locked(pfdtab, fdMin);
1276 if (fdto != -1)
1277 {
1278 /* setup the target. */
1279 pfdtab->tab[fdto].fd = fdto;
1280 pfdtab->tab[fdto].oflags = file->oflags;
1281 pfdtab->tab[fdto].shflags = file->shflags;
1282 pfdtab->tab[fdto].native = file->native;
1283
1284 /* close the source. */
1285 file->fd = -1;
1286 file->oflags = 0;
1287 file->shflags = 0;
1288 file->native = -1;
1289 }
1290 else
1291 {
1292 errno = EMFILE;
1293 fdto = -1;
1294 }
1295
1296 shfile_put(pfdtab, file, &tmp);
1297 }
1298 else
1299 fdto = -1;
1300 return fdto;
1301
1302#else
1303 int fdnew = fcntl(fdfrom, F_DUPFD, fdMin);
1304 if (fdnew >= 0)
1305 close(fdfrom);
1306 return fdnew;
1307#endif
1308}
1309
1310/**
1311 * close().
1312 */
1313int shfile_close(shfdtab *pfdtab, unsigned fd)
1314{
1315 int rc;
1316#ifdef SHFILE_IN_USE
1317 shmtxtmp tmp;
1318 shfile *file = shfile_get(pfdtab, fd, &tmp);
1319 if (file)
1320 {
1321 shfile_native_close(file->native, file->oflags);
1322
1323 file->fd = -1;
1324 file->oflags = 0;
1325 file->shflags = 0;
1326 file->native = -1;
1327
1328 shfile_put(pfdtab, file, &tmp);
1329 rc = 0;
1330 }
1331 else
1332 rc = -1;
1333
1334#else
1335 rc = close(fd);
1336#endif
1337
1338 TRACE2((NULL, "shfile_close(%d) -> %d [%d]\n", fd, rc, errno));
1339 return rc;
1340}
1341
1342/**
1343 * read().
1344 */
1345long shfile_read(shfdtab *pfdtab, int fd, void *buf, size_t len)
1346{
1347 long rc;
1348#ifdef SHFILE_IN_USE
1349 shmtxtmp tmp;
1350 shfile *file = shfile_get(pfdtab, fd, &tmp);
1351 if (file)
1352 {
1353# if K_OS == K_OS_WINDOWS
1354 DWORD dwRead = 0;
1355 if (ReadFile((HANDLE)file->native, buf, (DWORD)len, &dwRead, NULL))
1356 rc = dwRead;
1357 else
1358 rc = shfile_dos2errno(GetLastError());
1359# else
1360 rc = read(file->native, buf, len);
1361# endif
1362
1363 shfile_put(pfdtab, file, &tmp);
1364 }
1365 else
1366 rc = -1;
1367
1368#else
1369 rc = read(fd, buf, len);
1370#endif
1371 return rc;
1372}
1373
1374/**
1375 * write().
1376 */
1377long shfile_write(shfdtab *pfdtab, int fd, const void *buf, size_t len)
1378{
1379 long rc;
1380#ifdef SHFILE_IN_USE
1381 shmtxtmp tmp;
1382 shfile *file = shfile_get(pfdtab, fd, &tmp);
1383 if (file)
1384 {
1385# if K_OS == K_OS_WINDOWS
1386 DWORD dwWritten = 0;
1387 if (WriteFile((HANDLE)file->native, buf, (DWORD)len, &dwWritten, NULL))
1388 rc = dwWritten;
1389 else
1390 rc = shfile_dos2errno(GetLastError());
1391# else
1392 rc = write(file->native, buf, len);
1393# endif
1394
1395 shfile_put(pfdtab, file, &tmp);
1396 }
1397 else
1398 rc = -1;
1399
1400# ifdef DEBUG
1401 if (fd != shthread_get_shell()->tracefd)
1402 TRACE2((NULL, "shfile_write(%d,,%d) -> %d [%d]\n", fd, len, rc, errno));
1403# endif
1404
1405#else
1406 if (fd != shthread_get_shell()->tracefd)
1407 {
1408 int iSavedErrno = errno;
1409 struct stat s;
1410 int x;
1411 x = fstat(fd, &s);
1412 TRACE2((NULL, "shfile_write(%d) - %lu bytes (%d) - pos %lu - before; %o\n",
1413 fd, (long)s.st_size, x, (long)lseek(fd, 0, SEEK_CUR), s.st_mode ));
1414 errno = iSavedErrno;
1415 }
1416
1417 rc = write(fd, buf, len);
1418#endif
1419 return rc;
1420}
1421
1422/**
1423 * lseek().
1424 */
1425long shfile_lseek(shfdtab *pfdtab, int fd, long off, int whench)
1426{
1427 long rc;
1428#ifdef SHFILE_IN_USE
1429 shmtxtmp tmp;
1430 shfile *file = shfile_get(pfdtab, fd, &tmp);
1431 if (file)
1432 {
1433# if K_OS == K_OS_WINDOWS
1434 assert(SEEK_SET == FILE_BEGIN);
1435 assert(SEEK_CUR == FILE_CURRENT);
1436 assert(SEEK_END == FILE_END);
1437 rc = SetFilePointer((HANDLE)file->native, off, NULL, whench);
1438 if (rc == INVALID_SET_FILE_POINTER)
1439 rc = shfile_dos2errno(GetLastError());
1440# else
1441 rc = lseek(file->native, off, whench);
1442# endif
1443
1444 shfile_put(pfdtab, file, &tmp);
1445 }
1446 else
1447 rc = -1;
1448
1449#else
1450 rc = lseek(fd, off, whench);
1451#endif
1452
1453 return rc;
1454}
1455
1456int shfile_fcntl(shfdtab *pfdtab, int fd, int cmd, int arg)
1457{
1458 int rc;
1459#ifdef SHFILE_IN_USE
1460 shmtxtmp tmp;
1461 shfile *file = shfile_get(pfdtab, fd, &tmp);
1462 if (file)
1463 {
1464 switch (cmd)
1465 {
1466 case F_GETFL:
1467 rc = file->oflags;
1468 break;
1469
1470 case F_SETFL:
1471 {
1472 unsigned mask = O_NONBLOCK | O_APPEND | O_BINARY | O_TEXT;
1473# ifdef O_DIRECT
1474 mask |= O_DIRECT;
1475# endif
1476# ifdef O_ASYNC
1477 mask |= O_ASYNC;
1478# endif
1479# ifdef O_SYNC
1480 mask |= O_SYNC;
1481# endif
1482 if ((file->oflags & mask) == (arg & mask))
1483 rc = 0;
1484 else
1485 {
1486# if K_OS == K_OS_WINDOWS
1487 assert(0);
1488 errno = EINVAL;
1489 rc = -1;
1490# else
1491 rc = fcntl(file->native, F_SETFL, arg);
1492 if (rc != -1)
1493 file->oflags = (file->oflags & ~mask) | (arg & mask);
1494# endif
1495 }
1496 break;
1497 }
1498
1499 case F_DUPFD:
1500 {
1501# if K_OS == K_OS_WINDOWS
1502 HANDLE hNew = INVALID_HANDLE_VALUE;
1503 if (DuplicateHandle(GetCurrentProcess(),
1504 (HANDLE)file->native,
1505 GetCurrentProcess(),
1506 &hNew,
1507 0,
1508 FALSE /* bInheritHandle */,
1509 DUPLICATE_SAME_ACCESS))
1510 rc = shfile_insert(pfdtab, (intptr_t)hNew, file->oflags, file->shflags, arg, "shfile_fcntl");
1511 else
1512 rc = shfile_dos2errno(GetLastError());
1513# else
1514 int nativeNew = fcntl(file->native, F_DUPFD, SHFILE_UNIX_MIN_FD);
1515 if (nativeNew != -1)
1516 rc = shfile_insert(pfdtab, nativeNew, file->oflags, file->shflags, arg, "shfile_fcntl");
1517 else
1518 rc = -1;
1519# endif
1520 break;
1521 }
1522
1523 default:
1524 errno = -EINVAL;
1525 rc = -1;
1526 break;
1527 }
1528
1529 shfile_put(pfdtab, file, &tmp);
1530 }
1531 else
1532 rc = -1;
1533
1534#else
1535 rc = fcntl(fd, cmd, arg);
1536#endif
1537
1538 switch (cmd)
1539 {
1540 case F_GETFL: TRACE2((NULL, "shfile_fcntl(%d,F_GETFL,ignored=%d) -> %d [%d]\n", fd, arg, rc, errno)); break;
1541 case F_SETFL: TRACE2((NULL, "shfile_fcntl(%d,F_SETFL,newflags=%#x) -> %d [%d]\n", fd, arg, rc, errno)); break;
1542 case F_DUPFD: TRACE2((NULL, "shfile_fcntl(%d,F_DUPFD,minfd=%d) -> %d [%d]\n", fd, arg, rc, errno)); break;
1543 default: TRACE2((NULL, "shfile_fcntl(%d,%d,%d) -> %d [%d]\n", fd, cmd, arg, rc, errno)); break;
1544 }
1545 return rc;
1546}
1547
1548int shfile_stat(shfdtab *pfdtab, const char *path, struct stat *pst)
1549{
1550#ifdef SHFILE_IN_USE
1551 char abspath[SHFILE_MAX_PATH];
1552 int rc;
1553 rc = shfile_make_path(pfdtab, path, &abspath[0]);
1554 if (!rc)
1555 {
1556# if K_OS == K_OS_WINDOWS
1557 rc = stat(abspath, pst); /** @todo re-implement stat. */
1558# else
1559 rc = stat(abspath, pst);
1560# endif
1561 }
1562 TRACE2((NULL, "shfile_stat(,%s,) -> %d [%d]\n", path, rc, errno));
1563 return rc;
1564#else
1565 return stat(path, pst);
1566#endif
1567}
1568
1569int shfile_lstat(shfdtab *pfdtab, const char *path, struct stat *pst)
1570{
1571 int rc;
1572#ifdef SHFILE_IN_USE
1573 char abspath[SHFILE_MAX_PATH];
1574
1575 rc = shfile_make_path(pfdtab, path, &abspath[0]);
1576 if (!rc)
1577 {
1578# if K_OS == K_OS_WINDOWS
1579 rc = stat(abspath, pst); /** @todo implement lstat. */
1580# else
1581 rc = lstat(abspath, pst);
1582# endif
1583 }
1584#else
1585 rc = stat(path, pst);
1586#endif
1587 TRACE2((NULL, "shfile_stat(,%s,) -> %d [%d]\n", path, rc, errno));
1588 return rc;
1589}
1590
1591/**
1592 * chdir().
1593 */
1594int shfile_chdir(shfdtab *pfdtab, const char *path)
1595{
1596 int rc;
1597#ifdef SHFILE_IN_USE
1598 shinstance *psh = shthread_get_shell();
1599 char abspath[SHFILE_MAX_PATH];
1600
1601 rc = shfile_make_path(pfdtab, path, &abspath[0]);
1602 if (!rc)
1603 {
1604 char *abspath_copy = sh_strdup(psh, abspath);
1605 char *free_me = abspath_copy;
1606 rc = chdir(abspath);
1607 if (!rc)
1608 {
1609 shmtxtmp tmp;
1610 shmtx_enter(&pfdtab->mtx, &tmp);
1611
1612 shfile_fix_slashes(abspath_copy);
1613 free_me = pfdtab->cwd;
1614 pfdtab->cwd = abspath_copy;
1615
1616 shmtx_leave(&pfdtab->mtx, &tmp);
1617 }
1618 sh_free(psh, free_me);
1619 }
1620 else
1621 rc = -1;
1622#else
1623 rc = chdir(path);
1624#endif
1625
1626 TRACE2((NULL, "shfile_chdir(,%s) -> %d [%d]\n", path, rc, errno));
1627 return rc;
1628}
1629
1630/**
1631 * getcwd().
1632 */
1633char *shfile_getcwd(shfdtab *pfdtab, char *buf, int size)
1634{
1635 char *ret;
1636#ifdef SHFILE_IN_USE
1637
1638 ret = NULL;
1639 if (buf && !size)
1640 errno = -EINVAL;
1641 else
1642 {
1643 size_t cwd_size;
1644 shmtxtmp tmp;
1645 shmtx_enter(&pfdtab->mtx, &tmp);
1646
1647 cwd_size = strlen(pfdtab->cwd) + 1;
1648 if (buf)
1649 {
1650 if (cwd_size <= (size_t)size)
1651 ret = memcpy(buf, pfdtab->cwd, cwd_size);
1652 else
1653 errno = ERANGE;
1654 }
1655 else
1656 {
1657 if ((size_t)size < cwd_size)
1658 size = (int)cwd_size;
1659 ret = sh_malloc(shthread_get_shell(), size);
1660 if (ret)
1661 ret = memcpy(ret, pfdtab->cwd, cwd_size);
1662 else
1663 errno = ENOMEM;
1664 }
1665
1666 shmtx_leave(&pfdtab->mtx, &tmp);
1667 }
1668#else
1669 ret = getcwd(buf, size);
1670#endif
1671
1672 TRACE2((NULL, "shfile_getcwd(,%p,%d) -> %s [%d]\n", buf, size, ret, errno));
1673 return ret;
1674}
1675
1676/**
1677 * access().
1678 */
1679int shfile_access(shfdtab *pfdtab, const char *path, int type)
1680{
1681 int rc;
1682#ifdef SHFILE_IN_USE
1683 char abspath[SHFILE_MAX_PATH];
1684
1685 rc = shfile_make_path(pfdtab, path, &abspath[0]);
1686 if (!rc)
1687 {
1688# ifdef _MSC_VER
1689 if (type & X_OK)
1690 type = (type & ~X_OK) | R_OK;
1691# endif
1692 rc = access(abspath, type);
1693 }
1694#else
1695# ifdef _MSC_VER
1696 if (type & X_OK)
1697 type = (type & ~X_OK) | R_OK;
1698# endif
1699 rc = access(path, type);
1700#endif
1701
1702 TRACE2((NULL, "shfile_access(,%s,%#x) -> %d [%d]\n", path, type, rc, errno));
1703 return rc;
1704}
1705
1706/**
1707 * isatty()
1708 */
1709int shfile_isatty(shfdtab *pfdtab, int fd)
1710{
1711 int rc;
1712#ifdef SHFILE_IN_USE
1713 shmtxtmp tmp;
1714 shfile *file = shfile_get(pfdtab, fd, &tmp);
1715 if (file)
1716 {
1717# if K_OS == K_OS_WINDOWS
1718 rc = (file->shflags & SHFILE_FLAGS_TYPE_MASK) == SHFILE_FLAGS_TTY;
1719# else
1720 rc = isatty(file->native);
1721# endif
1722 shfile_put(pfdtab, file, &tmp);
1723 }
1724 else
1725 rc = 0;
1726#else
1727 rc = isatty(fd);
1728#endif
1729
1730 TRACE2((NULL, "isatty(%d) -> %d [%d]\n", fd, rc, errno));
1731 return rc;
1732}
1733
1734/**
1735 * fcntl F_SETFD / FD_CLOEXEC.
1736 */
1737int shfile_cloexec(shfdtab *pfdtab, int fd, int closeit)
1738{
1739 int rc;
1740#ifdef SHFILE_IN_USE
1741 shmtxtmp tmp;
1742 shfile *file = shfile_get(pfdtab, fd, &tmp);
1743 if (file)
1744 {
1745 if (closeit)
1746 file->shflags |= SHFILE_FLAGS_CLOSE_ON_EXEC;
1747 else
1748 file->shflags &= ~SHFILE_FLAGS_CLOSE_ON_EXEC;
1749 shfile_put(pfdtab, file, &tmp);
1750 rc = 0;
1751 }
1752 else
1753 rc = -1;
1754#else
1755 rc = fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0)
1756 | (closeit ? FD_CLOEXEC : 0));
1757#endif
1758
1759 TRACE2((NULL, "shfile_cloexec(%d, %d) -> %d [%d]\n", fd, closeit, rc, errno));
1760 return rc;
1761}
1762
1763
1764int shfile_ioctl(shfdtab *pfdtab, int fd, unsigned long request, void *buf)
1765{
1766 int rc;
1767#ifdef SHFILE_IN_USE
1768 shmtxtmp tmp;
1769 shfile *file = shfile_get(pfdtab, fd, &tmp);
1770 if (file)
1771 {
1772# if K_OS == K_OS_WINDOWS
1773 rc = -1;
1774 errno = ENOSYS;
1775# else
1776 rc = ioctl(file->native, request, buf);
1777# endif
1778 shfile_put(pfdtab, file, &tmp);
1779 }
1780 else
1781 rc = -1;
1782#else
1783 rc = ioctl(fd, request, buf);
1784#endif
1785
1786 TRACE2((NULL, "ioctl(%d, %#x, %p) -> %d\n", fd, request, buf, rc));
1787 return rc;
1788}
1789
1790
1791mode_t shfile_get_umask(shfdtab *pfdtab)
1792{
1793 /** @todo */
1794 return 022;
1795}
1796
1797void shfile_set_umask(shfdtab *pfdtab, mode_t mask)
1798{
1799 /** @todo */
1800 (void)mask;
1801}
1802
1803
1804
1805shdir *shfile_opendir(shfdtab *pfdtab, const char *dir)
1806{
1807#if defined(SHFILE_IN_USE) && K_OS == K_OS_WINDOWS
1808 shdir *pdir = NULL;
1809
1810 TRACE2((NULL, "shfile_opendir: dir='%s'\n", dir));
1811 shfile_init_globals();
1812 if (g_pfnNtQueryDirectoryFile)
1813 {
1814 char abspath[SHFILE_MAX_PATH];
1815 if (shfile_make_path(pfdtab, dir, &abspath[0]) == 0)
1816 {
1817 HANDLE hFile;
1818 SECURITY_ATTRIBUTES SecurityAttributes;
1819
1820 SecurityAttributes.nLength = sizeof(SecurityAttributes);
1821 SecurityAttributes.lpSecurityDescriptor = NULL;
1822 SecurityAttributes.bInheritHandle = FALSE;
1823
1824 hFile = CreateFileA(abspath,
1825 GENERIC_READ,
1826 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
1827 &SecurityAttributes,
1828 OPEN_EXISTING,
1829 FILE_ATTRIBUTE_DIRECTORY | FILE_FLAG_BACKUP_SEMANTICS,
1830 NULL /* hTemplateFile */);
1831 if (hFile != INVALID_HANDLE_VALUE)
1832 {
1833 pdir = (shdir *)sh_malloc(shthread_get_shell(), sizeof(*pdir));
1834 if (pdir)
1835 {
1836 pdir->pfdtab = pfdtab;
1837 pdir->native = hFile;
1838 pdir->off = ~(size_t)0;
1839 }
1840 else
1841 CloseHandle(hFile);
1842 }
1843 else
1844 {
1845 errno = shfile_dos2errno(GetLastError());
1846 TRACE2((NULL, "shfile_opendir: CreateFileA(%s) -> %d/%d\n", abspath, GetLastError(), errno));
1847 }
1848 }
1849 }
1850 else
1851 errno = ENOSYS;
1852 return pdir;
1853#else
1854 TRACE2((NULL, "shfile_opendir: dir='%s'\n", dir));
1855 return (shdir *)opendir(dir);
1856#endif
1857}
1858
1859shdirent *shfile_readdir(struct shdir *pdir)
1860{
1861#if defined(SHFILE_IN_USE) && K_OS == K_OS_WINDOWS
1862 if (pdir)
1863 {
1864 NTSTATUS rcNt;
1865
1866 if ( pdir->off == ~(size_t)0
1867 || pdir->off + sizeof(MY_FILE_NAMES_INFORMATION) >= pdir->cb)
1868 {
1869 MY_IO_STATUS_BLOCK Ios;
1870
1871 memset(&Ios, 0, sizeof(Ios));
1872 rcNt = g_pfnNtQueryDirectoryFile(pdir->native,
1873 NULL /*Event*/,
1874 NULL /*ApcRoutine*/,
1875 NULL /*ApcContext*/,
1876 &Ios,
1877 &pdir->buf[0],
1878 sizeof(pdir->buf),
1879 MY_FileNamesInformation,
1880 FALSE /*ReturnSingleEntry*/,
1881 NULL /*FileName*/,
1882 pdir->off == ~(size_t)0 /*RestartScan*/);
1883 if (rcNt >= 0 && rcNt != STATUS_PENDING)
1884 {
1885 pdir->cb = Ios.Information;
1886 pdir->off = 0;
1887 }
1888 else if (rcNt == STATUS_NO_MORE_FILES)
1889 errno = 0; /* wrong? */
1890 else
1891 shfile_nt2errno(rcNt);
1892 }
1893
1894 if ( pdir->off != ~(size_t)0
1895 && pdir->off + sizeof(MY_FILE_NAMES_INFORMATION) <= pdir->cb)
1896 {
1897 PMY_FILE_NAMES_INFORMATION pcur = (PMY_FILE_NAMES_INFORMATION)&pdir->buf[pdir->off];
1898 ANSI_STRING astr;
1899 UNICODE_STRING ustr;
1900
1901 astr.Length = astr.MaximumLength = sizeof(pdir->ent.name);
1902 astr.Buffer = &pdir->ent.name[0];
1903
1904 ustr.Length = ustr.MaximumLength = pcur->FileNameLength < ~(USHORT)0 ? (USHORT)pcur->FileNameLength : ~(USHORT)0;
1905 ustr.Buffer = &pcur->FileName[0];
1906
1907 rcNt = g_pfnRtlUnicodeStringToAnsiString(&astr, &ustr, 0/*AllocateDestinationString*/);
1908 if (rcNt < 0)
1909 sprintf(pdir->ent.name, "conversion-failed-%08x-rcNt=%08x-len=%u",
1910 pcur->FileIndex, rcNt, pcur->FileNameLength);
1911 if (pcur->NextEntryOffset)
1912 pdir->off += pcur->NextEntryOffset;
1913 else
1914 pdir->off = pdir->cb;
1915 return &pdir->ent;
1916 }
1917 }
1918 else
1919 errno = EINVAL;
1920 return NULL;
1921#else
1922 struct dirent *pde = readdir((DIR *)pdir);
1923 return pde ? (shdirent *)&pde->d_name[0] : NULL;
1924#endif
1925}
1926
1927void shfile_closedir(struct shdir *pdir)
1928{
1929#if defined(SHFILE_IN_USE) && K_OS == K_OS_WINDOWS
1930 if (pdir)
1931 {
1932 CloseHandle(pdir->native);
1933 pdir->pfdtab = NULL;
1934 pdir->native = INVALID_HANDLE_VALUE;
1935 sh_free(shthread_get_shell(), pdir);
1936 }
1937 else
1938 errno = EINVAL;
1939#else
1940 closedir((DIR *)pdir);
1941#endif
1942}
1943
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette