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

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

kash: Hammering on threaded mode.

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