source: trunk/src/kash/shfile.c@ 2650

Last change on this file since 2650 was 2650, checked in by bird, 13 years ago

kash/shfile.c: Fixed console inherit proble on windows. Fixed CWD slashes on windows and OS/2.

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