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

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

kash: when duplicateing a fdtab, don't heed close-on-exec on windows or in non-forked mode. Close files in sh_execve before waiting, but leave the tracefd open.

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Id
File size: 64.4 KB
Line 
1/* $Id: shfile.c 3444 2020-09-10 14:08:18Z 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)
924{
925 if (!pfdtab)
926 return;
927
928 if (pfdtab->tab)
929 {
930 unsigned left = pfdtab->size;
931 struct shfile *pfd = pfdtab->tab;
932 while (left-- > 0)
933 {
934 if (pfd->fd != -1)
935 {
936#if K_OS == K_OS_WINDOWS
937 BOOL rc = CloseHandle((HANDLE)pfd->native);
938 assert(rc == TRUE); K_NOREF(rc);
939#else
940 int rc = close((int)pfd->native);
941 assert(rc == 0); K_NOREF(rc);
942#endif
943 pfd->fd = -1;
944 pfd->native = -1;
945 }
946 pfd++;
947 }
948
949 sh_free(NULL, pfdtab->tab);
950 pfdtab->tab = NULL;
951 }
952
953 shmtx_delete(&pfdtab->mtx);
954
955 sh_free(NULL, pfdtab->cwd);
956 pfdtab->cwd = NULL;
957}
958
959#if K_OS == K_OS_WINDOWS && defined(SHFILE_IN_USE)
960
961/**
962 * Changes the inheritability of a file descriptor, taking console handles into
963 * account.
964 *
965 * @note This MAY change the native handle for the entry.
966 *
967 * @returns The native handle.
968 * @param pfd The file descriptor to change.
969 * @param set If set, make child processes inherit the handle, if clear
970 * make them not inherit it.
971 */
972static HANDLE shfile_set_inherit_win(shfile *pfd, int set)
973{
974 HANDLE hFile = (HANDLE)pfd->native;
975 if (!SetHandleInformation(hFile, HANDLE_FLAG_INHERIT, set ? HANDLE_FLAG_INHERIT : 0))
976 {
977 /* SetHandleInformation doesn't work for console handles,
978 so we have to duplicate the handle to change the
979 inheritability. */
980 DWORD err = GetLastError();
981 if ( err == ERROR_INVALID_PARAMETER
982 && DuplicateHandle(GetCurrentProcess(),
983 hFile,
984 GetCurrentProcess(),
985 &hFile,
986 0,
987 set ? TRUE : FALSE /* bInheritHandle */,
988 DUPLICATE_SAME_ACCESS))
989 {
990 TRACE2((NULL, "shfile_set_inherit_win: %p -> %p (set=%d)\n", pfd->native, hFile, set));
991 if (!CloseHandle((HANDLE)pfd->native))
992 assert(0);
993 pfd->native = (intptr_t)hFile;
994 }
995 else
996 {
997 err = GetLastError();
998 assert(0);
999 hFile = (HANDLE)pfd->native;
1000 }
1001 }
1002 return hFile;
1003}
1004
1005# ifdef SH_FORKED_MODE
1006/**
1007 * Helper for shfork.
1008 *
1009 * @param pfdtab The file descriptor table.
1010 * @param set Whether to make all handles inheritable (1) or
1011 * to restore them to the rigth state (0).
1012 * @param hndls Where to store the three standard handles.
1013 */
1014void shfile_fork_win(shfdtab *pfdtab, int set, intptr_t *hndls)
1015{
1016 shmtxtmp tmp;
1017 unsigned i;
1018
1019 shmtx_enter(&pfdtab->mtx, &tmp);
1020 TRACE2((NULL, "shfile_fork_win: set=%d\n", set));
1021
1022 i = pfdtab->size;
1023 while (i-- > 0)
1024 {
1025 if (pfdtab->tab[i].fd == i)
1026 {
1027 shfile_set_inherit_win(&pfdtab->tab[i], set);
1028 if (set)
1029 TRACE2((NULL, " #%d: native=%#x oflags=%#x shflags=%#x\n",
1030 i, pfdtab->tab[i].native, pfdtab->tab[i].oflags, pfdtab->tab[i].shflags));
1031 }
1032 }
1033
1034 if (hndls)
1035 {
1036 for (i = 0; i < 3; i++)
1037 {
1038 if ( pfdtab->size > i
1039 && pfdtab->tab[i].fd == i)
1040 hndls[i] = pfdtab->tab[i].native;
1041 else
1042 hndls[i] = (intptr_t)INVALID_HANDLE_VALUE;
1043 TRACE2((NULL, "shfile_fork_win: i=%d size=%d fd=%d native=%d hndls[%d]=%p\n",
1044 i, pfdtab->size, pfdtab->tab[i].fd, pfdtab->tab[i].native, i, hndls[i]));
1045 }
1046 }
1047
1048 shmtx_leave(&pfdtab->mtx, &tmp);
1049}
1050# endif /* SH_FORKED_MODE */
1051
1052/**
1053 * Helper for sh_execve.
1054 *
1055 * This is called before and after CreateProcess. On the first call it
1056 * will mark the non-close-on-exec handles as inheritable and produce
1057 * the startup info for the CRT. On the second call, after CreateProcess,
1058 * it will restore the handle inheritability properties.
1059 *
1060 * @returns Pointer to CRT data if prepare is 1, NULL if prepare is 0.
1061 * @param pfdtab The file descriptor table.
1062 * @param prepare Which call, 1 if before, 0 if after and success, -1 if after on failure.
1063 * @param sizep Where to store the size of the returned data.
1064 * @param hndls Where to store the three standard handles.
1065 */
1066void *shfile_exec_win(shfdtab *pfdtab, int prepare, unsigned short *sizep, intptr_t *hndls)
1067{
1068 void *pvRet;
1069 shmtxtmp tmp;
1070 unsigned count;
1071 unsigned i;
1072
1073 shmtx_enter(&pfdtab->mtx, &tmp);
1074 TRACE2((NULL, "shfile_exec_win: prepare=%p\n", prepare));
1075
1076 count = pfdtab->size < (0x10000-4) / (1 + sizeof(HANDLE))
1077 ? pfdtab->size
1078 : (0x10000-4) / (1 + sizeof(HANDLE));
1079 while (count > 3 && pfdtab->tab[count - 1].fd == -1)
1080 count--;
1081
1082 if (prepare > 0)
1083 {
1084 size_t cbData = sizeof(int) + count * (1 + sizeof(HANDLE));
1085 uint8_t *pbData = sh_malloc(shthread_get_shell(), cbData);
1086 uint8_t *paf = pbData + sizeof(int);
1087 HANDLE *pah = (HANDLE *)(paf + count);
1088
1089 *(int *)pbData = count;
1090
1091 i = count;
1092 while (i-- > 0)
1093 {
1094 if ( pfdtab->tab[i].fd == i
1095 && !(pfdtab->tab[i].shflags & SHFILE_FLAGS_CLOSE_ON_EXEC))
1096 {
1097 HANDLE hFile = shfile_set_inherit_win(&pfdtab->tab[i], 1);
1098 TRACE2((NULL, " #%d: native=%#x oflags=%#x shflags=%#x\n",
1099 i, hFile, pfdtab->tab[i].oflags, pfdtab->tab[i].shflags));
1100 paf[i] = FOPEN;
1101 if (pfdtab->tab[i].oflags & _O_APPEND)
1102 paf[i] |= FAPPEND;
1103 if (pfdtab->tab[i].oflags & _O_TEXT)
1104 paf[i] |= FTEXT;
1105 switch (pfdtab->tab[i].shflags & SHFILE_FLAGS_TYPE_MASK)
1106 {
1107 case SHFILE_FLAGS_TTY: paf[i] |= FDEV; break;
1108 case SHFILE_FLAGS_PIPE: paf[i] |= FPIPE; break;
1109 }
1110 pah[i] = hFile;
1111 }
1112 else
1113 {
1114 paf[i] = 0;
1115 pah[i] = INVALID_HANDLE_VALUE;
1116 }
1117 }
1118
1119 for (i = 0; i < 3; i++)
1120 {
1121 if ( i < count
1122 && pfdtab->tab[i].fd == i)
1123 hndls[i] = pfdtab->tab[i].native;
1124 else
1125 hndls[i] = (intptr_t)INVALID_HANDLE_VALUE;
1126 TRACE2((NULL, "shfile_exec_win: i=%d count=%d fd=%d native=%d hndls[%d]=\n",
1127 i, count, pfdtab->tab[i].fd, pfdtab->tab[i].native, i, hndls[i]));
1128 }
1129
1130 *sizep = (unsigned short)cbData;
1131 pvRet = pbData;
1132 }
1133 else
1134 {
1135 shfile *file = pfdtab->tab;
1136 assert(!hndls);
1137 assert(!sizep);
1138 i = count;
1139 if (prepare == 0)
1140 for (i = 0; i < count; i++, file++)
1141 {
1142 if ( file->fd == i
1143 && !(file->shflags & SHFILE_FLAGS_TRACE))
1144 {
1145 shfile_native_close(file->native, file->oflags);
1146
1147 file->fd = -1;
1148 file->oflags = 0;
1149 file->shflags = 0;
1150 file->native = -1;
1151 }
1152 }
1153 else
1154 for (i = 0; i < count; i++, file++)
1155 if ( file->fd == i
1156 && !(file->shflags & SHFILE_FLAGS_CLOSE_ON_EXEC))
1157 shfile_set_inherit_win(file, 0);
1158 pvRet = NULL;
1159 }
1160
1161 shmtx_leave(&pfdtab->mtx, &tmp);
1162 return pvRet;
1163}
1164
1165#endif /* K_OS_WINDOWS */
1166
1167#if K_OS != K_OS_WINDOWS
1168/**
1169 * Prepare file handles for inherting before a execve call.
1170 *
1171 * This is only used in the normal mode, so we've forked and need not worry
1172 * about cleaning anything up after us. Nor do we need think about locking.
1173 *
1174 * @returns 0 on success, -1 on failure.
1175 */
1176int shfile_exec_unix(shfdtab *pfdtab)
1177{
1178 int rc = 0;
1179# ifdef SHFILE_IN_USE
1180 unsigned fd;
1181
1182 for (fd = 0; fd < pfdtab->size; fd++)
1183 {
1184 if ( pfdtab->tab[fd].fd != -1
1185 && !(pfdtab->tab[fd].shflags & SHFILE_FLAGS_CLOSE_ON_EXEC) )
1186 {
1187 TRACE2((NULL, "shfile_exec_unix: %d => %d\n", pfdtab->tab[fd].native, fd));
1188 if (dup2(pfdtab->tab[fd].native, fd) < 0)
1189 {
1190 /* fatal_error(NULL, "shfile_exec_unix: failed to move %d to %d", pfdtab->tab[fd].fd, fd); */
1191 rc = -1;
1192 }
1193 }
1194 }
1195# endif
1196 return rc;
1197}
1198#endif /* !K_OS_WINDOWS */
1199
1200/**
1201 * open().
1202 */
1203int shfile_open(shfdtab *pfdtab, const char *name, unsigned flags, mode_t mode)
1204{
1205 int fd;
1206#ifdef SHFILE_IN_USE
1207 char absname[SHFILE_MAX_PATH];
1208# if K_OS == K_OS_WINDOWS
1209 HANDLE hFile;
1210 DWORD dwDesiredAccess;
1211 DWORD dwShareMode;
1212 DWORD dwCreationDisposition;
1213 DWORD dwFlagsAndAttributes;
1214 SECURITY_ATTRIBUTES SecurityAttributes;
1215
1216# ifndef _O_ACCMODE
1217# define _O_ACCMODE (_O_RDONLY|_O_WRONLY|_O_RDWR)
1218# endif
1219 switch (flags & (_O_ACCMODE | _O_APPEND))
1220 {
1221 case _O_RDONLY: dwDesiredAccess = GENERIC_READ; break;
1222 case _O_RDONLY | _O_APPEND: dwDesiredAccess = GENERIC_READ; break;
1223 case _O_WRONLY: dwDesiredAccess = GENERIC_WRITE; break;
1224 case _O_WRONLY | _O_APPEND: dwDesiredAccess = (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA); break;
1225 case _O_RDWR: dwDesiredAccess = GENERIC_READ | GENERIC_WRITE; break;
1226 case _O_RDWR | _O_APPEND: dwDesiredAccess = GENERIC_READ | (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA); break;
1227
1228 default:
1229 RETURN_ERROR(-1, EINVAL, "invalid mode");
1230 }
1231
1232 dwShareMode = FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE;
1233
1234 SecurityAttributes.nLength = sizeof(SecurityAttributes);
1235 SecurityAttributes.lpSecurityDescriptor = NULL;
1236 SecurityAttributes.bInheritHandle = FALSE;
1237
1238 if (flags & _O_CREAT)
1239 {
1240 if ((flags & (_O_EXCL | _O_TRUNC)) == (_O_EXCL | _O_TRUNC))
1241 RETURN_ERROR(-1, EINVAL, "_O_EXCL | _O_TRUNC");
1242
1243 if (flags & _O_TRUNC)
1244 dwCreationDisposition = CREATE_ALWAYS; /* not 100%, but close enough */
1245 else if (flags & _O_EXCL)
1246 dwCreationDisposition = CREATE_NEW;
1247 else
1248 dwCreationDisposition = OPEN_ALWAYS;
1249 }
1250 else if (flags & _O_TRUNC)
1251 dwCreationDisposition = TRUNCATE_EXISTING;
1252 else
1253 dwCreationDisposition = OPEN_EXISTING;
1254
1255 if (!(flags & _O_CREAT) || (mode & 0222))
1256 dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
1257 else
1258 dwFlagsAndAttributes = FILE_ATTRIBUTE_READONLY;
1259
1260 fd = shfile_make_path(pfdtab, name, &absname[0]);
1261 if (!fd)
1262 {
1263 SetLastError(0);
1264 hFile = CreateFileA(absname,
1265 dwDesiredAccess,
1266 dwShareMode,
1267 &SecurityAttributes,
1268 dwCreationDisposition,
1269 dwFlagsAndAttributes,
1270 NULL /* hTemplateFile */);
1271 if (hFile != INVALID_HANDLE_VALUE)
1272 fd = shfile_insert(pfdtab, (intptr_t)hFile, flags, 0, -1, "shfile_open");
1273 else
1274 fd = shfile_dos2errno(GetLastError());
1275 }
1276
1277# else /* K_OS != K_OS_WINDOWS */
1278 fd = shfile_make_path(pfdtab, name, &absname[0]);
1279 if (!fd)
1280 {
1281 fd = open(absname, flags, mode);
1282 if (fd != -1)
1283 fd = shfile_copy_insert_and_close(pfdtab, &fd, flags, 0, -1, "shfile_open");
1284 }
1285
1286# endif /* K_OS != K_OS_WINDOWS */
1287
1288#else
1289 fd = open(name, flags, mode);
1290#endif
1291
1292 TRACE2((NULL, "shfile_open(%p:{%s}, %#x, 0%o) -> %d [%d]\n", name, name, flags, mode, fd, errno));
1293 return fd;
1294}
1295
1296int shfile_pipe(shfdtab *pfdtab, int fds[2])
1297{
1298 int rc = -1;
1299#ifdef SHFILE_IN_USE
1300# if K_OS == K_OS_WINDOWS
1301 HANDLE hRead = INVALID_HANDLE_VALUE;
1302 HANDLE hWrite = INVALID_HANDLE_VALUE;
1303 SECURITY_ATTRIBUTES SecurityAttributes;
1304
1305 SecurityAttributes.nLength = sizeof(SecurityAttributes);
1306 SecurityAttributes.lpSecurityDescriptor = NULL;
1307 SecurityAttributes.bInheritHandle = FALSE;
1308
1309 fds[1] = fds[0] = -1;
1310 if (CreatePipe(&hRead, &hWrite, &SecurityAttributes, 4096))
1311 {
1312 fds[0] = shfile_insert(pfdtab, (intptr_t)hRead, O_RDONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
1313 if (fds[0] != -1)
1314 {
1315 fds[1] = shfile_insert(pfdtab, (intptr_t)hWrite, O_WRONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
1316 if (fds[1] != -1)
1317 rc = 0;
1318 }
1319
1320# else
1321 int native_fds[2];
1322
1323 fds[1] = fds[0] = -1;
1324 if (!pipe(native_fds))
1325 {
1326 fds[0] = shfile_copy_insert_and_close(pfdtab, &native_fds[0], O_RDONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
1327 if (fds[0] != -1)
1328 {
1329 fds[1] = shfile_copy_insert_and_close(pfdtab, &native_fds[1], O_WRONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
1330 if (fds[1] != -1)
1331 rc = 0;
1332 }
1333# endif
1334 if (fds[1] == -1)
1335 {
1336 int s = errno;
1337 if (fds[0] != -1)
1338 {
1339 shmtxtmp tmp;
1340 shmtx_enter(&pfdtab->mtx, &tmp);
1341 rc = fds[0];
1342 pfdtab->tab[rc].fd = -1;
1343 pfdtab->tab[rc].oflags = 0;
1344 pfdtab->tab[rc].shflags = 0;
1345 pfdtab->tab[rc].native = -1;
1346 shmtx_leave(&pfdtab->mtx, &tmp);
1347 }
1348
1349# if K_OS == K_OS_WINDOWS
1350 CloseHandle(hRead);
1351 CloseHandle(hWrite);
1352# else
1353 close(native_fds[0]);
1354 close(native_fds[1]);
1355# endif
1356 fds[0] = fds[1] = -1;
1357 errno = s;
1358 rc = -1;
1359 }
1360 }
1361 else
1362 {
1363# if K_OS == K_OS_WINDOWS
1364 errno = shfile_dos2errno(GetLastError());
1365# endif
1366 rc = -1;
1367 }
1368
1369#else
1370 rc = pipe(fds);
1371#endif
1372
1373 TRACE2((NULL, "shfile_pipe() -> %d{%d,%d} [%d]\n", rc, fds[0], fds[1], errno));
1374 return rc;
1375}
1376
1377/**
1378 * dup().
1379 */
1380int shfile_dup(shfdtab *pfdtab, int fd)
1381{
1382 return shfile_fcntl(pfdtab,fd, F_DUPFD, 0);
1383}
1384
1385/**
1386 * Move the file descriptor, closing any existing descriptor at @a fdto.
1387 *
1388 * @returns fdto on success, -1 and errno on failure.
1389 * @param pfdtab The file descriptor table.
1390 * @param fdfrom The descriptor to move.
1391 * @param fdto Where to move it.
1392 */
1393int shfile_movefd(shfdtab *pfdtab, int fdfrom, int fdto)
1394{
1395#ifdef SHFILE_IN_USE
1396 int rc;
1397 shmtxtmp tmp;
1398 shfile *file = shfile_get(pfdtab, fdfrom, &tmp);
1399 if (file)
1400 {
1401 /* prepare the new entry */
1402 if (fdto >= (int)pfdtab->size)
1403 shfile_grow_tab_locked(pfdtab, fdto);
1404 if (fdto < (int)pfdtab->size)
1405 {
1406 if (pfdtab->tab[fdto].fd != -1)
1407 shfile_native_close(pfdtab->tab[fdto].native, pfdtab->tab[fdto].oflags);
1408
1409 /* setup the target. */
1410 pfdtab->tab[fdto].fd = fdto;
1411 pfdtab->tab[fdto].oflags = file->oflags;
1412 pfdtab->tab[fdto].shflags = file->shflags;
1413 pfdtab->tab[fdto].native = file->native;
1414
1415 /* close the source. */
1416 file->fd = -1;
1417 file->oflags = 0;
1418 file->shflags = 0;
1419 file->native = -1;
1420
1421 rc = fdto;
1422 }
1423 else
1424 {
1425 errno = EMFILE;
1426 rc = -1;
1427 }
1428
1429 shfile_put(pfdtab, file, &tmp);
1430 }
1431 else
1432 rc = -1;
1433 return rc;
1434
1435#else
1436 int fdnew = dup2(fdfrom, fdto);
1437 if (fdnew >= 0)
1438 close(fdfrom);
1439 return fdnew;
1440#endif
1441}
1442
1443/**
1444 * Move the file descriptor to somewhere at @a fdMin or above.
1445 *
1446 * @returns the new file descriptor success, -1 and errno on failure.
1447 * @param pfdtab The file descriptor table.
1448 * @param fdfrom The descriptor to move.
1449 * @param fdMin The minimum descriptor.
1450 */
1451int shfile_movefd_above(shfdtab *pfdtab, int fdfrom, int fdMin)
1452{
1453#ifdef SHFILE_IN_USE
1454 int fdto;
1455 shmtxtmp tmp;
1456 shfile *file = shfile_get(pfdtab, fdfrom, &tmp);
1457 if (file)
1458 {
1459 /* find a new place */
1460 int i;
1461 fdto = -1;
1462 for (i = fdMin; (unsigned)i < pfdtab->size; i++)
1463 if (pfdtab->tab[i].fd == -1)
1464 {
1465 fdto = i;
1466 break;
1467 }
1468 if (fdto == -1)
1469 fdto = shfile_grow_tab_locked(pfdtab, fdMin);
1470 if (fdto != -1)
1471 {
1472 /* setup the target. */
1473 pfdtab->tab[fdto].fd = fdto;
1474 pfdtab->tab[fdto].oflags = file->oflags;
1475 pfdtab->tab[fdto].shflags = file->shflags;
1476 pfdtab->tab[fdto].native = file->native;
1477
1478 /* close the source. */
1479 file->fd = -1;
1480 file->oflags = 0;
1481 file->shflags = 0;
1482 file->native = -1;
1483 }
1484 else
1485 {
1486 errno = EMFILE;
1487 fdto = -1;
1488 }
1489
1490 shfile_put(pfdtab, file, &tmp);
1491 }
1492 else
1493 fdto = -1;
1494 return fdto;
1495
1496#else
1497 int fdnew = fcntl(fdfrom, F_DUPFD, fdMin);
1498 if (fdnew >= 0)
1499 close(fdfrom);
1500 return fdnew;
1501#endif
1502}
1503
1504/**
1505 * close().
1506 */
1507int shfile_close(shfdtab *pfdtab, unsigned fd)
1508{
1509 int rc;
1510#ifdef SHFILE_IN_USE
1511 shmtxtmp tmp;
1512 shfile *file = shfile_get(pfdtab, fd, &tmp);
1513 if (file)
1514 {
1515 shfile_native_close(file->native, file->oflags);
1516
1517 file->fd = -1;
1518 file->oflags = 0;
1519 file->shflags = 0;
1520 file->native = -1;
1521
1522 shfile_put(pfdtab, file, &tmp);
1523 rc = 0;
1524 }
1525 else
1526 rc = -1;
1527
1528#else
1529 rc = close(fd);
1530#endif
1531
1532 TRACE2((NULL, "shfile_close(%d) -> %d [%d]\n", fd, rc, errno));
1533 return rc;
1534}
1535
1536/**
1537 * read().
1538 */
1539long shfile_read(shfdtab *pfdtab, int fd, void *buf, size_t len)
1540{
1541 long rc;
1542#ifdef SHFILE_IN_USE
1543 shmtxtmp tmp;
1544 shfile *file = shfile_get(pfdtab, fd, &tmp);
1545 if (file)
1546 {
1547# if K_OS == K_OS_WINDOWS
1548 DWORD dwRead = 0;
1549 if (ReadFile((HANDLE)file->native, buf, (DWORD)len, &dwRead, NULL))
1550 rc = dwRead;
1551 else
1552 rc = shfile_dos2errno(GetLastError());
1553# else
1554 rc = read(file->native, buf, len);
1555# endif
1556
1557 shfile_put(pfdtab, file, &tmp);
1558 }
1559 else
1560 rc = -1;
1561
1562#else
1563 rc = read(fd, buf, len);
1564#endif
1565 return rc;
1566}
1567
1568/**
1569 * write().
1570 */
1571long shfile_write(shfdtab *pfdtab, int fd, const void *buf, size_t len)
1572{
1573 long rc;
1574#ifdef SHFILE_IN_USE
1575 shmtxtmp tmp;
1576 shfile *file = shfile_get(pfdtab, fd, &tmp);
1577 if (file)
1578 {
1579# if K_OS == K_OS_WINDOWS
1580 DWORD dwWritten = 0;
1581 if (WriteFile((HANDLE)file->native, buf, (DWORD)len, &dwWritten, NULL))
1582 rc = dwWritten;
1583 else
1584 rc = shfile_dos2errno(GetLastError());
1585# else
1586 rc = write(file->native, buf, len);
1587# endif
1588
1589 shfile_put(pfdtab, file, &tmp);
1590 }
1591 else
1592 rc = -1;
1593
1594# ifdef DEBUG
1595 if (fd != shthread_get_shell()->tracefd)
1596 TRACE2((NULL, "shfile_write(%d,,%d) -> %d [%d]\n", fd, len, rc, errno));
1597# endif
1598
1599#else
1600 if (fd != shthread_get_shell()->tracefd)
1601 {
1602 int iSavedErrno = errno;
1603 struct stat s;
1604 int x;
1605 x = fstat(fd, &s);
1606 TRACE2((NULL, "shfile_write(%d) - %lu bytes (%d) - pos %lu - before; %o\n",
1607 fd, (long)s.st_size, x, (long)lseek(fd, 0, SEEK_CUR), s.st_mode ));
1608 K_NOREF(x);
1609 errno = iSavedErrno;
1610 }
1611
1612 rc = write(fd, buf, len);
1613#endif
1614 return rc;
1615}
1616
1617/**
1618 * lseek().
1619 */
1620long shfile_lseek(shfdtab *pfdtab, int fd, long off, int whench)
1621{
1622 long rc;
1623#ifdef SHFILE_IN_USE
1624 shmtxtmp tmp;
1625 shfile *file = shfile_get(pfdtab, fd, &tmp);
1626 if (file)
1627 {
1628# if K_OS == K_OS_WINDOWS
1629 assert(SEEK_SET == FILE_BEGIN);
1630 assert(SEEK_CUR == FILE_CURRENT);
1631 assert(SEEK_END == FILE_END);
1632 rc = SetFilePointer((HANDLE)file->native, off, NULL, whench);
1633 if (rc == INVALID_SET_FILE_POINTER)
1634 rc = shfile_dos2errno(GetLastError());
1635# else
1636 rc = lseek(file->native, off, whench);
1637# endif
1638
1639 shfile_put(pfdtab, file, &tmp);
1640 }
1641 else
1642 rc = -1;
1643
1644#else
1645 rc = lseek(fd, off, whench);
1646#endif
1647
1648 return rc;
1649}
1650
1651int shfile_fcntl(shfdtab *pfdtab, int fd, int cmd, int arg)
1652{
1653 int rc;
1654#ifdef SHFILE_IN_USE
1655 shmtxtmp tmp;
1656 shfile *file = shfile_get(pfdtab, fd, &tmp);
1657 if (file)
1658 {
1659 switch (cmd)
1660 {
1661 case F_GETFL:
1662 rc = file->oflags;
1663 break;
1664
1665 case F_SETFL:
1666 {
1667 unsigned mask = O_NONBLOCK | O_APPEND | O_BINARY | O_TEXT;
1668# ifdef O_DIRECT
1669 mask |= O_DIRECT;
1670# endif
1671# ifdef O_ASYNC
1672 mask |= O_ASYNC;
1673# endif
1674# ifdef O_SYNC
1675 mask |= O_SYNC;
1676# endif
1677 if ((file->oflags & mask) == (arg & mask))
1678 rc = 0;
1679 else
1680 {
1681# if K_OS == K_OS_WINDOWS
1682 assert(0);
1683 errno = EINVAL;
1684 rc = -1;
1685# else
1686 rc = fcntl(file->native, F_SETFL, arg);
1687 if (rc != -1)
1688 file->oflags = (file->oflags & ~mask) | (arg & mask);
1689# endif
1690 }
1691 break;
1692 }
1693
1694 case F_DUPFD:
1695 {
1696# if K_OS == K_OS_WINDOWS
1697 HANDLE hNew = INVALID_HANDLE_VALUE;
1698 if (DuplicateHandle(GetCurrentProcess(),
1699 (HANDLE)file->native,
1700 GetCurrentProcess(),
1701 &hNew,
1702 0,
1703 FALSE /* bInheritHandle */,
1704 DUPLICATE_SAME_ACCESS))
1705 rc = shfile_insert(pfdtab, (intptr_t)hNew, file->oflags, file->shflags, arg, "shfile_fcntl");
1706 else
1707 rc = shfile_dos2errno(GetLastError());
1708# else
1709 int nativeNew = fcntl(file->native, F_DUPFD, SHFILE_UNIX_MIN_FD);
1710 if (nativeNew != -1)
1711 rc = shfile_insert(pfdtab, nativeNew, file->oflags, file->shflags, arg, "shfile_fcntl");
1712 else
1713 rc = -1;
1714# endif
1715 break;
1716 }
1717
1718 default:
1719 errno = -EINVAL;
1720 rc = -1;
1721 break;
1722 }
1723
1724 shfile_put(pfdtab, file, &tmp);
1725 }
1726 else
1727 rc = -1;
1728
1729#else
1730 rc = fcntl(fd, cmd, arg);
1731#endif
1732
1733 switch (cmd)
1734 {
1735 case F_GETFL: TRACE2((NULL, "shfile_fcntl(%d,F_GETFL,ignored=%d) -> %d [%d]\n", fd, arg, rc, errno)); break;
1736 case F_SETFL: TRACE2((NULL, "shfile_fcntl(%d,F_SETFL,newflags=%#x) -> %d [%d]\n", fd, arg, rc, errno)); break;
1737 case F_DUPFD: TRACE2((NULL, "shfile_fcntl(%d,F_DUPFD,minfd=%d) -> %d [%d]\n", fd, arg, rc, errno)); break;
1738 default: TRACE2((NULL, "shfile_fcntl(%d,%d,%d) -> %d [%d]\n", fd, cmd, arg, rc, errno)); break;
1739 }
1740 return rc;
1741}
1742
1743int shfile_stat(shfdtab *pfdtab, const char *path, struct stat *pst)
1744{
1745#ifdef SHFILE_IN_USE
1746 char abspath[SHFILE_MAX_PATH];
1747 int rc;
1748 rc = shfile_make_path(pfdtab, path, &abspath[0]);
1749 if (!rc)
1750 {
1751# if K_OS == K_OS_WINDOWS
1752 int dir_slash = shfile_trailing_slash_hack(abspath);
1753 rc = stat(abspath, pst); /** @todo re-implement stat. */
1754 if (!rc && dir_slash && !S_ISDIR(pst->st_mode))
1755 {
1756 rc = -1;
1757 errno = ENOTDIR;
1758 }
1759# else
1760 rc = stat(abspath, pst);
1761# endif
1762 }
1763 TRACE2((NULL, "shfile_stat(,%s,) -> %d [%d]\n", path, rc, errno));
1764 return rc;
1765#else
1766 return stat(path, pst);
1767#endif
1768}
1769
1770int shfile_lstat(shfdtab *pfdtab, const char *path, struct stat *pst)
1771{
1772 int rc;
1773#ifdef SHFILE_IN_USE
1774 char abspath[SHFILE_MAX_PATH];
1775
1776 rc = shfile_make_path(pfdtab, path, &abspath[0]);
1777 if (!rc)
1778 {
1779# if K_OS == K_OS_WINDOWS
1780 int dir_slash = shfile_trailing_slash_hack(abspath);
1781 rc = stat(abspath, pst); /** @todo re-implement stat. */
1782 if (!rc && dir_slash && !S_ISDIR(pst->st_mode))
1783 {
1784 rc = -1;
1785 errno = ENOTDIR;
1786 }
1787# else
1788 rc = lstat(abspath, pst);
1789# endif
1790 }
1791#else
1792 rc = stat(path, pst);
1793#endif
1794 TRACE2((NULL, "shfile_stat(,%s,) -> %d [%d]\n", path, rc, errno));
1795 return rc;
1796}
1797
1798/**
1799 * chdir().
1800 */
1801int shfile_chdir(shfdtab *pfdtab, const char *path)
1802{
1803 int rc;
1804#ifdef SHFILE_IN_USE
1805 shinstance *psh = shthread_get_shell();
1806 char abspath[SHFILE_MAX_PATH];
1807
1808 rc = shfile_make_path(pfdtab, path, &abspath[0]);
1809 if (!rc)
1810 {
1811 char *abspath_copy = sh_strdup(psh, abspath);
1812 char *free_me = abspath_copy;
1813 rc = chdir(abspath);
1814 if (!rc)
1815 {
1816 shmtxtmp tmp;
1817 shmtx_enter(&pfdtab->mtx, &tmp);
1818
1819 shfile_fix_slashes(abspath_copy);
1820 free_me = pfdtab->cwd;
1821 pfdtab->cwd = abspath_copy;
1822
1823 shmtx_leave(&pfdtab->mtx, &tmp);
1824 }
1825 sh_free(psh, free_me);
1826 }
1827 else
1828 rc = -1;
1829#else
1830 rc = chdir(path);
1831#endif
1832
1833 TRACE2((NULL, "shfile_chdir(,%s) -> %d [%d]\n", path, rc, errno));
1834 return rc;
1835}
1836
1837/**
1838 * getcwd().
1839 */
1840char *shfile_getcwd(shfdtab *pfdtab, char *buf, int size)
1841{
1842 char *ret;
1843#ifdef SHFILE_IN_USE
1844
1845 ret = NULL;
1846 if (buf && !size)
1847 errno = -EINVAL;
1848 else
1849 {
1850 size_t cwd_size;
1851 shmtxtmp tmp;
1852 shmtx_enter(&pfdtab->mtx, &tmp);
1853
1854 cwd_size = strlen(pfdtab->cwd) + 1;
1855 if (buf)
1856 {
1857 if (cwd_size <= (size_t)size)
1858 ret = memcpy(buf, pfdtab->cwd, cwd_size);
1859 else
1860 errno = ERANGE;
1861 }
1862 else
1863 {
1864 if ((size_t)size < cwd_size)
1865 size = (int)cwd_size;
1866 ret = sh_malloc(shthread_get_shell(), size);
1867 if (ret)
1868 ret = memcpy(ret, pfdtab->cwd, cwd_size);
1869 else
1870 errno = ENOMEM;
1871 }
1872
1873 shmtx_leave(&pfdtab->mtx, &tmp);
1874 }
1875#else
1876 ret = getcwd(buf, size);
1877#endif
1878
1879 TRACE2((NULL, "shfile_getcwd(,%p,%d) -> %s [%d]\n", buf, size, ret, errno));
1880 return ret;
1881}
1882
1883/**
1884 * access().
1885 */
1886int shfile_access(shfdtab *pfdtab, const char *path, int type)
1887{
1888 int rc;
1889#ifdef SHFILE_IN_USE
1890 char abspath[SHFILE_MAX_PATH];
1891
1892 rc = shfile_make_path(pfdtab, path, &abspath[0]);
1893 if (!rc)
1894 {
1895# ifdef _MSC_VER
1896 if (type & X_OK)
1897 type = (type & ~X_OK) | R_OK;
1898# endif
1899 rc = access(abspath, type);
1900 }
1901#else
1902# ifdef _MSC_VER
1903 if (type & X_OK)
1904 type = (type & ~X_OK) | R_OK;
1905# endif
1906 rc = access(path, type);
1907#endif
1908
1909 TRACE2((NULL, "shfile_access(,%s,%#x) -> %d [%d]\n", path, type, rc, errno));
1910 return rc;
1911}
1912
1913/**
1914 * isatty()
1915 */
1916int shfile_isatty(shfdtab *pfdtab, int fd)
1917{
1918 int rc;
1919#ifdef SHFILE_IN_USE
1920 shmtxtmp tmp;
1921 shfile *file = shfile_get(pfdtab, fd, &tmp);
1922 if (file)
1923 {
1924# if K_OS == K_OS_WINDOWS
1925 rc = (file->shflags & SHFILE_FLAGS_TYPE_MASK) == SHFILE_FLAGS_TTY;
1926# else
1927 rc = isatty(file->native);
1928# endif
1929 shfile_put(pfdtab, file, &tmp);
1930 }
1931 else
1932 rc = 0;
1933#else
1934 rc = isatty(fd);
1935#endif
1936
1937 TRACE2((NULL, "isatty(%d) -> %d [%d]\n", fd, rc, errno));
1938 return rc;
1939}
1940
1941/**
1942 * fcntl F_SETFD / FD_CLOEXEC.
1943 */
1944int shfile_cloexec(shfdtab *pfdtab, int fd, int closeit)
1945{
1946 int rc;
1947#ifdef SHFILE_IN_USE
1948 shmtxtmp tmp;
1949 shfile *file = shfile_get(pfdtab, fd, &tmp);
1950 if (file)
1951 {
1952 if (closeit)
1953 file->shflags |= SHFILE_FLAGS_CLOSE_ON_EXEC;
1954 else
1955 file->shflags &= ~SHFILE_FLAGS_CLOSE_ON_EXEC;
1956 shfile_put(pfdtab, file, &tmp);
1957 rc = 0;
1958 }
1959 else
1960 rc = -1;
1961#else
1962 rc = fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0)
1963 | (closeit ? FD_CLOEXEC : 0));
1964#endif
1965
1966 TRACE2((NULL, "shfile_cloexec(%d, %d) -> %d [%d]\n", fd, closeit, rc, errno));
1967 return rc;
1968}
1969
1970/**
1971 * Sets the SHFILE_FLAGS_TRACE flag.
1972 */
1973int shfile_set_trace(shfdtab *pfdtab, int fd)
1974{
1975 int rc;
1976#ifdef SHFILE_IN_USE
1977 shmtxtmp tmp;
1978 shfile *file = shfile_get(pfdtab, fd, &tmp);
1979 if (file)
1980 {
1981 file->shflags |= SHFILE_FLAGS_TRACE;
1982 shfile_put(pfdtab, file, &tmp);
1983 rc = 0;
1984 }
1985 else
1986 rc = -1;
1987#else
1988 rc = 0;
1989#endif
1990
1991 TRACE2((NULL, "shfile_set_trace(%d) -> %d\n", fd, rc));
1992 return rc;
1993}
1994
1995
1996int shfile_ioctl(shfdtab *pfdtab, int fd, unsigned long request, void *buf)
1997{
1998 int rc;
1999#ifdef SHFILE_IN_USE
2000 shmtxtmp tmp;
2001 shfile *file = shfile_get(pfdtab, fd, &tmp);
2002 if (file)
2003 {
2004# if K_OS == K_OS_WINDOWS
2005 rc = -1;
2006 errno = ENOSYS;
2007# else
2008 rc = ioctl(file->native, request, buf);
2009# endif
2010 shfile_put(pfdtab, file, &tmp);
2011 }
2012 else
2013 rc = -1;
2014#else
2015 rc = ioctl(fd, request, buf);
2016#endif
2017
2018 TRACE2((NULL, "ioctl(%d, %#x, %p) -> %d\n", fd, request, buf, rc));
2019 return rc;
2020}
2021
2022
2023mode_t shfile_get_umask(shfdtab *pfdtab)
2024{
2025 /** @todo */
2026 return 022;
2027}
2028
2029void shfile_set_umask(shfdtab *pfdtab, mode_t mask)
2030{
2031 /** @todo */
2032 (void)mask;
2033}
2034
2035
2036
2037shdir *shfile_opendir(shfdtab *pfdtab, const char *dir)
2038{
2039#if defined(SHFILE_IN_USE) && K_OS == K_OS_WINDOWS
2040 shdir *pdir = NULL;
2041
2042 TRACE2((NULL, "shfile_opendir: dir='%s'\n", dir));
2043 shfile_init_globals();
2044 if (g_pfnNtQueryDirectoryFile)
2045 {
2046 char abspath[SHFILE_MAX_PATH];
2047 if (shfile_make_path(pfdtab, dir, &abspath[0]) == 0)
2048 {
2049 HANDLE hFile;
2050 SECURITY_ATTRIBUTES SecurityAttributes;
2051
2052 SecurityAttributes.nLength = sizeof(SecurityAttributes);
2053 SecurityAttributes.lpSecurityDescriptor = NULL;
2054 SecurityAttributes.bInheritHandle = FALSE;
2055
2056 hFile = CreateFileA(abspath,
2057 GENERIC_READ,
2058 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
2059 &SecurityAttributes,
2060 OPEN_EXISTING,
2061 FILE_ATTRIBUTE_DIRECTORY | FILE_FLAG_BACKUP_SEMANTICS,
2062 NULL /* hTemplateFile */);
2063 if (hFile != INVALID_HANDLE_VALUE)
2064 {
2065 pdir = (shdir *)sh_malloc(shthread_get_shell(), sizeof(*pdir));
2066 if (pdir)
2067 {
2068 pdir->pfdtab = pfdtab;
2069 pdir->native = hFile;
2070 pdir->off = ~(size_t)0;
2071 }
2072 else
2073 CloseHandle(hFile);
2074 }
2075 else
2076 {
2077 errno = shfile_dos2errno(GetLastError());
2078 TRACE2((NULL, "shfile_opendir: CreateFileA(%s) -> %d/%d\n", abspath, GetLastError(), errno));
2079 }
2080 }
2081 }
2082 else
2083 errno = ENOSYS;
2084 return pdir;
2085#else
2086 TRACE2((NULL, "shfile_opendir: dir='%s'\n", dir));
2087 return (shdir *)opendir(dir);
2088#endif
2089}
2090
2091shdirent *shfile_readdir(struct shdir *pdir)
2092{
2093#if defined(SHFILE_IN_USE) && K_OS == K_OS_WINDOWS
2094 if (pdir)
2095 {
2096 NTSTATUS rcNt;
2097
2098 if ( pdir->off == ~(size_t)0
2099 || pdir->off + sizeof(MY_FILE_NAMES_INFORMATION) >= pdir->cb)
2100 {
2101 MY_IO_STATUS_BLOCK Ios;
2102
2103 memset(&Ios, 0, sizeof(Ios));
2104 rcNt = g_pfnNtQueryDirectoryFile(pdir->native,
2105 NULL /*Event*/,
2106 NULL /*ApcRoutine*/,
2107 NULL /*ApcContext*/,
2108 &Ios,
2109 &pdir->buf[0],
2110 sizeof(pdir->buf),
2111 MY_FileNamesInformation,
2112 FALSE /*ReturnSingleEntry*/,
2113 NULL /*FileName*/,
2114 pdir->off == ~(size_t)0 /*RestartScan*/);
2115 if (rcNt >= 0 && rcNt != STATUS_PENDING)
2116 {
2117 pdir->cb = Ios.Information;
2118 pdir->off = 0;
2119 }
2120 else if (rcNt == STATUS_NO_MORE_FILES)
2121 errno = 0; /* wrong? */
2122 else
2123 shfile_nt2errno(rcNt);
2124 }
2125
2126 if ( pdir->off != ~(size_t)0
2127 && pdir->off + sizeof(MY_FILE_NAMES_INFORMATION) <= pdir->cb)
2128 {
2129 PMY_FILE_NAMES_INFORMATION pcur = (PMY_FILE_NAMES_INFORMATION)&pdir->buf[pdir->off];
2130 ANSI_STRING astr;
2131 UNICODE_STRING ustr;
2132
2133 astr.Length = astr.MaximumLength = sizeof(pdir->ent.name);
2134 astr.Buffer = &pdir->ent.name[0];
2135
2136 ustr.Length = ustr.MaximumLength = pcur->FileNameLength < ~(USHORT)0 ? (USHORT)pcur->FileNameLength : ~(USHORT)0;
2137 ustr.Buffer = &pcur->FileName[0];
2138
2139 rcNt = g_pfnRtlUnicodeStringToAnsiString(&astr, &ustr, 0/*AllocateDestinationString*/);
2140 if (rcNt < 0)
2141 sprintf(pdir->ent.name, "conversion-failed-%08x-rcNt=%08x-len=%u",
2142 pcur->FileIndex, rcNt, pcur->FileNameLength);
2143 if (pcur->NextEntryOffset)
2144 pdir->off += pcur->NextEntryOffset;
2145 else
2146 pdir->off = pdir->cb;
2147 return &pdir->ent;
2148 }
2149 }
2150 else
2151 errno = EINVAL;
2152 return NULL;
2153#else
2154 struct dirent *pde = readdir((DIR *)pdir);
2155 return pde ? (shdirent *)&pde->d_name[0] : NULL;
2156#endif
2157}
2158
2159void shfile_closedir(struct shdir *pdir)
2160{
2161#if defined(SHFILE_IN_USE) && K_OS == K_OS_WINDOWS
2162 if (pdir)
2163 {
2164 CloseHandle(pdir->native);
2165 pdir->pfdtab = NULL;
2166 pdir->native = INVALID_HANDLE_VALUE;
2167 sh_free(shthread_get_shell(), pdir);
2168 }
2169 else
2170 errno = EINVAL;
2171#else
2172 closedir((DIR *)pdir);
2173#endif
2174}
2175
Note: See TracBrowser for help on using the repository browser.