VirtualBox

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

Last change on this file since 2649 was 2647, checked in by bird, 12 years ago

shfile.c: Fixed bug in shfile_movefd that caused sever file descriptor leakage when using redirection.

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Id
File size: 55.8 KB
Line 
1/* $Id: shfile.c 2647 2012-09-09 03:21:35Z 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#if 0 /* Seems to happen for console handles, ignore it. */
794 DWORD err = GetLastError();
795 assert(0);
796#endif
797 }
798 }
799 }
800
801 if (hndls)
802 {
803 for (i = 0; i < 3; i++)
804 {
805 if ( pfdtab->size > i
806 && pfdtab->tab[i].fd == i)
807 hndls[i] = pfdtab->tab[i].native;
808 else
809 hndls[i] = (intptr_t)INVALID_HANDLE_VALUE;
810 TRACE2((NULL, "shfile_fork_win: i=%d size=%d fd=%d native=%d hndls[%d]=%p\n",
811 i, pfdtab->size, pfdtab->tab[i].fd, pfdtab->tab[i].native, i, hndls[i]));
812 }
813 }
814
815 shmtx_leave(&pfdtab->mtx, &tmp);
816}
817
818/**
819 * Helper for sh_execve.
820 *
821 * This is called before and after CreateProcess. On the first call it
822 * will mark the non-close-on-exec handles as inheritable and produce
823 * the startup info for the CRT. On the second call, after CreateProcess,
824 * it will restore the handle inheritability properties.
825 *
826 * @returns Pointer to CRT data if prepare is 1, NULL if prepare is 0.
827 * @param pfdtab The file descriptor table.
828 * @param prepare Which call, 1 if before and 0 if after.
829 * @param sizep Where to store the size of the returned data.
830 * @param hndls Where to store the three standard handles.
831 */
832void *shfile_exec_win(shfdtab *pfdtab, int prepare, unsigned short *sizep, intptr_t *hndls)
833{
834 void *pvRet;
835 shmtxtmp tmp;
836 unsigned count;
837 unsigned i;
838
839 shmtx_enter(&pfdtab->mtx, &tmp);
840 TRACE2((NULL, "shfile_exec_win: prepare=%p\n", prepare));
841
842 count = pfdtab->size < (0x10000-4) / (1 + sizeof(HANDLE))
843 ? pfdtab->size
844 : (0x10000-4) / (1 + sizeof(HANDLE));
845 while (count > 3 && pfdtab->tab[count - 1].fd == -1)
846 count--;
847
848 if (prepare)
849 {
850 size_t cbData = sizeof(int) + count * (1 + sizeof(HANDLE));
851 uint8_t *pbData = sh_malloc(shthread_get_shell(), cbData);
852 uint8_t *paf = pbData + sizeof(int);
853 HANDLE *pah = (HANDLE *)(paf + count);
854
855 *(int *)pbData = count;
856
857 i = count;
858 while (i-- > 0)
859 {
860 if ( pfdtab->tab[i].fd == i
861 && !(pfdtab->tab[i].shflags & SHFILE_FLAGS_CLOSE_ON_EXEC))
862 {
863 HANDLE hFile = (HANDLE)pfdtab->tab[i].native;
864 TRACE2((NULL, " #%d: native=%#x oflags=%#x shflags=%#x\n",
865 i, hFile, pfdtab->tab[i].oflags, pfdtab->tab[i].shflags));
866
867 if (!SetHandleInformation(hFile, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT))
868 {
869#if 0 /* Seems to fail for console handles, ignore. */
870 DWORD err = GetLastError();
871 assert(0);
872#endif
873 }
874 paf[i] = FOPEN;
875 if (pfdtab->tab[i].oflags & _O_APPEND)
876 paf[i] |= FAPPEND;
877 if (pfdtab->tab[i].oflags & _O_TEXT)
878 paf[i] |= FTEXT;
879 switch (pfdtab->tab[i].shflags & SHFILE_FLAGS_TYPE_MASK)
880 {
881 case SHFILE_FLAGS_TTY: paf[i] |= FDEV; break;
882 case SHFILE_FLAGS_PIPE: paf[i] |= FPIPE; break;
883 }
884 pah[i] = hFile;
885 }
886 else
887 {
888 paf[i] = 0;
889 pah[i] = INVALID_HANDLE_VALUE;
890 }
891 }
892
893 for (i = 0; i < 3; i++)
894 {
895 if ( i < count
896 && pfdtab->tab[i].fd == i)
897 hndls[i] = pfdtab->tab[i].native;
898 else
899 hndls[i] = (intptr_t)INVALID_HANDLE_VALUE;
900 TRACE2((NULL, "shfile_exec_win: i=%d count=%d fd=%d native=%d hndls[%d]=\n",
901 i, count, pfdtab->tab[i].fd, pfdtab->tab[i].native, i, hndls[i]));
902 }
903
904 *sizep = (unsigned short)cbData;
905 pvRet = pbData;
906 }
907 else
908 {
909 assert(!hndls);
910 assert(!sizep);
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 = (HANDLE)pfdtab->tab[i].native;
918 if (!SetHandleInformation(hFile, HANDLE_FLAG_INHERIT, 0))
919 {
920 DWORD err = GetLastError();
921 assert(0);
922 }
923 }
924 }
925 pvRet = NULL;
926 }
927
928 shmtx_leave(&pfdtab->mtx, &tmp);
929 return pvRet;
930}
931
932#endif /* K_OS_WINDOWS */
933
934#if K_OS != K_OS_WINDOWS
935/**
936 * Prepare file handles for inherting before a execve call.
937 *
938 * This is only used in the normal mode, so we've forked and need not worry
939 * about cleaning anything up after us. Nor do we need think about locking.
940 *
941 * @returns 0 on success, -1 on failure.
942 */
943int shfile_exec_unix(shfdtab *pfdtab)
944{
945 int rc = 0;
946# ifdef SHFILE_IN_USE
947 unsigned fd;
948
949 for (fd = 0; fd < pfdtab->size; fd++)
950 {
951 if ( pfdtab->tab[fd].fd != -1
952 && !(pfdtab->tab[fd].shflags & SHFILE_FLAGS_CLOSE_ON_EXEC) )
953 {
954 TRACE2((NULL, "shfile_exec_unix: %d => %d\n", pfdtab->tab[fd].native, fd));
955 if (dup2(pfdtab->tab[fd].native, fd) < 0)
956 {
957 /* fatal_error(NULL, "shfile_exec_unix: failed to move %d to %d", pfdtab->tab[fd].fd, fd); */
958 rc = -1;
959 }
960 }
961 }
962# endif
963 return rc;
964}
965#endif /* !K_OS_WINDOWS */
966
967/**
968 * open().
969 */
970int shfile_open(shfdtab *pfdtab, const char *name, unsigned flags, mode_t mode)
971{
972 int fd;
973#ifdef SHFILE_IN_USE
974 char absname[SHFILE_MAX_PATH];
975# if K_OS == K_OS_WINDOWS
976 HANDLE hFile;
977 DWORD dwDesiredAccess;
978 DWORD dwShareMode;
979 DWORD dwCreationDisposition;
980 DWORD dwFlagsAndAttributes;
981 SECURITY_ATTRIBUTES SecurityAttributes;
982
983# ifndef _O_ACCMODE
984# define _O_ACCMODE (_O_RDONLY|_O_WRONLY|_O_RDWR)
985# endif
986 switch (flags & (_O_ACCMODE | _O_APPEND))
987 {
988 case _O_RDONLY: dwDesiredAccess = GENERIC_READ; break;
989 case _O_RDONLY | _O_APPEND: dwDesiredAccess = GENERIC_READ; break;
990 case _O_WRONLY: dwDesiredAccess = GENERIC_WRITE; break;
991 case _O_WRONLY | _O_APPEND: dwDesiredAccess = (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA); break;
992 case _O_RDWR: dwDesiredAccess = GENERIC_READ | GENERIC_WRITE; break;
993 case _O_RDWR | _O_APPEND: dwDesiredAccess = GENERIC_READ | (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA); break;
994
995 default:
996 RETURN_ERROR(-1, EINVAL, "invalid mode");
997 }
998
999 dwShareMode = FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE;
1000
1001 SecurityAttributes.nLength = sizeof(SecurityAttributes);
1002 SecurityAttributes.lpSecurityDescriptor = NULL;
1003 SecurityAttributes.bInheritHandle = FALSE;
1004
1005 if (flags & _O_CREAT)
1006 {
1007 if ((flags & (_O_EXCL | _O_TRUNC)) == (_O_EXCL | _O_TRUNC))
1008 RETURN_ERROR(-1, EINVAL, "_O_EXCL | _O_TRUNC");
1009
1010 if (flags & _O_TRUNC)
1011 dwCreationDisposition = CREATE_ALWAYS; /* not 100%, but close enough */
1012 else if (flags & _O_EXCL)
1013 dwCreationDisposition = CREATE_NEW;
1014 else
1015 dwCreationDisposition = OPEN_ALWAYS;
1016 }
1017 else if (flags & _O_TRUNC)
1018 dwCreationDisposition = TRUNCATE_EXISTING;
1019 else
1020 dwCreationDisposition = OPEN_EXISTING;
1021
1022 if (!(flags & _O_CREAT) || (mode & 0222))
1023 dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
1024 else
1025 dwFlagsAndAttributes = FILE_ATTRIBUTE_READONLY;
1026
1027 fd = shfile_make_path(pfdtab, name, &absname[0]);
1028 if (!fd)
1029 {
1030 SetLastError(0);
1031 hFile = CreateFileA(absname,
1032 dwDesiredAccess,
1033 dwShareMode,
1034 &SecurityAttributes,
1035 dwCreationDisposition,
1036 dwFlagsAndAttributes,
1037 NULL /* hTemplateFile */);
1038 if (hFile != INVALID_HANDLE_VALUE)
1039 fd = shfile_insert(pfdtab, (intptr_t)hFile, flags, 0, -1, "shfile_open");
1040 else
1041 fd = shfile_dos2errno(GetLastError());
1042 }
1043
1044# else /* K_OS != K_OS_WINDOWS */
1045 fd = shfile_make_path(pfdtab, name, &absname[0]);
1046 if (!fd)
1047 {
1048 fd = open(absname, flags, mode);
1049 if (fd != -1)
1050 fd = shfile_copy_insert_and_close(pfdtab, &fd, flags, 0, -1, "shfile_open");
1051 }
1052
1053# endif /* K_OS != K_OS_WINDOWS */
1054
1055#else
1056 fd = open(name, flags, mode);
1057#endif
1058
1059 TRACE2((NULL, "shfile_open(%p:{%s}, %#x, 0%o) -> %d [%d]\n", name, name, flags, mode, fd, errno));
1060 return fd;
1061}
1062
1063int shfile_pipe(shfdtab *pfdtab, int fds[2])
1064{
1065 int rc = -1;
1066#ifdef SHFILE_IN_USE
1067# if K_OS == K_OS_WINDOWS
1068 HANDLE hRead = INVALID_HANDLE_VALUE;
1069 HANDLE hWrite = INVALID_HANDLE_VALUE;
1070 SECURITY_ATTRIBUTES SecurityAttributes;
1071
1072 SecurityAttributes.nLength = sizeof(SecurityAttributes);
1073 SecurityAttributes.lpSecurityDescriptor = NULL;
1074 SecurityAttributes.bInheritHandle = FALSE;
1075
1076 fds[1] = fds[0] = -1;
1077 if (CreatePipe(&hRead, &hWrite, &SecurityAttributes, 4096))
1078 {
1079 fds[0] = shfile_insert(pfdtab, (intptr_t)hRead, O_RDONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
1080 if (fds[0] != -1)
1081 {
1082 fds[1] = shfile_insert(pfdtab, (intptr_t)hWrite, O_WRONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
1083 if (fds[1] != -1)
1084 rc = 0;
1085 }
1086
1087# else
1088 int native_fds[2];
1089
1090 fds[1] = fds[0] = -1;
1091 if (!pipe(native_fds))
1092 {
1093 fds[0] = shfile_copy_insert_and_close(pfdtab, &native_fds[0], O_RDONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
1094 if (fds[0] != -1)
1095 {
1096 fds[1] = shfile_copy_insert_and_close(pfdtab, &native_fds[1], O_WRONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
1097 if (fds[1] != -1)
1098 rc = 0;
1099 }
1100# endif
1101 if (fds[1] == -1)
1102 {
1103 int s = errno;
1104 if (fds[0] != -1)
1105 {
1106 shmtxtmp tmp;
1107 shmtx_enter(&pfdtab->mtx, &tmp);
1108 rc = fds[0];
1109 pfdtab->tab[rc].fd = -1;
1110 pfdtab->tab[rc].oflags = 0;
1111 pfdtab->tab[rc].shflags = 0;
1112 pfdtab->tab[rc].native = -1;
1113 shmtx_leave(&pfdtab->mtx, &tmp);
1114 }
1115
1116# if K_OS == K_OS_WINDOWS
1117 CloseHandle(hRead);
1118 CloseHandle(hWrite);
1119# else
1120 close(native_fds[0]);
1121 close(native_fds[1]);
1122# endif
1123 fds[0] = fds[1] = -1;
1124 errno = s;
1125 rc = -1;
1126 }
1127 }
1128 else
1129 {
1130# if K_OS == K_OS_WINDOWS
1131 errno = shfile_dos2errno(GetLastError());
1132# endif
1133 rc = -1;
1134 }
1135
1136#else
1137 rc = pipe(fds);
1138#endif
1139
1140 TRACE2((NULL, "shfile_pipe() -> %d{%d,%d} [%d]\n", rc, fds[0], fds[1], errno));
1141 return rc;
1142}
1143
1144/**
1145 * dup().
1146 */
1147int shfile_dup(shfdtab *pfdtab, int fd)
1148{
1149 return shfile_fcntl(pfdtab,fd, F_DUPFD, 0);
1150}
1151
1152/**
1153 * Move the file descriptor, closing any existing descriptor at @a fdto.
1154 *
1155 * @returns fdto on success, -1 and errno on failure.
1156 * @param pfdtab The file descriptor table.
1157 * @param fdfrom The descriptor to move.
1158 * @param fdto Where to move it.
1159 */
1160int shfile_movefd(shfdtab *pfdtab, int fdfrom, int fdto)
1161{
1162#ifdef SHFILE_IN_USE
1163 int rc;
1164 shmtxtmp tmp;
1165 shfile *file = shfile_get(pfdtab, fdfrom, &tmp);
1166 if (file)
1167 {
1168 /* prepare the new entry */
1169 if (fdto >= (int)pfdtab->size)
1170 shfile_grow_tab_locked(pfdtab, fdto);
1171 if (fdto < (int)pfdtab->size)
1172 {
1173 if (pfdtab->tab[fdto].fd != -1)
1174 shfile_native_close(pfdtab->tab[fdto].native, pfdtab->tab[fdto].oflags);
1175
1176 /* setup the target. */
1177 pfdtab->tab[fdto].fd = fdto;
1178 pfdtab->tab[fdto].oflags = file->oflags;
1179 pfdtab->tab[fdto].shflags = file->shflags;
1180 pfdtab->tab[fdto].native = file->native;
1181
1182 /* close the source. */
1183 file->fd = -1;
1184 file->oflags = 0;
1185 file->shflags = 0;
1186 file->native = -1;
1187
1188 rc = fdto;
1189 }
1190 else
1191 {
1192 errno = EMFILE;
1193 rc = -1;
1194 }
1195
1196 shfile_put(pfdtab, file, &tmp);
1197 }
1198 else
1199 rc = -1;
1200 return rc;
1201
1202#else
1203 int fdnew = dup2(fdfrom, fdto);
1204 if (fdnew >= 0)
1205 close(fdfrom);
1206 return fdnew;
1207#endif
1208}
1209
1210/**
1211 * Move the file descriptor to somewhere at @a fdMin or above.
1212 *
1213 * @returns the new file descriptor success, -1 and errno on failure.
1214 * @param pfdtab The file descriptor table.
1215 * @param fdfrom The descriptor to move.
1216 * @param fdMin The minimum descriptor.
1217 */
1218int shfile_movefd_above(shfdtab *pfdtab, int fdfrom, int fdMin)
1219{
1220#ifdef SHFILE_IN_USE
1221 int fdto;
1222 shmtxtmp tmp;
1223 shfile *file = shfile_get(pfdtab, fdfrom, &tmp);
1224 if (file)
1225 {
1226 /* find a new place */
1227 int i;
1228 fdto = -1;
1229 for (i = fdMin; (unsigned)i < pfdtab->size; i++)
1230 if (pfdtab->tab[i].fd == -1)
1231 {
1232 fdto = i;
1233 break;
1234 }
1235 if (fdto == -1)
1236 fdto = shfile_grow_tab_locked(pfdtab, fdMin);
1237 if (fdto != -1)
1238 {
1239 /* setup the target. */
1240 pfdtab->tab[fdto].fd = fdto;
1241 pfdtab->tab[fdto].oflags = file->oflags;
1242 pfdtab->tab[fdto].shflags = file->shflags;
1243 pfdtab->tab[fdto].native = file->native;
1244
1245 /* close the source. */
1246 file->fd = -1;
1247 file->oflags = 0;
1248 file->shflags = 0;
1249 file->native = -1;
1250 }
1251 else
1252 {
1253 errno = EMFILE;
1254 fdto = -1;
1255 }
1256
1257 shfile_put(pfdtab, file, &tmp);
1258 }
1259 else
1260 fdto = -1;
1261 return fdto;
1262
1263#else
1264 int fdnew = fcntl(fdfrom, F_DUPFD, fdMin);
1265 if (fdnew >= 0)
1266 close(fdfrom);
1267 return fdnew;
1268#endif
1269}
1270
1271/**
1272 * close().
1273 */
1274int shfile_close(shfdtab *pfdtab, unsigned fd)
1275{
1276 int rc;
1277#ifdef SHFILE_IN_USE
1278 shmtxtmp tmp;
1279 shfile *file = shfile_get(pfdtab, fd, &tmp);
1280 if (file)
1281 {
1282 shfile_native_close(file->native, file->oflags);
1283
1284 file->fd = -1;
1285 file->oflags = 0;
1286 file->shflags = 0;
1287 file->native = -1;
1288
1289 shfile_put(pfdtab, file, &tmp);
1290 rc = 0;
1291 }
1292 else
1293 rc = -1;
1294
1295#else
1296 rc = close(fd);
1297#endif
1298
1299 TRACE2((NULL, "shfile_close(%d) -> %d [%d]\n", fd, rc, errno));
1300 return rc;
1301}
1302
1303/**
1304 * read().
1305 */
1306long shfile_read(shfdtab *pfdtab, int fd, void *buf, size_t len)
1307{
1308 long rc;
1309#ifdef SHFILE_IN_USE
1310 shmtxtmp tmp;
1311 shfile *file = shfile_get(pfdtab, fd, &tmp);
1312 if (file)
1313 {
1314# if K_OS == K_OS_WINDOWS
1315 DWORD dwRead = 0;
1316 if (ReadFile((HANDLE)file->native, buf, (DWORD)len, &dwRead, NULL))
1317 rc = dwRead;
1318 else
1319 rc = shfile_dos2errno(GetLastError());
1320# else
1321 rc = read(file->native, buf, len);
1322# endif
1323
1324 shfile_put(pfdtab, file, &tmp);
1325 }
1326 else
1327 rc = -1;
1328
1329#else
1330 rc = read(fd, buf, len);
1331#endif
1332 return rc;
1333}
1334
1335/**
1336 * write().
1337 */
1338long shfile_write(shfdtab *pfdtab, int fd, const void *buf, size_t len)
1339{
1340 long rc;
1341#ifdef SHFILE_IN_USE
1342 shmtxtmp tmp;
1343 shfile *file = shfile_get(pfdtab, fd, &tmp);
1344 if (file)
1345 {
1346# if K_OS == K_OS_WINDOWS
1347 DWORD dwWritten = 0;
1348 if (WriteFile((HANDLE)file->native, buf, (DWORD)len, &dwWritten, NULL))
1349 rc = dwWritten;
1350 else
1351 rc = shfile_dos2errno(GetLastError());
1352# else
1353 rc = write(file->native, buf, len);
1354# endif
1355
1356 shfile_put(pfdtab, file, &tmp);
1357 }
1358 else
1359 rc = -1;
1360
1361#else
1362 if (fd != shthread_get_shell()->tracefd)
1363 {
1364 struct stat s;
1365 int x;
1366 x = fstat(fd, &s);
1367 TRACE2((NULL, "shfile_write(%d) - %lu bytes (%d) - pos %lu - before; %o\n",
1368 fd, (long)s.st_size, x, (long)lseek(fd, 0, SEEK_CUR), s.st_mode ));
1369 errno = 0;
1370 }
1371
1372 rc = write(fd, buf, len);
1373#endif
1374
1375#ifdef DEBUG
1376 if (fd != shthread_get_shell()->tracefd)
1377 {
1378 struct stat s;
1379 int x;
1380 TRACE2((NULL, "shfile_write(%d,,%d) -> %d [%d]\n", fd, len, rc, errno));
1381 x=fstat(fd, &s);
1382 TRACE2((NULL, "shfile_write(%d) - %lu bytes (%d) - pos %lu - after\n", fd, (long)s.st_size, x, (long)lseek(fd, 0, SEEK_CUR) ));
1383 }
1384#endif
1385 return rc;
1386}
1387
1388/**
1389 * lseek().
1390 */
1391long shfile_lseek(shfdtab *pfdtab, int fd, long off, int whench)
1392{
1393 long rc;
1394#ifdef SHFILE_IN_USE
1395 shmtxtmp tmp;
1396 shfile *file = shfile_get(pfdtab, fd, &tmp);
1397 if (file)
1398 {
1399# if K_OS == K_OS_WINDOWS
1400 assert(SEEK_SET == FILE_BEGIN);
1401 assert(SEEK_CUR == FILE_CURRENT);
1402 assert(SEEK_END == FILE_END);
1403 rc = SetFilePointer((HANDLE)file->native, off, NULL, whench);
1404 if (rc == INVALID_SET_FILE_POINTER)
1405 rc = shfile_dos2errno(GetLastError());
1406# else
1407 rc = lseek(file->native, off, whench);
1408# endif
1409
1410 shfile_put(pfdtab, file, &tmp);
1411 }
1412 else
1413 rc = -1;
1414
1415#else
1416 rc = lseek(fd, off, whench);
1417#endif
1418
1419 return rc;
1420}
1421
1422int shfile_fcntl(shfdtab *pfdtab, int fd, int cmd, int arg)
1423{
1424 int rc;
1425#ifdef SHFILE_IN_USE
1426 shmtxtmp tmp;
1427 shfile *file = shfile_get(pfdtab, fd, &tmp);
1428 if (file)
1429 {
1430 switch (cmd)
1431 {
1432 case F_GETFL:
1433 rc = file->oflags;
1434 break;
1435
1436 case F_SETFL:
1437 {
1438 unsigned mask = O_NONBLOCK | O_APPEND | O_BINARY | O_TEXT;
1439# ifdef O_DIRECT
1440 mask |= O_DIRECT;
1441# endif
1442# ifdef O_ASYNC
1443 mask |= O_ASYNC;
1444# endif
1445# ifdef O_SYNC
1446 mask |= O_SYNC;
1447# endif
1448 if ((file->oflags & mask) == (arg & mask))
1449 rc = 0;
1450 else
1451 {
1452# if K_OS == K_OS_WINDOWS
1453 assert(0);
1454 errno = EINVAL;
1455 rc = -1;
1456# else
1457 rc = fcntl(file->native, F_SETFL, arg);
1458 if (rc != -1)
1459 file->oflags = (file->oflags & ~mask) | (arg & mask);
1460# endif
1461 }
1462 break;
1463 }
1464
1465 case F_DUPFD:
1466 {
1467# if K_OS == K_OS_WINDOWS
1468 HANDLE hNew = INVALID_HANDLE_VALUE;
1469 if (DuplicateHandle(GetCurrentProcess(),
1470 (HANDLE)file->native,
1471 GetCurrentProcess(),
1472 &hNew,
1473 0,
1474 FALSE /* bInheritHandle */,
1475 DUPLICATE_SAME_ACCESS))
1476 rc = shfile_insert(pfdtab, (intptr_t)hNew, file->oflags, file->shflags, arg, "shfile_fcntl");
1477 else
1478 rc = shfile_dos2errno(GetLastError());
1479# else
1480 int nativeNew = fcntl(file->native, F_DUPFD, SHFILE_UNIX_MIN_FD);
1481 if (nativeNew != -1)
1482 rc = shfile_insert(pfdtab, nativeNew, file->oflags, file->shflags, arg, "shfile_fcntl");
1483 else
1484 rc = -1;
1485# endif
1486 break;
1487 }
1488
1489 default:
1490 errno = -EINVAL;
1491 rc = -1;
1492 break;
1493 }
1494
1495 shfile_put(pfdtab, file, &tmp);
1496 }
1497 else
1498 rc = -1;
1499
1500#else
1501 rc = fcntl(fd, cmd, arg);
1502#endif
1503
1504 switch (cmd)
1505 {
1506 case F_GETFL: TRACE2((NULL, "shfile_fcntl(%d,F_GETFL,ignored=%d) -> %d [%d]\n", fd, arg, rc, errno)); break;
1507 case F_SETFL: TRACE2((NULL, "shfile_fcntl(%d,F_SETFL,newflags=%#x) -> %d [%d]\n", fd, arg, rc, errno)); break;
1508 case F_DUPFD: TRACE2((NULL, "shfile_fcntl(%d,F_DUPFD,minfd=%d) -> %d [%d]\n", fd, arg, rc, errno)); break;
1509 default: TRACE2((NULL, "shfile_fcntl(%d,%d,%d) -> %d [%d]\n", fd, cmd, arg, rc, errno)); break;
1510 }
1511 return rc;
1512}
1513
1514int shfile_stat(shfdtab *pfdtab, const char *path, struct stat *pst)
1515{
1516#ifdef SHFILE_IN_USE
1517 char abspath[SHFILE_MAX_PATH];
1518 int rc;
1519 rc = shfile_make_path(pfdtab, path, &abspath[0]);
1520 if (!rc)
1521 {
1522# if K_OS == K_OS_WINDOWS
1523 rc = stat(abspath, pst); /** @todo re-implement stat. */
1524# else
1525 rc = stat(abspath, pst);
1526# endif
1527 }
1528 TRACE2((NULL, "shfile_stat(,%s,) -> %d [%d]\n", path, rc, errno));
1529 return rc;
1530#else
1531 return stat(path, pst);
1532#endif
1533}
1534
1535int shfile_lstat(shfdtab *pfdtab, const char *path, struct stat *pst)
1536{
1537 int rc;
1538#ifdef SHFILE_IN_USE
1539 char abspath[SHFILE_MAX_PATH];
1540
1541 rc = shfile_make_path(pfdtab, path, &abspath[0]);
1542 if (!rc)
1543 {
1544# if K_OS == K_OS_WINDOWS
1545 rc = stat(abspath, pst); /** @todo implement lstat. */
1546# else
1547 rc = lstat(abspath, pst);
1548# endif
1549 }
1550#else
1551 rc = stat(path, pst);
1552#endif
1553 TRACE2((NULL, "shfile_stat(,%s,) -> %d [%d]\n", path, rc, errno));
1554 return rc;
1555}
1556
1557/**
1558 * chdir().
1559 */
1560int shfile_chdir(shfdtab *pfdtab, const char *path)
1561{
1562 int rc;
1563#ifdef SHFILE_IN_USE
1564 shinstance *psh = shthread_get_shell();
1565 char abspath[SHFILE_MAX_PATH];
1566
1567 rc = shfile_make_path(pfdtab, path, &abspath[0]);
1568 if (!rc)
1569 {
1570 char *abspath_copy = sh_strdup(psh, abspath);
1571 char *free_me = abspath_copy;
1572 rc = chdir(path);
1573 if (!rc)
1574 {
1575 shmtxtmp tmp;
1576 shmtx_enter(&pfdtab->mtx, &tmp);
1577
1578 free_me = pfdtab->cwd;
1579 pfdtab->cwd = abspath_copy;
1580
1581 shmtx_leave(&pfdtab->mtx, &tmp);
1582 }
1583 sh_free(psh, free_me);
1584 }
1585 else
1586 rc = -1;
1587#else
1588 rc = chdir(path);
1589#endif
1590
1591 TRACE2((NULL, "shfile_chdir(,%s) -> %d [%d]\n", path, rc, errno));
1592 return rc;
1593}
1594
1595/**
1596 * getcwd().
1597 */
1598char *shfile_getcwd(shfdtab *pfdtab, char *buf, int size)
1599{
1600 char *ret;
1601#ifdef SHFILE_IN_USE
1602
1603 ret = NULL;
1604 if (buf && !size)
1605 errno = -EINVAL;
1606 else
1607 {
1608 size_t cwd_size;
1609 shmtxtmp tmp;
1610 shmtx_enter(&pfdtab->mtx, &tmp);
1611
1612 cwd_size = strlen(pfdtab->cwd) + 1;
1613 if (buf)
1614 {
1615 if (cwd_size <= (size_t)size)
1616 ret = memcpy(buf, pfdtab->cwd, cwd_size);
1617 else
1618 errno = ERANGE;
1619 }
1620 else
1621 {
1622 if ((size_t)size < cwd_size)
1623 size = (int)cwd_size;
1624 ret = sh_malloc(shthread_get_shell(), size);
1625 if (ret)
1626 ret = memcpy(ret, pfdtab->cwd, cwd_size);
1627 else
1628 errno = ENOMEM;
1629 }
1630
1631 shmtx_leave(&pfdtab->mtx, &tmp);
1632 }
1633#else
1634 ret = getcwd(buf, size);
1635#endif
1636
1637 TRACE2((NULL, "shfile_getcwd(,%p,%d) -> %s [%d]\n", buf, size, ret, errno));
1638 return ret;
1639}
1640
1641/**
1642 * access().
1643 */
1644int shfile_access(shfdtab *pfdtab, const char *path, int type)
1645{
1646 int rc;
1647#ifdef SHFILE_IN_USE
1648 char abspath[SHFILE_MAX_PATH];
1649
1650 rc = shfile_make_path(pfdtab, path, &abspath[0]);
1651 if (!rc)
1652 {
1653# ifdef _MSC_VER
1654 if (type & X_OK)
1655 type = (type & ~X_OK) | R_OK;
1656# endif
1657 rc = access(abspath, type);
1658 }
1659#else
1660# ifdef _MSC_VER
1661 if (type & X_OK)
1662 type = (type & ~X_OK) | R_OK;
1663# endif
1664 rc = access(path, type);
1665#endif
1666
1667 TRACE2((NULL, "shfile_access(,%s,%#x) -> %d [%d]\n", path, type, rc, errno));
1668 return rc;
1669}
1670
1671/**
1672 * isatty()
1673 */
1674int shfile_isatty(shfdtab *pfdtab, int fd)
1675{
1676 int rc;
1677#ifdef SHFILE_IN_USE
1678 shmtxtmp tmp;
1679 shfile *file = shfile_get(pfdtab, fd, &tmp);
1680 if (file)
1681 {
1682# if K_OS == K_OS_WINDOWS
1683 rc = (file->shflags & SHFILE_FLAGS_TYPE_MASK) == SHFILE_FLAGS_TTY;
1684# else
1685 rc = isatty(file->native);
1686# endif
1687 shfile_put(pfdtab, file, &tmp);
1688 }
1689 else
1690 rc = 0;
1691#else
1692 rc = isatty(fd);
1693#endif
1694
1695 TRACE2((NULL, "isatty(%d) -> %d [%d]\n", fd, rc, errno));
1696 return rc;
1697}
1698
1699/**
1700 * fcntl F_SETFD / FD_CLOEXEC.
1701 */
1702int shfile_cloexec(shfdtab *pfdtab, int fd, int closeit)
1703{
1704 int rc;
1705#ifdef SHFILE_IN_USE
1706 shmtxtmp tmp;
1707 shfile *file = shfile_get(pfdtab, fd, &tmp);
1708 if (file)
1709 {
1710 if (closeit)
1711 file->shflags |= SHFILE_FLAGS_CLOSE_ON_EXEC;
1712 else
1713 file->shflags &= ~SHFILE_FLAGS_CLOSE_ON_EXEC;
1714 shfile_put(pfdtab, file, &tmp);
1715 rc = 0;
1716 }
1717 else
1718 rc = -1;
1719#else
1720 rc = fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0)
1721 | (closeit ? FD_CLOEXEC : 0));
1722#endif
1723
1724 TRACE2((NULL, "shfile_cloexec(%d, %d) -> %d [%d]\n", fd, closeit, rc, errno));
1725 return rc;
1726}
1727
1728
1729int shfile_ioctl(shfdtab *pfdtab, int fd, unsigned long request, void *buf)
1730{
1731 int rc;
1732#ifdef SHFILE_IN_USE
1733 shmtxtmp tmp;
1734 shfile *file = shfile_get(pfdtab, fd, &tmp);
1735 if (file)
1736 {
1737# if K_OS == K_OS_WINDOWS
1738 rc = -1;
1739 errno = ENOSYS;
1740# else
1741 rc = ioctl(file->native, request, buf);
1742# endif
1743 shfile_put(pfdtab, file, &tmp);
1744 }
1745 else
1746 rc = -1;
1747#else
1748 rc = ioctl(fd, request, buf);
1749#endif
1750
1751 TRACE2((NULL, "ioctl(%d, %#x, %p) -> %d\n", fd, request, buf, rc));
1752 return rc;
1753}
1754
1755
1756mode_t shfile_get_umask(shfdtab *pfdtab)
1757{
1758 /** @todo */
1759 return 022;
1760}
1761
1762void shfile_set_umask(shfdtab *pfdtab, mode_t mask)
1763{
1764 /** @todo */
1765 (void)mask;
1766}
1767
1768
1769
1770shdir *shfile_opendir(shfdtab *pfdtab, const char *dir)
1771{
1772#if defined(SHFILE_IN_USE) && K_OS == K_OS_WINDOWS
1773 shdir *pdir = NULL;
1774
1775 if (g_pfnNtQueryDirectoryFile)
1776 {
1777 char abspath[SHFILE_MAX_PATH];
1778 if (shfile_make_path(pfdtab, dir, &abspath[0]) == 0)
1779 {
1780 HANDLE hFile;
1781 SECURITY_ATTRIBUTES SecurityAttributes;
1782
1783 SecurityAttributes.nLength = sizeof(SecurityAttributes);
1784 SecurityAttributes.lpSecurityDescriptor = NULL;
1785 SecurityAttributes.bInheritHandle = FALSE;
1786
1787 hFile = CreateFileA(abspath,
1788 GENERIC_READ,
1789 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
1790 &SecurityAttributes,
1791 OPEN_EXISTING,
1792 FILE_ATTRIBUTE_DIRECTORY | FILE_FLAG_BACKUP_SEMANTICS,
1793 NULL /* hTemplateFile */);
1794 if (hFile != INVALID_HANDLE_VALUE)
1795 {
1796 pdir = (shdir *)sh_malloc(shthread_get_shell(), sizeof(*pdir));
1797 if (pdir)
1798 {
1799 pdir->pfdtab = pfdtab;
1800 pdir->native = hFile;
1801 pdir->off = ~(size_t)0;
1802 }
1803 else
1804 CloseHandle(hFile);
1805 }
1806 else
1807 shfile_dos2errno(GetLastError());
1808 }
1809 }
1810 else
1811 errno = ENOSYS;
1812 return pdir;
1813#else
1814 return (shdir *)opendir(dir);
1815#endif
1816}
1817
1818shdirent *shfile_readdir(struct shdir *pdir)
1819{
1820#if defined(SHFILE_IN_USE) && K_OS == K_OS_WINDOWS
1821 if (pdir)
1822 {
1823 NTSTATUS rcNt;
1824
1825 if ( pdir->off == ~(size_t)0
1826 || pdir->off + sizeof(MY_FILE_NAMES_INFORMATION) >= pdir->cb)
1827 {
1828 MY_IO_STATUS_BLOCK Ios;
1829
1830 memset(&Ios, 0, sizeof(Ios));
1831 rcNt = g_pfnNtQueryDirectoryFile(pdir->native,
1832 NULL /*Event*/,
1833 NULL /*ApcRoutine*/,
1834 NULL /*ApcContext*/,
1835 &Ios,
1836 &pdir->buf[0],
1837 sizeof(pdir->buf),
1838 MY_FileNamesInformation,
1839 FALSE /*ReturnSingleEntry*/,
1840 NULL /*FileName*/,
1841 pdir->off == ~(size_t)0 /*RestartScan*/);
1842 if (rcNt >= 0 && rcNt != STATUS_PENDING)
1843 {
1844 pdir->cb = Ios.Information;
1845 pdir->off = 0;
1846 }
1847 else if (rcNt == STATUS_NO_MORE_FILES)
1848 errno = 0; /* wrong? */
1849 else
1850 shfile_nt2errno(rcNt);
1851 }
1852
1853 if ( pdir->off != ~(size_t)0
1854 && pdir->off + sizeof(MY_FILE_NAMES_INFORMATION) <= pdir->cb)
1855 {
1856 PMY_FILE_NAMES_INFORMATION pcur = (PMY_FILE_NAMES_INFORMATION)&pdir->buf[pdir->off];
1857 ANSI_STRING astr;
1858 UNICODE_STRING ustr;
1859
1860 astr.Length = astr.MaximumLength = sizeof(pdir->ent.name);
1861 astr.Buffer = &pdir->ent.name[0];
1862
1863 ustr.Length = ustr.MaximumLength = pcur->FileNameLength < ~(USHORT)0 ? (USHORT)pcur->FileNameLength : ~(USHORT)0;
1864 ustr.Buffer = &pcur->FileName[0];
1865
1866 rcNt = g_pfnRtlUnicodeStringToAnsiString(&astr, &ustr, 0/*AllocateDestinationString*/);
1867 if (rcNt < 0)
1868 sprintf(pdir->ent.name, "conversion-failed-%08x-rcNt=%08x-len=%u",
1869 pcur->FileIndex, rcNt, pcur->FileNameLength);
1870 if (pcur->NextEntryOffset)
1871 pdir->off += pcur->NextEntryOffset;
1872 else
1873 pdir->off = pdir->cb;
1874 return &pdir->ent;
1875 }
1876 }
1877 else
1878 errno = EINVAL;
1879 return NULL;
1880#else
1881 struct dirent *pde = readdir((DIR *)pdir);
1882 return pde ? (shdirent *)&pde->d_name[0] : NULL;
1883#endif
1884}
1885
1886void shfile_closedir(struct shdir *pdir)
1887{
1888#if defined(SHFILE_IN_USE) && K_OS == K_OS_WINDOWS
1889 if (pdir)
1890 {
1891 CloseHandle(pdir->native);
1892 pdir->pfdtab = NULL;
1893 pdir->native = INVALID_HANDLE_VALUE;
1894 sh_free(shthread_get_shell(), pdir);
1895 }
1896 else
1897 errno = EINVAL;
1898#else
1899 closedir((DIR *)pdir);
1900#endif
1901}
1902
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