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

Last change on this file since 2419 was 2417, checked in by bird, 15 years ago

opendir fix.

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Id
File size: 47.5 KB
Line 
1/* $Id: shfile.c 2417 2010-09-14 00:42:43Z 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 <assert.h>
35
36#if K_OS == K_OS_WINDOWS
37# include <limits.h>
38# ifndef PIPE_BUF
39# define PIPE_BUF 512
40# endif
41# include <ntstatus.h>
42# define WIN32_NO_STATUS
43# include <Windows.h>
44# if !defined(_WIN32_WINNT)
45# define _WIN32_WINNT 0x0502 /* Windows Server 2003 */
46# endif
47# include <winternl.h> //NTSTATUS
48#else
49# include <unistd.h>
50# include <fcntl.h>
51# include <dirent.h>
52#endif
53
54
55/*******************************************************************************
56* Defined Constants And Macros *
57*******************************************************************************/
58/** @def SHFILE_IN_USE
59 * Whether the file descriptor table stuff is actually in use or not.
60 */
61#if K_OS == K_OS_WINDOWS \
62 || !defined(SH_FORKED_MODE)
63# define SHFILE_IN_USE
64#endif
65/** The max file table size. */
66#define SHFILE_MAX 1024
67/** The file table growth rate. */
68#define SHFILE_GROW 64
69/** The min native unix file descriptor. */
70#define SHFILE_UNIX_MIN_FD 32
71/** The path buffer size we use. */
72#define SHFILE_MAX_PATH 4096
73
74/** Set errno and return. Doing a trace in debug build. */
75#define RETURN_ERROR(rc, err, msg) \
76 do { \
77 TRACE2((NULL, "%s: " ## msg ## " - returning %d / %d\n", __FUNCTION__, (rc), (err))); \
78 errno = (err); \
79 return (rc); \
80 } while (0)
81
82#if K_OS == K_OS_WINDOWS
83 /* See msdos.h for description. */
84# define FOPEN 0x01
85# define FEOFLAG 0x02
86# define FCRLF 0x04
87# define FPIPE 0x08
88# define FNOINHERIT 0x10
89# define FAPPEND 0x20
90# define FDEV 0x40
91# define FTEXT 0x80
92
93# define MY_ObjectBasicInformation 0
94# define MY_FileNamesInformation 12
95
96typedef struct
97{
98 ULONG Attributes;
99 ACCESS_MASK GrantedAccess;
100 ULONG HandleCount;
101 ULONG PointerCount;
102 ULONG PagedPoolUsage;
103 ULONG NonPagedPoolUsage;
104 ULONG Reserved[3];
105 ULONG NameInformationLength;
106 ULONG TypeInformationLength;
107 ULONG SecurityDescriptorLength;
108 LARGE_INTEGER CreateTime;
109} MY_OBJECT_BASIC_INFORMATION;
110
111#if 0
112typedef struct
113{
114 union
115 {
116 LONG Status;
117 PVOID Pointer;
118 };
119 ULONG_PTR Information;
120} MY_IO_STATUS_BLOCK;
121#else
122typedef IO_STATUS_BLOCK MY_IO_STATUS_BLOCK;
123#endif
124typedef MY_IO_STATUS_BLOCK *PMY_IO_STATUS_BLOCK;
125
126typedef struct
127{
128 ULONG NextEntryOffset;
129 ULONG FileIndex;
130 ULONG FileNameLength;
131 WCHAR FileName[1];
132} MY_FILE_NAMES_INFORMATION, *PMY_FILE_NAMES_INFORMATION;
133
134typedef NTSTATUS (NTAPI * PFN_NtQueryObject)(HANDLE, int, void *, size_t, size_t *);
135typedef NTSTATUS (NTAPI * PFN_NtQueryDirectoryFile)(HANDLE, HANDLE, void *, void *, PMY_IO_STATUS_BLOCK, void *,
136 ULONG, int, int, PUNICODE_STRING, int);
137typedef NTSTATUS (NTAPI * PFN_RtlUnicodeStringToAnsiString)(PANSI_STRING, PCUNICODE_STRING, int);
138
139
140#endif /* K_OS_WINDOWS */
141
142
143/*******************************************************************************
144* Global Variables *
145*******************************************************************************/
146#if K_OS == K_OS_WINDOWS
147static int g_shfile_globals_initialized = 0;
148static PFN_NtQueryObject g_pfnNtQueryObject = NULL;
149static PFN_NtQueryDirectoryFile g_pfnNtQueryDirectoryFile = NULL;
150static PFN_RtlUnicodeStringToAnsiString g_pfnRtlUnicodeStringToAnsiString = NULL;
151#endif /* K_OS_WINDOWS */
152
153
154#ifdef SHFILE_IN_USE
155
156/**
157 * Close the specified native handle.
158 *
159 * @param native The native file handle.
160 * @param flags The flags in case they might come in handy later.
161 */
162static void shfile_native_close(intptr_t native, unsigned flags)
163{
164#if K_OS == K_OS_WINDOWS
165 BOOL fRc = CloseHandle((HANDLE)native);
166 assert(fRc); (void)fRc;
167#else
168 int s = errno;
169 close(native);
170 errno = s;
171#endif
172 (void)flags;
173}
174
175/**
176 * Inserts the file into the descriptor table.
177 *
178 * If we're out of memory and cannot extend the table, we'll close the
179 * file, set errno to EMFILE and return -1.
180 *
181 * @returns The file descriptor number. -1 and errno on failure.
182 * @param pfdtab The file descriptor table.
183 * @param native The native file handle.
184 * @param oflags The flags the it was opened/created with.
185 * @param shflags The shell file flags.
186 * @param fdMin The minimum file descriptor number, pass -1 if any is ok.
187 * @param who Who we're doing this for (for logging purposes).
188 */
189static int shfile_insert(shfdtab *pfdtab, intptr_t native, unsigned oflags, unsigned shflags, int fdMin, const char *who)
190{
191 shmtxtmp tmp;
192 int fd;
193 int i;
194
195 /*
196 * Fend of bad stuff.
197 */
198 if (fdMin >= SHFILE_MAX)
199 {
200 errno = EMFILE;
201 return -1;
202 }
203
204 shmtx_enter(&pfdtab->mtx, &tmp);
205
206 /*
207 * Search for a fitting unused location.
208 */
209 fd = -1;
210 for (i = 0; (unsigned)i < pfdtab->size; i++)
211 if ( i >= fdMin
212 && pfdtab->tab[i].fd == -1)
213 {
214 fd = i;
215 break;
216 }
217 if (fd == -1)
218 {
219 /*
220 * Grow the descriptor table.
221 */
222 shfile *new_tab;
223 int new_size = pfdtab->size + SHFILE_GROW;
224 while (new_size < fdMin)
225 new_size += SHFILE_GROW;
226 new_tab = sh_realloc(shthread_get_shell(), pfdtab->tab, new_size * sizeof(shfile));
227 if (new_tab)
228 {
229 for (i = pfdtab->size; i < new_size; i++)
230 {
231 new_tab[i].fd = -1;
232 new_tab[i].oflags = 0;
233 new_tab[i].shflags = 0;
234 new_tab[i].native = -1;
235 }
236
237 fd = pfdtab->size;
238 if (fd < fdMin)
239 fd = fdMin;
240
241 pfdtab->tab = new_tab;
242 pfdtab->size = new_size;
243 }
244 }
245
246 /*
247 * Fill in the entry if we've found one.
248 */
249 if (fd != -1)
250 {
251 pfdtab->tab[fd].fd = fd;
252 pfdtab->tab[fd].oflags = oflags;
253 pfdtab->tab[fd].shflags = shflags;
254 pfdtab->tab[fd].native = native;
255 }
256 else
257 shfile_native_close(native, oflags);
258
259 shmtx_leave(&pfdtab->mtx, &tmp);
260
261 if (fd == -1)
262 errno = EMFILE;
263 (void)who;
264 return fd;
265}
266
267/**
268 * Gets a file descriptor and lock the file descriptor table.
269 *
270 * @returns Pointer to the file and table ownership on success,
271 * NULL and errno set to EBADF on failure.
272 * @param pfdtab The file descriptor table.
273 * @param fd The file descriptor number.
274 * @param ptmp See shmtx_enter.
275 */
276static shfile *shfile_get(shfdtab *pfdtab, int fd, shmtxtmp *ptmp)
277{
278 shfile *file = NULL;
279 if ( fd >= 0
280 && (unsigned)fd < pfdtab->size)
281 {
282 shmtx_enter(&pfdtab->mtx, ptmp);
283 if ((unsigned)fd < pfdtab->size
284 && pfdtab->tab[fd].fd != -1)
285 file = &pfdtab->tab[fd];
286 else
287 shmtx_leave(&pfdtab->mtx, ptmp);
288 }
289 if (!file)
290 errno = EBADF;
291 return file;
292}
293
294/**
295 * Puts back a file descriptor and releases the table ownership.
296 *
297 * @param pfdtab The file descriptor table.
298 * @param file The file.
299 * @param ptmp See shmtx_leave.
300 */
301static void shfile_put(shfdtab *pfdtab, shfile *file, shmtxtmp *ptmp)
302{
303 shmtx_leave(&pfdtab->mtx, ptmp);
304 assert(file);
305 (void)file;
306}
307
308/**
309 * Constructs a path from the current directory and the passed in path.
310 *
311 * @returns 0 on success, -1 and errno set to ENAMETOOLONG or EINVAL on failure.
312 *
313 * @param pfdtab The file descriptor table
314 * @param path The path the caller supplied.
315 * @param buf Where to put the path. This is assumed to be SHFILE_MAX_PATH
316 * chars in size.
317 */
318int shfile_make_path(shfdtab *pfdtab, const char *path, char *buf)
319{
320 size_t path_len = strlen(path);
321 if (path_len == 0)
322 {
323 errno = EINVAL;
324 return -1;
325 }
326 if (path_len >= SHFILE_MAX_PATH)
327 {
328 errno = ENAMETOOLONG;
329 return -1;
330 }
331 if ( *path == '/'
332#if K_OS == K_OS_WINDOWS || K_OS == K_OS_OS2
333 || *path == '\\'
334 || ( *path
335 && path[1] == ':'
336 && ( (*path >= 'A' && *path <= 'Z')
337 || (*path >= 'a' && *path <= 'z')))
338#endif
339 )
340 {
341 memcpy(buf, path, path_len + 1);
342 }
343 else
344 {
345 size_t cwd_len;
346 shmtxtmp tmp;
347
348 shmtx_enter(&pfdtab->mtx, &tmp);
349
350 cwd_len = strlen(pfdtab->cwd);
351 memcpy(buf, pfdtab->cwd, cwd_len);
352
353 shmtx_leave(&pfdtab->mtx, &tmp);
354
355 if (cwd_len + path_len + 1 >= SHFILE_MAX_PATH)
356 {
357 errno = ENAMETOOLONG;
358 return -1;
359 }
360 if ( !cwd_len
361 || buf[cwd_len - 1] != '/')
362 buf[cwd_len++] = '/';
363 memcpy(buf + cwd_len, path, path_len + 1);
364 }
365
366#if K_OS == K_OS_WINDOWS || K_OS == K_OS_OS2
367 if (!strcmp(buf, "/dev/null"))
368 strcpy(buf, "NUL");
369#endif
370 return 0;
371}
372
373# if K_OS == K_OS_WINDOWS
374
375/**
376 * Converts a DOS(/Windows) error code to errno,
377 * assigning it to errno.
378 *
379 * @returns -1
380 * @param err The DOS error.
381 */
382static int shfile_dos2errno(int err)
383{
384 switch (err)
385 {
386 case ERROR_BAD_ENVIRONMENT: errno = E2BIG; break;
387 case ERROR_ACCESS_DENIED: errno = EACCES; break;
388 case ERROR_CURRENT_DIRECTORY: errno = EACCES; break;
389 case ERROR_LOCK_VIOLATION: errno = EACCES; break;
390 case ERROR_NETWORK_ACCESS_DENIED: errno = EACCES; break;
391 case ERROR_CANNOT_MAKE: errno = EACCES; break;
392 case ERROR_FAIL_I24: errno = EACCES; break;
393 case ERROR_DRIVE_LOCKED: errno = EACCES; break;
394 case ERROR_SEEK_ON_DEVICE: errno = EACCES; break;
395 case ERROR_NOT_LOCKED: errno = EACCES; break;
396 case ERROR_LOCK_FAILED: errno = EACCES; break;
397 case ERROR_NO_PROC_SLOTS: errno = EAGAIN; break;
398 case ERROR_MAX_THRDS_REACHED: errno = EAGAIN; break;
399 case ERROR_NESTING_NOT_ALLOWED: errno = EAGAIN; break;
400 case ERROR_INVALID_HANDLE: errno = EBADF; break;
401 case ERROR_INVALID_TARGET_HANDLE: errno = EBADF; break;
402 case ERROR_DIRECT_ACCESS_HANDLE: errno = EBADF; break;
403 case ERROR_WAIT_NO_CHILDREN: errno = ECHILD; break;
404 case ERROR_CHILD_NOT_COMPLETE: errno = ECHILD; break;
405 case ERROR_FILE_EXISTS: errno = EEXIST; break;
406 case ERROR_ALREADY_EXISTS: errno = EEXIST; break;
407 case ERROR_INVALID_FUNCTION: errno = EINVAL; break;
408 case ERROR_INVALID_ACCESS: errno = EINVAL; break;
409 case ERROR_INVALID_DATA: errno = EINVAL; break;
410 case ERROR_INVALID_PARAMETER: errno = EINVAL; break;
411 case ERROR_NEGATIVE_SEEK: errno = EINVAL; break;
412 case ERROR_TOO_MANY_OPEN_FILES: errno = EMFILE; break;
413 case ERROR_FILE_NOT_FOUND: errno = ENOENT; break;
414 case ERROR_PATH_NOT_FOUND: errno = ENOENT; break;
415 case ERROR_INVALID_DRIVE: errno = ENOENT; break;
416 case ERROR_NO_MORE_FILES: errno = ENOENT; break;
417 case ERROR_BAD_NETPATH: errno = ENOENT; break;
418 case ERROR_BAD_NET_NAME: errno = ENOENT; break;
419 case ERROR_BAD_PATHNAME: errno = ENOENT; break;
420 case ERROR_FILENAME_EXCED_RANGE: errno = ENOENT; break;
421 case ERROR_BAD_FORMAT: errno = ENOEXEC; break;
422 case ERROR_ARENA_TRASHED: errno = ENOMEM; break;
423 case ERROR_NOT_ENOUGH_MEMORY: errno = ENOMEM; break;
424 case ERROR_INVALID_BLOCK: errno = ENOMEM; break;
425 case ERROR_NOT_ENOUGH_QUOTA: errno = ENOMEM; break;
426 case ERROR_DISK_FULL: errno = ENOSPC; break;
427 case ERROR_DIR_NOT_EMPTY: errno = ENOTEMPTY; break;
428 case ERROR_BROKEN_PIPE: errno = EPIPE; break;
429 case ERROR_NOT_SAME_DEVICE: errno = EXDEV; break;
430 default: errno = EINVAL; break;
431 }
432 return -1;
433}
434
435/**
436 * Converts an NT status code to errno,
437 * assigning it to errno.
438 *
439 * @returns -1
440 * @param rcNt The NT status code.
441 */
442static int shfile_nt2errno(NTSTATUS rcNt)
443{
444 switch (rcNt)
445 {
446 default: errno = EINVAL; break;
447 }
448 return -1;
449}
450
451DWORD shfile_query_handle_access_mask(HANDLE h, PACCESS_MASK pMask)
452{
453 MY_OBJECT_BASIC_INFORMATION BasicInfo;
454 NTSTATUS rcNt;
455
456 if (!g_pfnNtQueryObject)
457 return ERROR_NOT_SUPPORTED;
458
459 rcNt = g_pfnNtQueryObject(h, MY_ObjectBasicInformation, &BasicInfo, sizeof(BasicInfo), NULL);
460 if (rcNt >= 0)
461 {
462 *pMask = BasicInfo.GrantedAccess;
463 return NO_ERROR;
464 }
465 if (rcNt != STATUS_INVALID_HANDLE)
466 return ERROR_GEN_FAILURE;
467 return ERROR_INVALID_HANDLE;
468}
469
470# endif /* K_OS == K_OS_WINDOWS */
471
472#endif /* SHFILE_IN_USE */
473
474/**
475 * Initializes the global variables in this file.
476 */
477static void shfile_init_globals(void)
478{
479#if K_OS == K_OS_WINDOWS
480 if (!g_shfile_globals_initialized)
481 {
482 HMODULE hNtDll = GetModuleHandle("NTDLL");
483 g_pfnNtQueryObject = (PFN_NtQueryObject) GetProcAddress(hNtDll, "NtQueryObject");
484 g_pfnNtQueryDirectoryFile = (PFN_NtQueryDirectoryFile)GetProcAddress(hNtDll, "NtQueryDirectoryFile");
485 g_pfnRtlUnicodeStringToAnsiString = (PFN_RtlUnicodeStringToAnsiString)GetProcAddress(hNtDll, "RtlUnicodeStringToAnsiString");
486 if ( !g_pfnRtlUnicodeStringToAnsiString
487 || !g_pfnNtQueryDirectoryFile)
488 {
489 /* fatal error */
490 }
491 g_shfile_globals_initialized = 1;
492 }
493#endif
494}
495
496/**
497 * Initializes a file descriptor table.
498 *
499 * @returns 0 on success, -1 and errno on failure.
500 * @param pfdtab The table to initialize.
501 * @param inherit File descriptor table to inherit from. If not specified
502 * we will inherit from the current process as it were.
503 */
504int shfile_init(shfdtab *pfdtab, shfdtab *inherit)
505{
506 int rc;
507
508 shfile_init_globals();
509
510 pfdtab->cwd = NULL;
511 pfdtab->size = 0;
512 pfdtab->tab = NULL;
513 rc = shmtx_init(&pfdtab->mtx);
514 if (!rc)
515 {
516#ifdef SHFILE_IN_USE
517 char buf[SHFILE_MAX_PATH];
518 if (getcwd(buf, sizeof(buf)))
519 {
520 pfdtab->cwd = sh_strdup(NULL, buf);
521 if (!inherit)
522 {
523# if K_OS == K_OS_WINDOWS
524 static const struct
525 {
526 DWORD dwStdHandle;
527 unsigned fFlags;
528 } aStdHandles[3] =
529 {
530 { STD_INPUT_HANDLE, _O_RDONLY },
531 { STD_OUTPUT_HANDLE, _O_WRONLY },
532 { STD_ERROR_HANDLE, _O_WRONLY }
533 };
534 int i;
535 STARTUPINFO Info;
536 ACCESS_MASK Mask;
537 DWORD dwErr;
538
539 rc = 0;
540
541 /* Try pick up the Visual C++ CRT file descriptor info. */
542 __try {
543 GetStartupInfo(&Info);
544 } __except (EXCEPTION_EXECUTE_HANDLER) {
545 memset(&Info, 0, sizeof(Info));
546 }
547
548 if ( Info.cbReserved2 > sizeof(int)
549 && (uintptr_t)Info.lpReserved2 >= 0x1000
550 && (i = *(int *)Info.lpReserved2) >= 1
551 && i <= 2048
552 && ( Info.cbReserved2 == i * 5 + 4
553 //|| Info.cbReserved2 == i * 5 + 1 - check the cygwin sources.
554 || Info.cbReserved2 == i * 9 + 4))
555 {
556 uint8_t *paf = (uint8_t *)Info.lpReserved2 + sizeof(int);
557 int dwPerH = 1 + (Info.cbReserved2 == i * 9 + 4);
558 DWORD *ph = (DWORD *)(paf + i) + dwPerH * i;
559 HANDLE aStdHandles2[3];
560 int j;
561
562 //if (Info.cbReserved2 == i * 5 + 1) - check the cygwin sources.
563 // i--;
564
565 for (j = 0; j < 3; j++)
566 aStdHandles2[j] = GetStdHandle(aStdHandles[j].dwStdHandle);
567
568 while (i-- > 0)
569 {
570 ph -= dwPerH;
571
572 if ( (paf[i] & (FOPEN | FNOINHERIT)) == FOPEN
573 && *ph != (uint32_t)INVALID_HANDLE_VALUE)
574 {
575 HANDLE h = (HANDLE)(intptr_t)*ph;
576 int fd2;
577 int fFlags;
578 int fFlags2;
579
580 if ( h == aStdHandles2[j = 0]
581 || h == aStdHandles2[j = 1]
582 || h == aStdHandles2[j = 2])
583 fFlags = aStdHandles[j].fFlags;
584 else
585 {
586 dwErr = shfile_query_handle_access_mask(h, &Mask);
587 if (dwErr == ERROR_INVALID_HANDLE)
588 continue;
589 else if (dwErr == NO_ERROR)
590 {
591 fFlags = 0;
592 if ( (Mask & (GENERIC_READ | FILE_READ_DATA))
593 && (Mask & (GENERIC_WRITE | FILE_WRITE_DATA | FILE_APPEND_DATA)))
594 fFlags |= O_RDWR;
595 else if (Mask & (GENERIC_READ | FILE_READ_DATA))
596 fFlags |= O_RDONLY;
597 else if (Mask & (GENERIC_WRITE | FILE_WRITE_DATA | FILE_APPEND_DATA))
598 fFlags |= O_WRONLY;
599 else
600 fFlags |= O_RDWR;
601 if ((Mask & (FILE_WRITE_DATA | FILE_APPEND_DATA)) == FILE_APPEND_DATA)
602 fFlags |= O_APPEND;
603 }
604 else
605 fFlags = O_RDWR;
606 }
607
608 if (paf[i] & FPIPE)
609 fFlags2 = SHFILE_FLAGS_PIPE;
610 else if (paf[i] & FDEV)
611 fFlags2 = SHFILE_FLAGS_TTY;
612 else
613 fFlags2 = 0;
614
615 fd2 = shfile_insert(pfdtab, (intptr_t)h, fFlags, fFlags2, i, "shtab_init");
616 assert(fd2 == i); (void)fd2;
617 if (fd2 != i)
618 rc = -1;
619 }
620 }
621 }
622
623 /* Check the three standard handles. */
624 for (i = 0; i < 3; i++)
625 if ( (unsigned)i >= pfdtab->size
626 || pfdtab->tab[i].fd == -1)
627 {
628 HANDLE hFile = GetStdHandle(aStdHandles[i].dwStdHandle);
629 if (hFile != INVALID_HANDLE_VALUE)
630 {
631 DWORD dwType = GetFileType(hFile);
632 unsigned fFlags = aStdHandles[i].fFlags;
633 unsigned fFlags2;
634 int fd2;
635 if (dwType == FILE_TYPE_CHAR)
636 fFlags2 = SHFILE_FLAGS_TTY;
637 else if (dwType == FILE_TYPE_PIPE)
638 fFlags2 = SHFILE_FLAGS_PIPE;
639 else
640 fFlags2 = SHFILE_FLAGS_FILE;
641 fd2 = shfile_insert(pfdtab, (intptr_t)hFile, fFlags, fFlags2, i, "shtab_init");
642 assert(fd2 == i); (void)fd2;
643 if (fd2 != i)
644 rc = -1;
645 }
646 }
647# else
648# endif
649 }
650 else
651 {
652 /** @todo */
653 errno = ENOSYS;
654 rc = -1;
655 }
656 }
657 else
658 rc = -1;
659#endif
660 }
661 return rc;
662}
663
664#if K_OS == K_OS_WINDOWS && defined(SHFILE_IN_USE)
665
666/**
667 * Helper for shfork.
668 *
669 * @param pfdtab The file descriptor table.
670 * @param set Whether to make all handles inheritable (1) or
671 * to restore them to the rigth state (0).
672 * @param hndls Where to store the three standard handles.
673 */
674void shfile_fork_win(shfdtab *pfdtab, int set, intptr_t *hndls)
675{
676 shmtxtmp tmp;
677 unsigned i;
678 DWORD fFlag = set ? HANDLE_FLAG_INHERIT : 0;
679
680 shmtx_enter(&pfdtab->mtx, &tmp);
681 TRACE2((NULL, "shfile_fork_win: set=%d\n", set));
682
683 i = pfdtab->size;
684 while (i-- > 0)
685 {
686 if (pfdtab->tab[i].fd == i)
687 {
688 HANDLE hFile = (HANDLE)pfdtab->tab[i].native;
689 if (set)
690 TRACE2((NULL, " #%d: native=%#x oflags=%#x shflags=%#x\n",
691 i, hFile, pfdtab->tab[i].oflags, pfdtab->tab[i].shflags));
692 if (!SetHandleInformation(hFile, HANDLE_FLAG_INHERIT, fFlag))
693 {
694 DWORD err = GetLastError();
695 assert(0);
696 }
697 }
698 }
699
700 if (hndls)
701 {
702 for (i = 0; i < 3; i++)
703 {
704 if ( pfdtab->size > i
705 && pfdtab->tab[i].fd == i)
706 hndls[i] = pfdtab->tab[i].native;
707 else
708 hndls[i] = (intptr_t)INVALID_HANDLE_VALUE;
709 TRACE2((NULL, "shfile_fork_win: i=%d size=%d fd=%d native=%d hndls[%d]=%p\n",
710 i, pfdtab->size, pfdtab->tab[i].fd, pfdtab->tab[i].native, i, hndls[i]));
711 }
712 }
713
714 shmtx_leave(&pfdtab->mtx, &tmp);
715}
716
717/**
718 * Helper for sh_execve.
719 *
720 * This is called before and after CreateProcess. On the first call it
721 * will mark the non-close-on-exec handles as inheritable and produce
722 * the startup info for the CRT. On the second call, after CreateProcess,
723 * it will restore the handle inheritability properties.
724 *
725 * @returns Pointer to CRT data if prepare is 1, NULL if prepare is 0.
726 * @param pfdtab The file descriptor table.
727 * @param prepare Which call, 1 if before and 0 if after.
728 * @param sizep Where to store the size of the returned data.
729 * @param hndls Where to store the three standard handles.
730 */
731void *shfile_exec_win(shfdtab *pfdtab, int prepare, unsigned short *sizep, intptr_t *hndls)
732{
733 void *pvRet;
734 shmtxtmp tmp;
735 unsigned count;
736 unsigned i;
737
738 shmtx_enter(&pfdtab->mtx, &tmp);
739 TRACE2((NULL, "shfile_exec_win: prepare=%p\n", prepare));
740
741 count = pfdtab->size < (0x10000-4) / (1 + sizeof(HANDLE))
742 ? pfdtab->size
743 : (0x10000-4) / (1 + sizeof(HANDLE));
744 while (count > 3 && pfdtab->tab[count - 1].fd == -1)
745 count--;
746
747 if (prepare)
748 {
749 size_t cbData = sizeof(int) + count * (1 + sizeof(HANDLE));
750 uint8_t *pbData = sh_malloc(shthread_get_shell(), cbData);
751 uint8_t *paf = pbData + sizeof(int);
752 HANDLE *pah = (HANDLE *)(paf + count);
753
754 *(int *)pbData = count;
755
756 i = count;
757 while (i-- > 0)
758 {
759 if ( pfdtab->tab[i].fd == i
760 && !(pfdtab->tab[i].shflags & SHFILE_FLAGS_CLOSE_ON_EXEC))
761 {
762 HANDLE hFile = (HANDLE)pfdtab->tab[i].native;
763 TRACE2((NULL, " #%d: native=%#x oflags=%#x shflags=%#x\n",
764 i, hFile, pfdtab->tab[i].oflags, pfdtab->tab[i].shflags));
765
766 if (!SetHandleInformation(hFile, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT))
767 {
768 DWORD err = GetLastError();
769 assert(0);
770 }
771 paf[i] = FOPEN;
772 if (pfdtab->tab[i].oflags & _O_APPEND)
773 paf[i] |= FAPPEND;
774 if (pfdtab->tab[i].oflags & _O_TEXT)
775 paf[i] |= FTEXT;
776 switch (pfdtab->tab[i].shflags & SHFILE_FLAGS_TYPE_MASK)
777 {
778 case SHFILE_FLAGS_TTY: paf[i] |= FDEV; break;
779 case SHFILE_FLAGS_PIPE: paf[i] |= FPIPE; break;
780 }
781 pah[i] = hFile;
782 }
783 else
784 {
785 paf[i] = 0;
786 pah[i] = INVALID_HANDLE_VALUE;
787 }
788 }
789
790 for (i = 0; i < 3; i++)
791 {
792 if ( i < count
793 && pfdtab->tab[i].fd == i)
794 hndls[i] = pfdtab->tab[i].native;
795 else
796 hndls[i] = (intptr_t)INVALID_HANDLE_VALUE;
797 TRACE2((NULL, "shfile_exec_win: i=%d count=%d fd=%d native=%d hndls[%d]=\n",
798 i, count, pfdtab->tab[i].fd, pfdtab->tab[i].native, i, hndls[i]));
799 }
800
801 *sizep = (unsigned short)cbData;
802 pvRet = pbData;
803 }
804 else
805 {
806 assert(!hndls);
807 assert(!sizep);
808 i = count;
809 while (i-- > 0)
810 {
811 if ( pfdtab->tab[i].fd == i
812 && !(pfdtab->tab[i].shflags & SHFILE_FLAGS_CLOSE_ON_EXEC))
813 {
814 HANDLE hFile = (HANDLE)pfdtab->tab[i].native;
815 if (!SetHandleInformation(hFile, HANDLE_FLAG_INHERIT, 0))
816 {
817 DWORD err = GetLastError();
818 assert(0);
819 }
820 }
821 }
822 pvRet = NULL;
823 }
824
825 shmtx_leave(&pfdtab->mtx, &tmp);
826 return pvRet;
827}
828
829#endif /* K_OS_WINDOWS */
830
831
832/**
833 * open().
834 */
835int shfile_open(shfdtab *pfdtab, const char *name, unsigned flags, mode_t mode)
836{
837 int fd;
838#ifdef SHFILE_IN_USE
839 char absname[SHFILE_MAX_PATH];
840# if K_OS == K_OS_WINDOWS
841 HANDLE hFile;
842 DWORD dwDesiredAccess;
843 DWORD dwShareMode;
844 DWORD dwCreationDisposition;
845 DWORD dwFlagsAndAttributes;
846 SECURITY_ATTRIBUTES SecurityAttributes;
847
848# ifndef _O_ACCMODE
849# define _O_ACCMODE (_O_RDONLY|_O_WRONLY|_O_RDWR)
850# endif
851 switch (flags & (_O_ACCMODE | _O_APPEND))
852 {
853 case _O_RDONLY: dwDesiredAccess = GENERIC_READ; break;
854 case _O_RDONLY | _O_APPEND: dwDesiredAccess = GENERIC_READ; break;
855 case _O_WRONLY: dwDesiredAccess = GENERIC_WRITE; break;
856 case _O_WRONLY | _O_APPEND: dwDesiredAccess = (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA); break;
857 case _O_RDWR: dwDesiredAccess = GENERIC_READ | GENERIC_WRITE; break;
858 case _O_RDWR | _O_APPEND: dwDesiredAccess = GENERIC_READ | (FILE_GENERIC_WRITE & ~FILE_WRITE_DATA); break;
859
860 default:
861 RETURN_ERROR(-1, EINVAL, "invalid mode");
862 }
863
864 dwShareMode = FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE;
865
866 SecurityAttributes.nLength = sizeof(SecurityAttributes);
867 SecurityAttributes.lpSecurityDescriptor = NULL;
868 SecurityAttributes.bInheritHandle = FALSE;
869
870 if (flags & _O_CREAT)
871 {
872 if ((flags & (_O_EXCL | _O_TRUNC)) == (_O_EXCL | _O_TRUNC))
873 RETURN_ERROR(-1, EINVAL, "_O_EXCL | _O_TRUNC");
874
875 if (flags & _O_TRUNC)
876 dwCreationDisposition = CREATE_ALWAYS; /* not 100%, but close enough */
877 else if (flags & _O_EXCL)
878 dwCreationDisposition = CREATE_NEW;
879 else
880 dwCreationDisposition = OPEN_ALWAYS;
881 }
882 else if (flags & _O_TRUNC)
883 dwCreationDisposition = TRUNCATE_EXISTING;
884 else
885 dwCreationDisposition = OPEN_EXISTING;
886
887 if (!(flags & _O_CREAT) || (mode & 0222))
888 dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
889 else
890 dwFlagsAndAttributes = FILE_ATTRIBUTE_READONLY;
891
892 fd = shfile_make_path(pfdtab, name, &absname[0]);
893 if (!fd)
894 {
895 SetLastError(0);
896 hFile = CreateFileA(absname,
897 dwDesiredAccess,
898 dwShareMode,
899 &SecurityAttributes,
900 dwCreationDisposition,
901 dwFlagsAndAttributes,
902 NULL /* hTemplateFile */);
903 if (hFile != INVALID_HANDLE_VALUE)
904 fd = shfile_insert(pfdtab, (intptr_t)hFile, flags, 0, -1, "shfile_open");
905 else
906 fd = shfile_dos2errno(GetLastError());
907 }
908
909# else /* K_OS != K_OS_WINDOWS */
910 fd = shfile_make_path(pfdtab, name, &absname[0]);
911 if (!fd)
912 {
913 fd = open(absname, flag, mode);
914 if (fd != -1)
915 {
916 int native = fcntl(fd, F_DUPFD, SHFILE_UNIX_MIN_FD);
917 int s = errno;
918 close(fd);
919 errno = s;
920 if (native != -1)
921 fd = shfile_insert(pfdtab, native, flags, 0, -1, "shfile_open");
922 else
923 fd = -1;
924 }
925 }
926
927# endif /* K_OS != K_OS_WINDOWS */
928
929#else
930 fd = open(name, flags, mode);
931#endif
932
933 TRACE2((NULL, "shfile_open(%p:{%s}, %#x, 0%o) -> %d [%d]\n", name, name, flags, mode, fd, errno));
934 return fd;
935}
936
937int shfile_pipe(shfdtab *pfdtab, int fds[2])
938{
939 int rc;
940#ifdef SHFILE_IN_USE
941# if K_OS == K_OS_WINDOWS
942 HANDLE hRead = INVALID_HANDLE_VALUE;
943 HANDLE hWrite = INVALID_HANDLE_VALUE;
944 SECURITY_ATTRIBUTES SecurityAttributes;
945
946 SecurityAttributes.nLength = sizeof(SecurityAttributes);
947 SecurityAttributes.lpSecurityDescriptor = NULL;
948 SecurityAttributes.bInheritHandle = FALSE;
949
950 fds[1] = fds[0] = -1;
951 if (CreatePipe(&hRead, &hWrite, &SecurityAttributes, 4096))
952 {
953 fds[0] = shfile_insert(pfdtab, (intptr_t)hRead, O_RDONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
954 if (fds[0] != -1)
955 {
956 fds[1] = shfile_insert(pfdtab, (intptr_t)hWrite, O_WRONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
957 if (fds[1] != -1)
958 rc = 0;
959 }
960
961# else
962 int native_fds[2];
963
964 fds[1] = fds[0] = -1;
965 if (!pipe(native_fds))
966 {
967 fds[0] = shfile_insert(pfdtab, native_fds[0], O_RDONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
968 if (fds[0] != -1)
969 {
970 fds[1] = shfile_insert(pfdtab, native_fds[1], O_WRONLY, SHFILE_FLAGS_PIPE, -1, "shfile_pipe");
971 if (fds[1] != -1)
972 rc = 0;
973 }
974# endif
975 if (fds[1] == -1)
976 {
977 int s = errno;
978 if (fds[0] != -1)
979 {
980 shmtxtmp tmp;
981 shmtx_enter(&pfdtab->mtx, &tmp);
982 rc = fds[0];
983 pfdtab->tab[rc].fd = -1;
984 pfdtab->tab[rc].oflags = 0;
985 pfdtab->tab[rc].shflags = 0;
986 pfdtab->tab[rc].native = -1;
987 shmtx_leave(&pfdtab->mtx, &tmp);
988 }
989
990# if K_OS == K_OS_WINDOWS
991 CloseHandle(hRead);
992 CloseHandle(hWrite);
993# else
994 close(native_fds[0]);
995 close(native_fds[1]);
996# endif
997 fds[0] = fds[1] = -1;
998 errno = s;
999 rc = -1;
1000 }
1001 }
1002 else
1003 {
1004# if K_OS == K_OS_WINDOWS
1005 errno = shfile_dos2errno(GetLastError());
1006# endif
1007 rc = -1;
1008 }
1009
1010#else
1011 rc = pipe(fds);
1012#endif
1013
1014 TRACE2((NULL, "shfile_pipe() -> %d{%d,%d} [%d]\n", rc, fds[0], fds[1], errno));
1015 return rc;
1016}
1017
1018/**
1019 * dup().
1020 */
1021int shfile_dup(shfdtab *pfdtab, int fd)
1022{
1023 return shfile_fcntl(pfdtab,fd, F_DUPFD, 0);
1024}
1025
1026/**
1027 * close().
1028 */
1029int shfile_close(shfdtab *pfdtab, unsigned fd)
1030{
1031 int rc;
1032#ifdef SHFILE_IN_USE
1033 shmtxtmp tmp;
1034 shfile *file = shfile_get(pfdtab, fd, &tmp);
1035 if (file)
1036 {
1037 shfile_native_close(file->native, file->oflags);
1038
1039 file->fd = -1;
1040 file->oflags = 0;
1041 file->shflags = 0;
1042 file->native = -1;
1043
1044 shfile_put(pfdtab, file, &tmp);
1045 rc = 0;
1046 }
1047 else
1048 rc = -1;
1049
1050#else
1051 rc = close(fd);
1052#endif
1053
1054 TRACE2((NULL, "shfile_close(%d) -> %d [%d]\n", fd, rc, errno));
1055 return rc;
1056}
1057
1058/**
1059 * read().
1060 */
1061long shfile_read(shfdtab *pfdtab, int fd, void *buf, size_t len)
1062{
1063 long rc;
1064#ifdef SHFILE_IN_USE
1065 shmtxtmp tmp;
1066 shfile *file = shfile_get(pfdtab, fd, &tmp);
1067 if (file)
1068 {
1069# if K_OS == K_OS_WINDOWS
1070 DWORD dwRead = 0;
1071 if (ReadFile((HANDLE)file->native, buf, (DWORD)len, &dwRead, NULL))
1072 rc = dwRead;
1073 else
1074 rc = shfile_dos2errno(GetLastError());
1075# else
1076 rc = read(file->native, buf, len);
1077# endif
1078
1079 shfile_put(pfdtab, file, &tmp);
1080 }
1081 else
1082 rc = -1;
1083
1084#else
1085 rc = read(fd, buf, len);
1086#endif
1087 return rc;
1088}
1089
1090/**
1091 * write().
1092 */
1093long shfile_write(shfdtab *pfdtab, int fd, const void *buf, size_t len)
1094{
1095 long rc;
1096#ifdef SHFILE_IN_USE
1097 shmtxtmp tmp;
1098 shfile *file = shfile_get(pfdtab, fd, &tmp);
1099 if (file)
1100 {
1101# if K_OS == K_OS_WINDOWS
1102 DWORD dwWritten = 0;
1103 if (WriteFile((HANDLE)file->native, buf, (DWORD)len, &dwWritten, NULL))
1104 rc = dwWritten;
1105 else
1106 rc = shfile_dos2errno(GetLastError());
1107# else
1108 rc = write(file->native, buf, len);
1109# endif
1110
1111 shfile_put(pfdtab, file, &tmp);
1112 }
1113 else
1114 rc = -1;
1115
1116#else
1117 rc = write(fd, buf, len);
1118#endif
1119 return rc;
1120}
1121
1122/**
1123 * lseek().
1124 */
1125long shfile_lseek(shfdtab *pfdtab, int fd, long off, int whench)
1126{
1127 long rc;
1128#ifdef SHFILE_IN_USE
1129 shmtxtmp tmp;
1130 shfile *file = shfile_get(pfdtab, fd, &tmp);
1131 if (file)
1132 {
1133# if K_OS == K_OS_WINDOWS
1134 assert(SEEK_SET == FILE_BEGIN);
1135 assert(SEEK_CUR == FILE_CURRENT);
1136 assert(SEEK_END == FILE_END);
1137 rc = SetFilePointer((HANDLE)file->native, off, NULL, whench);
1138 if (rc == INVALID_SET_FILE_POINTER)
1139 rc = shfile_dos2errno(GetLastError());
1140# else
1141 rc = lseek(file->native, off, whench);
1142# endif
1143
1144 shfile_put(pfdtab, file, &tmp);
1145 }
1146 else
1147 rc = -1;
1148
1149#else
1150 rc = lseek(fd, off, whench);
1151#endif
1152
1153 return rc;
1154}
1155
1156int shfile_fcntl(shfdtab *pfdtab, int fd, int cmd, int arg)
1157{
1158 int rc;
1159#ifdef SHFILE_IN_USE
1160 shmtxtmp tmp;
1161 shfile *file = shfile_get(pfdtab, fd, &tmp);
1162 if (file)
1163 {
1164 switch (cmd)
1165 {
1166 case F_GETFL:
1167 rc = file->oflags;
1168 break;
1169
1170 case F_SETFL:
1171 {
1172 unsigned mask = O_NONBLOCK | O_APPEND | O_BINARY | O_TEXT;
1173# ifdef O_DIRECT
1174 mask |= O_DIRECT;
1175# endif
1176# ifdef O_ASYNC
1177 mask |= O_ASYNC;
1178# endif
1179# ifdef O_SYNC
1180 mask |= O_SYNC;
1181# endif
1182 if ((file->oflags & mask) == (arg & mask))
1183 rc = 0;
1184 else
1185 {
1186# if K_OS == K_OS_WINDOWS
1187 assert(0);
1188 errno = EINVAL;
1189 rc = -1;
1190# else
1191 rc = fcntl(file->native, F_SETFL, arg);
1192 if (rc != -1)
1193 file->flags = (file->flags & ~mask) | (arg & mask);
1194# endif
1195 }
1196 break;
1197 }
1198
1199 case F_DUPFD:
1200 {
1201# if K_OS == K_OS_WINDOWS
1202 HANDLE hNew = INVALID_HANDLE_VALUE;
1203 if (DuplicateHandle(GetCurrentProcess(),
1204 (HANDLE)file->native,
1205 GetCurrentProcess(),
1206 &hNew,
1207 0,
1208 FALSE /* bInheritHandle */,
1209 DUPLICATE_SAME_ACCESS))
1210 rc = shfile_insert(pfdtab, (intptr_t)hNew, file->oflags, file->shflags, arg, "shfile_fcntl");
1211 else
1212 rc = shfile_dos2errno(GetLastError());
1213# else
1214 int nativeNew = fcntl(file->native F_DUPFD, SHFILE_UNIX_MIN_FD);
1215 if (nativeNew != -1)
1216 rc = shfile_insert(pfdtab, nativeNew, file->oflags, file->shflags, arg, "shfile_fcntl");
1217# endif
1218 break;
1219 }
1220
1221 default:
1222 errno = -EINVAL;
1223 rc = -1;
1224 break;
1225 }
1226
1227 shfile_put(pfdtab, file, &tmp);
1228 }
1229 else
1230 rc = -1;
1231
1232#else
1233 rc = fcntl(fd, cmd, arg);
1234#endif
1235
1236 switch (cmd)
1237 {
1238 case F_GETFL: TRACE2((NULL, "shfile_fcntl(%d,F_GETFL,ignored=%d) -> %d [%d]\n", fd, arg, rc, errno)); break;
1239 case F_SETFL: TRACE2((NULL, "shfile_fcntl(%d,F_SETFL,newflags=%#x) -> %d [%d]\n", fd, arg, rc, errno)); break;
1240 case F_DUPFD: TRACE2((NULL, "shfile_fcntl(%d,F_DUPFS,minfd=%d) -> %d [%d]\n", fd, arg, rc, errno)); break;
1241 default: TRACE2((NULL, "shfile_fcntl(%d,%d,%d) -> %d [%d]\n", fd, cmd, arg, rc, errno)); break;
1242 }
1243 return rc;
1244}
1245
1246int shfile_stat(shfdtab *pfdtab, const char *path, struct stat *pst)
1247{
1248#ifdef SHFILE_IN_USE
1249 char abspath[SHFILE_MAX_PATH];
1250 int rc;
1251 rc = shfile_make_path(pfdtab, path, &abspath[0]);
1252 if (!rc)
1253 {
1254# if K_OS == K_OS_WINDOWS
1255 rc = stat(abspath, pst); /** @todo re-implement stat. */
1256# else
1257 rc = stat(abspath, pst);
1258# endif
1259 }
1260 TRACE2((NULL, "shfile_stat(,%s,) -> %d [%d]\n", path, rc, errno));
1261 return rc;
1262#else
1263 return stat(path, pst);
1264#endif
1265}
1266
1267int shfile_lstat(shfdtab *pfdtab, const char *path, struct stat *pst)
1268{
1269 int rc;
1270#ifdef SHFILE_IN_USE
1271 char abspath[SHFILE_MAX_PATH];
1272
1273 rc = shfile_make_path(pfdtab, path, &abspath[0]);
1274 if (!rc)
1275 {
1276# if K_OS == K_OS_WINDOWS
1277 rc = stat(abspath, pst); /** @todo implement lstat. */
1278# else
1279 rc = lstat(abspath, pst);
1280# endif
1281 }
1282#else
1283 rc = stat(path, pst);
1284#endif
1285 TRACE2((NULL, "shfile_stat(,%s,) -> %d [%d]\n", path, rc, errno));
1286 return rc;
1287}
1288
1289/**
1290 * chdir().
1291 */
1292int shfile_chdir(shfdtab *pfdtab, const char *path)
1293{
1294 shinstance *psh = shthread_get_shell();
1295 int rc;
1296#ifdef SHFILE_IN_USE
1297 char abspath[SHFILE_MAX_PATH];
1298
1299 rc = shfile_make_path(pfdtab, path, &abspath[0]);
1300 if (!rc)
1301 {
1302 char *abspath_copy = sh_strdup(psh, abspath);
1303 char *free_me = abspath_copy;
1304 rc = chdir(path);
1305 if (!rc)
1306 {
1307 shmtxtmp tmp;
1308 shmtx_enter(&pfdtab->mtx, &tmp);
1309
1310 free_me = pfdtab->cwd;
1311 pfdtab->cwd = abspath_copy;
1312
1313 shmtx_leave(&pfdtab->mtx, &tmp);
1314 }
1315 sh_free(psh, free_me);
1316 }
1317 else
1318 rc = -1;
1319#else
1320 rc = chdir(path);
1321#endif
1322
1323 TRACE2((psh, "shfile_chdir(,%s) -> %d [%d]\n", path, rc, errno));
1324 return rc;
1325}
1326
1327/**
1328 * getcwd().
1329 */
1330char *shfile_getcwd(shfdtab *pfdtab, char *buf, int size)
1331{
1332 char *ret;
1333#ifdef SHFILE_IN_USE
1334
1335 ret = NULL;
1336 if (buf && !size)
1337 errno = -EINVAL;
1338 else
1339 {
1340 size_t cwd_size;
1341 shmtxtmp tmp;
1342 shmtx_enter(&pfdtab->mtx, &tmp);
1343
1344 cwd_size = strlen(pfdtab->cwd) + 1;
1345 if (buf)
1346 {
1347 if (cwd_size <= (size_t)size)
1348 ret = memcpy(buf, pfdtab->cwd, cwd_size);
1349 else
1350 errno = ERANGE;
1351 }
1352 else
1353 {
1354 if (size < cwd_size)
1355 size = (int)cwd_size;
1356 ret = sh_malloc(shthread_get_shell(), size);
1357 if (ret)
1358 ret = memcpy(ret, pfdtab->cwd, cwd_size);
1359 else
1360 errno = ENOMEM;
1361 }
1362
1363 shmtx_leave(&pfdtab->mtx, &tmp);
1364 }
1365#else
1366 ret = getcwd(buf, size);
1367#endif
1368
1369 TRACE2((NULL, "shfile_getcwd(,%p,%d) -> %s [%d]\n", buf, size, ret, errno));
1370 return ret;
1371}
1372
1373/**
1374 * access().
1375 */
1376int shfile_access(shfdtab *pfdtab, const char *path, int type)
1377{
1378 int rc;
1379#ifdef SHFILE_IN_USE
1380 char abspath[SHFILE_MAX_PATH];
1381
1382 rc = shfile_make_path(pfdtab, path, &abspath[0]);
1383 if (!rc)
1384 {
1385# ifdef _MSC_VER
1386 if (type & X_OK)
1387 type = (type & ~X_OK) | R_OK;
1388# endif
1389 rc = access(abspath, type);
1390 }
1391#else
1392# ifdef _MSC_VER
1393 if (type & X_OK)
1394 type = (type & ~X_OK) | R_OK;
1395# endif
1396 rc = access(path, type);
1397#endif
1398
1399 TRACE2((NULL, "shfile_access(,%s,%#x) -> %d [%d]\n", path, type, rc, errno));
1400 return rc;
1401}
1402
1403/**
1404 * isatty()
1405 */
1406int shfile_isatty(shfdtab *pfdtab, int fd)
1407{
1408 int rc;
1409#ifdef SHFILE_IN_USE
1410 shmtxtmp tmp;
1411 shfile *file = shfile_get(pfdtab, fd, &tmp);
1412 if (file)
1413 {
1414# if K_OS == K_OS_WINDOWS
1415 rc = (file->shflags & SHFILE_FLAGS_TYPE_MASK) == SHFILE_FLAGS_TTY;
1416# else
1417 rc = isatty(file->native);
1418# endif
1419 shfile_put(pfdtab, file, &tmp);
1420 }
1421 else
1422 rc = 0;
1423#else
1424 rc = isatty(fd);
1425#endif
1426
1427 TRACE2((NULL, "isatty(%d) -> %d [%d]\n", fd, rc, errno));
1428 return rc;
1429}
1430
1431/**
1432 * fcntl F_SETFD / FD_CLOEXEC.
1433 */
1434int shfile_cloexec(shfdtab *pfdtab, int fd, int closeit)
1435{
1436 int rc;
1437#ifdef SHFILE_IN_USE
1438 shmtxtmp tmp;
1439 shfile *file = shfile_get(pfdtab, fd, &tmp);
1440 if (file)
1441 {
1442 if (closeit)
1443 file->shflags |= SHFILE_FLAGS_CLOSE_ON_EXEC;
1444 else
1445 file->shflags &= ~SHFILE_FLAGS_CLOSE_ON_EXEC;
1446 shfile_put(pfdtab, file, &tmp);
1447 }
1448 else
1449 rc = -1;
1450#else
1451 rc = fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0)
1452 | (closeit ? FD_CLOEXEC : 0));
1453#endif
1454
1455 TRACE2((NULL, "shfile_cloexec(%d, %d) -> %d [%d]\n", fd, closeit, rc, errno));
1456 return rc;
1457}
1458
1459
1460int shfile_ioctl(shfdtab *pfdtab, int fd, unsigned long request, void *buf)
1461{
1462 int rc;
1463#ifdef SHFILE_IN_USE
1464 shmtxtmp tmp;
1465 shfile *file = shfile_get(pfdtab, fd, &tmp);
1466 if (file)
1467 {
1468# if K_OS == K_OS_WINDOWS
1469 rc = -1;
1470 errno = ENOSYS;
1471# else
1472 rc = ioctl(file->native, request, buf);
1473# endif
1474 shfile_put(pfdtab, file, &tmp);
1475 }
1476 else
1477 rc = -1;
1478#else
1479 rc = ioctl(fd, request, buf);
1480#endif
1481
1482 TRACE2((NULL, "ioctl(%d, %#x, %p) -> %d\n", fd, request, buf, rc));
1483 return rc;
1484}
1485
1486
1487mode_t shfile_get_umask(shfdtab *pfdtab)
1488{
1489 /** @todo */
1490 return 022;
1491}
1492
1493void shfile_set_umask(shfdtab *pfdtab, mode_t mask)
1494{
1495 /** @todo */
1496 (void)mask;
1497}
1498
1499
1500
1501shdir *shfile_opendir(shfdtab *pfdtab, const char *dir)
1502{
1503#ifdef SHFILE_IN_USE
1504 shdir *pdir = NULL;
1505
1506 if (g_pfnNtQueryDirectoryFile)
1507 {
1508 char abspath[SHFILE_MAX_PATH];
1509 if (shfile_make_path(pfdtab, dir, &abspath[0]) == 0)
1510 {
1511 HANDLE hFile;
1512 SECURITY_ATTRIBUTES SecurityAttributes;
1513
1514 SecurityAttributes.nLength = sizeof(SecurityAttributes);
1515 SecurityAttributes.lpSecurityDescriptor = NULL;
1516 SecurityAttributes.bInheritHandle = FALSE;
1517
1518 hFile = CreateFileA(abspath,
1519 GENERIC_READ,
1520 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
1521 &SecurityAttributes,
1522 OPEN_EXISTING,
1523 FILE_ATTRIBUTE_DIRECTORY | FILE_FLAG_BACKUP_SEMANTICS,
1524 NULL /* hTemplateFile */);
1525 if (hFile != INVALID_HANDLE_VALUE)
1526 {
1527 pdir = (shdir *)sh_malloc(shthread_get_shell(), sizeof(*pdir));
1528 if (pdir)
1529 {
1530 pdir->pfdtab = pfdtab;
1531 pdir->native = hFile;
1532 pdir->off = ~(size_t)0;
1533 }
1534 else
1535 CloseHandle(hFile);
1536 }
1537 else
1538 shfile_dos2errno(GetLastError());
1539 }
1540 }
1541 else
1542 errno = ENOSYS;
1543 return pdir;
1544#else
1545 return (shdir *)opendir(dir);
1546#endif
1547}
1548
1549shdirent *shfile_readdir(struct shdir *pdir)
1550{
1551#ifdef SHFILE_IN_USE
1552 if (pdir)
1553 {
1554 NTSTATUS rcNt;
1555
1556 if ( pdir->off == ~(size_t)0
1557 || pdir->off + sizeof(MY_FILE_NAMES_INFORMATION) >= pdir->cb)
1558 {
1559 MY_IO_STATUS_BLOCK Ios;
1560
1561 memset(&Ios, 0, sizeof(Ios));
1562 rcNt = g_pfnNtQueryDirectoryFile(pdir->native,
1563 NULL /*Event*/,
1564 NULL /*ApcRoutine*/,
1565 NULL /*ApcContext*/,
1566 &Ios,
1567 &pdir->buf[0],
1568 sizeof(pdir->buf),
1569 MY_FileNamesInformation,
1570 FALSE /*ReturnSingleEntry*/,
1571 NULL /*FileName*/,
1572 pdir->off == ~(size_t)0 /*RestartScan*/);
1573 if (rcNt >= 0 && rcNt != STATUS_PENDING)
1574 {
1575 pdir->cb = Ios.Information;
1576 pdir->off = 0;
1577 }
1578 else if (rcNt == STATUS_NO_MORE_FILES)
1579 errno = 0; /* wrong? */
1580 else
1581 shfile_nt2errno(rcNt);
1582 }
1583
1584 if ( pdir->off != ~(size_t)0
1585 && pdir->off + sizeof(MY_FILE_NAMES_INFORMATION) <= pdir->cb)
1586 {
1587 PMY_FILE_NAMES_INFORMATION pcur = (PMY_FILE_NAMES_INFORMATION)&pdir->buf[pdir->off];
1588 ANSI_STRING astr;
1589 UNICODE_STRING ustr;
1590
1591 astr.Length = astr.MaximumLength = sizeof(pdir->ent.name);
1592 astr.Buffer = &pdir->ent.name[0];
1593
1594 ustr.Length = ustr.MaximumLength = pcur->FileNameLength < ~(USHORT)0 ? (USHORT)pcur->FileNameLength : ~(USHORT)0;
1595 ustr.Buffer = &pcur->FileName[0];
1596
1597 rcNt = g_pfnRtlUnicodeStringToAnsiString(&astr, &ustr, 0/*AllocateDestinationString*/);
1598 if (rcNt < 0)
1599 sprintf(pdir->ent.name, "conversion-failed-%08x-rcNt=%08x-len=%u",
1600 pcur->FileIndex, rcNt, pcur->FileNameLength);
1601 if (pcur->NextEntryOffset)
1602 pdir->off += pcur->NextEntryOffset;
1603 else
1604 pdir->off = pdir->cb;
1605 return &pdir->ent;
1606 }
1607 }
1608 else
1609 errno = EINVAL;
1610 return NULL;
1611#else
1612 struct dirent *pde = readdir((DIR *)pdir);
1613 return pde ? (shdirent *)&pde->d_name[0] : NULL;
1614#endif
1615}
1616
1617void shfile_closedir(struct shdir *pdir)
1618{
1619#ifdef SHFILE_IN_USE
1620 if (pdir)
1621 {
1622 CloseHandle(pdir->native);
1623 pdir->pfdtab = NULL;
1624 pdir->native = INVALID_HANDLE_VALUE;
1625 sh_free(shthread_get_shell(), pdir);
1626 }
1627 else
1628 errno = EINVAL;
1629#else
1630 closedir((DIR *)pdir);
1631#endif
1632}
1633
Note: See TracBrowser for help on using the repository browser.