45#if defined _MSC_VER && _MSC_VER >= 1400
55#include "ruby/win32.h"
58#include "win32/file.h"
61#include "internal/enc.h"
62#include "internal/object.h"
63#include "internal/static_assert.h"
66#define isdirsep(x) ((x) == '/' || (x) == '\\')
68#if defined _MSC_VER && _MSC_VER <= 1200
69# define CharNextExA(cp, p, flags) CharNextExA((WORD)(cp), (p), (flags))
72static int w32_wopen(
const WCHAR *file,
int oflag,
int perm);
73static int w32_stati128(
const char *path,
struct stati128 *st, UINT cp, BOOL lstat);
74static char *w32_getenv(
const char *name, UINT cp);
80#define DLN_FIND_EXTRA_ARG_DECL ,UINT cp
81#define DLN_FIND_EXTRA_ARG ,cp
82#define rb_w32_stati128(path, st) w32_stati128(path, st, cp, FALSE)
83#define getenv(name) w32_getenv(name, cp)
85#define CharNext(p) CharNextExA(cp, (p), 0)
86#define dln_find_exe_r rb_w32_udln_find_exe_r
87#define dln_find_file_r rb_w32_udln_find_file_r
94#define dln_find_exe_r(fname, path, buf, size) rb_w32_udln_find_exe_r(fname, path, buf, size, cp)
95#define dln_find_file_r(fname, path, buf, size) rb_w32_udln_find_file_r(fname, path, buf, size, cp)
101# define PATH_MAX MAX_PATH
102# elif defined HAVE_SYS_PARAM_H
103# include <sys/param.h>
104# define PATH_MAX MAXPATHLEN
116#if RUBY_MSVCRT_VERSION >= 140
117# define _filbuf _fgetc_nolock
118# define _flsbuf _fputc_nolock
120#define enough_to_get(n) (--(n) >= 0)
121#define enough_to_put(n) (--(n) >= 0)
124#define Debug(something) something
126#define Debug(something)
129#define TO_SOCKET(x) _get_osfhandle(x)
131int rb_w32_reparse_symlink_p(
const WCHAR *path);
133static int has_redirection(
const char *, UINT);
134int rb_w32_wait_events(HANDLE *events,
int num, DWORD timeout);
135static int rb_w32_open_osfhandle(intptr_t osfhandle,
int flags);
136static int wstati128(
const WCHAR *path,
struct stati128 *st, BOOL lstat);
139static FARPROC get_proc_address(
const char *module,
const char *func, HANDLE *mh);
141#define RUBY_CRITICAL if (0) {} else
148 { ERROR_INVALID_FUNCTION, EINVAL },
149 { ERROR_FILE_NOT_FOUND, ENOENT },
150 { ERROR_PATH_NOT_FOUND, ENOENT },
151 { ERROR_TOO_MANY_OPEN_FILES, EMFILE },
152 { ERROR_ACCESS_DENIED, EACCES },
153 { ERROR_INVALID_HANDLE, EBADF },
154 { ERROR_ARENA_TRASHED, ENOMEM },
155 { ERROR_NOT_ENOUGH_MEMORY, ENOMEM },
156 { ERROR_INVALID_BLOCK, ENOMEM },
157 { ERROR_BAD_ENVIRONMENT, E2BIG },
158 { ERROR_BAD_FORMAT, ENOEXEC },
159 { ERROR_INVALID_ACCESS, EINVAL },
160 { ERROR_INVALID_DATA, EINVAL },
161 { ERROR_INVALID_DRIVE, ENOENT },
162 { ERROR_CURRENT_DIRECTORY, EACCES },
163 { ERROR_NOT_SAME_DEVICE, EXDEV },
164 { ERROR_NO_MORE_FILES, ENOENT },
165 { ERROR_WRITE_PROTECT, EROFS },
166 { ERROR_BAD_UNIT, ENODEV },
167 { ERROR_NOT_READY, ENXIO },
168 { ERROR_BAD_COMMAND, EACCES },
169 { ERROR_CRC, EACCES },
170 { ERROR_BAD_LENGTH, EACCES },
172 { ERROR_NOT_DOS_DISK, EACCES },
173 { ERROR_SECTOR_NOT_FOUND, EACCES },
174 { ERROR_OUT_OF_PAPER, EACCES },
175 { ERROR_WRITE_FAULT, EIO },
176 { ERROR_READ_FAULT, EIO },
177 { ERROR_GEN_FAILURE, EACCES },
178 { ERROR_LOCK_VIOLATION, EACCES },
179 { ERROR_SHARING_VIOLATION, EACCES },
180 { ERROR_WRONG_DISK, EACCES },
181 { ERROR_SHARING_BUFFER_EXCEEDED, EACCES },
182 { ERROR_BAD_NETPATH, ENOENT },
183 { ERROR_NETWORK_ACCESS_DENIED, EACCES },
184 { ERROR_BAD_NET_NAME, ENOENT },
185 { ERROR_FILE_EXISTS, EEXIST },
186 { ERROR_CANNOT_MAKE, EACCES },
187 { ERROR_FAIL_I24, EACCES },
188 { ERROR_INVALID_PARAMETER, EINVAL },
189 { ERROR_NO_PROC_SLOTS, EAGAIN },
190 { ERROR_DRIVE_LOCKED, EACCES },
191 { ERROR_BROKEN_PIPE, EPIPE },
192 { ERROR_DISK_FULL, ENOSPC },
193 { ERROR_INVALID_TARGET_HANDLE, EBADF },
194 { ERROR_INVALID_HANDLE, EINVAL },
195 { ERROR_WAIT_NO_CHILDREN, ECHILD },
196 { ERROR_CHILD_NOT_COMPLETE, ECHILD },
197 { ERROR_DIRECT_ACCESS_HANDLE, EBADF },
198 { ERROR_NEGATIVE_SEEK, EINVAL },
199 { ERROR_SEEK_ON_DEVICE, EACCES },
200 { ERROR_DIR_NOT_EMPTY, ENOTEMPTY },
201 { ERROR_DIRECTORY, ENOTDIR },
202 { ERROR_NOT_LOCKED, EACCES },
203 { ERROR_BAD_PATHNAME, ENOENT },
204 { ERROR_MAX_THRDS_REACHED, EAGAIN },
205 { ERROR_LOCK_FAILED, EACCES },
206 { ERROR_ALREADY_EXISTS, EEXIST },
207 { ERROR_INVALID_STARTING_CODESEG, ENOEXEC },
208 { ERROR_INVALID_STACKSEG, ENOEXEC },
209 { ERROR_INVALID_MODULETYPE, ENOEXEC },
210 { ERROR_INVALID_EXE_SIGNATURE, ENOEXEC },
211 { ERROR_EXE_MARKED_INVALID, ENOEXEC },
212 { ERROR_BAD_EXE_FORMAT, ENOEXEC },
213 { ERROR_ITERATED_DATA_EXCEEDS_64k,ENOEXEC },
214 { ERROR_INVALID_MINALLOCSIZE, ENOEXEC },
215 { ERROR_DYNLINK_FROM_INVALID_RING,ENOEXEC },
216 { ERROR_IOPL_NOT_ENABLED, ENOEXEC },
217 { ERROR_INVALID_SEGDPL, ENOEXEC },
218 { ERROR_AUTODATASEG_EXCEEDS_64k, ENOEXEC },
219 { ERROR_RING2SEG_MUST_BE_MOVABLE, ENOEXEC },
220 { ERROR_RELOC_CHAIN_XEEDS_SEGLIM, ENOEXEC },
221 { ERROR_INFLOOP_IN_RELOC_CHAIN, ENOEXEC },
222 { ERROR_FILENAME_EXCED_RANGE, ENOENT },
223 { ERROR_NESTING_NOT_ALLOWED, EAGAIN },
224#ifndef ERROR_PIPE_LOCAL
225#define ERROR_PIPE_LOCAL 229L
227 { ERROR_PIPE_LOCAL, EPIPE },
228 { ERROR_BAD_PIPE, EPIPE },
229 { ERROR_PIPE_BUSY, EAGAIN },
230 { ERROR_NO_DATA, EPIPE },
231 { ERROR_PIPE_NOT_CONNECTED, EPIPE },
232 { ERROR_OPERATION_ABORTED, EINTR },
233 { ERROR_NOT_ENOUGH_QUOTA, ENOMEM },
234 { ERROR_MOD_NOT_FOUND, ENOENT },
235 { ERROR_PRIVILEGE_NOT_HELD, EACCES, },
236 { ERROR_CANT_RESOLVE_FILENAME, ELOOP, },
239 { WSAEACCES, EACCES },
240 { WSAEFAULT, EFAULT },
241 { WSAEINVAL, EINVAL },
242 { WSAEMFILE, EMFILE },
243 { WSAEWOULDBLOCK, EWOULDBLOCK },
244 { WSAEINPROGRESS, EINPROGRESS },
245 { WSAEALREADY, EALREADY },
246 { WSAENOTSOCK, ENOTSOCK },
247 { WSAEDESTADDRREQ, EDESTADDRREQ },
248 { WSAEMSGSIZE, EMSGSIZE },
249 { WSAEPROTOTYPE, EPROTOTYPE },
250 { WSAENOPROTOOPT, ENOPROTOOPT },
251 { WSAEPROTONOSUPPORT, EPROTONOSUPPORT },
252 { WSAESOCKTNOSUPPORT, ESOCKTNOSUPPORT },
253 { WSAEOPNOTSUPP, EOPNOTSUPP },
254 { WSAEPFNOSUPPORT, EPFNOSUPPORT },
255 { WSAEAFNOSUPPORT, EAFNOSUPPORT },
256 { WSAEADDRINUSE, EADDRINUSE },
257 { WSAEADDRNOTAVAIL, EADDRNOTAVAIL },
258 { WSAENETDOWN, ENETDOWN },
259 { WSAENETUNREACH, ENETUNREACH },
260 { WSAENETRESET, ENETRESET },
261 { WSAECONNABORTED, ECONNABORTED },
262 { WSAECONNRESET, ECONNRESET },
263 { WSAENOBUFS, ENOBUFS },
264 { WSAEISCONN, EISCONN },
265 { WSAENOTCONN, ENOTCONN },
266 { WSAESHUTDOWN, ESHUTDOWN },
267 { WSAETOOMANYREFS, ETOOMANYREFS },
268 { WSAETIMEDOUT, ETIMEDOUT },
269 { WSAECONNREFUSED, ECONNREFUSED },
271 { WSAENAMETOOLONG, ENAMETOOLONG },
272 { WSAEHOSTDOWN, EHOSTDOWN },
273 { WSAEHOSTUNREACH, EHOSTUNREACH },
274 { WSAEPROCLIM, EPROCLIM },
275 { WSAENOTEMPTY, ENOTEMPTY },
276 { WSAEUSERS, EUSERS },
277 { WSAEDQUOT, EDQUOT },
278 { WSAESTALE, ESTALE },
279 { WSAEREMOTE, EREMOTE },
284rb_w32_map_errno(DWORD winerr)
292 for (i = 0; i < (int)(
sizeof(errmap) /
sizeof(*errmap)); i++) {
293 if (errmap[i].winerr == winerr) {
294 return errmap[i].err;
298 if (winerr >= WSABASEERR) {
304#define map_errno rb_w32_map_errno
306static const char *NTLoginName;
308static OSVERSIONINFO osver;
314 memset(&osver, 0,
sizeof(OSVERSIONINFO));
315 osver.dwOSVersionInfoSize =
sizeof(OSVERSIONINFO);
316 GetVersionEx(&osver);
324 return osver.dwPlatformId;
332 return osver.dwMajorVersion;
343 DWORD err = GetLastError(); \
344 if (err == ERROR_LOCK_VIOLATION || err == ERROR_IO_PENDING) \
345 errno = EWOULDBLOCK; \
346 else if (err == ERROR_NOT_LOCKED) \
349 errno = map_errno(err); \
352#define LK_LEN ULONG_MAX
356flock_winnt(uintptr_t self,
int argc, uintptr_t* argv)
360 const HANDLE fh = (HANDLE)self;
361 const int oper = argc;
363 memset(&o, 0,
sizeof(o));
367 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, LK_LEN, &o), i);
370 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, LK_LEN, &o), i);
372 case LOCK_SH|LOCK_NB:
373 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, LK_LEN, &o), i);
375 case LOCK_EX|LOCK_NB:
376 LK_ERR(LockFileEx(fh,
377 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
378 0, LK_LEN, LK_LEN, &o), i);
381 case LOCK_UN|LOCK_NB:
382 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, LK_LEN, &o), i);
395flock(
int fd,
int oper)
397 const asynchronous_func_t locker = flock_winnt;
399 return rb_w32_asynchronize(locker,
400 (
VALUE)_get_osfhandle(fd), oper, NULL,
406translate_wchar(WCHAR *p,
int from,
int to)
417translate_char(
char *p,
int from,
int to, UINT cp)
420 if ((
unsigned char)*p == from)
422 p = CharNextExA(cp, p, 0);
427#ifndef CSIDL_LOCAL_APPDATA
428#define CSIDL_LOCAL_APPDATA 28
430#ifndef CSIDL_COMMON_APPDATA
431#define CSIDL_COMMON_APPDATA 35
434#define CSIDL_WINDOWS 36
437#define CSIDL_SYSTEM 37
440#define CSIDL_PROFILE 40
445get_special_folder(
int n, WCHAR *buf,
size_t len)
451 if (SHGetSpecialFolderLocation(NULL, n, &pidl) == 0) {
452 f = SHGetPathFromIDListEx(pidl, buf,
len, 0);
454 alloc->lpVtbl->Free(alloc, pidl);
455 alloc->lpVtbl->Release(alloc);
462regulate_path(WCHAR *path)
464 WCHAR *p = translate_wchar(path, L
'\\', L
'/');
465 if (p - path == 2 && path[1] == L
':') {
473get_proc_address(
const char *module,
const char *func, HANDLE *mh)
479 h = LoadLibrary(module);
481 h = GetModuleHandle(module);
485 ptr = GetProcAddress(h, func);
497rb_w32_special_folder(
int type)
499 WCHAR path[PATH_MAX];
501 if (!get_special_folder(
type, path, numberof(path)))
return Qnil;
503 return rb_w32_conv_from_wchar(path, rb_filesystem_encoding());
506#if defined _MSC_VER && _MSC_VER <= 1200
508#define GetSystemWindowsDirectoryW GetWindowsDirectoryW
513rb_w32_system_tmpdir(WCHAR *path, UINT
len)
515 static const WCHAR temp[] = L
"temp";
518 if (!get_special_folder(CSIDL_LOCAL_APPDATA, path,
len)) {
519 if (GetSystemWindowsDirectoryW(path,
len))
return 0;
521 p = translate_wchar(path, L
'\\', L
'/');
522 if (*(p - 1) != L
'/') *p++ = L
'/';
523 if ((UINT)(p - path + numberof(temp)) >=
len)
return 0;
524 memcpy(p, temp,
sizeof(temp));
525 return (UINT)(p - path + numberof(temp) - 1);
540 WCHAR *buffer = NULL;
541 size_t buffer_len = MAX_PATH,
len = 0;
543 HOME_NONE, ENV_HOME, ENV_USERPROFILE, ENV_DRIVEPATH
544 } home_type = HOME_NONE;
546 if ((
len = GetEnvironmentVariableW(L
"HOME", NULL, 0)) != 0) {
548 home_type = ENV_HOME;
550 else if ((
len = GetEnvironmentVariableW(L
"USERPROFILE", NULL, 0)) != 0) {
552 home_type = ENV_USERPROFILE;
554 else if ((
len = GetEnvironmentVariableW(L
"HOMEDRIVE", NULL, 0)) != 0) {
556 if ((
len = GetEnvironmentVariableW(L
"HOMEPATH", NULL, 0)) != 0) {
558 home_type = ENV_DRIVEPATH;
563 buffer = malloc(
sizeof(WCHAR) * buffer_len);
564 if (buffer == NULL)
return NULL;
568 GetEnvironmentVariableW(L
"HOME", buffer, buffer_len);
570 case ENV_USERPROFILE:
571 GetEnvironmentVariableW(L
"USERPROFILE", buffer, buffer_len);
574 len = GetEnvironmentVariableW(L
"HOMEDRIVE", buffer, buffer_len);
575 GetEnvironmentVariableW(L
"HOMEPATH", buffer +
len, buffer_len -
len);
578 if (!get_special_folder(CSIDL_PROFILE, buffer, buffer_len) &&
579 !get_special_folder(CSIDL_PERSONAL, buffer, buffer_len)) {
583 buffer = realloc(buffer,
sizeof(WCHAR) * (lstrlenW(buffer) + 1));
588 regulate_path(buffer);
599 if (!GetEnvironmentVariableW(L
"HOME", env, numberof(env))) {
600 WCHAR *whome = rb_w32_home_dir();
602 _wputenv_s(L
"HOME", whome);
607 if (!GetEnvironmentVariableW(L
"USER", env, numberof(env))) {
609 if (!GetEnvironmentVariableW(L
"USERNAME", env, numberof(env)) &&
610 !GetUserNameW(env, (
len = numberof(env), &
len))) {
611 NTLoginName =
"<Unknown>";
614 _wputenv_s(L
"USER", env);
615 NTLoginName = rb_w32_wstr_to_mbstr(CP_UTF8, env, -1, NULL);
619 NTLoginName = rb_w32_wstr_to_mbstr(CP_UTF8, env, -1, NULL);
622 if (!GetEnvironmentVariableW(L
"TMPDIR", env, numberof(env)) &&
623 !GetEnvironmentVariableW(L
"TMP", env, numberof(env)) &&
624 !GetEnvironmentVariableW(L
"TEMP", env, numberof(env)) &&
625 rb_w32_system_tmpdir(env, numberof(env))) {
626 _wputenv_s(L
"TMPDIR", env);
630static void init_stdhandle(
void);
632#if RUBY_MSVCRT_VERSION >= 80
635invalid_parameter(
const wchar_t *expr,
const wchar_t *func,
const wchar_t *file,
unsigned int line, uintptr_t dummy)
640int ruby_w32_rtc_error;
647rtc_error_handler(
int e, const
char *src,
int line, const
char *exe, const
char *fmt, ...)
652 if (!ruby_w32_rtc_error)
return 0;
653 str = rb_sprintf(
"%s:%d: ", src, line);
655 rb_str_vcatf(str, fmt, ap);
664static CRITICAL_SECTION select_mutex;
666static CRITICAL_SECTION socklist_mutex;
669static CRITICAL_SECTION conlist_mutex;
671#define conlist_disabled ((st_table *)-1)
673#define thread_exclusive(obj) \
674 for (bool exclusive_for_##obj = (EnterCriticalSection(&obj##_mutex), true); \
675 exclusive_for_##obj; \
676 exclusive_for_##obj = (LeaveCriticalSection(&obj##_mutex), false))
678static CRITICAL_SECTION uenvarea_mutex;
679static char *uenvarea;
684 int state, seq[16], reverse;
689enum {constat_init = -2, constat_esc = -1, constat_seq = 0};
693free_conlist(st_data_t key, st_data_t val, st_data_t arg)
701constat_delete(HANDLE h)
703 thread_exclusive(conlist) {
704 if (conlist && conlist != conlist_disabled) {
705 st_data_t key = (st_data_t)h, val;
706 st_delete(conlist, &key, &val);
717 DeleteCriticalSection(&select_mutex);
718 DeleteCriticalSection(&socklist_mutex);
719 DeleteCriticalSection(&conlist_mutex);
720 thread_exclusive(uenvarea) {
726 DeleteCriticalSection(&uenvarea_mutex);
733 EnterCriticalSection(&socklist_mutex);
735 st_free_table(socklist);
738 LeaveCriticalSection(&socklist_mutex);
740 EnterCriticalSection(&conlist_mutex);
741 if (conlist && conlist != conlist_disabled) {
742 st_foreach(conlist, free_conlist, 0);
743 st_free_table(conlist);
746 LeaveCriticalSection(&conlist_mutex);
749#define ATOMIC_LONG_CAS(var, oldval, newval) InterlockedCompareExchange(&(var), (newval), (oldval))
753install_vm_exit_handler(
void)
755 static LONG installed = 0;
758 while ((i = ATOMIC_LONG_CAS(installed, 0, -1)) != 1) {
764 ATOMIC_LONG_CAS(installed, -1, 1);
780 version = MAKEWORD(2, 0);
781 if (WSAStartup(version, &retdata))
782 rb_fatal(
"Unable to locate winsock library!");
783 if (LOBYTE(retdata.wVersion) != 2)
784 rb_fatal(
"could not find version 2 of winsock dll");
786 InitializeCriticalSection(&select_mutex);
787 InitializeCriticalSection(&socklist_mutex);
788 InitializeCriticalSection(&conlist_mutex);
790 atexit(exit_handler);
793#define MAKE_SOCKDATA(af, fl) ((int)((((int)af)<<4)|((fl)&0xFFFF)))
794#define GET_FAMILY(v) ((int)(((v)>>4)&0xFFFF))
795#define GET_FLAGS(v) ((int)((v)&0xFFFF))
799socklist_insert(SOCKET sock,
int flag)
803 thread_exclusive(socklist) {
805 socklist = st_init_numtable();
806 install_vm_exit_handler();
808 ret = st_insert(socklist, (st_data_t)sock, (st_data_t)flag);
816socklist_lookup(SOCKET sock,
int *flagp)
821 thread_exclusive(socklist) {
822 if (!socklist)
continue;
823 ret = st_lookup(socklist, (st_data_t)sock, &data);
833socklist_delete(SOCKET *sockp,
int *flagp)
839 thread_exclusive(socklist) {
840 if (!socklist)
continue;
841 key = (st_data_t)*sockp;
843 data = (st_data_t)*flagp;
844 ret = st_delete(socklist, &key, &data);
846 *sockp = (SOCKET)key;
855#if RUBY_MSVCRT_VERSION >= 80
857# define _CrtSetReportMode(type,mode) ((void)0)
858# define _RTC_SetErrorFunc(func) ((void)0)
860static void set_pioinfo_extra(
void);
862static int w32_cmdvector(
const WCHAR *,
char ***, UINT,
rb_encoding *);
868rb_w32_sysinit(
int *argc,
char ***argv)
870#if RUBY_MSVCRT_VERSION >= 80
872 _CrtSetReportMode(_CRT_ASSERT, 0);
873 _set_invalid_parameter_handler(invalid_parameter);
874 _RTC_SetErrorFunc(rtc_error_handler);
877 SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX);
884 *argc = w32_cmdvector(GetCommandLineW(), argv, CP_UTF8, &OnigEncodingUTF_8);
892 InitializeCriticalSection(&uenvarea_mutex);
904 return (
char *)NTLoginName;
907#define MAXCHILDNUM 256
916#define FOREACH_CHILD(v) do { \
917 struct ChildRecord* v; \
918 for (v = ChildRecord; v < ChildRecord + sizeof(ChildRecord) / sizeof(ChildRecord[0]); ++v)
919#define END_FOREACH_CHILD } while (0)
923FindChildSlot(rb_pid_t pid)
926 FOREACH_CHILD(child) {
927 if (child->pid == pid) {
936FindChildSlotByHandle(HANDLE h)
939 FOREACH_CHILD(child) {
940 if (child->hProcess == h) {
951 HANDLE h = child->hProcess;
952 child->hProcess = NULL;
959FindFreeChildSlot(
void)
961 FOREACH_CHILD(child) {
964 child->hProcess = NULL;
978#define InternalCmdsMax 8
979static const char szInternalCmds[][InternalCmdsMax+2] = {
1033internal_match(
const void *key,
const void *elem)
1035 return strncmp(key, ((
const char *)elem) + 1, InternalCmdsMax);
1040is_command_com(
const char *interp)
1042 int i = strlen(interp) - 11;
1044 if ((i == 0 || (i > 0 && isdirsep(interp[i-1]))) &&
1045 strcasecmp(interp+i,
"command.com") == 0) {
1051static int internal_cmd_match(
const char *cmdname,
int nt);
1055is_internal_cmd(
const char *cmd,
int nt)
1057 char cmdname[9], *b = cmdname, c;
1060 if (!(c = *cmd++))
return 0;
1061 }
while (isspace(c));
1064 while (isalpha(c)) {
1066 if (b == cmdname +
sizeof(cmdname))
return 0;
1069 if (c ==
'.') c = *cmd;
1071 case '<':
case '>':
case '|':
1073 case '\0':
case ' ':
case '\t':
case '\n':
1079 return internal_cmd_match(cmdname, nt);
1084internal_cmd_match(
const char *cmdname,
int nt)
1088 nm = bsearch(cmdname, szInternalCmds,
1089 sizeof(szInternalCmds) /
sizeof(*szInternalCmds),
1090 sizeof(*szInternalCmds),
1092 if (!nm || !(nm[0] & (nt ? 2 : 1)))
1099rb_w32_get_osfhandle(
int fh)
1101 return _get_osfhandle(fh);
1106join_argv(
char *cmd,
char *
const *argv, BOOL escape, UINT cp,
int backslash)
1110 int len, n, bs, quote;
1112 for (t = argv, q = cmd,
len = 0; (p = *t) != 0; t++) {
1115 if (!*p || strpbrk(p,
" \t\"'")) {
1120 for (bs = 0; *p; ++p) {
1134 memset(q,
'\\', bs);
1139 case '<':
case '>':
case '|':
case '^':
1140 if (escape && !quote) {
1141 len += (n = p - s) + 1;
1152 p = CharNextExA(cp, p, 0) - 1;
1156 len += (n = p - s) + 1;
1160 if (backslash > 0) {
1163 translate_char(q,
'/',
'\\', cp);
1166 if (quote) *q++ =
'"';
1179#define STRNDUPV(ptr, v, src, len) \
1180 (((char *)memcpy(((ptr) = ALLOCV((v), (len) + 1)), (src), (len)))[len] = 0)
1184check_spawn_mode(
int mode)
1206 if (mode == P_OVERLAY) {
1207 WaitForSingleObject(child->hProcess, INFINITE);
1208 GetExitCodeProcess(child->hProcess, &exitcode);
1209 CloseChildHandle(child);
1217CreateChild(
struct ChildRecord *child,
const WCHAR *cmd,
const WCHAR *prog, HANDLE hInput, HANDLE hOutput, HANDLE hError, DWORD dwCreationFlags)
1220 STARTUPINFOW aStartupInfo;
1221 PROCESS_INFORMATION aProcessInformation;
1222 SECURITY_ATTRIBUTES sa;
1224 if (!cmd && !prog) {
1234 sa.nLength =
sizeof(SECURITY_ATTRIBUTES);
1235 sa.lpSecurityDescriptor = NULL;
1236 sa.bInheritHandle = TRUE;
1238 memset(&aStartupInfo, 0,
sizeof(aStartupInfo));
1239 memset(&aProcessInformation, 0,
sizeof(aProcessInformation));
1240 aStartupInfo.cb =
sizeof(aStartupInfo);
1241 aStartupInfo.dwFlags = STARTF_USESTDHANDLES;
1243 aStartupInfo.hStdInput = hInput;
1246 aStartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
1249 aStartupInfo.hStdOutput = hOutput;
1252 aStartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
1255 aStartupInfo.hStdError = hError;
1258 aStartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
1261 dwCreationFlags |= NORMAL_PRIORITY_CLASS;
1263 if (lstrlenW(cmd) > 32767) {
1270 fRet = CreateProcessW(prog, (WCHAR *)cmd, &sa, &sa,
1271 sa.bInheritHandle, dwCreationFlags, NULL, NULL,
1272 &aStartupInfo, &aProcessInformation);
1273 errno = map_errno(GetLastError());
1281 CloseHandle(aProcessInformation.hThread);
1283 child->hProcess = aProcessInformation.hProcess;
1284 child->pid = (rb_pid_t)aProcessInformation.dwProcessId;
1291is_batch(
const char *cmd)
1293 int len = strlen(cmd);
1294 if (
len <= 4)
return 0;
1296 if (*cmd++ !=
'.')
return 0;
1297 if (strcasecmp(cmd,
"bat") == 0)
return 1;
1298 if (strcasecmp(cmd,
"cmd") == 0)
return 1;
1302#define filecp rb_w32_filecp
1303#define mbstr_to_wstr rb_w32_mbstr_to_wstr
1304#define wstr_to_mbstr rb_w32_wstr_to_mbstr
1305#define acp_to_wstr(str, plen) mbstr_to_wstr(CP_ACP, str, -1, plen)
1306#define wstr_to_acp(str, plen) wstr_to_mbstr(CP_ACP, str, -1, plen)
1307#define filecp_to_wstr(str, plen) mbstr_to_wstr(filecp(), str, -1, plen)
1308#define wstr_to_filecp(str, plen) wstr_to_mbstr(filecp(), str, -1, plen)
1309#define utf8_to_wstr(str, plen) mbstr_to_wstr(CP_UTF8, str, -1, plen)
1310#define wstr_to_utf8(str, plen) wstr_to_mbstr(CP_UTF8, str, -1, plen)
1314w32_spawn(
int mode,
const char *cmd,
const char *prog, UINT cp)
1316 char fbuf[PATH_MAX];
1318 const char *shell = NULL;
1319 WCHAR *wcmd = NULL, *wshell = NULL;
1325 char *cmd_sep = NULL;
1327 if (check_spawn_mode(mode))
return -1;
1330 if (!(p = dln_find_exe_r(prog, NULL, fbuf,
sizeof(fbuf)))) {
1335 translate_char(p,
'/',
'\\', cp);
1342 if ((shell = w32_getenv(
"RUBYSHELL", cp)) && (redir = has_redirection(cmd, cp))) {
1343 size_t shell_len = strlen(shell);
1344 size_t cmd_len = strlen(cmd) +
sizeof(
" -c ") + 2;
1345 char *tmp =
ALLOCV(v, shell_len + cmd_len);
1346 memcpy(tmp, shell, shell_len + 1);
1347 translate_char(tmp,
'/',
'\\', cp);
1348 snprintf(tmp + shell_len, cmd_len,
" -c \"%s\"", cmd);
1351 else if ((shell = w32_getenv(
"COMSPEC", cp)) &&
1352 (nt = !is_command_com(shell),
1353 (redir < 0 ? has_redirection(cmd, cp) : redir) ||
1354 is_internal_cmd(cmd, nt))) {
1355 size_t cmd_len = strlen(shell) + strlen(cmd) +
sizeof(
" /c ") + (nt ? 2 : 0);
1356 char *tmp =
ALLOCV(v, cmd_len);
1357 snprintf(tmp, cmd_len, nt ?
"%s /c \"%s\"" :
"%s /c %s", shell, cmd);
1361 int len = 0, quote = (*cmd ==
'"') ?
'"' : (*cmd ==
'\'') ?
'\'' : 0;
1363 for (prog = cmd + !!quote;; prog = CharNextExA(cp, prog, 0)) {
1364 if (*prog ==
'/') slash = 1;
1368 STRNDUPV(p, v2, cmd,
len);
1374 if ((
unsigned char)*prog == quote) {
1375 len = prog++ - cmd - 1;
1376 STRNDUPV(p, v2, cmd + 1,
len);
1380 if (quote)
continue;
1381 if (
ISSPACE(*prog) || strchr(
"<>|*?\"", *prog)) {
1383 STRNDUPV(p, v2, cmd,
len + (slash ? strlen(prog) : 0));
1386 sep = *(cmd_sep = &p[
len]);
1393 shell = dln_find_exe_r(shell, NULL, fbuf,
sizeof(fbuf));
1394 if (p && slash) translate_char(p,
'/',
'\\', cp);
1396 shell = p ? p : cmd;
1399 len = strlen(shell);
1400 if (strchr(shell,
' ')) quote = -1;
1401 if (shell == fbuf) {
1404 else if (shell != p && strchr(shell,
'/')) {
1405 STRNDUPV(p, v2, shell,
len);
1408 if (p) translate_char(p,
'/',
'\\', cp);
1409 if (is_batch(shell)) {
1410 int alen = strlen(prog);
1411 cmd = p =
ALLOCV(v,
len + alen + (quote ? 2 : 0) + 1);
1412 if (quote) *p++ =
'"';
1413 memcpy(p, shell,
len);
1415 if (quote) *p++ =
'"';
1416 memcpy(p, prog, alen + 1);
1423 if (!e && shell && !(wshell = mbstr_to_wstr(cp, shell, -1, NULL))) e = E2BIG;
1424 if (cmd_sep) *cmd_sep = sep;
1425 if (!e && cmd && !(wcmd = mbstr_to_wstr(cp, cmd, -1, NULL))) e = E2BIG;
1431 if (CreateChild(child, wcmd, wshell, NULL, NULL, NULL, 0)) {
1432 ret = child_result(child, mode);
1443rb_w32_spawn(
int mode,
const char *cmd,
const char *prog)
1446 return w32_spawn(mode, cmd, prog, filecp());
1451rb_w32_uspawn(
int mode,
const char *cmd,
const char *prog)
1453 return w32_spawn(mode, cmd, prog, CP_UTF8);
1458w32_spawn_process(
int mode,
const char *prog,
char *
const *argv,
1459 int in_fd,
int out_fd,
int err_fd, DWORD flags, UINT cp)
1463 BOOL ntcmd = FALSE, tmpnt;
1465 char *cmd, fbuf[PATH_MAX];
1466 WCHAR *wcmd = NULL, *wprog = NULL;
1470 HANDLE in_handle = NULL, out_handle = NULL, err_handle = NULL;
1472 if (check_spawn_mode(mode))
return -1;
1475 in_handle = (HANDLE)rb_w32_get_osfhandle(in_fd);
1478 out_handle = (HANDLE)rb_w32_get_osfhandle(out_fd);
1481 err_handle = (HANDLE)rb_w32_get_osfhandle(err_fd);
1484 if (!prog) prog = argv[0];
1485 if ((shell = w32_getenv(
"COMSPEC", cp)) &&
1486 internal_cmd_match(prog, tmpnt = !is_command_com(shell))) {
1491 else if ((cmd = dln_find_exe_r(prog, NULL, fbuf,
sizeof(fbuf)))) {
1492 if (cmd == prog) strlcpy(cmd = fbuf, prog,
sizeof(fbuf));
1493 translate_char(cmd,
'/',
'\\', cp);
1496 else if (strchr(prog,
'/')) {
1498 if (
len <
sizeof(fbuf))
1499 strlcpy(cmd = fbuf, prog,
sizeof(fbuf));
1501 STRNDUPV(cmd, v, prog,
len);
1502 translate_char(cmd,
'/',
'\\', cp);
1505 if (c_switch || is_batch(prog)) {
1507 progs[0] = (
char *)prog;
1509 len = join_argv(NULL, progs, ntcmd, cp, 1);
1510 if (c_switch)
len += 3;
1512 if (argv[0])
len += join_argv(NULL, argv, ntcmd, cp, 0);
1514 join_argv(cmd, progs, ntcmd, cp, 1);
1515 if (c_switch) strlcat(cmd,
" /c",
len);
1516 if (argv[0]) join_argv(cmd + strlcat(cmd,
" ",
len), argv, ntcmd, cp, 0);
1517 prog = c_switch ? shell : 0;
1520 len = join_argv(NULL, argv, FALSE, cp, 1);
1522 join_argv(cmd, argv, FALSE, cp, 1);
1525 if (!e && cmd && !(wcmd = mbstr_to_wstr(cp, cmd, -1, NULL))) e = E2BIG;
1527 if (!e && prog && !(wprog = mbstr_to_wstr(cp, prog, -1, NULL))) e = E2BIG;
1531 if (CreateChild(child, wcmd, wprog, in_handle, out_handle, err_handle, flags)) {
1532 ret = child_result(child, mode);
1543rb_w32_aspawn_flags(
int mode,
const char *prog,
char *
const *argv, DWORD flags)
1546 return w32_spawn_process(mode, prog, argv, -1, -1, -1, flags, filecp());
1551rb_w32_uaspawn_flags(
int mode,
const char *prog,
char *
const *argv, DWORD flags)
1553 return w32_spawn_process(mode, prog, argv, -1, -1, -1, flags, CP_UTF8);
1558rb_w32_aspawn(
int mode,
const char *prog,
char *
const *argv)
1560 return w32_spawn_process(mode, prog, argv, -1, -1, -1, 0, filecp());
1565rb_w32_uaspawn(
int mode,
const char *prog,
char *
const *argv)
1567 return rb_w32_uaspawn_flags(mode, prog, argv, 0);
1572rb_w32_uspawn_process(
int mode,
const char *prog,
char *
const *argv,
1573 int in_fd,
int out_fd,
int err_fd, DWORD flags)
1575 return w32_spawn_process(mode, prog, argv, in_fd, out_fd, err_fd,
1597insert(
const char *path,
VALUE vinfo,
void *enc)
1603 if (!tmpcurr)
return -1;
1605 tmpcurr->len = strlen(path);
1606 tmpcurr->str =
strdup(path);
1607 if (!tmpcurr->str)
return -1;
1608 tmpcurr->flags |= NTMALLOC;
1610 *tail = &tmpcurr->next;
1619 char buffer[PATH_MAX], *buf = buffer;
1623 if (patt->len >= PATH_MAX)
1624 if (!(buf = malloc(patt->len + 1)))
return 0;
1626 memcpy(buf, patt->str, patt->len);
1627 buf[patt->len] =
'\0';
1628 translate_char(buf,
'\\',
'/', cp);
1629 status = ruby_brace_glob_with_enc(buf, 0, insert, (
VALUE)&tail, enc);
1633 if (status || last == tail)
return 0;
1634 if (patt->flags & NTMALLOC)
1647has_redirection(
const char *cmd, UINT cp)
1657 for (ptr = cmd; *ptr;) {
1663 else if (quote == *ptr)
1679 if (*++ptr !=
'_' && !
ISALPHA(*ptr))
break;
1680 while (*++ptr ==
'_' ||
ISALNUM(*ptr));
1681 if (*ptr++ ==
'%')
return TRUE;
1687 ptr = CharNextExA(cp, ptr, 0);
1695static inline WCHAR *
1696skipspace(WCHAR *ptr)
1705w32_cmdvector(
const WCHAR *cmd,
char ***vec, UINT cp,
rb_encoding *enc)
1708 int elements, strsz, done;
1709 int slashes, escape;
1710 WCHAR *ptr, *base, *cmdline;
1711 char *cptr, *buffer;
1727 ptr = cmdline = wcsdup(cmd);
1738 while (*(ptr = skipspace(ptr))) {
1740 quote = slashes = globbing = escape = 0;
1741 for (done = 0; !done && *ptr; ) {
1750 if (quote != L
'\'') slashes++;
1790 if (!(slashes & 1)) {
1793 else if (quote == *ptr) {
1794 if (quote == L
'"' && quote == ptr[1])
1804 ptr = CharNextW(ptr);
1827 slashes = quote = 0;
1828 while (p < base +
len) {
1832 if (quote != L
'\'') slashes++;
1837 if (!(slashes & 1) && quote && quote != c) {
1842 memcpy(p - ((slashes + 1) >> 1), p + (~slashes & 1),
1843 sizeof(WCHAR) * (base +
len - p));
1844 len -= ((slashes + 1) >> 1) + (~slashes & 1);
1845 p -= (slashes + 1) >> 1;
1846 if (!(slashes & 1)) {
1848 if (quote == L
'"' && quote == *p)
1869 if (!curr)
goto do_nothing;
1870 curr->str = rb_w32_wstr_to_mbstr(cp, base,
len, &curr->len);
1871 curr->flags |= NTMALLOC;
1873 if (globbing && (tail = cmdglob(curr, cmdtail, cp, enc))) {
1878 cmdtail = &curr->next;
1888 for (elements = 0, strsz = 0, curr = cmdhead; curr; curr = curr->next) {
1890 strsz += (curr->len + 1);
1893 len = (elements+1)*
sizeof(
char *) + strsz;
1894 buffer = (
char *)malloc(
len);
1897 while ((curr = cmdhead) != 0) {
1898 cmdhead = curr->next;
1899 if (curr->flags & NTMALLOC) free(curr->str);
1903 for (vptr = *vec; *vptr; ++vptr);
1919 vptr = (
char **) buffer;
1921 cptr = buffer + (elements+1) *
sizeof(
char *);
1923 while ((curr = cmdhead) != 0) {
1924 memcpy(cptr, curr->str, curr->len);
1925 cptr[curr->len] =
'\0';
1927 cptr += curr->len + 1;
1928 cmdhead = curr->next;
1929 if (curr->flags & NTMALLOC) free(curr->str);
1934 *vec = (
char **) buffer;
1946open_special(
const WCHAR *path, DWORD access, DWORD flags)
1948 const DWORD share_mode =
1949 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1950 return CreateFileW(path, access, share_mode, NULL, OPEN_EXISTING,
1951 FILE_FLAG_BACKUP_SEMANTICS|flags, NULL);
1961#define GetBit(bits, i) ((bits)[(i) / CHAR_BIT] & (1 << (i) % CHAR_BIT))
1962#define SetBit(bits, i) ((bits)[(i) / CHAR_BIT] |= (1 << (i) % CHAR_BIT))
1964#define BitOfIsDir(n) ((n) * 2)
1965#define BitOfIsRep(n) ((n) * 2 + 1)
1966#define DIRENT_PER_CHAR (CHAR_BIT / 2)
1968static const WCHAR namespace_prefix[] = {L
'\\', L
'\\', L
'?', L
'\\'};
1970enum {FINAL_PATH_MAX = PATH_MAX + numberof(namespace_prefix)};
1974open_dir_handle(
const WCHAR *filename, WIN32_FIND_DATAW *fd)
1985 fh = open_special(filename, 0, 0);
1986 if (fh != INVALID_HANDLE_VALUE) {
1987 len = GetFinalPathNameByHandleW(fh, fullname, FINAL_PATH_MAX, 0);
1989 if (
len >= FINAL_PATH_MAX) {
1990 errno = ENAMETOOLONG;
1991 return INVALID_HANDLE_VALUE;
1995 len = lstrlenW(filename);
1996 if (
len >= PATH_MAX) {
1997 errno = ENAMETOOLONG;
1998 return INVALID_HANDLE_VALUE;
2002 p = &fullname[
len-1];
2003 if (!(isdirsep(*p) || *p == L
':')) *++p = L
'\\';
2010 fh = FindFirstFileW(fullname, fd);
2011 if (fh == INVALID_HANDLE_VALUE) {
2012 errno = map_errno(GetLastError());
2019w32_wopendir(
const WCHAR *wpath)
2022 WIN32_FIND_DATAW fd;
2035 if (wstati128(wpath, &sbuf, FALSE) < 0) {
2038 if (!(sbuf.st_mode & S_IFDIR) &&
2039 (!
ISALPHA(wpath[0]) || wpath[1] != L
':' || wpath[2] != L
'\0' ||
2040 ((1 << ((wpath[0] & 0x5f) -
'A')) & GetLogicalDrives()) == 0)) {
2044 fh = open_dir_handle(wpath, &fd);
2045 if (fh == INVALID_HANDLE_VALUE) {
2052 p = calloc(1,
sizeof(
DIR));
2056 pathlen = lstrlenW(wpath);
2066 len = lstrlenW(fd.cFileName) + 1;
2067 altlen = lstrlenW(fd.cAlternateFileName) + 1;
2073 tmpW = realloc(p->start, (idx +
len + altlen) *
sizeof(WCHAR));
2083 memcpy(&p->start[idx], fd.cFileName,
len *
sizeof(WCHAR));
2084 memcpy(&p->start[idx +
len], fd.cAlternateFileName, altlen *
sizeof(WCHAR));
2086 if (p->nfiles % DIRENT_PER_CHAR == 0) {
2087 tmp = realloc(p->bits, p->nfiles / DIRENT_PER_CHAR + 1);
2091 p->bits[p->nfiles / DIRENT_PER_CHAR] = 0;
2093 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
2094 SetBit(p->bits, BitOfIsDir(p->nfiles));
2095 if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2096 WCHAR *tmppath = malloc((pathlen +
len + 1) *
sizeof(WCHAR));
2097 memcpy(tmppath, wpath, pathlen *
sizeof(WCHAR));
2098 tmppath[pathlen] = L
'\\';
2099 memcpy(tmppath + pathlen + 1, fd.cFileName,
len *
sizeof(WCHAR));
2100 if (rb_w32_reparse_symlink_p(tmppath))
2101 SetBit(p->bits, BitOfIsRep(p->nfiles));
2106 idx +=
len + altlen;
2107 }
while (FindNextFileW(fh, &fd));
2118 UINT cp = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
2124rb_w32_wstr_to_mbstr(UINT cp,
const WCHAR *wstr,
int clen,
long *plen)
2127 int len = WideCharToMultiByte(cp, 0, wstr, clen, NULL, 0, NULL, NULL);
2128 if (!(ptr = malloc(
len)))
return 0;
2129 WideCharToMultiByte(cp, 0, wstr, clen, ptr,
len, NULL, NULL);
2132 if (clen == -1) --
len;
2140rb_w32_mbstr_to_wstr(UINT cp,
const char *str,
int clen,
long *plen)
2143 int len = MultiByteToWideChar(cp, 0, str, clen, NULL, 0);
2144 if (!(ptr = malloc(
sizeof(WCHAR) *
len)))
return 0;
2145 MultiByteToWideChar(cp, 0, str, clen, ptr,
len);
2148 if (clen == -1) --
len;
2156rb_w32_opendir(
const char *filename)
2159 WCHAR *wpath = filecp_to_wstr(filename, NULL);
2162 ret = w32_wopendir(wpath);
2169rb_w32_uopendir(
const char *filename)
2172 WCHAR *wpath = utf8_to_wstr(filename, NULL);
2175 ret = w32_wopendir(wpath);
2186move_to_next_entry(
DIR *dirp)
2190 dirp->curr += lstrlenW(dirp->curr) + 1;
2191 dirp->curr += lstrlenW(dirp->curr) + 1;
2192 if (dirp->curr >= (dirp->start + dirp->size)) {
2204win32_direct_conv(
const WCHAR *file,
const WCHAR *alt,
struct direct *entry,
const void *enc)
2206 UINT cp = *((UINT *)enc);
2207 if (!(entry->d_name = wstr_to_mbstr(cp, file, -1, &entry->d_namlen)))
2211 entry->d_altname = wstr_to_mbstr(cp, alt, -1, &altlen);
2212 entry->d_altlen = altlen;
2219rb_w32_conv_from_wchar(
const WCHAR *wstr,
rb_encoding *enc)
2222 long len = lstrlenW(wstr);
2223 int encindex = rb_enc_to_index(enc);
2225 if (encindex == ENCINDEX_UTF_16LE) {
2226 return rb_enc_str_new((
char *)wstr,
len *
sizeof(WCHAR), enc);
2229#if SIZEOF_INT < SIZEOF_LONG
2230# error long should equal to int on Windows
2233 len = WideCharToMultiByte(CP_UTF8, 0, wstr, clen, NULL, 0, NULL, NULL);
2234 src = rb_enc_str_new(0,
len, rb_enc_from_index(ENCINDEX_UTF_8));
2235 WideCharToMultiByte(CP_UTF8, 0, wstr, clen, RSTRING_PTR(src),
len, NULL, NULL);
2238 case ENCINDEX_ASCII_8BIT:
2239 case ENCINDEX_US_ASCII:
2241 case ENCINDEX_UTF_8:
2250rb_w32_conv_from_wstr(
const WCHAR *wstr,
long *lenp,
rb_encoding *enc)
2252 VALUE str = rb_w32_conv_from_wchar(wstr, enc);
2256 if (
NIL_P(str))
return wstr_to_utf8(wstr, lenp);
2257 *lenp =
len = RSTRING_LEN(str);
2258 memcpy(ptr = malloc(
len + 1), RSTRING_PTR(str),
len);
2265ruby_direct_conv(
const WCHAR *file,
const WCHAR *alt,
struct direct *entry,
const void *enc)
2267 if (!(entry->d_name = rb_w32_conv_from_wstr(file, &entry->d_namlen, enc)))
2271 entry->d_altname = rb_w32_conv_from_wstr(alt, &altlen, enc);
2272 entry->d_altlen = altlen;
2279readdir_internal(
DIR *dirp, BOOL (*conv)(
const WCHAR *,
const WCHAR *,
struct direct *,
const void *),
const void *enc)
2281 static long dummy_ino = 0;
2288 free(dirp->dirstr.d_name);
2289 free(dirp->dirstr.d_altname);
2290 dirp->dirstr.d_altname = 0;
2291 dirp->dirstr.d_altlen = 0;
2292 conv(dirp->curr, dirp->curr + lstrlenW(dirp->curr) + 1, &dirp->dirstr, enc);
2297 dirp->dirstr.d_ino = (ino_t)(InterlockedIncrement(&dummy_ino) - 1);
2303 if (GetBit(dirp->bits, BitOfIsRep(dirp->loc)))
2304 dirp->dirstr.d_type = DT_LNK;
2305 else if (GetBit(dirp->bits, BitOfIsDir(dirp->loc)))
2306 dirp->dirstr.d_type = DT_DIR;
2308 dirp->dirstr.d_type = DT_REG;
2314 move_to_next_entry(dirp);
2316 return &(dirp->dirstr);
2327 int idx = rb_enc_to_index(enc);
2328 if (idx == ENCINDEX_ASCII_8BIT) {
2329 const UINT cp = filecp();
2330 return readdir_internal(dirp, win32_direct_conv, &cp);
2332 else if (idx == ENCINDEX_UTF_8) {
2333 const UINT cp = CP_UTF8;
2334 return readdir_internal(dirp, win32_direct_conv, &cp);
2337 return readdir_internal(dirp, ruby_direct_conv, enc);
2342rb_w32_ureaddir(
DIR *dirp)
2344 const UINT cp = CP_UTF8;
2345 return readdir_internal(dirp, win32_direct_conv, &cp);
2354rb_w32_telldir(
DIR *dirp)
2365rb_w32_seekdir(
DIR *dirp,
long loc)
2367 if (dirp->loc > loc) rb_w32_rewinddir(dirp);
2369 while (dirp->curr && dirp->loc < loc) {
2370 move_to_next_entry(dirp);
2380rb_w32_rewinddir(
DIR *dirp)
2382 dirp->curr = dirp->start;
2392rb_w32_closedir(
DIR *dirp)
2395 free(dirp->dirstr.d_name);
2396 free(dirp->dirstr.d_altname);
2404#if RUBY_MSVCRT_VERSION >= 140
2419 CRITICAL_SECTION _lock;
2421#define FILE_COUNT(stream) ((vcruntime_file*)stream)->_cnt
2422#define FILE_READPTR(stream) ((vcruntime_file*)stream)->_ptr
2423#define FILE_FILENO(stream) ((vcruntime_file*)stream)->_file
2425#define FILE_COUNT(stream) stream->_cnt
2426#define FILE_READPTR(stream) stream->_ptr
2427#define FILE_FILENO(stream) stream->_file
2431#if RUBY_MSVCRT_VERSION >= 140
2432typedef char lowio_text_mode;
2433typedef char lowio_pipe_lookahead[3];
2436 CRITICAL_SECTION lock;
2439 unsigned char osfile;
2440 lowio_text_mode textmode;
2441 lowio_pipe_lookahead _pipe_lookahead;
2443 uint8_t unicode : 1;
2444 uint8_t utf8translations : 1;
2445 uint8_t dbcsBufferUsed : 1;
2454 CRITICAL_SECTION lock;
2455#if RUBY_MSVCRT_VERSION >= 80
2462#if !defined _CRTIMP || defined __MINGW32__
2464#define _CRTIMP __declspec(dllimport)
2467#if RUBY_MSVCRT_VERSION >= 140
2468static ioinfo ** __pioinfo = NULL;
2471EXTERN_C _CRTIMP
ioinfo * __pioinfo[];
2474static inline ioinfo* _pioinfo(
int);
2477#define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
2478#define _osfhnd(i) (_pioinfo(i)->osfhnd)
2479#define _osfile(i) (_pioinfo(i)->osfile)
2480#define rb_acrt_lowio_lock_fh(i) EnterCriticalSection(&_pioinfo(i)->lock)
2481#define rb_acrt_lowio_unlock_fh(i) LeaveCriticalSection(&_pioinfo(i)->lock)
2483#if RUBY_MSVCRT_VERSION >= 80
2484static size_t pioinfo_extra = 0;
2488set_pioinfo_extra(
void)
2490#if RUBY_MSVCRT_VERSION >= 140
2491# define FUNCTION_RET 0xc3
2493# define UCRTBASE "ucrtbased.dll"
2495# define UCRTBASE "ucrtbase.dll"
2510 char *p = (
char*)get_proc_address(UCRTBASE,
"_isatty", NULL);
2513#if defined(_M_ARM64) || defined(__aarch64__)
2514#define IS_INSN(pc, name) ((*(pc) & name##_mask) == name##_id)
2515 const int max_num_inst = 500;
2516 uint32_t *start = (uint32_t*)p;
2517 uint32_t *end_limit = (start + max_num_inst);
2518 uint32_t *pc = start;
2521 fprintf(stderr,
"_isatty proc not found in " UCRTBASE
"\n");
2526 const uint32_t ret_id = 0xd65f0000;
2527 const uint32_t ret_mask = 0xfffffc1f;
2528 for(; pc < end_limit; pc++) {
2529 if (IS_INSN(pc, ret)) {
2533 if (pc == end_limit) {
2534 fprintf(stderr,
"end of _isatty not found in " UCRTBASE
"\n");
2539 const uint32_t adrp_id = 0x90000000;
2540 const uint32_t adrp_mask = 0x9f000000;
2541 const uint32_t add_id = 0x11000000;
2542 const uint32_t add_mask = 0x7fc00000;
2543 for(; pc > start; pc--) {
2544 if (IS_INSN(pc, adrp) && IS_INSN(pc + 1, add)) {
2549 fprintf(stderr,
"pioinfo mark not found in " UCRTBASE
"\n");
2559 const uint32_t adrp_insn = *pc;
2560 const uint32_t adrp_immhi = (adrp_insn & 0x00ffffe0) >> 5;
2561 const uint32_t adrp_immlo = (adrp_insn & 0x60000000) >> (5 + 19 + 5);
2562 const int64_t adrp_sign = (adrp_insn & 0x00800000) ? ~0x001fffff : 0;
2564 const int64_t adrp_imm = (adrp_sign | (adrp_immhi << 2) | adrp_immlo) << 12;
2566 const uint64_t adrp_base = (uint64_t)pc & 0xfffffffffffff000;
2568 const uint32_t add_insn = *(pc + 1);
2569 const uint64_t add_imm = (add_insn & 0x3ffc00) >> (5 + 5);
2571 __pioinfo = (
ioinfo**)(adrp_base + adrp_imm + add_imm);
2579# define FUNCTION_BEFORE_RET_MARK "\x48\x83\xc4"
2580# define FUNCTION_SKIP_BYTES 1
2583# define PIOINFO_MARK "\x48\x8d\x0d"
2586# define PIOINFO_MARK "\x48\x8d\x15"
2591# define FUNCTION_BEFORE_RET_MARK "\x5d"
2593# define FUNCTION_BEFORE_RET_MARK_2 "\xc9"
2594# define FUNCTION_SKIP_BYTES 0
2596# define PIOINFO_MARK "\x8B\x04\x85"
2599 for (pend += 10; pend < p + 500; pend++) {
2601 if ((memcmp(pend, FUNCTION_BEFORE_RET_MARK,
sizeof(FUNCTION_BEFORE_RET_MARK) - 1) == 0
2602# ifdef FUNCTION_BEFORE_RET_MARK_2
2603 || memcmp(pend, FUNCTION_BEFORE_RET_MARK_2,
sizeof(FUNCTION_BEFORE_RET_MARK_2) - 1) == 0
2606 *(pend + (
sizeof(FUNCTION_BEFORE_RET_MARK) - 1) + FUNCTION_SKIP_BYTES) == (
char)FUNCTION_RET) {
2608 for (pend -= (
sizeof(PIOINFO_MARK) - 1); pend > p; pend--) {
2609 if (memcmp(pend, PIOINFO_MARK,
sizeof(PIOINFO_MARK) - 1) == 0) {
2618 fprintf(stderr,
"unexpected " UCRTBASE
"\n");
2622 p +=
sizeof(PIOINFO_MARK) - 1;
2624 rel = *(int32_t*)(p);
2625 rip = p +
sizeof(int32_t);
2626 __pioinfo = (
ioinfo**)(rip + rel);
2628 __pioinfo = *(
ioinfo***)(p);
2634 fd = _open(
"NUL", O_RDONLY);
2635 for (pioinfo_extra = 0; pioinfo_extra <= 64; pioinfo_extra +=
sizeof(
void *)) {
2636 if (_osfhnd(fd) == _get_osfhandle(fd)) {
2642 if (pioinfo_extra > 64) {
2648#define pioinfo_extra 0
2654 const size_t sizeof_ioinfo =
sizeof(
ioinfo) + pioinfo_extra;
2655 return (
ioinfo*)((
char*)__pioinfo[fd >> IOINFO_L2E] +
2656 (fd & (IOINFO_ARRAY_ELTS - 1)) * sizeof_ioinfo);
2659#define _set_osfhnd(fh, osfh) (void)(_osfhnd(fh) = osfh)
2660#define _set_osflags(fh, flags) (_osfile(fh) = (flags))
2665#define FNOINHERIT 0x10
2670static int is_socket(SOCKET);
2671static int is_console(SOCKET);
2675rb_w32_io_cancelable_p(
int fd)
2677 return is_socket(TO_SOCKET(fd)) || !is_console(TO_SOCKET(fd));
2682rb_w32_open_osfhandle(intptr_t osfhandle,
int flags)
2691 if (flags & O_APPEND)
2692 fileflags |= FAPPEND;
2697 if (flags & O_NOINHERIT)
2698 fileflags |= FNOINHERIT;
2701 hF = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
2702 fh = _open_osfhandle((intptr_t)hF, 0);
2710 rb_acrt_lowio_lock_fh(fh);
2712 _set_osfhnd(fh, osfhandle);
2716 _set_osflags(fh, fileflags);
2717 rb_acrt_lowio_unlock_fh(fh);
2728#define open_null(fd) \
2730 (nullfd = open("NUL", O_RDWR)) : 0), \
2731 ((nullfd == (fd)) ? (keep = 1) : dup2(nullfd, fd)), \
2734 if (fileno(stdin) < 0) {
2735 FILE_FILENO(stdin) = open_null(0);
2738 setmode(fileno(stdin), O_BINARY);
2740 if (fileno(stdout) < 0) {
2741 FILE_FILENO(stdout) = open_null(1);
2743 if (fileno(stderr) < 0) {
2744 FILE_FILENO(stderr) = open_null(2);
2746 if (nullfd >= 0 && !keep) close(nullfd);
2747 setvbuf(stderr, NULL, _IONBF, 0);
2750 HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
2752 if (GetConsoleMode(h, &m)) {
2753#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
2754#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x4
2756 SetConsoleMode(h, m | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
2765is_socket(SOCKET sock)
2767 if (socklist_lookup(sock, NULL))
2775rb_w32_is_socket(
int fd)
2777 return is_socket(TO_SOCKET(fd));
2790rb_w32_strerror(
int e)
2792 static char buffer[512];
2796 if (e < 0 || e > sys_nerr) {
2799#if WSAEWOULDBLOCK != EWOULDBLOCK
2800 else if (e >= EADDRINUSE && e <= EWOULDBLOCK) {
2804 for (s = 0; s < (int)(
sizeof(errmap)/
sizeof(*errmap)); s++)
2805 if (errmap[s].winerr == WSAEWOULDBLOCK)
2807 for (i = s; i < (int)(
sizeof(errmap)/
sizeof(*errmap)); i++)
2808 if (errmap[i].err == e) {
2809 e = errmap[i].winerr;
2814 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2815 FORMAT_MESSAGE_IGNORE_INSERTS, &source, e,
2816 MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
2817 buffer,
sizeof(buffer), NULL) == 0 &&
2818 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2819 FORMAT_MESSAGE_IGNORE_INSERTS, &source, e, 0,
2820 buffer,
sizeof(buffer), NULL) == 0)
2821 strlcpy(buffer,
"Unknown Error",
sizeof(buffer));
2824 strlcpy(buffer, strerror(e),
sizeof(buffer));
2827 while ((p = strpbrk(p,
"\r\n")) != NULL) {
2828 memmove(p, p + 1, strlen(p));
2879 return (uid == ROOT_UID ? 0 : -1);
2886 return (gid == ROOT_GID ? 0 : -1);
2895ioctl(
int i,
int u, ...)
2902rb_w32_fdset(
int fd, fd_set *set)
2911rb_w32_fdclr(
int fd, fd_set *set)
2914 SOCKET s = TO_SOCKET(fd);
2916 for (i = 0; i < set->fd_count; i++) {
2917 if (set->fd_array[i] == s) {
2918 memmove(&set->fd_array[i], &set->fd_array[i+1],
2919 sizeof(set->fd_array[0]) * (--set->fd_count - i));
2929rb_w32_fdisset(
int fd, fd_set *set)
2932 SOCKET s = TO_SOCKET(fd);
2933 if (s == (SOCKET)INVALID_HANDLE_VALUE)
2935 RUBY_CRITICAL {ret = __WSAFDIsSet(s, set);}
2943 max = min(src->fd_count, (UINT)max);
2944 if ((UINT)dst->
capa < (UINT)max) {
2945 dst->
capa = (src->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2949 memcpy(dst->
fdset->fd_array, src->fd_array,
2950 max *
sizeof(src->fd_array[0]));
2951 dst->
fdset->fd_count = src->fd_count;
2958 if ((UINT)dst->
capa < src->
fdset->fd_count) {
2959 dst->
capa = (src->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2963 memcpy(dst->
fdset->fd_array, src->
fdset->fd_array,
2964 src->
fdset->fd_count *
sizeof(src->
fdset->fd_array[0]));
2978extract_fd(
rb_fdset_t *dst, fd_set *src,
int (*func)(SOCKET))
2984 while (s < src->fd_count) {
2985 SOCKET fd = src->fd_array[s];
2987 if (!func || (*func)(fd)) {
2991 for (d = 0; d < dst->
fdset->fd_count; d++) {
2992 if (dst->
fdset->fd_array[d] == fd)
2995 if (d == dst->
fdset->fd_count) {
2996 if ((
int)dst->
fdset->fd_count >= dst->
capa) {
2997 dst->
capa = (dst->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
3000 dst->
fdset->fd_array[dst->
fdset->fd_count++] = fd;
3004 &src->fd_array[s+1],
3005 sizeof(src->fd_array[0]) * (--src->fd_count - s));
3015 return dst ? dst->
fdset->fd_count : m;
3020copy_fd(fd_set *dst, fd_set *src)
3023 if (!src || !dst)
return 0;
3025 for (s = 0; s < src->fd_count; ++s) {
3026 SOCKET fd = src->fd_array[s];
3028 for (d = 0; d < dst->fd_count; ++d) {
3029 if (dst->fd_array[d] == fd)
3032 if (d == dst->fd_count && d < FD_SETSIZE) {
3033 dst->fd_array[dst->fd_count++] = fd;
3037 return dst->fd_count;
3042is_not_socket(SOCKET sock)
3044 return !is_socket(sock);
3054 ret = (GetFileType((HANDLE)sock) == FILE_TYPE_PIPE);
3062is_readable_pipe(SOCKET sock)
3068 if (PeekNamedPipe((HANDLE)sock, NULL, 0, NULL, &n, NULL)) {
3072 ret = (GetLastError() == ERROR_BROKEN_PIPE);
3081is_console(SOCKET sock)
3088 ret = (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n));
3096is_readable_console(SOCKET sock)
3103 if (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n) && n > 0) {
3104 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
3105 ir.Event.KeyEvent.uChar.UnicodeChar) {
3108 else if (ir.EventType == KEY_EVENT && !ir.Event.KeyEvent.bKeyDown &&
3109 ir.Event.KeyEvent.wVirtualKeyCode == VK_MENU &&
3110 ir.Event.KeyEvent.uChar.UnicodeChar) {
3114 ReadConsoleInputW((HANDLE)sock, &ir, 1, &n);
3124is_invalid_handle(SOCKET sock)
3126 return (HANDLE)sock == INVALID_HANDLE_VALUE;
3131do_select(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3138 rb_w32_sleep(timeout->tv_sec * 1000 + timeout->tv_usec / 1000);
3140 rb_w32_sleep(INFINITE);
3144 thread_exclusive(select) {
3145 r = select(nfds, rd, wr, ex, timeout);
3147 if (r == SOCKET_ERROR) {
3148 errno = map_errno(WSAGetLastError());
3163rb_w32_time_subtract(
struct timeval *rest,
const struct timeval *wait)
3165 if (rest->tv_sec < wait->tv_sec) {
3168 while (rest->tv_usec < wait->tv_usec) {
3169 if (rest->tv_sec <= wait->tv_sec) {
3173 rest->tv_usec += 1000 * 1000;
3175 rest->tv_sec -= wait->tv_sec;
3176 rest->tv_usec -= wait->tv_usec;
3177 return rest->tv_sec != 0 || rest->tv_usec != 0;
3184 if (t1->tv_sec < t2->tv_sec)
3186 if (t1->tv_sec > t2->tv_sec)
3188 if (t1->tv_usec < t2->tv_usec)
3190 if (t1->tv_usec > t2->tv_usec)
3197int rb_w32_check_interrupt(
void *);
3202rb_w32_select_with_thread(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3203 struct timeval *timeout,
void *th)
3212 struct timeval limit = {0, 0};
3214 if (nfds < 0 || (timeout && (timeout->tv_sec < 0 || timeout->tv_usec < 0))) {
3220 if (timeout->tv_sec < 0 ||
3221 timeout->tv_usec < 0 ||
3222 timeout->tv_usec >= 1000000) {
3226 gettimeofday(&limit, NULL);
3227 limit.tv_sec += timeout->tv_sec;
3228 limit.tv_usec += timeout->tv_usec;
3229 if (limit.tv_usec >= 1000000) {
3230 limit.tv_usec -= 1000000;
3242 nonsock += extract_fd(&else_rd, rd, is_not_socket);
3245 nonsock += extract_fd(&else_wr, wr, is_not_socket);
3248 if (extract_fd(NULL, else_rd.
fdset, is_invalid_handle) > 0 ||
3249 extract_fd(NULL, else_wr.
fdset, is_invalid_handle) > 0) {
3257 extract_fd(&pipe_rd, else_rd.
fdset, is_pipe);
3260 extract_fd(&cons_rd, else_rd.
fdset, is_console);
3263 extract_fd(&except, ex, is_not_socket);
3266 if (rd && (
int)rd->fd_count > r) r = (int)rd->fd_count;
3267 if (wr && (
int)wr->fd_count > r) r = (int)wr->fd_count;
3268 if (ex && (
int)ex->fd_count > r) r = (int)ex->fd_count;
3269 if (nfds > r) nfds = r;
3273 const struct timeval wait = {0, 10 * 1000};
3276 if (th && rb_w32_check_interrupt(th) != WAIT_TIMEOUT) {
3283 extract_fd(&else_rd, pipe_rd.
fdset, is_readable_pipe);
3284 extract_fd(&else_rd, cons_rd.
fdset, is_readable_console);
3287 if (else_rd.
fdset->fd_count || else_wr.
fdset->fd_count) {
3288 r = do_select(nfds, rd, wr, ex, &zero);
3290 r += copy_fd(rd, else_rd.
fdset);
3291 r += copy_fd(wr, else_wr.
fdset);
3297 const struct timeval *dowait = &wait;
3307 if (rd) copy_fd(&orig_rd, rd);
3308 if (wr) copy_fd(&orig_wr, wr);
3309 if (ex) copy_fd(&orig_ex, ex);
3310 r = do_select(nfds, rd, wr, ex, &zero);
3312 if (rd) copy_fd(rd, &orig_rd);
3313 if (wr) copy_fd(wr, &orig_wr);
3314 if (ex) copy_fd(ex, &orig_ex);
3318 gettimeofday(&now, NULL);
3320 if (!rb_w32_time_subtract(&rest, &now))
break;
3321 if (compare(&rest, &wait) < 0) dowait = &rest;
3323 Sleep(dowait->tv_sec * 1000 + (dowait->tv_usec + 999) / 1000);
3339rb_w32_select(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3342 return rb_w32_select_with_thread(nfds, rd, wr, ex, timeout, 0);
3347get_wsa_extension_function(SOCKET s, GUID guid)
3352 WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid,
sizeof(guid),
3353 &ptr,
sizeof(ptr), &dmy, NULL, NULL);
3363rb_w32_accept(
int s,
struct sockaddr *addr,
int *addrlen)
3369 r = accept(TO_SOCKET(s), addr, addrlen);
3370 if (r != INVALID_SOCKET) {
3371 SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0);
3372 fd = rb_w32_open_osfhandle((intptr_t)r, O_RDWR|O_BINARY|O_NOINHERIT);
3374 socklist_insert(r, 0);
3379 errno = map_errno(WSAGetLastError());
3390rb_w32_bind(
int s,
const struct sockaddr *addr,
int addrlen)
3395 r = bind(TO_SOCKET(s), addr, addrlen);
3396 if (r == SOCKET_ERROR)
3397 errno = map_errno(WSAGetLastError());
3406rb_w32_connect(
int s,
const struct sockaddr *addr,
int addrlen)
3410 r = connect(TO_SOCKET(s), addr, addrlen);
3411 if (r == SOCKET_ERROR) {
3412 int err = WSAGetLastError();
3413 if (err != WSAEWOULDBLOCK)
3414 errno = map_errno(err);
3416 errno = EINPROGRESS;
3427rb_w32_getpeername(
int s,
struct sockaddr *addr,
int *addrlen)
3431 r = getpeername(TO_SOCKET(s), addr, addrlen);
3432 if (r == SOCKET_ERROR)
3433 errno = map_errno(WSAGetLastError());
3442rb_w32_getsockname(
int fd,
struct sockaddr *addr,
int *addrlen)
3447 sock = TO_SOCKET(fd);
3448 r = getsockname(sock, addr, addrlen);
3449 if (r == SOCKET_ERROR) {
3450 DWORD wsaerror = WSAGetLastError();
3451 if (wsaerror == WSAEINVAL) {
3453 if (socklist_lookup(sock, &flags)) {
3454 int af = GET_FAMILY(flags);
3456 memset(addr, 0, *addrlen);
3457 addr->sa_family = af;
3462 errno = map_errno(wsaerror);
3472rb_w32_getsockopt(
int s,
int level,
int optname,
char *optval,
int *optlen)
3476 r = getsockopt(TO_SOCKET(s), level, optname, optval, optlen);
3477 if (r == SOCKET_ERROR)
3478 errno = map_errno(WSAGetLastError());
3487rb_w32_ioctlsocket(
int s,
long cmd, u_long *argp)
3491 r = ioctlsocket(TO_SOCKET(s), cmd, argp);
3492 if (r == SOCKET_ERROR)
3493 errno = map_errno(WSAGetLastError());
3502rb_w32_listen(
int s,
int backlog)
3506 r = listen(TO_SOCKET(s), backlog);
3507 if (r == SOCKET_ERROR)
3508 errno = map_errno(WSAGetLastError());
3520finish_overlapped_socket(BOOL input, SOCKET s, WSAOVERLAPPED *wol,
int result, DWORD *
len, DWORD size)
3525 if (result != SOCKET_ERROR)
3527 else if ((err = WSAGetLastError()) == WSA_IO_PENDING) {
3528 switch (rb_w32_wait_events_blocking(&wol->hEvent, 1, INFINITE)) {
3531 result = WSAGetOverlappedResult(s, wol, &size, TRUE, &flg);
3538 result = SOCKET_ERROR;
3541 if ((err = WSAGetLastError()) == WSAECONNABORTED && !input)
3543 else if (err == WSAEMSGSIZE && input) {
3549 errno = map_errno(err);
3551 case WAIT_OBJECT_0 + 1:
3554 CancelIo((HANDLE)s);
3559 if (err == WSAECONNABORTED && !input)
3562 errno = map_errno(err);
3565 CloseHandle(wol->hEvent);
3572overlapped_socket_io(BOOL input,
int fd,
char *buf,
int len,
int flags,
3573 struct sockaddr *addr,
int *addrlen)
3584 socklist_lookup(s, &mode);
3585 if (GET_FLAGS(mode) & O_NONBLOCK) {
3588 if (addr && addrlen)
3589 r = recvfrom(s, buf,
len, flags, addr, addrlen);
3591 r = recv(s, buf,
len, flags);
3592 if (r == SOCKET_ERROR)
3593 errno = map_errno(WSAGetLastError());
3596 if (addr && addrlen)
3597 r = sendto(s, buf,
len, flags, addr, *addrlen);
3599 r = send(s, buf,
len, flags);
3600 if (r == SOCKET_ERROR) {
3601 DWORD err = WSAGetLastError();
3602 if (err == WSAECONNABORTED)
3605 errno = map_errno(err);
3615 memset(&wol, 0,
sizeof(wol));
3617 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3620 if (addr && addrlen)
3621 ret = WSARecvFrom(s, &wbuf, 1, &size, &flg, addr, addrlen,
3624 ret = WSARecv(s, &wbuf, 1, &size, &flg, &wol, NULL);
3627 if (addr && addrlen)
3628 ret = WSASendTo(s, &wbuf, 1, &size, flags, addr, *addrlen,
3631 ret = WSASend(s, &wbuf, 1, &size, flags, &wol, NULL);
3635 finish_overlapped_socket(input, s, &wol, ret, &rlen, size);
3644rb_w32_recv(
int fd,
char *buf,
int len,
int flags)
3646 return overlapped_socket_io(TRUE, fd, buf,
len, flags, NULL, NULL);
3651rb_w32_recvfrom(
int fd,
char *buf,
int len,
int flags,
3652 struct sockaddr *from,
int *fromlen)
3654 return overlapped_socket_io(TRUE, fd, buf,
len, flags, from, fromlen);
3659rb_w32_send(
int fd,
const char *buf,
int len,
int flags)
3661 return overlapped_socket_io(FALSE, fd, (
char *)buf,
len, flags, NULL, NULL);
3666rb_w32_sendto(
int fd,
const char *buf,
int len,
int flags,
3667 const struct sockaddr *to,
int tolen)
3669 return overlapped_socket_io(FALSE, fd, (
char *)buf,
len, flags,
3670 (
struct sockaddr *)to, &tolen);
3673#if !defined(MSG_TRUNC) && !defined(__MINGW32__)
3679 DWORD dwBufferCount;
3684#ifndef WSAID_WSARECVMSG
3685#define WSAID_WSARECVMSG {0xf689d7c8,0x6f1f,0x436b,{0x8a,0x53,0xe5,0x4f,0xe3,0x51,0xc3,0x22}}
3687#ifndef WSAID_WSASENDMSG
3688#define WSAID_WSASENDMSG {0xa441e712,0x754f,0x43ca,{0x84,0xa7,0x0d,0xee,0x44,0xcf,0x60,0x6d}}
3692#define msghdr_to_wsamsg(msg, wsamsg) \
3695 (wsamsg)->name = (msg)->msg_name; \
3696 (wsamsg)->namelen = (msg)->msg_namelen; \
3697 (wsamsg)->lpBuffers = ALLOCA_N(WSABUF, (msg)->msg_iovlen); \
3698 (wsamsg)->dwBufferCount = (msg)->msg_iovlen; \
3699 for (i = 0; i < (msg)->msg_iovlen; ++i) { \
3700 (wsamsg)->lpBuffers[i].buf = (msg)->msg_iov[i].iov_base; \
3701 (wsamsg)->lpBuffers[i].len = (msg)->msg_iov[i].iov_len; \
3703 (wsamsg)->Control.buf = (msg)->msg_control; \
3704 (wsamsg)->Control.len = (msg)->msg_controllen; \
3705 (wsamsg)->dwFlags = (msg)->msg_flags; \
3710recvmsg(
int fd,
struct msghdr *msg,
int flags)
3712 typedef int (WSAAPI *WSARecvMsg_t)(SOCKET,
WSAMSG *, DWORD *, WSAOVERLAPPED *, LPWSAOVERLAPPED_COMPLETION_ROUTINE);
3713 static WSARecvMsg_t pWSARecvMsg = NULL;
3723 static const GUID guid = WSAID_WSARECVMSG;
3724 pWSARecvMsg = (WSARecvMsg_t)get_wsa_extension_function(s, guid);
3729 msghdr_to_wsamsg(msg, &wsamsg);
3730 wsamsg.dwFlags |= flags;
3732 socklist_lookup(s, &mode);
3733 if (GET_FLAGS(mode) & O_NONBLOCK) {
3735 if ((ret = pWSARecvMsg(s, &wsamsg, &
len, NULL, NULL)) == SOCKET_ERROR) {
3736 errno = map_errno(WSAGetLastError());
3744 memset(&wol, 0,
sizeof(wol));
3746 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3747 ret = pWSARecvMsg(s, &wsamsg, &size, &wol, NULL);
3750 ret = finish_overlapped_socket(TRUE, s, &wol, ret, &
len, size);
3752 if (ret == SOCKET_ERROR)
3756 msg->msg_name = wsamsg.name;
3757 msg->msg_namelen = wsamsg.namelen;
3758 msg->msg_flags = wsamsg.dwFlags;
3765sendmsg(
int fd,
const struct msghdr *msg,
int flags)
3767 typedef int (WSAAPI *WSASendMsg_t)(SOCKET,
const WSAMSG *, DWORD, DWORD *, WSAOVERLAPPED *, LPWSAOVERLAPPED_COMPLETION_ROUTINE);
3768 static WSASendMsg_t pWSASendMsg = NULL;
3778 static const GUID guid = WSAID_WSASENDMSG;
3779 pWSASendMsg = (WSASendMsg_t)get_wsa_extension_function(s, guid);
3784 msghdr_to_wsamsg(msg, &wsamsg);
3786 socklist_lookup(s, &mode);
3787 if (GET_FLAGS(mode) & O_NONBLOCK) {
3789 if ((ret = pWSASendMsg(s, &wsamsg, flags, &
len, NULL, NULL)) == SOCKET_ERROR) {
3790 errno = map_errno(WSAGetLastError());
3798 memset(&wol, 0,
sizeof(wol));
3800 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3801 ret = pWSASendMsg(s, &wsamsg, flags, &size, &wol, NULL);
3804 finish_overlapped_socket(FALSE, s, &wol, ret, &
len, size);
3814rb_w32_setsockopt(
int s,
int level,
int optname,
const char *optval,
int optlen)
3818 r = setsockopt(TO_SOCKET(s), level, optname, optval, optlen);
3819 if (r == SOCKET_ERROR)
3820 errno = map_errno(WSAGetLastError());
3829rb_w32_shutdown(
int s,
int how)
3833 r = shutdown(TO_SOCKET(s), how);
3834 if (r == SOCKET_ERROR)
3835 errno = map_errno(WSAGetLastError());
3842open_ifs_socket(
int af,
int type,
int protocol)
3844 unsigned long proto_buffers_len = 0;
3846 SOCKET out = INVALID_SOCKET;
3848 if (WSAEnumProtocols(NULL, NULL, &proto_buffers_len) == SOCKET_ERROR) {
3849 error_code = WSAGetLastError();
3850 if (error_code == WSAENOBUFS) {
3851 WSAPROTOCOL_INFO *proto_buffers;
3852 int protocols_available = 0;
3854 proto_buffers = (WSAPROTOCOL_INFO *)malloc(proto_buffers_len);
3855 if (!proto_buffers) {
3856 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
3857 return INVALID_SOCKET;
3860 protocols_available =
3861 WSAEnumProtocols(NULL, proto_buffers, &proto_buffers_len);
3862 if (protocols_available != SOCKET_ERROR) {
3864 for (i = 0; i < protocols_available; i++) {
3865 if ((af != AF_UNSPEC && af != proto_buffers[i].iAddressFamily) ||
3866 (
type != proto_buffers[i].iSocketType) ||
3867 (protocol != 0 && protocol != proto_buffers[i].iProtocol))
3870 if ((proto_buffers[i].dwServiceFlags1 & XP1_IFS_HANDLES) == 0)
3873 out = WSASocket(af,
type, protocol, &(proto_buffers[i]), 0,
3874 WSA_FLAG_OVERLAPPED);
3877 if (out == INVALID_SOCKET)
3878 out = WSASocket(af,
type, protocol, NULL, 0, 0);
3879 if (out != INVALID_SOCKET)
3880 SetHandleInformation((HANDLE)out, HANDLE_FLAG_INHERIT, 0);
3883 free(proto_buffers);
3894rb_w32_socket(
int af,
int type,
int protocol)
3900 s = open_ifs_socket(af,
type, protocol);
3901 if (s == INVALID_SOCKET) {
3902 errno = map_errno(WSAGetLastError());
3906 fd = rb_w32_open_osfhandle(s, O_RDWR|O_BINARY|O_NOINHERIT);
3908 socklist_insert(s, MAKE_SOCKDATA(af, 0));
3919struct hostent * WSAAPI
3920rb_w32_gethostbyaddr(
const char *addr,
int len,
int type)
3924 r = gethostbyaddr(addr,
len,
type);
3926 errno = map_errno(WSAGetLastError());
3934struct hostent * WSAAPI
3935rb_w32_gethostbyname(
const char *name)
3939 r = gethostbyname(name);
3941 errno = map_errno(WSAGetLastError());
3950rb_w32_gethostname(
char *name,
int len)
3954 r = gethostname(name,
len);
3955 if (r == SOCKET_ERROR)
3956 errno = map_errno(WSAGetLastError());
3961#undef getprotobyname
3964struct protoent * WSAAPI
3965rb_w32_getprotobyname(
const char *name)
3969 r = getprotobyname(name);
3971 errno = map_errno(WSAGetLastError());
3976#undef getprotobynumber
3979struct protoent * WSAAPI
3980rb_w32_getprotobynumber(
int num)
3984 r = getprotobynumber(num);
3986 errno = map_errno(WSAGetLastError());
3994struct servent * WSAAPI
3995rb_w32_getservbyname(
const char *name,
const char *proto)
3999 r = getservbyname(name, proto);
4001 errno = map_errno(WSAGetLastError());
4009struct servent * WSAAPI
4010rb_w32_getservbyport(
int port,
const char *proto)
4014 r = getservbyport(port, proto);
4016 errno = map_errno(WSAGetLastError());
4025socketpair_unix_path(
struct sockaddr_un *sock_un)
4028 WCHAR wpath[
sizeof(sock_un->sun_path)/
sizeof(*sock_un->sun_path)] = L
"";
4033 listener = socket(AF_UNIX, SOCK_STREAM, 0);
4034 if (listener == INVALID_SOCKET)
4037 memset(sock_un, 0,
sizeof(*sock_un));
4038 sock_un->sun_family = AF_UNIX;
4048 for (
int try = 0; ;
try++) {
4049 LARGE_INTEGER ticks;
4050 size_t path_len = 0;
4051 const size_t maxpath =
sizeof(sock_un->sun_path)/
sizeof(*sock_un->sun_path);
4056 path_len = GetTempPathW(maxpath, wpath);
4059 wcsncpy(wpath, L
"C:/Temp/", maxpath);
4060 path_len = lstrlenW(wpath);
4067 closesocket(listener);
4072 path_len = WideCharToMultiByte(CP_UTF8, 0, wpath, path_len, sock_un->sun_path, maxpath, NULL, NULL);
4073 QueryPerformanceCounter(&ticks);
4074 path_len += snprintf(sock_un->sun_path + path_len,
4078 GetCurrentProcessId());
4081 MultiByteToWideChar(CP_UTF8, 0, sock_un->sun_path, -1, wpath,
sizeof(wpath)/
sizeof(*wpath));
4083 if (bind(listener, (
struct sockaddr *)sock_un,
sizeof(*sock_un)) != SOCKET_ERROR)
4086 closesocket(listener);
4088 return sizeof(*sock_un);
4094socketpair_internal(
int af,
int type,
int protocol, SOCKET *sv)
4096 SOCKET svr = INVALID_SOCKET, r = INVALID_SOCKET, w = INVALID_SOCKET;
4097 struct sockaddr_in sock_in4;
4100 struct sockaddr_in6 sock_in6;
4104 struct sockaddr_un sock_un = {0, {0}};
4105 WCHAR wpath[
sizeof(sock_un.sun_path)/
sizeof(*sock_un.sun_path)] = L
"";
4108 struct sockaddr *addr;
4114#if defined PF_INET && PF_INET != AF_INET
4117 sock_in4.sin_family = AF_INET;
4118 sock_in4.sin_port = 0;
4119 sock_in4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4120 addr = (
struct sockaddr *)&sock_in4;
4121 len =
sizeof(sock_in4);
4125 memset(&sock_in6, 0,
sizeof(sock_in6));
4126 sock_in6.sin6_family = AF_INET6;
4127 sock_in6.sin6_addr = IN6ADDR_LOOPBACK_INIT;
4128 addr = (
struct sockaddr *)&sock_in6;
4129 len =
sizeof(sock_in6);
4134 addr = (
struct sockaddr *)&sock_un;
4135 len = socketpair_unix_path(&sock_un);
4136 MultiByteToWideChar(CP_UTF8, 0, sock_un.sun_path, -1, wpath,
sizeof(wpath)/
sizeof(*wpath));
4142 errno = EAFNOSUPPORT;
4145 if (
type != SOCK_STREAM) {
4150 sv[0] = (SOCKET)INVALID_HANDLE_VALUE;
4151 sv[1] = (SOCKET)INVALID_HANDLE_VALUE;
4154 svr = open_ifs_socket(af,
type, protocol);
4155 if (svr == INVALID_SOCKET)
4157 if (bind(svr, addr,
len) < 0)
4159 if (getsockname(svr, addr, &
len) < 0)
4161 if (
type == SOCK_STREAM)
4164 w = open_ifs_socket(af,
type, protocol);
4165 if (w == INVALID_SOCKET)
4167 if (connect(w, addr,
len) < 0)
4170 r = accept(svr, addr, &
len);
4171 if (r == INVALID_SOCKET)
4173 SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0);
4179 errno = map_errno(WSAGetLastError());
4180 if (r != INVALID_SOCKET)
4182 if (w != INVALID_SOCKET)
4189 if (svr != INVALID_SOCKET)
4192 if (sock_un.sun_family == AF_UNIX)
4202socketpair(
int af,
int type,
int protocol,
int *sv)
4206 if (socketpair_internal(af,
type, protocol, pair) < 0)
4208 sv[0] = rb_w32_open_osfhandle(pair[0], O_RDWR|O_BINARY|O_NOINHERIT);
4210 closesocket(pair[0]);
4211 closesocket(pair[1]);
4214 sv[1] = rb_w32_open_osfhandle(pair[1], O_RDWR|O_BINARY|O_NOINHERIT);
4216 rb_w32_close(sv[0]);
4217 closesocket(pair[1]);
4220 socklist_insert(pair[0], MAKE_SOCKDATA(af, 0));
4221 socklist_insert(pair[1], MAKE_SOCKDATA(af, 0));
4226#if !defined(_MSC_VER) || _MSC_VER >= 1400
4229str2guid(
const char *str, GUID *guid)
4231#define hex2byte(str) \
4232 ((isdigit(*(str)) ? *(str) - '0' : toupper(*(str)) - 'A' + 10) << 4 | (isdigit(*((str) + 1)) ? *((str) + 1) - '0' : toupper(*((str) + 1)) - 'A' + 10))
4235 if (*str ==
'{') str++;
4236 guid->Data1 = (long)strtoul(str, &end, 16);
4238 guid->Data2 = (
unsigned short)strtoul(str, &end, 16);
4240 guid->Data3 = (
unsigned short)strtoul(str, &end, 16);
4242 guid->Data4[0] = hex2byte(str);
4244 guid->Data4[1] = hex2byte(str);
4246 for (i = 0; i < 6; i++) {
4247 guid->Data4[i + 2] = hex2byte(str);
4253#ifndef HAVE_TYPE_NET_LUID
4257 uint64_t Reserved :24;
4258 uint64_t NetLuidIndex :24;
4259 uint64_t IfType :16;
4265getifaddrs(
struct ifaddrs **ifap)
4269 IP_ADAPTER_ADDRESSES *root, *addr;
4272 ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, NULL, &size);
4273 if (ret != ERROR_BUFFER_OVERFLOW) {
4274 errno = map_errno(ret);
4277 root = ruby_xmalloc(size);
4278 ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, root, &size);
4279 if (ret != ERROR_SUCCESS) {
4280 errno = map_errno(ret);
4285 for (prev = NULL, addr = root; addr; addr = addr->Next) {
4286 struct ifaddrs *ifa = ruby_xcalloc(1,
sizeof(*ifa));
4287 char name[IFNAMSIZ];
4292 prev->ifa_next = ifa;
4296 str2guid(addr->AdapterName, &guid);
4297 if (ConvertInterfaceGuidToLuid(&guid, &luid) == NO_ERROR &&
4298 ConvertInterfaceLuidToNameA(&luid, name,
sizeof(name)) == NO_ERROR) {
4305 if (addr->IfType & IF_TYPE_SOFTWARE_LOOPBACK)
4306 ifa->ifa_flags |= IFF_LOOPBACK;
4307 if (addr->OperStatus == IfOperStatusUp) {
4308 ifa->ifa_flags |= IFF_UP;
4310 if (addr->FirstUnicastAddress) {
4311 IP_ADAPTER_UNICAST_ADDRESS *cur;
4313 for (cur = addr->FirstUnicastAddress; cur; cur = cur->Next) {
4314 if (cur->Flags & IP_ADAPTER_ADDRESS_TRANSIENT ||
4315 cur->DadState == IpDadStateDeprecated) {
4320 ifa = ruby_xcalloc(1,
sizeof(*ifa));
4321 prev->ifa_next = ifa;
4323 ifa->ifa_flags = prev->ifa_flags;
4325 ifa->ifa_addr = ruby_xmalloc(cur->Address.iSockaddrLength);
4326 memcpy(ifa->ifa_addr, cur->Address.lpSockaddr,
4327 cur->Address.iSockaddrLength);
4342freeifaddrs(
struct ifaddrs *ifp)
4345 struct ifaddrs *next = ifp->ifa_next;
4346 ruby_xfree(ifp->ifa_addr);
4347 ruby_xfree(ifp->ifa_name);
4359void endhostent(
void) {}
4360void endnetent(
void) {}
4361void endprotoent(
void) {}
4362void endservent(
void) {}
4364struct netent *getnetent (
void) {
return (
struct netent *) NULL;}
4366struct netent *getnetbyaddr(
long net,
int type) {
return (
struct netent *)NULL;}
4368struct netent *getnetbyname(
const char *name) {
return (
struct netent *)NULL;}
4370struct protoent *getprotoent (
void) {
return (
struct protoent *) NULL;}
4372struct servent *getservent (
void) {
return (
struct servent *) NULL;}
4374void sethostent (
int stayopen) {}
4376void setnetent (
int stayopen) {}
4378void setprotoent (
int stayopen) {}
4380void setservent (
int stayopen) {}
4383int rb_w32_set_nonblock2(
int fd,
int nonblock);
4387setfl(SOCKET sock,
int arg)
4394 socklist_lookup(sock, &flag);
4395 af = GET_FAMILY(flag);
4396 flag = GET_FLAGS(flag);
4397 if (arg & O_NONBLOCK) {
4402 flag &= ~O_NONBLOCK;
4406 ret = ioctlsocket(sock, FIONBIO, &ioctlArg);
4408 socklist_insert(sock, MAKE_SOCKDATA(af, flag));
4410 errno = map_errno(WSAGetLastError());
4418dupfd(HANDLE hDup,
int flags,
int minfd)
4426 ret = _open_osfhandle((intptr_t)hDup, flags | FOPEN);
4428 goto close_fds_and_return;
4431 goto close_fds_and_return;
4433 fds[filled++] = ret;
4434 }
while (filled < (
int)numberof(fds));
4436 ret = dupfd(hDup, flags, minfd);
4438 close_fds_and_return:
4440 while (filled > 0) {
4441 int fd = fds[--filled];
4442 _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE);
4452fcntl(
int fd,
int cmd, ...)
4461 arg = va_arg(va,
int);
4463 return rb_w32_set_nonblock2(fd, arg);
4465 case F_DUPFD:
case F_DUPFD_CLOEXEC: {
4469 if (!(DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
4470 GetCurrentProcess(), &hDup, 0L,
4471 cmd == F_DUPFD && !(flag & FNOINHERIT),
4472 DUPLICATE_SAME_ACCESS))) {
4473 errno = map_errno(GetLastError());
4478 arg = va_arg(va,
int);
4484 flag &= ~FNOINHERIT;
4485 if ((ret = dupfd(hDup, flag, arg)) == -1)
4491 if (h == -1)
return -1;
4492 if (!GetHandleInformation((HANDLE)h, &flag)) {
4493 errno = map_errno(GetLastError());
4496 return (flag & HANDLE_FLAG_INHERIT) ? 0 : FD_CLOEXEC;
4500 if (h == -1)
return -1;
4502 arg = va_arg(va,
int);
4504 if (!SetHandleInformation((HANDLE)h, HANDLE_FLAG_INHERIT,
4505 (arg & FD_CLOEXEC) ? 0 : HANDLE_FLAG_INHERIT)) {
4506 errno = map_errno(GetLastError());
4509 if (arg & FD_CLOEXEC)
4510 _osfile(fd) |= FNOINHERIT;
4512 _osfile(fd) &= ~FNOINHERIT;
4523rb_w32_set_nonblock2(
int fd,
int nonblock)
4525 SOCKET sock = TO_SOCKET(fd);
4526 if (is_socket(sock)) {
4527 return setfl(sock, nonblock ? O_NONBLOCK : 0);
4529 else if (is_pipe(sock)) {
4531 if (!GetNamedPipeHandleState((HANDLE)sock, &state, NULL, NULL, NULL, NULL, 0)) {
4532 errno = map_errno(GetLastError());
4536 state |= PIPE_NOWAIT;
4539 state &= ~PIPE_NOWAIT;
4541 if (!SetNamedPipeHandleState((HANDLE)sock, &state, NULL, NULL)) {
4542 errno = map_errno(GetLastError());
4554rb_w32_set_nonblock(
int fd)
4556 return rb_w32_set_nonblock2(fd, TRUE);
4565poll_child_status(
struct ChildRecord *child,
int *stat_loc)
4570 if (!GetExitCodeProcess(child->hProcess, &exitcode)) {
4572 err = GetLastError();
4574 case ERROR_INVALID_PARAMETER:
4577 case ERROR_INVALID_HANDLE:
4581 errno = map_errno(err);
4585 CloseChildHandle(child);
4588 if (exitcode != STILL_ACTIVE) {
4591 if (rb_w32_wait_events_blocking(&child->hProcess, 1, INFINITE) != WAIT_OBJECT_0) {
4595 CloseChildHandle(child);
4597 *stat_loc = exitcode << 8;
4598 if (exitcode & 0xC0000000) {
4599 static const struct {
4603 {STATUS_ACCESS_VIOLATION, SIGSEGV},
4604 {STATUS_ILLEGAL_INSTRUCTION, SIGILL},
4605 {STATUS_PRIVILEGED_INSTRUCTION, SIGILL},
4606 {STATUS_FLOAT_DENORMAL_OPERAND, SIGFPE},
4607 {STATUS_FLOAT_DIVIDE_BY_ZERO, SIGFPE},
4608 {STATUS_FLOAT_INEXACT_RESULT, SIGFPE},
4609 {STATUS_FLOAT_INVALID_OPERATION, SIGFPE},
4610 {STATUS_FLOAT_OVERFLOW, SIGFPE},
4611 {STATUS_FLOAT_STACK_CHECK, SIGFPE},
4612 {STATUS_FLOAT_UNDERFLOW, SIGFPE},
4613#ifdef STATUS_FLOAT_MULTIPLE_FAULTS
4614 {STATUS_FLOAT_MULTIPLE_FAULTS, SIGFPE},
4616#ifdef STATUS_FLOAT_MULTIPLE_TRAPS
4617 {STATUS_FLOAT_MULTIPLE_TRAPS, SIGFPE},
4619 {STATUS_CONTROL_C_EXIT, SIGINT},
4622 for (i = 0; i < (int)numberof(table); i++) {
4623 if (table[i].status == exitcode) {
4624 *stat_loc |= table[i].sig;
4629 if (i >= (
int)numberof(table))
4630 *stat_loc |= SIGSEGV;
4640waitpid(rb_pid_t pid,
int *stat_loc,
int options)
4645 if (options == WNOHANG) {
4656 HANDLE events[MAXCHILDNUM];
4659 FOREACH_CHILD(child) {
4660 if (!child->pid || child->pid < 0)
continue;
4661 if ((pid = poll_child_status(child, stat_loc)))
return pid;
4662 events[count++] = child->hProcess;
4663 } END_FOREACH_CHILD;
4669 ret = rb_w32_wait_events_blocking(events, count, timeout);
4670 if (ret == WAIT_TIMEOUT)
return 0;
4671 if ((ret -= WAIT_OBJECT_0) == count) {
4675 errno = map_errno(GetLastError());
4679 cause = FindChildSlotByHandle(events[ret]);
4684 return poll_child_status(cause, stat_loc);
4694 while (!(pid = poll_child_status(child, stat_loc))) {
4696 int ret = rb_w32_wait_events_blocking(&child->hProcess, 1, timeout);
4697 if (ret == WAIT_OBJECT_0 + 1)
return -1;
4698 if (ret != WAIT_OBJECT_0) {
4700 if (options & WNOHANG) {
4707 if (pid == -1 && retried) pid = 0;
4713#include <sys/timeb.h>
4718filetime_split(
const FILETIME* ft,
long *subsec)
4724 tmp.LowPart = ft->dwLowDateTime;
4725 tmp.HighPart = ft->dwHighDateTime;
4732 lt -= (
LONG_LONG)((1970-1601)*365.2425) * 24 * 60 * 60 * subsec_unit;
4734 *subsec = (long)(lt % subsec_unit);
4735 return (time_t)(lt / subsec_unit);
4745 GetSystemTimePreciseAsFileTime(&ft);
4746 tv->tv_sec = filetime_split(&ft, &subsec);
4747 tv->tv_usec = subsec / 10;
4754clock_gettime(clockid_t clock_id,
struct timespec *sp)
4757 case CLOCK_REALTIME:
4762 GetSystemTimePreciseAsFileTime(&ft);
4763 sp->tv_sec = filetime_split(&ft, &subsec);
4764 sp->tv_nsec = subsec * 100;
4767 case CLOCK_MONOTONIC:
4770 LARGE_INTEGER count;
4771 if (!QueryPerformanceFrequency(&freq)) {
4772 errno = map_errno(GetLastError());
4775 if (!QueryPerformanceCounter(&count)) {
4776 errno = map_errno(GetLastError());
4779 sp->tv_sec = count.QuadPart / freq.QuadPart;
4780 if (freq.QuadPart < 1000000000)
4781 sp->tv_nsec = (count.QuadPart % freq.QuadPart) * 1000000000 / freq.QuadPart;
4783 sp->tv_nsec = (long)((count.QuadPart % freq.QuadPart) * (1000000000.0 / freq.QuadPart));
4794clock_getres(clockid_t clock_id,
struct timespec *sp)
4797 case CLOCK_REALTIME:
4803 case CLOCK_MONOTONIC:
4806 if (!QueryPerformanceFrequency(&freq)) {
4807 errno = map_errno(GetLastError());
4811 sp->tv_nsec = (long)(1000000000.0 / freq.QuadPart);
4822w32_getcwd(
char *buffer,
int size, UINT cp,
void *alloc(
int,
void *),
void *arg)
4827 len = GetCurrentDirectoryW(0, NULL);
4829 errno = map_errno(GetLastError());
4833 if (buffer && size <
len) {
4839 if (!GetCurrentDirectoryW(
len, p)) {
4840 errno = map_errno(GetLastError());
4844 wlen = translate_wchar(p, L
'\\', L
'/') - p + 1;
4845 len = WideCharToMultiByte(cp, 0, p, wlen, NULL, 0, NULL, NULL);
4853 buffer = (*alloc)(
len, arg);
4859 WideCharToMultiByte(cp, 0, p, wlen, buffer,
len, NULL, NULL);
4866getcwd_alloc(
int size,
void *dummy)
4868 return malloc(size);
4873rb_w32_getcwd(
char *buffer,
int size)
4875 return w32_getcwd(buffer, size, filecp(), getcwd_alloc, NULL);
4880rb_w32_ugetcwd(
char *buffer,
int size)
4882 return w32_getcwd(buffer, size, CP_UTF8, getcwd_alloc, NULL);
4887getcwd_value(
int size,
void *arg)
4890 return RSTRING_PTR(str);
4895rb_dir_getwd_ospath(
void)
4898 w32_getcwd(NULL, 0, CP_UTF8, getcwd_value, &cwd);
4904chown(
const char *path,
int owner,
int group)
4911rb_w32_uchown(
const char *path,
int owner,
int group)
4917lchown(
const char *path,
int owner,
int group)
4923rb_w32_ulchown(
const char *path,
int owner,
int group)
4930kill(rb_pid_t pid,
int sig)
4935 if (pid < 0 || (pid == 0 && sig != SIGINT)) {
4940 if ((
unsigned int)pid == GetCurrentProcessId() &&
4941 (sig != 0 && sig != SIGKILL)) {
4942 if ((ret = raise(sig)) != 0) {
4953 OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid);
4954 if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) {
4955 if (GetLastError() == ERROR_INVALID_PARAMETER) {
4971 DWORD ctrlEvent = CTRL_C_EVENT;
4975 ctrlEvent = CTRL_BREAK_EVENT;
4977 if (!GenerateConsoleCtrlEvent(ctrlEvent, (DWORD)pid)) {
4978 if ((err = GetLastError()) == 0)
4981 errno = map_errno(GetLastError());
4992 hProc = child->hProcess;
4995 hProc = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid);
4997 if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) {
4998 if (GetLastError() == ERROR_INVALID_PARAMETER) {
5008 if (!GetExitCodeProcess(hProc, &status)) {
5009 errno = map_errno(GetLastError());
5012 else if (status == STILL_ACTIVE) {
5013 if (!TerminateProcess(hProc, 0)) {
5040wlink(
const WCHAR *from,
const WCHAR *to)
5042 if (!CreateHardLinkW(to, from, NULL)) {
5043 errno = map_errno(GetLastError());
5052rb_w32_ulink(
const char *from,
const char *to)
5058 if (!(wfrom = utf8_to_wstr(from, NULL)))
5060 if (!(wto = utf8_to_wstr(to, NULL))) {
5064 ret = wlink(wfrom, wto);
5072link(
const char *from,
const char *to)
5078 if (!(wfrom = filecp_to_wstr(from, NULL)))
5080 if (!(wto = filecp_to_wstr(to, NULL))) {
5084 ret = wlink(wfrom, wto);
5091#ifndef FILE_DEVICE_FILE_SYSTEM
5092# define FILE_DEVICE_FILE_SYSTEM 0x00000009
5094#ifndef FSCTL_GET_REPARSE_POINT
5095# define FSCTL_GET_REPARSE_POINT ((0x9<<16)|(42<<2))
5097#ifndef IO_REPARSE_TAG_SYMLINK
5098# define IO_REPARSE_TAG_SYMLINK 0xA000000CL
5109 f = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5110 if (f == INVALID_HANDLE_VALUE) {
5111 return GetLastError();
5114 if (!DeviceIoControl(f, FSCTL_GET_REPARSE_POINT, NULL, 0,
5115 rp, size, &ret, NULL)) {
5118 else if (rp->ReparseTag != IO_REPARSE_TAG_SYMLINK &&
5119 rp->ReparseTag != IO_REPARSE_TAG_MOUNT_POINT) {
5120 e = ERROR_INVALID_PARAMETER;
5128rb_w32_reparse_symlink_p(
const WCHAR *path)
5136 e = rb_w32_read_reparse_point(path, rp,
sizeof(rbuf), &wbuf, &
len);
5137 if (e == ERROR_MORE_DATA) {
5138 size_t size = rb_w32_reparse_buffer_size(
len + 1);
5140 e = rb_w32_read_reparse_point(path, rp, size, &wbuf, &
len);
5145 case ERROR_MORE_DATA:
5154 size_t bufsize, WCHAR **result, DWORD *
len)
5156 int e = reparse_symlink(path, rp, bufsize);
5159 if (!e || e == ERROR_MORE_DATA) {
5161 if (rp->ReparseTag == IO_REPARSE_TAG_SYMLINK) {
5162 name = ((
char *)rp->SymbolicLinkReparseBuffer.PathBuffer +
5163 rp->SymbolicLinkReparseBuffer.PrintNameOffset);
5164 ret = rp->SymbolicLinkReparseBuffer.PrintNameLength;
5165 *
len = ret /
sizeof(WCHAR);
5167 else if (rp->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT) {
5168 static const WCHAR volume[] = L
"Volume{";
5170 name = ((
char *)rp->MountPointReparseBuffer.PathBuffer +
5171 rp->MountPointReparseBuffer.SubstituteNameOffset +
5172 volume_prefix_len *
sizeof(WCHAR));
5173 ret = rp->MountPointReparseBuffer.SubstituteNameLength;
5174 *
len = ret /
sizeof(WCHAR);
5175 ret -= volume_prefix_len *
sizeof(WCHAR);
5176 if (ret >
sizeof(volume) - 1 *
sizeof(WCHAR) &&
5177 memcmp(name, volume,
sizeof(volume) - 1 *
sizeof(WCHAR)) == 0)
5185 if ((
char *)name + ret +
sizeof(WCHAR) > (
char *)rp + bufsize)
5189 ((WCHAR *)name)[ret/
sizeof(WCHAR)] = L
'\0';
5190 translate_wchar(name, L
'\\', L
'/');
5200w32_readlink(UINT cp,
const char *path,
char *buf,
size_t bufsize)
5202 VALUE rp_buf, rp_buf_bigger = 0;
5203 DWORD
len = MultiByteToWideChar(cp, 0, path, -1, NULL, 0);
5204 size_t size = rb_w32_reparse_buffer_size(bufsize);
5206 WCHAR *wpath =
ALLOCV(rp_buf,
sizeof(WCHAR) *
len + size);
5211 MultiByteToWideChar(cp, 0, path, -1, wpath,
len);
5212 e = rb_w32_read_reparse_point(wpath, rp, size, &wname, &
len);
5213 if (e == ERROR_MORE_DATA) {
5214 size = rb_w32_reparse_buffer_size(
len + 1);
5215 rp =
ALLOCV(rp_buf_bigger, size);
5216 e = rb_w32_read_reparse_point(wpath, rp, size, &wname, &
len);
5221 errno = e == -1 ? EINVAL : map_errno(e);
5224 len = lstrlenW(wname);
5225 ret = WideCharToMultiByte(cp, 0, wname,
len, buf, bufsize, NULL, NULL);
5236rb_w32_ureadlink(
const char *path,
char *buf,
size_t bufsize)
5238 return w32_readlink(CP_UTF8, path, buf, bufsize);
5243readlink(
const char *path,
char *buf,
size_t bufsize)
5245 return w32_readlink(filecp(), path, buf, bufsize);
5248#ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5249#define SYMBOLIC_LINK_FLAG_DIRECTORY (0x1)
5251#ifndef SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
5252#define SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE (0x2)
5257w32_symlink(UINT cp,
const char *src,
const char *link)
5259 int atts, len1, len2;
5261 WCHAR *wsrc, *wlink;
5266 static DWORD create_flag = SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
5276 len1 = MultiByteToWideChar(cp, 0, src, -1, NULL, 0);
5277 len2 = MultiByteToWideChar(cp, 0, link, -1, NULL, 0);
5278 wsrc =
ALLOCV_N(WCHAR, buf, len1+len2);
5279 wlink = wsrc + len1;
5280 MultiByteToWideChar(cp, 0, src, -1, wsrc, len1);
5281 MultiByteToWideChar(cp, 0, link, -1, wlink, len2);
5282 translate_wchar(wsrc, L
'/', L
'\\');
5284 atts = GetFileAttributesW(wsrc);
5285 if (atts != -1 && atts & FILE_ATTRIBUTE_DIRECTORY)
5286 flag = SYMBOLIC_LINK_FLAG_DIRECTORY;
5287 ret = CreateSymbolicLinkW(wlink, wsrc, flag |= create_flag);
5289 (e = GetLastError()) == ERROR_INVALID_PARAMETER &&
5290 (flag & SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)) {
5292 flag &= ~SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
5293 ret = CreateSymbolicLinkW(wlink, wsrc, flag);
5294 if (!ret) e = GetLastError();
5299 errno = map_errno(e);
5307rb_w32_usymlink(
const char *src,
const char *link)
5309 return w32_symlink(CP_UTF8, src, link);
5314symlink(
const char *src,
const char *link)
5316 return w32_symlink(filecp(), src, link);
5323 return waitpid(-1, status, 0);
5328w32_getenv(
const char *name, UINT cp)
5330 WCHAR *wenvarea, *wenv;
5331 int len = strlen(name);
5332 char *env, *found = NULL;
5335 if (
len == 0)
return NULL;
5340 return getenv(name);
5343 thread_exclusive(uenvarea) {
5348 wenvarea = GetEnvironmentStringsW();
5350 map_errno(GetLastError());
5353 for (wenv = wenvarea, wlen = 1; *wenv; wenv += lstrlenW(wenv) + 1)
5354 wlen += lstrlenW(wenv) + 1;
5355 uenvarea = wstr_to_mbstr(cp, wenvarea, wlen, NULL);
5356 FreeEnvironmentStringsW(wenvarea);
5360 for (env = uenvarea; *env; env += strlen(env) + 1) {
5361 if (strncasecmp(env, name,
len) == 0 && *(env +
len) ==
'=') {
5362 found = env +
len + 1;
5373rb_w32_ugetenv(
const char *name)
5375 return w32_getenv(name, CP_UTF8);
5380rb_w32_getenv(
const char *name)
5382 return w32_getenv(name, CP_ACP);
5387get_attr_vsn(
const WCHAR *path, DWORD *atts, DWORD *vsn)
5389 BY_HANDLE_FILE_INFORMATION st = {0};
5391 HANDLE h = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5393 if (h == INVALID_HANDLE_VALUE) {
5398 if (!GetFileInformationByHandle(h, &st)) {
5403 *atts = st.dwFileAttributes;
5404 *vsn = st.dwVolumeSerialNumber;
5412wrename(
const WCHAR *oldpath,
const WCHAR *newpath)
5415 DWORD oldatts = 0, newatts = (DWORD)-1;
5416 DWORD oldvsn = 0, newvsn = 0, e;
5418 e = get_attr_vsn(oldpath, &oldatts, &oldvsn);
5420 errno = map_errno(e);
5423 if (oldatts & FILE_ATTRIBUTE_REPARSE_POINT) {
5424 HANDLE fh = open_special(oldpath, 0, 0);
5425 if (fh == INVALID_HANDLE_VALUE) {
5427 if (e == ERROR_CANT_RESOLVE_FILENAME) {
5434 get_attr_vsn(newpath, &newatts, &newvsn);
5437 if (newatts != (DWORD)-1 && newatts & FILE_ATTRIBUTE_READONLY)
5438 SetFileAttributesW(newpath, newatts & ~ FILE_ATTRIBUTE_READONLY);
5440 if (!MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED))
5444 DWORD e = GetLastError();
5445 if ((e == ERROR_ACCESS_DENIED) && (oldatts & FILE_ATTRIBUTE_DIRECTORY) &&
5449 errno = map_errno(e);
5452 SetFileAttributesW(newpath, oldatts);
5460rb_w32_urename(
const char *from,
const char *to)
5466 if (!(wfrom = utf8_to_wstr(from, NULL)))
5468 if (!(wto = utf8_to_wstr(to, NULL))) {
5472 ret = wrename(wfrom, wto);
5480rb_w32_rename(
const char *from,
const char *to)
5486 if (!(wfrom = filecp_to_wstr(from, NULL)))
5488 if (!(wto = filecp_to_wstr(to, NULL))) {
5492 ret = wrename(wfrom, wto);
5500isUNCRoot(
const WCHAR *path)
5502 if (path[0] == L
'\\' && path[1] == L
'\\') {
5503 const WCHAR *p = path + 2;
5504 if (p[0] == L
'?' && p[1] == L
'\\') {
5512 for (p++; *p; p++) {
5516 if (!p[0] || !p[1] || (p[1] == L
'.' && !p[2]))
5523#define COPY_STAT(src, dest, size_cast) do { \
5524 (dest).st_dev = (src).st_dev; \
5525 (dest).st_ino = (src).st_ino; \
5526 (dest).st_mode = (src).st_mode; \
5527 (dest).st_nlink = (src).st_nlink; \
5528 (dest).st_uid = (src).st_uid; \
5529 (dest).st_gid = (src).st_gid; \
5530 (dest).st_rdev = (src).st_rdev; \
5531 (dest).st_size = size_cast(src).st_size; \
5532 (dest).st_atime = (src).st_atime; \
5533 (dest).st_mtime = (src).st_mtime; \
5534 (dest).st_ctime = (src).st_ctime; \
5537static time_t filetime_to_unixtime(
const FILETIME *ft);
5538static long filetime_to_nsec(
const FILETIME *ft);
5539static WCHAR *name_for_stat(WCHAR *buf,
const WCHAR *path);
5540static DWORD stati128_handle(HANDLE h,
struct stati128 *st);
5545rb_w32_fstat(
int fd,
struct stat *st)
5547 BY_HANDLE_FILE_INFORMATION info;
5548 int ret = fstat(fd, st);
5550 if (ret)
return ret;
5551 if (GetEnvironmentVariableW(L
"TZ", NULL, 0) == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND)
return ret;
5552 if (GetFileInformationByHandle((HANDLE)_get_osfhandle(fd), &info)) {
5553 st->st_atime = filetime_to_unixtime(&info.ftLastAccessTime);
5554 st->st_mtime = filetime_to_unixtime(&info.ftLastWriteTime);
5555 st->st_ctime = filetime_to_unixtime(&info.ftCreationTime);
5562rb_w32_fstati128(
int fd,
struct stati128 *st)
5565 int ret = fstat(fd, &tmp);
5567 if (ret)
return ret;
5568 COPY_STAT(tmp, *st, +);
5569 stati128_handle((HANDLE)_get_osfhandle(fd), st);
5573#if !defined FILE_INVALID_FILE_ID && !defined __MINGW32__
5575 BYTE Identifier[16];
5579#if !defined(_WIN32_WINNT_WIN8) || _WIN32_WINNT < 0x602
5580#define FileIdInfo 0x12
5591 return GetFileInformationByHandleEx(h, FileIdInfo,
id,
sizeof(*
id));
5596stati128_handle(HANDLE h,
struct stati128 *st)
5598 BY_HANDLE_FILE_INFORMATION info;
5599 DWORD attr = (DWORD)-1;
5601 if (GetFileInformationByHandle(h, &info)) {
5603 st->st_size = ((__int64)info.nFileSizeHigh << 32) | info.nFileSizeLow;
5604 st->st_atime = filetime_to_unixtime(&info.ftLastAccessTime);
5605 st->st_atimensec = filetime_to_nsec(&info.ftLastAccessTime);
5606 st->st_mtime = filetime_to_unixtime(&info.ftLastWriteTime);
5607 st->st_mtimensec = filetime_to_nsec(&info.ftLastWriteTime);
5608 st->st_ctime = filetime_to_unixtime(&info.ftCreationTime);
5609 st->st_ctimensec = filetime_to_nsec(&info.ftCreationTime);
5610 st->st_nlink = info.nNumberOfLinks;
5611 attr = info.dwFileAttributes;
5612 if (get_ino(h, &fii)) {
5613 st->st_ino = *((
unsigned __int64 *)&fii.FileId);
5614 st->st_inohigh = *((__int64 *)&fii.FileId + 1);
5617 st->st_ino = ((__int64)info.nFileIndexHigh << 32) | info.nFileIndexLow;
5626filetime_to_unixtime(
const FILETIME *ft)
5629 time_t t = filetime_split(ft, &subsec);
5631 if (t < 0)
return 0;
5637filetime_to_nsec(
const FILETIME *ft)
5640 tmp.LowPart = ft->dwLowDateTime;
5641 tmp.HighPart = ft->dwHighDateTime;
5642 return (
long)(tmp.QuadPart % 10000000) * 100;
5647fileattr_to_unixmode(DWORD attr,
const WCHAR *path,
unsigned mode)
5649 if (attr & FILE_ATTRIBUTE_READONLY) {
5653 mode |= S_IREAD | S_IWRITE | S_IWUSR;
5656 if (mode & S_IFMT) {
5659 else if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
5663 else if (attr & FILE_ATTRIBUTE_DIRECTORY) {
5664 mode |= S_IFDIR | S_IEXEC;
5670 if (path && (mode & S_IFREG)) {
5671 const WCHAR *end = path + lstrlenW(path);
5672 while (path < end) {
5673 end = CharPrevW(path, end);
5675 if ((_wcsicmp(end, L
".bat") == 0) ||
5676 (_wcsicmp(end, L
".cmd") == 0) ||
5677 (_wcsicmp(end, L
".com") == 0) ||
5678 (_wcsicmp(end, L
".exe") == 0)) {
5683 if (!iswalnum(*end))
break;
5687 mode |= (mode & 0500) >> 3;
5688 mode |= (mode & 0500) >> 6;
5695check_valid_dir(
const WCHAR *path)
5697 WIN32_FIND_DATAW fd;
5699 WCHAR full[PATH_MAX];
5705 if (!(p = wcsstr(path, L
"...")))
5707 q = p + wcsspn(p, L
".");
5708 if ((p == path || wcschr(L
":/\\", *(p - 1))) &&
5709 (!*q || wcschr(L
":/\\", *q))) {
5716 if (!GetFullPathNameW(path,
sizeof(full) /
sizeof(WCHAR), full, &dmy)) {
5717 errno = map_errno(GetLastError());
5720 if (full[1] == L
':' && !full[3] && GetDriveTypeW(full) != DRIVE_NO_ROOT_DIR)
5723 fh = open_dir_handle(path, &fd);
5724 if (fh == INVALID_HANDLE_VALUE)
5732stat_by_find(
const WCHAR *path,
struct stati128 *st)
5735 WIN32_FIND_DATAW wfd;
5738 h = FindFirstFileW(path, &wfd);
5739 if (h == INVALID_HANDLE_VALUE) {
5740 errno = map_errno(GetLastError());
5744 st->st_mode = fileattr_to_unixmode(wfd.dwFileAttributes, path, 0);
5745 st->st_atime = filetime_to_unixtime(&wfd.ftLastAccessTime);
5746 st->st_atimensec = filetime_to_nsec(&wfd.ftLastAccessTime);
5747 st->st_mtime = filetime_to_unixtime(&wfd.ftLastWriteTime);
5748 st->st_mtimensec = filetime_to_nsec(&wfd.ftLastWriteTime);
5749 st->st_ctime = filetime_to_unixtime(&wfd.ftCreationTime);
5750 st->st_ctimensec = filetime_to_nsec(&wfd.ftCreationTime);
5751 st->st_size = ((__int64)wfd.nFileSizeHigh << 32) | wfd.nFileSizeLow;
5758path_drive(
const WCHAR *path)
5760 return (iswalpha(path[0]) && path[1] == L
':') ?
5761 towupper(path[0]) - L
'A' : _getdrive() - 1;
5766winnt_stat(
const WCHAR *path,
struct stati128 *st, BOOL lstat)
5768 DWORD flags = lstat ? FILE_FLAG_OPEN_REPARSE_POINT : 0;
5770 WCHAR finalname[PATH_MAX];
5773 memset(st, 0,
sizeof(*st));
5774 f = open_special(path, 0, flags);
5775 open_error = GetLastError();
5776 if (f == INVALID_HANDLE_VALUE && !lstat) {
5778 FILE_ATTRIBUTE_TAG_INFO attr_info;
5781 f = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5782 e = GetFileInformationByHandleEx(f, FileAttributeTagInfo,
5783 &attr_info,
sizeof(attr_info));
5784 if (!e || attr_info.ReparseTag != IO_REPARSE_TAG_AF_UNIX) {
5786 f = INVALID_HANDLE_VALUE;
5789 if (f != INVALID_HANDLE_VALUE) {
5790 DWORD attr = stati128_handle(f, st);
5791 const DWORD
len = GetFinalPathNameByHandleW(f, finalname, numberof(finalname), 0);
5793 switch (GetFileType(f)) {
5794 case FILE_TYPE_CHAR:
5797 case FILE_TYPE_PIPE:
5801 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
5802 FILE_ATTRIBUTE_TAG_INFO attr_info;
5805 e = GetFileInformationByHandleEx(f, FileAttributeTagInfo,
5806 &attr_info,
sizeof(attr_info));
5807 if (e && attr_info.ReparseTag == IO_REPARSE_TAG_AF_UNIX) {
5811 else if (rb_w32_reparse_symlink_p(path)) {
5814 mode |= S_IFLNK | S_IEXEC;
5817 mode |= S_IFDIR | S_IEXEC;
5822 if (attr & FILE_ATTRIBUTE_DIRECTORY) {
5823 if (check_valid_dir(path))
return -1;
5825 st->st_mode = fileattr_to_unixmode(attr, path, mode);
5827 finalname[min(
len, numberof(finalname)-1)] = L
'\0';
5829 if (wcsncmp(path, namespace_prefix, numberof(namespace_prefix)) == 0)
5830 path += numberof(namespace_prefix);
5834 if ((open_error == ERROR_FILE_NOT_FOUND) || (open_error == ERROR_INVALID_NAME)
5835 || (open_error == ERROR_PATH_NOT_FOUND || (open_error == ERROR_BAD_NETPATH))) {
5836 errno = map_errno(open_error);
5840 if (stat_by_find(path, st))
return -1;
5843 st->st_dev = st->st_rdev = path_drive(path);
5850rb_w32_stat(
const char *path,
struct stat *st)
5854 if (w32_stati128(path, &tmp, filecp(), FALSE))
return -1;
5855 COPY_STAT(tmp, *st, (_off_t));
5861wstati128(
const WCHAR *path,
struct stati128 *st, BOOL lstat)
5871 size = lstrlenW(path) + 2;
5873 if (!(path = name_for_stat(buf1, path)))
5875 ret = winnt_stat(path, st, lstat);
5884name_for_stat(WCHAR *buf1,
const WCHAR *path)
5890 for (p = path, s = buf1; *p; p++, s++) {
5898 if (!
len || L
'\"' == *(--s)) {
5902 end = buf1 +
len - 1;
5904 if (isUNCRoot(buf1)) {
5907 else if (*end != L
'\\')
5908 lstrcatW(buf1, L
"\\");
5910 else if (*end == L
'\\' || (buf1 + 1 == end && *end == L
':'))
5911 lstrcatW(buf1, L
".");
5918rb_w32_ustati128(
const char *path,
struct stati128 *st)
5920 return w32_stati128(path, st, CP_UTF8, FALSE);
5925rb_w32_stati128(
const char *path,
struct stati128 *st)
5927 return w32_stati128(path, st, filecp(), FALSE);
5932w32_stati128(
const char *path,
struct stati128 *st, UINT cp, BOOL lstat)
5937 if (!(wpath = mbstr_to_wstr(cp, path, -1, NULL)))
5939 ret = wstati128(wpath, st, lstat);
5946rb_w32_ulstati128(
const char *path,
struct stati128 *st)
5948 return w32_stati128(path, st, CP_UTF8, TRUE);
5953rb_w32_lstati128(
const char *path,
struct stati128 *st)
5955 return w32_stati128(path, st, filecp(), TRUE);
5960rb_w32_lseek(
int fd, rb_off_t ofs,
int whence)
5962 SOCKET sock = TO_SOCKET(fd);
5963 if (is_socket(sock) || is_pipe(sock)) {
5967 return _lseeki64(fd, ofs, whence);
5972w32_access(
const char *path,
int mode, UINT cp)
5975 if (w32_stati128(path, &stat, cp, FALSE) != 0)
5978 if ((stat.st_mode & mode) != mode) {
5987rb_w32_access(
const char *path,
int mode)
5989 return w32_access(path, mode, filecp());
5994rb_w32_uaccess(
const char *path,
int mode)
5996 return w32_access(path, mode, CP_UTF8);
6001rb_chsize(HANDLE h, rb_off_t size)
6003 long upos, lpos, usize, lsize;
6007 if ((lpos = SetFilePointer(h, 0, (upos = 0, &upos), SEEK_CUR)) == -1L &&
6008 (e = GetLastError())) {
6009 errno = map_errno(e);
6012 usize = (long)(size >> 32);
6014 if (SetFilePointer(h, lsize, &usize, SEEK_SET) == (DWORD)-1L &&
6015 (e = GetLastError())) {
6016 errno = map_errno(e);
6018 else if (!SetEndOfFile(h)) {
6019 errno = map_errno(GetLastError());
6024 SetFilePointer(h, lpos, &upos, SEEK_SET);
6030w32_truncate(
const char *path, rb_off_t length, UINT cp)
6036 if (!(wpath = mbstr_to_wstr(cp, path, -1, NULL)))
6038 h = CreateFileW(wpath, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
6039 if (h == INVALID_HANDLE_VALUE) {
6040 errno = map_errno(GetLastError());
6045 ret = rb_chsize(h, length);
6052rb_w32_utruncate(
const char *path, rb_off_t length)
6054 return w32_truncate(path, length, CP_UTF8);
6059rb_w32_truncate(
const char *path, rb_off_t length)
6061 return w32_truncate(path, length, filecp());
6066rb_w32_ftruncate(
int fd, rb_off_t length)
6070 h = (HANDLE)_get_osfhandle(fd);
6071 if (h == (HANDLE)-1)
return -1;
6072 return rb_chsize(h, length);
6077filetime_to_clock(FILETIME *ft)
6079 __int64 qw = ft->dwHighDateTime;
6081 qw |= ft->dwLowDateTime;
6088rb_w32_times(
struct tms *tmbuf)
6090 FILETIME create, exit, kernel, user;
6092 if (GetProcessTimes(GetCurrentProcess(),&create, &exit, &kernel, &user)) {
6093 tmbuf->tms_utime = filetime_to_clock(&user);
6094 tmbuf->tms_stime = filetime_to_clock(&kernel);
6095 tmbuf->tms_cutime = 0;
6096 tmbuf->tms_cstime = 0;
6099 tmbuf->tms_utime = clock();
6100 tmbuf->tms_stime = 0;
6101 tmbuf->tms_cutime = 0;
6102 tmbuf->tms_cstime = 0;
6109#define yield_once() Sleep(0)
6110#define yield_until(condition) do yield_once(); while (!(condition))
6119 uintptr_t (*func)(uintptr_t self,
int argc, uintptr_t* argv);
6127call_asynchronous(PVOID argp)
6131 arg->stackaddr = &argp;
6132 ret = (DWORD)arg->func(arg->self, arg->argc, arg->argv);
6133 arg->errnum =
errno;
6139rb_w32_asynchronize(asynchronous_func_t func, uintptr_t self,
6140 int argc, uintptr_t* argv, uintptr_t intrval)
6143 BOOL interrupted = FALSE;
6149 arg.stackaddr = NULL;
6156 thr = CreateThread(NULL, 0, call_asynchronous, &arg, 0, &val);
6159 yield_until(arg.stackaddr);
6161 if (rb_w32_wait_events_blocking(&thr, 1, INFINITE) != WAIT_OBJECT_0) {
6164 if (TerminateThread(thr, intrval)) {
6169 GetExitCodeThread(thr, &val);
6174 MEMORY_BASIC_INFORMATION m;
6176 memset(&m, 0,
sizeof(m));
6177 if (!VirtualQuery(arg.stackaddr, &m,
sizeof(m))) {
6178 Debug(fprintf(stderr,
"couldn't get stack base:%p:%d\n",
6179 arg.stackaddr, GetLastError()));
6181 else if (!VirtualFree(m.AllocationBase, 0, MEM_RELEASE)) {
6182 Debug(fprintf(stderr,
"couldn't release stack:%p:%d\n",
6183 m.AllocationBase, GetLastError()));
6194 rb_fatal(
"failed to launch waiter thread:%ld", GetLastError());
6202rb_w32_get_environ(
void)
6204 WCHAR *envtop, *env;
6205 char **myenvtop, **myenv;
6218 envtop = GetEnvironmentStringsW();
6219 for (env = envtop, num = 0; *env; env += lstrlenW(env) + 1)
6220 if (*env !=
'=') num++;
6222 myenvtop = (
char **)malloc(
sizeof(
char *) * (num + 1));
6223 for (env = envtop, myenv = myenvtop; *env; env += lstrlenW(env) + 1) {
6225 if (!(*myenv = wstr_to_utf8(env, NULL))) {
6232 FreeEnvironmentStringsW(envtop);
6239rb_w32_free_environ(
char **env)
6243 while (*t) free(*t++);
6251 return GetCurrentProcessId();
6259 typedef long (WINAPI query_func)(HANDLE, int,
void *, ULONG, ULONG *);
6260 static query_func *pNtQueryInformationProcess = (query_func *)-1;
6263 if (pNtQueryInformationProcess == (query_func *)-1)
6264 pNtQueryInformationProcess = (query_func *)get_proc_address(
"ntdll.dll",
"NtQueryInformationProcess", NULL);
6265 if (pNtQueryInformationProcess) {
6268 void* PebBaseAddress;
6269 uintptr_t AffinityMask;
6270 uintptr_t BasePriority;
6271 uintptr_t UniqueProcessId;
6272 uintptr_t ParentProcessId;
6275 long ret = pNtQueryInformationProcess(GetCurrentProcess(), 0, &pbi,
sizeof(pbi), &
len);
6277 ppid = pbi.ParentProcessId;
6284STATIC_ASSERT(std_handle, (STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)==(STD_ERROR_HANDLE-STD_OUTPUT_HANDLE));
6287#define set_new_std_handle(newfd, handle) do { \
6288 if ((unsigned)(newfd) > 2) break; \
6289 SetStdHandle(STD_INPUT_HANDLE+(STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)*(newfd), \
6292#define set_new_std_fd(newfd) set_new_std_handle(newfd, (HANDLE)rb_w32_get_osfhandle(newfd))
6296rb_w32_dup2(
int oldfd,
int newfd)
6300 if (oldfd == newfd)
return newfd;
6301 ret = dup2(oldfd, newfd);
6302 if (ret < 0)
return ret;
6303 set_new_std_fd(newfd);
6309rb_w32_uopen(
const char *file,
int oflag, ...)
6316 va_start(arg, oflag);
6317 pmode = va_arg(arg,
int);
6320 if (!(wfile = utf8_to_wstr(file, NULL)))
6322 ret = w32_wopen(wfile, oflag, pmode);
6329check_if_wdir(
const WCHAR *wfile)
6331 DWORD attr = GetFileAttributesW(wfile);
6332 if (attr == (DWORD)-1L ||
6333 !(attr & FILE_ATTRIBUTE_DIRECTORY) ||
6334 check_valid_dir(wfile)) {
6343rb_w32_open(
const char *file,
int oflag, ...)
6350 va_start(arg, oflag);
6351 pmode = va_arg(arg,
int);
6354 if (!(wfile = filecp_to_wstr(file, NULL)))
6356 ret = w32_wopen(wfile, oflag, pmode);
6363rb_w32_wopen(
const WCHAR *file,
int oflag, ...)
6367 if (oflag & O_CREAT) {
6369 va_start(arg, oflag);
6370 pmode = va_arg(arg,
int);
6374 return w32_wopen(file, oflag, pmode);
6378w32_wopen(
const WCHAR *file,
int oflag,
int pmode)
6384 DWORD attr = FILE_ATTRIBUTE_NORMAL;
6385 SECURITY_ATTRIBUTES sec;
6389 share_delete = oflag & O_SHARE_DELETE ? FILE_SHARE_DELETE : 0;
6390 oflag &= ~O_SHARE_DELETE;
6391 if ((oflag & O_TEXT) || !(oflag & O_BINARY)) {
6392 fd = _wopen(file, oflag, pmode);
6396 check_if_wdir(file);
6399 errno = map_errno(GetLastError());
6406 sec.nLength =
sizeof(sec);
6407 sec.lpSecurityDescriptor = NULL;
6408 if (oflag & O_NOINHERIT) {
6409 sec.bInheritHandle = FALSE;
6410 flags |= FNOINHERIT;
6413 sec.bInheritHandle = TRUE;
6415 oflag &= ~O_NOINHERIT;
6418 oflag &= ~(O_BINARY | O_TEXT);
6420 switch (oflag & (O_RDWR | O_RDONLY | O_WRONLY)) {
6422 access = GENERIC_READ | GENERIC_WRITE;
6425 access = GENERIC_READ;
6428 access = GENERIC_WRITE;
6434 oflag &= ~(O_RDWR | O_RDONLY | O_WRONLY);
6436 switch (oflag & (O_CREAT | O_EXCL | O_TRUNC)) {
6438 create = OPEN_ALWAYS;
6442 create = OPEN_EXISTING;
6444 case O_CREAT | O_EXCL:
6445 case O_CREAT | O_EXCL | O_TRUNC:
6446 create = CREATE_NEW;
6449 case O_TRUNC | O_EXCL:
6450 create = TRUNCATE_EXISTING;
6452 case O_CREAT | O_TRUNC:
6453 create = CREATE_ALWAYS;
6459 if (oflag & O_CREAT) {
6461 if (!(pmode & S_IWRITE))
6462 attr = FILE_ATTRIBUTE_READONLY;
6464 oflag &= ~(O_CREAT | O_EXCL | O_TRUNC);
6466 if (oflag & O_TEMPORARY) {
6467 attr |= FILE_FLAG_DELETE_ON_CLOSE;
6470 oflag &= ~O_TEMPORARY;
6472 if (oflag & _O_SHORT_LIVED)
6473 attr |= FILE_ATTRIBUTE_TEMPORARY;
6474 oflag &= ~_O_SHORT_LIVED;
6476 switch (oflag & (O_SEQUENTIAL | O_RANDOM)) {
6480 attr |= FILE_FLAG_SEQUENTIAL_SCAN;
6483 attr |= FILE_FLAG_RANDOM_ACCESS;
6489 oflag &= ~(O_SEQUENTIAL | O_RANDOM);
6491 if (oflag & ~O_APPEND) {
6498 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6499 fd = _open_osfhandle((intptr_t)h, 0);
6507 rb_acrt_lowio_lock_fh(fd);
6508 _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE);
6509 _set_osflags(fd, 0);
6511 h = CreateFileW(file, access, FILE_SHARE_READ | FILE_SHARE_WRITE | share_delete, &sec, create, attr, NULL);
6512 if (h == INVALID_HANDLE_VALUE) {
6513 DWORD e = GetLastError();
6514 if (e != ERROR_ACCESS_DENIED || !check_if_wdir(file))
6515 errno = map_errno(e);
6516 rb_acrt_lowio_unlock_fh(fd);
6521 switch (GetFileType(h)) {
6522 case FILE_TYPE_CHAR:
6525 case FILE_TYPE_PIPE:
6528 case FILE_TYPE_UNKNOWN:
6529 errno = map_errno(GetLastError());
6531 rb_acrt_lowio_unlock_fh(fd);
6535 if (!(flags & (FDEV | FPIPE)) && (oflag & O_APPEND))
6538 _set_osfhnd(fd, (intptr_t)h);
6539 _set_osflags(fd, flags | FOPEN);
6541 rb_acrt_lowio_unlock_fh(fd);
6551rb_w32_fclose(
FILE *fp)
6553 int fd = fileno(fp);
6554 SOCKET sock = TO_SOCKET(fd);
6555 int save_errno =
errno;
6557 if (fflush(fp))
return -1;
6558 if (!is_socket(sock)) {
6559 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
6562 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
6565 if (closesocket(sock) == SOCKET_ERROR) {
6566 errno = map_errno(WSAGetLastError());
6574rb_w32_pipe(
int fds[2])
6576 static long serial = 0;
6577 static const char prefix[] =
"\\\\.\\pipe\\ruby";
6579 width_of_prefix = (int)
sizeof(prefix) - 1,
6580 width_of_pid = (int)
sizeof(rb_pid_t) * 2,
6581 width_of_serial = (int)
sizeof(serial) * 2,
6582 width_of_ids = width_of_pid + 1 + width_of_serial + 1
6584 char name[
sizeof(prefix) + width_of_ids];
6585 SECURITY_ATTRIBUTES sec;
6586 HANDLE hRead, hWrite, h;
6587 int fdRead, fdWrite;
6590 memcpy(name, prefix, width_of_prefix);
6591 snprintf(name + width_of_prefix, width_of_ids,
"%.*"PRI_PIDT_PREFIX"x-%.*lx",
6592 width_of_pid, rb_w32_getpid(), width_of_serial, InterlockedIncrement(&serial)-1);
6594 sec.nLength =
sizeof(sec);
6595 sec.lpSecurityDescriptor = NULL;
6596 sec.bInheritHandle = FALSE;
6599 hRead = CreateNamedPipe(name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
6600 0, 2, 65536, 65536, 0, &sec);
6602 if (hRead == INVALID_HANDLE_VALUE) {
6603 DWORD err = GetLastError();
6604 if (err == ERROR_PIPE_BUSY)
6607 errno = map_errno(GetLastError());
6612 hWrite = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, &sec,
6613 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
6615 if (hWrite == INVALID_HANDLE_VALUE) {
6616 errno = map_errno(GetLastError());
6623 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6624 fdRead = _open_osfhandle((intptr_t)h, 0);
6628 CloseHandle(hWrite);
6634 rb_acrt_lowio_lock_fh(fdRead);
6635 _set_osfhnd(fdRead, (intptr_t)hRead);
6636 _set_osflags(fdRead, FOPEN | FPIPE | FNOINHERIT);
6637 rb_acrt_lowio_unlock_fh(fdRead);
6643 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6644 fdWrite = _open_osfhandle((intptr_t)h, 0);
6646 if (fdWrite == -1) {
6648 CloseHandle(hWrite);
6652 rb_acrt_lowio_lock_fh(fdWrite);
6653 _set_osfhnd(fdWrite, (intptr_t)hWrite);
6654 _set_osflags(fdWrite, FOPEN | FPIPE | FNOINHERIT);
6655 rb_acrt_lowio_unlock_fh(fdWrite);
6658 rb_w32_close(fdRead);
6670console_emulator_p(
void)
6675 const void *
const func = WriteConsoleW;
6677 MEMORY_BASIC_INFORMATION m;
6679 memset(&m, 0,
sizeof(m));
6680 if (!VirtualQuery(func, &m,
sizeof(m))) {
6683 k = GetModuleHandle(
"kernel32.dll");
6684 if (!k)
return FALSE;
6685 return (HMODULE)m.AllocationBase != k;
6691constat_handle(HANDLE h)
6695 thread_exclusive(conlist) {
6697 if (console_emulator_p()) {
6698 conlist = conlist_disabled;
6701 conlist = st_init_numtable();
6702 install_vm_exit_handler();
6704 else if (conlist == conlist_disabled) {
6707 if (st_lookup(conlist, (st_data_t)h, &data)) {
6711 CONSOLE_SCREEN_BUFFER_INFO csbi;
6713 p->vt100.state = constat_init;
6714 p->vt100.attr = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
6715 p->vt100.reverse = 0;
6716 p->vt100.saved.X = p->vt100.saved.Y = 0;
6717 if (GetConsoleScreenBufferInfo(h, &csbi)) {
6718 p->vt100.attr = csbi.wAttributes;
6720 st_insert(conlist, (st_data_t)h, (st_data_t)p);
6728constat_reset(HANDLE h)
6732 thread_exclusive(conlist) {
6733 if (!conlist || conlist == conlist_disabled)
continue;
6734 if (!st_lookup(conlist, (st_data_t)h, &data))
continue;
6736 p->vt100.state = constat_init;
6740#define FOREGROUND_MASK (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY)
6741#define BACKGROUND_MASK (BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY)
6743#define constat_attr_color_reverse(attr) \
6744 ((attr) & ~(FOREGROUND_MASK | BACKGROUND_MASK)) | \
6745 (((attr) & FOREGROUND_MASK) << 4) | \
6746 (((attr) & BACKGROUND_MASK) >> 4)
6750constat_attr(
int count,
const int *seq, WORD attr, WORD default_attr,
int *reverse)
6755 if (!count)
return attr;
6756 if (rev) attr = constat_attr_color_reverse(attr);
6757 bold = attr & FOREGROUND_INTENSITY;
6758 attr &= ~(FOREGROUND_INTENSITY | BACKGROUND_INTENSITY);
6760 while (count-- > 0) {
6763 attr = default_attr;
6768 bold = FOREGROUND_INTENSITY;
6771#ifndef COMMON_LVB_UNDERSCORE
6772#define COMMON_LVB_UNDERSCORE 0x8000
6774 attr |= COMMON_LVB_UNDERSCORE;
6781 attr &= ~(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
6785 attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_GREEN)) | FOREGROUND_RED;
6789 attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_RED)) | FOREGROUND_GREEN;
6793 attr = (attr & ~FOREGROUND_BLUE) | FOREGROUND_GREEN | FOREGROUND_RED;
6797 attr = (attr & ~(FOREGROUND_GREEN | FOREGROUND_RED)) | FOREGROUND_BLUE;
6801 attr = (attr & ~FOREGROUND_GREEN) | FOREGROUND_BLUE | FOREGROUND_RED;
6805 attr = (attr & ~FOREGROUND_RED) | FOREGROUND_BLUE | FOREGROUND_GREEN;
6809 attr |= FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
6813 attr &= ~(BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED);
6816 attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_GREEN)) | BACKGROUND_RED;
6819 attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_RED)) | BACKGROUND_GREEN;
6822 attr = (attr & ~BACKGROUND_BLUE) | BACKGROUND_GREEN | BACKGROUND_RED;
6825 attr = (attr & ~(BACKGROUND_GREEN | BACKGROUND_RED)) | BACKGROUND_BLUE;
6828 attr = (attr & ~BACKGROUND_GREEN) | BACKGROUND_BLUE | BACKGROUND_RED;
6831 attr = (attr & ~BACKGROUND_RED) | BACKGROUND_BLUE | BACKGROUND_GREEN;
6834 attr |= BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED;
6839 if (rev) attr = constat_attr_color_reverse(attr);
6846constat_clear(HANDLE handle, WORD attr, DWORD
len, COORD pos)
6850 FillConsoleOutputAttribute(handle, attr,
len, pos, &written);
6851 FillConsoleOutputCharacterW(handle, L
' ',
len, pos, &written);
6856constat_apply(HANDLE handle,
struct constat *s, WCHAR w)
6858 CONSOLE_SCREEN_BUFFER_INFO csbi;
6859 const int *seq = s->vt100.seq;
6860 int count = s->vt100.state;
6864 if (!GetConsoleScreenBufferInfo(handle, &csbi))
return;
6865 arg0 = (count > 0 && seq[0] > 0);
6866 if (arg0) arg1 = seq[0];
6869 SetConsoleTextAttribute(handle, constat_attr(count, seq, csbi.wAttributes, s->vt100.attr, &s->vt100.reverse));
6872 csbi.dwCursorPosition.X = 0;
6874 csbi.dwCursorPosition.Y -= arg1;
6875 if (csbi.dwCursorPosition.Y < csbi.srWindow.Top)
6876 csbi.dwCursorPosition.Y = csbi.srWindow.Top;
6877 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6880 csbi.dwCursorPosition.X = 0;
6883 csbi.dwCursorPosition.Y += arg1;
6884 if (csbi.dwCursorPosition.Y > csbi.srWindow.Bottom)
6885 csbi.dwCursorPosition.Y = csbi.srWindow.Bottom;
6886 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6889 csbi.dwCursorPosition.X += arg1;
6890 if (csbi.dwCursorPosition.X >= csbi.srWindow.Right)
6891 csbi.dwCursorPosition.X = csbi.srWindow.Right;
6892 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6895 csbi.dwCursorPosition.X -= arg1;
6896 if (csbi.dwCursorPosition.X < csbi.srWindow.Left)
6897 csbi.dwCursorPosition.X = csbi.srWindow.Left;
6898 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6902 arg1 += csbi.srWindow.Left;
6903 if (arg1 > csbi.srWindow.Right)
6904 arg1 = csbi.srWindow.Right;
6905 csbi.dwCursorPosition.X = arg1;
6906 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6909 arg1 += csbi.srWindow.Top;
6910 if (arg1 > csbi.srWindow.Bottom)
6911 arg1 = csbi.srWindow.Bottom;
6912 csbi.dwCursorPosition.Y = arg1;
6913 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6917 pos.Y = arg1 + csbi.srWindow.Top - 1;
6918 if (pos.Y > csbi.srWindow.Bottom) pos.Y = csbi.srWindow.Bottom;
6919 if (count < 2 || (arg1 = seq[1]) <= 0) arg1 = 1;
6920 pos.X = arg1 + csbi.srWindow.Left - 1;
6921 if (pos.X > csbi.srWindow.Right) pos.X = csbi.srWindow.Right;
6922 SetConsoleCursorPosition(handle, pos);
6925 switch (arg0 ? arg1 : 0) {
6927 constat_clear(handle, csbi.wAttributes,
6928 (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.dwCursorPosition.Y + 1)
6929 - csbi.dwCursorPosition.X),
6930 csbi.dwCursorPosition);
6934 pos.Y = csbi.srWindow.Top;
6935 constat_clear(handle, csbi.wAttributes,
6936 (csbi.dwSize.X * (csbi.dwCursorPosition.Y - csbi.srWindow.Top)
6937 + csbi.dwCursorPosition.X + 1),
6942 pos.Y = csbi.srWindow.Top;
6943 constat_clear(handle, csbi.wAttributes,
6944 (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1)),
6950 constat_clear(handle, csbi.wAttributes,
6951 (csbi.dwSize.X * csbi.dwSize.Y),
6957 switch (arg0 ? arg1 : 0) {
6959 constat_clear(handle, csbi.wAttributes,
6960 (csbi.dwSize.X - csbi.dwCursorPosition.X),
6961 csbi.dwCursorPosition);
6965 pos.Y = csbi.dwCursorPosition.Y;
6966 constat_clear(handle, csbi.wAttributes,
6967 csbi.dwCursorPosition.X + 1, pos);
6971 pos.Y = csbi.dwCursorPosition.Y;
6972 constat_clear(handle, csbi.wAttributes,
6973 csbi.dwSize.X, pos);
6978 s->vt100.saved = csbi.dwCursorPosition;
6981 SetConsoleCursorPosition(handle, s->vt100.saved);
6984 if (count >= 2 && seq[0] == -1 && seq[1] == 25) {
6985 CONSOLE_CURSOR_INFO cci;
6986 GetConsoleCursorInfo(handle, &cci);
6987 cci.bVisible = TRUE;
6988 SetConsoleCursorInfo(handle, &cci);
6992 if (count >= 2 && seq[0] == -1 && seq[1] == 25) {
6993 CONSOLE_CURSOR_INFO cci;
6994 GetConsoleCursorInfo(handle, &cci);
6995 cci.bVisible = FALSE;
6996 SetConsoleCursorInfo(handle, &cci);
7004static const long MAXSIZE_CONSOLE_WRITING = 31366;
7008constat_parse(HANDLE h,
struct constat *s,
const WCHAR **ptrp,
long *lenp)
7010 const WCHAR *ptr = *ptrp;
7011 long rest,
len = *lenp;
7015 rest = *lenp -
len - 1;
7016 if (s->vt100.state == constat_esc) {
7019 s->vt100.state = constat_init;
7020 if (
len > 0 && *ptr != L
'[')
continue;
7021 s->vt100.state = constat_esc;
7023 else if (s->vt100.state == constat_esc) {
7026 s->vt100.state = constat_init;
7029 rest = *lenp -
len - 1;
7030 if (rest > 0) --rest;
7031 s->vt100.state = constat_seq;
7032 s->vt100.seq[0] = 0;
7034 else if (s->vt100.state >= constat_seq) {
7035 if (wc >= L
'0' && wc <= L
'9') {
7036 if (s->vt100.state < (
int)numberof(s->vt100.seq)) {
7037 int *seq = &s->vt100.seq[s->vt100.state];
7038 *seq = (*seq * 10) + (wc - L
'0');
7041 else if (s->vt100.state == constat_seq && s->vt100.seq[0] == 0 && wc == L
'?') {
7042 s->vt100.seq[s->vt100.state++] = -1;
7046 if (++s->vt100.state < (
int)numberof(s->vt100.seq)) {
7047 s->vt100.seq[s->vt100.state] = 0;
7050 s->vt100.state = (int)numberof(s->vt100.seq);
7054 constat_apply(h, s, wc);
7055 s->vt100.state = constat_init;
7060 else if ((rest = *lenp -
len) < MAXSIZE_CONSOLE_WRITING) {
7078 SOCKET sock = TO_SOCKET(fd);
7079 int save_errno =
errno;
7081 if (!is_socket(sock)) {
7082 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
7083 constat_delete((HANDLE)sock);
7086 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
7087 socklist_delete(&sock, NULL);
7090 if (closesocket(sock) == SOCKET_ERROR) {
7091 errno = map_errno(WSAGetLastError());
7097#ifndef INVALID_SET_FILE_POINTER
7098#define INVALID_SET_FILE_POINTER ((DWORD)-1)
7102setup_overlapped(OVERLAPPED *ol,
int fd,
int iswrite, rb_off_t *_offset)
7104 memset(ol, 0,
sizeof(*ol));
7109 DWORD seek_method = ((_osfile(fd) & FAPPEND) && iswrite) ? FILE_END : FILE_CURRENT;
7113 uint64_t offset = *_offset;
7114 ol->Offset = (uint32_t)(offset & 0xFFFFFFFFLL);
7115 ol->OffsetHigh = (uint32_t)((offset & 0xFFFFFFFF00000000LL) >> 32);
7118 LARGE_INTEGER seek_offset = {0}, current_offset = {0};
7119 if (!SetFilePointerEx((HANDLE)_osfhnd(fd), seek_offset, ¤t_offset, seek_method)) {
7120 DWORD last_error = GetLastError();
7121 if (last_error != NO_ERROR) {
7122 errno = map_errno(last_error);
7128 *_offset = current_offset.QuadPart;
7130 else if (!(_osfile(fd) & (FDEV | FPIPE))) {
7132 DWORD low = SetFilePointer((HANDLE)_osfhnd(fd), 0, &high, seek_method);
7134 if (low == INVALID_SET_FILE_POINTER) {
7135 DWORD err = GetLastError();
7136 if (err != NO_ERROR) {
7137 errno = map_errno(err);
7143 ol->OffsetHigh = high;
7146 ol->hEvent = CreateEvent(NULL, TRUE, TRUE, NULL);
7148 errno = map_errno(GetLastError());
7155finish_overlapped(OVERLAPPED *ol,
int fd, DWORD size, rb_off_t *_offset)
7157 CloseHandle(ol->hEvent);
7161 DWORD seek_method = (_osfile(fd) & FAPPEND) ? FILE_END : FILE_BEGIN;
7163 LARGE_INTEGER seek_offset = {0};
7164 if (seek_method == FILE_BEGIN) {
7165 seek_offset.QuadPart = *_offset;
7168 SetFilePointerEx((HANDLE)_osfhnd(fd), seek_offset, NULL, seek_method);
7170 else if (!(_osfile(fd) & (FDEV | FPIPE))) {
7171 LONG high = ol->OffsetHigh;
7172 DWORD low = ol->Offset + size;
7173 if (low < ol->Offset)
7175 SetFilePointer((HANDLE)_osfhnd(fd), low, &high, FILE_BEGIN);
7182rb_w32_read_internal(
int fd,
void *buf,
size_t size, rb_off_t *offset)
7184 SOCKET sock = TO_SOCKET(fd);
7192 BOOL islineinput = FALSE;
7195 if (is_socket(sock))
7196 return rb_w32_recv(fd, buf, size, 0);
7199 if (_get_osfhandle(fd) == -1) {
7203 if (!offset && _osfile(fd) & FTEXT) {
7204 return _read(fd, buf, size);
7207 rb_acrt_lowio_lock_fh(fd);
7209 if (!size || _osfile(fd) & FEOFLAG) {
7210 _set_osflags(fd, _osfile(fd) & ~FEOFLAG);
7211 rb_acrt_lowio_unlock_fh(fd);
7216 isconsole = is_console(_osfhnd(fd)) && (osver.dwMajorVersion < 6 || (osver.dwMajorVersion == 6 && osver.dwMinorVersion < 2));
7219 GetConsoleMode((HANDLE)_osfhnd(fd),&mode);
7220 islineinput = (mode & ENABLE_LINE_INPUT) != 0;
7225 constat_reset((HANDLE)_osfhnd(fd));
7237 if (setup_overlapped(&ol, fd, FALSE, offset)) {
7238 rb_acrt_lowio_unlock_fh(fd);
7242 if (!ReadFile((HANDLE)_osfhnd(fd), buf,
len, &read, &ol)) {
7243 err = GetLastError();
7244 if (err == ERROR_NO_DATA && (_osfile(fd) & FPIPE)) {
7246 if (GetNamedPipeHandleState((HANDLE)_osfhnd(fd), &state, NULL, NULL, NULL, NULL, 0) && (state & PIPE_NOWAIT)) {
7247 errno = EWOULDBLOCK;
7250 errno = map_errno(err);
7252 rb_acrt_lowio_unlock_fh(fd);
7255 else if (err != ERROR_IO_PENDING) {
7256 CloseHandle(ol.hEvent);
7257 if (err == ERROR_ACCESS_DENIED)
7259 else if (err == ERROR_BROKEN_PIPE || err == ERROR_HANDLE_EOF) {
7260 rb_acrt_lowio_unlock_fh(fd);
7264 errno = map_errno(err);
7266 rb_acrt_lowio_unlock_fh(fd);
7270 wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE);
7271 if (wait != WAIT_OBJECT_0) {
7272 if (wait == WAIT_OBJECT_0 + 1)
7275 errno = map_errno(GetLastError());
7276 CloseHandle(ol.hEvent);
7277 CancelIo((HANDLE)_osfhnd(fd));
7278 rb_acrt_lowio_unlock_fh(fd);
7282 if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &read, TRUE) &&
7283 (err = GetLastError()) != ERROR_HANDLE_EOF) {
7285 if (err != ERROR_BROKEN_PIPE) {
7286 errno = map_errno(err);
7289 CloseHandle(ol.hEvent);
7290 CancelIo((HANDLE)_osfhnd(fd));
7291 rb_acrt_lowio_unlock_fh(fd);
7296 err = GetLastError();
7297 errno = map_errno(err);
7300 finish_overlapped(&ol, fd, read, offset);
7304 buf = (
char *)buf + read;
7305 if (err != ERROR_OPERATION_ABORTED &&
7306 !(isconsole &&
len == 1 && (!islineinput || *((
char *)buf - 1) ==
'\n')) && size > 0)
7310 _set_osflags(fd, _osfile(fd) | FEOFLAG);
7313 rb_acrt_lowio_unlock_fh(fd);
7321rb_w32_write_internal(
int fd,
const void *buf,
size_t size, rb_off_t *offset)
7323 SOCKET sock = TO_SOCKET(fd);
7331 if (is_socket(sock))
7332 return rb_w32_send(fd, buf, size, 0);
7335 if (_get_osfhandle(fd) == -1) {
7340 if (!offset && (_osfile(fd) & FTEXT) &&
7341 (!(_osfile(fd) & FPIPE) || fd == fileno(stdout) || fd == fileno(stderr))) {
7342 ssize_t w = _write(fd, buf, size);
7343 if (w == (ssize_t)-1 &&
errno == EINVAL) {
7344 errno = map_errno(GetLastError());
7349 rb_acrt_lowio_lock_fh(fd);
7351 if (!size || _osfile(fd) & FEOFLAG) {
7352 rb_acrt_lowio_unlock_fh(fd);
7358 len = (_osfile(fd) & FDEV) ? min(MAXSIZE_CONSOLE_WRITING, size) : size;
7363 if (setup_overlapped(&ol, fd, TRUE, offset)) {
7364 rb_acrt_lowio_unlock_fh(fd);
7368 if (!WriteFile((HANDLE)_osfhnd(fd), buf,
len, &written, &ol)) {
7369 err = GetLastError();
7370 if (err != ERROR_IO_PENDING) {
7371 CloseHandle(ol.hEvent);
7372 if (err == ERROR_ACCESS_DENIED)
7375 errno = map_errno(err);
7377 rb_acrt_lowio_unlock_fh(fd);
7381 wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE);
7382 if (wait != WAIT_OBJECT_0) {
7383 if (wait == WAIT_OBJECT_0 + 1)
7386 errno = map_errno(GetLastError());
7387 CloseHandle(ol.hEvent);
7388 CancelIo((HANDLE)_osfhnd(fd));
7389 rb_acrt_lowio_unlock_fh(fd);
7393 if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &written, TRUE)) {
7394 errno = map_errno(GetLastError());
7395 CloseHandle(ol.hEvent);
7396 CancelIo((HANDLE)_osfhnd(fd));
7397 rb_acrt_lowio_unlock_fh(fd);
7402 finish_overlapped(&ol, fd, written, offset);
7405 if (written ==
len) {
7406 buf = (
const char *)buf +
len;
7411 size_t newlen =
len / 2;
7413 size +=
len - newlen;
7418 errno = EWOULDBLOCK;
7421 rb_acrt_lowio_unlock_fh(fd);
7427rb_w32_read(
int fd,
void *buf,
size_t size)
7429 return rb_w32_read_internal(fd, buf, size, NULL);
7433rb_w32_write(
int fd,
const void *buf,
size_t size)
7435 return rb_w32_write_internal(fd, buf, size, NULL);
7439rb_w32_pread(
int descriptor,
void *base,
size_t size, rb_off_t offset)
7441 return rb_w32_read_internal(descriptor, base, size, &offset);
7445rb_w32_pwrite(
int descriptor,
const void *base,
size_t size, rb_off_t offset)
7447 return rb_w32_write_internal(descriptor, base, size, &offset);
7452rb_w32_write_console(uintptr_t strarg,
int fd)
7455 DWORD dwMode, reslen;
7459 const WCHAR *ptr, *next;
7463 handle = (HANDLE)_osfhnd(fd);
7464 if (!GetConsoleMode(handle, &dwMode))
7467 s = constat_handle(handle);
7477 case ENCINDEX_US_ASCII:
7478 case ENCINDEX_ASCII_8BIT:
7480 case ENCINDEX_UTF_8:
7481 ptr = wbuffer = mbstr_to_wstr(CP_UTF8, RSTRING_PTR(str), RSTRING_LEN(str), &
len);
7482 if (!ptr)
return -1L;
7484 case ENCINDEX_UTF_16LE:
7485 ptr = (
const WCHAR *)RSTRING_PTR(str);
7486 len = RSTRING_LEN(str) /
sizeof(WCHAR);
7490 if (dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) {
7491 if (!WriteConsoleW(handle, ptr,
len, &reslen, NULL))
7492 reslen = (DWORD)-1L;
7496 long curlen = constat_parse(handle, s, (next = ptr, &next), &
len);
7497 reslen += next - ptr;
7500 if (!WriteConsoleW(handle, ptr, curlen, &written, NULL)) {
7501 reslen = (DWORD)-1L;
7510 return (
long)reslen;
7513#if RUBY_MSVCRT_VERSION < 80 && !defined(HAVE__GMTIME64_S)
7516unixtime_to_filetime(time_t time, FILETIME *ft)
7520 tmp.QuadPart = ((
LONG_LONG)time + (
LONG_LONG)((1970-1601)*365.2425) * 24 * 60 * 60) * 10 * 1000 * 1000;
7521 ft->dwLowDateTime = tmp.LowPart;
7522 ft->dwHighDateTime = tmp.HighPart;
7529timespec_to_filetime(
const struct timespec *ts, FILETIME *ft)
7533 tmp.QuadPart = ((
LONG_LONG)ts->tv_sec + (
LONG_LONG)((1970-1601)*365.2425) * 24 * 60 * 60) * 10 * 1000 * 1000;
7534 tmp.QuadPart += ts->tv_nsec / 100;
7535 ft->dwLowDateTime = tmp.LowPart;
7536 ft->dwHighDateTime = tmp.HighPart;
7542wutimensat(
int dirfd,
const WCHAR *path,
const struct timespec *times,
int flags)
7545 FILETIME atime, mtime;
7550 if (dirfd != AT_FDCWD) {
7560 if (wstati128(path, &stat, FALSE)) {
7565 if (timespec_to_filetime(×[0], &atime)) {
7568 if (timespec_to_filetime(×[1], &mtime)) {
7573 GetSystemTimePreciseAsFileTime(&atime);
7578 const DWORD attr = GetFileAttributesW(path);
7579 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY))
7580 SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY);
7581 hFile = open_special(path, GENERIC_WRITE, 0);
7582 if (hFile == INVALID_HANDLE_VALUE) {
7583 errno = map_errno(GetLastError());
7587 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
7588 errno = map_errno(GetLastError());
7593 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY))
7594 SetFileAttributesW(path, attr);
7602w32_utimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags, UINT cp)
7604 WCHAR *wpath = mbstr_to_wstr(cp, path, -1, NULL);
7608 ret = wutimensat(dirfd, wpath, times, flags);
7616rb_w32_uutime(
const char *path,
const struct utimbuf *times)
7620 ts[0].tv_sec = times->actime;
7622 ts[1].tv_sec = times->modtime;
7624 return w32_utimensat(AT_FDCWD, path, ts, 0, CP_UTF8);
7629rb_w32_utime(
const char *path,
const struct utimbuf *times)
7633 ts[0].tv_sec = times->actime;
7635 ts[1].tv_sec = times->modtime;
7637 return w32_utimensat(AT_FDCWD, path, ts, 0, filecp());
7642rb_w32_uutimes(
const char *path,
const struct timeval *times)
7646 ts[0].tv_sec = times[0].tv_sec;
7647 ts[0].tv_nsec = times[0].tv_usec * 1000;
7648 ts[1].tv_sec = times[1].tv_sec;
7649 ts[1].tv_nsec = times[1].tv_usec * 1000;
7650 return w32_utimensat(AT_FDCWD, path, ts, 0, CP_UTF8);
7655rb_w32_utimes(
const char *path,
const struct timeval *times)
7659 ts[0].tv_sec = times[0].tv_sec;
7660 ts[0].tv_nsec = times[0].tv_usec * 1000;
7661 ts[1].tv_sec = times[1].tv_sec;
7662 ts[1].tv_nsec = times[1].tv_usec * 1000;
7663 return w32_utimensat(AT_FDCWD, path, ts, 0, filecp());
7668rb_w32_uutimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags)
7670 return w32_utimensat(dirfd, path, times, flags, CP_UTF8);
7675rb_w32_utimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags)
7677 return w32_utimensat(dirfd, path, times, flags, filecp());
7682rb_w32_uchdir(
const char *path)
7687 if (!(wpath = utf8_to_wstr(path, NULL)))
7689 ret = _wchdir(wpath);
7696wmkdir(
const WCHAR *wpath,
int mode)
7701 if (CreateDirectoryW(wpath, NULL) == FALSE) {
7702 errno = map_errno(GetLastError());
7705 if (_wchmod(wpath, mode) == -1) {
7706 RemoveDirectoryW(wpath);
7716rb_w32_umkdir(
const char *path,
int mode)
7721 if (!(wpath = utf8_to_wstr(path, NULL)))
7723 ret = wmkdir(wpath, mode);
7730rb_w32_mkdir(
const char *path,
int mode)
7735 if (!(wpath = filecp_to_wstr(path, NULL)))
7737 ret = wmkdir(wpath, mode);
7744wrmdir(
const WCHAR *wpath)
7748 const DWORD attr = GetFileAttributesW(wpath);
7749 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7750 SetFileAttributesW(wpath, attr & ~FILE_ATTRIBUTE_READONLY);
7752 if (RemoveDirectoryW(wpath) == FALSE) {
7753 errno = map_errno(GetLastError());
7755 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7756 SetFileAttributesW(wpath, attr);
7765rb_w32_rmdir(
const char *path)
7770 if (!(wpath = filecp_to_wstr(path, NULL)))
7772 ret = wrmdir(wpath);
7779rb_w32_urmdir(
const char *path)
7784 if (!(wpath = utf8_to_wstr(path, NULL)))
7786 ret = wrmdir(wpath);
7793wunlink(
const WCHAR *path)
7796 const DWORD SYMLINKD = FILE_ATTRIBUTE_REPARSE_POINT|FILE_ATTRIBUTE_DIRECTORY;
7798 const DWORD attr = GetFileAttributesW(path);
7799 if (attr == (DWORD)-1) {
7801 else if ((attr & SYMLINKD) == SYMLINKD) {
7802 ret = RemoveDirectoryW(path);
7805 if (attr & FILE_ATTRIBUTE_READONLY) {
7806 SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY);
7808 ret = DeleteFileW(path);
7811 errno = map_errno(GetLastError());
7813 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7814 SetFileAttributesW(path, attr);
7823rb_w32_uunlink(
const char *path)
7828 if (!(wpath = utf8_to_wstr(path, NULL)))
7830 ret = wunlink(wpath);
7837rb_w32_unlink(
const char *path)
7842 if (!(wpath = filecp_to_wstr(path, NULL)))
7844 ret = wunlink(wpath);
7851rb_w32_uchmod(
const char *path,
int mode)
7856 if (!(wpath = utf8_to_wstr(path, NULL)))
7858 ret = _wchmod(wpath, mode);
7865fchmod(
int fd,
int mode)
7869 LARGE_INTEGER CreationTime;
7870 LARGE_INTEGER LastAccessTime;
7871 LARGE_INTEGER LastWriteTime;
7872 LARGE_INTEGER ChangeTime;
7873 DWORD FileAttributes;
7874 } info = {{{0}}, {{0}}, {{0}},};
7875 HANDLE h = (HANDLE)_get_osfhandle(fd);
7877 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
7878 if (!(mode & 0200)) info.FileAttributes |= FILE_ATTRIBUTE_READONLY;
7879 if (!SetFileInformationByHandle(h, 0, &info,
sizeof(info))) {
7880 errno = map_errno(GetLastError());
7888rb_w32_isatty(
int fd)
7893 if (_get_osfhandle(fd) == -1) {
7896 if (!GetConsoleMode((HANDLE)_osfhnd(fd), &mode)) {
7903#if defined(_MSC_VER) && RUBY_MSVCRT_VERSION <= 60
7904extern long _ftol(
double);
7925 int *ip = (
int *)(&x + 1) - 1;
7932rb_w32_inet_ntop(
int af,
const void *addr,
char *numaddr,
size_t numaddr_len)
7934 return (inet_ntop)(af, (
void *)addr, numaddr, numaddr_len);
7939rb_w32_inet_pton(
int af,
const char *src,
void *dst)
7941 return (inet_pton)(af, src, dst);
7946rb_w32_fd_is_text(
int fd)
7948 return _osfile(fd) & FTEXT;
7951#if RUBY_MSVCRT_VERSION < 80 && !defined(HAVE__GMTIME64_S)
7954unixtime_to_systemtime(
const time_t t, SYSTEMTIME *st)
7957 if (unixtime_to_filetime(t, &ft))
return -1;
7958 if (!FileTimeToSystemTime(&ft, st))
return -1;
7964systemtime_to_tm(
const SYSTEMTIME *st,
struct tm *t)
7966 int y = st->wYear, m = st->wMonth, d = st->wDay;
7967 t->tm_sec = st->wSecond;
7968 t->tm_min = st->wMinute;
7969 t->tm_hour = st->wHour;
7970 t->tm_mday = st->wDay;
7971 t->tm_mon = st->wMonth - 1;
7972 t->tm_year = y - 1900;
7973 t->tm_wday = st->wDayOfWeek;
7981 d += 31 + 28 + (!(y % 4) && ((y % 100) || !(y % 400)));
7982 d += ((m - 3) * 153 + 2) / 5;
7990systemtime_to_localtime(TIME_ZONE_INFORMATION *tz, SYSTEMTIME *gst, SYSTEMTIME *lst)
7992 TIME_ZONE_INFORMATION stdtz;
7995 if (!SystemTimeToTzSpecificLocalTime(tz, gst, lst))
return -1;
7997 GetTimeZoneInformation(&stdtz);
8000 if (tz->StandardBias == tz->DaylightBias)
return 0;
8001 if (!tz->StandardDate.wMonth)
return 0;
8002 if (!tz->DaylightDate.wMonth)
return 0;
8003 if (tz != &stdtz) stdtz = *tz;
8005 stdtz.StandardDate.wMonth = stdtz.DaylightDate.wMonth = 0;
8006 if (!SystemTimeToTzSpecificLocalTime(&stdtz, gst, &sst))
return 0;
8007 if (lst->wMinute == sst.wMinute && lst->wHour == sst.wHour)
8013#ifdef HAVE__GMTIME64_S
8014# ifndef HAVE__LOCALTIME64_S
8016# define HAVE__LOCALTIME64_S 1
8018# ifndef MINGW_HAS_SECURE_API
8019 _CRTIMP errno_t __cdecl _gmtime64_s(
struct tm* tm,
const __time64_t *time);
8020 _CRTIMP errno_t __cdecl _localtime64_s(
struct tm* tm,
const __time64_t *time);
8022# define gmtime_s _gmtime64_s
8023# define localtime_s _localtime64_s
8028gmtime_r(
const time_t *tp,
struct tm *rp)
8036#if RUBY_MSVCRT_VERSION >= 80 || defined(HAVE__GMTIME64_S)
8037 e = gmtime_s(rp, tp);
8038 if (e != 0)
goto error;
8042 if (unixtime_to_systemtime(*tp, &st))
goto error;
8044 systemtime_to_tm(&st, rp);
8052localtime_r(
const time_t *tp,
struct tm *rp)
8060#if RUBY_MSVCRT_VERSION >= 80 || defined(HAVE__LOCALTIME64_S)
8061 e = localtime_s(rp, tp);
8065 SYSTEMTIME gst, lst;
8066 if (unixtime_to_systemtime(*tp, &gst))
goto error;
8067 rp->tm_isdst = systemtime_to_localtime(NULL, &gst, &lst);
8068 systemtime_to_tm(&lst, rp);
8076rb_w32_wrap_io_handle(HANDLE h,
int flags)
8079 int len =
sizeof(tmp);
8080 int r = getsockopt((SOCKET)h, SOL_SOCKET, SO_DEBUG, (
char *)&tmp, &
len);
8081 if (r != SOCKET_ERROR || WSAGetLastError() != WSAENOTSOCK) {
8083 if (flags & O_NONBLOCK) {
8084 flags &= ~O_NONBLOCK;
8087 socklist_insert((SOCKET)h, f);
8089 else if (flags & O_NONBLOCK) {
8093 return rb_w32_open_osfhandle((intptr_t)h, flags);
8098rb_w32_unwrap_io_handle(
int fd)
8100 SOCKET sock = TO_SOCKET(fd);
8101 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
8102 if (!is_socket(sock)) {
8103 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
8104 constat_delete((HANDLE)sock);
8107 socklist_delete(&sock, NULL);
8112#if !defined(__MINGW64__) && defined(__MINGW64_VERSION_MAJOR)
8118rb_w32_pow(
double x,
double y)
8122 unsigned int default_control = _controlfp(0, 0);
8123 _controlfp(_PC_64, _MCW_PC);
8126 _controlfp(default_control, _MCW_PC);
8134 BY_HANDLE_FILE_INFORMATION bhfi;
8145 tmp = rb_check_convert_type_with_id(*file,
T_FILE,
"IO", idTo_io);
8148 if (f == (HANDLE)-1)
return INVALID_HANDLE_VALUE;
8157 tmp = rb_str_encode_ospath(*file);
8158 len = MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, NULL, 0);
8160 MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, ptr,
len);
8161 f = CreateFileW(ptr, 0,
8162 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
8163 FILE_FLAG_BACKUP_SEMANTICS, NULL);
8165 if (f == INVALID_HANDLE_VALUE)
return f;
8168 if (GetFileType(f) == FILE_TYPE_DISK) {
8169 ZeroMemory(st,
sizeof(*st));
8170 if (get_ino(f, &st->info.fii)) {
8171 st->file_id_p = TRUE;
8174 else if (GetLastError() != ERROR_INVALID_PARAMETER) {
8176 return INVALID_HANDLE_VALUE;
8180 if (GetFileInformationByHandle(f, &st->info.bhfi)) {
8181 st->file_id_p = FALSE;
8185 if (ret) CloseHandle(ret);
8186 return INVALID_HANDLE_VALUE;
8190close_handle(
VALUE h)
8192 CloseHandle((HANDLE)h);
8202call_w32_io_info(
VALUE arg)
8205 return (
VALUE)w32_io_info(p->fname, p->st);
8209rb_w32_file_identical_p(
VALUE fname1,
VALUE fname2)
8212 HANDLE f1 = 0, f2 = 0;
8214 f1 = w32_io_info(&fname1, &st1);
8215 if (f1 == INVALID_HANDLE_VALUE)
return Qfalse;
8218 arg.fname = &fname2;
8223 f2 = w32_io_info(&fname2, &st2);
8225 if (f2 == INVALID_HANDLE_VALUE)
return Qfalse;
8226 if (f2) CloseHandle(f2);
8228 if (st1.file_id_p != st2.file_id_p)
return Qfalse;
8229 if (!st1.file_id_p) {
8230 if (st1.info.bhfi.dwVolumeSerialNumber == st2.info.bhfi.dwVolumeSerialNumber &&
8231 st1.info.bhfi.nFileIndexHigh == st2.info.bhfi.nFileIndexHigh &&
8232 st1.info.bhfi.nFileIndexLow == st2.info.bhfi.nFileIndexLow)
8236 if (st1.info.fii.VolumeSerialNumber == st2.info.fii.VolumeSerialNumber &&
8237 memcmp(&st1.info.fii.FileId, &st2.info.fii.FileId,
sizeof(
FILE_ID_128)) == 0)
8244rb_w32_set_thread_description(HANDLE th,
const WCHAR *name)
8247 typedef HRESULT (WINAPI *set_thread_description_func)(HANDLE, PCWSTR);
8248 static set_thread_description_func set_thread_description =
8249 (set_thread_description_func)-1;
8250 if (set_thread_description == (set_thread_description_func)-1) {
8252 set_thread_description = (set_thread_description_func)
8253 get_proc_address(
"kernel32",
"SetThreadDescription", NULL);
8255 if (set_thread_description) {
8256 result = set_thread_description(th, name);
8262rb_w32_set_thread_description_str(HANDLE th,
VALUE name)
8264 int idx, result = FALSE;
8268 return rb_w32_set_thread_description(th, L
"");
8271 idx = rb_enc_get_index(name);
8272 if (idx == ENCINDEX_UTF_16LE) {
8273 result = rb_w32_set_thread_description(th, s);
8276 name =
rb_str_conv_enc(name, rb_enc_from_index(idx), rb_utf8_encoding());
8277 s = mbstr_to_wstr(CP_UTF8, RSTRING_PTR(name), RSTRING_LEN(name)+1, NULL);
8278 result = rb_w32_set_thread_description(th, s);
8287#if RUBY_MSVCRT_VERSION < 120
8288#include "missing/nextafter.c"
8292rb_w32_mmap(
void *addr,
size_t len,
int prot,
int flags,
int fd, rb_off_t offset)
8296 DWORD protect = PAGE_EXECUTE_READWRITE;
8298 if (fd > 0 || offset) {
8313 ptr = VirtualAlloc(addr,
len, MEM_RESERVE | MEM_COMMIT, protect);
8315 errno = rb_w32_map_errno(GetLastError());
8323rb_w32_munmap(
void *addr,
size_t len)
8325 if (!VirtualFree(addr, 0, MEM_RELEASE)) {
8326 errno = rb_w32_map_errno(GetLastError());
8334rb_w32_mprotect(
void *addr,
size_t len,
int prot)
8350 if (prot & PROT_EXEC) {
8351 if (!FlushInstructionCache(GetCurrentProcess(), addr,
len)) {
8352 errno = rb_w32_map_errno(GetLastError());
int ruby_glob_func(const char *path, VALUE arg, void *enc)
Type of a glob callback function.
#define T_FILE
Old name of RUBY_T_FILE.
#define ALLOCV
Old name of RB_ALLOCV.
#define ISSPACE
Old name of rb_isspace.
#define ALLOC
Old name of RB_ALLOC.
#define xfree
Old name of ruby_xfree.
#define xrealloc
Old name of ruby_xrealloc.
#define ECONV_UNDEF_REPLACE
Old name of RUBY_ECONV_UNDEF_REPLACE.
#define ENCODING_GET(obj)
Old name of RB_ENCODING_GET.
#define ECONV_INVALID_REPLACE
Old name of RUBY_ECONV_INVALID_REPLACE.
#define ASSUME
Old name of RBIMPL_ASSUME.
#define ISALPHA
Old name of rb_isalpha.
#define Qtrue
Old name of RUBY_Qtrue.
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
#define ISALNUM
Old name of rb_isalnum.
#define ALLOCV_END
Old name of RB_ALLOCV_END.
VALUE rb_str_conv_enc(VALUE str, rb_encoding *from, rb_encoding *to)
Encoding conversion main routine.
VALUE rb_str_conv_enc_opts(VALUE str, rb_encoding *from, rb_encoding *to, int ecflags, VALUE ecopts)
Identical to rb_str_conv_enc(), except it additionally takes IO encoder options.
int rb_econv_has_convpath_p(const char *from_encoding, const char *to_encoding)
Queries if there is more than one way to convert between the passed two encodings.
void rb_write_error2(const char *str, long len)
Identical to rb_write_error(), except it additionally takes the message's length.
VALUE rb_str_cat(VALUE dst, const char *src, long srclen)
Destructively appends the passed contents to the string.
#define rb_strlen_lit(str)
Length of a string literal.
#define rb_utf8_str_new(str, len)
Identical to rb_str_new, except it generates a string of "UTF-8" encoding.
VALUE rb_f_notimplement(int argc, const VALUE *argv, VALUE obj, VALUE marker)
Raises rb_eNotImpError.
int rb_io_descriptor(VALUE io)
Returns an integer representing the numeric file descriptor for io.
int len
Length of the buffer.
char * ruby_strdup(const char *str)
This is our own version of strdup(3) that uses ruby_xmalloc() instead of system malloc (benefits our ...
#define strdup(s)
Just another name of ruby_strdup.
void ruby_vm_at_exit(void(*func)(ruby_vm_t *))
ruby_vm_at_exit registers a function func to be invoked when a VM passed away.
void rb_w32_fd_dup(rb_fdset_t *dst, const rb_fdset_t *src)
Identical to rb_w32_fd_copy(), except it copies unlimited number of file descriptors.
void rb_w32_fd_copy(rb_fdset_t *dst, const fd_set *src, int max)
Destructively overwrites an fdset with another.
void rb_fd_term(rb_fdset_t *f)
Destroys the rb_fdset_t, releasing any memory and resources it used.
#define rb_long2int
Just another name of rb_long2int_inline.
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
#define ALLOCA_N(type, n)
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
VALUE type(ANYARGS)
ANYARGS-ed function type.
VALUE rb_ensure(type *q, VALUE w, type *e, VALUE r)
An equivalent of ensure clause.
#define RBIMPL_ATTR_NONNULL(list)
Wraps (or simulates) __attribute__((nonnull))
#define PRI_PIDT_PREFIX
A rb_sprintf() format prefix to be used for a pid_t parameter.
#define rb_fd_init
Initialises the :given :rb_fdset_t.
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
#define FilePathValue(v)
Ensures that the parameter object is a path.
#define errno
Ractor-aware version of errno.
The data structure which wraps the fd_set bitmap used by select(2).
fd_set * fdset
File descriptors buffer.
int capa
Maximum allowed number of FDs.
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
uintptr_t VALUE
Type that represents a Ruby object.