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

Last change on this file since 3505 was 3505, checked in by bird, 4 years ago

kash: shthread_set_name for naming the async CloseHandle thread.

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