/win32/win32.c
C | 5274 lines | 4881 code | 290 blank | 103 comment | 472 complexity | e2015b87517cbd2087bc184fc8c77f91 MD5 | raw file
Possible License(s): LGPL-2.1, AGPL-3.0, GPL-2.0, BSD-3-Clause
Large files files are truncated, but you can click here to view the full file
- /*
- * Copyright (c) 1993, Intergraph Corporation
- *
- * You may distribute under the terms of either the GNU General Public
- * License or the Artistic License, as specified in the perl README file.
- *
- * Various Unix compatibility functions and NT specific functions.
- *
- * Some of this code was derived from the MSDOS port(s) and the OS/2 port.
- *
- */
- #include "ruby/ruby.h"
- #include "ruby/encoding.h"
- #include "dln.h"
- #include <fcntl.h>
- #include <process.h>
- #include <sys/stat.h>
- /* #include <sys/wait.h> */
- #include <stdio.h>
- #include <stdlib.h>
- #include <errno.h>
- #include <assert.h>
- #include <ctype.h>
- #include <windows.h>
- #include <winbase.h>
- #include <wincon.h>
- #include <share.h>
- #include <shlobj.h>
- #include <mbstring.h>
- #if _MSC_VER >= 1400
- #include <crtdbg.h>
- #include <rtcapi.h>
- #endif
- #ifdef __MINGW32__
- #include <mswsock.h>
- #endif
- #include "ruby/win32.h"
- #include "win32/dir.h"
- #define isdirsep(x) ((x) == '/' || (x) == '\\')
- #undef stat
- #undef fclose
- #undef close
- #undef setsockopt
- #if defined __BORLANDC__
- # define _filbuf _fgetc
- # define _flsbuf _fputc
- # define enough_to_get(n) (--(n) >= 0)
- # define enough_to_put(n) (++(n) < 0)
- #else
- # define enough_to_get(n) (--(n) >= 0)
- # define enough_to_put(n) (--(n) >= 0)
- #endif
- #ifdef WIN32_DEBUG
- #define Debug(something) something
- #else
- #define Debug(something) /* nothing */
- #endif
- #define TO_SOCKET(x) _get_osfhandle(x)
- static struct ChildRecord *CreateChild(const char *, const char *, SECURITY_ATTRIBUTES *, HANDLE, HANDLE, HANDLE);
- static int has_redirection(const char *);
- int rb_w32_wait_events(HANDLE *events, int num, DWORD timeout);
- static int rb_w32_open_osfhandle(intptr_t osfhandle, int flags);
- #define RUBY_CRITICAL(expr) do { expr; } while (0)
- /* errno mapping */
- static struct {
- DWORD winerr;
- int err;
- } errmap[] = {
- { ERROR_INVALID_FUNCTION, EINVAL },
- { ERROR_FILE_NOT_FOUND, ENOENT },
- { ERROR_PATH_NOT_FOUND, ENOENT },
- { ERROR_TOO_MANY_OPEN_FILES, EMFILE },
- { ERROR_ACCESS_DENIED, EACCES },
- { ERROR_INVALID_HANDLE, EBADF },
- { ERROR_ARENA_TRASHED, ENOMEM },
- { ERROR_NOT_ENOUGH_MEMORY, ENOMEM },
- { ERROR_INVALID_BLOCK, ENOMEM },
- { ERROR_BAD_ENVIRONMENT, E2BIG },
- { ERROR_BAD_FORMAT, ENOEXEC },
- { ERROR_INVALID_ACCESS, EINVAL },
- { ERROR_INVALID_DATA, EINVAL },
- { ERROR_INVALID_DRIVE, ENOENT },
- { ERROR_CURRENT_DIRECTORY, EACCES },
- { ERROR_NOT_SAME_DEVICE, EXDEV },
- { ERROR_NO_MORE_FILES, ENOENT },
- { ERROR_WRITE_PROTECT, EROFS },
- { ERROR_BAD_UNIT, ENODEV },
- { ERROR_NOT_READY, ENXIO },
- { ERROR_BAD_COMMAND, EACCES },
- { ERROR_CRC, EACCES },
- { ERROR_BAD_LENGTH, EACCES },
- { ERROR_SEEK, EIO },
- { ERROR_NOT_DOS_DISK, EACCES },
- { ERROR_SECTOR_NOT_FOUND, EACCES },
- { ERROR_OUT_OF_PAPER, EACCES },
- { ERROR_WRITE_FAULT, EIO },
- { ERROR_READ_FAULT, EIO },
- { ERROR_GEN_FAILURE, EACCES },
- { ERROR_LOCK_VIOLATION, EACCES },
- { ERROR_SHARING_VIOLATION, EACCES },
- { ERROR_WRONG_DISK, EACCES },
- { ERROR_SHARING_BUFFER_EXCEEDED, EACCES },
- { ERROR_BAD_NETPATH, ENOENT },
- { ERROR_NETWORK_ACCESS_DENIED, EACCES },
- { ERROR_BAD_NET_NAME, ENOENT },
- { ERROR_FILE_EXISTS, EEXIST },
- { ERROR_CANNOT_MAKE, EACCES },
- { ERROR_FAIL_I24, EACCES },
- { ERROR_INVALID_PARAMETER, EINVAL },
- { ERROR_NO_PROC_SLOTS, EAGAIN },
- { ERROR_DRIVE_LOCKED, EACCES },
- { ERROR_BROKEN_PIPE, EPIPE },
- { ERROR_DISK_FULL, ENOSPC },
- { ERROR_INVALID_TARGET_HANDLE, EBADF },
- { ERROR_INVALID_HANDLE, EINVAL },
- { ERROR_WAIT_NO_CHILDREN, ECHILD },
- { ERROR_CHILD_NOT_COMPLETE, ECHILD },
- { ERROR_DIRECT_ACCESS_HANDLE, EBADF },
- { ERROR_NEGATIVE_SEEK, EINVAL },
- { ERROR_SEEK_ON_DEVICE, EACCES },
- { ERROR_DIR_NOT_EMPTY, ENOTEMPTY },
- { ERROR_DIRECTORY, ENOTDIR },
- { ERROR_NOT_LOCKED, EACCES },
- { ERROR_BAD_PATHNAME, ENOENT },
- { ERROR_MAX_THRDS_REACHED, EAGAIN },
- { ERROR_LOCK_FAILED, EACCES },
- { ERROR_ALREADY_EXISTS, EEXIST },
- { ERROR_INVALID_STARTING_CODESEG, ENOEXEC },
- { ERROR_INVALID_STACKSEG, ENOEXEC },
- { ERROR_INVALID_MODULETYPE, ENOEXEC },
- { ERROR_INVALID_EXE_SIGNATURE, ENOEXEC },
- { ERROR_EXE_MARKED_INVALID, ENOEXEC },
- { ERROR_BAD_EXE_FORMAT, ENOEXEC },
- { ERROR_ITERATED_DATA_EXCEEDS_64k,ENOEXEC },
- { ERROR_INVALID_MINALLOCSIZE, ENOEXEC },
- { ERROR_DYNLINK_FROM_INVALID_RING,ENOEXEC },
- { ERROR_IOPL_NOT_ENABLED, ENOEXEC },
- { ERROR_INVALID_SEGDPL, ENOEXEC },
- { ERROR_AUTODATASEG_EXCEEDS_64k, ENOEXEC },
- { ERROR_RING2SEG_MUST_BE_MOVABLE, ENOEXEC },
- { ERROR_RELOC_CHAIN_XEEDS_SEGLIM, ENOEXEC },
- { ERROR_INFLOOP_IN_RELOC_CHAIN, ENOEXEC },
- { ERROR_FILENAME_EXCED_RANGE, ENOENT },
- { ERROR_NESTING_NOT_ALLOWED, EAGAIN },
- #ifndef ERROR_PIPE_LOCAL
- #define ERROR_PIPE_LOCAL 229L
- #endif
- { ERROR_PIPE_LOCAL, EPIPE },
- { ERROR_BAD_PIPE, EPIPE },
- { ERROR_PIPE_BUSY, EAGAIN },
- { ERROR_NO_DATA, EPIPE },
- { ERROR_PIPE_NOT_CONNECTED, EPIPE },
- { ERROR_OPERATION_ABORTED, EINTR },
- { ERROR_NOT_ENOUGH_QUOTA, ENOMEM },
- { ERROR_MOD_NOT_FOUND, ENOENT },
- { WSAENAMETOOLONG, ENAMETOOLONG },
- { WSAENOTEMPTY, ENOTEMPTY },
- { WSAEINTR, EINTR },
- { WSAEBADF, EBADF },
- { WSAEACCES, EACCES },
- { WSAEFAULT, EFAULT },
- { WSAEINVAL, EINVAL },
- { WSAEMFILE, EMFILE },
- };
- int
- rb_w32_map_errno(DWORD winerr)
- {
- int i;
- if (winerr == 0) {
- return 0;
- }
- for (i = 0; i < sizeof(errmap) / sizeof(*errmap); i++) {
- if (errmap[i].winerr == winerr) {
- return errmap[i].err;
- }
- }
- if (winerr >= WSABASEERR) {
- return winerr;
- }
- return EINVAL;
- }
- #define map_errno rb_w32_map_errno
- static const char *NTLoginName;
- static OSVERSIONINFO osver;
- static void
- get_version(void)
- {
- memset(&osver, 0, sizeof(OSVERSIONINFO));
- osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
- GetVersionEx(&osver);
- }
- #ifdef _M_IX86
- DWORD
- rb_w32_osid(void)
- {
- return osver.dwPlatformId;
- }
- #endif
- static DWORD
- rb_w32_osver(void)
- {
- return osver.dwMajorVersion;
- }
- #define IsWinNT() rb_w32_iswinnt()
- #define IsWin95() rb_w32_iswin95()
- #ifdef WIN95
- #define IfWin95(win95, winnt) (IsWin95() ? (win95) : (winnt))
- #else
- #define IfWin95(win95, winnt) (winnt)
- #endif
- HANDLE
- GetCurrentThreadHandle(void)
- {
- static HANDLE current_process_handle = NULL;
- HANDLE h;
- if (!current_process_handle)
- current_process_handle = GetCurrentProcess();
- if (!DuplicateHandle(current_process_handle, GetCurrentThread(),
- current_process_handle, &h,
- 0, FALSE, DUPLICATE_SAME_ACCESS))
- return NULL;
- return h;
- }
- /* simulate flock by locking a range on the file */
- #define LK_ERR(f,i) \
- do { \
- if (f) \
- i = 0; \
- else { \
- DWORD err = GetLastError(); \
- if (err == ERROR_LOCK_VIOLATION || err == ERROR_IO_PENDING) \
- errno = EWOULDBLOCK; \
- else if (err == ERROR_NOT_LOCKED) \
- i = 0; \
- else \
- errno = map_errno(err); \
- } \
- } while (0)
- #define LK_LEN ULONG_MAX
- static uintptr_t
- flock_winnt(uintptr_t self, int argc, uintptr_t* argv)
- {
- OVERLAPPED o;
- int i = -1;
- const HANDLE fh = (HANDLE)self;
- const int oper = argc;
- memset(&o, 0, sizeof(o));
- switch(oper) {
- case LOCK_SH: /* shared lock */
- LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, LK_LEN, &o), i);
- break;
- case LOCK_EX: /* exclusive lock */
- LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, LK_LEN, &o), i);
- break;
- case LOCK_SH|LOCK_NB: /* non-blocking shared lock */
- LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, LK_LEN, &o), i);
- break;
- case LOCK_EX|LOCK_NB: /* non-blocking exclusive lock */
- LK_ERR(LockFileEx(fh,
- LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
- 0, LK_LEN, LK_LEN, &o), i);
- break;
- case LOCK_UN: /* unlock lock */
- case LOCK_UN|LOCK_NB: /* unlock is always non-blocking, I hope */
- LK_ERR(UnlockFileEx(fh, 0, LK_LEN, LK_LEN, &o), i);
- break;
- default: /* unknown */
- errno = EINVAL;
- break;
- }
- return i;
- }
- #ifdef WIN95
- static uintptr_t
- flock_win95(uintptr_t self, int argc, uintptr_t* argv)
- {
- int i = -1;
- const HANDLE fh = (HANDLE)self;
- const int oper = argc;
- switch(oper) {
- case LOCK_EX:
- do {
- LK_ERR(LockFile(fh, 0, 0, LK_LEN, LK_LEN), i);
- } while (i && errno == EWOULDBLOCK);
- break;
- case LOCK_EX|LOCK_NB:
- LK_ERR(LockFile(fh, 0, 0, LK_LEN, LK_LEN), i);
- break;
- case LOCK_UN:
- case LOCK_UN|LOCK_NB:
- LK_ERR(UnlockFile(fh, 0, 0, LK_LEN, LK_LEN), i);
- break;
- default:
- errno = EINVAL;
- break;
- }
- return i;
- }
- #endif
- #undef LK_ERR
- int
- flock(int fd, int oper)
- {
- #ifdef WIN95
- static asynchronous_func_t locker = NULL;
- if (!locker) {
- if (IsWinNT())
- locker = flock_winnt;
- else
- locker = flock_win95;
- }
- #else
- const asynchronous_func_t locker = flock_winnt;
- #endif
- return rb_w32_asynchronize(locker,
- (VALUE)_get_osfhandle(fd), oper, NULL,
- (DWORD)-1);
- }
- static inline WCHAR *
- translate_wchar(WCHAR *p, int from, int to)
- {
- for (; *p; p++) {
- if (*p == from)
- *p = to;
- }
- return p;
- }
- static inline char *
- translate_char(char *p, int from, int to)
- {
- while (*p) {
- if ((unsigned char)*p == from)
- *p = to;
- p = CharNext(p);
- }
- return p;
- }
- #ifndef CSIDL_LOCAL_APPDATA
- #define CSIDL_LOCAL_APPDATA 28
- #endif
- #ifndef CSIDL_COMMON_APPDATA
- #define CSIDL_COMMON_APPDATA 35
- #endif
- #ifndef CSIDL_WINDOWS
- #define CSIDL_WINDOWS 36
- #endif
- #ifndef CSIDL_SYSTEM
- #define CSIDL_SYSTEM 37
- #endif
- #ifndef CSIDL_PROFILE
- #define CSIDL_PROFILE 40
- #endif
- static BOOL
- get_special_folder(int n, WCHAR *env)
- {
- LPITEMIDLIST pidl;
- LPMALLOC alloc;
- BOOL f = FALSE;
- if (SHGetSpecialFolderLocation(NULL, n, &pidl) == 0) {
- f = SHGetPathFromIDListW(pidl, env);
- SHGetMalloc(&alloc);
- alloc->lpVtbl->Free(alloc, pidl);
- alloc->lpVtbl->Release(alloc);
- }
- return f;
- }
- static void
- regulate_path(WCHAR *path)
- {
- WCHAR *p = translate_wchar(path, L'\\', L'/');
- if (p - path == 2 && path[1] == L':') {
- *p++ = L'/';
- *p = L'\0';
- }
- }
- static UINT
- get_system_directory(WCHAR *path, UINT len)
- {
- HANDLE hKernel = GetModuleHandle("kernel32.dll");
- if (hKernel) {
- typedef UINT WINAPI wgetdir_func(WCHAR*, UINT);
- FARPROC ptr = GetProcAddress(hKernel, "GetSystemWindowsDirectoryW");
- if (ptr) {
- return (*(wgetdir_func *)ptr)(path, len);
- }
- }
- return GetWindowsDirectoryW(path, len);
- }
- #define numberof(array) (sizeof(array) / sizeof(*array))
- static void
- init_env(void)
- {
- static const WCHAR TMPDIR[] = L"TMPDIR";
- WCHAR env[_MAX_PATH];
- WCHAR *buf;
- DWORD len;
- BOOL f;
- if (!GetEnvironmentVariableW(L"HOME", env, numberof(env))) {
- f = FALSE;
- if (GetEnvironmentVariableW(L"HOMEDRIVE", env, numberof(env)))
- len = lstrlenW(env);
- else
- len = 0;
- if (GetEnvironmentVariableW(L"HOMEPATH", env + len, numberof(env) - len) || len) {
- f = TRUE;
- }
- else if (GetEnvironmentVariableW(L"USERPROFILE", env, numberof(env))) {
- f = TRUE;
- }
- else if (get_special_folder(CSIDL_PROFILE, env)) {
- f = TRUE;
- }
- else if (get_special_folder(CSIDL_PERSONAL, env)) {
- f = TRUE;
- }
- if (f) {
- regulate_path(env);
- buf = ALLOCA_N(WCHAR, 5 + lstrlenW(env) + 1);
- wsprintfW(buf, L"HOME=%s", env);
- _wputenv(buf);
- }
- }
- if (!GetEnvironmentVariableW(L"USER", env, numberof(env))) {
- if (!GetEnvironmentVariableW(L"USERNAME", env, numberof(env)) &&
- !GetUserNameW(env, (len = numberof(env), &len))) {
- NTLoginName = "<Unknown>";
- return;
- }
- buf = ALLOCA_N(WCHAR, 5 + lstrlenW(env) + 1);
- wsprintfW(buf, L"USER=%s", env);
- _wputenv(buf);
- }
- NTLoginName = strdup(rb_w32_getenv("USER"));
- if (!GetEnvironmentVariableW(TMPDIR, env, numberof(env)) &&
- !GetEnvironmentVariableW(L"TMP", env, numberof(env)) &&
- !GetEnvironmentVariableW(L"TEMP", env, numberof(env)) &&
- (get_special_folder(CSIDL_LOCAL_APPDATA, env) ||
- get_system_directory(env, numberof(env)))) {
- static const WCHAR temp[] = L"temp";
- WCHAR *p = translate_wchar(env, L'\\', L'/');
- if (*(p - 1) != L'/') *p++ = L'/';
- if (p - env + numberof(temp) < numberof(env)) {
- memcpy(p, temp, sizeof(temp));
- buf = ALLOCA_N(WCHAR, lstrlenW(TMPDIR) + 1 + lstrlenW(env) + 1);
- wsprintfW(buf, L"%s=%s", TMPDIR, env);
- _wputenv(buf);
- }
- }
- }
- typedef BOOL (WINAPI *cancel_io_t)(HANDLE);
- static cancel_io_t cancel_io = NULL;
- static void
- init_func(void)
- {
- if (!cancel_io)
- cancel_io = (cancel_io_t)GetProcAddress(GetModuleHandle("kernel32"),
- "CancelIo");
- }
- static void init_stdhandle(void);
- #if RT_VER >= 80
- static void
- invalid_parameter(const wchar_t *expr, const wchar_t *func, const wchar_t *file, unsigned int line, uintptr_t dummy)
- {
- // nothing to do
- }
- int ruby_w32_rtc_error;
- static int __cdecl
- rtc_error_handler(int e, const char *src, int line, const char *exe, const char *fmt, ...)
- {
- va_list ap;
- VALUE str;
- if (!ruby_w32_rtc_error) return 0;
- str = rb_sprintf("%s:%d: ", src, line);
- va_start(ap, fmt);
- rb_str_vcatf(str, fmt, ap);
- va_end(ap);
- rb_str_cat(str, "\n", 1);
- rb_write_error2(RSTRING_PTR(str), RSTRING_LEN(str));
- return 0;
- }
- #endif
- static CRITICAL_SECTION select_mutex;
- static int NtSocketsInitialized = 0;
- static st_table *socklist = NULL;
- static char *envarea;
- static void
- exit_handler(void)
- {
- if (NtSocketsInitialized) {
- WSACleanup();
- st_free_table(socklist);
- socklist = NULL;
- NtSocketsInitialized = 0;
- }
- if (envarea) {
- FreeEnvironmentStrings(envarea);
- envarea = NULL;
- }
- DeleteCriticalSection(&select_mutex);
- }
- static void
- StartSockets(void)
- {
- WORD version;
- WSADATA retdata;
- //
- // initalize the winsock interface and insure that it's
- // cleaned up at exit.
- //
- version = MAKEWORD(2, 0);
- if (WSAStartup(version, &retdata))
- rb_fatal ("Unable to locate winsock library!\n");
- if (LOBYTE(retdata.wVersion) != 2)
- rb_fatal("could not find version 2 of winsock dll\n");
- socklist = st_init_numtable();
- NtSocketsInitialized = 1;
- }
- //
- // Initialization stuff
- //
- void
- rb_w32_sysinit(int *argc, char ***argv)
- {
- #if RT_VER >= 80
- static void set_pioinfo_extra(void);
- _CrtSetReportMode(_CRT_ASSERT, 0);
- _set_invalid_parameter_handler(invalid_parameter);
- _RTC_SetErrorFunc(rtc_error_handler);
- set_pioinfo_extra();
- #endif
- get_version();
- //
- // subvert cmd.exe's feeble attempt at command line parsing
- //
- *argc = rb_w32_cmdvector(GetCommandLine(), argv);
- //
- // Now set up the correct time stuff
- //
- tzset();
- init_env();
- init_func();
- init_stdhandle();
- InitializeCriticalSection(&select_mutex);
- atexit(exit_handler);
- // Initialize Winsock
- StartSockets();
- }
- char *
- getlogin(void)
- {
- return (char *)NTLoginName;
- }
- #define MAXCHILDNUM 256 /* max num of child processes */
- static struct ChildRecord {
- HANDLE hProcess; /* process handle */
- rb_pid_t pid; /* process id */
- } ChildRecord[MAXCHILDNUM];
- #define FOREACH_CHILD(v) do { \
- struct ChildRecord* v; \
- for (v = ChildRecord; v < ChildRecord + sizeof(ChildRecord) / sizeof(ChildRecord[0]); ++v)
- #define END_FOREACH_CHILD } while (0)
- static struct ChildRecord *
- FindChildSlot(rb_pid_t pid)
- {
- FOREACH_CHILD(child) {
- if (child->pid == pid) {
- return child;
- }
- } END_FOREACH_CHILD;
- return NULL;
- }
- static struct ChildRecord *
- FindChildSlotByHandle(HANDLE h)
- {
- FOREACH_CHILD(child) {
- if (child->hProcess == h) {
- return child;
- }
- } END_FOREACH_CHILD;
- return NULL;
- }
- static void
- CloseChildHandle(struct ChildRecord *child)
- {
- HANDLE h = child->hProcess;
- child->hProcess = NULL;
- child->pid = 0;
- CloseHandle(h);
- }
- static struct ChildRecord *
- FindFreeChildSlot(void)
- {
- FOREACH_CHILD(child) {
- if (!child->pid) {
- child->pid = -1; /* lock the slot */
- child->hProcess = NULL;
- return child;
- }
- } END_FOREACH_CHILD;
- return NULL;
- }
- /*
- ruby -lne 'BEGIN{$cmds = Hash.new(0); $mask = 1}'
- -e '$cmds[$_.downcase] |= $mask' -e '$mask <<= 1 if ARGF.eof'
- -e 'END{$cmds.sort.each{|n,f|puts " \"\\#{f.to_s(8)}\" #{n.dump} + 1,"}}'
- 98cmd ntcmd
- */
- static const char *const szInternalCmds[] = {
- "\2" "assoc" + 1,
- "\3" "break" + 1,
- "\3" "call" + 1,
- "\3" "cd" + 1,
- "\1" "chcp" + 1,
- "\3" "chdir" + 1,
- "\3" "cls" + 1,
- "\2" "color" + 1,
- "\3" "copy" + 1,
- "\1" "ctty" + 1,
- "\3" "date" + 1,
- "\3" "del" + 1,
- "\3" "dir" + 1,
- "\3" "echo" + 1,
- "\2" "endlocal" + 1,
- "\3" "erase" + 1,
- "\3" "exit" + 1,
- "\3" "for" + 1,
- "\2" "ftype" + 1,
- "\3" "goto" + 1,
- "\3" "if" + 1,
- "\1" "lfnfor" + 1,
- "\1" "lh" + 1,
- "\1" "lock" + 1,
- "\3" "md" + 1,
- "\3" "mkdir" + 1,
- "\2" "move" + 1,
- "\3" "path" + 1,
- "\3" "pause" + 1,
- "\2" "popd" + 1,
- "\3" "prompt" + 1,
- "\2" "pushd" + 1,
- "\3" "rd" + 1,
- "\3" "rem" + 1,
- "\3" "ren" + 1,
- "\3" "rename" + 1,
- "\3" "rmdir" + 1,
- "\3" "set" + 1,
- "\2" "setlocal" + 1,
- "\3" "shift" + 1,
- "\2" "start" + 1,
- "\3" "time" + 1,
- "\2" "title" + 1,
- "\1" "truename" + 1,
- "\3" "type" + 1,
- "\1" "unlock" + 1,
- "\3" "ver" + 1,
- "\3" "verify" + 1,
- "\3" "vol" + 1,
- };
- static int
- internal_match(const void *key, const void *elem)
- {
- return strcmp(key, *(const char *const *)elem);
- }
- static int
- is_command_com(const char *interp)
- {
- int i = strlen(interp) - 11;
- if ((i == 0 || i > 0 && isdirsep(interp[i-1])) &&
- strcasecmp(interp+i, "command.com") == 0) {
- return 1;
- }
- return 0;
- }
- static int internal_cmd_match(const char *cmdname, int nt);
- static int
- is_internal_cmd(const char *cmd, int nt)
- {
- char cmdname[9], *b = cmdname, c;
- do {
- if (!(c = *cmd++)) return 0;
- } while (isspace(c));
- while (isalpha(c)) {
- *b++ = tolower(c);
- if (b == cmdname + sizeof(cmdname)) return 0;
- c = *cmd++;
- }
- if (c == '.') c = *cmd;
- switch (c) {
- case '<': case '>': case '|':
- return 1;
- case '\0': case ' ': case '\t': case '\n':
- break;
- default:
- return 0;
- }
- *b = 0;
- return internal_cmd_match(cmdname, nt);
- }
- static int
- internal_cmd_match(const char *cmdname, int nt)
- {
- char **nm;
- nm = bsearch(cmdname, szInternalCmds,
- sizeof(szInternalCmds) / sizeof(*szInternalCmds),
- sizeof(*szInternalCmds),
- internal_match);
- if (!nm || !(nm[0][-1] & (nt ? 2 : 1)))
- return 0;
- return 1;
- }
- SOCKET
- rb_w32_get_osfhandle(int fh)
- {
- return _get_osfhandle(fh);
- }
- static int
- argv_size(char *const *argv, BOOL escape)
- {
- const char *p;
- char *const *t;
- int len, n, bs, quote;
- for (t = argv, len = 0; *t; t++) {
- for (p = *t, n = quote = bs = 0; *p; ++p) {
- switch (*p) {
- case '\\':
- ++bs;
- break;
- case '<': case '>': case '|': case '^':
- bs = 0;
- if (escape && !quote) n++;
- break;
- case '"':
- n += bs + 1; bs = 0;
- quote = 1;
- break;
- case ' ': case '\t':
- quote = 1;
- default:
- bs = 0;
- p = CharNext(p) - 1;
- break;
- }
- }
- len += p - *t + n + 1;
- if (p - *t == 0 || quote) len += 2;
- }
- return len;
- }
- static char *
- join_argv(char *cmd, char *const *argv, BOOL escape)
- {
- const char *p, *s;
- char *q, *const *t;
- int n, bs, quote;
- for (t = argv, q = cmd; p = *t; t++) {
- quote = 0;
- s = p;
- if (!*p || strpbrk(p, " \t\"'")) {
- quote = 1;
- *q++ = '"';
- }
- for (bs = 0; *p; ++p) {
- switch (*p) {
- case '\\':
- ++bs;
- break;
- case '"':
- memcpy(q, s, n = p - s); q += n; s = p;
- memset(q, '\\', ++bs); q += bs; bs = 0;
- break;
- case '<': case '>': case '|': case '^':
- if (escape && !quote) {
- memcpy(q, s, n = p - s); q += n; s = p;
- *q++ = '^';
- break;
- }
- default:
- bs = 0;
- p = CharNext(p) - 1;
- break;
- }
- }
- memcpy(q, s, n = p - s);
- q += n;
- if (quote) *q++ = '"';
- *q++ = ' ';
- }
- if (q > cmd) --q;
- *q = '\0';
- return cmd;
- }
- #ifdef HAVE_SYS_PARAM_H
- # include <sys/param.h>
- #else
- # define MAXPATHLEN 512
- #endif
- #define STRNDUPA(ptr, src, len) \
- (((char *)memcpy(((ptr) = ALLOCA_N(char, (len) + 1)), (src), (len)))[len] = 0)
- static int
- check_spawn_mode(int mode)
- {
- switch (mode) {
- case P_NOWAIT:
- case P_OVERLAY:
- return 0;
- default:
- errno = EINVAL;
- return -1;
- }
- }
- static rb_pid_t
- child_result(struct ChildRecord *child, int mode)
- {
- DWORD exitcode;
- if (!child) {
- return -1;
- }
- switch (mode) {
- case P_NOWAIT:
- return child->pid;
- case P_OVERLAY:
- WaitForSingleObject(child->hProcess, INFINITE);
- GetExitCodeProcess(child->hProcess, &exitcode);
- CloseChildHandle(child);
- _exit(exitcode);
- default:
- return -1; /* not reached */
- }
- }
- static struct ChildRecord *
- CreateChild(const char *cmd, const char *prog, SECURITY_ATTRIBUTES *psa,
- HANDLE hInput, HANDLE hOutput, HANDLE hError)
- {
- BOOL fRet;
- DWORD dwCreationFlags;
- STARTUPINFO aStartupInfo;
- PROCESS_INFORMATION aProcessInformation;
- SECURITY_ATTRIBUTES sa;
- struct ChildRecord *child;
- if (!cmd && !prog) {
- errno = EFAULT;
- return NULL;
- }
- child = FindFreeChildSlot();
- if (!child) {
- errno = EAGAIN;
- return NULL;
- }
- if (!psa) {
- sa.nLength = sizeof (SECURITY_ATTRIBUTES);
- sa.lpSecurityDescriptor = NULL;
- sa.bInheritHandle = TRUE;
- psa = &sa;
- }
- memset(&aStartupInfo, 0, sizeof (STARTUPINFO));
- memset(&aProcessInformation, 0, sizeof (PROCESS_INFORMATION));
- aStartupInfo.cb = sizeof (STARTUPINFO);
- aStartupInfo.dwFlags = STARTF_USESTDHANDLES;
- if (hInput) {
- aStartupInfo.hStdInput = hInput;
- }
- else {
- aStartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
- }
- if (hOutput) {
- aStartupInfo.hStdOutput = hOutput;
- }
- else {
- aStartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
- }
- if (hError) {
- aStartupInfo.hStdError = hError;
- }
- else {
- aStartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
- }
- dwCreationFlags = (NORMAL_PRIORITY_CLASS);
- RUBY_CRITICAL({
- fRet = CreateProcess(prog, (char *)cmd, psa, psa,
- psa->bInheritHandle, dwCreationFlags, NULL, NULL,
- &aStartupInfo, &aProcessInformation);
- errno = map_errno(GetLastError());
- });
- if (!fRet) {
- child->pid = 0; /* release the slot */
- return NULL;
- }
- CloseHandle(aProcessInformation.hThread);
- child->hProcess = aProcessInformation.hProcess;
- child->pid = (rb_pid_t)aProcessInformation.dwProcessId;
- if (!IsWinNT()) {
- /* On Win9x, make pid positive similarly to cygwin and perl */
- child->pid = -child->pid;
- }
- return child;
- }
- static int
- is_batch(const char *cmd)
- {
- int len = strlen(cmd);
- if (len <= 4) return 0;
- cmd += len - 4;
- if (*cmd++ != '.') return 0;
- if (strcasecmp(cmd, "bat") == 0) return 1;
- if (strcasecmp(cmd, "cmd") == 0) return 1;
- return 0;
- }
- rb_pid_t
- rb_w32_spawn(int mode, const char *cmd, const char *prog)
- {
- char fbuf[MAXPATHLEN];
- char *p = NULL;
- const char *shell = NULL;
- if (check_spawn_mode(mode)) return -1;
- if (prog) {
- if (!(p = dln_find_exe_r(prog, NULL, fbuf, sizeof(fbuf)))) {
- shell = prog;
- }
- else {
- shell = p;
- translate_char(p, '/', '\\');
- }
- }
- else {
- int redir = -1;
- int nt;
- while (ISSPACE(*cmd)) cmd++;
- if ((shell = getenv("RUBYSHELL")) && (redir = has_redirection(cmd))) {
- char *tmp = ALLOCA_N(char, strlen(shell) + strlen(cmd) + sizeof(" -c ") + 2);
- sprintf(tmp, "%s -c \"%s\"", shell, cmd);
- cmd = tmp;
- }
- else if ((shell = getenv("COMSPEC")) &&
- (nt = !is_command_com(shell),
- (redir < 0 ? has_redirection(cmd) : redir) ||
- is_internal_cmd(cmd, nt))) {
- char *tmp = ALLOCA_N(char, strlen(shell) + strlen(cmd) + sizeof(" /c ")
- + (nt ? 2 : 0));
- sprintf(tmp, nt ? "%s /c \"%s\"" : "%s /c %s", shell, cmd);
- cmd = tmp;
- }
- else {
- int len = 0, quote = (*cmd == '"') ? '"' : (*cmd == '\'') ? '\'' : 0;
- for (prog = cmd + !!quote;; prog = CharNext(prog)) {
- if (!*prog) {
- len = prog - cmd;
- shell = cmd;
- break;
- }
- if ((unsigned char)*prog == quote) {
- len = prog++ - cmd - 1;
- STRNDUPA(p, cmd + 1, len);
- shell = p;
- break;
- }
- if (quote) continue;
- if (ISSPACE(*prog) || strchr("<>|*?\"", *prog)) {
- len = prog - cmd;
- STRNDUPA(p, cmd, len);
- shell = p;
- break;
- }
- }
- shell = dln_find_exe_r(shell, NULL, fbuf, sizeof(fbuf));
- if (!shell) {
- shell = p ? p : cmd;
- }
- else {
- len = strlen(shell);
- if (strchr(shell, ' ')) quote = -1;
- if (shell == fbuf) {
- p = fbuf;
- }
- else if (shell != p && strchr(shell, '/')) {
- STRNDUPA(p, shell, len);
- shell = p;
- }
- if (p) translate_char(p, '/', '\\');
- if (is_batch(shell)) {
- int alen = strlen(prog);
- cmd = p = ALLOCA_N(char, len + alen + (quote ? 2 : 0) + 1);
- if (quote) *p++ = '"';
- memcpy(p, shell, len);
- p += len;
- if (quote) *p++ = '"';
- memcpy(p, prog, alen + 1);
- shell = 0;
- }
- }
- }
- }
- return child_result(CreateChild(cmd, shell, NULL, NULL, NULL, NULL), mode);
- }
- rb_pid_t
- rb_w32_aspawn(int mode, const char *prog, char *const *argv)
- {
- int len, c_switch = 0;
- BOOL ntcmd = FALSE, tmpnt;
- const char *shell;
- char *cmd, fbuf[MAXPATHLEN];
- if (check_spawn_mode(mode)) return -1;
- if (!prog) prog = argv[0];
- if ((shell = getenv("COMSPEC")) &&
- internal_cmd_match(prog, tmpnt = !is_command_com(shell))) {
- ntcmd = tmpnt;
- prog = shell;
- c_switch = 1;
- }
- else if ((cmd = dln_find_exe_r(prog, NULL, fbuf, sizeof(fbuf)))) {
- if (cmd == prog) strlcpy(cmd = fbuf, prog, sizeof(fbuf));
- translate_char(cmd, '/', '\\');
- prog = cmd;
- }
- else if (strchr(prog, '/')) {
- len = strlen(prog);
- if (len < sizeof(fbuf))
- strlcpy(cmd = fbuf, prog, sizeof(fbuf));
- else
- STRNDUPA(cmd, prog, len);
- translate_char(cmd, '/', '\\');
- prog = cmd;
- }
- if (c_switch || is_batch(prog)) {
- char *progs[2];
- progs[0] = (char *)prog;
- progs[1] = NULL;
- len = argv_size(progs, ntcmd);
- if (c_switch) len += 3;
- else ++argv;
- if (argv[0]) len += argv_size(argv, ntcmd);
- cmd = ALLOCA_N(char, len);
- join_argv(cmd, progs, ntcmd);
- if (c_switch) strlcat(cmd, " /c", len);
- if (argv[0]) join_argv(cmd + strlcat(cmd, " ", len), argv, ntcmd);
- prog = c_switch ? shell : 0;
- }
- else {
- len = argv_size(argv, FALSE);
- cmd = ALLOCA_N(char, len);
- join_argv(cmd, argv, FALSE);
- }
- return child_result(CreateChild(cmd, prog, NULL, NULL, NULL, NULL), mode);
- }
- typedef struct _NtCmdLineElement {
- struct _NtCmdLineElement *next;
- char *str;
- int len;
- int flags;
- } NtCmdLineElement;
- //
- // Possible values for flags
- //
- #define NTGLOB 0x1 // element contains a wildcard
- #define NTMALLOC 0x2 // string in element was malloc'ed
- #define NTSTRING 0x4 // element contains a quoted string
- static int
- insert(const char *path, VALUE vinfo, void *enc)
- {
- NtCmdLineElement *tmpcurr;
- NtCmdLineElement ***tail = (NtCmdLineElement ***)vinfo;
- tmpcurr = (NtCmdLineElement *)malloc(sizeof(NtCmdLineElement));
- if (!tmpcurr) return -1;
- MEMZERO(tmpcurr, NtCmdLineElement, 1);
- tmpcurr->len = strlen(path);
- tmpcurr->str = strdup(path);
- if (!tmpcurr->str) return -1;
- tmpcurr->flags |= NTMALLOC;
- **tail = tmpcurr;
- *tail = &tmpcurr->next;
- return 0;
- }
- static NtCmdLineElement **
- cmdglob(NtCmdLineElement *patt, NtCmdLineElement **tail)
- {
- char buffer[MAXPATHLEN], *buf = buffer;
- char *p;
- NtCmdLineElement **last = tail;
- int status;
- if (patt->len >= MAXPATHLEN)
- if (!(buf = malloc(patt->len + 1))) return 0;
- strlcpy(buf, patt->str, patt->len + 1);
- buf[patt->len] = '\0';
- for (p = buf; *p; p = CharNext(p))
- if (*p == '\\')
- *p = '/';
- status = ruby_brace_glob(buf, 0, insert, (VALUE)&tail);
- if (buf != buffer)
- free(buf);
- if (status || last == tail) return 0;
- if (patt->flags & NTMALLOC)
- free(patt->str);
- free(patt);
- return tail;
- }
- //
- // Check a command string to determine if it has I/O redirection
- // characters that require it to be executed by a command interpreter
- //
- static int
- has_redirection(const char *cmd)
- {
- char quote = '\0';
- const char *ptr;
- //
- // Scan the string, looking for redirection characters (< or >), pipe
- // character (|) or newline (\n) that are not in a quoted string
- //
- for (ptr = cmd; *ptr;) {
- switch (*ptr) {
- case '\'':
- case '\"':
- if (!quote)
- quote = *ptr;
- else if (quote == *ptr)
- quote = '\0';
- ptr++;
- break;
- case '>':
- case '<':
- case '|':
- case '\n':
- if (!quote)
- return TRUE;
- ptr++;
- break;
- case '%':
- if (*++ptr != '_' && !ISALPHA(*ptr)) break;
- while (*++ptr == '_' || ISALNUM(*ptr));
- if (*ptr++ == '%') return TRUE;
- break;
- case '\\':
- ptr++;
- default:
- ptr = CharNext(ptr);
- break;
- }
- }
- return FALSE;
- }
- static inline char *
- skipspace(char *ptr)
- {
- while (ISSPACE(*ptr))
- ptr++;
- return ptr;
- }
- int
- rb_w32_cmdvector(const char *cmd, char ***vec)
- {
- int globbing, len;
- int elements, strsz, done;
- int slashes, escape;
- char *ptr, *base, *buffer, *cmdline;
- char **vptr;
- char quote;
- NtCmdLineElement *curr, **tail;
- NtCmdLineElement *cmdhead = NULL, **cmdtail = &cmdhead;
- //
- // just return if we don't have a command line
- //
- while (ISSPACE(*cmd))
- cmd++;
- if (!*cmd) {
- *vec = NULL;
- return 0;
- }
- ptr = cmdline = strdup(cmd);
- //
- // Ok, parse the command line, building a list of CmdLineElements.
- // When we've finished, and it's an input command (meaning that it's
- // the processes argv), we'll do globing and then build the argument
- // vector.
- // The outer loop does one interation for each element seen.
- // The inner loop does one interation for each character in the element.
- //
- while (*(ptr = skipspace(ptr))) {
- base = ptr;
- quote = slashes = globbing = escape = 0;
- for (done = 0; !done && *ptr; ) {
- //
- // Switch on the current character. We only care about the
- // white-space characters, the wild-card characters, and the
- // quote characters.
- //
- switch (*ptr) {
- case '\\':
- if (quote != '\'') slashes++;
- break;
- case ' ':
- case '\t':
- case '\n':
- //
- // if we're not in a string, then we're finished with this
- // element
- //
- if (!quote) {
- *ptr = 0;
- done = 1;
- }
- break;
- case '*':
- case '?':
- case '[':
- case '{':
- //
- // record the fact that this element has a wildcard character
- // N.B. Don't glob if inside a single quoted string
- //
- if (quote != '\'')
- globbing++;
- slashes = 0;
- break;
- case '\'':
- case '\"':
- //
- // if we're already in a string, see if this is the
- // terminating close-quote. If it is, we're finished with
- // the string, but not neccessarily with the element.
- // If we're not already in a string, start one.
- //
- if (!(slashes & 1)) {
- if (!quote)
- quote = *ptr;
- else if (quote == *ptr) {
- if (quote == '"' && quote == ptr[1])
- ptr++;
- quote = '\0';
- }
- }
- escape++;
- slashes = 0;
- break;
- default:
- ptr = CharNext(ptr);
- slashes = 0;
- continue;
- }
- ptr++;
- }
- //
- // when we get here, we've got a pair of pointers to the element,
- // base and ptr. Base points to the start of the element while ptr
- // points to the character following the element.
- //
- len = ptr - base;
- if (done) --len;
- //
- // if it's an input vector element and it's enclosed by quotes,
- // we can remove them.
- //
- if (escape) {
- char *p = base, c;
- slashes = quote = 0;
- while (p < base + len) {
- switch (c = *p) {
- case '\\':
- p++;
- if (quote != '\'') slashes++;
- break;
- case '\'':
- case '"':
- if (!(slashes & 1) && quote && quote != c) {
- p++;
- slashes = 0;
- break;
- }
- memcpy(p - ((slashes + 1) >> 1), p + (~slashes & 1),
- base + len - p);
- len -= ((slashes + 1) >> 1) + (~slashes & 1);
- p -= (slashes + 1) >> 1;
- if (!(slashes & 1)) {
- if (quote) {
- if (quote == '"' && quote == *p)
- p++;
- quote = '\0';
- }
- else
- quote = c;
- }
- else
- p++;
- slashes = 0;
- break;
- default:
- p = CharNext(p);
- slashes = 0;
- break;
- }
- }
- }
- curr = (NtCmdLineElement *)calloc(sizeof(NtCmdLineElement), 1);
- if (!curr) goto do_nothing;
- curr->str = base;
- curr->len = len;
- if (globbing && (tail = cmdglob(curr, cmdtail))) {
- cmdtail = tail;
- }
- else {
- *cmdtail = curr;
- cmdtail = &curr->next;
- }
- }
- //
- // Almost done!
- // Count up the elements, then allocate space for a vector of pointers
- // (argv) and a string table for the elements.
- //
- for (elements = 0, strsz = 0, curr = cmdhead; curr; curr = curr->next) {
- elements++;
- strsz += (curr->len + 1);
- }
- len = (elements+1)*sizeof(char *) + strsz;
- buffer = (char *)malloc(len);
- if (!buffer) {
- do_nothing:
- while (curr = cmdhead) {
- cmdhead = curr->next;
- if (curr->flags & NTMALLOC) free(curr->str);
- free(curr);
- }
- free(cmdline);
- for (vptr = *vec; *vptr; ++vptr);
- return vptr - *vec;
- }
-
- //
- // make vptr point to the start of the buffer
- // and ptr point to the area we'll consider the string table.
- //
- // buffer (*vec)
- // |
- // V ^---------------------V
- // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
- // | | | .... | NULL | | ..... |\0 | | ..... |\0 |...
- // +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
- // |- elements+1 -| ^ 1st element ^ 2nd element
- vptr = (char **) buffer;
- ptr = buffer + (elements+1) * sizeof(char *);
- while (curr = cmdhead) {
- strlcpy(ptr, curr->str, curr->len + 1);
- *vptr++ = ptr;
- ptr += curr->len + 1;
- cmdhead = curr->next;
- if (curr->flags & NTMALLOC) free(curr->str);
- free(curr);
- }
- *vptr = 0;
- *vec = (char **) buffer;
- free(cmdline);
- return elements;
- }
- //
- // UNIX compatible directory access functions for NT
- //
- #define PATHLEN 1024
- //
- // The idea here is to read all the directory names into a string table
- // (separated by nulls) and when one of the other dir functions is called
- // return the pointer to the current file name.
- //
- #define GetBit(bits, i) ((bits)[(i) / CHAR_BIT] & (1 << (i) % CHAR_BIT))
- #define SetBit(bits, i) ((bits)[(i) / CHAR_BIT] |= (1 << (i) % CHAR_BIT))
- #define BitOfIsDir(n) ((n) * 2)
- #define BitOfIsRep(n) ((n) * 2 + 1)
- #define DIRENT_PER_CHAR (CHAR_BIT / 2)
- static HANDLE
- open_dir_handle(const char *filename, WIN32_FIND_DATAW *fd)
- {
- HANDLE fh;
- static const WCHAR wildcard[] = L"\\*";
- UINT cp = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
- WCHAR *scanname;
- WCHAR *p;
- int len;
- //
- // Create the search pattern
- //
- len = MultiByteToWideChar(cp, 0, filename, -1, NULL, 0);
- if (len <= 0) {
- errno = map_errno(GetLastError());
- return INVALID_HANDLE_VALUE;
- }
- scanname = ALLOCA_N(WCHAR, len + sizeof(wildcard) / sizeof(WCHAR));
- len = MultiByteToWideChar(cp, 0, filename, -1, scanname, len + 2);
- if (len <= 0) {
- errno = map_errno(GetLastError());
- return INVALID_HANDLE_VALUE;
- }
- p = CharPrevW(scanname, scanname + len);
- if (*p == L'/' || *p == L'\\' || *p == L':')
- lstrcatW(scanname, wildcard + 1);
- else
- lstrcatW(scanname, wildcard);
- //
- // do the FindFirstFile call
- //
- fh = FindFirstFileW(scanname, fd);
- if (fh == INVALID_HANDLE_VALUE) {
- errno = map_errno(GetLastError());
- }
- return fh;
- }
- static DIR *
- opendir_internal(HANDLE fh, WIN32_FIND_DATAW *fd)
- {
- DIR *p;
- long len;
- long idx;
- WCHAR *tmpW;
- char *tmp;
- if (fh == INVALID_HANDLE_VALUE) {
- return NULL;
- }
- //
- // Get us a DIR structure
- //
- p = calloc(sizeof(DIR), 1);
- if (p == NULL)
- return NULL;
- idx = 0;
- //
- // loop finding all the files that match the wildcard
- // (which should be all of them in this directory!).
- // the variable idx should point one past the null terminator
- // of the previous string found.
- //
- do {
- len = lstrlenW(fd->cFileName) + 1;
- //
- // bump the string table size by enough for the
- // new name and it's null terminator
- //
- tmpW = realloc(p->start, (idx + len) * sizeof(WCHAR));
- if (!tmpW) {
- error:
- rb_w32_closedir(p);
- FindClose(fh);
- errno = ENOMEM;
- return NULL;
- }
- p->start = tmpW;
- memcpy(&p->start[idx], fd->cFileName, len * sizeof(WCHAR));
- if (p->nfiles % DIRENT_PER_CHAR == 0) {
- tmp = realloc(p->bits, p->nfiles / DIRENT_PER_CHAR + 1);
- if (!tmp)
- goto error;
- p->bits = tmp;
- p->bits[p->nfiles / DIRENT_PER_CHAR] = 0;
- }
- if (fd->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
- SetBit(p->bits, BitOfIsDir(p->nfiles));
- if (fd->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
- SetBit(p->bits, BitOfIsRep(p->nfiles));
- p->nfiles++;
- idx += len;
- } while (FindNextFileW(fh, fd));
- FindClose(fh);
- p->size = idx;
- p->curr = p->start;
- return p;
- }
- DIR *
- rb_w32_opendir(const char *filename)
- {
- struct stati64 sbuf;
- WIN32_FIND_DATAW fd;
- HANDLE fh;
- //
- // check to see if we've got a directory
- //
- if (rb_w32_stati64(filename, &sbuf) < 0)
- return NULL;
- if (!(sbuf.st_mode & S_IFDIR) &&
- (!ISALPHA(filename[0]) || filename[1] != ':' || filename[2] != '\0' ||
- ((1 << ((filename[0] & 0x5f) - 'A')) & GetLogicalDrives()) == 0)) {
- errno = ENOTDIR;
- return NULL;
- }
- fh = open_dir_handle(filename, &fd);
- return opendir_internal(fh, &fd);
- }
- //
- // Move to next entry
- //
- static void
- move_to_next_entry(DIR *dirp)
- {
- if (dirp->curr) {
- dirp->loc++;
- dirp->curr += lstrlenW(dirp->curr) + 1;
- if (dirp->curr >= (dirp->start + dirp->size)) {
- dirp->curr = NULL;
- }
- }
- }
- static char *
- win32_conv_from_wstr(const WCHAR *wstr, long *len)
- {
- UINT cp = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
- char *ptr;
- *len = WideCharToMultiByte(cp, 0, wstr, -1, NULL, 0, NULL, NULL) - 1;
- if (!(ptr = malloc(*len + 1))) return 0;
- WideCharToMultiByte(cp, 0, wstr, -1, ptr, *len + 1, NULL, NULL);
- return ptr;
- }
- //
- // Readdir just returns the current string pointer and bumps the
- // string pointer to the next entry.
- //
- static BOOL
- win32_direct_conv(const WCHAR *file, struct direct *entry, rb_encoding *dummy)
- {
- if (!(entry->d_name = win32_conv_from_wstr(file, &entry->d_namlen)))
- return FALSE;
- return TRUE;
- }
- VALUE
- rb_w32_conv_from_wchar(const WCHAR *wstr, rb_encoding *enc)
- {
- static rb_encoding *utf16 = (rb_encoding *)-1;
- VALUE src;
- VALUE opthash;
- int ecflags;
- VALUE ecopts;
- if (utf16 == (rb_encoding *)-1) {
- utf16 = rb_enc_find("UTF-16LE");
- if (utf16 == rb_ascii8bit_encoding())
- utf16 = NULL;
- }
- if (!utf16)
- /* maybe miniruby */
- return Qnil;
- src = rb_enc_str_new((char *)wstr, lstrlenW(wstr) * sizeof(WCHAR), utf16);
- opthash = rb_hash_new();
- rb_hash_aset(opthash, ID2SYM(rb_intern("undef")),
- ID2SYM(rb_intern("replace")));
- ecflags = rb_econv_prepare_opts(opthash, &ecopts);
- return rb_str_encode(src, rb_enc_from_encoding(enc), ecflags, ecopts);
- }
- char *
- rb_w32_conv_from_wstr(const WCHAR *wstr, long *lenp, rb_encoding *enc)
- {
- VALUE str = rb_w32_conv_from_wchar(wstr, enc);
- long len;
- char *ptr;
- if (NIL_P(str)) return win32_conv_from_wstr(wstr, lenp);
- *lenp = len = RSTRING_LEN(str);
- memcpy(ptr = malloc(len + 1), RSTRING_PTR(str), len);
- ptr[len] = '\0';
- return ptr;
- }
- static BOOL
- ruby_direct_conv(const WCHAR *file, struct direct *entry, rb_encoding *enc)
- {
- if (!(entry->d_name = rb_w32_conv_from_wstr(file, &entry->d_namlen, enc)))
- return FALSE;
- return TRUE;
- }
- static struct direct *
- readdir_internal(DIR *dirp, BOOL (*conv)(const WCHAR *, struct direct *, rb_encoding *), rb_encoding *enc)
- {
- static int dummy = 0;
- if (dirp->curr) {
- //
- // first set up the structure to return
- //
- if (dirp->dirstr.d_name)
- free(dirp->dirstr.d_name);
- conv(dirp->curr, &dirp->dirstr, enc);
- //
- // Fake inode
- //
- dirp->dirstr.d_ino = dummy++;
- //
- // Attributes
- //
- dirp->dirstr.d_isdir = GetBit(dirp->bits, BitOfIsDir(dirp->loc));
- dirp->dirstr.d_isrep = GetBit(dirp->bits, BitOfIsRep(dirp->loc));
- //
- // Now set up for the next call to readdir
- //
- move_to_next_entry(dirp);
- return &(dirp->dirstr);
- } else
- return NULL;
- }
- struct direct *
- rb_w32_readdir(DIR *dirp)
- {
- return readdir_internal(dirp, win32_direct_conv, NULL);
- }
- struct direct *
- rb_w32_readdir_with_enc(DIR *dirp, rb_encoding *enc)
- {
- if (enc == rb_ascii8bit_encoding())
- return readdir_internal(dirp, win32_direct_conv, NULL);
- else
- return readdir_internal(dirp, ruby_direct_conv, enc);
- }
- //
- // Telldir returns the current string pointer position
- //
- long
- rb_w32_telldir(DIR *dirp)
- {
- return dirp->loc;
- }
- //
- // Seekdir moves the string pointer to a previously saved position
- // (Saved by telldir).
- void
- rb_w32_seekdir(DIR *dirp, long loc)
- {
- if (dirp->loc > loc) rb_w32_rewinddir(dirp);
- while (dirp->curr && dirp->loc < loc) {
- move_to_next_entry(dirp);
- }
- }
- //
- // Rewinddir resets the string pointer to the start
- //
- void
- rb_w32_rewinddir(DIR *dirp)
- {
- dirp->curr = dirp->start;
- dirp->loc = 0;
- }
- //
- // This just free's the memory allocated by opendir
- //
- void
- rb_w32_closedir(DIR *dirp)
- {
- if (dirp) {
- if (dirp->dirstr.d_name)
- free(dirp->dirstr.d_name);
- if (dirp->start)
- free(dirp->start);
- if (dirp->bits)
- free(dirp->bits);
- free(dirp);
- }
- }
- #if (defined _MT || defined __MSVCRT__) && !defined __BORLANDC__
- #define MSVCRT_THREADS
- #endif
- #ifdef MSVCRT_THREADS
- # define MTHREAD_ONLY(x) x
- # define STHREAD_ONLY(x)
- #elif defined(__BORLANDC__)
- # define MTHREAD_ONLY(x)
- # define STHREAD_ONLY(x)
- #else
- # define MTHREAD_ONLY(x)
- # define STHREAD_ONLY(x) x
- #endif
- typedef struct {
- intptr_t osfhnd; /* underlying OS file HANDLE */
- char osfile; /* attributes of file (e.g., open in text mode?) */
- char pipech; /* one char buffer for handles opened on pipes */
- #ifdef MSVCRT_THREADS
- int lockinitflag;
- CRITICAL_SECTION lock;
- #endif
- #if RT_VER >= 80
- char textmode;
- char pipech2[2];
- #endif
- } ioinfo;
- #if !defined _CRTIMP || defined __MINGW32__
- #undef _CRTIMP
- #define _CRTIMP __declspec(dllimport)
- #endif
- #if !defined(__BORLANDC__)
- EXTERN_C _CRTIMP ioinfo * __pioinfo[];
- #define IOINFO_L2E 5
- #define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
- #define _pioinfo(i) ((ioinfo*)((char*)(__pioinfo[i >> IOINFO_L2E]) + (i & (IOINFO_ARRAY_ELTS - 1)) * (sizeof(ioinfo) + pioinfo_extra)))
- #define _osfhnd(i) (_pioinfo(i)->osfhnd)
- #define _osfile(i) (_pioinfo(i)->osfile)
- #define _pipech(i) (_pioinfo(i)->pipech)
- #if RT_VER >= 80
- static size_t pioinfo_extra = 0; /* workaround for VC++8 SP1 */
- static void
- set_pioinfo_extra(void)
- {
- int fd;
- fd = _open("NUL", O_RDONLY);
- for (pioinfo_extra = 0; pioinfo_extra <= 64; pioinfo_extra += sizeof(void *)) {
- if (_osfhnd(fd) == _get_osfhandle(fd)) {
- break;
- }
- }
- _close(fd);
- if (pioinfo_extra > 64) {
- /* not found, maybe something wrong... */
- pioinfo_extra = 0;
- }
- }
- #else
- #define pioinfo_extra 0
- #endif
- #define _set_osfhnd(fh, osfh) (void)(_osfhnd(fh) = osfh)
- #define _set_osflags(fh, flags) (_osfile(fh) = (flags))
- #define FOPEN 0x01 /* file handle open */
- #define FEOFLAG 0x02 /* end of file has been encountered */
- #define FPIPE 0x08 /* file handle refers to a pipe */
- #define FNOINHERIT 0x10 /* file handle opened O_NOINHERIT */
- #define FAPPEND 0x20 /* file handle opened O_APPEND */
- #define FDEV 0x40 /* file handle refers to device */
- #define FTEXT 0x80 /* file handle is in text mode */
- static int
- rb_w32_open_osfhandle(intptr_t osfhandle, int flags)
- {
- int fh;
- char fileflags; /* _osfile flags */
- HANDLE hF;
- /* copy relevant flags from second parameter */
- fileflags = FDEV;
- if (flags & O_APPEND)
- fileflags |= FAPPEND;
- if (flags & O_TEXT)
- fileflags |= FTEXT;
- if (flags & O_NOINHERIT)
- fileflags |= FNOINHERIT;
- /* attempt to allocate a C Runtime file handle */
- hF = CreateFile("NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
- fh = _open_osfhandle((long)hF, 0);
- CloseHandle(hF);
- if (fh == -1) {
- errno = EMFILE; /* too many open files */
- _doserrno = 0L; /* not an OS error */
- }
- else {
- MTHREAD_ONLY(EnterCriticalSection(&(_pioinfo(fh)->lock)));
- /* the file is open. now, set the info in _osfhnd array */
- _set_osfhnd(fh, osfhandle);
- fileflags |= FOPEN; /* mark as open */
- _set_osflags(fh, fileflags); /* set osfile entry */
- MTHREAD_ONLY(LeaveCriticalSection(&_pioinfo(fh)->lock));
- }
- return fh; /* return handle */
- }
- static void
- init_stdhandle(void)
- {
- int nullfd = -1;
- int keep = 0;
- #define open_null(fd) \
- (((nullfd < 0) ? \
- (nullfd = open("NUL", O_RDWR|O_BINARY)) : 0), \
- ((nullfd == (fd)) ? (keep = 1) : dup2(nullfd, fd)), \
- (fd))
- if (fileno(stdin) < 0) {
- stdin->_file = open_null(0);
- }
- else {
- setmode(fileno(stdin), O_BINARY);
- }
- if (fileno(stdout) < 0) {
- stdout->_file = open_null(1);
- }
- else {
- setmode(fileno(stdout), O_BINARY);
- }
- if (fileno(stderr) < 0) {
- stderr->_file = open_null(2);
- }
- else {
- setmode(fileno(stderr), O_BINARY);
- }
- if (nullfd >= 0 && !keep) close(nullfd);
- setvbuf(stderr, NULL, _IONBF, 0);
- }
- #else
- #define _set_osfhnd(fh, osfh) (void)((fh), (osfh))
- #define _set_osflags(fh, flags) (void)((fh), (flags))
- static void
- init_stdhandle(void)
- {
- }
- #endif
- #ifdef __BORLANDC__
- static int
- rb_w32_open_osfhandle(intptr_t osfhandle, int flags)
- {
- int fd = _open_osfhandle(osfhandle, flags);
- if (fd == -1) {
- errno = EMFILE; /* too many open files */
- _doserrno = 0L; /* not an OS error */
- }
- return fd;
- }
- #endif
- #undef getsockopt
- static int
- is_socket(SOCKET sock)
- {
- if (st_lookup(socklist, (st_data_t)sock, NULL))
- return TRUE;
- else
- return FALSE;
- }
- int
- rb_w32_is_socket(int fd)
- {
- return is_socket(TO_SOCKET(fd));
- }
- //
- // Since the errors returned by the socket error function
- // WSAGetLastError() are not known by the library routine strerror
- // we have to roll our own.
- //
- #undef strerror
- char *
- rb_w32_strerror(int e)
- {
- static char buffer[512];
- DWORD source = 0;
- char *p;
- #if defined __BORLANDC__ && defined ENOTEMPTY // _sys_errlist is broken
- switch (e) {
- case ENAMETOOLONG:
- return "Filename too long";
- case ENOTEMPTY:
- return "Directory not empty";
- }
- #endif
- if (e < 0 || e > sys_nerr) {
- if (e < 0)
- e = GetLastError();
- if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS, &source, e, 0,
- buffer, sizeof(buffer), NULL) == 0)
- strlcpy(buffer, "Unknown Error", sizeof(buffer));
- }
- else
- strlcpy(buffer, strerror(e), sizeof(buffer));
- p = buffer;
- while ((p = strpbrk(p, "\r\n")) != NULL) {
- memmove(p, p + 1, strlen(p));
- }
- return buffer;
- }
- //
- // various stubs
- //
- // Ownership
- //
- // Just pretend that everyone is a superuser. NT will let us know if
- // we don't really have permission to do something.
- //
- #define ROOT_UID 0
- #define ROOT_GID 0
- rb_uid_t
- getuid(void)
- {
- return ROOT_UID;
- }
- rb_uid_t
- geteuid(void)
- {
- return ROOT_UID;
- }
- rb_gid_t
- getgid(void)
- {
- return ROOT_GID;
- }
- rb_gid_t
- getegid(void)
- {
- return ROOT_GID;
- }
- int
- setuid(rb_uid_t uid)
- {
- return (uid == ROOT_UID ? 0 : -1);
- }
- int
- setgid(rb_gid_t gid)
- {
- return (gid == ROOT_GID ? 0 : -1);
- }
- //
- // File system stuff
- //
- int
- ioctl(int i, int u, ...)
- {
- errno = EINVAL;
- return -1;
- }
- #undef FD_SET
- void
- rb_w32_fdset(int fd, fd_set *set)
- {
- unsigned int i;
- SOCKET s = TO_SOCKET(fd);
- for (i = 0; i < set->fd_count; i++) {
- if (set->fd_array[i] == s) {
- return;
- }
- }
- if (i == set->fd_count) {
- if (set->fd_count < FD_SETSIZE) {
- set->fd_array[i] = s;
- set->fd_count++;
- }
- }
- }
- #undef FD_CLR
- void
- rb_w32_fdclr(int fd, fd_set *set)
- {
- unsigned int i;
- SOCKET s = TO_SOCKET(fd);
- for (i = 0; i < set->fd_count; i++) {
- if (set->fd_array[i] == s) {
- memmove(&set->fd_array[i], &set->fd_array[i+1],
- sizeof(set->fd_array[0]) * (--set->fd_count - i));
- break;
- }
- }
- }
- #undef FD_ISSET
- int
- rb_w32_fdisset(int fd, fd_set *set)
- {
- int ret;
- SOCKET s = TO_SOCKET(fd);
- if (s == (SOCKET)INVALID_HANDLE_VALUE)
- return 0;
- RUBY_CRITICAL(ret = __WSAFDIsSet(s, set));
- return ret;
- }
- //
- // Networking trampolines
- // These are used to avoid socket startup/shutdown overhead in case
- // the socket routines aren't used.
- //
- #undef select
- static int
- extract_fd(rb_fdset_t *dst, fd_set *src, int (*func)(SOCKET))
- {
- unsigned int s = 0;
- if (!src || !dst) return 0;
- while (s < src->fd_count) {
- SOCKET fd = src->fd_array[s];
- if (!func || (*func)(fd)) { /* move it to dst */
- unsigned int d;
- for (d = 0; d < dst->fdset->fd_count; d++) {
- if (dst->fdset->fd_array[d] == fd)
- break;
- }
- if (d == dst->fdset->fd_count) {
- if ((int)dst->fdset->fd_count >= dst->capa) {
- dst->capa = (dst->fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
- dst->fdset = xrealloc(dst->fdset, sizeof(unsigned int) + sizeof(SOCKET) * dst->capa);
- }
- dst->fdset->fd_array[dst->fdset->fd_count++] = fd;
- }
- memmove(
- &src->fd_array[s],
- &src->fd_array[s+1]…
Large files files are truncated, but you can click here to view the full file