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

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

kash: Hammering on threaded mode. Got shexit half working. Incomplete sh_destroy.

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