VirtualBox

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

Last change on this file since 2438 was 2425, checked in by bird, 14 years ago

kash: oops

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Id
File size: 55.6 KB
Line 
1/* $Id: shfile.c 2425 2010-10-18 08:52:22Z 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 * Initializes the global variables in this file.
531 */
532static void shfile_init_globals(void)
533{
534#if K_OS == K_OS_WINDOWS
535 if (!g_shfile_globals_initialized)
536 {
537 HMODULE hNtDll = GetModuleHandle("NTDLL");
538 g_pfnNtQueryObject = (PFN_NtQueryObject) GetProcAddress(hNtDll, "NtQueryObject");
539 g_pfnNtQueryDirectoryFile = (PFN_NtQueryDirectoryFile)GetProcAddress(hNtDll, "NtQueryDirectoryFile");
540 g_pfnRtlUnicodeStringToAnsiString = (PFN_RtlUnicodeStringToAnsiString)GetProcAddress(hNtDll, "RtlUnicodeStringToAnsiString");
541 if ( !g_pfnRtlUnicodeStringToAnsiString
542 || !g_pfnNtQueryDirectoryFile)
543 {
544 /* fatal error */
545 }
546 g_shfile_globals_initialized = 1;
547 }
548#endif
549}
550
551/**
552 * Initializes a file descriptor table.
553 *
554 * @returns 0 on success, -1 and errno on failure.
555 * @param pfdtab The table to initialize.
556 * @param inherit File descriptor table to inherit from. If not specified
557 * we will inherit from the current process as it were.
558 */
559int shfile_init(shfdtab *pfdtab, shfdtab *inherit)
560{
561 int rc;
562
563 shfile_init_globals();
564
565 pfdtab->cwd = NULL;
566 pfdtab->size = 0;
567 pfdtab->tab = NULL;
568 rc = shmtx_init(&pfdtab->mtx);
569 if (!rc)
570 {
571#ifdef SHFILE_IN_USE
572 char buf[SHFILE_MAX_PATH];
573 if (getcwd(buf, sizeof(buf)))
574 {
575 pfdtab->cwd = sh_strdup(NULL, buf);
576 if (!inherit)
577 {
578# if K_OS == K_OS_WINDOWS
579 static const struct
580 {
581 DWORD dwStdHandle;
582 unsigned fFlags;
583 } aStdHandles[3] =
584 {
585 { STD_INPUT_HANDLE, _O_RDONLY },
586 { STD_OUTPUT_HANDLE, _O_WRONLY },
587 { STD_ERROR_HANDLE, _O_WRONLY }
588 };
589 int i;
590 STARTUPINFO Info;
591 ACCESS_MASK Mask;
592 DWORD dwErr;
593
594 rc = 0;
595
596 /* Try pick up the Visual C++ CRT file descriptor info. */
597 __try {
598 GetStartupInfo(&Info);
599 } __except (EXCEPTION_EXECUTE_HANDLER) {
600 memset(&Info, 0, sizeof(Info));
601 }
602
603 if ( Info.cbReserved2 > sizeof(int)
604 && (uintptr_t)Info.lpReserved2 >= 0x1000
605 && (i = *(int *)Info.lpReserved2) >= 1
606 && i <= 2048
607 && ( Info.cbReserved2 == i * 5 + 4
608 //|| Info.cbReserved2 == i * 5 + 1 - check the cygwin sources.
609 || Info.cbReserved2 == i * 9 + 4))
610 {
611 uint8_t *paf = (uint8_t *)Info.lpReserved2 + sizeof(int);
612 int dwPerH = 1 + (Info.cbReserved2 == i * 9 + 4);
613 DWORD *ph = (DWORD *)(paf + i) + dwPerH * i;
614 HANDLE aStdHandles2[3];
615 int j;
616
617 //if (Info.cbReserved2 == i * 5 + 1) - check the cygwin sources.
618 // i--;
619
620 for (j = 0; j < 3; j++)
621 aStdHandles2[j] = GetStdHandle(aStdHandles[j].dwStdHandle);
622
623 while (i-- > 0)
624 {
625 ph -= dwPerH;
626
627 if ( (paf[i] & (FOPEN | FNOINHERIT)) == FOPEN
628 && *ph != (uint32_t)INVALID_HANDLE_VALUE)
629 {
630 HANDLE h = (HANDLE)(intptr_t)*ph;
631 int fd2;
632 int fFlags;
633 int fFlags2;
634
635 if ( h == aStdHandles2[j = 0]
636 || h == aStdHandles2[j = 1]
637 || h == aStdHandles2[j = 2])
638 fFlags = aStdHandles[j].fFlags;
639 else
640 {
641 dwErr = shfile_query_handle_access_mask(h, &Mask);
642 if (dwErr == ERROR_INVALID_HANDLE)
643 continue;
644 else if (dwErr == NO_ERROR)
645 {
646 fFlags = 0;
647 if ( (Mask & (GENERIC_READ | FILE_READ_DATA))
648 && (Mask & (GENERIC_WRITE | FILE_WRITE_DATA | FILE_APPEND_DATA)))
649 fFlags |= O_RDWR;
650 else if (Mask & (GENERIC_READ | FILE_READ_DATA))
651 fFlags |= O_RDONLY;
652 else if (Mask & (GENERIC_WRITE | FILE_WRITE_DATA | FILE_APPEND_DATA))
653 fFlags |= O_WRONLY;
654 else
655 fFlags |= O_RDWR;
656 if ((Mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) == FILE_APPEND_DATA)
657 fFlags |= O_APPEND;
658 }
659 else
660 fFlags = O_RDWR;
661 }
662
663 if (paf[i] & FPIPE)
664 fFlags2 = SHFILE_FLAGS_PIPE;
665 else if (paf[i] & FDEV)
666 fFlags2 = SHFILE_FLAGS_TTY;
667 else
668 fFlags2 = 0;
669
670 fd2 = shfile_insert(pfdtab, (intptr_t)h, fFlags, fFlags2, i, "shtab_init");
671 assert(fd2 == i); (void)fd2;
672 if (fd2 != i)
673 rc = -1;
674 }
675 }
676 }
677
678 /* Check the three standard handles. */
679 for (i = 0; i < 3; i++)
680 if ( (unsigned)i >= pfdtab->size
681 || pfdtab->tab[i].fd == -1)
682 {
683 HANDLE hFile = GetStdHandle(aStdHandles[i].dwStdHandle);
684 if (hFile != INVALID_HANDLE_VALUE)
685 {
686 DWORD dwType = GetFileType(hFile);
687 unsigned fFlags = aStdHandles[i].fFlags;
688 unsigned fFlags2;
689 int fd2;
690 if (dwType == FILE_TYPE_CHAR)
691 fFlags2 = SHFILE_FLAGS_TTY;
692 else if (dwType == FILE_TYPE_PIPE)
693 fFlags2 = SHFILE_FLAGS_PIPE;
694 else
695 fFlags2 = SHFILE_FLAGS_FILE;
696 fd2 = shfile_insert(pfdtab, (intptr_t)hFile, fFlags, fFlags2, i, "shtab_init");
697 assert(fd2 == i); (void)fd2;
698 if (fd2 != i)
699 rc = -1;
700 }
701 }
702# else
703 /*
704 * Annoying...
705 */
706 int fd;
707
708 for (fd = 0; fd < 10; fd++)
709 {
710 int oflags = fcntl(fd, F_GETFL, 0);
711 if (oflags != -1)
712 {
713 int cox = fcntl(fd, F_GETFD, 0);
714 struct stat st;
715 if ( cox != -1
716 && fstat(fd, &st) != -1)
717 {
718 int native;
719 int fd2;
720 int fFlags2 = 0;
721 if (cox & FD_CLOEXEC)
722 fFlags2 |= SHFILE_FLAGS_CLOSE_ON_EXEC;
723 if (S_ISREG(st.st_mode))
724 fFlags2 |= SHFILE_FLAGS_FILE;
725 else if (S_ISDIR(st.st_mode))
726 fFlags2 |= SHFILE_FLAGS_DIR;
727 else if (S_ISCHR(st.st_mode))
728 fFlags2 |= SHFILE_FLAGS_TTY;
729 else if (S_ISFIFO(st.st_mode))
730 fFlags2 |= SHFILE_FLAGS_PIPE;
731 else
732 fFlags2 |= SHFILE_FLAGS_TTY;
733
734 native = fcntl(fd, F_DUPFD, SHFILE_UNIX_MIN_FD);
735 if (native == -1)
736 native = fd;
737 fd2 = shfile_insert(pfdtab, native, oflags, fFlags2, fd, "shtab_init");
738 assert(fd2 == fd); (void)fd2;
739 if (fd2 != fd)
740 rc = -1;
741 if (native != fd)
742 close(fd);
743 }
744 }
745 }
746
747# endif
748 }
749 else
750 {
751 /** @todo */
752 errno = ENOSYS;
753 rc = -1;
754 }
755 }
756 else
757 rc = -1;
758#endif
759 }
760 return rc;
761}
762
763#if K_OS == K_OS_WINDOWS && defined(SHFILE_IN_USE)
764
765/**
766 * Helper for shfork.
767 *
768 * @param pfdtab The file descriptor table.
769 * @param set Whether to make all handles inheritable (1) or
770 * to restore them to the rigth state (0).
771 * @param hndls Where to store the three standard handles.
772 */
773void shfile_fork_win(shfdtab *pfdtab, int set, intptr_t *hndls)
774{
775 shmtxtmp tmp;
776 unsigned i;
777 DWORD fFlag = set ? HANDLE_FLAG_INHERIT : 0;
778
779 shmtx_enter(&pfdtab->mtx, &tmp);
780 TRACE2((NULL, "shfile_fork_win: set=%d\n", set));
781
782 i = pfdtab->size;
783 while (i-- > 0)
784 {
785 if (pfdtab->tab[i].fd == i)
786 {
787 HANDLE hFile = (HANDLE)pfdtab->tab[i].native;
788 if (set)
789 TRACE2((NULL, " #%d: native=%#x oflags=%#x shflags=%#x\n",
790 i, hFile, pfdtab->tab[i].oflags, pfdtab->tab[i].shflags));
791 if (!SetHandleInformation(hFile, HANDLE_FLAG_INHERIT, fFlag))
792 {
793 DWORD err = GetLastError();
794 assert(0);
795 }
796 }
797 }
798
799 if (hndls)
800 {
801 for (i = 0; i < 3; i++)
802 {
803 if ( pfdtab->size > i
804 && pfdtab->tab[i].fd == i)
805 hndls[i] = pfdtab->tab[i].native;
806 else
807 hndls[i] = (intptr_t)INVALID_HANDLE_VALUE;
808 TRACE2((NULL, "shfile_fork_win: i=%d size=%d fd=%d native=%d hndls[%d]=%p\n",
809 i, pfdtab->size, pfdtab->tab[i].fd, pfdtab->tab[i].native, i, hndls[i]));
810 }
811 }
812
813 shmtx_leave(&pfdtab->mtx, &tmp);
814}
815
816/**
817 * Helper for sh_execve.
818 *
819 * This is called before and after CreateProcess. On the first call it
820 * will mark the non-close-on-exec handles as inheritable and produce
821 * the startup info for the CRT. On the second call, after CreateProcess,
822 * it will restore the handle inheritability properties.
823 *
824 * @returns Pointer to CRT data if prepare is 1, NULL if prepare is 0.
825 * @param pfdtab The file descriptor table.
826 * @param prepare Which call, 1 if before and 0 if after.
827 * @param sizep Where to store the size of the returned data.
828 * @param hndls Where to store the three standard handles.
829 */
830void *shfile_exec_win(shfdtab *pfdtab, int prepare, unsigned short *sizep, intptr_t *hndls)
831{
832 void *pvRet;
833 shmtxtmp tmp;
834 unsigned count;
835 unsigned i;
836
837 shmtx_enter(&pfdtab->mtx, &tmp);
838 TRACE2((NULL, "shfile_exec_win: prepare=%p\n", prepare));
839
840 count = pfdtab->size < (0x10000-4) / (1 + sizeof(HANDLE))
841 ? pfdtab->size
842 : (0x10000-4) / (1 + sizeof(HANDLE));
843 while (count > 3 && pfdtab->tab[count - 1].fd == -1)
844 count--;
845
846 if (prepare)
847 {
848 size_t cbData = sizeof(int) + count * (1 + sizeof(HANDLE));
849 uint8_t *pbData = sh_malloc(shthread_get_shell(), cbData);
850 uint8_t *paf = pbData + sizeof(int);
851 HANDLE *pah = (HANDLE *)(paf + count);
852
853 *(int *)pbData = count;
854
855 i = count;
856 while (i-- > 0)
857 {
858 if ( pfdtab->tab[i].fd == i
859 && !(pfdtab->tab[i].shflags & SHFILE_FLAGS_CLOSE_ON_EXEC))
860 {
861 HANDLE hFile = (HANDLE)pfdtab->tab[i].native;
862 TRACE2((NULL, " #%d: native=%#x oflags=%#x shflags=%#x\n",
863 i, hFile, pfdtab->tab[i].oflags, pfdtab->tab[i].shflags));
864
865 if (!SetHandleInformation(hFile, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT))
866 {
867 DWORD err = GetLastError();
868 assert(0);
869 }
870 paf[i] = FOPEN;
871 if (pfdtab->tab[i].oflags & _O_APPEND)
872 paf[i] |= FAPPEND;
873 if (pfdtab->tab[i].oflags & _O_TEXT)
874 paf[i] |= FTEXT;
875 switch (pfdtab->tab[i].shflags & SHFILE_FLAGS_TYPE_MASK)
876 {
877 case SHFILE_FLAGS_TTY: paf[i] |= FDEV; break;
878 case SHFILE_FLAGS_PIPE: paf[i] |= FPIPE; break;
879 }
880 pah[i] = hFile;
881 }
882 else
883 {
884 paf[i] = 0;
885 pah[i] = INVALID_HANDLE_VALUE;
886 }
887 }
888
889 for (i = 0; i < 3; i++)
890 {
891 if ( i < count
892 && pfdtab->tab[i].fd == i)
893 hndls[i] = pfdtab->tab[i].native;
894 else
895 hndls[i] = (intptr_t)INVALID_HANDLE_VALUE;
896 TRACE2((NULL, "shfile_exec_win: i=%d count=%d fd=%d native=%d hndls[%d]=\n",
897 i, count, pfdtab->tab[i].fd, pfdtab->tab[i].native, i, hndls[i]));
898 }
899
900 *sizep = (unsigned short)cbData;
901 pvRet = pbData;
902 }
903 else
904 {
905 assert(!hndls);
906 assert(!sizep);
907 i = count;
908 while (i-- > 0)
909 {
910 if ( pfdtab->tab[i].fd == i
911 && !(pfdtab->tab[i].shflags & SHFILE_FLAGS_CLOSE_ON_EXEC))
912 {
913 HANDLE hFile = (HANDLE)pfdtab->tab[i].native;
914 if (!SetHandleInformation(hFile, HANDLE_FLAG_INHERIT, 0))
915 {
916 DWORD err = GetLastError();
917 assert(0);
918 }
919 }
920 }
921 pvRet = NULL;
922 }
923
924 shmtx_leave(&pfdtab->mtx, &tmp);
925 return pvRet;
926}
927
928#endif /* K_OS_WINDOWS */
929
930#if K_OS != K_OS_WINDOWS
931/**
932 * Prepare file handles for inherting before a execve call.
933 *
934 * This is only used in the normal mode, so we've forked and need not worry
935 * about cleaning anything up after us. Nor do we need think about locking.
936 *
937 * @returns 0 on success, -1 on failure.
938 */
939int shfile_exec_unix(shfdtab *pfdtab)
940{
941 int rc = 0;
942# ifdef SHFILE_IN_USE
943 unsigned fd;
944
945 for (fd = 0; fd < pfdtab->size; fd++)
946 {
947 if ( pfdtab->tab[fd].fd != -1
948 && !(pfdtab->tab[fd].shflags & SHFILE_FLAGS_CLOSE_ON_EXEC) )
949 {
950 TRACE2((NULL, "shfile_exec_unix: %d => %d\n", pfdtab->tab[fd].native, fd));
951 if (dup2(pfdtab->tab[fd].native, fd) < 0)
952 {
953 /* fatal_error(NULL, "shfile_exec_unix: failed to move %d to %d", pfdtab->tab[fd].fd, fd); */
954 rc = -1;
955 }
956 }
957 }
958# endif
959 return rc;
960}
961#endif /* !K_OS_WINDOWS */
962
963/**
964 * open().
965 */
966int shfile_open(shfdtab *pfdtab, const char *name, unsigned flags, mode_t mode)
967{
968 int fd;
969#ifdef SHFILE_IN_USE
970 char absname[SHFILE_MAX_PATH];
971# if K_OS == K_OS_WINDOWS
972 HANDLE hFile;
973 DWORD dwDesiredAccess;
974 DWORD dwShareMode;
975 DWORD dwCreationDisposition;
976 DWORD dwFlagsAndAttributes;
977 SECURITY_ATTRIBUTES SecurityAttributes;
978
979# ifndef _O_ACCMODE
980# define _O_ACCMODE (_O_RDONLY|_O_WRONLY|_O_RDWR)
981# endif
982 switch (flags & (_O_ACCMODE | _O_APPEND))
983 {
984 case _O_RDONLY: dwDesiredAccess = GENERIC_READ; break;
985 case _O_RDONLY | _O_APPEND: dwDesiredAccess = GENERIC_READ; break;
986 case _O_WRONLY: dwDesiredAccess = GENERIC_WRITE; break;
987 case _O_WRONLY | _O_APPEND: dwDesiredAccess = (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA); break;
988 case _O_RDWR: dwDesiredAccess = GENERIC_READ | GENERIC_WRITE; break;
989 case _O_RDWR | _O_APPEND: dwDesiredAccess = GENERIC_READ | (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA); break;
990
991 default:
992 RETURN_ERROR(-1, EINVAL, "invalid mode");
993 }
994
995 dwShareMode = FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE;
996
997 SecurityAttributes.nLength = sizeof(SecurityAttributes);
998 SecurityAttributes.lpSecurityDescriptor = NULL;
999 SecurityAttributes.bInheritHandle = FALSE;
1000
1001 if (flags & _O_CREAT)
1002 {
1003 if ((flags & (_O_EXCL | _O_TRUNC)) == (_O_EXCL | _O_TRUNC))
1004 RETURN_ERROR(-1, EINVAL, "_O_EXCL | _O_TRUNC");
1005
1006 if (flags & _O_TRUNC)
1007 dwCreationDisposition = CREATE_ALWAYS; /* not 100%, but close enough */
1008 else if (flags & _O_EXCL)
1009 dwCreationDisposition = CREATE_NEW;
1010 else
1011 dwCreationDisposition = OPEN_ALWAYS;
1012 }
1013 else if (flags & _O_TRUNC)
1014 dwCreationDisposition = TRUNCATE_EXISTING;
1015 else
1016 dwCreationDisposition = OPEN_EXISTING;
1017
1018 if (!(flags & _O_CREAT) || (mode & 0222))
1019 dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
1020 else
1021 dwFlagsAndAttributes = FILE_ATTRIBUTE_READONLY;
1022
1023 fd = shfile_make_path(pfdtab, name, &absname[0]);
1024 if (!fd)
1025 {
1026 SetLastError(0);
1027 hFile = CreateFileA(absname,
1028 dwDesiredAccess,
1029 dwShareMode,
1030 &SecurityAttributes,
1031 dwCreationDisposition,
1032 dwFlagsAndAttributes,
1033 NULL /* hTemplateFile */);
1034 if (hFile != INVALID_HANDLE_VALUE)
1035 fd = shfile_insert(pfdtab, (intptr_t)hFile, flags, 0, -1, "shfile_open");
1036 else
1037 fd = shfile_dos2errno(GetLastError());
1038 }
1039
1040# else /* K_OS != K_OS_WINDOWS */
1041 fd = shfile_make_path(pfdtab, name, &absname[0]);
1042 if (!fd)
1043 {
1044 fd = open(absname, flags, mode);
1045 if (fd != -1)
1046 fd = shfile_copy_insert_and_close(pfdtab, &fd, flags, 0, -1, "shfile_open");
1047 }
1048
1049# endif /* K_OS != K_OS_WINDOWS */
1050
1051#else
1052 fd = open(name, flags, mode);
1053#endif
1054
1055 TRACE2((NULL, "shfile_open(%p:{%s}, %#x, 0%o) -> %d [%d]\n", name, name, flags, mode, fd, errno));
1056 return fd;
1057}
1058
1059int shfile_pipe(shfdtab *pfdtab, int fds[2])
1060{
1061 int rc = -1;
1062#ifdef SHFILE_IN_USE
1063# if K_OS == K_OS_WINDOWS
1064 HANDLE hRead = INVALID_HANDLE_VALUE;
1065 HANDLE hWrite = INVALID_HANDLE_VALUE;
1066 SECURITY_ATTRIBUTES SecurityAttributes;
1067
1068 SecurityAttributes.nLength = sizeof(SecurityAttributes);
1069 SecurityAttributes.lpSecurityDescriptor = NULL;
1070 SecurityAttributes.bInheritHandle = FALSE;
1071
1072 fds[1] = fds[0] = -1;
1073 if (CreatePipe(&hRead, &hWrite, &SecurityAttributes, 4096))
1074 {
1075 fds[0] = shfile_insert(pfdtab, (intptr_t)hRead, O_RDONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
1076 if (fds[0] != -1)
1077 {
1078 fds[1] = shfile_insert(pfdtab, (intptr_t)hWrite, O_WRONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
1079 if (fds[1] != -1)
1080 rc = 0;
1081 }
1082
1083# else
1084 int native_fds[2];
1085
1086 fds[1] = fds[0] = -1;
1087 if (!pipe(native_fds))
1088 {
1089 fds[0] = shfile_copy_insert_and_close(pfdtab, &native_fds[0], O_RDONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
1090 if (fds[0] != -1)
1091 {
1092 fds[1] = shfile_copy_insert_and_close(pfdtab, &native_fds[1], O_WRONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
1093 if (fds[1] != -1)
1094 rc = 0;
1095 }
1096# endif
1097 if (fds[1] == -1)
1098 {
1099 int s = errno;
1100 if (fds[0] != -1)
1101 {
1102 shmtxtmp tmp;
1103 shmtx_enter(&pfdtab->mtx, &tmp);
1104 rc = fds[0];
1105 pfdtab->tab[rc].fd = -1;
1106 pfdtab->tab[rc].oflags = 0;
1107 pfdtab->tab[rc].shflags = 0;
1108 pfdtab->tab[rc].native = -1;
1109 shmtx_leave(&pfdtab->mtx, &tmp);
1110 }
1111
1112# if K_OS == K_OS_WINDOWS
1113 CloseHandle(hRead);
1114 CloseHandle(hWrite);
1115# else
1116 close(native_fds[0]);
1117 close(native_fds[1]);
1118# endif
1119 fds[0] = fds[1] = -1;
1120 errno = s;
1121 rc = -1;
1122 }
1123 }
1124 else
1125 {
1126# if K_OS == K_OS_WINDOWS
1127 errno = shfile_dos2errno(GetLastError());
1128# endif
1129 rc = -1;
1130 }
1131
1132#else
1133 rc = pipe(fds);
1134#endif
1135
1136 TRACE2((NULL, "shfile_pipe() -> %d{%d,%d} [%d]\n", rc, fds[0], fds[1], errno));
1137 return rc;
1138}
1139
1140/**
1141 * dup().
1142 */
1143int shfile_dup(shfdtab *pfdtab, int fd)
1144{
1145 return shfile_fcntl(pfdtab,fd, F_DUPFD, 0);
1146}
1147
1148/**
1149 * Move the file descriptor, closing any existing descriptor at @a fdto.
1150 *
1151 * @returns fdto on success, -1 and errno on failure.
1152 * @param pfdtab The file descriptor table.
1153 * @param fdfrom The descriptor to move.
1154 * @param fdto Where to move it.
1155 */
1156int shfile_movefd(shfdtab *pfdtab, int fdfrom, int fdto)
1157{
1158#ifdef SHFILE_IN_USE
1159 int rc;
1160 shmtxtmp tmp;
1161 shfile *file = shfile_get(pfdtab, fdfrom, &tmp);
1162 if (file)
1163 {
1164 /* prepare the new entry */
1165 if (fdto >= (int)pfdtab->size)
1166 shfile_grow_tab_locked(pfdtab, fdto);
1167 if (fdto < (int)pfdtab->size)
1168 {
1169 if (pfdtab->tab[fdto].fd != -1)
1170 shfile_native_close(pfdtab->tab[fdto].native, pfdtab->tab[fdto].oflags);
1171
1172 /* setup the target. */
1173 pfdtab->tab[fdto].fd = fdto;
1174 pfdtab->tab[fdto].oflags = file->oflags;
1175 pfdtab->tab[fdto].shflags = file->shflags;
1176 pfdtab->tab[fdto].native = file->native;
1177
1178 /* close the source. */
1179 file->fd = -1;
1180 file->oflags = 0;
1181 file->shflags = 0;
1182 file->native = -1;
1183
1184 rc = fdto;
1185 }
1186 else
1187 {
1188 errno = EMFILE;
1189 rc = -1;
1190 }
1191
1192 shfile_put(pfdtab, file, &tmp);
1193 }
1194 else
1195 rc = -1;
1196 return rc;
1197
1198#else
1199 return dup2(fdfrom, fdto);
1200#endif
1201}
1202
1203/**
1204 * Move the file descriptor to somewhere at @a fdMin or above.
1205 *
1206 * @returns the new file descriptor success, -1 and errno on failure.
1207 * @param pfdtab The file descriptor table.
1208 * @param fdfrom The descriptor to move.
1209 * @param fdMin The minimum descriptor.
1210 */
1211int shfile_movefd_above(shfdtab *pfdtab, int fdfrom, int fdMin)
1212{
1213#ifdef SHFILE_IN_USE
1214 int fdto;
1215 shmtxtmp tmp;
1216 shfile *file = shfile_get(pfdtab, fdfrom, &tmp);
1217 if (file)
1218 {
1219 /* find a new place */
1220 int i;
1221 fdto = -1;
1222 for (i = fdMin; (unsigned)i < pfdtab->size; i++)
1223 if (pfdtab->tab[i].fd == -1)
1224 {
1225 fdto = i;
1226 break;
1227 }
1228 if (fdto == -1)
1229 fdto = shfile_grow_tab_locked(pfdtab, fdMin);
1230 if (fdto != -1)
1231 {
1232 /* setup the target. */
1233 pfdtab->tab[fdto].fd = fdto;
1234 pfdtab->tab[fdto].oflags = file->oflags;
1235 pfdtab->tab[fdto].shflags = file->shflags;
1236 pfdtab->tab[fdto].native = file->native;
1237
1238 /* close the source. */
1239 file->fd = -1;
1240 file->oflags = 0;
1241 file->shflags = 0;
1242 file->native = -1;
1243 }
1244 else
1245 {
1246 errno = EMFILE;
1247 fdto = -1;
1248 }
1249
1250 shfile_put(pfdtab, file, &tmp);
1251 }
1252 else
1253 fdto = -1;
1254 return fdto;
1255
1256#else
1257 int fdnew = fcntl(fdfrom, F_DUPFD, fdMin);
1258 if (fdnew >= 0)
1259 close(fdfrom);
1260 return fdnew;
1261#endif
1262}
1263
1264/**
1265 * close().
1266 */
1267int shfile_close(shfdtab *pfdtab, unsigned fd)
1268{
1269 int rc;
1270#ifdef SHFILE_IN_USE
1271 shmtxtmp tmp;
1272 shfile *file = shfile_get(pfdtab, fd, &tmp);
1273 if (file)
1274 {
1275 shfile_native_close(file->native, file->oflags);
1276
1277 file->fd = -1;
1278 file->oflags = 0;
1279 file->shflags = 0;
1280 file->native = -1;
1281
1282 shfile_put(pfdtab, file, &tmp);
1283 rc = 0;
1284 }
1285 else
1286 rc = -1;
1287
1288#else
1289 rc = close(fd);
1290#endif
1291
1292 TRACE2((NULL, "shfile_close(%d) -> %d [%d]\n", fd, rc, errno));
1293 return rc;
1294}
1295
1296/**
1297 * read().
1298 */
1299long shfile_read(shfdtab *pfdtab, int fd, void *buf, size_t len)
1300{
1301 long rc;
1302#ifdef SHFILE_IN_USE
1303 shmtxtmp tmp;
1304 shfile *file = shfile_get(pfdtab, fd, &tmp);
1305 if (file)
1306 {
1307# if K_OS == K_OS_WINDOWS
1308 DWORD dwRead = 0;
1309 if (ReadFile((HANDLE)file->native, buf, (DWORD)len, &dwRead, NULL))
1310 rc = dwRead;
1311 else
1312 rc = shfile_dos2errno(GetLastError());
1313# else
1314 rc = read(file->native, buf, len);
1315# endif
1316
1317 shfile_put(pfdtab, file, &tmp);
1318 }
1319 else
1320 rc = -1;
1321
1322#else
1323 rc = read(fd, buf, len);
1324#endif
1325 return rc;
1326}
1327
1328/**
1329 * write().
1330 */
1331long shfile_write(shfdtab *pfdtab, int fd, const void *buf, size_t len)
1332{
1333 long rc;
1334#ifdef SHFILE_IN_USE
1335 shmtxtmp tmp;
1336 shfile *file = shfile_get(pfdtab, fd, &tmp);
1337 if (file)
1338 {
1339# if K_OS == K_OS_WINDOWS
1340 DWORD dwWritten = 0;
1341 if (WriteFile((HANDLE)file->native, buf, (DWORD)len, &dwWritten, NULL))
1342 rc = dwWritten;
1343 else
1344 rc = shfile_dos2errno(GetLastError());
1345# else
1346 rc = write(file->native, buf, len);
1347# endif
1348
1349 shfile_put(pfdtab, file, &tmp);
1350 }
1351 else
1352 rc = -1;
1353
1354#else
1355 if (fd != shthread_get_shell()->tracefd)
1356 {
1357 struct stat s;
1358 int x;
1359 x = fstat(fd, &s);
1360 TRACE2((NULL, "shfile_write(%d) - %lu bytes (%d) - pos %lu - before; %o\n",
1361 fd, (long)s.st_size, x, (long)lseek(fd, 0, SEEK_CUR), s.st_mode ));
1362 errno = 0;
1363 }
1364
1365 rc = write(fd, buf, len);
1366#endif
1367
1368#ifdef DEBUG
1369 if (fd != shthread_get_shell()->tracefd)
1370 {
1371 struct stat s;
1372 int x;
1373 TRACE2((NULL, "shfile_write(%d,,%d) -> %d [%d]\n", fd, len, rc, errno));
1374 x=fstat(fd, &s);
1375 TRACE2((NULL, "shfile_write(%d) - %lu bytes (%d) - pos %lu - after\n", fd, (long)s.st_size, x, (long)lseek(fd, 0, SEEK_CUR) ));
1376 }
1377#endif
1378 return rc;
1379}
1380
1381/**
1382 * lseek().
1383 */
1384long shfile_lseek(shfdtab *pfdtab, int fd, long off, int whench)
1385{
1386 long rc;
1387#ifdef SHFILE_IN_USE
1388 shmtxtmp tmp;
1389 shfile *file = shfile_get(pfdtab, fd, &tmp);
1390 if (file)
1391 {
1392# if K_OS == K_OS_WINDOWS
1393 assert(SEEK_SET == FILE_BEGIN);
1394 assert(SEEK_CUR == FILE_CURRENT);
1395 assert(SEEK_END == FILE_END);
1396 rc = SetFilePointer((HANDLE)file->native, off, NULL, whench);
1397 if (rc == INVALID_SET_FILE_POINTER)
1398 rc = shfile_dos2errno(GetLastError());
1399# else
1400 rc = lseek(file->native, off, whench);
1401# endif
1402
1403 shfile_put(pfdtab, file, &tmp);
1404 }
1405 else
1406 rc = -1;
1407
1408#else
1409 rc = lseek(fd, off, whench);
1410#endif
1411
1412 return rc;
1413}
1414
1415int shfile_fcntl(shfdtab *pfdtab, int fd, int cmd, int arg)
1416{
1417 int rc;
1418#ifdef SHFILE_IN_USE
1419 shmtxtmp tmp;
1420 shfile *file = shfile_get(pfdtab, fd, &tmp);
1421 if (file)
1422 {
1423 switch (cmd)
1424 {
1425 case F_GETFL:
1426 rc = file->oflags;
1427 break;
1428
1429 case F_SETFL:
1430 {
1431 unsigned mask = O_NONBLOCK | O_APPEND | O_BINARY | O_TEXT;
1432# ifdef O_DIRECT
1433 mask |= O_DIRECT;
1434# endif
1435# ifdef O_ASYNC
1436 mask |= O_ASYNC;
1437# endif
1438# ifdef O_SYNC
1439 mask |= O_SYNC;
1440# endif
1441 if ((file->oflags & mask) == (arg & mask))
1442 rc = 0;
1443 else
1444 {
1445# if K_OS == K_OS_WINDOWS
1446 assert(0);
1447 errno = EINVAL;
1448 rc = -1;
1449# else
1450 rc = fcntl(file->native, F_SETFL, arg);
1451 if (rc != -1)
1452 file->oflags = (file->oflags & ~mask) | (arg & mask);
1453# endif
1454 }
1455 break;
1456 }
1457
1458 case F_DUPFD:
1459 {
1460# if K_OS == K_OS_WINDOWS
1461 HANDLE hNew = INVALID_HANDLE_VALUE;
1462 if (DuplicateHandle(GetCurrentProcess(),
1463 (HANDLE)file->native,
1464 GetCurrentProcess(),
1465 &hNew,
1466 0,
1467 FALSE /* bInheritHandle */,
1468 DUPLICATE_SAME_ACCESS))
1469 rc = shfile_insert(pfdtab, (intptr_t)hNew, file->oflags, file->shflags, arg, "shfile_fcntl");
1470 else
1471 rc = shfile_dos2errno(GetLastError());
1472# else
1473 int nativeNew = fcntl(file->native, F_DUPFD, SHFILE_UNIX_MIN_FD);
1474 if (nativeNew != -1)
1475 rc = shfile_insert(pfdtab, nativeNew, file->oflags, file->shflags, arg, "shfile_fcntl");
1476 else
1477 rc = -1;
1478# endif
1479 break;
1480 }
1481
1482 default:
1483 errno = -EINVAL;
1484 rc = -1;
1485 break;
1486 }
1487
1488 shfile_put(pfdtab, file, &tmp);
1489 }
1490 else
1491 rc = -1;
1492
1493#else
1494 rc = fcntl(fd, cmd, arg);
1495#endif
1496
1497 switch (cmd)
1498 {
1499 case F_GETFL: TRACE2((NULL, "shfile_fcntl(%d,F_GETFL,ignored=%d) -> %d [%d]\n", fd, arg, rc, errno)); break;
1500 case F_SETFL: TRACE2((NULL, "shfile_fcntl(%d,F_SETFL,newflags=%#x) -> %d [%d]\n", fd, arg, rc, errno)); break;
1501 case F_DUPFD: TRACE2((NULL, "shfile_fcntl(%d,F_DUPFS,minfd=%d) -> %d [%d]\n", fd, arg, rc, errno)); break;
1502 default: TRACE2((NULL, "shfile_fcntl(%d,%d,%d) -> %d [%d]\n", fd, cmd, arg, rc, errno)); break;
1503 }
1504 return rc;
1505}
1506
1507int shfile_stat(shfdtab *pfdtab, const char *path, struct stat *pst)
1508{
1509#ifdef SHFILE_IN_USE
1510 char abspath[SHFILE_MAX_PATH];
1511 int rc;
1512 rc = shfile_make_path(pfdtab, path, &abspath[0]);
1513 if (!rc)
1514 {
1515# if K_OS == K_OS_WINDOWS
1516 rc = stat(abspath, pst); /** @todo re-implement stat. */
1517# else
1518 rc = stat(abspath, pst);
1519# endif
1520 }
1521 TRACE2((NULL, "shfile_stat(,%s,) -> %d [%d]\n", path, rc, errno));
1522 return rc;
1523#else
1524 return stat(path, pst);
1525#endif
1526}
1527
1528int shfile_lstat(shfdtab *pfdtab, const char *path, struct stat *pst)
1529{
1530 int rc;
1531#ifdef SHFILE_IN_USE
1532 char abspath[SHFILE_MAX_PATH];
1533
1534 rc = shfile_make_path(pfdtab, path, &abspath[0]);
1535 if (!rc)
1536 {
1537# if K_OS == K_OS_WINDOWS
1538 rc = stat(abspath, pst); /** @todo implement lstat. */
1539# else
1540 rc = lstat(abspath, pst);
1541# endif
1542 }
1543#else
1544 rc = stat(path, pst);
1545#endif
1546 TRACE2((NULL, "shfile_stat(,%s,) -> %d [%d]\n", path, rc, errno));
1547 return rc;
1548}
1549
1550/**
1551 * chdir().
1552 */
1553int shfile_chdir(shfdtab *pfdtab, const char *path)
1554{
1555 int rc;
1556#ifdef SHFILE_IN_USE
1557 shinstance *psh = shthread_get_shell();
1558 char abspath[SHFILE_MAX_PATH];
1559
1560 rc = shfile_make_path(pfdtab, path, &abspath[0]);
1561 if (!rc)
1562 {
1563 char *abspath_copy = sh_strdup(psh, abspath);
1564 char *free_me = abspath_copy;
1565 rc = chdir(path);
1566 if (!rc)
1567 {
1568 shmtxtmp tmp;
1569 shmtx_enter(&pfdtab->mtx, &tmp);
1570
1571 free_me = pfdtab->cwd;
1572 pfdtab->cwd = abspath_copy;
1573
1574 shmtx_leave(&pfdtab->mtx, &tmp);
1575 }
1576 sh_free(psh, free_me);
1577 }
1578 else
1579 rc = -1;
1580#else
1581 rc = chdir(path);
1582#endif
1583
1584 TRACE2((NULL, "shfile_chdir(,%s) -> %d [%d]\n", path, rc, errno));
1585 return rc;
1586}
1587
1588/**
1589 * getcwd().
1590 */
1591char *shfile_getcwd(shfdtab *pfdtab, char *buf, int size)
1592{
1593 char *ret;
1594#ifdef SHFILE_IN_USE
1595
1596 ret = NULL;
1597 if (buf && !size)
1598 errno = -EINVAL;
1599 else
1600 {
1601 size_t cwd_size;
1602 shmtxtmp tmp;
1603 shmtx_enter(&pfdtab->mtx, &tmp);
1604
1605 cwd_size = strlen(pfdtab->cwd) + 1;
1606 if (buf)
1607 {
1608 if (cwd_size <= (size_t)size)
1609 ret = memcpy(buf, pfdtab->cwd, cwd_size);
1610 else
1611 errno = ERANGE;
1612 }
1613 else
1614 {
1615 if ((size_t)size < cwd_size)
1616 size = (int)cwd_size;
1617 ret = sh_malloc(shthread_get_shell(), size);
1618 if (ret)
1619 ret = memcpy(ret, pfdtab->cwd, cwd_size);
1620 else
1621 errno = ENOMEM;
1622 }
1623
1624 shmtx_leave(&pfdtab->mtx, &tmp);
1625 }
1626#else
1627 ret = getcwd(buf, size);
1628#endif
1629
1630 TRACE2((NULL, "shfile_getcwd(,%p,%d) -> %s [%d]\n", buf, size, ret, errno));
1631 return ret;
1632}
1633
1634/**
1635 * access().
1636 */
1637int shfile_access(shfdtab *pfdtab, const char *path, int type)
1638{
1639 int rc;
1640#ifdef SHFILE_IN_USE
1641 char abspath[SHFILE_MAX_PATH];
1642
1643 rc = shfile_make_path(pfdtab, path, &abspath[0]);
1644 if (!rc)
1645 {
1646# ifdef _MSC_VER
1647 if (type & X_OK)
1648 type = (type & ~X_OK) | R_OK;
1649# endif
1650 rc = access(abspath, type);
1651 }
1652#else
1653# ifdef _MSC_VER
1654 if (type & X_OK)
1655 type = (type & ~X_OK) | R_OK;
1656# endif
1657 rc = access(path, type);
1658#endif
1659
1660 TRACE2((NULL, "shfile_access(,%s,%#x) -> %d [%d]\n", path, type, rc, errno));
1661 return rc;
1662}
1663
1664/**
1665 * isatty()
1666 */
1667int shfile_isatty(shfdtab *pfdtab, int fd)
1668{
1669 int rc;
1670#ifdef SHFILE_IN_USE
1671 shmtxtmp tmp;
1672 shfile *file = shfile_get(pfdtab, fd, &tmp);
1673 if (file)
1674 {
1675# if K_OS == K_OS_WINDOWS
1676 rc = (file->shflags & SHFILE_FLAGS_TYPE_MASK) == SHFILE_FLAGS_TTY;
1677# else
1678 rc = isatty(file->native);
1679# endif
1680 shfile_put(pfdtab, file, &tmp);
1681 }
1682 else
1683 rc = 0;
1684#else
1685 rc = isatty(fd);
1686#endif
1687
1688 TRACE2((NULL, "isatty(%d) -> %d [%d]\n", fd, rc, errno));
1689 return rc;
1690}
1691
1692/**
1693 * fcntl F_SETFD / FD_CLOEXEC.
1694 */
1695int shfile_cloexec(shfdtab *pfdtab, int fd, int closeit)
1696{
1697 int rc;
1698#ifdef SHFILE_IN_USE
1699 shmtxtmp tmp;
1700 shfile *file = shfile_get(pfdtab, fd, &tmp);
1701 if (file)
1702 {
1703 if (closeit)
1704 file->shflags |= SHFILE_FLAGS_CLOSE_ON_EXEC;
1705 else
1706 file->shflags &= ~SHFILE_FLAGS_CLOSE_ON_EXEC;
1707 shfile_put(pfdtab, file, &tmp);
1708 rc = 0;
1709 }
1710 else
1711 rc = -1;
1712#else
1713 rc = fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0)
1714 | (closeit ? FD_CLOEXEC : 0));
1715#endif
1716
1717 TRACE2((NULL, "shfile_cloexec(%d, %d) -> %d [%d]\n", fd, closeit, rc, errno));
1718 return rc;
1719}
1720
1721
1722int shfile_ioctl(shfdtab *pfdtab, int fd, unsigned long request, void *buf)
1723{
1724 int rc;
1725#ifdef SHFILE_IN_USE
1726 shmtxtmp tmp;
1727 shfile *file = shfile_get(pfdtab, fd, &tmp);
1728 if (file)
1729 {
1730# if K_OS == K_OS_WINDOWS
1731 rc = -1;
1732 errno = ENOSYS;
1733# else
1734 rc = ioctl(file->native, request, buf);
1735# endif
1736 shfile_put(pfdtab, file, &tmp);
1737 }
1738 else
1739 rc = -1;
1740#else
1741 rc = ioctl(fd, request, buf);
1742#endif
1743
1744 TRACE2((NULL, "ioctl(%d, %#x, %p) -> %d\n", fd, request, buf, rc));
1745 return rc;
1746}
1747
1748
1749mode_t shfile_get_umask(shfdtab *pfdtab)
1750{
1751 /** @todo */
1752 return 022;
1753}
1754
1755void shfile_set_umask(shfdtab *pfdtab, mode_t mask)
1756{
1757 /** @todo */
1758 (void)mask;
1759}
1760
1761
1762
1763shdir *shfile_opendir(shfdtab *pfdtab, const char *dir)
1764{
1765#if defined(SHFILE_IN_USE) && K_OS == K_OS_WINDOWS
1766 shdir *pdir = NULL;
1767
1768 if (g_pfnNtQueryDirectoryFile)
1769 {
1770 char abspath[SHFILE_MAX_PATH];
1771 if (shfile_make_path(pfdtab, dir, &abspath[0]) == 0)
1772 {
1773 HANDLE hFile;
1774 SECURITY_ATTRIBUTES SecurityAttributes;
1775
1776 SecurityAttributes.nLength = sizeof(SecurityAttributes);
1777 SecurityAttributes.lpSecurityDescriptor = NULL;
1778 SecurityAttributes.bInheritHandle = FALSE;
1779
1780 hFile = CreateFileA(abspath,
1781 GENERIC_READ,
1782 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
1783 &SecurityAttributes,
1784 OPEN_EXISTING,
1785 FILE_ATTRIBUTE_DIRECTORY | FILE_FLAG_BACKUP_SEMANTICS,
1786 NULL /* hTemplateFile */);
1787 if (hFile != INVALID_HANDLE_VALUE)
1788 {
1789 pdir = (shdir *)sh_malloc(shthread_get_shell(), sizeof(*pdir));
1790 if (pdir)
1791 {
1792 pdir->pfdtab = pfdtab;
1793 pdir->native = hFile;
1794 pdir->off = ~(size_t)0;
1795 }
1796 else
1797 CloseHandle(hFile);
1798 }
1799 else
1800 shfile_dos2errno(GetLastError());
1801 }
1802 }
1803 else
1804 errno = ENOSYS;
1805 return pdir;
1806#else
1807 return (shdir *)opendir(dir);
1808#endif
1809}
1810
1811shdirent *shfile_readdir(struct shdir *pdir)
1812{
1813#if defined(SHFILE_IN_USE) && K_OS == K_OS_WINDOWS
1814 if (pdir)
1815 {
1816 NTSTATUS rcNt;
1817
1818 if ( pdir->off == ~(size_t)0
1819 || pdir->off + sizeof(MY_FILE_NAMES_INFORMATION) >= pdir->cb)
1820 {
1821 MY_IO_STATUS_BLOCK Ios;
1822
1823 memset(&Ios, 0, sizeof(Ios));
1824 rcNt = g_pfnNtQueryDirectoryFile(pdir->native,
1825 NULL /*Event*/,
1826 NULL /*ApcRoutine*/,
1827 NULL /*ApcContext*/,
1828 &Ios,
1829 &pdir->buf[0],
1830 sizeof(pdir->buf),
1831 MY_FileNamesInformation,
1832 FALSE /*ReturnSingleEntry*/,
1833 NULL /*FileName*/,
1834 pdir->off == ~(size_t)0 /*RestartScan*/);
1835 if (rcNt >= 0 && rcNt != STATUS_PENDING)
1836 {
1837 pdir->cb = Ios.Information;
1838 pdir->off = 0;
1839 }
1840 else if (rcNt == STATUS_NO_MORE_FILES)
1841 errno = 0; /* wrong? */
1842 else
1843 shfile_nt2errno(rcNt);
1844 }
1845
1846 if ( pdir->off != ~(size_t)0
1847 && pdir->off + sizeof(MY_FILE_NAMES_INFORMATION) <= pdir->cb)
1848 {
1849 PMY_FILE_NAMES_INFORMATION pcur = (PMY_FILE_NAMES_INFORMATION)&pdir->buf[pdir->off];
1850 ANSI_STRING astr;
1851 UNICODE_STRING ustr;
1852
1853 astr.Length = astr.MaximumLength = sizeof(pdir->ent.name);
1854 astr.Buffer = &pdir->ent.name[0];
1855
1856 ustr.Length = ustr.MaximumLength = pcur->FileNameLength < ~(USHORT)0 ? (USHORT)pcur->FileNameLength : ~(USHORT)0;
1857 ustr.Buffer = &pcur->FileName[0];
1858
1859 rcNt = g_pfnRtlUnicodeStringToAnsiString(&astr, &ustr, 0/*AllocateDestinationString*/);
1860 if (rcNt < 0)
1861 sprintf(pdir->ent.name, "conversion-failed-%08x-rcNt=%08x-len=%u",
1862 pcur->FileIndex, rcNt, pcur->FileNameLength);
1863 if (pcur->NextEntryOffset)
1864 pdir->off += pcur->NextEntryOffset;
1865 else
1866 pdir->off = pdir->cb;
1867 return &pdir->ent;
1868 }
1869 }
1870 else
1871 errno = EINVAL;
1872 return NULL;
1873#else
1874 struct dirent *pde = readdir((DIR *)pdir);
1875 return pde ? (shdirent *)&pde->d_name[0] : NULL;
1876#endif
1877}
1878
1879void shfile_closedir(struct shdir *pdir)
1880{
1881#if defined(SHFILE_IN_USE) && K_OS == K_OS_WINDOWS
1882 if (pdir)
1883 {
1884 CloseHandle(pdir->native);
1885 pdir->pfdtab = NULL;
1886 pdir->native = INVALID_HANDLE_VALUE;
1887 sh_free(shthread_get_shell(), pdir);
1888 }
1889 else
1890 errno = EINVAL;
1891#else
1892 closedir((DIR *)pdir);
1893#endif
1894}
1895
Note: See TracBrowser for help on using the repository browser.

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