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

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

kash: Use kHlpAssert instead of assert.h (debugger stops on the assertion rather than at exit process code).

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Id
File size: 81.7 KB
Line 
1/* $Id: shfile.c 3477 2020-09-17 21:52:16Z 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
36#if K_OS == K_OS_WINDOWS
37# include <ntstatus.h>
38# define WIN32_NO_STATUS
39# include <Windows.h>
40# if !defined(_WIN32_WINNT)
41# define _WIN32_WINNT 0x0502 /* Windows Server 2003 */
42# endif
43# include <winternl.h> //NTSTATUS
44#else
45# include <unistd.h>
46# include <fcntl.h>
47# include <dirent.h>
48#endif
49
50
51/*******************************************************************************
52* Defined Constants And Macros *
53*******************************************************************************/
54/** @def SHFILE_IN_USE
55 * Whether the file descriptor table stuff is actually in use or not.
56 */
57#if K_OS == K_OS_WINDOWS \
58 || K_OS == K_OS_OPENBSD /* because of ugly pthread library pipe hacks */ \
59 || !defined(SH_FORKED_MODE)
60# define SHFILE_IN_USE
61#endif
62/** The max file table size. */
63#define SHFILE_MAX 1024
64/** The file table growth rate. */
65#define SHFILE_GROW 64
66/** The min native unix file descriptor. */
67#define SHFILE_UNIX_MIN_FD 32
68/** The path buffer size we use. */
69#define SHFILE_MAX_PATH 4096
70
71/** Set errno and return. Doing a trace in debug build. */
72#define RETURN_ERROR(rc, err, msg) \
73 do { \
74 TRACE2((NULL, "%s: " ## msg ## " - returning %d / %d\n", __FUNCTION__, (rc), (err))); \
75 errno = (err); \
76 return (rc); \
77 } while (0)
78
79#if K_OS == K_OS_WINDOWS
80 /* See msdos.h for description. */
81# define FOPEN 0x01
82# define FEOFLAG 0x02
83# define FCRLF 0x04
84# define FPIPE 0x08
85# define FNOINHERIT 0x10
86# define FAPPEND 0x20
87# define FDEV 0x40
88# define FTEXT 0x80
89
90# define MY_ObjectBasicInformation 0
91# define MY_FileNamesInformation 12
92
93typedef struct
94{
95 ULONG Attributes;
96 ACCESS_MASK GrantedAccess;
97 ULONG HandleCount;
98 ULONG PointerCount;
99 ULONG PagedPoolUsage;
100 ULONG NonPagedPoolUsage;
101 ULONG Reserved[3];
102 ULONG NameInformationLength;
103 ULONG TypeInformationLength;
104 ULONG SecurityDescriptorLength;
105 LARGE_INTEGER CreateTime;
106} MY_OBJECT_BASIC_INFORMATION;
107
108#if 0
109typedef struct
110{
111 union
112 {
113 LONG Status;
114 PVOID Pointer;
115 };
116 ULONG_PTR Information;
117} MY_IO_STATUS_BLOCK;
118#else
119typedef IO_STATUS_BLOCK MY_IO_STATUS_BLOCK;
120#endif
121typedef MY_IO_STATUS_BLOCK *PMY_IO_STATUS_BLOCK;
122
123typedef struct
124{
125 ULONG NextEntryOffset;
126 ULONG FileIndex;
127 ULONG FileNameLength;
128 WCHAR FileName[1];
129} MY_FILE_NAMES_INFORMATION, *PMY_FILE_NAMES_INFORMATION;
130
131typedef NTSTATUS (NTAPI * PFN_NtQueryObject)(HANDLE, int, void *, size_t, size_t *);
132typedef NTSTATUS (NTAPI * PFN_NtQueryDirectoryFile)(HANDLE, HANDLE, void *, void *, PMY_IO_STATUS_BLOCK, void *,
133 ULONG, int, int, PUNICODE_STRING, int);
134typedef NTSTATUS (NTAPI * PFN_RtlUnicodeStringToAnsiString)(PANSI_STRING, PCUNICODE_STRING, int);
135
136
137#endif /* K_OS_WINDOWS */
138
139
140/*********************************************************************************************************************************
141* Global Variables *
142*********************************************************************************************************************************/
143#if K_OS == K_OS_WINDOWS
144static int g_shfile_globals_initialized = 0;
145static PFN_NtQueryObject g_pfnNtQueryObject = NULL;
146static PFN_NtQueryDirectoryFile g_pfnNtQueryDirectoryFile = NULL;
147static PFN_RtlUnicodeStringToAnsiString g_pfnRtlUnicodeStringToAnsiString = NULL;
148# ifdef KASH_ASYNC_CLOSE_HANDLE
149/** Data for the asynchronous CloseHandle machinery. */
150static struct shfileasyncclose
151{
152 /** Mutex protecting the asynchronous CloseHandle stuff. */
153 shmtx mtx;
154 /** Handle to event that the closer-threads are waiting on. */
155 HANDLE evt_workers;
156 /** The ring buffer read index (for closer-threads). */
157 unsigned volatile idx_read;
158 /** The ring buffer write index (for shfile_native_close).
159 * When idx_read and idx_write are the same, the ring buffer is empty. */
160 unsigned volatile idx_write;
161 /** Number of handles currently being pending closure (handles + current
162 * CloseHandle calls). */
163 unsigned volatile num_pending;
164 /** Set if the threads should terminate. */
165 KBOOL volatile terminate_threads;
166 /** Set if one or more shell threads have requested evt_sync to be signalled
167 * when there are no more pending requests. */
168 KBOOL volatile signal_sync;
169 /** Number of threads that have been spawned. */
170 KU8 num_threads;
171 /** Handle to event that the shell threads are waiting on to sync. */
172 HANDLE evt_sync;
173 /** Ring buffer containing handles to be closed. */
174 HANDLE handles[32];
175 /** Worker threads doing the asynchronous closing. */
176 HANDLE threads[8];
177} g_shfile_async_close;
178# endif
179#endif /* K_OS_WINDOWS */
180
181
182/*********************************************************************************************************************************
183* Internal Functions *
184*********************************************************************************************************************************/
185#ifdef SHFILE_IN_USE
186# if K_OS == K_OS_WINDOWS
187static HANDLE shfile_set_inherit_win(shfile *pfd, int set);
188# endif
189#endif
190
191
192#ifdef SHFILE_IN_USE
193
194# ifdef DEBUG
195# if K_OS == K_OS_WINDOWS
196static KU64 shfile_nano_ts(void)
197{
198 static KBOOL volatile s_has_factor = K_FALSE;
199 static double volatile s_factor;
200 double factor;
201 LARGE_INTEGER now;
202 if (s_has_factor)
203 factor = s_factor;
204 else
205 {
206 QueryPerformanceFrequency(&now);
207 s_factor = factor = (double)1000000000.0 / now.QuadPart;
208 s_has_factor = K_TRUE;
209 }
210 QueryPerformanceCounter(&now);
211 return (KU64)(now.QuadPart * factor);
212}
213# endif /* K_OS_WINDOWS */
214# endif /* DEBUG */
215
216# if K_OS == K_OS_WINDOWS && defined(KASH_ASYNC_CLOSE_HANDLE)
217/**
218 * The closer thread function.
219 */
220static unsigned __stdcall shfile_async_close_handle_thread(void *ignored)
221{
222 KBOOL decrement_pending = K_FALSE;
223 while (!g_shfile_async_close.terminate_threads)
224 {
225 HANDLE toclose;
226 unsigned idx;
227 shmtxtmp tmp;
228
229 /*
230 * Grab a handle if there is one:
231 */
232 shmtx_enter(&g_shfile_async_close.mtx, &tmp);
233
234 if (decrement_pending)
235 {
236 kHlpAssert(g_shfile_async_close.num_pending > 0);
237 g_shfile_async_close.num_pending -= 1;
238 }
239
240 idx = g_shfile_async_close.idx_read % K_ELEMENTS(g_shfile_async_close.handles);
241 if (idx != g_shfile_async_close.idx_write % K_ELEMENTS(g_shfile_async_close.handles))
242 {
243 kHlpAssert(g_shfile_async_close.num_pending > 0);
244 toclose = g_shfile_async_close.handles[idx];
245 kHlpAssert(toclose);
246 g_shfile_async_close.handles[idx] = NULL;
247 g_shfile_async_close.idx_read = (idx + 1) % K_ELEMENTS(g_shfile_async_close.handles);
248 }
249 else
250 {
251 /* Signal waiters if requested and we've reached zero pending requests. */
252 if (g_shfile_async_close.signal_sync && g_shfile_async_close.num_pending == 0)
253 {
254 BOOL rc = SetEvent(g_shfile_async_close.evt_sync);
255 kHlpAssert(rc);
256 g_shfile_async_close.signal_sync = FALSE;
257 }
258 toclose = NULL;
259 }
260 shmtx_leave(&g_shfile_async_close.mtx, &tmp);
261
262 /* Do the closing if we have something to close, otherwise wait for work to arrive. */
263 if (toclose != NULL)
264 {
265 BOOL rc = CloseHandle(toclose);
266 kHlpAssert(rc);
267 decrement_pending = K_TRUE;
268 }
269 else
270 {
271 DWORD dwRet = WaitForSingleObject(g_shfile_async_close.evt_workers, 10000 /*ms*/);
272 kHlpAssert(dwRet == WAIT_OBJECT_0 || dwRet == WAIT_TIMEOUT);
273 decrement_pending = K_FALSE;
274 }
275 }
276
277 K_NOREF(ignored);
278 return 0;
279}
280
281/**
282 * Try submit a handle for automatic closing.
283 *
284 * @returns K_TRUE if submitted successfully, K_FALSE if not.
285 */
286static KBOOL shfile_async_close_submit(HANDLE toclose)
287{
288 KBOOL ret;
289 unsigned idx;
290 unsigned idx_next;
291 unsigned idx_read;
292 unsigned num_pending = 0;
293 unsigned num_threads = 0;
294 shmtxtmp tmp;
295 shmtx_enter(&g_shfile_async_close.mtx, &tmp);
296
297 /* Get the write index and check that there is a free slot in the buffer: */
298 idx = g_shfile_async_close.idx_write % K_ELEMENTS(g_shfile_async_close.handles);
299 idx_next = (idx + 1) % K_ELEMENTS(g_shfile_async_close.handles);
300 idx_read = g_shfile_async_close.idx_read % K_ELEMENTS(g_shfile_async_close.handles);
301 if (idx_next != idx_read)
302 {
303 /* Write the handle to the ring buffer: */
304 kHlpAssert(g_shfile_async_close.handles[idx] == NULL);
305 g_shfile_async_close.handles[idx] = toclose;
306 g_shfile_async_close.idx_write = idx_next;
307
308 num_pending = g_shfile_async_close.num_pending + 1;
309 g_shfile_async_close.num_pending = num_pending;
310
311 ret = SetEvent(g_shfile_async_close.evt_workers);
312 kHlpAssert(ret);
313 if (ret)
314 {
315 /* If we have more pending requests than threads, create a new thread. */
316 num_threads = g_shfile_async_close.num_threads;
317 if (num_pending > num_threads && num_threads < K_ELEMENTS(g_shfile_async_close.threads))
318 {
319 int const savederrno = errno;
320 unsigned tid = 0;
321 intptr_t hThread = _beginthreadex(NULL /*security*/, 0 /*stack_size*/, shfile_async_close_handle_thread,
322 NULL /*arg*/, 0 /*initflags*/, &tid);
323 kHlpAssert(hThread != -1);
324 if (hThread != -1)
325 {
326 g_shfile_async_close.threads[num_threads] = (HANDLE)hThread;
327 g_shfile_async_close.num_threads = ++num_threads;
328 }
329 else
330 {
331 TRACE2((NULL, "shfile_async_close_submit: _beginthreadex failed: %d\n", errno));
332 if (num_threads == 0)
333 ret = K_FALSE;
334 }
335 errno = savederrno;
336 }
337 }
338 else
339 TRACE2((NULL, "shfile_async_close_submit: SetEvent(%p) failed: %u\n", g_shfile_async_close.evt_workers, GetLastError()));
340
341 /* cleanup on failure. */
342 if (ret)
343 { /* likely */ }
344 else
345 {
346 g_shfile_async_close.handles[idx] = NULL;
347 g_shfile_async_close.idx_write = idx;
348 g_shfile_async_close.num_pending = num_pending - 1;
349 }
350 }
351 else
352 ret = K_FALSE;
353
354 shmtx_leave(&g_shfile_async_close.mtx, &tmp);
355 TRACE2((NULL, "shfile_async_close_submit: toclose=%p idx=%d #pending=%u #thread=%u -> %d\n",
356 toclose, idx, num_pending, num_threads, ret));
357 return ret;
358}
359
360/**
361 * Wait for all pending CloseHandle calls to complete.
362 */
363void shfile_async_close_sync(void)
364{
365 shmtxtmp tmp;
366 shmtx_enter(&g_shfile_async_close.mtx, &tmp);
367
368 if (g_shfile_async_close.num_pending > 0)
369 {
370 DWORD dwRet;
371
372/** @todo help out? */
373 if (!g_shfile_async_close.signal_sync)
374 {
375 BOOL rc = ResetEvent(g_shfile_async_close.evt_sync);
376 kHlpAssert(rc); K_NOREF(rc);
377
378 g_shfile_async_close.signal_sync = K_TRUE;
379 }
380
381 shmtx_leave(&g_shfile_async_close.mtx, &tmp);
382
383 TRACE2((NULL, "shfile_async_close_sync: Calling WaitForSingleObject...\n"));
384 dwRet = WaitForSingleObject(g_shfile_async_close.evt_sync, 10000 /*ms*/);
385 kHlpAssert(dwRet == WAIT_OBJECT_0);
386 kHlpAssert(g_shfile_async_close.num_pending == 0);
387 TRACE2((NULL, "shfile_async_close_sync: WaitForSingleObject returned %u...\n", dwRet));
388 }
389 else
390 shmtx_leave(&g_shfile_async_close.mtx, &tmp);
391}
392
393# endif /* K_OS == K_OS_WINDOWS && defined(KASH_ASYNC_CLOSE_HANDLE) */
394
395/**
396 * Close the specified native handle.
397 *
398 * @param native The native file handle.
399 * @param file The file table entry if available.
400 * @param inheritable The inheritability of the handle on windows, K_FALSE elsewhere.
401 */
402static void shfile_native_close(intptr_t native, shfile *file, KBOOL inheritable)
403{
404# if K_OS == K_OS_WINDOWS
405# ifdef KASH_ASYNC_CLOSE_HANDLE
406 /*
407 * CloseHandle may take several milliseconds on NTFS after we've appended
408 * a few bytes to a file. When a script uses lots of 'echo line-text >> file'
409 * we end up executing very slowly, even if 'echo' is builtin and the statement
410 * requires no subshells to be spawned.
411 *
412 * So, detect problematic handles and do CloseHandle asynchronously. When
413 * executing a child process, we probably will have to make sure the CloseHandle
414 * operation has completed before we do ResumeThread on the child to make 100%
415 * sure we can't have any sharing conflicts or end up with incorrect CRT stat()
416 * results. Sharing conflicts are not a problem for builtin commands, and for
417 * stat we do not use the CRT code but ntstat.c/h and it seems to work fine
418 * (might be a tiny bit slower, so (TODO) might be worth reducing what we ask for).
419 *
420 * If child processes are spawned using handle inheritance and the handle in
421 * question is inheritable, we will have to fix the inheriability before pushing
422 * on the async-close queue. This shouldn't have the CloseHandle issues.
423 */
424 if ( file
425 && (file->shflags & (SHFILE_FLAGS_DIRTY | SHFILE_FLAGS_TYPE_MASK))
426 == (SHFILE_FLAGS_DIRTY | SHFILE_FLAGS_FILE))
427 {
428 if (inheritable)
429 native = (intptr_t)shfile_set_inherit_win(file, 0);
430 if (shfile_async_close_submit((HANDLE)native))
431 return;
432 }
433
434 /*
435 * Otherwise close it right here:
436 */
437# endif
438 {
439# ifdef DEBUG
440 KU64 ns = shfile_nano_ts();
441 BOOL fRc = CloseHandle((HANDLE)native);
442 kHlpAssert(fRc); K_NOREF(fRc);
443 ns = shfile_nano_ts() - ns;
444 if (ns > 1000000)
445 TRACE2((NULL, "shfile_native_close: %u ns %p oflags=%#x %s\n",
446 ns, native, file ? file->oflags : 0, file ? file->dbgname : NULL));
447# else
448 BOOL fRc = CloseHandle((HANDLE)native);
449 kHlpAssert(fRc); K_NOREF(fRc);
450# endif
451 }
452
453# else /* K_OS != K_OS_WINDOWS */
454 int s = errno;
455 close(native);
456 errno = s;
457# endif /* K_OS != K_OS_WINDOWS */
458 K_NOREF(file);
459}
460
461/**
462 * Grows the descriptor table, making sure that it can hold @a fdMin,
463 *
464 * @returns The max(fdMin, fdFirstNew) on success, -1 on failure.
465 * @param pfdtab The table to grow.
466 * @param fdMin Grow to include this index.
467 */
468static int shfile_grow_tab_locked(shfdtab *pfdtab, int fdMin)
469{
470 /*
471 * Grow the descriptor table.
472 */
473 int fdRet = -1;
474 shfile *new_tab;
475 int new_size = pfdtab->size + SHFILE_GROW;
476 while (new_size < fdMin)
477 new_size += SHFILE_GROW;
478 new_tab = sh_realloc(shthread_get_shell(), pfdtab->tab, new_size * sizeof(shfile));
479 if (new_tab)
480 {
481 int i;
482 for (i = pfdtab->size; i < new_size; i++)
483 {
484 new_tab[i].fd = -1;
485 new_tab[i].oflags = 0;
486 new_tab[i].shflags = 0;
487 new_tab[i].native = -1;
488# ifdef DEBUG
489 new_tab[i].dbgname = NULL;
490# endif
491 }
492
493 fdRet = pfdtab->size;
494 if (fdRet < fdMin)
495 fdRet = fdMin;
496
497 pfdtab->tab = new_tab;
498 pfdtab->size = new_size;
499 }
500
501 return fdRet;
502}
503
504/**
505 * Inserts the file into the descriptor table.
506 *
507 * If we're out of memory and cannot extend the table, we'll close the
508 * file, set errno to EMFILE and return -1.
509 *
510 * @returns The file descriptor number. -1 and errno on failure.
511 * @param pfdtab The file descriptor table.
512 * @param native The native file handle.
513 * @param oflags The flags the it was opened/created with.
514 * @param shflags The shell file flags.
515 * @param fdMin The minimum file descriptor number, pass -1 if any is ok.
516 * @param who Who we're doing this for (for logging purposes).
517 * @param dbgname The filename, if applicable/available.
518 */
519static int shfile_insert(shfdtab *pfdtab, intptr_t native, unsigned oflags, unsigned shflags, int fdMin,
520 const char *who, const char *dbgname)
521{
522 shmtxtmp tmp;
523 int fd;
524 int i;
525
526 /*
527 * Fend of bad stuff.
528 */
529 if (fdMin >= SHFILE_MAX)
530 {
531 TRACE2((NULL, "shfile_insert: fdMin=%d is out of bounds; native=%p %s\n", fdMin, native, dbgname));
532 shfile_native_close(native, NULL, K_FALSE);
533 errno = EMFILE;
534 return -1;
535 }
536# if K_OS != K_OS_WINDOWS
537 if (fcntl((int)native, F_SETFD, fcntl((int)native, F_GETFD, 0) | FD_CLOEXEC) == -1)
538 {
539 int e = errno;
540 TRACE2((NULL, "shfile_insert: F_SETFD failed %d; native=%p %s\n", e, native, dbgname));
541 close((int)native);
542 errno = e;
543 return -1;
544 }
545# endif
546
547 shmtx_enter(&pfdtab->mtx, &tmp);
548
549 /*
550 * Search for a fitting unused location.
551 */
552 fd = -1;
553 for (i = fdMin >= 0 ? fdMin : 0; (unsigned)i < pfdtab->size; i++)
554 if (pfdtab->tab[i].fd == -1)
555 {
556 fd = i;
557 break;
558 }
559 if (fd == -1)
560 fd = shfile_grow_tab_locked(pfdtab, fdMin);
561
562 /*
563 * Fill in the entry if we've found one.
564 */
565 if (fd != -1)
566 {
567 pfdtab->tab[fd].fd = fd;
568 pfdtab->tab[fd].oflags = oflags;
569 pfdtab->tab[fd].shflags = shflags;
570 pfdtab->tab[fd].native = native;
571#ifdef DEBUG
572 pfdtab->tab[fd].dbgname = dbgname ? sh_strdup(NULL, dbgname) : NULL;
573#endif
574 TRACE2((NULL, "shfile_insert: #%d: native=%p oflags=%#x shflags=%#x %s\n", fd, native, oflags, shflags, dbgname));
575 }
576 else
577 shfile_native_close(native, NULL, K_FALSE);
578
579 shmtx_leave(&pfdtab->mtx, &tmp);
580
581 if (fd == -1)
582 errno = EMFILE;
583 (void)who;
584 return fd;
585}
586
587# if K_OS != K_OS_WINDOWS
588/**
589 * Makes a copy of the native file, closes the original, and inserts the copy
590 * into the descriptor table.
591 *
592 * If we're out of memory and cannot extend the table, we'll close the
593 * file, set errno to EMFILE and return -1.
594 *
595 * @returns The file descriptor number. -1 and errno on failure.
596 * @param pfdtab The file descriptor table.
597 * @param pnative The native file handle on input, -1 on output.
598 * @param oflags The flags the it was opened/created with.
599 * @param shflags The shell file flags.
600 * @param fdMin The minimum file descriptor number, pass -1 if any is ok.
601 * @param who Who we're doing this for (for logging purposes).
602 * @param dbgname The filename, if applicable/available.
603 */
604static int shfile_copy_insert_and_close(shfdtab *pfdtab, int *pnative, unsigned oflags, unsigned shflags, int fdMin,
605 const char *who, const char *dbgname)
606{
607 int fd = -1;
608 int s = errno;
609 int native_copy = fcntl(*pnative, F_DUPFD, SHFILE_UNIX_MIN_FD);
610 close(*pnative);
611 *pnative = -1;
612 errno = s;
613
614 if (native_copy != -1)
615 fd = shfile_insert(pfdtab, native_copy, oflags, shflags, fdMin, who, dbgname);
616 return fd;
617}
618# endif /* !K_OS_WINDOWS */
619
620/**
621 * Gets a file descriptor and lock the file descriptor table.
622 *
623 * @returns Pointer to the file and table ownership on success,
624 * NULL and errno set to EBADF on failure.
625 * @param pfdtab The file descriptor table.
626 * @param fd The file descriptor number.
627 * @param ptmp See shmtx_enter.
628 */
629static shfile *shfile_get(shfdtab *pfdtab, int fd, shmtxtmp *ptmp)
630{
631 shfile *file = NULL;
632 if ( fd >= 0
633 && (unsigned)fd < pfdtab->size)
634 {
635 shmtx_enter(&pfdtab->mtx, ptmp);
636 if ((unsigned)fd < pfdtab->size
637 && pfdtab->tab[fd].fd != -1)
638 file = &pfdtab->tab[fd];
639 else
640 shmtx_leave(&pfdtab->mtx, ptmp);
641 }
642 if (!file)
643 errno = EBADF;
644 return file;
645}
646
647/**
648 * Puts back a file descriptor and releases the table ownership.
649 *
650 * @param pfdtab The file descriptor table.
651 * @param file The file.
652 * @param ptmp See shmtx_leave.
653 */
654static void shfile_put(shfdtab *pfdtab, shfile *file, shmtxtmp *ptmp)
655{
656 shmtx_leave(&pfdtab->mtx, ptmp);
657 kHlpAssert(file);
658 (void)file;
659}
660
661/**
662 * Constructs a path from the current directory and the passed in path.
663 *
664 * @returns 0 on success, -1 and errno set to ENAMETOOLONG or EINVAL on failure.
665 *
666 * @param pfdtab The file descriptor table
667 * @param path The path the caller supplied.
668 * @param buf Where to put the path. This is assumed to be SHFILE_MAX_PATH
669 * chars in size.
670 */
671int shfile_make_path(shfdtab *pfdtab, const char *path, char *buf)
672{
673 size_t path_len = strlen(path);
674 if (path_len == 0)
675 {
676 errno = EINVAL;
677 return -1;
678 }
679 if (path_len >= SHFILE_MAX_PATH)
680 {
681 errno = ENAMETOOLONG;
682 return -1;
683 }
684 if ( *path == '/'
685# if K_OS == K_OS_WINDOWS || K_OS == K_OS_OS2
686 || *path == '\\'
687 || ( *path
688 && path[1] == ':'
689 && ( (*path >= 'A' && *path <= 'Z')
690 || (*path >= 'a' && *path <= 'z')))
691# endif
692 )
693 {
694 memcpy(buf, path, path_len + 1);
695 }
696 else
697 {
698 size_t cwd_len;
699 shmtxtmp tmp;
700
701 shmtx_enter(&pfdtab->mtx, &tmp);
702
703 cwd_len = strlen(pfdtab->cwd);
704 memcpy(buf, pfdtab->cwd, cwd_len);
705
706 shmtx_leave(&pfdtab->mtx, &tmp);
707
708 if (cwd_len + path_len + 1 >= SHFILE_MAX_PATH)
709 {
710 errno = ENAMETOOLONG;
711 return -1;
712 }
713 if ( !cwd_len
714 || buf[cwd_len - 1] != '/')
715 buf[cwd_len++] = '/';
716 memcpy(buf + cwd_len, path, path_len + 1);
717 }
718
719# if K_OS == K_OS_WINDOWS || K_OS == K_OS_OS2
720 if (!strcmp(buf, "/dev/null"))
721 strcpy(buf, "NUL");
722# endif
723 return 0;
724}
725
726# if K_OS == K_OS_WINDOWS
727
728/**
729 * Adjusts the file name if it ends with a trailing directory slash.
730 *
731 * Windows APIs doesn't like trailing slashes.
732 *
733 * @returns 1 if it has a directory slash, 0 if not.
734 *
735 * @param abspath The path to adjust (SHFILE_MAX_PATH).
736 */
737static int shfile_trailing_slash_hack(char *abspath)
738{
739 /*
740 * Anything worth adjust here?
741 */
742 size_t path_len = strlen(abspath);
743 if ( path_len == 0
744 || ( abspath[path_len - 1] != '/'
745# if K_OS == K_OS_WINDOWS || K_OS == K_OS_OS2
746 && abspath[path_len - 1] != '\\'
747# endif
748 )
749 )
750 return 0;
751
752 /*
753 * Ok, make the adjustment.
754 */
755 if (path_len + 2 <= SHFILE_MAX_PATH)
756 {
757 /* Add a '.' to the end. */
758 abspath[path_len++] = '.';
759 abspath[path_len] = '\0';
760 }
761 else
762 {
763 /* No space for a dot, remove the slash if it's alone or just remove
764 one and add a dot like above. */
765 if ( abspath[path_len - 2] != '/'
766# if K_OS == K_OS_WINDOWS || K_OS == K_OS_OS2
767 && abspath[path_len - 2] != '\\'
768# endif
769 )
770 abspath[--path_len] = '\0';
771 else
772 abspath[path_len - 1] = '.';
773 }
774
775 return 1;
776}
777
778
779/**
780 * Converts a DOS(/Windows) error code to errno,
781 * assigning it to errno.
782 *
783 * @returns -1
784 * @param err The DOS error.
785 */
786static int shfile_dos2errno(int err)
787{
788 switch (err)
789 {
790 case ERROR_BAD_ENVIRONMENT: errno = E2BIG; break;
791 case ERROR_ACCESS_DENIED: errno = EACCES; break;
792 case ERROR_CURRENT_DIRECTORY: errno = EACCES; break;
793 case ERROR_LOCK_VIOLATION: errno = EACCES; break;
794 case ERROR_NETWORK_ACCESS_DENIED: errno = EACCES; break;
795 case ERROR_CANNOT_MAKE: errno = EACCES; break;
796 case ERROR_FAIL_I24: errno = EACCES; break;
797 case ERROR_DRIVE_LOCKED: errno = EACCES; break;
798 case ERROR_SEEK_ON_DEVICE: errno = EACCES; break;
799 case ERROR_NOT_LOCKED: errno = EACCES; break;
800 case ERROR_LOCK_FAILED: errno = EACCES; break;
801 case ERROR_NO_PROC_SLOTS: errno = EAGAIN; break;
802 case ERROR_MAX_THRDS_REACHED: errno = EAGAIN; break;
803 case ERROR_NESTING_NOT_ALLOWED: errno = EAGAIN; break;
804 case ERROR_INVALID_HANDLE: errno = EBADF; break;
805 case ERROR_INVALID_TARGET_HANDLE: errno = EBADF; break;
806 case ERROR_DIRECT_ACCESS_HANDLE: errno = EBADF; break;
807 case ERROR_WAIT_NO_CHILDREN: errno = ECHILD; break;
808 case ERROR_CHILD_NOT_COMPLETE: errno = ECHILD; break;
809 case ERROR_FILE_EXISTS: errno = EEXIST; break;
810 case ERROR_ALREADY_EXISTS: errno = EEXIST; break;
811 case ERROR_INVALID_FUNCTION: errno = EINVAL; break;
812 case ERROR_INVALID_ACCESS: errno = EINVAL; break;
813 case ERROR_INVALID_DATA: errno = EINVAL; break;
814 case ERROR_INVALID_PARAMETER: errno = EINVAL; break;
815 case ERROR_NEGATIVE_SEEK: errno = EINVAL; break;
816 case ERROR_TOO_MANY_OPEN_FILES: errno = EMFILE; break;
817 case ERROR_FILE_NOT_FOUND: errno = ENOENT; break;
818 case ERROR_PATH_NOT_FOUND: errno = ENOENT; break;
819 case ERROR_INVALID_DRIVE: errno = ENOENT; break;
820 case ERROR_NO_MORE_FILES: errno = ENOENT; break;
821 case ERROR_BAD_NETPATH: errno = ENOENT; break;
822 case ERROR_BAD_NET_NAME: errno = ENOENT; break;
823 case ERROR_BAD_PATHNAME: errno = ENOENT; break;
824 case ERROR_FILENAME_EXCED_RANGE: errno = ENOENT; break;
825 case ERROR_BAD_FORMAT: errno = ENOEXEC; break;
826 case ERROR_ARENA_TRASHED: errno = ENOMEM; break;
827 case ERROR_NOT_ENOUGH_MEMORY: errno = ENOMEM; break;
828 case ERROR_INVALID_BLOCK: errno = ENOMEM; break;
829 case ERROR_NOT_ENOUGH_QUOTA: errno = ENOMEM; break;
830 case ERROR_DISK_FULL: errno = ENOSPC; break;
831 case ERROR_DIR_NOT_EMPTY: errno = ENOTEMPTY; break;
832 case ERROR_BROKEN_PIPE: errno = EPIPE; break;
833 case ERROR_NOT_SAME_DEVICE: errno = EXDEV; break;
834 default: errno = EINVAL; break;
835 }
836 return -1;
837}
838
839/**
840 * Converts an NT status code to errno,
841 * assigning it to errno.
842 *
843 * @returns -1
844 * @param rcNt The NT status code.
845 */
846static int shfile_nt2errno(NTSTATUS rcNt)
847{
848 switch (rcNt)
849 {
850 default: errno = EINVAL; break;
851 }
852 return -1;
853}
854
855DWORD shfile_query_handle_access_mask(HANDLE h, PACCESS_MASK pMask)
856{
857 MY_OBJECT_BASIC_INFORMATION BasicInfo;
858 NTSTATUS rcNt;
859
860 if (!g_pfnNtQueryObject)
861 return ERROR_NOT_SUPPORTED;
862
863 rcNt = g_pfnNtQueryObject(h, MY_ObjectBasicInformation, &BasicInfo, sizeof(BasicInfo), NULL);
864 if (rcNt >= 0)
865 {
866 *pMask = BasicInfo.GrantedAccess;
867 return NO_ERROR;
868 }
869 if (rcNt != STATUS_INVALID_HANDLE)
870 return ERROR_GEN_FAILURE;
871 return ERROR_INVALID_HANDLE;
872}
873
874# endif /* K_OS == K_OS_WINDOWS */
875
876#endif /* SHFILE_IN_USE */
877
878/**
879 * Converts DOS slashes to UNIX slashes if necessary.
880 *
881 * @param pszPath The path to fix.
882 */
883K_INLINE void shfile_fix_slashes(char *pszPath)
884{
885#if K_OS == K_OS_WINDOWS || K_OS == K_OS_OS2
886 while ((pszPath = strchr(pszPath, '\\')))
887 *pszPath++ = '/';
888#else
889 (void)pszPath;
890#endif
891}
892
893/**
894 * Initializes the global variables in this file.
895 */
896static void shfile_init_globals(void)
897{
898#if K_OS == K_OS_WINDOWS
899 if (!g_shfile_globals_initialized)
900 {
901 HMODULE hNtDll = GetModuleHandle("NTDLL");
902 g_pfnNtQueryObject = (PFN_NtQueryObject) GetProcAddress(hNtDll, "NtQueryObject");
903 g_pfnNtQueryDirectoryFile = (PFN_NtQueryDirectoryFile)GetProcAddress(hNtDll, "NtQueryDirectoryFile");
904 g_pfnRtlUnicodeStringToAnsiString = (PFN_RtlUnicodeStringToAnsiString)GetProcAddress(hNtDll, "RtlUnicodeStringToAnsiString");
905 if ( !g_pfnRtlUnicodeStringToAnsiString
906 || !g_pfnNtQueryDirectoryFile)
907 {
908 /* fatal error */
909 }
910
911# ifdef KASH_ASYNC_CLOSE_HANDLE
912 /*
913 * Init the async CloseHandle state.
914 */
915 shmtx_init(&g_shfile_async_close.mtx);
916 g_shfile_async_close.evt_workers = CreateEventW(NULL, FALSE /*fManualReset*/, FALSE /*fInitialState*/, NULL /*pwszName*/);
917 g_shfile_async_close.evt_sync = CreateEventW(NULL, TRUE /*fManualReset*/, FALSE /*fInitialState*/, NULL /*pwszName*/);
918 if ( !g_shfile_async_close.evt_workers
919 || !g_shfile_async_close.evt_sync)
920 {
921 fprintf(stderr, "fatal error: CreateEventW failed: %u\n", GetLastError());
922 _exit(19);
923 }
924 g_shfile_async_close.idx_read = 0;
925 g_shfile_async_close.idx_write = 0;
926 g_shfile_async_close.num_pending = 0;
927 g_shfile_async_close.terminate_threads = K_FALSE;
928 g_shfile_async_close.signal_sync = K_FALSE;
929 g_shfile_async_close.num_threads = 0;
930 {
931 unsigned i = K_ELEMENTS(g_shfile_async_close.handles);
932 while (i-- > 0)
933 g_shfile_async_close.handles[i] = NULL;
934 i = K_ELEMENTS(g_shfile_async_close.threads);
935 while (i-- > 0)
936 g_shfile_async_close.threads[i] = NULL;
937 }
938# endif
939
940 g_shfile_globals_initialized = 1;
941 }
942#endif
943}
944
945/**
946 * Initializes a file descriptor table.
947 *
948 * @returns 0 on success, -1 and errno on failure.
949 * @param pfdtab The table to initialize.
950 * @param inherit File descriptor table to inherit from. If not specified
951 * we will inherit from the current process as it were.
952 */
953int shfile_init(shfdtab *pfdtab, shfdtab *inherit)
954{
955 int rc;
956
957 shfile_init_globals();
958
959 pfdtab->cwd = NULL;
960 pfdtab->size = 0;
961 pfdtab->tab = NULL;
962 rc = shmtx_init(&pfdtab->mtx);
963 if (!rc)
964 {
965#ifdef SHFILE_IN_USE
966 /* Get CWD with unix slashes. */
967 if (!inherit)
968 {
969 char buf[SHFILE_MAX_PATH];
970 if (getcwd(buf, sizeof(buf)))
971 {
972 shfile_fix_slashes(buf);
973 pfdtab->cwd = sh_strdup(NULL, buf);
974 }
975 if (pfdtab->cwd)
976 {
977# if K_OS == K_OS_WINDOWS
978 static const struct
979 {
980 DWORD dwStdHandle;
981 unsigned fFlags;
982 } aStdHandles[3] =
983 {
984 { STD_INPUT_HANDLE, _O_RDONLY },
985 { STD_OUTPUT_HANDLE, _O_WRONLY },
986 { STD_ERROR_HANDLE, _O_WRONLY }
987 };
988 int i;
989 STARTUPINFO Info;
990 ACCESS_MASK Mask;
991 DWORD dwErr;
992
993 rc = 0;
994
995 /* Try pick up the Visual C++ CRT file descriptor info. */
996 __try {
997 GetStartupInfo(&Info);
998 } __except (EXCEPTION_EXECUTE_HANDLER) {
999 memset(&Info, 0, sizeof(Info));
1000 }
1001
1002 if ( Info.cbReserved2 > sizeof(int)
1003 && (uintptr_t)Info.lpReserved2 >= 0x1000
1004 && (i = *(int *)Info.lpReserved2) >= 1
1005 && i <= 2048
1006 && ( Info.cbReserved2 == i * 5 + 4
1007 //|| Info.cbReserved2 == i * 5 + 1 - check the cygwin sources.
1008 || Info.cbReserved2 == i * 9 + 4))
1009 {
1010 uint8_t *paf = (uint8_t *)Info.lpReserved2 + sizeof(int);
1011 int dwPerH = 1 + (Info.cbReserved2 == i * 9 + 4);
1012 DWORD *ph = (DWORD *)(paf + i) + dwPerH * i;
1013 HANDLE aStdHandles2[3];
1014 int j;
1015
1016 //if (Info.cbReserved2 == i * 5 + 1) - check the cygwin sources.
1017 // i--;
1018
1019 for (j = 0; j < 3; j++)
1020 aStdHandles2[j] = GetStdHandle(aStdHandles[j].dwStdHandle);
1021
1022 while (i-- > 0)
1023 {
1024 ph -= dwPerH;
1025
1026 if ( (paf[i] & (FOPEN | FNOINHERIT)) == FOPEN
1027 && *ph != (uint32_t)INVALID_HANDLE_VALUE)
1028 {
1029 HANDLE h = (HANDLE)(intptr_t)*ph;
1030 int fd2;
1031 int fFlags;
1032 int fFlags2;
1033
1034 if ( h == aStdHandles2[j = 0]
1035 || h == aStdHandles2[j = 1]
1036 || h == aStdHandles2[j = 2])
1037 fFlags = aStdHandles[j].fFlags;
1038 else
1039 {
1040 dwErr = shfile_query_handle_access_mask(h, &Mask);
1041 if (dwErr == ERROR_INVALID_HANDLE)
1042 continue;
1043 else if (dwErr == NO_ERROR)
1044 {
1045 fFlags = 0;
1046 if ( (Mask & (GENERIC_READ | FILE_READ_DATA))
1047 && (Mask & (GENERIC_WRITE | FILE_WRITE_DATA | FILE_APPEND_DATA)))
1048 fFlags |= O_RDWR;
1049 else if (Mask & (GENERIC_READ | FILE_READ_DATA))
1050 fFlags |= O_RDONLY;
1051 else if (Mask & (GENERIC_WRITE | FILE_WRITE_DATA | FILE_APPEND_DATA))
1052 fFlags |= O_WRONLY;
1053 else
1054 fFlags |= O_RDWR;
1055 if ((Mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) == FILE_APPEND_DATA)
1056 fFlags |= O_APPEND;
1057 }
1058 else
1059 fFlags = O_RDWR;
1060 }
1061
1062 if (paf[i] & FPIPE)
1063 fFlags2 = SHFILE_FLAGS_PIPE;
1064 else if (paf[i] & FDEV)
1065 fFlags2 = SHFILE_FLAGS_TTY;
1066 else
1067 fFlags2 = 0;
1068
1069 fd2 = shfile_insert(pfdtab, (intptr_t)h, fFlags, fFlags2, i, "shtab_init", NULL);
1070 kHlpAssert(fd2 == i); (void)fd2;
1071 if (fd2 != i)
1072 rc = -1;
1073 }
1074 }
1075 }
1076
1077 /* Check the three standard handles. */
1078 for (i = 0; i < 3; i++)
1079 if ( (unsigned)i >= pfdtab->size
1080 || pfdtab->tab[i].fd == -1)
1081 {
1082 HANDLE hFile = GetStdHandle(aStdHandles[i].dwStdHandle);
1083 if (hFile != INVALID_HANDLE_VALUE)
1084 {
1085 DWORD dwType = GetFileType(hFile);
1086 unsigned fFlags = aStdHandles[i].fFlags;
1087 unsigned fFlags2;
1088 int fd2;
1089 if (dwType == FILE_TYPE_CHAR)
1090 fFlags2 = SHFILE_FLAGS_TTY;
1091 else if (dwType == FILE_TYPE_PIPE)
1092 fFlags2 = SHFILE_FLAGS_PIPE;
1093 else
1094 fFlags2 = SHFILE_FLAGS_FILE;
1095 fd2 = shfile_insert(pfdtab, (intptr_t)hFile, fFlags, fFlags2, i, "shtab_init", NULL);
1096 kHlpAssert(fd2 == i); (void)fd2;
1097 if (fd2 != i)
1098 rc = -1;
1099 }
1100 }
1101# else
1102 /*
1103 * Annoying...
1104 */
1105 int fd;
1106
1107 for (fd = 0; fd < 10; fd++)
1108 {
1109 int oflags = fcntl(fd, F_GETFL, 0);
1110 if (oflags != -1)
1111 {
1112 int cox = fcntl(fd, F_GETFD, 0);
1113 struct stat st;
1114 if ( cox != -1
1115 && fstat(fd, &st) != -1)
1116 {
1117 int native;
1118 int fd2;
1119 int fFlags2 = 0;
1120 if (cox & FD_CLOEXEC)
1121 fFlags2 |= SHFILE_FLAGS_CLOSE_ON_EXEC;
1122 if (S_ISREG(st.st_mode))
1123 fFlags2 |= SHFILE_FLAGS_FILE;
1124 else if (S_ISDIR(st.st_mode))
1125 fFlags2 |= SHFILE_FLAGS_DIR;
1126 else if (S_ISCHR(st.st_mode))
1127 fFlags2 |= SHFILE_FLAGS_TTY;
1128 else if (S_ISFIFO(st.st_mode))
1129 fFlags2 |= SHFILE_FLAGS_PIPE;
1130 else
1131 fFlags2 |= SHFILE_FLAGS_TTY;
1132
1133 native = fcntl(fd, F_DUPFD, SHFILE_UNIX_MIN_FD);
1134 if (native == -1)
1135 native = fd;
1136 fd2 = shfile_insert(pfdtab, native, oflags, fFlags2, fd, "shtab_init", NULL);
1137 kHlpAssert(fd2 == fd); (void)fd2;
1138 if (fd2 != fd)
1139 rc = -1;
1140 if (native != fd)
1141 close(fd);
1142 }
1143 }
1144 }
1145
1146# endif
1147 }
1148 else
1149 rc = -1;
1150 }
1151 else
1152 {
1153 /*
1154 * Inherit from parent shell's file table.
1155 */
1156 shfile const *src;
1157 shfile *dst;
1158 shmtxtmp tmp;
1159 unsigned fdcount;
1160 unsigned fd;
1161
1162 shmtx_enter(&inherit->mtx, &tmp);
1163
1164 /* allocate table and cwd: */
1165 fdcount = inherit->size;
1166 pfdtab->tab = dst = (shfile *)(fdcount ? sh_calloc(NULL, sizeof(pfdtab->tab[0]), fdcount) : NULL);
1167 pfdtab->cwd = sh_strdup(NULL, inherit->cwd);
1168 if ( pfdtab->cwd
1169 && (pfdtab->tab || fdcount == 0))
1170 {
1171 /* duplicate table entries: */
1172 for (fd = 0, src = inherit->tab; fd < fdcount; fd++, src++, dst++)
1173 if (src->fd == -1)
1174 dst->native = dst->fd = -1;
1175 else
1176 {
1177# if K_OS == K_OS_WINDOWS
1178# ifdef SH_FORKED_MODE
1179 KBOOL const cox = !!(src->shflags & SHFILE_FLAGS_CLOSE_ON_EXEC);
1180# else
1181 KBOOL const cox = K_TRUE;
1182# endif
1183# endif
1184 *dst = *src;
1185# ifdef DEBUG
1186 if (src->dbgname)
1187 dst->dbgname = sh_strdup(NULL, src->dbgname);
1188# endif
1189# if K_OS == K_OS_WINDOWS
1190 if (DuplicateHandle(GetCurrentProcess(),
1191 (HANDLE)src->native,
1192 GetCurrentProcess(),
1193 (HANDLE *)&dst->native,
1194 0,
1195 FALSE /* bInheritHandle */,
1196 DUPLICATE_SAME_ACCESS))
1197 TRACE2((NULL, "shfile_init: %d (%#x, %#x) %p (was %p)\n",
1198 dst->fd, dst->oflags, dst->shflags, dst->native, src->native));
1199 else
1200 {
1201 dst->native = (intptr_t)INVALID_HANDLE_VALUE;
1202 rc = shfile_dos2errno(GetLastError());
1203 TRACE2((NULL, "shfile_init: %d (%#x, %#x) %p - failed %d / %u!\n",
1204 dst->fd, dst->oflags, dst->shflags, src->native, rc, GetLastError()));
1205 break;
1206 }
1207
1208# 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 */
1209 dst->native = dup3(src->native, -1, cox ? O_CLOEXEC : 0);
1210# else
1211 if (cox)
1212 {
1213# ifndef SH_FORKED_MODE
1214 shmtxtmp tmp2;
1215 shmtx_enter(&global_exec_something, &tmp)
1216# endif
1217 dst->native = dup2(src->native, -1);
1218 if (dst->native >= 0)
1219 rc = fcntl(dst->native, F_SETFD, FD_CLOEXEC);
1220# ifndef SH_FORKED_MODE
1221 shmtx_leave(&global_exec_something, &tmp)
1222# endif
1223 if (rc != 0)
1224 break;
1225 }
1226 else
1227 dst->native = dup2(src->native, -1);
1228 if (dst->native < 0)
1229 {
1230 rc = -1;
1231 break;
1232 }
1233# endif
1234 }
1235 }
1236 else
1237 rc = -1;
1238 pfdtab->size = fd;
1239 shmtx_leave(&inherit->mtx, &tmp);
1240 } /* inherit != NULL */
1241#endif
1242 }
1243 return rc;
1244}
1245
1246/**
1247 * Deletes the file descriptor table.
1248 *
1249 * Safe to call more than once.
1250 */
1251void shfile_uninit(shfdtab *pfdtab, int tracefd)
1252{
1253 if (!pfdtab)
1254 return;
1255
1256 if (pfdtab->tab)
1257 {
1258 unsigned left = pfdtab->size;
1259 struct shfile *pfd = pfdtab->tab;
1260 unsigned tracefdfound = 0;
1261 while (left-- > 0)
1262 {
1263 if (pfd->fd != -1)
1264 {
1265 if (pfd->fd != tracefd)
1266 {
1267#if K_OS == K_OS_WINDOWS
1268 BOOL rc = CloseHandle((HANDLE)pfd->native);
1269 kHlpAssert(rc == TRUE); K_NOREF(rc);
1270#else
1271 int rc = close((int)pfd->native);
1272 kHlpAssert(rc == 0); K_NOREF(rc);
1273#endif
1274 pfd->fd = -1;
1275 pfd->native = -1;
1276 }
1277 else
1278 tracefdfound++; /* there is only the one */
1279 }
1280 pfd++;
1281 }
1282
1283 if (!tracefdfound)
1284 { /* likely */ }
1285 else
1286 return;
1287
1288 sh_free(NULL, pfdtab->tab);
1289 pfdtab->tab = NULL;
1290 }
1291
1292 shmtx_delete(&pfdtab->mtx);
1293
1294 sh_free(NULL, pfdtab->cwd);
1295 pfdtab->cwd = NULL;
1296}
1297
1298#if K_OS == K_OS_WINDOWS && defined(SHFILE_IN_USE)
1299
1300/**
1301 * Changes the inheritability of a file descriptor, taking console handles into
1302 * account.
1303 *
1304 * @note This MAY change the native handle for the entry.
1305 *
1306 * @returns The native handle.
1307 * @param pfd The file descriptor to change.
1308 * @param set If set, make child processes inherit the handle, if clear
1309 * make them not inherit it.
1310 */
1311static HANDLE shfile_set_inherit_win(shfile *pfd, int set)
1312{
1313 HANDLE hFile = (HANDLE)pfd->native;
1314 if (!SetHandleInformation(hFile, HANDLE_FLAG_INHERIT, set ? HANDLE_FLAG_INHERIT : 0))
1315 {
1316 /* SetHandleInformation doesn't work for console handles,
1317 so we have to duplicate the handle to change the
1318 inheritability. */
1319 DWORD err = GetLastError();
1320 if ( err == ERROR_INVALID_PARAMETER
1321 && DuplicateHandle(GetCurrentProcess(),
1322 hFile,
1323 GetCurrentProcess(),
1324 &hFile,
1325 0,
1326 set ? TRUE : FALSE /* bInheritHandle */,
1327 DUPLICATE_SAME_ACCESS))
1328 {
1329 TRACE2((NULL, "shfile_set_inherit_win: %p -> %p (set=%d)\n", pfd->native, hFile, set));
1330 if (!CloseHandle((HANDLE)pfd->native))
1331 kHlpAssert(0);
1332 pfd->native = (intptr_t)hFile;
1333 }
1334 else
1335 {
1336 err = GetLastError();
1337 kHlpAssert(0);
1338 hFile = (HANDLE)pfd->native;
1339 }
1340 }
1341 return hFile;
1342}
1343
1344# ifdef SH_FORKED_MODE
1345/**
1346 * Helper for shfork.
1347 *
1348 * @param pfdtab The file descriptor table.
1349 * @param set Whether to make all handles inheritable (1) or
1350 * to restore them to the rigth state (0).
1351 * @param hndls Where to store the three standard handles.
1352 */
1353void shfile_fork_win(shfdtab *pfdtab, int set, intptr_t *hndls)
1354{
1355 shmtxtmp tmp;
1356 unsigned i;
1357
1358 shmtx_enter(&pfdtab->mtx, &tmp);
1359 TRACE2((NULL, "shfile_fork_win: set=%d\n", set));
1360
1361 i = pfdtab->size;
1362 while (i-- > 0)
1363 {
1364 if (pfdtab->tab[i].fd == i)
1365 {
1366 shfile_set_inherit_win(&pfdtab->tab[i], set);
1367 if (set)
1368 TRACE2((NULL, " #%d: native=%#x oflags=%#x shflags=%#x\n",
1369 i, pfdtab->tab[i].native, pfdtab->tab[i].oflags, pfdtab->tab[i].shflags));
1370 }
1371 }
1372
1373 if (hndls)
1374 {
1375 for (i = 0; i < 3; i++)
1376 {
1377 if ( pfdtab->size > i
1378 && pfdtab->tab[i].fd == i)
1379 hndls[i] = pfdtab->tab[i].native;
1380 else
1381 hndls[i] = (intptr_t)INVALID_HANDLE_VALUE;
1382 TRACE2((NULL, "shfile_fork_win: i=%d size=%d fd=%d native=%d hndls[%d]=%p\n",
1383 i, pfdtab->size, pfdtab->tab[i].fd, pfdtab->tab[i].native, i, hndls[i]));
1384 }
1385 }
1386
1387 shmtx_leave(&pfdtab->mtx, &tmp);
1388}
1389# endif /* SH_FORKED_MODE */
1390
1391/** shfile_exec_win helper that make sure there are no _O_APPEND handles. */
1392static KBOOL shfile_exec_win_no_append(shfdtab *pfdtab, unsigned count)
1393{
1394 unsigned i;
1395 for (i = 0; i < count; i++)
1396 if ( (pfdtab->tab[i].oflags & _O_APPEND)
1397 && (pfdtab->tab[i].oflags & (_O_WRONLY | _O_RDWR)))
1398 return K_FALSE;
1399 return K_TRUE;
1400}
1401
1402/**
1403 * Helper for sh_execve.
1404 *
1405 * This is called before and after CreateProcess. On the first call it
1406 * will mark the non-close-on-exec handles as inheritable and produce
1407 * the startup info for the CRT. On the second call, after CreateProcess,
1408 * it will restore the handle inheritability properties.
1409 *
1410 * @returns 0 on success, non-zero on failure.
1411 * @param pfdtab The file descriptor table.
1412 * @param prepare Which call, 1 if before, 0 if after and success, -1 if after on failure.
1413 * @param info The info structure.
1414 */
1415int shfile_exec_win(shfdtab *pfdtab, int prepare, shfdexecwin *info)
1416{
1417 STARTUPINFOA *strtinfo = (STARTUPINFOA *)info->strtinfo;
1418 int rc = 0;
1419 shmtxtmp tmp;
1420 unsigned count;
1421 unsigned i;
1422
1423 shmtx_enter(&pfdtab->mtx, &tmp);
1424 TRACE2((NULL, "shfile_exec_win: prepare=%p\n", prepare));
1425
1426 count = pfdtab->size < (0x10000-4) / (1 + sizeof(HANDLE))
1427 ? pfdtab->size
1428 : (0x10000-4) / (1 + sizeof(HANDLE));
1429 while ( count > 3
1430 && ( pfdtab->tab[count - 1].fd == -1
1431 || (pfdtab->tab[count - 1].shflags & SHFILE_FLAGS_CLOSE_ON_EXEC)))
1432 count--;
1433
1434 if (prepare > 0)
1435 {
1436 if (count <= 3 && shfile_exec_win_no_append(pfdtab, count))
1437 {
1438 info->inherithandles = 0;
1439 info->startsuspended = 1;
1440 strtinfo->cbReserved2 = 0;
1441 strtinfo->lpReserved2 = NULL;
1442 }
1443 else
1444 {
1445 size_t cbData = sizeof(int) + count * (1 + sizeof(HANDLE));
1446 uint8_t *pbData = sh_malloc(shthread_get_shell(), cbData);
1447 uint8_t *paf = pbData + sizeof(int);
1448 HANDLE *pah = (HANDLE *)(paf + count);
1449
1450 info->inherithandles = 1;
1451# ifdef KASH_ASYNC_CLOSE_HANDLE
1452 info->startsuspended = g_shfile_async_close.num_pending > 0;
1453# else
1454 info->startsuspended = 0;
1455# endif
1456 strtinfo->cbReserved2 = (unsigned short)cbData;
1457 strtinfo->lpReserved2 = pbData;
1458
1459# ifndef SH_FORKED_MODE
1460 shmtx_leave(&pfdtab->mtx, &tmp); /* should be harmless as this isn't really necessary at all. */
1461 shmtx_enter(&g_sh_exec_inherit_mtx, &info->tmp);
1462 shmtx_enter(&pfdtab->mtx, &tmp);
1463# endif
1464
1465 *(int *)pbData = count;
1466
1467 i = count;
1468 while (i-- > 0)
1469 {
1470 if ( pfdtab->tab[i].fd == i
1471 && !(pfdtab->tab[i].shflags & SHFILE_FLAGS_CLOSE_ON_EXEC))
1472 {
1473 HANDLE hFile = shfile_set_inherit_win(&pfdtab->tab[i], 1);
1474 TRACE2((NULL, " #%d: native=%#x oflags=%#x shflags=%#x\n",
1475 i, hFile, pfdtab->tab[i].oflags, pfdtab->tab[i].shflags));
1476 paf[i] = FOPEN;
1477 if (pfdtab->tab[i].oflags & _O_APPEND)
1478 paf[i] |= FAPPEND;
1479 if (pfdtab->tab[i].oflags & _O_TEXT)
1480 paf[i] |= FTEXT;
1481 switch (pfdtab->tab[i].shflags & SHFILE_FLAGS_TYPE_MASK)
1482 {
1483 case SHFILE_FLAGS_TTY: paf[i] |= FDEV; break;
1484 case SHFILE_FLAGS_PIPE: paf[i] |= FPIPE; break;
1485 }
1486 pah[i] = hFile;
1487 }
1488 else
1489 {
1490 paf[i] = 0;
1491 pah[i] = INVALID_HANDLE_VALUE;
1492 }
1493 }
1494 }
1495
1496 for (i = 0; i < 3; i++)
1497 {
1498 if ( i < count
1499 && pfdtab->tab[i].fd == i)
1500 {
1501 info->replacehandles[i] = 1;
1502 info->handles[i] = pfdtab->tab[i].native;
1503 }
1504 else
1505 {
1506 info->replacehandles[i] = 0;
1507 info->handles[i] = (intptr_t)INVALID_HANDLE_VALUE;
1508 }
1509 TRACE2((NULL, "shfile_exec_win: i=%d count=%d fd=%d native=%d hndls[%d]=\n",
1510 i, count, pfdtab->tab[i].fd, pfdtab->tab[i].native, i, info->handles[i]));
1511 }
1512 }
1513 else
1514 {
1515 shfile *file = pfdtab->tab;
1516
1517 sh_free(NULL, strtinfo->lpReserved2);
1518 strtinfo->lpReserved2 = NULL;
1519
1520 i = count;
1521 if (prepare == 0)
1522 for (i = 0; i < count; i++, file++)
1523 {
1524 if ( file->fd == i
1525 && !(file->shflags & SHFILE_FLAGS_TRACE))
1526 {
1527 shfile_native_close(file->native, file, info->inherithandles);
1528
1529 file->fd = -1;
1530 file->oflags = 0;
1531 file->shflags = 0;
1532 file->native = -1;
1533# ifdef DEBUG
1534 sh_free(NULL, file->dbgname);
1535 file->dbgname = NULL;
1536# endif
1537 }
1538 }
1539 else if (info->inherithandles)
1540 for (i = 0; i < count; i++, file++)
1541 if ( file->fd == i
1542 && !(file->shflags & SHFILE_FLAGS_CLOSE_ON_EXEC))
1543 shfile_set_inherit_win(file, 0);
1544
1545# ifndef SH_FORKED_MODE
1546 if (info->inherithandles)
1547 shmtx_leave(&g_sh_exec_inherit_mtx, &info->tmp);
1548# endif
1549 }
1550
1551 shmtx_leave(&pfdtab->mtx, &tmp);
1552 return rc;
1553}
1554
1555#endif /* K_OS_WINDOWS */
1556
1557#if K_OS != K_OS_WINDOWS
1558/**
1559 * Prepare file handles for inherting before a execve call.
1560 *
1561 * This is only used in the normal mode, so we've forked and need not worry
1562 * about cleaning anything up after us. Nor do we need think about locking.
1563 *
1564 * @returns 0 on success, -1 on failure.
1565 */
1566int shfile_exec_unix(shfdtab *pfdtab)
1567{
1568 int rc = 0;
1569# ifdef SHFILE_IN_USE
1570 unsigned fd;
1571
1572 for (fd = 0; fd < pfdtab->size; fd++)
1573 {
1574 if ( pfdtab->tab[fd].fd != -1
1575 && !(pfdtab->tab[fd].shflags & SHFILE_FLAGS_CLOSE_ON_EXEC) )
1576 {
1577 TRACE2((NULL, "shfile_exec_unix: %d => %d\n", pfdtab->tab[fd].native, fd));
1578 if (dup2(pfdtab->tab[fd].native, fd) < 0)
1579 {
1580 /* fatal_error(NULL, "shfile_exec_unix: failed to move %d to %d", pfdtab->tab[fd].fd, fd); */
1581 rc = -1;
1582 }
1583 }
1584 }
1585# endif
1586 return rc;
1587}
1588#endif /* !K_OS_WINDOWS */
1589
1590/**
1591 * open().
1592 */
1593int shfile_open(shfdtab *pfdtab, const char *name, unsigned flags, mode_t mode)
1594{
1595 int fd;
1596#ifdef SHFILE_IN_USE
1597 char absname[SHFILE_MAX_PATH];
1598# if K_OS == K_OS_WINDOWS
1599 HANDLE hFile;
1600 DWORD dwDesiredAccess;
1601 DWORD dwShareMode;
1602 DWORD dwCreationDisposition;
1603 DWORD dwFlagsAndAttributes;
1604 SECURITY_ATTRIBUTES SecurityAttributes;
1605
1606# ifndef _O_ACCMODE
1607# define _O_ACCMODE (_O_RDONLY|_O_WRONLY|_O_RDWR)
1608# endif
1609 switch (flags & (_O_ACCMODE | _O_APPEND))
1610 {
1611 case _O_RDONLY: dwDesiredAccess = GENERIC_READ; break;
1612 case _O_RDONLY | _O_APPEND: dwDesiredAccess = GENERIC_READ; break;
1613 case _O_WRONLY: dwDesiredAccess = GENERIC_WRITE; break;
1614 case _O_WRONLY | _O_APPEND: dwDesiredAccess = (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA); break;
1615 case _O_RDWR: dwDesiredAccess = GENERIC_READ | GENERIC_WRITE; break;
1616 case _O_RDWR | _O_APPEND: dwDesiredAccess = GENERIC_READ | (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA); break;
1617
1618 default:
1619 RETURN_ERROR(-1, EINVAL, "invalid mode");
1620 }
1621
1622 dwShareMode = FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE;
1623
1624 SecurityAttributes.nLength = sizeof(SecurityAttributes);
1625 SecurityAttributes.lpSecurityDescriptor = NULL;
1626 SecurityAttributes.bInheritHandle = FALSE;
1627
1628 if (flags & _O_CREAT)
1629 {
1630 if ((flags & (_O_EXCL | _O_TRUNC)) == (_O_EXCL | _O_TRUNC))
1631 RETURN_ERROR(-1, EINVAL, "_O_EXCL | _O_TRUNC");
1632
1633 if (flags & _O_TRUNC)
1634 dwCreationDisposition = CREATE_ALWAYS; /* not 100%, but close enough */
1635 else if (flags & _O_EXCL)
1636 dwCreationDisposition = CREATE_NEW;
1637 else
1638 dwCreationDisposition = OPEN_ALWAYS;
1639 }
1640 else if (flags & _O_TRUNC)
1641 dwCreationDisposition = TRUNCATE_EXISTING;
1642 else
1643 dwCreationDisposition = OPEN_EXISTING;
1644
1645 if (!(flags & _O_CREAT) || (mode & 0222))
1646 dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
1647 else
1648 dwFlagsAndAttributes = FILE_ATTRIBUTE_READONLY;
1649
1650 fd = shfile_make_path(pfdtab, name, &absname[0]);
1651 if (!fd)
1652 {
1653# ifdef DEBUG
1654 KU64 ns = shfile_nano_ts();
1655# endif
1656 SetLastError(0);
1657 hFile = CreateFileA(absname,
1658 dwDesiredAccess,
1659 dwShareMode,
1660 &SecurityAttributes,
1661 dwCreationDisposition,
1662 dwFlagsAndAttributes,
1663 NULL /* hTemplateFile */);
1664# ifdef DEBUG
1665 ns = shfile_nano_ts() - ns;
1666 if (ns > 1000000)
1667 TRACE2((NULL, "shfile_open: %u ns hFile=%p (%d) %s\n", ns, hFile, GetLastError(), absname));
1668# endif
1669 if (hFile != INVALID_HANDLE_VALUE)
1670 fd = shfile_insert(pfdtab, (intptr_t)hFile, flags, 0, -1, "shfile_open", absname);
1671 else
1672 fd = shfile_dos2errno(GetLastError());
1673 }
1674
1675# else /* K_OS != K_OS_WINDOWS */
1676 fd = shfile_make_path(pfdtab, name, &absname[0]);
1677 if (!fd)
1678 {
1679 fd = open(absname, flags, mode);
1680 if (fd != -1)
1681 fd = shfile_copy_insert_and_close(pfdtab, &fd, flags, 0, -1, "shfile_open", absname);
1682 }
1683
1684# endif /* K_OS != K_OS_WINDOWS */
1685
1686#else
1687 fd = open(name, flags, mode);
1688#endif
1689
1690 TRACE2((NULL, "shfile_open(%p:{%s}, %#x, 0%o) -> %d [%d]\n", name, name, flags, mode, fd, errno));
1691 return fd;
1692}
1693
1694int shfile_pipe(shfdtab *pfdtab, int fds[2])
1695{
1696 int rc = -1;
1697#ifdef SHFILE_IN_USE
1698# if K_OS == K_OS_WINDOWS
1699 HANDLE hRead = INVALID_HANDLE_VALUE;
1700 HANDLE hWrite = INVALID_HANDLE_VALUE;
1701 SECURITY_ATTRIBUTES SecurityAttributes;
1702
1703 SecurityAttributes.nLength = sizeof(SecurityAttributes);
1704 SecurityAttributes.lpSecurityDescriptor = NULL;
1705 SecurityAttributes.bInheritHandle = FALSE;
1706
1707 fds[1] = fds[0] = -1;
1708 if (CreatePipe(&hRead, &hWrite, &SecurityAttributes, SHFILE_PIPE_SIZE))
1709 {
1710 fds[0] = shfile_insert(pfdtab, (intptr_t)hRead, O_RDONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe", "pipe-rd");
1711 if (fds[0] != -1)
1712 {
1713 fds[1] = shfile_insert(pfdtab, (intptr_t)hWrite, O_WRONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe", "pipe-wr");
1714 if (fds[1] != -1)
1715 rc = 0;
1716 }
1717
1718# else
1719 int native_fds[2];
1720
1721 fds[1] = fds[0] = -1;
1722 if (!pipe(native_fds))
1723 {
1724 fds[0] = shfile_copy_insert_and_close(pfdtab, &native_fds[0], O_RDONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe", "pipe-rd");
1725 if (fds[0] != -1)
1726 {
1727 fds[1] = shfile_copy_insert_and_close(pfdtab, &native_fds[1], O_WRONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe", "pipe-wr");
1728 if (fds[1] != -1)
1729 rc = 0;
1730 }
1731# endif
1732 if (fds[1] == -1)
1733 {
1734 int s = errno;
1735 if (fds[0] != -1)
1736 {
1737 shmtxtmp tmp;
1738 shmtx_enter(&pfdtab->mtx, &tmp);
1739 rc = fds[0];
1740 pfdtab->tab[rc].fd = -1;
1741 pfdtab->tab[rc].oflags = 0;
1742 pfdtab->tab[rc].shflags = 0;
1743 pfdtab->tab[rc].native = -1;
1744 shmtx_leave(&pfdtab->mtx, &tmp);
1745 }
1746
1747# if K_OS == K_OS_WINDOWS
1748 CloseHandle(hRead);
1749 CloseHandle(hWrite);
1750# else
1751 close(native_fds[0]);
1752 close(native_fds[1]);
1753# endif
1754 fds[0] = fds[1] = -1;
1755 errno = s;
1756 rc = -1;
1757 }
1758 }
1759 else
1760 {
1761# if K_OS == K_OS_WINDOWS
1762 errno = shfile_dos2errno(GetLastError());
1763# endif
1764 rc = -1;
1765 }
1766
1767#else
1768 rc = pipe(fds);
1769#endif
1770
1771 TRACE2((NULL, "shfile_pipe() -> %d{%d,%d} [%d]\n", rc, fds[0], fds[1], errno));
1772 return rc;
1773}
1774
1775/**
1776 * dup().
1777 */
1778int shfile_dup(shfdtab *pfdtab, int fd)
1779{
1780 return shfile_fcntl(pfdtab,fd, F_DUPFD, 0);
1781}
1782
1783/**
1784 * Move the file descriptor, closing any existing descriptor at @a fdto.
1785 *
1786 * @returns fdto on success, -1 and errno on failure.
1787 * @param pfdtab The file descriptor table.
1788 * @param fdfrom The descriptor to move.
1789 * @param fdto Where to move it.
1790 */
1791int shfile_movefd(shfdtab *pfdtab, int fdfrom, int fdto)
1792{
1793#ifdef SHFILE_IN_USE
1794 int rc;
1795 shmtxtmp tmp;
1796 shfile *file = shfile_get(pfdtab, fdfrom, &tmp);
1797 if (file)
1798 {
1799 /* prepare the new entry */
1800 if ((unsigned)fdto >= pfdtab->size)
1801 shfile_grow_tab_locked(pfdtab, fdto);
1802 if ((unsigned)fdto < pfdtab->size)
1803 {
1804 if (pfdtab->tab[fdto].fd != -1)
1805 shfile_native_close(pfdtab->tab[fdto].native, &pfdtab->tab[fdto], K_FALSE);
1806
1807 /* setup the target. */
1808 pfdtab->tab[fdto].fd = fdto;
1809 pfdtab->tab[fdto].oflags = file->oflags;
1810 pfdtab->tab[fdto].shflags = file->shflags;
1811 pfdtab->tab[fdto].native = file->native;
1812# ifdef DEBUG
1813 pfdtab->tab[fdto].dbgname = file->dbgname;
1814# endif
1815
1816 /* close the source. */
1817 file->fd = -1;
1818 file->oflags = 0;
1819 file->shflags = 0;
1820 file->native = -1;
1821# ifdef DEBUG
1822 file->dbgname = NULL;
1823# endif
1824
1825 rc = fdto;
1826 }
1827 else
1828 {
1829 errno = EMFILE;
1830 rc = -1;
1831 }
1832
1833 shfile_put(pfdtab, file, &tmp);
1834 }
1835 else
1836 rc = -1;
1837 return rc;
1838
1839#else
1840 int fdnew = dup2(fdfrom, fdto);
1841 if (fdnew >= 0)
1842 close(fdfrom);
1843 return fdnew;
1844#endif
1845}
1846
1847/**
1848 * Move the file descriptor to somewhere at @a fdMin or above.
1849 *
1850 * @returns the new file descriptor success, -1 and errno on failure.
1851 * @param pfdtab The file descriptor table.
1852 * @param fdfrom The descriptor to move.
1853 * @param fdMin The minimum descriptor.
1854 */
1855int shfile_movefd_above(shfdtab *pfdtab, int fdfrom, int fdMin)
1856{
1857#ifdef SHFILE_IN_USE
1858 int fdto;
1859 shmtxtmp tmp;
1860 shfile *file = shfile_get(pfdtab, fdfrom, &tmp);
1861 if (file)
1862 {
1863 /* find a new place */
1864 int i;
1865 fdto = -1;
1866 for (i = fdMin; (unsigned)i < pfdtab->size; i++)
1867 if (pfdtab->tab[i].fd == -1)
1868 {
1869 fdto = i;
1870 break;
1871 }
1872 if (fdto == -1)
1873 fdto = shfile_grow_tab_locked(pfdtab, fdMin);
1874 if (fdto != -1)
1875 {
1876 /* setup the target. */
1877 pfdtab->tab[fdto].fd = fdto;
1878 pfdtab->tab[fdto].oflags = file->oflags;
1879 pfdtab->tab[fdto].shflags = file->shflags;
1880 pfdtab->tab[fdto].native = file->native;
1881# ifdef DEBUG
1882 pfdtab->tab[fdto].dbgname = file->dbgname;
1883# endif
1884
1885 /* close the source. */
1886 file->fd = -1;
1887 file->oflags = 0;
1888 file->shflags = 0;
1889 file->native = -1;
1890# ifdef DEBUG
1891 file->dbgname = NULL;
1892# endif
1893 }
1894 else
1895 {
1896 errno = EMFILE;
1897 fdto = -1;
1898 }
1899
1900 shfile_put(pfdtab, file, &tmp);
1901 }
1902 else
1903 fdto = -1;
1904 return fdto;
1905
1906#else
1907 int fdnew = fcntl(fdfrom, F_DUPFD, fdMin);
1908 if (fdnew >= 0)
1909 close(fdfrom);
1910 return fdnew;
1911#endif
1912}
1913
1914/**
1915 * close().
1916 */
1917int shfile_close(shfdtab *pfdtab, unsigned fd)
1918{
1919 int rc;
1920#ifdef SHFILE_IN_USE
1921 shmtxtmp tmp;
1922 shfile *file = shfile_get(pfdtab, fd, &tmp);
1923 if (file)
1924 {
1925 shfile_native_close(file->native, file, K_FALSE);
1926
1927 file->fd = -1;
1928 file->oflags = 0;
1929 file->shflags = 0;
1930 file->native = -1;
1931# ifdef DEBUG
1932 sh_free(NULL, file->dbgname);
1933 file->dbgname = NULL;
1934# endif
1935
1936 shfile_put(pfdtab, file, &tmp);
1937 rc = 0;
1938 }
1939 else
1940 rc = -1;
1941
1942#else
1943 rc = close(fd);
1944#endif
1945
1946 TRACE2((NULL, "shfile_close(%d) -> %d [%d]\n", fd, rc, errno));
1947 return rc;
1948}
1949
1950/**
1951 * read().
1952 */
1953long shfile_read(shfdtab *pfdtab, int fd, void *buf, size_t len)
1954{
1955 long rc;
1956#ifdef SHFILE_IN_USE
1957 shmtxtmp tmp;
1958 shfile *file = shfile_get(pfdtab, fd, &tmp);
1959 if (file)
1960 {
1961# if K_OS == K_OS_WINDOWS
1962 DWORD dwRead = 0;
1963 if (ReadFile((HANDLE)file->native, buf, (DWORD)len, &dwRead, NULL))
1964 rc = dwRead;
1965 else
1966 rc = shfile_dos2errno(GetLastError());
1967# else
1968 rc = read(file->native, buf, len);
1969# endif
1970
1971 shfile_put(pfdtab, file, &tmp);
1972 }
1973 else
1974 rc = -1;
1975
1976#else
1977 rc = read(fd, buf, len);
1978#endif
1979 return rc;
1980}
1981
1982/**
1983 * write().
1984 */
1985long shfile_write(shfdtab *pfdtab, int fd, const void *buf, size_t len)
1986{
1987 long rc;
1988#ifdef SHFILE_IN_USE
1989 shmtxtmp tmp;
1990 shfile *file = shfile_get(pfdtab, fd, &tmp);
1991 if (file)
1992 {
1993# if K_OS == K_OS_WINDOWS
1994 DWORD dwWritten = 0;
1995 if (WriteFile((HANDLE)file->native, buf, (DWORD)len, &dwWritten, NULL))
1996 rc = dwWritten;
1997 else
1998 rc = shfile_dos2errno(GetLastError());
1999# else
2000 rc = write(file->native, buf, len);
2001# endif
2002
2003 file->shflags |= SHFILE_FLAGS_DIRTY; /* there should be no concurrent access, so this is safe. */
2004 shfile_put(pfdtab, file, &tmp);
2005 }
2006 else
2007 rc = -1;
2008
2009# ifdef DEBUG
2010 if (fd != shthread_get_shell()->tracefd)
2011 TRACE2((NULL, "shfile_write(%d,,%d) -> %d [%d]\n", fd, len, rc, errno));
2012# endif
2013
2014#else
2015 if (fd != shthread_get_shell()->tracefd)
2016 {
2017 int iSavedErrno = errno;
2018 struct stat s;
2019 int x;
2020 x = fstat(fd, &s);
2021 TRACE2((NULL, "shfile_write(%d) - %lu bytes (%d) - pos %lu - before; %o\n",
2022 fd, (long)s.st_size, x, (long)lseek(fd, 0, SEEK_CUR), s.st_mode ));
2023 K_NOREF(x);
2024 errno = iSavedErrno;
2025 }
2026
2027 rc = write(fd, buf, len);
2028#endif
2029 return rc;
2030}
2031
2032/**
2033 * lseek().
2034 */
2035long shfile_lseek(shfdtab *pfdtab, int fd, long off, int whench)
2036{
2037 long rc;
2038#ifdef SHFILE_IN_USE
2039 shmtxtmp tmp;
2040 shfile *file = shfile_get(pfdtab, fd, &tmp);
2041 if (file)
2042 {
2043# if K_OS == K_OS_WINDOWS
2044 kHlpAssert(SEEK_SET == FILE_BEGIN);
2045 kHlpAssert(SEEK_CUR == FILE_CURRENT);
2046 kHlpAssert(SEEK_END == FILE_END);
2047 rc = SetFilePointer((HANDLE)file->native, off, NULL, whench);
2048 if (rc == INVALID_SET_FILE_POINTER)
2049 rc = shfile_dos2errno(GetLastError());
2050# else
2051 rc = lseek(file->native, off, whench);
2052# endif
2053
2054 shfile_put(pfdtab, file, &tmp);
2055 }
2056 else
2057 rc = -1;
2058
2059#else
2060 rc = lseek(fd, off, whench);
2061#endif
2062
2063 return rc;
2064}
2065
2066int shfile_fcntl(shfdtab *pfdtab, int fd, int cmd, int arg)
2067{
2068 int rc;
2069#ifdef SHFILE_IN_USE
2070 shmtxtmp tmp;
2071 shfile *file = shfile_get(pfdtab, fd, &tmp);
2072 if (file)
2073 {
2074 switch (cmd)
2075 {
2076 case F_GETFL:
2077 rc = file->oflags;
2078 break;
2079
2080 case F_SETFL:
2081 {
2082 unsigned mask = O_NONBLOCK | O_APPEND | O_BINARY | O_TEXT;
2083# ifdef O_DIRECT
2084 mask |= O_DIRECT;
2085# endif
2086# ifdef O_ASYNC
2087 mask |= O_ASYNC;
2088# endif
2089# ifdef O_SYNC
2090 mask |= O_SYNC;
2091# endif
2092 if ((file->oflags & mask) == (arg & mask))
2093 rc = 0;
2094 else
2095 {
2096# if K_OS == K_OS_WINDOWS
2097 kHlpAssert(0);
2098 errno = EINVAL;
2099 rc = -1;
2100# else
2101 rc = fcntl(file->native, F_SETFL, arg);
2102 if (rc != -1)
2103 file->oflags = (file->oflags & ~mask) | (arg & mask);
2104# endif
2105 }
2106 break;
2107 }
2108
2109 case F_DUPFD:
2110 {
2111# if K_OS == K_OS_WINDOWS
2112 HANDLE hNew = INVALID_HANDLE_VALUE;
2113 if (DuplicateHandle(GetCurrentProcess(),
2114 (HANDLE)file->native,
2115 GetCurrentProcess(),
2116 &hNew,
2117 0,
2118 FALSE /* bInheritHandle */,
2119 DUPLICATE_SAME_ACCESS))
2120 rc = shfile_insert(pfdtab, (intptr_t)hNew, file->oflags, file->shflags, arg,
2121 "shfile_fcntl", SHFILE_DBGNAME(file->dbgname));
2122 else
2123 rc = shfile_dos2errno(GetLastError());
2124# else
2125 int nativeNew = fcntl(file->native, F_DUPFD, SHFILE_UNIX_MIN_FD);
2126 if (nativeNew != -1)
2127 rc = shfile_insert(pfdtab, nativeNew, file->oflags, file->shflags, arg,
2128 "shfile_fcntl", SHFILE_DBGNAME(file->dbgname));
2129 else
2130 rc = -1;
2131# endif
2132 break;
2133 }
2134
2135 default:
2136 errno = -EINVAL;
2137 rc = -1;
2138 break;
2139 }
2140
2141 shfile_put(pfdtab, file, &tmp);
2142 }
2143 else
2144 rc = -1;
2145
2146#else
2147 rc = fcntl(fd, cmd, arg);
2148#endif
2149
2150 switch (cmd)
2151 {
2152 case F_GETFL: TRACE2((NULL, "shfile_fcntl(%d,F_GETFL,ignored=%d) -> %d [%d]\n", fd, arg, rc, errno)); break;
2153 case F_SETFL: TRACE2((NULL, "shfile_fcntl(%d,F_SETFL,newflags=%#x) -> %d [%d]\n", fd, arg, rc, errno)); break;
2154 case F_DUPFD: TRACE2((NULL, "shfile_fcntl(%d,F_DUPFD,minfd=%d) -> %d [%d]\n", fd, arg, rc, errno)); break;
2155 default: TRACE2((NULL, "shfile_fcntl(%d,%d,%d) -> %d [%d]\n", fd, cmd, arg, rc, errno)); break;
2156 }
2157 return rc;
2158}
2159
2160int shfile_stat(shfdtab *pfdtab, const char *path, struct stat *pst)
2161{
2162#ifdef SHFILE_IN_USE
2163 char abspath[SHFILE_MAX_PATH];
2164 int rc;
2165 rc = shfile_make_path(pfdtab, path, &abspath[0]);
2166 if (!rc)
2167 {
2168# if K_OS == K_OS_WINDOWS
2169# if 1
2170 rc = birdStatFollowLink(abspath, pst);
2171# else
2172 int dir_slash = shfile_trailing_slash_hack(abspath);
2173 rc = stat(abspath, pst); /** @todo re-implement stat. */
2174 if (!rc && dir_slash && !S_ISDIR(pst->st_mode))
2175 {
2176 rc = -1;
2177 errno = ENOTDIR;
2178
2179 }
2180# endif
2181# else
2182 rc = stat(abspath, pst);
2183# endif
2184 }
2185 TRACE2((NULL, "shfile_stat(,%s,) -> %d [%d] st_size=%llu st_mode=%o\n",
2186 path, rc, errno, (unsigned long long)pst->st_size, pst->st_mode));
2187 return rc;
2188#else
2189 return stat(path, pst);
2190#endif
2191}
2192
2193/**
2194 * @retval 1 if regular file.
2195 * @retval 0 if found but not a regular file.
2196 * @retval -1 and errno on failure
2197 */
2198int shfile_stat_isreg(shfdtab *pfdtab, const char *path)
2199{
2200#if defined(SHFILE_IN_USE) && K_OS == K_OS_WINDOWS
2201 char abspath[SHFILE_MAX_PATH];
2202 KU16 mode = 0;
2203 int rc = shfile_make_path(pfdtab, path, &abspath[0]);
2204 if (!rc)
2205 {
2206 rc = birdStatModeOnly(abspath, &mode, 0 /*fFollowLink*/);
2207 if (rc >= 0)
2208 rc = S_ISREG(mode) ? 1 : 0;
2209 }
2210 TRACE2((NULL, "shfile_stat_isreg(,%s,) -> %d [%d] st_mode=%o\n", path, rc, errno, mode));
2211 return rc;
2212#else
2213 struct stat st;
2214 int rc = shfile_stat(pfdtab, path, &st);
2215 if (rc >= 0)
2216 rc = S_ISREG(st.st_mode) ? 1 : 0;
2217 return rc;
2218#endif
2219}
2220
2221/**
2222 * Same as shfile_stat, but without the data structure.
2223 */
2224int shfile_stat_exists(shfdtab *pfdtab, const char *path)
2225{
2226#if defined(SHFILE_IN_USE) && K_OS == K_OS_WINDOWS
2227 char abspath[SHFILE_MAX_PATH];
2228 KU16 mode = 0;
2229 int rc = shfile_make_path(pfdtab, path, &abspath[0]);
2230 if (!rc)
2231 rc = birdStatModeOnly(abspath, &mode, 0 /*fFollowLink*/);
2232 TRACE2((NULL, "shfile_stat_exists(,%s,) -> %d [%d] st_mode=%o\n", path, rc, errno, mode));
2233 return rc;
2234#else
2235 struct stat ignored;
2236 return shfile_stat(pfdtab, path, &ignored);
2237#endif
2238}
2239
2240int shfile_lstat(shfdtab *pfdtab, const char *path, struct stat *pst)
2241{
2242 int rc;
2243#ifdef SHFILE_IN_USE
2244 char abspath[SHFILE_MAX_PATH];
2245
2246 rc = shfile_make_path(pfdtab, path, &abspath[0]);
2247 if (!rc)
2248 {
2249# if K_OS == K_OS_WINDOWS
2250# if 1
2251 rc = birdStatOnLink(abspath, pst);
2252# else
2253 int dir_slash = shfile_trailing_slash_hack(abspath);
2254 rc = stat(abspath, pst); /** @todo re-implement stat. */
2255 if (!rc && dir_slash && !S_ISDIR(pst->st_mode))
2256 {
2257 rc = -1;
2258 errno = ENOTDIR;
2259 }
2260# endif
2261# else
2262 rc = lstat(abspath, pst);
2263# endif
2264 }
2265#else
2266 rc = stat(path, pst);
2267#endif
2268 TRACE2((NULL, "shfile_lstat(,%s,) -> %d [%d] st_size=%llu st_mode=%o\n",
2269 path, rc, errno, (unsigned long long)pst->st_size, pst->st_mode));
2270 return rc;
2271}
2272
2273/**
2274 * chdir().
2275 */
2276int shfile_chdir(shfdtab *pfdtab, const char *path)
2277{
2278 int rc;
2279#ifdef SHFILE_IN_USE
2280 shinstance *psh = shthread_get_shell();
2281 char abspath[SHFILE_MAX_PATH];
2282
2283 rc = shfile_make_path(pfdtab, path, &abspath[0]);
2284 if (!rc)
2285 {
2286 char *abspath_copy = sh_strdup(psh, abspath);
2287 char *free_me = abspath_copy;
2288 rc = chdir(abspath);
2289 if (!rc)
2290 {
2291 shmtxtmp tmp;
2292 shmtx_enter(&pfdtab->mtx, &tmp);
2293
2294 shfile_fix_slashes(abspath_copy);
2295 free_me = pfdtab->cwd;
2296 pfdtab->cwd = abspath_copy;
2297
2298 shmtx_leave(&pfdtab->mtx, &tmp);
2299 }
2300 sh_free(psh, free_me);
2301 }
2302 else
2303 rc = -1;
2304#else
2305 rc = chdir(path);
2306#endif
2307
2308 TRACE2((NULL, "shfile_chdir(,%s) -> %d [%d]\n", path, rc, errno));
2309 return rc;
2310}
2311
2312/**
2313 * getcwd().
2314 */
2315char *shfile_getcwd(shfdtab *pfdtab, char *buf, int size)
2316{
2317 char *ret;
2318#ifdef SHFILE_IN_USE
2319
2320 ret = NULL;
2321 if (buf && !size)
2322 errno = -EINVAL;
2323 else
2324 {
2325 size_t cwd_size;
2326 shmtxtmp tmp;
2327 shmtx_enter(&pfdtab->mtx, &tmp);
2328
2329 cwd_size = strlen(pfdtab->cwd) + 1;
2330 if (buf)
2331 {
2332 if (cwd_size <= (size_t)size)
2333 ret = memcpy(buf, pfdtab->cwd, cwd_size);
2334 else
2335 errno = ERANGE;
2336 }
2337 else
2338 {
2339 if ((size_t)size < cwd_size)
2340 size = (int)cwd_size;
2341 ret = sh_malloc(shthread_get_shell(), size);
2342 if (ret)
2343 ret = memcpy(ret, pfdtab->cwd, cwd_size);
2344 else
2345 errno = ENOMEM;
2346 }
2347
2348 shmtx_leave(&pfdtab->mtx, &tmp);
2349 }
2350#else
2351 ret = getcwd(buf, size);
2352#endif
2353
2354 TRACE2((NULL, "shfile_getcwd(,%p,%d) -> %s [%d]\n", buf, size, ret, errno));
2355 return ret;
2356}
2357
2358/**
2359 * access().
2360 */
2361int shfile_access(shfdtab *pfdtab, const char *path, int type)
2362{
2363 int rc;
2364#ifdef SHFILE_IN_USE
2365 char abspath[SHFILE_MAX_PATH];
2366
2367 rc = shfile_make_path(pfdtab, path, &abspath[0]);
2368 if (!rc)
2369 {
2370# ifdef _MSC_VER
2371 if (type & X_OK)
2372 type = (type & ~X_OK) | R_OK;
2373# endif
2374 rc = access(abspath, type);
2375 }
2376#else
2377# ifdef _MSC_VER
2378 if (type & X_OK)
2379 type = (type & ~X_OK) | R_OK;
2380# endif
2381 rc = access(path, type);
2382#endif
2383
2384 TRACE2((NULL, "shfile_access(,%s,%#x) -> %d [%d]\n", path, type, rc, errno));
2385 return rc;
2386}
2387
2388/**
2389 * isatty()
2390 */
2391int shfile_isatty(shfdtab *pfdtab, int fd)
2392{
2393 int rc;
2394#ifdef SHFILE_IN_USE
2395 shmtxtmp tmp;
2396 shfile *file = shfile_get(pfdtab, fd, &tmp);
2397 if (file)
2398 {
2399# if K_OS == K_OS_WINDOWS
2400 rc = (file->shflags & SHFILE_FLAGS_TYPE_MASK) == SHFILE_FLAGS_TTY;
2401# else
2402 rc = isatty(file->native);
2403# endif
2404 shfile_put(pfdtab, file, &tmp);
2405 }
2406 else
2407 rc = 0;
2408#else
2409 rc = isatty(fd);
2410#endif
2411
2412 TRACE2((NULL, "isatty(%d) -> %d [%d]\n", fd, rc, errno));
2413 return rc;
2414}
2415
2416/**
2417 * fcntl F_SETFD / FD_CLOEXEC.
2418 */
2419int shfile_cloexec(shfdtab *pfdtab, int fd, int closeit)
2420{
2421 int rc;
2422#ifdef SHFILE_IN_USE
2423 shmtxtmp tmp;
2424 shfile *file = shfile_get(pfdtab, fd, &tmp);
2425 if (file)
2426 {
2427 if (closeit)
2428 file->shflags |= SHFILE_FLAGS_CLOSE_ON_EXEC;
2429 else
2430 file->shflags &= ~SHFILE_FLAGS_CLOSE_ON_EXEC;
2431 shfile_put(pfdtab, file, &tmp);
2432 rc = 0;
2433 }
2434 else
2435 rc = -1;
2436#else
2437 rc = fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0)
2438 | (closeit ? FD_CLOEXEC : 0));
2439#endif
2440
2441 TRACE2((NULL, "shfile_cloexec(%d, %d) -> %d [%d]\n", fd, closeit, rc, errno));
2442 return rc;
2443}
2444
2445/**
2446 * Sets the SHFILE_FLAGS_TRACE flag.
2447 */
2448int shfile_set_trace(shfdtab *pfdtab, int fd)
2449{
2450 int rc;
2451#ifdef SHFILE_IN_USE
2452 shmtxtmp tmp;
2453 shfile *file = shfile_get(pfdtab, fd, &tmp);
2454 if (file)
2455 {
2456 file->shflags |= SHFILE_FLAGS_TRACE;
2457 shfile_put(pfdtab, file, &tmp);
2458 rc = 0;
2459 }
2460 else
2461 rc = -1;
2462#else
2463 rc = 0;
2464#endif
2465
2466 TRACE2((NULL, "shfile_set_trace(%d) -> %d\n", fd, rc));
2467 return rc;
2468}
2469
2470
2471int shfile_ioctl(shfdtab *pfdtab, int fd, unsigned long request, void *buf)
2472{
2473 int rc;
2474#ifdef SHFILE_IN_USE
2475 shmtxtmp tmp;
2476 shfile *file = shfile_get(pfdtab, fd, &tmp);
2477 if (file)
2478 {
2479# if K_OS == K_OS_WINDOWS
2480 rc = -1;
2481 errno = ENOSYS;
2482# else
2483 rc = ioctl(file->native, request, buf);
2484# endif
2485 shfile_put(pfdtab, file, &tmp);
2486 }
2487 else
2488 rc = -1;
2489#else
2490 rc = ioctl(fd, request, buf);
2491#endif
2492
2493 TRACE2((NULL, "ioctl(%d, %#x, %p) -> %d\n", fd, request, buf, rc));
2494 return rc;
2495}
2496
2497
2498mode_t shfile_get_umask(shfdtab *pfdtab)
2499{
2500 /** @todo */
2501 return 022;
2502}
2503
2504void shfile_set_umask(shfdtab *pfdtab, mode_t mask)
2505{
2506 /** @todo */
2507 (void)mask;
2508}
2509
2510
2511
2512shdir *shfile_opendir(shfdtab *pfdtab, const char *dir)
2513{
2514#if defined(SHFILE_IN_USE) && K_OS == K_OS_WINDOWS
2515 shdir *pdir = NULL;
2516
2517 TRACE2((NULL, "shfile_opendir: dir='%s'\n", dir));
2518 shfile_init_globals();
2519 if (g_pfnNtQueryDirectoryFile)
2520 {
2521 char abspath[SHFILE_MAX_PATH];
2522 if (shfile_make_path(pfdtab, dir, &abspath[0]) == 0)
2523 {
2524 HANDLE hFile;
2525 SECURITY_ATTRIBUTES SecurityAttributes;
2526
2527 SecurityAttributes.nLength = sizeof(SecurityAttributes);
2528 SecurityAttributes.lpSecurityDescriptor = NULL;
2529 SecurityAttributes.bInheritHandle = FALSE;
2530
2531 hFile = CreateFileA(abspath,
2532 GENERIC_READ,
2533 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
2534 &SecurityAttributes,
2535 OPEN_EXISTING,
2536 FILE_ATTRIBUTE_DIRECTORY | FILE_FLAG_BACKUP_SEMANTICS,
2537 NULL /* hTemplateFile */);
2538 if (hFile != INVALID_HANDLE_VALUE)
2539 {
2540 pdir = (shdir *)sh_malloc(shthread_get_shell(), sizeof(*pdir));
2541 if (pdir)
2542 {
2543 pdir->pfdtab = pfdtab;
2544 pdir->native = hFile;
2545 pdir->off = ~(size_t)0;
2546 }
2547 else
2548 CloseHandle(hFile);
2549 }
2550 else
2551 {
2552 errno = shfile_dos2errno(GetLastError());
2553 TRACE2((NULL, "shfile_opendir: CreateFileA(%s) -> %d/%d\n", abspath, GetLastError(), errno));
2554 }
2555 }
2556 }
2557 else
2558 errno = ENOSYS;
2559 return pdir;
2560#else
2561 TRACE2((NULL, "shfile_opendir: dir='%s'\n", dir));
2562 return (shdir *)opendir(dir);
2563#endif
2564}
2565
2566shdirent *shfile_readdir(struct shdir *pdir)
2567{
2568#if defined(SHFILE_IN_USE) && K_OS == K_OS_WINDOWS
2569 if (pdir)
2570 {
2571 NTSTATUS rcNt;
2572
2573 if ( pdir->off == ~(size_t)0
2574 || pdir->off + sizeof(MY_FILE_NAMES_INFORMATION) >= pdir->cb)
2575 {
2576 MY_IO_STATUS_BLOCK Ios;
2577
2578 memset(&Ios, 0, sizeof(Ios));
2579 rcNt = g_pfnNtQueryDirectoryFile(pdir->native,
2580 NULL /*Event*/,
2581 NULL /*ApcRoutine*/,
2582 NULL /*ApcContext*/,
2583 &Ios,
2584 &pdir->buf[0],
2585 sizeof(pdir->buf),
2586 MY_FileNamesInformation,
2587 FALSE /*ReturnSingleEntry*/,
2588 NULL /*FileName*/,
2589 pdir->off == ~(size_t)0 /*RestartScan*/);
2590 if (rcNt >= 0 && rcNt != STATUS_PENDING)
2591 {
2592 pdir->cb = Ios.Information;
2593 pdir->off = 0;
2594 }
2595 else if (rcNt == STATUS_NO_MORE_FILES)
2596 errno = 0; /* wrong? */
2597 else
2598 shfile_nt2errno(rcNt);
2599 }
2600
2601 if ( pdir->off != ~(size_t)0
2602 && pdir->off + sizeof(MY_FILE_NAMES_INFORMATION) <= pdir->cb)
2603 {
2604 PMY_FILE_NAMES_INFORMATION pcur = (PMY_FILE_NAMES_INFORMATION)&pdir->buf[pdir->off];
2605 ANSI_STRING astr;
2606 UNICODE_STRING ustr;
2607
2608 astr.Length = astr.MaximumLength = sizeof(pdir->ent.name);
2609 astr.Buffer = &pdir->ent.name[0];
2610
2611 ustr.Length = ustr.MaximumLength = pcur->FileNameLength < ~(USHORT)0 ? (USHORT)pcur->FileNameLength : ~(USHORT)0;
2612 ustr.Buffer = &pcur->FileName[0];
2613
2614 rcNt = g_pfnRtlUnicodeStringToAnsiString(&astr, &ustr, 0/*AllocateDestinationString*/);
2615 if (rcNt < 0)
2616 sprintf(pdir->ent.name, "conversion-failed-%08x-rcNt=%08x-len=%u",
2617 pcur->FileIndex, rcNt, pcur->FileNameLength);
2618 if (pcur->NextEntryOffset)
2619 pdir->off += pcur->NextEntryOffset;
2620 else
2621 pdir->off = pdir->cb;
2622 return &pdir->ent;
2623 }
2624 }
2625 else
2626 errno = EINVAL;
2627 return NULL;
2628#else
2629 struct dirent *pde = readdir((DIR *)pdir);
2630 return pde ? (shdirent *)&pde->d_name[0] : NULL;
2631#endif
2632}
2633
2634void shfile_closedir(struct shdir *pdir)
2635{
2636#if defined(SHFILE_IN_USE) && K_OS == K_OS_WINDOWS
2637 if (pdir)
2638 {
2639 CloseHandle(pdir->native);
2640 pdir->pfdtab = NULL;
2641 pdir->native = INVALID_HANDLE_VALUE;
2642 sh_free(shthread_get_shell(), pdir);
2643 }
2644 else
2645 errno = EINVAL;
2646#else
2647 closedir((DIR *)pdir);
2648#endif
2649}
2650
Note: See TracBrowser for help on using the repository browser.