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

Last change on this file since 3458 was 3458, checked in by bird, 5 years ago

kash: Use reference counting of parser output in threaded-mode.

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