VirtualBox

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

Last change on this file since 3364 was 3240, checked in by bird, 6 years ago

kash: GCC warnings.

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