59#include "ruby/win32.h"
62#include "win32/file.h"
65#include "internal/enc.h"
66#include "internal/object.h"
67#include "internal/static_assert.h"
70#define isdirsep(x) ((x) == '/' || (x) == '\\')
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)
84#define DLN_CHAR_NEXT(p) CharNextExA(cp, (p), 0)
85#define dln_find_exe_r rb_w32_udln_find_exe_r
86#define dln_find_file_r rb_w32_udln_find_file_r
93#define dln_find_exe_r(fname, path, buf, size) rb_w32_udln_find_exe_r(fname, path, buf, size, cp)
94#define dln_find_file_r(fname, path, buf, size) rb_w32_udln_find_file_r(fname, path, buf, size, cp)
100# define PATH_MAX MAX_PATH
101# elif defined HAVE_SYS_PARAM_H
102# include <sys/param.h>
103# define PATH_MAX MAXPATHLEN
115#define _filbuf _fgetc_nolock
116#define _flsbuf _fputc_nolock
117#define enough_to_get(n) (--(n) >= 0)
118#define enough_to_put(n) (--(n) >= 0)
121#define Debug(something) something
123#define Debug(something)
126#define TO_SOCKET(x) _get_osfhandle(x)
128int rb_w32_reparse_symlink_p(
const WCHAR *path);
130static int has_redirection(
const char *, UINT);
131int rb_w32_wait_events(HANDLE *events,
int num, DWORD timeout);
132static int rb_w32_open_osfhandle(intptr_t osfhandle,
int flags);
133static int wstati128(
const WCHAR *path,
struct stati128 *st, BOOL lstat);
136static FARPROC get_proc_address(
const char *module,
const char *func, HANDLE *mh);
138#define RUBY_CRITICAL if (0) {} else
145 { ERROR_INVALID_FUNCTION, EINVAL },
146 { ERROR_FILE_NOT_FOUND, ENOENT },
147 { ERROR_PATH_NOT_FOUND, ENOENT },
148 { ERROR_TOO_MANY_OPEN_FILES, EMFILE },
149 { ERROR_ACCESS_DENIED, EACCES },
150 { ERROR_INVALID_HANDLE, EBADF },
151 { ERROR_ARENA_TRASHED, ENOMEM },
152 { ERROR_NOT_ENOUGH_MEMORY, ENOMEM },
153 { ERROR_INVALID_BLOCK, ENOMEM },
154 { ERROR_BAD_ENVIRONMENT, E2BIG },
155 { ERROR_BAD_FORMAT, ENOEXEC },
156 { ERROR_INVALID_ACCESS, EINVAL },
157 { ERROR_INVALID_DATA, EINVAL },
158 { ERROR_INVALID_DRIVE, ENOENT },
159 { ERROR_CURRENT_DIRECTORY, EACCES },
160 { ERROR_NOT_SAME_DEVICE, EXDEV },
161 { ERROR_NO_MORE_FILES, ENOENT },
162 { ERROR_WRITE_PROTECT, EROFS },
163 { ERROR_BAD_UNIT, ENODEV },
164 { ERROR_NOT_READY, ENXIO },
165 { ERROR_BAD_COMMAND, EACCES },
166 { ERROR_CRC, EACCES },
167 { ERROR_BAD_LENGTH, EACCES },
169 { ERROR_NOT_DOS_DISK, EACCES },
170 { ERROR_SECTOR_NOT_FOUND, EACCES },
171 { ERROR_OUT_OF_PAPER, EACCES },
172 { ERROR_WRITE_FAULT, EIO },
173 { ERROR_READ_FAULT, EIO },
174 { ERROR_GEN_FAILURE, EACCES },
175 { ERROR_LOCK_VIOLATION, EACCES },
176 { ERROR_SHARING_VIOLATION, EACCES },
177 { ERROR_WRONG_DISK, EACCES },
178 { ERROR_SHARING_BUFFER_EXCEEDED, EACCES },
179 { ERROR_BAD_NETPATH, ENOENT },
180 { ERROR_NETWORK_ACCESS_DENIED, EACCES },
181 { ERROR_BAD_NET_NAME, ENOENT },
182 { ERROR_FILE_EXISTS, EEXIST },
183 { ERROR_CANNOT_MAKE, EACCES },
184 { ERROR_FAIL_I24, EACCES },
185 { ERROR_INVALID_PARAMETER, EINVAL },
186 { ERROR_NO_PROC_SLOTS, EAGAIN },
187 { ERROR_DRIVE_LOCKED, EACCES },
188 { ERROR_BROKEN_PIPE, EPIPE },
189 { ERROR_DISK_FULL, ENOSPC },
190 { ERROR_INVALID_TARGET_HANDLE, EBADF },
191 { ERROR_INVALID_HANDLE, EINVAL },
192 { ERROR_WAIT_NO_CHILDREN, ECHILD },
193 { ERROR_CHILD_NOT_COMPLETE, ECHILD },
194 { ERROR_DIRECT_ACCESS_HANDLE, EBADF },
195 { ERROR_NEGATIVE_SEEK, EINVAL },
196 { ERROR_SEEK_ON_DEVICE, EACCES },
197 { ERROR_DIR_NOT_EMPTY, ENOTEMPTY },
198 { ERROR_DIRECTORY, ENOTDIR },
199 { ERROR_NOT_LOCKED, EACCES },
200 { ERROR_BAD_PATHNAME, ENOENT },
201 { ERROR_MAX_THRDS_REACHED, EAGAIN },
202 { ERROR_LOCK_FAILED, EACCES },
203 { ERROR_ALREADY_EXISTS, EEXIST },
204 { ERROR_INVALID_STARTING_CODESEG, ENOEXEC },
205 { ERROR_INVALID_STACKSEG, ENOEXEC },
206 { ERROR_INVALID_MODULETYPE, ENOEXEC },
207 { ERROR_INVALID_EXE_SIGNATURE, ENOEXEC },
208 { ERROR_EXE_MARKED_INVALID, ENOEXEC },
209 { ERROR_BAD_EXE_FORMAT, ENOEXEC },
210 { ERROR_ITERATED_DATA_EXCEEDS_64k,ENOEXEC },
211 { ERROR_INVALID_MINALLOCSIZE, ENOEXEC },
212 { ERROR_DYNLINK_FROM_INVALID_RING,ENOEXEC },
213 { ERROR_IOPL_NOT_ENABLED, ENOEXEC },
214 { ERROR_INVALID_SEGDPL, ENOEXEC },
215 { ERROR_AUTODATASEG_EXCEEDS_64k, ENOEXEC },
216 { ERROR_RING2SEG_MUST_BE_MOVABLE, ENOEXEC },
217 { ERROR_RELOC_CHAIN_XEEDS_SEGLIM, ENOEXEC },
218 { ERROR_INFLOOP_IN_RELOC_CHAIN, ENOEXEC },
219 { ERROR_FILENAME_EXCED_RANGE, ENOENT },
220 { ERROR_NESTING_NOT_ALLOWED, EAGAIN },
221#ifndef ERROR_PIPE_LOCAL
222#define ERROR_PIPE_LOCAL 229L
224 { ERROR_PIPE_LOCAL, EPIPE },
225 { ERROR_BAD_PIPE, EPIPE },
226 { ERROR_PIPE_BUSY, EAGAIN },
227 { ERROR_NO_DATA, EPIPE },
228 { ERROR_PIPE_NOT_CONNECTED, EPIPE },
229 { ERROR_OPERATION_ABORTED, EINTR },
230 { ERROR_NOT_ENOUGH_QUOTA, ENOMEM },
231 { ERROR_MOD_NOT_FOUND, ENOENT },
232 { ERROR_PRIVILEGE_NOT_HELD, EACCES, },
233 { ERROR_CANT_RESOLVE_FILENAME, ELOOP, },
236 { WSAEACCES, EACCES },
237 { WSAEFAULT, EFAULT },
238 { WSAEINVAL, EINVAL },
239 { WSAEMFILE, EMFILE },
240 { WSAEWOULDBLOCK, EWOULDBLOCK },
241 { WSAEINPROGRESS, EINPROGRESS },
242 { WSAEALREADY, EALREADY },
243 { WSAENOTSOCK, ENOTSOCK },
244 { WSAEDESTADDRREQ, EDESTADDRREQ },
245 { WSAEMSGSIZE, EMSGSIZE },
246 { WSAEPROTOTYPE, EPROTOTYPE },
247 { WSAENOPROTOOPT, ENOPROTOOPT },
248 { WSAEPROTONOSUPPORT, EPROTONOSUPPORT },
249 { WSAESOCKTNOSUPPORT, ESOCKTNOSUPPORT },
250 { WSAEOPNOTSUPP, EOPNOTSUPP },
251 { WSAEPFNOSUPPORT, EPFNOSUPPORT },
252 { WSAEAFNOSUPPORT, EAFNOSUPPORT },
253 { WSAEADDRINUSE, EADDRINUSE },
254 { WSAEADDRNOTAVAIL, EADDRNOTAVAIL },
255 { WSAENETDOWN, ENETDOWN },
256 { WSAENETUNREACH, ENETUNREACH },
257 { WSAENETRESET, ENETRESET },
258 { WSAECONNABORTED, ECONNABORTED },
259 { WSAECONNRESET, ECONNRESET },
260 { WSAENOBUFS, ENOBUFS },
261 { WSAEISCONN, EISCONN },
262 { WSAENOTCONN, ENOTCONN },
263 { WSAESHUTDOWN, ESHUTDOWN },
264 { WSAETOOMANYREFS, ETOOMANYREFS },
265 { WSAETIMEDOUT, ETIMEDOUT },
266 { WSAECONNREFUSED, ECONNREFUSED },
268 { WSAENAMETOOLONG, ENAMETOOLONG },
269 { WSAEHOSTDOWN, EHOSTDOWN },
270 { WSAEHOSTUNREACH, EHOSTUNREACH },
271 { WSAEPROCLIM, EPROCLIM },
272 { WSAENOTEMPTY, ENOTEMPTY },
273 { WSAEUSERS, EUSERS },
274 { WSAEDQUOT, EDQUOT },
275 { WSAESTALE, ESTALE },
276 { WSAEREMOTE, EREMOTE },
281rb_w32_map_errno(DWORD winerr)
289 for (i = 0; i < (int)(
sizeof(errmap) /
sizeof(*errmap)); i++) {
290 if (errmap[i].winerr == winerr) {
291 return errmap[i].err;
295 if (winerr >= WSABASEERR) {
301#define map_errno rb_w32_map_errno
303static const char *NTLoginName;
305static OSVERSIONINFO osver;
311 memset(&osver, 0,
sizeof(OSVERSIONINFO));
312 osver.dwOSVersionInfoSize =
sizeof(OSVERSIONINFO);
313 GetVersionEx(&osver);
320 return osver.dwMajorVersion;
331 DWORD err = GetLastError(); \
332 if (err == ERROR_LOCK_VIOLATION || err == ERROR_IO_PENDING) \
333 errno = EWOULDBLOCK; \
334 else if (err == ERROR_NOT_LOCKED) \
337 errno = map_errno(err); \
340#define LK_LEN ULONG_MAX
344flock_winnt(uintptr_t self,
int argc, uintptr_t* argv)
348 const HANDLE fh = (HANDLE)self;
349 const int oper = argc;
351 memset(&o, 0,
sizeof(o));
355 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, LK_LEN, &o), i);
358 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, LK_LEN, &o), i);
360 case LOCK_SH|LOCK_NB:
361 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, LK_LEN, &o), i);
363 case LOCK_EX|LOCK_NB:
364 LK_ERR(LockFileEx(fh,
365 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
366 0, LK_LEN, LK_LEN, &o), i);
369 case LOCK_UN|LOCK_NB:
370 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, LK_LEN, &o), i);
383flock(
int fd,
int oper)
385 const asynchronous_func_t locker = flock_winnt;
387 return rb_w32_asynchronize(locker,
388 (
VALUE)_get_osfhandle(fd), oper, NULL,
394translate_wchar(WCHAR *p,
int from,
int to)
405translate_char(
char *p,
int from,
int to, UINT cp)
408 if ((
unsigned char)*p == from)
410 p = CharNextExA(cp, p, 0);
415#ifndef CSIDL_LOCAL_APPDATA
416#define CSIDL_LOCAL_APPDATA 28
418#ifndef CSIDL_COMMON_APPDATA
419#define CSIDL_COMMON_APPDATA 35
422#define CSIDL_WINDOWS 36
425#define CSIDL_SYSTEM 37
428#define CSIDL_PROFILE 40
433get_special_folder(
int n, WCHAR *buf,
size_t len)
439 if (SHGetSpecialFolderLocation(NULL, n, &pidl) == 0) {
440 f = SHGetPathFromIDListEx(pidl, buf,
len, 0);
442 alloc->lpVtbl->Free(alloc, pidl);
443 alloc->lpVtbl->Release(alloc);
450regulate_path(WCHAR *path)
452 WCHAR *p = translate_wchar(path, L
'\\', L
'/');
453 if (p - path == 2 && path[1] == L
':') {
461get_proc_address(
const char *module,
const char *func, HANDLE *mh)
467 h = LoadLibrary(module);
469 h = GetModuleHandle(module);
473 ptr = GetProcAddress(h, func);
485rb_w32_special_folder(
int type)
487 WCHAR path[PATH_MAX];
489 if (!get_special_folder(
type, path, numberof(path)))
return Qnil;
491 return rb_w32_conv_from_wchar(path, rb_filesystem_encoding());
496rb_w32_system_tmpdir(WCHAR *path, UINT
len)
498 static const WCHAR temp[] = L
"temp";
501 if (!get_special_folder(CSIDL_LOCAL_APPDATA, path,
len)) {
502 if (GetSystemWindowsDirectoryW(path,
len))
return 0;
504 p = translate_wchar(path, L
'\\', L
'/');
505 if (*(p - 1) != L
'/') *p++ = L
'/';
506 if ((UINT)(p - path + numberof(temp)) >=
len)
return 0;
507 memcpy(p, temp,
sizeof(temp));
508 return (UINT)(p - path + numberof(temp) - 1);
523 WCHAR *buffer = NULL;
524 size_t buffer_len = MAX_PATH,
len = 0;
526 HOME_NONE, ENV_HOME, ENV_USERPROFILE, ENV_DRIVEPATH
527 } home_type = HOME_NONE;
529 if ((
len = GetEnvironmentVariableW(L
"HOME", NULL, 0)) != 0) {
531 home_type = ENV_HOME;
533 else if ((
len = GetEnvironmentVariableW(L
"USERPROFILE", NULL, 0)) != 0) {
535 home_type = ENV_USERPROFILE;
537 else if ((
len = GetEnvironmentVariableW(L
"HOMEDRIVE", NULL, 0)) != 0) {
539 if ((
len = GetEnvironmentVariableW(L
"HOMEPATH", NULL, 0)) != 0) {
541 home_type = ENV_DRIVEPATH;
546 buffer = malloc(
sizeof(WCHAR) * buffer_len);
547 if (buffer == NULL)
return NULL;
551 GetEnvironmentVariableW(L
"HOME", buffer, buffer_len);
553 case ENV_USERPROFILE:
554 GetEnvironmentVariableW(L
"USERPROFILE", buffer, buffer_len);
557 len = GetEnvironmentVariableW(L
"HOMEDRIVE", buffer, buffer_len);
558 GetEnvironmentVariableW(L
"HOMEPATH", buffer +
len, buffer_len -
len);
561 if (!get_special_folder(CSIDL_PROFILE, buffer, buffer_len) &&
562 !get_special_folder(CSIDL_PERSONAL, buffer, buffer_len)) {
566 buffer = realloc(buffer,
sizeof(WCHAR) * (lstrlenW(buffer) + 1));
571 regulate_path(buffer);
582 if (!GetEnvironmentVariableW(L
"HOME", env, numberof(env))) {
583 WCHAR *whome = rb_w32_home_dir();
585 _wputenv_s(L
"HOME", whome);
590 if (!GetEnvironmentVariableW(L
"USER", env, numberof(env))) {
592 if (!GetEnvironmentVariableW(L
"USERNAME", env, numberof(env)) &&
593 !GetUserNameW(env, (
len = numberof(env), &
len))) {
594 NTLoginName =
"<Unknown>";
597 _wputenv_s(L
"USER", env);
598 NTLoginName = rb_w32_wstr_to_mbstr(CP_UTF8, env, -1, NULL);
602 NTLoginName = rb_w32_wstr_to_mbstr(CP_UTF8, env, -1, NULL);
605 if (!GetEnvironmentVariableW(L
"TMPDIR", env, numberof(env)) &&
606 !GetEnvironmentVariableW(L
"TMP", env, numberof(env)) &&
607 !GetEnvironmentVariableW(L
"TEMP", env, numberof(env)) &&
608 rb_w32_system_tmpdir(env, numberof(env))) {
609 _wputenv_s(L
"TMPDIR", env);
613static void init_stdhandle(
void);
617invalid_parameter(
const wchar_t *expr,
const wchar_t *func,
const wchar_t *file,
unsigned int line, uintptr_t dummy)
622int ruby_w32_rtc_error;
629rtc_error_handler(
int e, const
char *src,
int line, const
char *exe, const
char *fmt, ...)
634 if (!ruby_w32_rtc_error)
return 0;
635 str = rb_sprintf(
"%s:%d: ", src, line);
637 rb_str_vcatf(str, fmt, ap);
645static CRITICAL_SECTION select_mutex;
647static CRITICAL_SECTION socklist_mutex;
650static CRITICAL_SECTION conlist_mutex;
652#define conlist_disabled ((st_table *)-1)
654#define thread_exclusive(obj) \
655 for (bool exclusive_for_##obj = (EnterCriticalSection(&obj##_mutex), true); \
656 exclusive_for_##obj; \
657 exclusive_for_##obj = (LeaveCriticalSection(&obj##_mutex), false))
659static CRITICAL_SECTION uenvarea_mutex;
660static char *uenvarea;
665 int state, seq[16], reverse;
670enum {constat_init = -2, constat_esc = -1, constat_seq = 0};
674free_conlist(st_data_t key, st_data_t val, st_data_t arg)
682constat_delete(HANDLE h)
684 thread_exclusive(conlist) {
685 if (conlist && conlist != conlist_disabled) {
686 st_data_t key = (st_data_t)h, val;
687 st_delete(conlist, &key, &val);
698 DeleteCriticalSection(&select_mutex);
699 DeleteCriticalSection(&socklist_mutex);
700 DeleteCriticalSection(&conlist_mutex);
701 thread_exclusive(uenvarea) {
707 DeleteCriticalSection(&uenvarea_mutex);
714 EnterCriticalSection(&socklist_mutex);
716 st_free_table(socklist);
719 LeaveCriticalSection(&socklist_mutex);
721 EnterCriticalSection(&conlist_mutex);
722 if (conlist && conlist != conlist_disabled) {
723 st_foreach(conlist, free_conlist, 0);
724 st_free_table(conlist);
727 LeaveCriticalSection(&conlist_mutex);
730#define ATOMIC_LONG_CAS(var, oldval, newval) InterlockedCompareExchange(&(var), (newval), (oldval))
734install_vm_exit_handler(
void)
736 static LONG installed = 0;
739 while ((i = ATOMIC_LONG_CAS(installed, 0, -1)) != 1) {
745 ATOMIC_LONG_CAS(installed, -1, 1);
761 version = MAKEWORD(2, 0);
762 if (WSAStartup(version, &retdata))
763 rb_fatal(
"Unable to locate winsock library!");
764 if (LOBYTE(retdata.wVersion) != 2)
765 rb_fatal(
"could not find version 2 of winsock dll");
767 InitializeCriticalSection(&select_mutex);
768 InitializeCriticalSection(&socklist_mutex);
769 InitializeCriticalSection(&conlist_mutex);
771 atexit(exit_handler);
774#define MAKE_SOCKDATA(af, fl) ((int)((((int)af)<<4)|((fl)&0xFFFF)))
775#define GET_FAMILY(v) ((int)(((v)>>4)&0xFFFF))
776#define GET_FLAGS(v) ((int)((v)&0xFFFF))
780socklist_insert(SOCKET sock,
int flag)
784 thread_exclusive(socklist) {
786 socklist = st_init_numtable();
787 install_vm_exit_handler();
789 ret = st_insert(socklist, (st_data_t)sock, (st_data_t)flag);
797socklist_lookup(SOCKET sock,
int *flagp)
802 thread_exclusive(socklist) {
803 if (!socklist)
continue;
804 ret = st_lookup(socklist, (st_data_t)sock, &data);
814socklist_delete(SOCKET *sockp,
int *flagp)
820 thread_exclusive(socklist) {
821 if (!socklist)
continue;
822 key = (st_data_t)*sockp;
824 data = (st_data_t)*flagp;
825 ret = st_delete(socklist, &key, &data);
827 *sockp = (SOCKET)key;
837# define _CrtSetReportMode(type,mode) ((void)0)
838# define _RTC_SetErrorFunc(func) ((void)0)
840static void set_pioinfo_extra(
void);
841static int w32_cmdvector(
const WCHAR *,
char ***, UINT,
rb_encoding *);
858rb_w32_init_long_paths(
void)
861 enum {peb_bit_field_offset = 3, is_long_path_aware_process = 0x80};
862 typedef long (WINAPI version_func)(OSVERSIONINFOW *);
863 typedef void *(WINAPI peb_func)(
void);
864 version_func *pRtlGetVersion;
865 peb_func *pRtlGetCurrentPeb;
869 pRtlGetVersion = (version_func *)get_proc_address(
"ntdll.dll",
"RtlGetVersion", NULL);
870 if (!pRtlGetVersion)
return;
871 memset(&osvi, 0,
sizeof(osvi));
872 osvi.dwOSVersionInfoSize =
sizeof(osvi);
873 if (pRtlGetVersion(&osvi))
return;
876 if (osvi.dwMajorVersion < 10)
return;
877 if (osvi.dwMajorVersion == 10 && osvi.dwMinorVersion == 0 &&
878 osvi.dwBuildNumber < 15063)
return;
880 pRtlGetCurrentPeb = (peb_func *)get_proc_address(
"ntdll.dll",
"RtlGetCurrentPeb", NULL);
881 if (!pRtlGetCurrentPeb)
return;
882 bit_field = (BYTE *)pRtlGetCurrentPeb() + peb_bit_field_offset;
883 *bit_field |= is_long_path_aware_process;
888rb_w32_sysinit(
int *argc,
char ***argv)
890 _CrtSetReportMode(_CRT_ASSERT, 0);
891 _set_invalid_parameter_handler(invalid_parameter);
892 _RTC_SetErrorFunc(rtc_error_handler);
894 SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX);
901 *argc = w32_cmdvector(GetCommandLineW(), argv, CP_UTF8, &OnigEncodingUTF_8);
909 InitializeCriticalSection(&uenvarea_mutex);
921 return (
char *)NTLoginName;
924#define MAXCHILDNUM 256
933#define FOREACH_CHILD(v) do { \
934 struct ChildRecord* v; \
935 for (v = ChildRecord; v < ChildRecord + sizeof(ChildRecord) / sizeof(ChildRecord[0]); ++v)
936#define END_FOREACH_CHILD } while (0)
940FindChildSlot(rb_pid_t pid)
943 FOREACH_CHILD(child) {
944 if (child->pid == pid) {
953FindChildSlotByHandle(HANDLE h)
956 FOREACH_CHILD(child) {
957 if (child->hProcess == h) {
968 HANDLE h = child->hProcess;
969 child->hProcess = NULL;
976FindFreeChildSlot(
void)
978 FOREACH_CHILD(child) {
981 child->hProcess = NULL;
989#define InternalCmdsMax 8
990static const char szInternalCmds[][InternalCmdsMax+1] = {
1038internal_match(
const void *key,
const void *elem)
1040 return strncmp(key, elem, InternalCmdsMax);
1043static int internal_cmd_match(
const char *cmdname);
1047is_internal_cmd(
const char *cmd)
1049 char cmdname[InternalCmdsMax+1], *b = cmdname, c;
1052 if (!(c = *cmd++))
return 0;
1053 }
while (isspace(c));
1056 while (isalpha(c)) {
1058 if (b == cmdname +
sizeof(cmdname))
return 0;
1061 if (c ==
'.') c = *cmd;
1063 case '<':
case '>':
case '|':
1065 case '\0':
case ' ':
case '\t':
case '\n':
1071 return internal_cmd_match(cmdname);
1076internal_cmd_match(
const char *cmdname)
1080 nm = bsearch(cmdname, szInternalCmds,
1081 numberof(szInternalCmds),
1082 sizeof(*szInternalCmds),
1090rb_w32_get_osfhandle(
int fh)
1092 return _get_osfhandle(fh);
1097join_argv(
char *cmd,
char *
const *argv, BOOL escape, UINT cp,
int backslash, BOOL quote_bs)
1101 int len, n, bs, quote;
1103 for (t = argv, q = cmd,
len = 0; (p = *t) != 0; t++) {
1106 if (!*p || strpbrk(p,
" \t\"'")) {
1111 for (bs = 0; *p; ++p) {
1125 memset(q,
'\\', bs);
1130 case '<':
case '>':
case '|':
case '^':
1131 if (escape && !quote) {
1132 len += (n = p - s) + 1;
1143 p = CharNextExA(cp, p, 0) - 1;
1147 len += (n = p - s) + 1;
1148 if (quote)
len += (quote_bs ? bs : 0) + 1;
1151 if (backslash > 0) {
1154 translate_char(q,
'/',
'\\', cp);
1159 if (quote_bs && bs) {
1160 memset(q,
'\\', bs);
1177#define STRNDUPV(ptr, v, src, len) \
1178 (((char *)memcpy(((ptr) = ALLOCV((v), (len) + 1)), (src), (len)))[len] = 0)
1182check_spawn_mode(
int mode)
1204 if (mode == P_OVERLAY) {
1205 WaitForSingleObject(child->hProcess, INFINITE);
1206 GetExitCodeProcess(child->hProcess, &exitcode);
1207 CloseChildHandle(child);
1215CreateChild(
struct ChildRecord *child,
const WCHAR *cmd,
const WCHAR *prog, HANDLE hInput, HANDLE hOutput, HANDLE hError, DWORD dwCreationFlags)
1218 STARTUPINFOW aStartupInfo;
1219 PROCESS_INFORMATION aProcessInformation;
1220 SECURITY_ATTRIBUTES sa;
1222 if (!cmd && !prog) {
1232 sa.nLength =
sizeof(SECURITY_ATTRIBUTES);
1233 sa.lpSecurityDescriptor = NULL;
1234 sa.bInheritHandle = TRUE;
1236 memset(&aStartupInfo, 0,
sizeof(aStartupInfo));
1237 memset(&aProcessInformation, 0,
sizeof(aProcessInformation));
1238 aStartupInfo.cb =
sizeof(aStartupInfo);
1239 aStartupInfo.dwFlags = STARTF_USESTDHANDLES;
1241 aStartupInfo.hStdInput = hInput;
1244 aStartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
1247 aStartupInfo.hStdOutput = hOutput;
1250 aStartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
1253 aStartupInfo.hStdError = hError;
1256 aStartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
1259 dwCreationFlags |= NORMAL_PRIORITY_CLASS;
1261 if (lstrlenW(cmd) > 32767) {
1268 fRet = CreateProcessW(prog, (WCHAR *)cmd, &sa, &sa,
1269 sa.bInheritHandle, dwCreationFlags, NULL, NULL,
1270 &aStartupInfo, &aProcessInformation);
1271 errno = map_errno(GetLastError());
1279 CloseHandle(aProcessInformation.hThread);
1281 child->hProcess = aProcessInformation.hProcess;
1282 child->pid = (rb_pid_t)aProcessInformation.dwProcessId;
1289is_batch(
const char *cmd)
1291 int len = strlen(cmd);
1292 if (
len <= 4)
return 0;
1294 if (*cmd++ !=
'.')
return 0;
1295 if (strcasecmp(cmd,
"bat") == 0)
return 1;
1296 if (strcasecmp(cmd,
"cmd") == 0)
return 1;
1300#define filecp rb_w32_filecp
1301#define mbstr_to_wstr rb_w32_mbstr_to_wstr
1302#define wstr_to_mbstr rb_w32_wstr_to_mbstr
1303#define acp_to_wstr(str, plen) mbstr_to_wstr(CP_ACP, str, -1, plen)
1304#define wstr_to_acp(str, plen) wstr_to_mbstr(CP_ACP, str, -1, plen)
1305#define filecp_to_wstr(str, plen) mbstr_to_wstr(filecp(), str, -1, plen)
1306#define wstr_to_filecp(str, plen) wstr_to_mbstr(filecp(), str, -1, plen)
1307#define utf8_to_wstr(str, plen) mbstr_to_wstr(CP_UTF8, str, -1, plen)
1308#define wstr_to_utf8(str, plen) wstr_to_mbstr(CP_UTF8, str, -1, plen)
1312w32_spawn(
int mode,
const char *cmd,
const char *prog, UINT cp)
1314 char fbuf[PATH_MAX];
1316 const char *shell = NULL;
1317 WCHAR *wcmd = NULL, *wshell = NULL;
1323 char *cmd_sep = NULL;
1325 if (check_spawn_mode(mode))
return -1;
1328 if (!(p = dln_find_exe_r(prog, NULL, fbuf,
sizeof(fbuf)))) {
1333 translate_char(p,
'/',
'\\', cp);
1339 if ((shell = w32_getenv(
"RUBYSHELL", cp)) && (redir = has_redirection(cmd, cp))) {
1340 size_t shell_len = strlen(shell);
1341 size_t cmd_len = strlen(cmd) +
sizeof(
" -c ") + 2;
1342 char *tmp =
ALLOCV(v, shell_len + cmd_len);
1343 memcpy(tmp, shell, shell_len + 1);
1344 translate_char(tmp,
'/',
'\\', cp);
1345 snprintf(tmp + shell_len, cmd_len,
" -c \"%s\"", cmd);
1348 else if ((shell = w32_getenv(
"COMSPEC", cp)) &&
1349 ((redir < 0 ? has_redirection(cmd, cp) : redir) || is_internal_cmd(cmd))) {
1350 size_t cmd_len = strlen(shell) + strlen(cmd) +
sizeof(
" /c \"\"");
1351 char *tmp =
ALLOCV(v, cmd_len);
1352 snprintf(tmp, cmd_len,
"%s /c \"%s\"", shell, cmd);
1356 int len = 0, quote = (*cmd ==
'"') ?
'"' : (*cmd ==
'\'') ?
'\'' : 0;
1358 for (prog = cmd + !!quote;; prog = CharNextExA(cp, prog, 0)) {
1359 if (*prog ==
'/') slash = 1;
1363 STRNDUPV(p, v2, cmd,
len);
1369 if ((
unsigned char)*prog == quote) {
1370 len = prog++ - cmd - 1;
1371 STRNDUPV(p, v2, cmd + 1,
len);
1375 if (quote)
continue;
1376 if (
ISSPACE(*prog) || strchr(
"<>|*?\"", *prog)) {
1378 STRNDUPV(p, v2, cmd,
len + (slash ? strlen(prog) : 0));
1381 sep = *(cmd_sep = &p[
len]);
1388 shell = dln_find_exe_r(shell, NULL, fbuf,
sizeof(fbuf));
1389 if (p && slash) translate_char(p,
'/',
'\\', cp);
1391 shell = p ? p : cmd;
1394 len = strlen(shell);
1395 if (strchr(shell,
' ')) quote = -1;
1396 if (shell == fbuf) {
1399 else if (shell != p && strchr(shell,
'/')) {
1400 STRNDUPV(p, v2, shell,
len);
1403 if (p) translate_char(p,
'/',
'\\', cp);
1404 if (is_batch(shell)) {
1405 int alen = strlen(prog);
1406 cmd = p =
ALLOCV(v,
len + alen + (quote ? 2 : 0) + 1);
1407 if (quote) *p++ =
'"';
1408 memcpy(p, shell,
len);
1410 if (quote) *p++ =
'"';
1411 memcpy(p, prog, alen + 1);
1418 if (!e && shell && !(wshell = mbstr_to_wstr(cp, shell, -1, NULL))) e = E2BIG;
1419 if (cmd_sep) *cmd_sep = sep;
1420 if (!e && cmd && !(wcmd = mbstr_to_wstr(cp, cmd, -1, NULL))) e = E2BIG;
1426 if (CreateChild(child, wcmd, wshell, NULL, NULL, NULL, 0)) {
1427 ret = child_result(child, mode);
1438rb_w32_spawn(
int mode,
const char *cmd,
const char *prog)
1441 return w32_spawn(mode, cmd, prog, filecp());
1446rb_w32_uspawn(
int mode,
const char *cmd,
const char *prog)
1448 return w32_spawn(mode, cmd, prog, CP_UTF8);
1453w32_spawn_process(
int mode,
const char *prog,
char *
const *argv,
1454 int in_fd,
int out_fd,
int err_fd, DWORD flags, UINT cp)
1459 char *cmd, fbuf[PATH_MAX];
1460 WCHAR *wcmd = NULL, *wprog = NULL;
1464 HANDLE in_handle = NULL, out_handle = NULL, err_handle = NULL;
1466 if (check_spawn_mode(mode))
return -1;
1469 in_handle = (HANDLE)rb_w32_get_osfhandle(in_fd);
1472 out_handle = (HANDLE)rb_w32_get_osfhandle(out_fd);
1475 err_handle = (HANDLE)rb_w32_get_osfhandle(err_fd);
1478 if (!prog) prog = argv[0];
1479 if ((shell = w32_getenv(
"COMSPEC", cp)) && internal_cmd_match(prog)) {
1483 else if ((cmd = dln_find_exe_r(prog, NULL, fbuf,
sizeof(fbuf)))) {
1484 if (cmd == prog) strlcpy(cmd = fbuf, prog,
sizeof(fbuf));
1485 translate_char(cmd,
'/',
'\\', cp);
1488 else if (strchr(prog,
'/')) {
1490 if (
len <
sizeof(fbuf))
1491 strlcpy(cmd = fbuf, prog,
sizeof(fbuf));
1493 STRNDUPV(cmd, v, prog,
len);
1494 translate_char(cmd,
'/',
'\\', cp);
1497 if (c_switch || is_batch(prog)) {
1499 progs[0] = (
char *)prog;
1501 len = join_argv(NULL, progs, TRUE, cp, 1, FALSE);
1502 if (c_switch)
len += 3;
1504 if (argv[0])
len += join_argv(NULL, argv, TRUE, cp, 0, FALSE);
1506 join_argv(cmd, progs, TRUE, cp, 1, FALSE);
1507 if (c_switch) strlcat(cmd,
" /c",
len);
1508 if (argv[0]) join_argv(cmd + strlcat(cmd,
" ",
len), argv, TRUE, cp, 0, FALSE);
1509 prog = c_switch ? shell : 0;
1512 len = join_argv(NULL, argv, FALSE, cp, 1, TRUE);
1514 join_argv(cmd, argv, FALSE, cp, 1, TRUE);
1517 if (!e && cmd && !(wcmd = mbstr_to_wstr(cp, cmd, -1, NULL))) e = E2BIG;
1519 if (!e && prog && !(wprog = mbstr_to_wstr(cp, prog, -1, NULL))) e = E2BIG;
1523 if (CreateChild(child, wcmd, wprog, in_handle, out_handle, err_handle, flags)) {
1524 ret = child_result(child, mode);
1535rb_w32_aspawn_flags(
int mode,
const char *prog,
char *
const *argv, DWORD flags)
1538 return w32_spawn_process(mode, prog, argv, -1, -1, -1, flags, filecp());
1543rb_w32_uaspawn_flags(
int mode,
const char *prog,
char *
const *argv, DWORD flags)
1545 return w32_spawn_process(mode, prog, argv, -1, -1, -1, flags, CP_UTF8);
1550rb_w32_aspawn(
int mode,
const char *prog,
char *
const *argv)
1552 return w32_spawn_process(mode, prog, argv, -1, -1, -1, 0, filecp());
1557rb_w32_uaspawn(
int mode,
const char *prog,
char *
const *argv)
1559 return rb_w32_uaspawn_flags(mode, prog, argv, 0);
1564rb_w32_uspawn_process(
int mode,
const char *prog,
char *
const *argv,
1565 int in_fd,
int out_fd,
int err_fd, DWORD flags)
1567 return w32_spawn_process(mode, prog, argv, in_fd, out_fd, err_fd,
1589insert(
const char *path,
VALUE vinfo,
void *enc)
1595 if (!tmpcurr)
return -1;
1597 tmpcurr->len = strlen(path);
1598 tmpcurr->str =
strdup(path);
1599 if (!tmpcurr->str)
return -1;
1600 tmpcurr->flags |= NTMALLOC;
1602 *tail = &tmpcurr->next;
1611 char buffer[PATH_MAX], *buf = buffer;
1615 if (patt->len >= PATH_MAX)
1616 if (!(buf = malloc(patt->len + 1)))
return 0;
1618 memcpy(buf, patt->str, patt->len);
1619 buf[patt->len] =
'\0';
1620 translate_char(buf,
'\\',
'/', cp);
1621 status = ruby_brace_glob_with_enc(buf, 0, insert, (
VALUE)&tail, enc);
1625 if (status || last == tail)
return 0;
1626 if (patt->flags & NTMALLOC)
1639has_redirection(
const char *cmd, UINT cp)
1649 for (ptr = cmd; *ptr;) {
1655 else if (quote == *ptr)
1671 if (*++ptr !=
'_' && !
ISALPHA(*ptr))
break;
1672 while (*++ptr ==
'_' ||
ISALNUM(*ptr));
1673 if (*ptr && *ptr++ ==
'%')
return TRUE;
1679 ptr = CharNextExA(cp, ptr, 0);
1687static inline WCHAR *
1688skipspace(WCHAR *ptr)
1697w32_cmdvector(
const WCHAR *cmd,
char ***vec, UINT cp,
rb_encoding *enc)
1700 int elements, strsz, done;
1701 int slashes, escape;
1702 WCHAR *ptr, *base, *cmdline;
1703 char *cptr, *buffer;
1719 ptr = cmdline = wcsdup(cmd);
1730 while (*(ptr = skipspace(ptr))) {
1732 quote = slashes = globbing = escape = 0;
1733 for (done = 0; !done && *ptr; ) {
1742 if (quote != L
'\'') slashes++;
1783 if (!(slashes & 1)) {
1786 else if (quote == *ptr) {
1787 if (quote == L
'"' && quote == ptr[1])
1797 ptr = CharNextW(ptr);
1820 slashes = quote = 0;
1821 while (p < base +
len) {
1825 if (quote != L
'\'') slashes++;
1830 if (!(slashes & 1) && quote && quote != c) {
1835 memcpy(p - ((slashes + 1) >> 1), p + (~slashes & 1),
1836 sizeof(WCHAR) * (base +
len - p));
1837 len -= ((slashes + 1) >> 1) + (~slashes & 1);
1838 p -= (slashes + 1) >> 1;
1839 if (!(slashes & 1)) {
1841 if (quote == L
'"' && quote == *p)
1862 if (!curr)
goto do_nothing;
1863 curr->str = rb_w32_wstr_to_mbstr(cp, base,
len, &curr->len);
1864 curr->flags |= NTMALLOC;
1866 if (globbing && (tail = cmdglob(curr, cmdtail, cp, enc))) {
1871 cmdtail = &curr->next;
1881 for (elements = 0, strsz = 0, curr = cmdhead; curr; curr = curr->next) {
1883 strsz += (curr->len + 1);
1886 len = (elements+1)*
sizeof(
char *) + strsz;
1887 buffer = (
char *)malloc(
len);
1890 while ((curr = cmdhead) != 0) {
1891 cmdhead = curr->next;
1892 if (curr->flags & NTMALLOC) free(curr->str);
1896 for (vptr = *vec; *vptr; ++vptr);
1912 vptr = (
char **) buffer;
1914 cptr = buffer + (elements+1) *
sizeof(
char *);
1916 while ((curr = cmdhead) != 0) {
1917 memcpy(cptr, curr->str, curr->len);
1918 cptr[curr->len] =
'\0';
1920 cptr += curr->len + 1;
1921 cmdhead = curr->next;
1922 if (curr->flags & NTMALLOC) free(curr->str);
1927 *vec = (
char **) buffer;
1939open_special(
const WCHAR *path, DWORD access, DWORD flags)
1941 const DWORD share_mode =
1942 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1943 return CreateFileW(path, access, share_mode, NULL, OPEN_EXISTING,
1944 FILE_FLAG_BACKUP_SEMANTICS|flags, NULL);
1954#define GetBit(bits, i) ((bits)[(i) / CHAR_BIT] & (1 << (i) % CHAR_BIT))
1955#define SetBit(bits, i) ((bits)[(i) / CHAR_BIT] |= (1 << (i) % CHAR_BIT))
1957#define BitOfIsDir(n) ((n) * 2)
1958#define BitOfIsRep(n) ((n) * 2 + 1)
1959#define DIRENT_PER_CHAR (CHAR_BIT / 2)
1961static const WCHAR namespace_prefix[] = {L
'\\', L
'\\', L
'?', L
'\\'};
1967get_handle_pathname(HANDLE fh, WCHAR **pathptr, DWORD add)
1969 DWORD
len = GetFinalPathNameByHandleW(fh, NULL, 0, 0);
1971 WCHAR *path = malloc((
len + add + 1) *
sizeof(WCHAR));
1972 if (!(*pathptr = path))
return 0;
1973 len = GetFinalPathNameByHandleW(fh, path,
len + 1, 0);
1983open_dir_handle(
const WCHAR *filename, WIN32_FIND_DATAW *fd)
1987 WCHAR *fullname = 0;
1995 fh = open_special(filename, 0, 0);
1996 if (fh != INVALID_HANDLE_VALUE) {
1997 len = get_handle_pathname(fh, &fullname, wildcard_len);
2001 len = lstrlenW(filename);
2002 fullname = malloc((
len + wildcard_len + 1) *
sizeof(WCHAR));
2003 if (!fullname)
return INVALID_HANDLE_VALUE;
2009 p = &fullname[
len-1];
2010 if (!(isdirsep(*p) || *p == L
':')) *++p = L
'\\';
2017 fh = FindFirstFileW(fullname, fd);
2018 if (fh == INVALID_HANDLE_VALUE) {
2019 errno = map_errno(GetLastError());
2027w32_wopendir(
const WCHAR *wpath)
2030 WIN32_FIND_DATAW fd;
2043 if (wstati128(wpath, &sbuf, FALSE) < 0) {
2046 if (!(sbuf.st_mode & S_IFDIR) &&
2047 (!
ISALPHA(wpath[0]) || wpath[1] != L
':' || wpath[2] != L
'\0' ||
2048 ((1 << ((wpath[0] & 0x5f) -
'A')) & GetLogicalDrives()) == 0)) {
2052 fh = open_dir_handle(wpath, &fd);
2053 if (fh == INVALID_HANDLE_VALUE) {
2060 p = calloc(1,
sizeof(
DIR));
2064 pathlen = lstrlenW(wpath);
2074 len = lstrlenW(fd.cFileName) + 1;
2075 altlen = lstrlenW(fd.cAlternateFileName) + 1;
2081 tmpW = realloc(p->start, (idx +
len + altlen) *
sizeof(WCHAR));
2091 memcpy(&p->start[idx], fd.cFileName,
len *
sizeof(WCHAR));
2092 memcpy(&p->start[idx +
len], fd.cAlternateFileName, altlen *
sizeof(WCHAR));
2094 if (p->nfiles % DIRENT_PER_CHAR == 0) {
2095 tmp = realloc(p->bits, p->nfiles / DIRENT_PER_CHAR + 1);
2099 p->bits[p->nfiles / DIRENT_PER_CHAR] = 0;
2101 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
2102 SetBit(p->bits, BitOfIsDir(p->nfiles));
2103 if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2104 WCHAR *tmppath = malloc((pathlen +
len + 1) *
sizeof(WCHAR));
2105 memcpy(tmppath, wpath, pathlen *
sizeof(WCHAR));
2106 tmppath[pathlen] = L
'\\';
2107 memcpy(tmppath + pathlen + 1, fd.cFileName,
len *
sizeof(WCHAR));
2108 if (rb_w32_reparse_symlink_p(tmppath))
2109 SetBit(p->bits, BitOfIsRep(p->nfiles));
2114 idx +=
len + altlen;
2115 }
while (FindNextFileW(fh, &fd));
2126 UINT cp = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
2132rb_w32_wstr_to_mbstr(UINT cp,
const WCHAR *wstr,
int clen,
long *plen)
2135 int len = WideCharToMultiByte(cp, 0, wstr, clen, NULL, 0, NULL, NULL);
2136 if (!(ptr = malloc(
len)))
return 0;
2137 WideCharToMultiByte(cp, 0, wstr, clen, ptr,
len, NULL, NULL);
2140 if (clen == -1) --
len;
2148rb_w32_mbstr_to_wstr(UINT cp,
const char *str,
int clen,
long *plen)
2151 int len = MultiByteToWideChar(cp, 0, str, clen, NULL, 0);
2152 if (!(ptr = malloc(
sizeof(WCHAR) *
len)))
return 0;
2153 MultiByteToWideChar(cp, 0, str, clen, ptr,
len);
2156 if (clen == -1) --
len;
2164rb_w32_opendir(
const char *filename)
2167 WCHAR *wpath = filecp_to_wstr(filename, NULL);
2170 ret = w32_wopendir(wpath);
2177rb_w32_uopendir(
const char *filename)
2180 WCHAR *wpath = utf8_to_wstr(filename, NULL);
2183 ret = w32_wopendir(wpath);
2194move_to_next_entry(
DIR *dirp)
2198 dirp->curr += lstrlenW(dirp->curr) + 1;
2199 dirp->curr += lstrlenW(dirp->curr) + 1;
2200 if (dirp->curr >= (dirp->start + dirp->size)) {
2212win32_direct_conv(
const WCHAR *file,
const WCHAR *alt,
struct direct *entry,
const void *enc)
2214 UINT cp = *((UINT *)enc);
2215 if (!(entry->d_name = wstr_to_mbstr(cp, file, -1, &entry->d_namlen)))
2219 entry->d_altname = wstr_to_mbstr(cp, alt, -1, &altlen);
2220 entry->d_altlen = altlen;
2227rb_w32_conv_from_wchar(
const WCHAR *wstr,
rb_encoding *enc)
2230 long len = lstrlenW(wstr);
2231 int encindex = rb_enc_to_index(enc);
2233 if (encindex == ENCINDEX_UTF_16LE) {
2234 return rb_enc_str_new((
char *)wstr,
len *
sizeof(WCHAR), enc);
2237#if SIZEOF_INT < SIZEOF_LONG
2238# error long should equal to int on Windows
2241 len = WideCharToMultiByte(CP_UTF8, 0, wstr, clen, NULL, 0, NULL, NULL);
2242 src = rb_enc_str_new(0,
len, rb_enc_from_index(ENCINDEX_UTF_8));
2243 WideCharToMultiByte(CP_UTF8, 0, wstr, clen, RSTRING_PTR(src),
len, NULL, NULL);
2246 case ENCINDEX_ASCII_8BIT:
2247 case ENCINDEX_US_ASCII:
2249 case ENCINDEX_UTF_8:
2258rb_w32_conv_from_wstr(
const WCHAR *wstr,
long *lenp,
rb_encoding *enc)
2260 VALUE str = rb_w32_conv_from_wchar(wstr, enc);
2264 if (
NIL_P(str))
return wstr_to_utf8(wstr, lenp);
2265 *lenp =
len = RSTRING_LEN(str);
2266 memcpy(ptr = malloc(
len + 1), RSTRING_PTR(str),
len);
2273ruby_direct_conv(
const WCHAR *file,
const WCHAR *alt,
struct direct *entry,
const void *enc)
2275 if (!(entry->d_name = rb_w32_conv_from_wstr(file, &entry->d_namlen, enc)))
2279 entry->d_altname = rb_w32_conv_from_wstr(alt, &altlen, enc);
2280 entry->d_altlen = altlen;
2287readdir_internal(
DIR *dirp, BOOL (*conv)(
const WCHAR *,
const WCHAR *,
struct direct *,
const void *),
const void *enc)
2289 static long dummy_ino = 0;
2296 free(dirp->dirstr.d_name);
2297 free(dirp->dirstr.d_altname);
2298 dirp->dirstr.d_altname = 0;
2299 dirp->dirstr.d_altlen = 0;
2300 conv(dirp->curr, dirp->curr + lstrlenW(dirp->curr) + 1, &dirp->dirstr, enc);
2305 dirp->dirstr.d_ino = (ino_t)(InterlockedIncrement(&dummy_ino) - 1);
2311 if (GetBit(dirp->bits, BitOfIsRep(dirp->loc)))
2312 dirp->dirstr.d_type = DT_LNK;
2313 else if (GetBit(dirp->bits, BitOfIsDir(dirp->loc)))
2314 dirp->dirstr.d_type = DT_DIR;
2316 dirp->dirstr.d_type = DT_REG;
2322 move_to_next_entry(dirp);
2324 return &(dirp->dirstr);
2335 int idx = rb_enc_to_index(enc);
2336 if (idx == ENCINDEX_ASCII_8BIT) {
2337 const UINT cp = filecp();
2338 return readdir_internal(dirp, win32_direct_conv, &cp);
2340 else if (idx == ENCINDEX_UTF_8) {
2341 const UINT cp = CP_UTF8;
2342 return readdir_internal(dirp, win32_direct_conv, &cp);
2345 return readdir_internal(dirp, ruby_direct_conv, enc);
2350rb_w32_ureaddir(
DIR *dirp)
2352 const UINT cp = CP_UTF8;
2353 return readdir_internal(dirp, win32_direct_conv, &cp);
2362rb_w32_telldir(
DIR *dirp)
2373rb_w32_seekdir(
DIR *dirp,
long loc)
2375 if (dirp->loc > loc) rb_w32_rewinddir(dirp);
2377 while (dirp->curr && dirp->loc < loc) {
2378 move_to_next_entry(dirp);
2388rb_w32_rewinddir(
DIR *dirp)
2390 dirp->curr = dirp->start;
2400rb_w32_closedir(
DIR *dirp)
2403 free(dirp->dirstr.d_name);
2404 free(dirp->dirstr.d_altname);
2426 CRITICAL_SECTION _lock;
2428#define FILE_COUNT(stream) ((vcruntime_file*)stream)->_cnt
2429#define FILE_READPTR(stream) ((vcruntime_file*)stream)->_ptr
2430#define FILE_FILENO(stream) ((vcruntime_file*)stream)->_file
2433typedef char lowio_text_mode;
2434typedef char lowio_pipe_lookahead[3];
2437 CRITICAL_SECTION lock;
2440 unsigned char osfile;
2441 lowio_text_mode textmode;
2442 lowio_pipe_lookahead _pipe_lookahead;
2444 uint8_t unicode : 1;
2445 uint8_t utf8translations : 1;
2446 uint8_t dbcsBufferUsed : 1;
2450#if !defined _CRTIMP || defined __MINGW32__
2452#define _CRTIMP __declspec(dllimport)
2455static ioinfo ** __pioinfo = NULL;
2457static inline ioinfo* _pioinfo(
int);
2460#define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
2461#define _osfhnd(i) (_pioinfo(i)->osfhnd)
2462#define _osfile(i) (_pioinfo(i)->osfile)
2463#define rb_acrt_lowio_lock_fh(i) EnterCriticalSection(&_pioinfo(i)->lock)
2464#define rb_acrt_lowio_unlock_fh(i) LeaveCriticalSection(&_pioinfo(i)->lock)
2466static size_t pioinfo_extra = 0;
2470set_pioinfo_extra(
void)
2472#define FUNCTION_RET 0xc3
2474# define UCRTBASE "ucrtbased.dll"
2476# define UCRTBASE "ucrtbase.dll"
2491 char *p = (
char*)get_proc_address(UCRTBASE,
"_isatty", NULL);
2494#if defined(_M_ARM64) || defined(__aarch64__)
2495#define IS_INSN(pc, name) ((*(pc) & name##_mask) == name##_id)
2496 const int max_num_inst = 500;
2497 uint32_t *start = (uint32_t*)p;
2498 uint32_t *end_limit = (start + max_num_inst);
2499 uint32_t *pc = start;
2502 fprintf(stderr,
"_isatty proc not found in " UCRTBASE
"\n");
2507 const uint32_t ret_id = 0xd65f0000;
2508 const uint32_t ret_mask = 0xfffffc1f;
2509 for(; pc < end_limit; pc++) {
2510 if (IS_INSN(pc, ret)) {
2514 if (pc == end_limit) {
2515 fprintf(stderr,
"end of _isatty not found in " UCRTBASE
"\n");
2520 const uint32_t adrp_id = 0x90000000;
2521 const uint32_t adrp_mask = 0x9f000000;
2522 const uint32_t add_id = 0x11000000;
2523 const uint32_t add_mask = 0x7fc00000;
2524 for(; pc > start; pc--) {
2525 if (IS_INSN(pc, adrp) && IS_INSN(pc + 1, add)) {
2530 fprintf(stderr,
"pioinfo mark not found in " UCRTBASE
"\n");
2540 const uint32_t adrp_insn = *pc;
2541 const uint32_t adrp_immhi = (adrp_insn & 0x00ffffe0) >> 5;
2542 const uint32_t adrp_immlo = (adrp_insn & 0x60000000) >> (5 + 19 + 5);
2543 const int64_t adrp_sign = (adrp_insn & 0x00800000) ? ~0x001fffff : 0;
2545 const int64_t adrp_imm = (adrp_sign | (adrp_immhi << 2) | adrp_immlo) << 12;
2547 const uint64_t adrp_base = (uint64_t)pc & 0xfffffffffffff000;
2549 const uint32_t add_insn = *(pc + 1);
2550 const uint64_t add_imm = (add_insn & 0x3ffc00) >> (5 + 5);
2552 __pioinfo = (
ioinfo**)(adrp_base + adrp_imm + add_imm);
2560# define FUNCTION_BEFORE_RET_MARK "\x48\x83\xc4"
2561# define FUNCTION_SKIP_BYTES 1
2564# define PIOINFO_MARK "\x48\x8d\x0d"
2567# define PIOINFO_MARK "\x48\x8d\x15"
2572# define FUNCTION_BEFORE_RET_MARK "\x5d"
2574# define FUNCTION_BEFORE_RET_MARK_2 "\xc9"
2575# define FUNCTION_SKIP_BYTES 0
2577# define PIOINFO_MARK "\x8B\x04\x85"
2580 for (pend += 10; pend < p + 500; pend++) {
2582 if ((memcmp(pend, FUNCTION_BEFORE_RET_MARK,
sizeof(FUNCTION_BEFORE_RET_MARK) - 1) == 0
2583# ifdef FUNCTION_BEFORE_RET_MARK_2
2584 || memcmp(pend, FUNCTION_BEFORE_RET_MARK_2,
sizeof(FUNCTION_BEFORE_RET_MARK_2) - 1) == 0
2587 *(pend + (
sizeof(FUNCTION_BEFORE_RET_MARK) - 1) + FUNCTION_SKIP_BYTES) == (
char)FUNCTION_RET) {
2589 for (pend -= (
sizeof(PIOINFO_MARK) - 1); pend > p; pend--) {
2590 if (memcmp(pend, PIOINFO_MARK,
sizeof(PIOINFO_MARK) - 1) == 0) {
2599 fprintf(stderr,
"unexpected " UCRTBASE
"\n");
2603 p +=
sizeof(PIOINFO_MARK) - 1;
2605 rel = *(int32_t*)(p);
2606 rip = p +
sizeof(int32_t);
2607 __pioinfo = (
ioinfo**)(rip + rel);
2609 __pioinfo = *(
ioinfo***)(p);
2614 fd = _open(
"NUL", O_RDONLY);
2615 for (pioinfo_extra = 0; pioinfo_extra <= 64; pioinfo_extra +=
sizeof(
void *)) {
2616 if (_osfhnd(fd) == _get_osfhandle(fd)) {
2622 if (pioinfo_extra > 64) {
2631 const size_t sizeof_ioinfo =
sizeof(
ioinfo) + pioinfo_extra;
2632 return (
ioinfo*)((
char*)__pioinfo[fd >> IOINFO_L2E] +
2633 (fd & (IOINFO_ARRAY_ELTS - 1)) * sizeof_ioinfo);
2636#define _set_osfhnd(fh, osfh) (void)(_osfhnd(fh) = osfh)
2637#define _set_osflags(fh, flags) (_osfile(fh) = (flags))
2642#define FNOINHERIT 0x10
2647static int is_socket(SOCKET);
2648static int is_console(SOCKET);
2652rb_w32_io_cancelable_p(
int fd)
2654 return is_socket(TO_SOCKET(fd)) || !is_console(TO_SOCKET(fd));
2659rb_w32_open_osfhandle(intptr_t osfhandle,
int flags)
2668 if (flags & O_APPEND)
2669 fileflags |= FAPPEND;
2674 if (flags & O_NOINHERIT)
2675 fileflags |= FNOINHERIT;
2678 hF = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
2679 fh = _open_osfhandle((intptr_t)hF, 0);
2687 rb_acrt_lowio_lock_fh(fh);
2689 _set_osfhnd(fh, osfhandle);
2693 _set_osflags(fh, fileflags);
2694 rb_acrt_lowio_unlock_fh(fh);
2705#define open_null(fd) \
2707 (nullfd = open("NUL", O_RDWR)) : 0), \
2708 ((nullfd == (fd)) ? (keep = 1) : dup2(nullfd, fd)), \
2711 if (fileno(stdin) < 0) {
2712 FILE_FILENO(stdin) = open_null(0);
2715 setmode(fileno(stdin), O_BINARY);
2717 if (fileno(stdout) < 0) {
2718 FILE_FILENO(stdout) = open_null(1);
2720 if (fileno(stderr) < 0) {
2721 FILE_FILENO(stderr) = open_null(2);
2723 if (nullfd >= 0 && !keep) close(nullfd);
2724 setvbuf(stderr, NULL, _IONBF, 0);
2727 HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
2729 if (GetConsoleMode(h, &m)) {
2730#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
2731#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x4
2733 SetConsoleMode(h, m | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
2742is_socket(SOCKET sock)
2744 if (socklist_lookup(sock, NULL))
2752rb_w32_is_socket(
int fd)
2754 return is_socket(TO_SOCKET(fd));
2767rb_w32_strerror(
int e)
2769 static char buffer[512];
2774 strlcpy(buffer,
"Unknown Error",
sizeof(buffer));
2775 else if (e > sys_nerr) {
2776#if WSAEWOULDBLOCK != EWOULDBLOCK
2777 if (e >= EADDRINUSE && e <= EWOULDBLOCK) {
2781 for (s = 0; s < (int)(
sizeof(errmap)/
sizeof(*errmap)); s++)
2782 if (errmap[s].winerr == WSAEWOULDBLOCK)
2784 for (i = s; i < (int)(
sizeof(errmap)/
sizeof(*errmap)); i++)
2785 if (errmap[i].err == e) {
2786 e = errmap[i].winerr;
2791 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2792 FORMAT_MESSAGE_IGNORE_INSERTS, &source, e,
2793 MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
2794 buffer,
sizeof(buffer), NULL) == 0 &&
2795 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2796 FORMAT_MESSAGE_IGNORE_INSERTS, &source, e, 0,
2797 buffer,
sizeof(buffer), NULL) == 0)
2798 strlcpy(buffer,
"Unknown Error",
sizeof(buffer));
2801 strlcpy(buffer, strerror(e),
sizeof(buffer));
2804 while ((p = strpbrk(p,
"\r\n")) != NULL) {
2805 memmove(p, p + 1, strlen(p));
2856 return (uid == ROOT_UID ? 0 : -1);
2863 return (gid == ROOT_GID ? 0 : -1);
2872ioctl(
int i,
int u, ...)
2879rb_w32_fdset(
int fd, fd_set *set)
2888rb_w32_fdclr(
int fd, fd_set *set)
2891 SOCKET s = TO_SOCKET(fd);
2893 for (i = 0; i < set->fd_count; i++) {
2894 if (set->fd_array[i] == s) {
2895 memmove(&set->fd_array[i], &set->fd_array[i+1],
2896 sizeof(set->fd_array[0]) * (--set->fd_count - i));
2906rb_w32_fdisset(
int fd, fd_set *set)
2909 SOCKET s = TO_SOCKET(fd);
2910 if (s == (SOCKET)INVALID_HANDLE_VALUE)
2912 RUBY_CRITICAL {ret = __WSAFDIsSet(s, set);}
2920 max = min(src->fd_count, (UINT)max);
2921 if ((UINT)dst->
capa < (UINT)max) {
2922 dst->
capa = (src->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2926 memcpy(dst->
fdset->fd_array, src->fd_array,
2927 max *
sizeof(src->fd_array[0]));
2928 dst->
fdset->fd_count = src->fd_count;
2935 if ((UINT)dst->
capa < src->
fdset->fd_count) {
2936 dst->
capa = (src->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2940 memcpy(dst->
fdset->fd_array, src->
fdset->fd_array,
2941 src->
fdset->fd_count *
sizeof(src->
fdset->fd_array[0]));
2955extract_fd(
rb_fdset_t *dst, fd_set *src,
int (*func)(SOCKET))
2961 while (s < src->fd_count) {
2962 SOCKET fd = src->fd_array[s];
2964 if (!func || (*func)(fd)) {
2968 for (d = 0; d < dst->
fdset->fd_count; d++) {
2969 if (dst->
fdset->fd_array[d] == fd)
2972 if (d == dst->
fdset->fd_count) {
2973 if ((
int)dst->
fdset->fd_count >= dst->
capa) {
2974 dst->
capa = (dst->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2977 dst->
fdset->fd_array[dst->
fdset->fd_count++] = fd;
2981 &src->fd_array[s+1],
2982 sizeof(src->fd_array[0]) * (--src->fd_count - s));
2992 return dst ? dst->
fdset->fd_count : m;
2997copy_fd(fd_set *dst, fd_set *src)
3000 if (!src || !dst)
return 0;
3002 for (s = 0; s < src->fd_count; ++s) {
3003 SOCKET fd = src->fd_array[s];
3005 for (d = 0; d < dst->fd_count; ++d) {
3006 if (dst->fd_array[d] == fd)
3009 if (d == dst->fd_count) {
3010 dst->fd_array[dst->fd_count++] = fd;
3014 return dst->fd_count;
3019save_fd(SOCKET *dst,
const fd_set *src)
3021 if (src) memcpy(dst, src->fd_array, src->fd_count *
sizeof(SOCKET));
3026restore_fd(fd_set *dst,
const SOCKET *src, UINT count)
3029 memcpy(dst->fd_array, src, count *
sizeof(SOCKET));
3030 dst->fd_count = count;
3035is_not_socket(SOCKET sock)
3037 return !is_socket(sock);
3047 ret = (GetFileType((HANDLE)sock) == FILE_TYPE_PIPE);
3055is_readable_pipe(SOCKET sock)
3061 if (PeekNamedPipe((HANDLE)sock, NULL, 0, NULL, &n, NULL)) {
3065 ret = (GetLastError() == ERROR_BROKEN_PIPE);
3074is_console(SOCKET sock)
3081 ret = (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n));
3089is_readable_console(SOCKET sock)
3096 if (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n) && n > 0) {
3097 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
3098 ir.Event.KeyEvent.uChar.UnicodeChar) {
3101 else if (ir.EventType == KEY_EVENT && !ir.Event.KeyEvent.bKeyDown &&
3102 ir.Event.KeyEvent.wVirtualKeyCode == VK_MENU &&
3103 ir.Event.KeyEvent.uChar.UnicodeChar) {
3107 ReadConsoleInputW((HANDLE)sock, &ir, 1, &n);
3117is_invalid_handle(SOCKET sock)
3119 return (HANDLE)sock == INVALID_HANDLE_VALUE;
3124do_select(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3131 rb_w32_sleep(timeout->tv_sec * 1000 + timeout->tv_usec / 1000);
3133 rb_w32_sleep(INFINITE);
3137 thread_exclusive(select) {
3138 r = select(nfds, rd, wr, ex, timeout);
3140 if (r == SOCKET_ERROR) {
3141 errno = map_errno(WSAGetLastError());
3156rb_w32_time_subtract(
struct timeval *rest,
const struct timeval *wait)
3158 if (rest->tv_sec < wait->tv_sec) {
3161 while (rest->tv_usec < wait->tv_usec) {
3162 if (rest->tv_sec <= wait->tv_sec) {
3166 rest->tv_usec += 1000 * 1000;
3168 rest->tv_sec -= wait->tv_sec;
3169 rest->tv_usec -= wait->tv_usec;
3170 return rest->tv_sec != 0 || rest->tv_usec != 0;
3177 if (t1->tv_sec < t2->tv_sec)
3179 if (t1->tv_sec > t2->tv_sec)
3181 if (t1->tv_usec < t2->tv_usec)
3183 if (t1->tv_usec > t2->tv_usec)
3190int rb_w32_check_interrupt(
void *);
3195rb_w32_select_with_thread(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3196 struct timeval *timeout,
void *th)
3205 struct timeval limit = {0, 0};
3207 if (nfds < 0 || (timeout && (timeout->tv_sec < 0 || timeout->tv_usec < 0))) {
3213 if (timeout->tv_sec < 0 ||
3214 timeout->tv_usec < 0 ||
3215 timeout->tv_usec >= 1000000) {
3219 gettimeofday(&limit, NULL);
3220 limit.tv_sec += timeout->tv_sec;
3221 limit.tv_usec += timeout->tv_usec;
3222 if (limit.tv_usec >= 1000000) {
3223 limit.tv_usec -= 1000000;
3235 nonsock += extract_fd(&else_rd, rd, is_not_socket);
3238 nonsock += extract_fd(&else_wr, wr, is_not_socket);
3241 if (extract_fd(NULL, else_rd.
fdset, is_invalid_handle) > 0 ||
3242 extract_fd(NULL, else_wr.
fdset, is_invalid_handle) > 0) {
3250 extract_fd(&pipe_rd, else_rd.
fdset, is_pipe);
3253 extract_fd(&cons_rd, else_rd.
fdset, is_console);
3256 extract_fd(&except, ex, is_not_socket);
3259 if (rd && (
int)rd->fd_count > r) r = (int)rd->fd_count;
3260 if (wr && (
int)wr->fd_count > r) r = (int)wr->fd_count;
3261 if (ex && (
int)ex->fd_count > r) r = (int)ex->fd_count;
3262 if (nfds > r) nfds = r;
3266 const struct timeval wait = {0, 10 * 1000};
3269 UINT nrd = rd ? rd->fd_count : 0;
3270 UINT nwr = wr ? wr->fd_count : 0;
3271 UINT nex = ex ? ex->fd_count : 0;
3272 SOCKET *orig =
ALLOC_N(SOCKET, nrd + nwr + nex);
3275 save_fd(orig + nrd, wr);
3276 save_fd(orig + nrd + nwr, ex);
3278 if (th && rb_w32_check_interrupt(th) != WAIT_TIMEOUT) {
3285 extract_fd(&else_rd, pipe_rd.
fdset, is_readable_pipe);
3286 extract_fd(&else_rd, cons_rd.
fdset, is_readable_console);
3289 if (else_rd.
fdset->fd_count || else_wr.
fdset->fd_count) {
3290 r = do_select(nfds, rd, wr, ex, &zero);
3293 r += copy_fd(rd, else_rd.
fdset);
3294 r += copy_fd(wr, else_wr.
fdset);
3300 const struct timeval *dowait = &wait;
3302 r = do_select(nfds, rd, wr, ex, &zero);
3307 gettimeofday(&now, NULL);
3309 if (!rb_w32_time_subtract(&rest, &now))
break;
3310 if (compare(&rest, &wait) < 0) dowait = &rest;
3312 restore_fd(rd, orig, nrd);
3313 restore_fd(wr, orig + nrd, nwr);
3314 restore_fd(ex, orig + nrd + nwr, nex);
3315 Sleep(dowait->tv_sec * 1000 + (dowait->tv_usec + 999) / 1000);
3318 ruby_xfree_sized(orig,
sizeof(SOCKET) * (nrd + nwr + nex));
3332rb_w32_select(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3335 return rb_w32_select_with_thread(nfds, rd, wr, ex, timeout, 0);
3340get_wsa_extension_function(SOCKET s, GUID guid)
3345 WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid,
sizeof(guid),
3346 &ptr,
sizeof(ptr), &dmy, NULL, NULL);
3356rb_w32_accept(
int s,
struct sockaddr *addr,
int *addrlen)
3362 r = accept(TO_SOCKET(s), addr, addrlen);
3363 if (r != INVALID_SOCKET) {
3364 SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0);
3365 fd = rb_w32_open_osfhandle((intptr_t)r, O_RDWR|O_BINARY|O_NOINHERIT);
3367 socklist_insert(r, 0);
3372 errno = map_errno(WSAGetLastError());
3383rb_w32_bind(
int s,
const struct sockaddr *addr,
int addrlen)
3388 r = bind(TO_SOCKET(s), addr, addrlen);
3389 if (r == SOCKET_ERROR)
3390 errno = map_errno(WSAGetLastError());
3399rb_w32_connect(
int s,
const struct sockaddr *addr,
int addrlen)
3403 r = connect(TO_SOCKET(s), addr, addrlen);
3404 if (r == SOCKET_ERROR) {
3405 int err = WSAGetLastError();
3406 if (err != WSAEWOULDBLOCK)
3407 errno = map_errno(err);
3409 errno = EINPROGRESS;
3420rb_w32_getpeername(
int s,
struct sockaddr *addr,
int *addrlen)
3424 r = getpeername(TO_SOCKET(s), addr, addrlen);
3425 if (r == SOCKET_ERROR)
3426 errno = map_errno(WSAGetLastError());
3435rb_w32_getsockname(
int fd,
struct sockaddr *addr,
int *addrlen)
3440 sock = TO_SOCKET(fd);
3441 r = getsockname(sock, addr, addrlen);
3442 if (r == SOCKET_ERROR) {
3443 DWORD wsaerror = WSAGetLastError();
3444 if (wsaerror == WSAEINVAL) {
3446 if (socklist_lookup(sock, &flags)) {
3447 int af = GET_FAMILY(flags);
3449 memset(addr, 0, *addrlen);
3450 addr->sa_family = af;
3455 errno = map_errno(wsaerror);
3465rb_w32_getsockopt(
int s,
int level,
int optname,
char *optval,
int *optlen)
3469 r = getsockopt(TO_SOCKET(s), level, optname, optval, optlen);
3470 if (r == SOCKET_ERROR)
3471 errno = map_errno(WSAGetLastError());
3475 if (r == 0 && level == SOL_SOCKET && optname == SO_ERROR &&
3476 *optlen == (
int)
sizeof(
int)) {
3478 memcpy(&sockerr, optval,
sizeof(sockerr));
3479 sockerr = map_errno(sockerr);
3480 memcpy(optval, &sockerr,
sizeof(sockerr));
3489rb_w32_ioctlsocket(
int s,
long cmd, u_long *argp)
3493 r = ioctlsocket(TO_SOCKET(s), cmd, argp);
3494 if (r == SOCKET_ERROR)
3495 errno = map_errno(WSAGetLastError());
3504rb_w32_listen(
int s,
int backlog)
3508 r = listen(TO_SOCKET(s), backlog);
3509 if (r == SOCKET_ERROR)
3510 errno = map_errno(WSAGetLastError());
3522finish_overlapped_socket(BOOL input, SOCKET s, WSAOVERLAPPED *wol,
int result, DWORD *
len, DWORD size)
3527 if (result != SOCKET_ERROR)
3529 else if ((err = WSAGetLastError()) == WSA_IO_PENDING) {
3530 switch (rb_w32_wait_events_blocking(&wol->hEvent, 1, INFINITE)) {
3533 result = WSAGetOverlappedResult(s, wol, &size, TRUE, &flg);
3540 result = SOCKET_ERROR;
3543 if ((err = WSAGetLastError()) == WSAECONNABORTED && !input)
3545 else if (err == WSAEMSGSIZE && input) {
3551 errno = map_errno(err);
3553 case WAIT_OBJECT_0 + 1:
3556 CancelIo((HANDLE)s);
3561 if (err == WSAECONNABORTED && !input)
3564 errno = map_errno(err);
3567 CloseHandle(wol->hEvent);
3574overlapped_socket_io(BOOL input,
int fd,
char *buf,
int len,
int flags,
3575 struct sockaddr *addr,
int *addrlen)
3586 socklist_lookup(s, &mode);
3587 if (GET_FLAGS(mode) & O_NONBLOCK) {
3590 if (addr && addrlen)
3591 r = recvfrom(s, buf,
len, flags, addr, addrlen);
3593 r = recv(s, buf,
len, flags);
3594 if (r == SOCKET_ERROR)
3595 errno = map_errno(WSAGetLastError());
3598 if (addr && addrlen)
3599 r = sendto(s, buf,
len, flags, addr, *addrlen);
3601 r = send(s, buf,
len, flags);
3602 if (r == SOCKET_ERROR) {
3603 DWORD err = WSAGetLastError();
3604 if (err == WSAECONNABORTED)
3607 errno = map_errno(err);
3617 memset(&wol, 0,
sizeof(wol));
3619 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3622 if (addr && addrlen)
3623 ret = WSARecvFrom(s, &wbuf, 1, &size, &flg, addr, addrlen,
3626 ret = WSARecv(s, &wbuf, 1, &size, &flg, &wol, NULL);
3629 if (addr && addrlen)
3630 ret = WSASendTo(s, &wbuf, 1, &size, flags, addr, *addrlen,
3633 ret = WSASend(s, &wbuf, 1, &size, flags, &wol, NULL);
3637 finish_overlapped_socket(input, s, &wol, ret, &rlen, size);
3646rb_w32_recv(
int fd,
char *buf,
int len,
int flags)
3648 return overlapped_socket_io(TRUE, fd, buf,
len, flags, NULL, NULL);
3653rb_w32_recvfrom(
int fd,
char *buf,
int len,
int flags,
3654 struct sockaddr *from,
int *fromlen)
3656 return overlapped_socket_io(TRUE, fd, buf,
len, flags, from, fromlen);
3661rb_w32_send(
int fd,
const char *buf,
int len,
int flags)
3663 return overlapped_socket_io(FALSE, fd, (
char *)buf,
len, flags, NULL, NULL);
3668rb_w32_sendto(
int fd,
const char *buf,
int len,
int flags,
3669 const struct sockaddr *to,
int tolen)
3671 return overlapped_socket_io(FALSE, fd, (
char *)buf,
len, flags,
3672 (
struct sockaddr *)to, &tolen);
3675#if !defined(MSG_TRUNC) && !defined(__MINGW32__)
3681 DWORD dwBufferCount;
3686#ifndef WSAID_WSARECVMSG
3687#define WSAID_WSARECVMSG {0xf689d7c8,0x6f1f,0x436b,{0x8a,0x53,0xe5,0x4f,0xe3,0x51,0xc3,0x22}}
3689#ifndef WSAID_WSASENDMSG
3690#define WSAID_WSASENDMSG {0xa441e712,0x754f,0x43ca,{0x84,0xa7,0x0d,0xee,0x44,0xcf,0x60,0x6d}}
3694#define msghdr_to_wsamsg(msg, wsamsg) \
3697 (wsamsg)->name = (msg)->msg_name; \
3698 (wsamsg)->namelen = (msg)->msg_namelen; \
3699 (wsamsg)->lpBuffers = ALLOCA_N(WSABUF, (msg)->msg_iovlen); \
3700 (wsamsg)->dwBufferCount = (msg)->msg_iovlen; \
3701 for (i = 0; i < (msg)->msg_iovlen; ++i) { \
3702 (wsamsg)->lpBuffers[i].buf = (msg)->msg_iov[i].iov_base; \
3703 (wsamsg)->lpBuffers[i].len = (msg)->msg_iov[i].iov_len; \
3705 (wsamsg)->Control.buf = (msg)->msg_control; \
3706 (wsamsg)->Control.len = (msg)->msg_controllen; \
3707 (wsamsg)->dwFlags = (msg)->msg_flags; \
3712recvmsg(
int fd,
struct msghdr *msg,
int flags)
3714 typedef int (WSAAPI *WSARecvMsg_t)(SOCKET,
WSAMSG *, DWORD *, WSAOVERLAPPED *, LPWSAOVERLAPPED_COMPLETION_ROUTINE);
3715 static WSARecvMsg_t pWSARecvMsg = NULL;
3725 static const GUID guid = WSAID_WSARECVMSG;
3726 pWSARecvMsg = (WSARecvMsg_t)get_wsa_extension_function(s, guid);
3731 msghdr_to_wsamsg(msg, &wsamsg);
3732 wsamsg.dwFlags |= flags;
3734 socklist_lookup(s, &mode);
3735 if (GET_FLAGS(mode) & O_NONBLOCK) {
3737 if ((ret = pWSARecvMsg(s, &wsamsg, &
len, NULL, NULL)) == SOCKET_ERROR) {
3738 errno = map_errno(WSAGetLastError());
3746 memset(&wol, 0,
sizeof(wol));
3748 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3749 ret = pWSARecvMsg(s, &wsamsg, &size, &wol, NULL);
3752 ret = finish_overlapped_socket(TRUE, s, &wol, ret, &
len, size);
3754 if (ret == SOCKET_ERROR)
3758 msg->msg_name = wsamsg.name;
3759 msg->msg_namelen = wsamsg.namelen;
3760 msg->msg_flags = wsamsg.dwFlags;
3767sendmsg(
int fd,
const struct msghdr *msg,
int flags)
3769 typedef int (WSAAPI *WSASendMsg_t)(SOCKET,
const WSAMSG *, DWORD, DWORD *, WSAOVERLAPPED *, LPWSAOVERLAPPED_COMPLETION_ROUTINE);
3770 static WSASendMsg_t pWSASendMsg = NULL;
3780 static const GUID guid = WSAID_WSASENDMSG;
3781 pWSASendMsg = (WSASendMsg_t)get_wsa_extension_function(s, guid);
3786 msghdr_to_wsamsg(msg, &wsamsg);
3788 socklist_lookup(s, &mode);
3789 if (GET_FLAGS(mode) & O_NONBLOCK) {
3791 if ((ret = pWSASendMsg(s, &wsamsg, flags, &
len, NULL, NULL)) == SOCKET_ERROR) {
3792 errno = map_errno(WSAGetLastError());
3800 memset(&wol, 0,
sizeof(wol));
3802 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3803 ret = pWSASendMsg(s, &wsamsg, flags, &size, &wol, NULL);
3806 finish_overlapped_socket(FALSE, s, &wol, ret, &
len, size);
3816rb_w32_setsockopt(
int s,
int level,
int optname,
const char *optval,
int optlen)
3820 r = setsockopt(TO_SOCKET(s), level, optname, optval, optlen);
3821 if (r == SOCKET_ERROR)
3822 errno = map_errno(WSAGetLastError());
3831rb_w32_shutdown(
int s,
int how)
3835 r = shutdown(TO_SOCKET(s), how);
3836 if (r == SOCKET_ERROR)
3837 errno = map_errno(WSAGetLastError());
3844open_ifs_socket(
int af,
int type,
int protocol)
3846 unsigned long proto_buffers_len = 0;
3848 SOCKET out = INVALID_SOCKET;
3850 if (WSAEnumProtocols(NULL, NULL, &proto_buffers_len) == SOCKET_ERROR) {
3851 error_code = WSAGetLastError();
3852 if (error_code == WSAENOBUFS) {
3853 WSAPROTOCOL_INFO *proto_buffers;
3854 int protocols_available = 0;
3856 proto_buffers = (WSAPROTOCOL_INFO *)malloc(proto_buffers_len);
3857 if (!proto_buffers) {
3858 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
3859 return INVALID_SOCKET;
3862 protocols_available =
3863 WSAEnumProtocols(NULL, proto_buffers, &proto_buffers_len);
3864 if (protocols_available != SOCKET_ERROR) {
3866 for (i = 0; i < protocols_available; i++) {
3867 if ((af != AF_UNSPEC && af != proto_buffers[i].iAddressFamily) ||
3868 (
type != proto_buffers[i].iSocketType) ||
3869 (protocol != 0 && protocol != proto_buffers[i].iProtocol))
3872 if ((proto_buffers[i].dwServiceFlags1 & XP1_IFS_HANDLES) == 0)
3875 out = WSASocket(af,
type, protocol, &(proto_buffers[i]), 0,
3876 WSA_FLAG_OVERLAPPED);
3879 if (out == INVALID_SOCKET)
3880 out = WSASocket(af,
type, protocol, NULL, 0, 0);
3881 if (out != INVALID_SOCKET)
3882 SetHandleInformation((HANDLE)out, HANDLE_FLAG_INHERIT, 0);
3885 free(proto_buffers);
3896rb_w32_socket(
int af,
int type,
int protocol)
3902 s = open_ifs_socket(af,
type, protocol);
3903 if (s == INVALID_SOCKET) {
3904 errno = map_errno(WSAGetLastError());
3908 fd = rb_w32_open_osfhandle(s, O_RDWR|O_BINARY|O_NOINHERIT);
3910 socklist_insert(s, MAKE_SOCKDATA(af, 0));
3921struct hostent * WSAAPI
3922rb_w32_gethostbyaddr(
const char *addr,
int len,
int type)
3926 r = gethostbyaddr(addr,
len,
type);
3928 errno = map_errno(WSAGetLastError());
3936struct hostent * WSAAPI
3937rb_w32_gethostbyname(
const char *name)
3941 r = gethostbyname(name);
3943 errno = map_errno(WSAGetLastError());
3952rb_w32_gethostname(
char *name,
int len)
3956 r = gethostname(name,
len);
3957 if (r == SOCKET_ERROR)
3958 errno = map_errno(WSAGetLastError());
3963#undef getprotobyname
3966struct protoent * WSAAPI
3967rb_w32_getprotobyname(
const char *name)
3971 r = getprotobyname(name);
3973 errno = map_errno(WSAGetLastError());
3978#undef getprotobynumber
3981struct protoent * WSAAPI
3982rb_w32_getprotobynumber(
int num)
3986 r = getprotobynumber(num);
3988 errno = map_errno(WSAGetLastError());
3996struct servent * WSAAPI
3997rb_w32_getservbyname(
const char *name,
const char *proto)
4001 r = getservbyname(name, proto);
4003 errno = map_errno(WSAGetLastError());
4011struct servent * WSAAPI
4012rb_w32_getservbyport(
int port,
const char *proto)
4016 r = getservbyport(port, proto);
4018 errno = map_errno(WSAGetLastError());
4027socketpair_unix_path(
struct sockaddr_un *sock_un)
4030 WCHAR wpath[
sizeof(sock_un->sun_path)/
sizeof(*sock_un->sun_path)] = L
"";
4035 listener = socket(AF_UNIX, SOCK_STREAM, 0);
4036 if (listener == INVALID_SOCKET)
4039 memset(sock_un, 0,
sizeof(*sock_un));
4040 sock_un->sun_family = AF_UNIX;
4050 for (
int try = 0; ;
try++) {
4051 LARGE_INTEGER ticks;
4052 size_t path_len = 0;
4053 const size_t maxpath =
sizeof(sock_un->sun_path)/
sizeof(*sock_un->sun_path);
4058 path_len = GetTempPathW(maxpath, wpath);
4059 if (path_len == 0 || path_len > maxpath) {
4068 wcsncpy(wpath, L
"C:/Temp/", maxpath);
4069 path_len = lstrlenW(wpath);
4076 closesocket(listener);
4081 path_len = WideCharToMultiByte(CP_UTF8, 0, wpath, path_len, sock_un->sun_path, maxpath, NULL, NULL);
4082 QueryPerformanceCounter(&ticks);
4083 path_len += snprintf(sock_un->sun_path + path_len,
4087 GetCurrentProcessId());
4090 MultiByteToWideChar(CP_UTF8, 0, sock_un->sun_path, -1, wpath,
sizeof(wpath)/
sizeof(*wpath));
4092 if (bind(listener, (
struct sockaddr *)sock_un,
sizeof(*sock_un)) != SOCKET_ERROR)
4095 closesocket(listener);
4097 return sizeof(*sock_un);
4103socketpair_internal(
int af,
int type,
int protocol, SOCKET *sv)
4105 SOCKET svr = INVALID_SOCKET, r = INVALID_SOCKET, w = INVALID_SOCKET;
4106 struct sockaddr_in sock_in4;
4109 struct sockaddr_in6 sock_in6;
4113 struct sockaddr_un sock_un = {0, {0}};
4114 WCHAR wpath[
sizeof(sock_un.sun_path)/
sizeof(*sock_un.sun_path)] = L
"";
4117 struct sockaddr *addr;
4123#if defined PF_INET && PF_INET != AF_INET
4126 sock_in4.sin_family = AF_INET;
4127 sock_in4.sin_port = 0;
4128 sock_in4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4129 addr = (
struct sockaddr *)&sock_in4;
4130 len =
sizeof(sock_in4);
4134 memset(&sock_in6, 0,
sizeof(sock_in6));
4135 sock_in6.sin6_family = AF_INET6;
4136 sock_in6.sin6_addr = IN6ADDR_LOOPBACK_INIT;
4137 addr = (
struct sockaddr *)&sock_in6;
4138 len =
sizeof(sock_in6);
4143 addr = (
struct sockaddr *)&sock_un;
4144 len = socketpair_unix_path(&sock_un);
4145 MultiByteToWideChar(CP_UTF8, 0, sock_un.sun_path, -1, wpath,
sizeof(wpath)/
sizeof(*wpath));
4151 errno = EAFNOSUPPORT;
4154 if (
type != SOCK_STREAM) {
4159 sv[0] = (SOCKET)INVALID_HANDLE_VALUE;
4160 sv[1] = (SOCKET)INVALID_HANDLE_VALUE;
4163 svr = open_ifs_socket(af,
type, protocol);
4164 if (svr == INVALID_SOCKET)
4166 if (bind(svr, addr,
len) < 0)
4168 if (getsockname(svr, addr, &
len) < 0)
4170 if (
type == SOCK_STREAM)
4173 w = open_ifs_socket(af,
type, protocol);
4174 if (w == INVALID_SOCKET)
4176 if (connect(w, addr,
len) < 0)
4179 r = accept(svr, addr, &
len);
4180 if (r == INVALID_SOCKET)
4182 SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0);
4188 errno = map_errno(WSAGetLastError());
4189 if (r != INVALID_SOCKET)
4191 if (w != INVALID_SOCKET)
4198 if (svr != INVALID_SOCKET)
4201 if (sock_un.sun_family == AF_UNIX)
4211socketpair(
int af,
int type,
int protocol,
int *sv)
4215 if (socketpair_internal(af,
type, protocol, pair) < 0)
4217 sv[0] = rb_w32_open_osfhandle(pair[0], O_RDWR|O_BINARY|O_NOINHERIT);
4219 closesocket(pair[0]);
4220 closesocket(pair[1]);
4223 sv[1] = rb_w32_open_osfhandle(pair[1], O_RDWR|O_BINARY|O_NOINHERIT);
4225 rb_w32_close(sv[0]);
4226 closesocket(pair[1]);
4229 socklist_insert(pair[0], MAKE_SOCKDATA(af, 0));
4230 socklist_insert(pair[1], MAKE_SOCKDATA(af, 0));
4237str2guid(
const char *str, GUID *guid)
4239#define hex2byte(str) \
4240 ((isdigit(*(str)) ? *(str) - '0' : toupper(*(str)) - 'A' + 10) << 4 | (isdigit(*((str) + 1)) ? *((str) + 1) - '0' : toupper(*((str) + 1)) - 'A' + 10))
4243 if (*str ==
'{') str++;
4244 guid->Data1 = (long)strtoul(str, &end, 16);
4246 guid->Data2 = (
unsigned short)strtoul(str, &end, 16);
4248 guid->Data3 = (
unsigned short)strtoul(str, &end, 16);
4250 guid->Data4[0] = hex2byte(str);
4252 guid->Data4[1] = hex2byte(str);
4254 for (i = 0; i < 6; i++) {
4255 guid->Data4[i + 2] = hex2byte(str);
4261#ifndef HAVE_TYPE_NET_LUID
4265 uint64_t Reserved :24;
4266 uint64_t NetLuidIndex :24;
4267 uint64_t IfType :16;
4273getifaddrs(
struct ifaddrs **ifap)
4277 IP_ADAPTER_ADDRESSES *root, *addr;
4280 ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, NULL, &size);
4281 if (ret != ERROR_BUFFER_OVERFLOW) {
4282 errno = map_errno(ret);
4285 root = ruby_xmalloc(size);
4286 ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, root, &size);
4287 if (ret != ERROR_SUCCESS) {
4288 errno = map_errno(ret);
4293 for (prev = NULL, addr = root; addr; addr = addr->Next) {
4294 struct ifaddrs *ifa = ruby_xcalloc(1,
sizeof(*ifa));
4295 char name[IFNAMSIZ];
4300 prev->ifa_next = ifa;
4304 str2guid(addr->AdapterName, &guid);
4305 if (ConvertInterfaceGuidToLuid(&guid, &luid) == NO_ERROR &&
4306 ConvertInterfaceLuidToNameA(&luid, name,
sizeof(name)) == NO_ERROR) {
4313 if (addr->IfType & IF_TYPE_SOFTWARE_LOOPBACK)
4314 ifa->ifa_flags |= IFF_LOOPBACK;
4315 if (addr->OperStatus == IfOperStatusUp) {
4316 ifa->ifa_flags |= IFF_UP;
4318 if (addr->FirstUnicastAddress) {
4319 IP_ADAPTER_UNICAST_ADDRESS *cur;
4321 for (cur = addr->FirstUnicastAddress; cur; cur = cur->Next) {
4322 if (cur->Flags & IP_ADAPTER_ADDRESS_TRANSIENT ||
4323 cur->DadState == IpDadStateDeprecated) {
4328 ifa = ruby_xcalloc(1,
sizeof(*ifa));
4329 prev->ifa_next = ifa;
4331 ifa->ifa_flags = prev->ifa_flags;
4333 ifa->ifa_addr = ruby_xmalloc(cur->Address.iSockaddrLength);
4334 memcpy(ifa->ifa_addr, cur->Address.lpSockaddr,
4335 cur->Address.iSockaddrLength);
4350freeifaddrs(
struct ifaddrs *ifp)
4353 struct ifaddrs *next = ifp->ifa_next;
4354 ruby_xfree(ifp->ifa_addr);
4355 ruby_xfree(ifp->ifa_name);
4366void endhostent(
void) {}
4367void endnetent(
void) {}
4368void endprotoent(
void) {}
4369void endservent(
void) {}
4371struct netent *getnetent (
void) {
return (
struct netent *) NULL;}
4373struct netent *getnetbyaddr(
long net,
int type) {
return (
struct netent *)NULL;}
4375struct netent *getnetbyname(
const char *name) {
return (
struct netent *)NULL;}
4377struct protoent *getprotoent (
void) {
return (
struct protoent *) NULL;}
4379struct servent *getservent (
void) {
return (
struct servent *) NULL;}
4381void sethostent (
int stayopen) {}
4383void setnetent (
int stayopen) {}
4385void setprotoent (
int stayopen) {}
4387void setservent (
int stayopen) {}
4390int rb_w32_set_nonblock2(
int fd,
int nonblock);
4394setfl(SOCKET sock,
int arg)
4401 socklist_lookup(sock, &flag);
4402 af = GET_FAMILY(flag);
4403 flag = GET_FLAGS(flag);
4404 if (arg & O_NONBLOCK) {
4409 flag &= ~O_NONBLOCK;
4413 ret = ioctlsocket(sock, FIONBIO, &ioctlArg);
4415 socklist_insert(sock, MAKE_SOCKDATA(af, flag));
4417 errno = map_errno(WSAGetLastError());
4425dupfd(HANDLE hDup,
int flags,
int minfd)
4433 ret = _open_osfhandle((intptr_t)hDup, flags | FOPEN);
4435 goto close_fds_and_return;
4438 goto close_fds_and_return;
4440 fds[filled++] = ret;
4441 }
while (filled < (
int)numberof(fds));
4443 ret = dupfd(hDup, flags, minfd);
4445 close_fds_and_return:
4447 while (filled > 0) {
4448 int fd = fds[--filled];
4449 _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE);
4459fcntl(
int fd,
int cmd, ...)
4468 arg = va_arg(va,
int);
4470 return rb_w32_set_nonblock2(fd, arg);
4472 case F_DUPFD:
case F_DUPFD_CLOEXEC: {
4476 if (!(DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
4477 GetCurrentProcess(), &hDup, 0L,
4478 cmd == F_DUPFD && !(flag & FNOINHERIT),
4479 DUPLICATE_SAME_ACCESS))) {
4480 errno = map_errno(GetLastError());
4485 arg = va_arg(va,
int);
4491 flag &= ~FNOINHERIT;
4492 if ((ret = dupfd(hDup, flag, arg)) == -1)
4498 if (h == -1)
return -1;
4499 if (!GetHandleInformation((HANDLE)h, &flag)) {
4500 errno = map_errno(GetLastError());
4503 return (flag & HANDLE_FLAG_INHERIT) ? 0 : FD_CLOEXEC;
4507 if (h == -1)
return -1;
4509 arg = va_arg(va,
int);
4511 if (!SetHandleInformation((HANDLE)h, HANDLE_FLAG_INHERIT,
4512 (arg & FD_CLOEXEC) ? 0 : HANDLE_FLAG_INHERIT)) {
4513 errno = map_errno(GetLastError());
4516 if (arg & FD_CLOEXEC)
4517 _osfile(fd) |= FNOINHERIT;
4519 _osfile(fd) &= ~FNOINHERIT;
4530rb_w32_set_nonblock2(
int fd,
int nonblock)
4532 SOCKET sock = TO_SOCKET(fd);
4533 if (is_socket(sock)) {
4534 return setfl(sock, nonblock ? O_NONBLOCK : 0);
4536 else if (is_pipe(sock)) {
4538 if (!GetNamedPipeHandleState((HANDLE)sock, &state, NULL, NULL, NULL, NULL, 0)) {
4539 errno = map_errno(GetLastError());
4543 state |= PIPE_NOWAIT;
4546 state &= ~PIPE_NOWAIT;
4548 if (!SetNamedPipeHandleState((HANDLE)sock, &state, NULL, NULL)) {
4549 errno = map_errno(GetLastError());
4561rb_w32_set_nonblock(
int fd)
4563 return rb_w32_set_nonblock2(fd, TRUE);
4572poll_child_status(
struct ChildRecord *child,
int *stat_loc)
4577 if (!GetExitCodeProcess(child->hProcess, &exitcode)) {
4579 err = GetLastError();
4581 case ERROR_INVALID_PARAMETER:
4584 case ERROR_INVALID_HANDLE:
4588 errno = map_errno(err);
4592 CloseChildHandle(child);
4595 if (exitcode != STILL_ACTIVE) {
4598 if (rb_w32_wait_events_blocking(&child->hProcess, 1, INFINITE) != WAIT_OBJECT_0) {
4602 CloseChildHandle(child);
4604 *stat_loc = exitcode << 8;
4605 if (exitcode & 0xC0000000) {
4606 static const struct {
4610 {STATUS_ACCESS_VIOLATION, SIGSEGV},
4611 {STATUS_ILLEGAL_INSTRUCTION, SIGILL},
4612 {STATUS_PRIVILEGED_INSTRUCTION, SIGILL},
4613 {STATUS_FLOAT_DENORMAL_OPERAND, SIGFPE},
4614 {STATUS_FLOAT_DIVIDE_BY_ZERO, SIGFPE},
4615 {STATUS_FLOAT_INEXACT_RESULT, SIGFPE},
4616 {STATUS_FLOAT_INVALID_OPERATION, SIGFPE},
4617 {STATUS_FLOAT_OVERFLOW, SIGFPE},
4618 {STATUS_FLOAT_STACK_CHECK, SIGFPE},
4619 {STATUS_FLOAT_UNDERFLOW, SIGFPE},
4620#ifdef STATUS_FLOAT_MULTIPLE_FAULTS
4621 {STATUS_FLOAT_MULTIPLE_FAULTS, SIGFPE},
4623#ifdef STATUS_FLOAT_MULTIPLE_TRAPS
4624 {STATUS_FLOAT_MULTIPLE_TRAPS, SIGFPE},
4626 {STATUS_CONTROL_C_EXIT, SIGINT},
4629 for (i = 0; i < (int)numberof(table); i++) {
4630 if (table[i].status == exitcode) {
4631 *stat_loc |= table[i].sig;
4636 if (i >= (
int)numberof(table))
4637 *stat_loc |= SIGSEGV;
4647waitpid(rb_pid_t pid,
int *stat_loc,
int options)
4652 if (options == WNOHANG) {
4663 HANDLE events[MAXCHILDNUM];
4666 FOREACH_CHILD(child) {
4667 if (!child->pid || child->pid < 0)
continue;
4668 if ((pid = poll_child_status(child, stat_loc)))
return pid;
4669 events[count++] = child->hProcess;
4670 } END_FOREACH_CHILD;
4676 ret = rb_w32_wait_events_blocking(events, count, timeout);
4677 if (ret == WAIT_TIMEOUT)
return 0;
4678 if ((ret -= WAIT_OBJECT_0) == count) {
4682 errno = map_errno(GetLastError());
4686 cause = FindChildSlotByHandle(events[ret]);
4691 return poll_child_status(cause, stat_loc);
4701 while (!(pid = poll_child_status(child, stat_loc))) {
4703 int ret = rb_w32_wait_events_blocking(&child->hProcess, 1, timeout);
4704 if (ret == WAIT_OBJECT_0 + 1)
return -1;
4705 if (ret != WAIT_OBJECT_0) {
4707 if (options & WNOHANG) {
4714 if (pid == -1 && retried) pid = 0;
4720#include <sys/timeb.h>
4723#define filetime_unit (10UL * 1000 * 1000)
4724#define filetime_diff_days ((1970-1601)*3652425UL/10000)
4725#define filetime_diff_secs (filetime_diff_days * (24ULL * 60 * 60))
4726#define unix_to_filetime(sec) (((sec) + filetime_diff_secs) * filetime_unit)
4727#define filetime_unix_offset unix_to_filetime(0ULL)
4739filetime_split(
const FILETIME* ft,
long *subsec)
4742 ULONGLONG lt = fi.i.QuadPart;
4748 lt -= unix_to_filetime(0);
4750 *subsec = (long)(lt % filetime_unit);
4751 return (time_t)(lt / filetime_unit);
4761 GetSystemTimePreciseAsFileTime(&ft);
4762 tv->tv_sec = filetime_split(&ft, &subsec);
4763 tv->tv_usec = subsec / 10;
4770filetime_to_timespec(FILETIME ft,
struct timespec *sp)
4773 sp->tv_sec = filetime_split(&ft, &subsec);
4774 sp->tv_nsec = subsec * 100;
4778static const long secs_in_ns = 1000000000;
4782clock_gettime(clockid_t clock_id,
struct timespec *sp)
4785 case CLOCK_REALTIME:
4786 case CLOCK_REALTIME_COARSE:
4790 GetSystemTimePreciseAsFileTime(&ft);
4791 filetime_to_timespec(ft, sp);
4794 case CLOCK_MONOTONIC:
4797 LARGE_INTEGER count;
4798 if (UNLIKELY(!QueryPerformanceFrequency(&freq))) {
4799 errno = map_errno(GetLastError());
4802 if (UNLIKELY(!QueryPerformanceCounter(&count))) {
4803 errno = map_errno(GetLastError());
4806 sp->tv_sec = count.QuadPart / freq.QuadPart;
4807 if (freq.QuadPart < secs_in_ns)
4808 sp->tv_nsec = (count.QuadPart % freq.QuadPart) * secs_in_ns / freq.QuadPart;
4810 sp->tv_nsec = (long)((count.QuadPart % freq.QuadPart) * ((double)secs_in_ns / freq.QuadPart));
4813 case CLOCK_PROCESS_CPUTIME_ID:
4814 case CLOCK_THREAD_CPUTIME_ID:
4818 if (clock_id == CLOCK_PROCESS_CPUTIME_ID) {
4819 ok = GetProcessTimes(GetCurrentProcess(), &c.ft, &e.ft, &k.ft, &u.ft);
4822 ok = GetThreadTimes(GetCurrentThread(), &c.ft, &e.ft, &k.ft, &u.ft);
4824 if (UNLIKELY(!ok)) {
4825 errno = map_errno(GetLastError());
4828 total.i.QuadPart = k.i.QuadPart + u.i.QuadPart;
4829 filetime_to_timespec(total.ft, sp);
4840clock_getres(clockid_t clock_id,
struct timespec *sp)
4843 case CLOCK_REALTIME:
4844 case CLOCK_REALTIME_COARSE:
4850 case CLOCK_MONOTONIC:
4853 if (!QueryPerformanceFrequency(&freq)) {
4854 errno = map_errno(GetLastError());
4858 sp->tv_nsec = (long)((
double)secs_in_ns / freq.QuadPart);
4861 case CLOCK_PROCESS_CPUTIME_ID:
4862 case CLOCK_THREAD_CPUTIME_ID:
4864 const int frames_in_sec = 60;
4866 sp->tv_nsec = (long)(secs_in_ns / frames_in_sec);
4877w32_getcwd(
char *buffer,
int size, UINT cp,
void *alloc(
int,
void *),
void *arg)
4882 len = GetCurrentDirectoryW(0, NULL);
4884 errno = map_errno(GetLastError());
4888 if (buffer && size <
len) {
4894 if (!GetCurrentDirectoryW(
len, p)) {
4895 errno = map_errno(GetLastError());
4899 wlen = translate_wchar(p, L
'\\', L
'/') - p + 1;
4900 len = WideCharToMultiByte(cp, 0, p, wlen, NULL, 0, NULL, NULL);
4908 buffer = (*alloc)(
len, arg);
4914 WideCharToMultiByte(cp, 0, p, wlen, buffer,
len, NULL, NULL);
4921getcwd_alloc(
int size,
void *dummy)
4923 return malloc(size);
4928rb_w32_getcwd(
char *buffer,
int size)
4930 return w32_getcwd(buffer, size, filecp(), getcwd_alloc, NULL);
4935rb_w32_ugetcwd(
char *buffer,
int size)
4937 return w32_getcwd(buffer, size, CP_UTF8, getcwd_alloc, NULL);
4942getcwd_value(
int size,
void *arg)
4945 return RSTRING_PTR(str);
4950rb_dir_getwd_ospath(
void)
4953 w32_getcwd(NULL, 0, CP_UTF8, getcwd_value, &cwd);
4959chown(
const char *path,
int owner,
int group)
4966rb_w32_uchown(
const char *path,
int owner,
int group)
4972lchown(
const char *path,
int owner,
int group)
4978rb_w32_ulchown(
const char *path,
int owner,
int group)
4985kill(rb_pid_t pid,
int sig)
4990 if (pid < 0 || (pid == 0 && sig != SIGINT)) {
4995 if ((
unsigned int)pid == GetCurrentProcessId() &&
4996 (sig != 0 && sig != SIGKILL)) {
4997 if ((ret = raise(sig)) != 0) {
5008 OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid);
5009 if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) {
5010 if (GetLastError() == ERROR_INVALID_PARAMETER) {
5026 DWORD ctrlEvent = CTRL_C_EVENT;
5030 ctrlEvent = CTRL_BREAK_EVENT;
5032 if (!GenerateConsoleCtrlEvent(ctrlEvent, (DWORD)pid)) {
5033 if ((err = GetLastError()) == 0)
5036 errno = map_errno(GetLastError());
5047 hProc = child->hProcess;
5050 hProc = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid);
5052 if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) {
5053 if (GetLastError() == ERROR_INVALID_PARAMETER) {
5063 if (!GetExitCodeProcess(hProc, &status)) {
5064 errno = map_errno(GetLastError());
5067 else if (status == STILL_ACTIVE) {
5068 if (!TerminateProcess(hProc, 0)) {
5095wlink(
const WCHAR *from,
const WCHAR *to)
5097 if (!CreateHardLinkW(to, from, NULL)) {
5098 errno = map_errno(GetLastError());
5107rb_w32_ulink(
const char *from,
const char *to)
5113 if (!(wfrom = utf8_to_wstr(from, NULL)))
5115 if (!(wto = utf8_to_wstr(to, NULL))) {
5119 ret = wlink(wfrom, wto);
5127link(
const char *from,
const char *to)
5133 if (!(wfrom = filecp_to_wstr(from, NULL)))
5135 if (!(wto = filecp_to_wstr(to, NULL))) {
5139 ret = wlink(wfrom, wto);
5146#ifndef FILE_DEVICE_FILE_SYSTEM
5147# define FILE_DEVICE_FILE_SYSTEM 0x00000009
5149#ifndef FSCTL_GET_REPARSE_POINT
5150# define FSCTL_GET_REPARSE_POINT ((0x9<<16)|(42<<2))
5152#ifndef IO_REPARSE_TAG_SYMLINK
5153# define IO_REPARSE_TAG_SYMLINK 0xA000000CL
5164 f = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5165 if (f == INVALID_HANDLE_VALUE) {
5166 return GetLastError();
5169 if (!DeviceIoControl(f, FSCTL_GET_REPARSE_POINT, NULL, 0,
5170 rp, size, &ret, NULL)) {
5173 else if (rp->ReparseTag != IO_REPARSE_TAG_SYMLINK &&
5174 rp->ReparseTag != IO_REPARSE_TAG_MOUNT_POINT) {
5175 e = ERROR_INVALID_PARAMETER;
5183rb_w32_reparse_symlink_p(
const WCHAR *path)
5191 e = rb_w32_read_reparse_point(path, rp,
sizeof(rbuf), &wbuf, &
len);
5192 if (e == ERROR_MORE_DATA) {
5193 size_t size = rb_w32_reparse_buffer_size(
len + 1);
5195 e = rb_w32_read_reparse_point(path, rp, size, &wbuf, &
len);
5200 case ERROR_MORE_DATA:
5209 size_t bufsize, WCHAR **result, DWORD *
len)
5211 int e = reparse_symlink(path, rp, bufsize);
5214 if (!e || e == ERROR_MORE_DATA) {
5216 if (rp->ReparseTag == IO_REPARSE_TAG_SYMLINK) {
5217 name = ((
char *)rp->SymbolicLinkReparseBuffer.PathBuffer +
5218 rp->SymbolicLinkReparseBuffer.PrintNameOffset);
5219 ret = rp->SymbolicLinkReparseBuffer.PrintNameLength;
5220 *
len = ret /
sizeof(WCHAR);
5222 else if (rp->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT) {
5223 static const WCHAR volume[] = L
"Volume{";
5225 name = ((
char *)rp->MountPointReparseBuffer.PathBuffer +
5226 rp->MountPointReparseBuffer.SubstituteNameOffset +
5227 volume_prefix_len *
sizeof(WCHAR));
5228 ret = rp->MountPointReparseBuffer.SubstituteNameLength;
5229 *
len = ret /
sizeof(WCHAR);
5230 ret -= volume_prefix_len *
sizeof(WCHAR);
5231 if (ret >
sizeof(volume) - 1 *
sizeof(WCHAR) &&
5232 memcmp(name, volume,
sizeof(volume) - 1 *
sizeof(WCHAR)) == 0)
5240 if ((
char *)name + ret +
sizeof(WCHAR) > (
char *)rp + bufsize)
5244 ((WCHAR *)name)[ret/
sizeof(WCHAR)] = L
'\0';
5245 translate_wchar(name, L
'\\', L
'/');
5255w32_readlink(UINT cp,
const char *path,
char *buf,
size_t bufsize)
5257 VALUE rp_buf, rp_buf_bigger = 0;
5258 DWORD
len = MultiByteToWideChar(cp, 0, path, -1, NULL, 0);
5259 size_t size = rb_w32_reparse_buffer_size(bufsize);
5261 WCHAR *wpath =
ALLOCV(rp_buf,
sizeof(WCHAR) *
len + size);
5266 MultiByteToWideChar(cp, 0, path, -1, wpath,
len);
5267 e = rb_w32_read_reparse_point(wpath, rp, size, &wname, &
len);
5268 if (e == ERROR_MORE_DATA) {
5269 size = rb_w32_reparse_buffer_size(
len + 1);
5270 rp =
ALLOCV(rp_buf_bigger, size);
5271 e = rb_w32_read_reparse_point(wpath, rp, size, &wname, &
len);
5276 errno = e == -1 ? EINVAL : map_errno(e);
5279 len = lstrlenW(wname);
5280 ret = WideCharToMultiByte(cp, 0, wname,
len, buf, bufsize, NULL, NULL);
5291rb_w32_ureadlink(
const char *path,
char *buf,
size_t bufsize)
5293 return w32_readlink(CP_UTF8, path, buf, bufsize);
5298readlink(
const char *path,
char *buf,
size_t bufsize)
5300 return w32_readlink(filecp(), path, buf, bufsize);
5303#ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5304#define SYMBOLIC_LINK_FLAG_DIRECTORY (0x1)
5306#ifndef SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
5307#define SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE (0x2)
5312w32_symlink(UINT cp,
const char *src,
const char *link)
5314 int atts, len1, len2;
5316 WCHAR *wsrc, *wlink;
5321 static DWORD create_flag = SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
5331 len1 = MultiByteToWideChar(cp, 0, src, -1, NULL, 0);
5332 len2 = MultiByteToWideChar(cp, 0, link, -1, NULL, 0);
5333 wsrc =
ALLOCV_N(WCHAR, buf, len1+len2);
5334 wlink = wsrc + len1;
5335 MultiByteToWideChar(cp, 0, src, -1, wsrc, len1);
5336 MultiByteToWideChar(cp, 0, link, -1, wlink, len2);
5337 translate_wchar(wsrc, L
'/', L
'\\');
5338 translate_wchar(wlink, L
'/', L
'\\');
5348 (((wsrc[0] >= L
'A' && wsrc[0] <= L
'Z') ||
5349 (wsrc[0] >= L
'a' && wsrc[0] <= L
'z')) && wsrc[1] == L
':') ||
5351 if (!independent && (sep = wcsrchr(wlink, L
'\\')) != NULL) {
5353 size_t dirlen = sep - wlink + 1;
5354 size_t srclen = wcslen(wsrc) + 1;
5355 WCHAR *fullsrc =
ALLOCV_N(WCHAR, buf2, dirlen + srclen);
5356 MEMCPY(fullsrc, wlink, WCHAR, dirlen);
5357 MEMCPY(fullsrc + dirlen, wsrc, WCHAR, srclen);
5358 atts = GetFileAttributesW(fullsrc);
5362 atts = GetFileAttributesW(wsrc);
5365 if (atts != -1 && atts & FILE_ATTRIBUTE_DIRECTORY)
5366 flag = SYMBOLIC_LINK_FLAG_DIRECTORY;
5367 ret = CreateSymbolicLinkW(wlink, wsrc, flag |= create_flag);
5369 (e = GetLastError()) == ERROR_INVALID_PARAMETER &&
5370 (flag & SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)) {
5372 flag &= ~SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
5373 ret = CreateSymbolicLinkW(wlink, wsrc, flag);
5374 if (!ret) e = GetLastError();
5379 errno = map_errno(e);
5387rb_w32_usymlink(
const char *src,
const char *link)
5389 return w32_symlink(CP_UTF8, src, link);
5394symlink(
const char *src,
const char *link)
5396 return w32_symlink(filecp(), src, link);
5403 return waitpid(-1, status, 0);
5408w32_getenv(
const char *name, UINT cp)
5410 WCHAR *wenvarea, *wenv;
5411 int len = strlen(name);
5412 char *env, *found = NULL;
5415 if (
len == 0)
return NULL;
5420 return getenv(name);
5423 thread_exclusive(uenvarea) {
5428 wenvarea = GetEnvironmentStringsW();
5430 map_errno(GetLastError());
5433 for (wenv = wenvarea, wlen = 1; *wenv; wenv += lstrlenW(wenv) + 1)
5434 wlen += lstrlenW(wenv) + 1;
5435 uenvarea = wstr_to_mbstr(cp, wenvarea, wlen, NULL);
5436 FreeEnvironmentStringsW(wenvarea);
5440 for (env = uenvarea; *env; env += strlen(env) + 1) {
5441 if (strncasecmp(env, name,
len) == 0 && *(env +
len) ==
'=') {
5442 found = env +
len + 1;
5453rb_w32_ugetenv(
const char *name)
5455 return w32_getenv(name, CP_UTF8);
5460rb_w32_getenv(
const char *name)
5462 return w32_getenv(name, CP_ACP);
5467get_attr_vsn(
const WCHAR *path, DWORD *atts, DWORD *vsn)
5469 BY_HANDLE_FILE_INFORMATION st = {0};
5471 HANDLE h = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5473 if (h == INVALID_HANDLE_VALUE) {
5478 if (!GetFileInformationByHandle(h, &st)) {
5483 *atts = st.dwFileAttributes;
5484 *vsn = st.dwVolumeSerialNumber;
5492wrename(
const WCHAR *oldpath,
const WCHAR *newpath)
5495 DWORD oldatts = 0, newatts = (DWORD)-1;
5496 DWORD oldvsn = 0, newvsn = 0, e;
5498 e = get_attr_vsn(oldpath, &oldatts, &oldvsn);
5500 errno = map_errno(e);
5503 if (oldatts & FILE_ATTRIBUTE_REPARSE_POINT) {
5504 HANDLE fh = open_special(oldpath, 0, 0);
5505 if (fh == INVALID_HANDLE_VALUE) {
5507 if (e == ERROR_CANT_RESOLVE_FILENAME) {
5514 get_attr_vsn(newpath, &newatts, &newvsn);
5517 if (newatts != (DWORD)-1 && newatts & FILE_ATTRIBUTE_READONLY)
5518 SetFileAttributesW(newpath, newatts & ~ FILE_ATTRIBUTE_READONLY);
5520 if (!MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED))
5524 DWORD e = GetLastError();
5525 if ((e == ERROR_ACCESS_DENIED) && (oldatts & FILE_ATTRIBUTE_DIRECTORY) &&
5529 errno = map_errno(e);
5532 SetFileAttributesW(newpath, oldatts);
5540rb_w32_urename(
const char *from,
const char *to)
5546 if (!(wfrom = utf8_to_wstr(from, NULL)))
5548 if (!(wto = utf8_to_wstr(to, NULL))) {
5552 ret = wrename(wfrom, wto);
5560rb_w32_rename(
const char *from,
const char *to)
5566 if (!(wfrom = filecp_to_wstr(from, NULL)))
5568 if (!(wto = filecp_to_wstr(to, NULL))) {
5572 ret = wrename(wfrom, wto);
5580isUNCRoot(
const WCHAR *path)
5582 if (path[0] == L
'\\' && path[1] == L
'\\') {
5583 const WCHAR *p = path + 2;
5584 if (p[0] == L
'?' && p[1] == L
'\\') {
5592 for (p++; *p; p++) {
5596 if (!p[0] || !p[1] || (p[1] == L
'.' && !p[2]))
5603#define COPY_STAT(src, dest, size_cast) do { \
5604 (dest).st_dev = (src).st_dev; \
5605 (dest).st_ino = (src).st_ino; \
5606 (dest).st_mode = (src).st_mode; \
5607 (dest).st_nlink = (src).st_nlink; \
5608 (dest).st_uid = (src).st_uid; \
5609 (dest).st_gid = (src).st_gid; \
5610 (dest).st_rdev = (src).st_rdev; \
5611 (dest).st_size = size_cast(src).st_size; \
5612 (dest).st_atime = (src).st_atime; \
5613 (dest).st_mtime = (src).st_mtime; \
5614 (dest).st_ctime = (src).st_ctime; \
5617static time_t filetime_to_unixtime(
const FILETIME *ft);
5618static long filetime_to_nsec(
const FILETIME *ft);
5619static WCHAR *name_for_stat(WCHAR *buf,
const WCHAR *path);
5620static DWORD stati128_handle(HANDLE h,
struct stati128 *st);
5625rb_w32_fstat(
int fd,
struct stat *st)
5627 BY_HANDLE_FILE_INFORMATION info;
5628 int ret = fstat(fd, st);
5630 if (ret)
return ret;
5631 if (GetEnvironmentVariableW(L
"TZ", NULL, 0) == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND)
return ret;
5632 if (GetFileInformationByHandle((HANDLE)_get_osfhandle(fd), &info)) {
5633 st->st_atime = filetime_to_unixtime(&info.ftLastAccessTime);
5634 st->st_mtime = filetime_to_unixtime(&info.ftLastWriteTime);
5635 st->st_ctime = filetime_to_unixtime(&info.ftCreationTime);
5642rb_w32_fstati128(
int fd,
struct stati128 *st)
5645 int ret = fstat(fd, &tmp);
5647 if (ret)
return ret;
5648 COPY_STAT(tmp, *st, +);
5649 stati128_handle((HANDLE)_get_osfhandle(fd), st);
5653#if !defined FILE_INVALID_FILE_ID && !defined __MINGW32__
5655 BYTE Identifier[16];
5659#if !defined(_WIN32_WINNT_WIN8) || _WIN32_WINNT < 0x602
5660#define FileIdInfo 0x12
5671 return GetFileInformationByHandleEx(h, FileIdInfo,
id,
sizeof(*
id));
5676stati128_handle(HANDLE h,
struct stati128 *st)
5678 BY_HANDLE_FILE_INFORMATION info;
5679 DWORD attr = (DWORD)-1;
5681 if (GetFileInformationByHandle(h, &info)) {
5683 st->st_size = ((__int64)info.nFileSizeHigh << 32) | info.nFileSizeLow;
5684 st->st_atime = filetime_to_unixtime(&info.ftLastAccessTime);
5685 st->st_atimensec = filetime_to_nsec(&info.ftLastAccessTime);
5686 st->st_mtime = filetime_to_unixtime(&info.ftLastWriteTime);
5687 st->st_mtimensec = filetime_to_nsec(&info.ftLastWriteTime);
5688 st->st_ctime = filetime_to_unixtime(&info.ftCreationTime);
5689 st->st_ctimensec = filetime_to_nsec(&info.ftCreationTime);
5690 st->st_nlink = info.nNumberOfLinks;
5691 attr = info.dwFileAttributes;
5692 if (get_ino(h, &fii)) {
5693 st->st_ino = *((
unsigned __int64 *)&fii.FileId);
5694 st->st_inohigh = *((__int64 *)&fii.FileId + 1);
5697 st->st_ino = ((__int64)info.nFileIndexHigh << 32) | info.nFileIndexLow;
5706filetime_to_unixtime(
const FILETIME *ft)
5709 time_t t = filetime_split(ft, &subsec);
5711 if (t < 0)
return 0;
5717filetime_to_nsec(
const FILETIME *ft)
5720 tmp.LowPart = ft->dwLowDateTime;
5721 tmp.HighPart = ft->dwHighDateTime;
5722 return (
long)(tmp.QuadPart % 10000000) * 100;
5727fileattr_to_unixmode(DWORD attr,
const WCHAR *path,
unsigned mode)
5729 if (attr & FILE_ATTRIBUTE_READONLY) {
5733 mode |= S_IREAD | S_IWRITE | S_IWUSR;
5736 if (mode & S_IFMT) {
5739 else if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
5743 else if (attr & FILE_ATTRIBUTE_DIRECTORY) {
5744 mode |= S_IFDIR | S_IEXEC;
5750 if (path && (mode & S_IFREG)) {
5751 const WCHAR *end = path + lstrlenW(path);
5752 while (path < end) {
5753 end = CharPrevW(path, end);
5755 if ((_wcsicmp(end, L
".bat") == 0) ||
5756 (_wcsicmp(end, L
".cmd") == 0) ||
5757 (_wcsicmp(end, L
".com") == 0) ||
5758 (_wcsicmp(end, L
".exe") == 0)) {
5763 if (!iswalnum(*end))
break;
5767 mode |= (mode & 0500) >> 3;
5768 mode |= (mode & 0500) >> 6;
5775check_valid_dir(
const WCHAR *path)
5777 WIN32_FIND_DATAW fd;
5779 WCHAR full[PATH_MAX];
5784 if (!(p = wcsstr(path, L
"...")))
5786 q = p + wcsspn(p, L
".");
5787 if ((p == path || wcschr(L
":/\\", *(p - 1))) &&
5788 (!*q || wcschr(L
":/\\", *q))) {
5795 DWORD
len = GetFullPathNameW(path, numberof(full), full, NULL);
5796 if (
len >= numberof(full)) {
5797 WCHAR *fullpath = malloc(
len *
sizeof(WCHAR));
5798 if (!fullpath)
return -1;
5799 len = GetFullPathNameW(path,
len, fullpath, NULL);
5804 errno = map_errno(GetLastError());
5807 if (
len == 3 && full[1] == L
':' && GetDriveTypeW(full) != DRIVE_NO_ROOT_DIR)
5810 fh = open_dir_handle(path, &fd);
5811 if (fh == INVALID_HANDLE_VALUE)
5819stat_by_find(
const WCHAR *path,
struct stati128 *st)
5822 WIN32_FIND_DATAW wfd;
5825 h = FindFirstFileW(path, &wfd);
5826 if (h == INVALID_HANDLE_VALUE) {
5827 errno = map_errno(GetLastError());
5831 st->st_mode = fileattr_to_unixmode(wfd.dwFileAttributes, path, 0);
5832 st->st_atime = filetime_to_unixtime(&wfd.ftLastAccessTime);
5833 st->st_atimensec = filetime_to_nsec(&wfd.ftLastAccessTime);
5834 st->st_mtime = filetime_to_unixtime(&wfd.ftLastWriteTime);
5835 st->st_mtimensec = filetime_to_nsec(&wfd.ftLastWriteTime);
5836 st->st_ctime = filetime_to_unixtime(&wfd.ftCreationTime);
5837 st->st_ctimensec = filetime_to_nsec(&wfd.ftCreationTime);
5838 st->st_size = ((__int64)wfd.nFileSizeHigh << 32) | wfd.nFileSizeLow;
5845path_drive(
const WCHAR *path)
5847 if (path[0] && path[1] == L
':') {
5848 if (iswalpha(path[0]))
return towupper(path[0]) - L
'A';
5849 return (
int)path[0];
5851 return _getdrive() - 1;
5854#if !defined(NTDDI_WIN11_ZN) || NTDDI_VERSION < NTDDI_WIN11_ZN
5857#define FileStatBasicByNameInfo 3
5860 LARGE_INTEGER FileId;
5861 LARGE_INTEGER CreationTime;
5862 LARGE_INTEGER LastAccessTime;
5863 LARGE_INTEGER LastWriteTime;
5864 LARGE_INTEGER ChangeTime;
5865 LARGE_INTEGER AllocationSize;
5866 LARGE_INTEGER EndOfFile;
5867 DWORD FileAttributes;
5869 DWORD NumberOfLinks;
5871 DWORD DeviceCharacteristics;
5873 LARGE_INTEGER VolumeSerialNumber;
5878#ifndef FILE_DEVICE_DISK
5879#define FILE_DEVICE_DISK 7
5882typedef BOOL (WINAPI *get_file_information_by_name_func)
5883 (PCWSTR,
int , PVOID, ULONG);
5884static get_file_information_by_name_func get_file_information_by_name =
5885 (get_file_information_by_name_func)-1;
5889large_integer_to_unixtime(
const LARGE_INTEGER *at,
long *nsecp)
5893 ft.dwLowDateTime = at->LowPart;
5894 ft.dwHighDateTime = at->HighPart;
5895 *nsecp = filetime_to_nsec(&ft);
5896 return filetime_to_unixtime(&ft);
5901path_drive_serial(
const WCHAR *path)
5906 if (path[0] && path[1] == L
':') {
5907 if (!iswalpha(path[0]))
return 0;
5908 drive = towupper(path[0]) - L
'A';
5911 drive = _getdrive() - 1;
5913 if (drive < 0 || (
int)numberof(serials) <= drive)
return 0;
5914 if (!serials[drive]) {
5916 WCHAR root[] = L
"_:\\";
5917 root[0] = L
'A' + drive;
5918 if (get_file_information_by_name(root, FileStatBasicByNameInfo,
5919 &info,
sizeof(info)))
5920 serials[drive] = info.VolumeSerialNumber.QuadPart;
5922 return serials[drive];
5927stat_by_name(
const WCHAR *path,
struct stati128 *st)
5933 unsigned __int64 ino;
5936 if (get_file_information_by_name == (get_file_information_by_name_func)-1) {
5938 get_file_information_by_name = (get_file_information_by_name_func)
5939 get_proc_address(
"kernel32",
"GetFileInformationByName", NULL);
5941 if (!get_file_information_by_name)
return 1;
5942 if (!get_file_information_by_name(path, FileStatBasicByNameInfo,
5943 &info,
sizeof(info))) {
5944 DWORD e = GetLastError();
5946 case ERROR_FILE_NOT_FOUND:
5947 case ERROR_INVALID_NAME:
5948 case ERROR_PATH_NOT_FOUND:
5949 case ERROR_BAD_NETPATH:
5950 errno = map_errno(e);
5955 if (info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
5957 if (info.DeviceType != FILE_DEVICE_DISK)
5959 if (info.VolumeSerialNumber.QuadPart != path_drive_serial(path))
5961 ino = *((
unsigned __int64 *)&info.FileId128);
5962 inohigh = *((__int64 *)&info.FileId128 + 1);
5963 if (!ino && !inohigh)
5965 if (info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
5966 if (check_valid_dir(path))
return -1;
5969 st->st_inohigh = inohigh;
5970 st->st_size = info.EndOfFile.QuadPart;
5971 st->st_atime = large_integer_to_unixtime(&info.LastAccessTime, &st->st_atimensec);
5972 st->st_mtime = large_integer_to_unixtime(&info.LastWriteTime, &st->st_mtimensec);
5973 st->st_ctime = large_integer_to_unixtime(&info.CreationTime, &st->st_ctimensec);
5974 st->st_nlink = info.NumberOfLinks;
5975 st->st_mode = fileattr_to_unixmode(info.FileAttributes, path, 0);
5976 st->st_dev = st->st_rdev = path_drive(path);
5982winnt_stat(
const WCHAR *path,
struct stati128 *st, BOOL lstat)
5984 DWORD flags = lstat ? FILE_FLAG_OPEN_REPARSE_POINT : 0;
5986 WCHAR *finalname = 0;
5989 memset(st, 0,
sizeof(*st));
5990 switch (stat_by_name(path, st)) {
5996 f = open_special(path, 0, flags);
5997 open_error = GetLastError();
5998 if (f == INVALID_HANDLE_VALUE && !lstat) {
6000 FILE_ATTRIBUTE_TAG_INFO attr_info;
6003 f = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
6004 e = GetFileInformationByHandleEx(f, FileAttributeTagInfo,
6005 &attr_info,
sizeof(attr_info));
6006 if (!e || attr_info.ReparseTag != IO_REPARSE_TAG_AF_UNIX) {
6008 f = INVALID_HANDLE_VALUE;
6011 if (f != INVALID_HANDLE_VALUE) {
6012 DWORD attr = stati128_handle(f, st);
6014 switch (GetFileType(f)) {
6015 case FILE_TYPE_CHAR:
6018 case FILE_TYPE_PIPE:
6022 if (attr & FILE_ATTRIBUTE_DIRECTORY) {
6023 if (check_valid_dir(path))
return -1;
6025 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
6026 FILE_ATTRIBUTE_TAG_INFO attr_info;
6029 e = GetFileInformationByHandleEx(f, FileAttributeTagInfo,
6030 &attr_info,
sizeof(attr_info));
6031 if (e && attr_info.ReparseTag == IO_REPARSE_TAG_AF_UNIX) {
6035 else if (rb_w32_reparse_symlink_p(path)) {
6038 mode |= S_IFLNK | S_IEXEC;
6041 mode |= S_IFDIR | S_IEXEC;
6045 const DWORD
len = get_handle_pathname(f, &finalname, 0);
6047 st->st_mode = fileattr_to_unixmode(attr, path, mode);
6050 if (wcsncmp(path, namespace_prefix, numberof(namespace_prefix)) == 0)
6051 path += numberof(namespace_prefix);
6055 switch (open_error) {
6056 case ERROR_FILE_NOT_FOUND:
6057 case ERROR_INVALID_NAME:
6058 case ERROR_PATH_NOT_FOUND:
6059 case ERROR_BAD_NETPATH:
6060 case ERROR_CANT_RESOLVE_FILENAME:
6061 errno = map_errno(open_error);
6065 if (stat_by_find(path, st))
return -1;
6068 st->st_dev = st->st_rdev = path_drive(path);
6069 if (finalname) free(finalname);
6076rb_w32_stat(
const char *path,
struct stat *st)
6080 if (w32_stati128(path, &tmp, filecp(), FALSE))
return -1;
6081 COPY_STAT(tmp, *st, (_off_t));
6087wstati128(
const WCHAR *path,
struct stati128 *st, BOOL lstat)
6097 size = lstrlenW(path) + 2;
6099 if (!(path = name_for_stat(buf1, path)))
6101 ret = winnt_stat(path, st, lstat);
6110name_for_stat(WCHAR *buf1,
const WCHAR *path)
6116 for (p = path, s = buf1; *p; p++, s++) {
6124 if (!
len || L
'\"' == *(--s)) {
6128 end = buf1 +
len - 1;
6130 if (isUNCRoot(buf1)) {
6133 else if (*end != L
'\\')
6134 lstrcatW(buf1, L
"\\");
6136 else if (*end == L
'\\' || (buf1 + 1 == end && *end == L
':'))
6137 lstrcatW(buf1, L
".");
6144rb_w32_ustati128(
const char *path,
struct stati128 *st)
6146 return w32_stati128(path, st, CP_UTF8, FALSE);
6151rb_w32_stati128(
const char *path,
struct stati128 *st)
6153 return w32_stati128(path, st, filecp(), FALSE);
6158w32_stati128(
const char *path,
struct stati128 *st, UINT cp, BOOL lstat)
6163 if (!(wpath = mbstr_to_wstr(cp, path, -1, NULL)))
6165 ret = wstati128(wpath, st, lstat);
6172rb_w32_ulstati128(
const char *path,
struct stati128 *st)
6174 return w32_stati128(path, st, CP_UTF8, TRUE);
6179rb_w32_lstati128(
const char *path,
struct stati128 *st)
6181 return w32_stati128(path, st, filecp(), TRUE);
6186rb_w32_lseek(
int fd, rb_off_t ofs,
int whence)
6188 SOCKET sock = TO_SOCKET(fd);
6189 if (is_socket(sock) || is_pipe(sock)) {
6193 return _lseeki64(fd, ofs, whence);
6198w32_access(
const char *path,
int mode, UINT cp)
6201 if (w32_stati128(path, &stat, cp, FALSE) != 0)
6204 if ((stat.st_mode & mode) != mode) {
6213rb_w32_access(
const char *path,
int mode)
6215 return w32_access(path, mode, filecp());
6220rb_w32_uaccess(
const char *path,
int mode)
6222 return w32_access(path, mode, CP_UTF8);
6227rb_chsize(HANDLE h, rb_off_t size)
6229 long upos, lpos, usize, lsize;
6233 if ((lpos = SetFilePointer(h, 0, (upos = 0, &upos), SEEK_CUR)) == -1L &&
6234 (e = GetLastError())) {
6235 errno = map_errno(e);
6238 usize = (long)(size >> 32);
6240 if (SetFilePointer(h, lsize, &usize, SEEK_SET) == (DWORD)-1L &&
6241 (e = GetLastError())) {
6242 errno = map_errno(e);
6244 else if (!SetEndOfFile(h)) {
6245 errno = map_errno(GetLastError());
6250 SetFilePointer(h, lpos, &upos, SEEK_SET);
6256w32_truncate(
const char *path, rb_off_t length, UINT cp)
6262 if (!(wpath = mbstr_to_wstr(cp, path, -1, NULL)))
6264 h = CreateFileW(wpath, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
6265 if (h == INVALID_HANDLE_VALUE) {
6266 errno = map_errno(GetLastError());
6271 ret = rb_chsize(h, length);
6278rb_w32_utruncate(
const char *path, rb_off_t length)
6280 return w32_truncate(path, length, CP_UTF8);
6285rb_w32_truncate(
const char *path, rb_off_t length)
6287 return w32_truncate(path, length, filecp());
6292rb_w32_ftruncate(
int fd, rb_off_t length)
6296 h = (HANDLE)_get_osfhandle(fd);
6297 if (h == (HANDLE)-1)
return -1;
6298 return rb_chsize(h, length);
6303filetime_to_clock(FILETIME *ft)
6305 __int64 qw = ft->dwHighDateTime;
6307 qw |= ft->dwLowDateTime;
6314rb_w32_times(
struct tms *tmbuf)
6316 FILETIME create, exit, kernel, user;
6318 if (GetProcessTimes(GetCurrentProcess(),&create, &exit, &kernel, &user)) {
6319 tmbuf->tms_utime = filetime_to_clock(&user);
6320 tmbuf->tms_stime = filetime_to_clock(&kernel);
6321 tmbuf->tms_cutime = 0;
6322 tmbuf->tms_cstime = 0;
6325 tmbuf->tms_utime = clock();
6326 tmbuf->tms_stime = 0;
6327 tmbuf->tms_cutime = 0;
6328 tmbuf->tms_cstime = 0;
6335#define yield_once() Sleep(0)
6336#define yield_until(condition) do yield_once(); while (!(condition))
6345 uintptr_t (*func)(uintptr_t self,
int argc, uintptr_t* argv);
6353call_asynchronous(PVOID argp)
6357 arg->stackaddr = &argp;
6358 ret = (DWORD)arg->func(arg->self, arg->argc, arg->argv);
6359 arg->errnum =
errno;
6365rb_w32_asynchronize(asynchronous_func_t func, uintptr_t self,
6366 int argc, uintptr_t* argv, uintptr_t intrval)
6369 BOOL interrupted = FALSE;
6375 arg.stackaddr = NULL;
6382 thr = CreateThread(NULL, 0, call_asynchronous, &arg, 0, &val);
6385 yield_until(arg.stackaddr);
6387 if (rb_w32_wait_events_blocking(&thr, 1, INFINITE) != WAIT_OBJECT_0) {
6390 if (TerminateThread(thr, intrval)) {
6395 GetExitCodeThread(thr, &val);
6400 MEMORY_BASIC_INFORMATION m;
6402 memset(&m, 0,
sizeof(m));
6403 if (!VirtualQuery(arg.stackaddr, &m,
sizeof(m))) {
6404 Debug(fprintf(stderr,
"couldn't get stack base:%p:%d\n",
6405 arg.stackaddr, GetLastError()));
6407 else if (!VirtualFree(m.AllocationBase, 0, MEM_RELEASE)) {
6408 Debug(fprintf(stderr,
"couldn't release stack:%p:%d\n",
6409 m.AllocationBase, GetLastError()));
6420 rb_fatal(
"failed to launch waiter thread:%ld", GetLastError());
6428rb_w32_get_environ(
void)
6430 WCHAR *envtop, *env;
6431 char **myenvtop, **myenv;
6444 envtop = GetEnvironmentStringsW();
6445 for (env = envtop, num = 0; *env; env += lstrlenW(env) + 1)
6446 if (*env !=
'=') num++;
6448 myenvtop = (
char **)malloc(
sizeof(
char *) * (num + 1));
6449 for (env = envtop, myenv = myenvtop; *env; env += lstrlenW(env) + 1) {
6451 if (!(*myenv = wstr_to_utf8(env, NULL))) {
6458 FreeEnvironmentStringsW(envtop);
6465rb_w32_free_environ(
char **env)
6469 while (*t) free(*t++);
6477 return GetCurrentProcessId();
6485 typedef long (WINAPI query_func)(HANDLE, int,
void *, ULONG, ULONG *);
6486 static query_func *pNtQueryInformationProcess = (query_func *)-1;
6489 if (pNtQueryInformationProcess == (query_func *)-1)
6490 pNtQueryInformationProcess = (query_func *)get_proc_address(
"ntdll.dll",
"NtQueryInformationProcess", NULL);
6491 if (pNtQueryInformationProcess) {
6494 void* PebBaseAddress;
6495 uintptr_t AffinityMask;
6496 uintptr_t BasePriority;
6497 uintptr_t UniqueProcessId;
6498 uintptr_t ParentProcessId;
6501 long ret = pNtQueryInformationProcess(GetCurrentProcess(), 0, &pbi,
sizeof(pbi), &
len);
6503 ppid = pbi.ParentProcessId;
6510STATIC_ASSERT(std_handle, (STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)==(STD_ERROR_HANDLE-STD_OUTPUT_HANDLE));
6513#define set_new_std_handle(newfd, handle) do { \
6514 if ((unsigned)(newfd) > 2) break; \
6515 SetStdHandle(STD_INPUT_HANDLE+(STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)*(newfd), \
6518#define set_new_std_fd(newfd) set_new_std_handle(newfd, (HANDLE)rb_w32_get_osfhandle(newfd))
6522rb_w32_dup2(
int oldfd,
int newfd)
6526 if (oldfd == newfd)
return newfd;
6527 ret = dup2(oldfd, newfd);
6528 if (ret < 0)
return ret;
6529 set_new_std_fd(newfd);
6535rb_w32_uopen(
const char *file,
int oflag, ...)
6542 va_start(arg, oflag);
6543 pmode = va_arg(arg,
int);
6546 if (!(wfile = utf8_to_wstr(file, NULL)))
6548 ret = w32_wopen(wfile, oflag, pmode);
6555check_if_wdir(
const WCHAR *wfile)
6557 DWORD attr = GetFileAttributesW(wfile);
6558 if (attr == (DWORD)-1L ||
6559 !(attr & FILE_ATTRIBUTE_DIRECTORY) ||
6560 check_valid_dir(wfile)) {
6569rb_w32_open(
const char *file,
int oflag, ...)
6576 va_start(arg, oflag);
6577 pmode = va_arg(arg,
int);
6580 if (!(wfile = filecp_to_wstr(file, NULL)))
6582 ret = w32_wopen(wfile, oflag, pmode);
6589rb_w32_wopen(
const WCHAR *file,
int oflag, ...)
6593 if (oflag & O_CREAT) {
6595 va_start(arg, oflag);
6596 pmode = va_arg(arg,
int);
6600 return w32_wopen(file, oflag, pmode);
6604w32_wopen(
const WCHAR *file,
int oflag,
int pmode)
6610 DWORD attr = FILE_ATTRIBUTE_NORMAL;
6611 SECURITY_ATTRIBUTES sec;
6615 share_delete = oflag & O_SHARE_DELETE ? FILE_SHARE_DELETE : 0;
6616 oflag &= ~O_SHARE_DELETE;
6617 if ((oflag & O_TEXT) || !(oflag & O_BINARY)) {
6618 fd = _wopen(file, oflag, pmode);
6622 check_if_wdir(file);
6625 errno = map_errno(GetLastError());
6632 sec.nLength =
sizeof(sec);
6633 sec.lpSecurityDescriptor = NULL;
6634 if (oflag & O_NOINHERIT) {
6635 sec.bInheritHandle = FALSE;
6636 flags |= FNOINHERIT;
6639 sec.bInheritHandle = TRUE;
6641 oflag &= ~O_NOINHERIT;
6644 oflag &= ~(O_BINARY | O_TEXT);
6646 switch (oflag & (O_RDWR | O_RDONLY | O_WRONLY)) {
6648 access = GENERIC_READ | GENERIC_WRITE;
6651 access = GENERIC_READ;
6654 access = GENERIC_WRITE;
6660 oflag &= ~(O_RDWR | O_RDONLY | O_WRONLY);
6662 switch (oflag & (O_CREAT | O_EXCL | O_TRUNC)) {
6664 create = OPEN_ALWAYS;
6668 create = OPEN_EXISTING;
6670 case O_CREAT | O_EXCL:
6671 case O_CREAT | O_EXCL | O_TRUNC:
6672 create = CREATE_NEW;
6675 case O_TRUNC | O_EXCL:
6676 create = TRUNCATE_EXISTING;
6678 case O_CREAT | O_TRUNC:
6679 create = CREATE_ALWAYS;
6685 if (oflag & O_CREAT) {
6687 if (!(pmode & S_IWRITE))
6688 attr = FILE_ATTRIBUTE_READONLY;
6690 oflag &= ~(O_CREAT | O_EXCL | O_TRUNC);
6692 if (oflag & O_TEMPORARY) {
6693 attr |= FILE_FLAG_DELETE_ON_CLOSE;
6696 oflag &= ~O_TEMPORARY;
6698 if (oflag & _O_SHORT_LIVED)
6699 attr |= FILE_ATTRIBUTE_TEMPORARY;
6700 oflag &= ~_O_SHORT_LIVED;
6702 switch (oflag & (O_SEQUENTIAL | O_RANDOM)) {
6706 attr |= FILE_FLAG_SEQUENTIAL_SCAN;
6709 attr |= FILE_FLAG_RANDOM_ACCESS;
6715 oflag &= ~(O_SEQUENTIAL | O_RANDOM);
6717 if (oflag & ~O_APPEND) {
6724 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6725 fd = _open_osfhandle((intptr_t)h, 0);
6733 rb_acrt_lowio_lock_fh(fd);
6734 _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE);
6735 _set_osflags(fd, 0);
6737 h = CreateFileW(file, access, FILE_SHARE_READ | FILE_SHARE_WRITE | share_delete, &sec, create, attr, NULL);
6738 if (h == INVALID_HANDLE_VALUE) {
6739 DWORD e = GetLastError();
6740 if (e != ERROR_ACCESS_DENIED || !check_if_wdir(file))
6741 errno = map_errno(e);
6742 rb_acrt_lowio_unlock_fh(fd);
6747 switch (GetFileType(h)) {
6748 case FILE_TYPE_CHAR:
6751 case FILE_TYPE_PIPE:
6754 case FILE_TYPE_UNKNOWN:
6755 errno = map_errno(GetLastError());
6757 rb_acrt_lowio_unlock_fh(fd);
6761 if (!(flags & (FDEV | FPIPE)) && (oflag & O_APPEND))
6764 _set_osfhnd(fd, (intptr_t)h);
6765 _set_osflags(fd, flags | FOPEN);
6767 rb_acrt_lowio_unlock_fh(fd);
6777rb_w32_fclose(
FILE *fp)
6779 int fd = fileno(fp);
6780 SOCKET sock = TO_SOCKET(fd);
6781 int save_errno =
errno;
6783 if (fflush(fp))
return -1;
6784 if (!is_socket(sock)) {
6785 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
6788 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
6791 if (closesocket(sock) == SOCKET_ERROR) {
6792 errno = map_errno(WSAGetLastError());
6800rb_w32_pipe(
int fds[2])
6802 static long serial = 0;
6803 static const char prefix[] =
"\\\\.\\pipe\\ruby";
6805 width_of_prefix = (int)
sizeof(prefix) - 1,
6806 width_of_pid = (int)
sizeof(rb_pid_t) * 2,
6807 width_of_serial = (int)
sizeof(serial) * 2,
6808 width_of_ids = width_of_pid + 1 + width_of_serial + 1
6810 char name[
sizeof(prefix) + width_of_ids];
6811 SECURITY_ATTRIBUTES sec;
6812 HANDLE hRead, hWrite, h;
6813 int fdRead, fdWrite;
6816 memcpy(name, prefix, width_of_prefix);
6817 snprintf(name + width_of_prefix, width_of_ids,
"%.*"PRI_PIDT_PREFIX"x-%.*lx",
6818 width_of_pid, rb_w32_getpid(), width_of_serial, (
unsigned long)(InterlockedIncrement(&serial)-1));
6820 sec.nLength =
sizeof(sec);
6821 sec.lpSecurityDescriptor = NULL;
6822 sec.bInheritHandle = FALSE;
6825 hRead = CreateNamedPipe(name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
6826 0, 2, 65536, 65536, 0, &sec);
6828 if (hRead == INVALID_HANDLE_VALUE) {
6829 DWORD err = GetLastError();
6830 if (err == ERROR_PIPE_BUSY)
6833 errno = map_errno(GetLastError());
6838 hWrite = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, &sec,
6839 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
6841 if (hWrite == INVALID_HANDLE_VALUE) {
6842 errno = map_errno(GetLastError());
6849 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6850 fdRead = _open_osfhandle((intptr_t)h, 0);
6854 CloseHandle(hWrite);
6860 rb_acrt_lowio_lock_fh(fdRead);
6861 _set_osfhnd(fdRead, (intptr_t)hRead);
6862 _set_osflags(fdRead, FOPEN | FPIPE | FNOINHERIT);
6863 rb_acrt_lowio_unlock_fh(fdRead);
6869 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6870 fdWrite = _open_osfhandle((intptr_t)h, 0);
6872 if (fdWrite == -1) {
6874 CloseHandle(hWrite);
6878 rb_acrt_lowio_lock_fh(fdWrite);
6879 _set_osfhnd(fdWrite, (intptr_t)hWrite);
6880 _set_osflags(fdWrite, FOPEN | FPIPE | FNOINHERIT);
6881 rb_acrt_lowio_unlock_fh(fdWrite);
6884 rb_w32_close(fdRead);
6896console_emulator_p(
void)
6898 const void *
const func = WriteConsoleW;
6900 MEMORY_BASIC_INFORMATION m;
6902 memset(&m, 0,
sizeof(m));
6903 if (!VirtualQuery(func, &m,
sizeof(m))) {
6906 k = GetModuleHandle(
"kernel32.dll");
6907 if (!k)
return FALSE;
6908 return (HMODULE)m.AllocationBase != k;
6913constat_handle(HANDLE h)
6917 thread_exclusive(conlist) {
6919 if (console_emulator_p()) {
6920 conlist = conlist_disabled;
6923 conlist = st_init_numtable();
6924 install_vm_exit_handler();
6926 else if (conlist == conlist_disabled) {
6929 if (st_lookup(conlist, (st_data_t)h, &data)) {
6933 CONSOLE_SCREEN_BUFFER_INFO csbi;
6935 p->vt100.state = constat_init;
6936 p->vt100.attr = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
6937 p->vt100.reverse = 0;
6938 p->vt100.saved.X = p->vt100.saved.Y = 0;
6939 if (GetConsoleScreenBufferInfo(h, &csbi)) {
6940 p->vt100.attr = csbi.wAttributes;
6942 st_insert(conlist, (st_data_t)h, (st_data_t)p);
6948#define FOREGROUND_MASK (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY)
6949#define BACKGROUND_MASK (BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY)
6951#define constat_attr_color_reverse(attr) \
6952 ((attr) & ~(FOREGROUND_MASK | BACKGROUND_MASK)) | \
6953 (((attr) & FOREGROUND_MASK) << 4) | \
6954 (((attr) & BACKGROUND_MASK) >> 4)
6958constat_attr(
int count,
const int *seq, WORD attr, WORD default_attr,
int *reverse)
6963 if (!count)
return attr;
6964 if (rev) attr = constat_attr_color_reverse(attr);
6965 bold = attr & FOREGROUND_INTENSITY;
6966 attr &= ~(FOREGROUND_INTENSITY | BACKGROUND_INTENSITY);
6968 while (count-- > 0) {
6971 attr = default_attr;
6976 bold = FOREGROUND_INTENSITY;
6982#ifndef COMMON_LVB_UNDERSCORE
6983#define COMMON_LVB_UNDERSCORE 0x8000
6985 attr |= COMMON_LVB_UNDERSCORE;
6988 attr &= ~COMMON_LVB_UNDERSCORE;
6998 attr &= ~(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
7001 attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_GREEN)) | FOREGROUND_RED;
7004 attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_RED)) | FOREGROUND_GREEN;
7007 attr = (attr & ~FOREGROUND_BLUE) | FOREGROUND_GREEN | FOREGROUND_RED;
7010 attr = (attr & ~(FOREGROUND_GREEN | FOREGROUND_RED)) | FOREGROUND_BLUE;
7013 attr = (attr & ~FOREGROUND_GREEN) | FOREGROUND_BLUE | FOREGROUND_RED;
7016 attr = (attr & ~FOREGROUND_RED) | FOREGROUND_BLUE | FOREGROUND_GREEN;
7019 attr |= FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
7024 attr = (attr & ~FOREGROUND_MASK) | (default_attr & FOREGROUND_MASK);
7028 attr &= ~(BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED);
7031 attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_GREEN)) | BACKGROUND_RED;
7034 attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_RED)) | BACKGROUND_GREEN;
7037 attr = (attr & ~BACKGROUND_BLUE) | BACKGROUND_GREEN | BACKGROUND_RED;
7040 attr = (attr & ~(BACKGROUND_GREEN | BACKGROUND_RED)) | BACKGROUND_BLUE;
7043 attr = (attr & ~BACKGROUND_GREEN) | BACKGROUND_BLUE | BACKGROUND_RED;
7046 attr = (attr & ~BACKGROUND_RED) | BACKGROUND_BLUE | BACKGROUND_GREEN;
7049 attr |= BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED;
7054 attr = (attr & ~BACKGROUND_MASK) | (default_attr & BACKGROUND_MASK);
7059 if (rev) attr = constat_attr_color_reverse(attr);
7066constat_clear(HANDLE handle, WORD attr, DWORD
len, COORD pos)
7070 FillConsoleOutputAttribute(handle, attr,
len, pos, &written);
7071 FillConsoleOutputCharacterW(handle, L
' ',
len, pos, &written);
7076constat_apply(HANDLE handle,
struct constat *s, WCHAR w)
7078 CONSOLE_SCREEN_BUFFER_INFO csbi;
7079 const int *seq = s->vt100.seq;
7080 int count = s->vt100.state;
7084 if (!GetConsoleScreenBufferInfo(handle, &csbi))
return;
7085 arg0 = (count > 0 && seq[0] > 0);
7086 if (arg0) arg1 = seq[0];
7089 SetConsoleTextAttribute(handle, constat_attr(count, seq, csbi.wAttributes, s->vt100.attr, &s->vt100.reverse));
7092 csbi.dwCursorPosition.X = 0;
7094 csbi.dwCursorPosition.Y -= arg1;
7095 if (csbi.dwCursorPosition.Y < csbi.srWindow.Top)
7096 csbi.dwCursorPosition.Y = csbi.srWindow.Top;
7097 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7100 csbi.dwCursorPosition.X = 0;
7103 csbi.dwCursorPosition.Y += arg1;
7104 if (csbi.dwCursorPosition.Y > csbi.srWindow.Bottom)
7105 csbi.dwCursorPosition.Y = csbi.srWindow.Bottom;
7106 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7109 csbi.dwCursorPosition.X += arg1;
7110 if (csbi.dwCursorPosition.X >= csbi.srWindow.Right)
7111 csbi.dwCursorPosition.X = csbi.srWindow.Right;
7112 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7115 csbi.dwCursorPosition.X -= arg1;
7116 if (csbi.dwCursorPosition.X < csbi.srWindow.Left)
7117 csbi.dwCursorPosition.X = csbi.srWindow.Left;
7118 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7122 arg1 += csbi.srWindow.Left;
7123 if (arg1 > csbi.srWindow.Right)
7124 arg1 = csbi.srWindow.Right;
7125 csbi.dwCursorPosition.X = arg1;
7126 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7129 arg1 += csbi.srWindow.Top;
7130 if (arg1 > csbi.srWindow.Bottom)
7131 arg1 = csbi.srWindow.Bottom;
7132 csbi.dwCursorPosition.Y = arg1;
7133 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7137 pos.Y = arg1 + csbi.srWindow.Top - 1;
7138 if (pos.Y > csbi.srWindow.Bottom) pos.Y = csbi.srWindow.Bottom;
7139 if (count < 2 || (arg1 = seq[1]) <= 0) arg1 = 1;
7140 pos.X = arg1 + csbi.srWindow.Left - 1;
7141 if (pos.X > csbi.srWindow.Right) pos.X = csbi.srWindow.Right;
7142 SetConsoleCursorPosition(handle, pos);
7145 switch (arg0 ? arg1 : 0) {
7147 constat_clear(handle, csbi.wAttributes,
7148 (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.dwCursorPosition.Y + 1)
7149 - csbi.dwCursorPosition.X),
7150 csbi.dwCursorPosition);
7154 pos.Y = csbi.srWindow.Top;
7155 constat_clear(handle, csbi.wAttributes,
7156 (csbi.dwSize.X * (csbi.dwCursorPosition.Y - csbi.srWindow.Top)
7157 + csbi.dwCursorPosition.X + 1),
7162 pos.Y = csbi.srWindow.Top;
7163 constat_clear(handle, csbi.wAttributes,
7164 (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1)),
7170 constat_clear(handle, csbi.wAttributes,
7171 (csbi.dwSize.X * csbi.dwSize.Y),
7177 switch (arg0 ? arg1 : 0) {
7179 constat_clear(handle, csbi.wAttributes,
7180 (csbi.dwSize.X - csbi.dwCursorPosition.X),
7181 csbi.dwCursorPosition);
7185 pos.Y = csbi.dwCursorPosition.Y;
7186 constat_clear(handle, csbi.wAttributes,
7187 csbi.dwCursorPosition.X + 1, pos);
7191 pos.Y = csbi.dwCursorPosition.Y;
7192 constat_clear(handle, csbi.wAttributes,
7193 csbi.dwSize.X, pos);
7198 s->vt100.saved = csbi.dwCursorPosition;
7201 SetConsoleCursorPosition(handle, s->vt100.saved);
7204 if (count >= 2 && seq[0] == -1 && seq[1] == 25) {
7205 CONSOLE_CURSOR_INFO cci;
7206 GetConsoleCursorInfo(handle, &cci);
7207 cci.bVisible = TRUE;
7208 SetConsoleCursorInfo(handle, &cci);
7212 if (count >= 2 && seq[0] == -1 && seq[1] == 25) {
7213 CONSOLE_CURSOR_INFO cci;
7214 GetConsoleCursorInfo(handle, &cci);
7215 cci.bVisible = FALSE;
7216 SetConsoleCursorInfo(handle, &cci);
7224static const long MAXSIZE_CONSOLE_WRITING = 31366;
7228constat_parse(HANDLE h,
struct constat *s,
const WCHAR **ptrp,
long *lenp)
7230 const WCHAR *ptr = *ptrp;
7231 long rest,
len = *lenp;
7235 rest = *lenp -
len - 1;
7236 if (s->vt100.state == constat_esc) {
7239 s->vt100.state = constat_init;
7240 if (
len > 0 && *ptr != L
'[')
continue;
7241 s->vt100.state = constat_esc;
7243 else if (s->vt100.state == constat_esc) {
7246 s->vt100.state = constat_init;
7249 rest = *lenp -
len - 1;
7250 if (rest > 0) --rest;
7251 s->vt100.state = constat_seq;
7252 s->vt100.seq[0] = 0;
7254 else if (s->vt100.state >= constat_seq) {
7255 if (wc >= L
'0' && wc <= L
'9') {
7256 if (s->vt100.state < (
int)numberof(s->vt100.seq)) {
7257 int *seq = &s->vt100.seq[s->vt100.state];
7258 *seq = (*seq * 10) + (wc - L
'0');
7261 else if (s->vt100.state == constat_seq && s->vt100.seq[0] == 0 && wc == L
'?') {
7262 s->vt100.seq[s->vt100.state++] = -1;
7266 if (++s->vt100.state < (
int)numberof(s->vt100.seq)) {
7267 s->vt100.seq[s->vt100.state] = 0;
7270 s->vt100.state = (int)numberof(s->vt100.seq);
7274 constat_apply(h, s, wc);
7275 s->vt100.state = constat_init;
7280 else if ((rest = *lenp -
len) < MAXSIZE_CONSOLE_WRITING) {
7298 SOCKET sock = TO_SOCKET(fd);
7299 int save_errno =
errno;
7301 if (!is_socket(sock)) {
7302 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
7303 constat_delete((HANDLE)sock);
7306 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
7307 socklist_delete(&sock, NULL);
7310 if (closesocket(sock) == SOCKET_ERROR) {
7311 errno = map_errno(WSAGetLastError());
7317#ifndef INVALID_SET_FILE_POINTER
7318#define INVALID_SET_FILE_POINTER ((DWORD)-1)
7322setup_overlapped(OVERLAPPED *ol,
int fd,
int iswrite, rb_off_t *_offset)
7324 memset(ol, 0,
sizeof(*ol));
7329 DWORD seek_method = ((_osfile(fd) & FAPPEND) && iswrite) ? FILE_END : FILE_CURRENT;
7333 uint64_t offset = *_offset;
7334 ol->Offset = (uint32_t)(offset & 0xFFFFFFFFLL);
7335 ol->OffsetHigh = (uint32_t)((offset & 0xFFFFFFFF00000000LL) >> 32);
7338 LARGE_INTEGER seek_offset = {0}, current_offset = {0};
7339 if (!SetFilePointerEx((HANDLE)_osfhnd(fd), seek_offset, ¤t_offset, seek_method)) {
7340 DWORD last_error = GetLastError();
7341 if (last_error != NO_ERROR) {
7342 errno = map_errno(last_error);
7348 *_offset = current_offset.QuadPart;
7350 else if (!(_osfile(fd) & (FDEV | FPIPE))) {
7352 DWORD low = SetFilePointer((HANDLE)_osfhnd(fd), 0, &high, seek_method);
7354 if (low == INVALID_SET_FILE_POINTER) {
7355 DWORD err = GetLastError();
7356 if (err != NO_ERROR) {
7357 errno = map_errno(err);
7363 ol->OffsetHigh = high;
7366 ol->hEvent = CreateEvent(NULL, TRUE, TRUE, NULL);
7368 errno = map_errno(GetLastError());
7375finish_overlapped(OVERLAPPED *ol,
int fd, DWORD size, rb_off_t *_offset)
7377 CloseHandle(ol->hEvent);
7381 DWORD seek_method = (_osfile(fd) & FAPPEND) ? FILE_END : FILE_BEGIN;
7383 LARGE_INTEGER seek_offset = {0};
7384 if (seek_method == FILE_BEGIN) {
7385 seek_offset.QuadPart = *_offset;
7388 SetFilePointerEx((HANDLE)_osfhnd(fd), seek_offset, NULL, seek_method);
7390 else if (!(_osfile(fd) & (FDEV | FPIPE))) {
7391 LONG high = ol->OffsetHigh;
7392 DWORD low = ol->Offset + size;
7393 if (low < ol->Offset)
7395 SetFilePointer((HANDLE)_osfhnd(fd), low, &high, FILE_BEGIN);
7402rb_w32_read_internal(
int fd,
void *buf,
size_t size, rb_off_t *offset)
7404 SOCKET sock = TO_SOCKET(fd);
7412 if (is_socket(sock))
7413 return rb_w32_recv(fd, buf, size, 0);
7416 if (_get_osfhandle(fd) == -1) {
7420 if (!offset && _osfile(fd) & FTEXT) {
7421 return _read(fd, buf, size);
7424 rb_acrt_lowio_lock_fh(fd);
7426 if (!size || _osfile(fd) & FEOFLAG) {
7427 _set_osflags(fd, _osfile(fd) & ~FEOFLAG);
7428 rb_acrt_lowio_unlock_fh(fd);
7437 if (setup_overlapped(&ol, fd, FALSE, offset)) {
7438 rb_acrt_lowio_unlock_fh(fd);
7442 if (!ReadFile((HANDLE)_osfhnd(fd), buf,
len, &read, &ol)) {
7443 err = GetLastError();
7444 if (err == ERROR_NO_DATA && (_osfile(fd) & FPIPE)) {
7446 if (GetNamedPipeHandleState((HANDLE)_osfhnd(fd), &state, NULL, NULL, NULL, NULL, 0) && (state & PIPE_NOWAIT)) {
7447 errno = EWOULDBLOCK;
7450 errno = map_errno(err);
7452 rb_acrt_lowio_unlock_fh(fd);
7455 else if (err != ERROR_IO_PENDING) {
7456 CloseHandle(ol.hEvent);
7457 if (err == ERROR_ACCESS_DENIED)
7459 else if (err == ERROR_BROKEN_PIPE || err == ERROR_HANDLE_EOF) {
7460 rb_acrt_lowio_unlock_fh(fd);
7464 errno = map_errno(err);
7466 rb_acrt_lowio_unlock_fh(fd);
7470 wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE);
7471 if (wait != WAIT_OBJECT_0) {
7472 if (wait == WAIT_OBJECT_0 + 1)
7475 errno = map_errno(GetLastError());
7476 CloseHandle(ol.hEvent);
7477 CancelIo((HANDLE)_osfhnd(fd));
7478 rb_acrt_lowio_unlock_fh(fd);
7482 if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &read, TRUE) &&
7483 (err = GetLastError()) != ERROR_HANDLE_EOF) {
7485 if (err != ERROR_BROKEN_PIPE) {
7486 errno = map_errno(err);
7489 CloseHandle(ol.hEvent);
7490 CancelIo((HANDLE)_osfhnd(fd));
7491 rb_acrt_lowio_unlock_fh(fd);
7496 err = GetLastError();
7497 errno = map_errno(err);
7500 finish_overlapped(&ol, fd, read, offset);
7504 buf = (
char *)buf + read;
7505 if (err != ERROR_OPERATION_ABORTED && size > 0)
7509 _set_osflags(fd, _osfile(fd) | FEOFLAG);
7512 rb_acrt_lowio_unlock_fh(fd);
7520rb_w32_write_internal(
int fd,
const void *buf,
size_t size, rb_off_t *offset)
7522 SOCKET sock = TO_SOCKET(fd);
7530 if (is_socket(sock))
7531 return rb_w32_send(fd, buf, size, 0);
7534 if (_get_osfhandle(fd) == -1) {
7539 if (!offset && (_osfile(fd) & FTEXT) &&
7540 (!(_osfile(fd) & FPIPE) || fd == fileno(stdout) || fd == fileno(stderr))) {
7541 ssize_t w = _write(fd, buf, size);
7542 if (w == (ssize_t)-1 &&
errno == EINVAL) {
7543 errno = map_errno(GetLastError());
7548 rb_acrt_lowio_lock_fh(fd);
7550 if (!size || _osfile(fd) & FEOFLAG) {
7551 rb_acrt_lowio_unlock_fh(fd);
7557 len = (_osfile(fd) & FDEV) ? min(MAXSIZE_CONSOLE_WRITING, size) : size;
7562 if (setup_overlapped(&ol, fd, TRUE, offset)) {
7563 rb_acrt_lowio_unlock_fh(fd);
7567 if (!WriteFile((HANDLE)_osfhnd(fd), buf,
len, &written, &ol)) {
7568 err = GetLastError();
7569 if (err != ERROR_IO_PENDING) {
7570 CloseHandle(ol.hEvent);
7571 if (err == ERROR_ACCESS_DENIED)
7574 errno = map_errno(err);
7576 rb_acrt_lowio_unlock_fh(fd);
7580 wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE);
7581 if (wait != WAIT_OBJECT_0) {
7582 if (wait == WAIT_OBJECT_0 + 1)
7585 errno = map_errno(GetLastError());
7586 CloseHandle(ol.hEvent);
7587 CancelIo((HANDLE)_osfhnd(fd));
7588 rb_acrt_lowio_unlock_fh(fd);
7592 if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &written, TRUE)) {
7593 errno = map_errno(GetLastError());
7594 CloseHandle(ol.hEvent);
7595 CancelIo((HANDLE)_osfhnd(fd));
7596 rb_acrt_lowio_unlock_fh(fd);
7601 finish_overlapped(&ol, fd, written, offset);
7604 if (written ==
len) {
7605 buf = (
const char *)buf +
len;
7610 size_t newlen =
len / 2;
7612 size +=
len - newlen;
7617 errno = EWOULDBLOCK;
7620 rb_acrt_lowio_unlock_fh(fd);
7626rb_w32_read(
int fd,
void *buf,
size_t size)
7628 return rb_w32_read_internal(fd, buf, size, NULL);
7632rb_w32_write(
int fd,
const void *buf,
size_t size)
7634 return rb_w32_write_internal(fd, buf, size, NULL);
7638rb_w32_pread(
int descriptor,
void *base,
size_t size, rb_off_t offset)
7640 return rb_w32_read_internal(descriptor, base, size, &offset);
7644rb_w32_pwrite(
int descriptor,
const void *base,
size_t size, rb_off_t offset)
7646 return rb_w32_write_internal(descriptor, base, size, &offset);
7651rb_w32_write_console(uintptr_t strarg,
int fd)
7654 DWORD dwMode, reslen;
7658 const WCHAR *ptr, *next;
7662 handle = (HANDLE)_osfhnd(fd);
7663 if (!GetConsoleMode(handle, &dwMode))
7666 s = constat_handle(handle);
7676 case ENCINDEX_US_ASCII:
7677 case ENCINDEX_ASCII_8BIT:
7679 case ENCINDEX_UTF_8:
7680 ptr = wbuffer = mbstr_to_wstr(CP_UTF8, RSTRING_PTR(str), RSTRING_LEN(str), &
len);
7681 if (!ptr)
return -1L;
7683 case ENCINDEX_UTF_16LE:
7684 ptr = (
const WCHAR *)RSTRING_PTR(str);
7685 len = RSTRING_LEN(str) /
sizeof(WCHAR);
7689 if (dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) {
7690 if (!WriteConsoleW(handle, ptr,
len, &reslen, NULL))
7691 reslen = (DWORD)-1L;
7695 long curlen = constat_parse(handle, s, (next = ptr, &next), &
len);
7696 reslen += next - ptr;
7699 if (!WriteConsoleW(handle, ptr, curlen, &written, NULL)) {
7700 reslen = (DWORD)-1L;
7709 return (
long)reslen;
7714timespec_to_filetime(
const struct timespec *ts, FILETIME *ft)
7718 tmp.QuadPart = unix_to_filetime((ULONGLONG)ts->tv_sec);
7719 tmp.QuadPart += ts->tv_nsec / 100;
7720 ft->dwLowDateTime = tmp.LowPart;
7721 ft->dwHighDateTime = tmp.HighPart;
7727wutimensat(
int dirfd,
const WCHAR *path,
const struct timespec *times,
int flags)
7730 FILETIME atime, mtime;
7735 if (dirfd != AT_FDCWD) {
7745 if (wstati128(path, &stat, FALSE)) {
7750 if (timespec_to_filetime(×[0], &atime)) {
7753 if (timespec_to_filetime(×[1], &mtime)) {
7758 GetSystemTimePreciseAsFileTime(&atime);
7763 const DWORD attr = GetFileAttributesW(path);
7764 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY))
7765 SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY);
7766 hFile = open_special(path, GENERIC_WRITE, 0);
7767 if (hFile == INVALID_HANDLE_VALUE) {
7768 errno = map_errno(GetLastError());
7772 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
7773 errno = map_errno(GetLastError());
7778 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY))
7779 SetFileAttributesW(path, attr);
7787w32_utimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags, UINT cp)
7789 WCHAR *wpath = mbstr_to_wstr(cp, path, -1, NULL);
7793 ret = wutimensat(dirfd, wpath, times, flags);
7801rb_w32_uutime(
const char *path,
const struct utimbuf *times)
7805 ts[0].tv_sec = times->actime;
7807 ts[1].tv_sec = times->modtime;
7809 return w32_utimensat(AT_FDCWD, path, ts, 0, CP_UTF8);
7814rb_w32_utime(
const char *path,
const struct utimbuf *times)
7818 ts[0].tv_sec = times->actime;
7820 ts[1].tv_sec = times->modtime;
7822 return w32_utimensat(AT_FDCWD, path, ts, 0, filecp());
7827rb_w32_uutimes(
const char *path,
const struct timeval *times)
7831 ts[0].tv_sec = times[0].tv_sec;
7832 ts[0].tv_nsec = times[0].tv_usec * 1000;
7833 ts[1].tv_sec = times[1].tv_sec;
7834 ts[1].tv_nsec = times[1].tv_usec * 1000;
7835 return w32_utimensat(AT_FDCWD, path, ts, 0, CP_UTF8);
7840rb_w32_utimes(
const char *path,
const struct timeval *times)
7844 ts[0].tv_sec = times[0].tv_sec;
7845 ts[0].tv_nsec = times[0].tv_usec * 1000;
7846 ts[1].tv_sec = times[1].tv_sec;
7847 ts[1].tv_nsec = times[1].tv_usec * 1000;
7848 return w32_utimensat(AT_FDCWD, path, ts, 0, filecp());
7853rb_w32_uutimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags)
7855 return w32_utimensat(dirfd, path, times, flags, CP_UTF8);
7860rb_w32_utimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags)
7862 return w32_utimensat(dirfd, path, times, flags, filecp());
7867rb_w32_uchdir(
const char *path)
7872 if (!(wpath = utf8_to_wstr(path, NULL)))
7874 ret = _wchdir(wpath);
7881wmkdir(
const WCHAR *wpath,
int mode)
7886 if (CreateDirectoryW(wpath, NULL) == FALSE) {
7887 errno = map_errno(GetLastError());
7890 if (_wchmod(wpath, mode) == -1) {
7891 RemoveDirectoryW(wpath);
7901rb_w32_umkdir(
const char *path,
int mode)
7906 if (!(wpath = utf8_to_wstr(path, NULL)))
7908 ret = wmkdir(wpath, mode);
7915rb_w32_mkdir(
const char *path,
int mode)
7920 if (!(wpath = filecp_to_wstr(path, NULL)))
7922 ret = wmkdir(wpath, mode);
7929wrmdir(
const WCHAR *wpath)
7933 const DWORD attr = GetFileAttributesW(wpath);
7934 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7935 SetFileAttributesW(wpath, attr & ~FILE_ATTRIBUTE_READONLY);
7937 if (RemoveDirectoryW(wpath) == FALSE) {
7938 errno = map_errno(GetLastError());
7940 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7941 SetFileAttributesW(wpath, attr);
7950rb_w32_rmdir(
const char *path)
7955 if (!(wpath = filecp_to_wstr(path, NULL)))
7957 ret = wrmdir(wpath);
7964rb_w32_urmdir(
const char *path)
7969 if (!(wpath = utf8_to_wstr(path, NULL)))
7971 ret = wrmdir(wpath);
7978wunlink(
const WCHAR *path)
7981 const DWORD SYMLINKD = FILE_ATTRIBUTE_REPARSE_POINT|FILE_ATTRIBUTE_DIRECTORY;
7983 const DWORD attr = GetFileAttributesW(path);
7984 if (attr == (DWORD)-1) {
7986 else if ((attr & SYMLINKD) == SYMLINKD) {
7987 ret = RemoveDirectoryW(path);
7990 if (attr & FILE_ATTRIBUTE_READONLY) {
7991 SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY);
7993 ret = DeleteFileW(path);
7996 errno = map_errno(GetLastError());
7998 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7999 SetFileAttributesW(path, attr);
8008rb_w32_uunlink(
const char *path)
8013 if (!(wpath = utf8_to_wstr(path, NULL)))
8015 ret = wunlink(wpath);
8022rb_w32_unlink(
const char *path)
8027 if (!(wpath = filecp_to_wstr(path, NULL)))
8029 ret = wunlink(wpath);
8036rb_w32_uchmod(
const char *path,
int mode)
8041 if (!(wpath = utf8_to_wstr(path, NULL)))
8043 ret = _wchmod(wpath, mode);
8050fchmod(
int fd,
int mode)
8054 LARGE_INTEGER CreationTime;
8055 LARGE_INTEGER LastAccessTime;
8056 LARGE_INTEGER LastWriteTime;
8057 LARGE_INTEGER ChangeTime;
8058 DWORD FileAttributes;
8059 } info = {{{0}}, {{0}}, {{0}},};
8060 HANDLE h = (HANDLE)_get_osfhandle(fd);
8062 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
8063 if (!(mode & 0200)) info.FileAttributes |= FILE_ATTRIBUTE_READONLY;
8064 if (!SetFileInformationByHandle(h, 0, &info,
sizeof(info))) {
8065 errno = map_errno(GetLastError());
8073rb_w32_isatty(
int fd)
8078 if (_get_osfhandle(fd) == -1) {
8081 if (!GetConsoleMode((HANDLE)_osfhnd(fd), &mode)) {
8093 int *ip = (
int *)(&x + 1) - 1;
8100rb_w32_inet_ntop(
int af,
const void *addr,
char *numaddr,
size_t numaddr_len)
8102 return (inet_ntop)(af, (
void *)addr, numaddr, numaddr_len);
8107rb_w32_inet_pton(
int af,
const char *src,
void *dst)
8109 return (inet_pton)(af, src, dst);
8114rb_w32_fd_is_text(
int fd)
8116 return _osfile(fd) & FTEXT;
8119#ifdef HAVE__GMTIME64_S
8120# ifndef HAVE__LOCALTIME64_S
8122# define HAVE__LOCALTIME64_S 1
8124# ifndef MINGW_HAS_SECURE_API
8125 _CRTIMP errno_t __cdecl _gmtime64_s(
struct tm* tm,
const __time64_t *time);
8126 _CRTIMP errno_t __cdecl _localtime64_s(
struct tm* tm,
const __time64_t *time);
8128# define gmtime_s _gmtime64_s
8129# define localtime_s _localtime64_s
8134gmtime_r(
const time_t *tp,
struct tm *rp)
8142 e = gmtime_s(rp, tp);
8143 if (e != 0)
goto error;
8149localtime_r(
const time_t *tp,
struct tm *rp)
8157 e = localtime_s(rp, tp);
8164rb_w32_wrap_io_handle(HANDLE h,
int flags)
8167 int len =
sizeof(tmp);
8168 int r = getsockopt((SOCKET)h, SOL_SOCKET, SO_DEBUG, (
char *)&tmp, &
len);
8169 if (r != SOCKET_ERROR || WSAGetLastError() != WSAENOTSOCK) {
8171 if (flags & O_NONBLOCK) {
8172 flags &= ~O_NONBLOCK;
8175 socklist_insert((SOCKET)h, f);
8177 else if (flags & O_NONBLOCK) {
8181 return rb_w32_open_osfhandle((intptr_t)h, flags);
8186rb_w32_unwrap_io_handle(
int fd)
8188 SOCKET sock = TO_SOCKET(fd);
8189 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
8190 if (!is_socket(sock)) {
8191 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
8192 constat_delete((HANDLE)sock);
8195 socklist_delete(&sock, NULL);
8200#if !defined(__MINGW64__) && defined(__MINGW64_VERSION_MAJOR)
8206rb_w32_pow(
double x,
double y)
8210 unsigned int default_control = _controlfp(0, 0);
8211 _controlfp(_PC_64, _MCW_PC);
8214 _controlfp(default_control, _MCW_PC);
8222 BY_HANDLE_FILE_INFORMATION bhfi;
8233 tmp = rb_check_convert_type_with_id(*file,
T_FILE,
"IO", idTo_io);
8236 if (f == (HANDLE)-1)
return INVALID_HANDLE_VALUE;
8245 tmp = rb_str_encode_ospath(*file);
8246 len = MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, NULL, 0);
8248 MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, ptr,
len);
8249 f = CreateFileW(ptr, 0,
8250 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
8251 FILE_FLAG_BACKUP_SEMANTICS, NULL);
8253 if (f == INVALID_HANDLE_VALUE)
return f;
8256 if (GetFileType(f) == FILE_TYPE_DISK) {
8257 ZeroMemory(st,
sizeof(*st));
8258 if (get_ino(f, &st->info.fii)) {
8259 st->file_id_p = TRUE;
8262 else if (GetLastError() != ERROR_INVALID_PARAMETER) {
8264 return INVALID_HANDLE_VALUE;
8268 if (GetFileInformationByHandle(f, &st->info.bhfi)) {
8269 st->file_id_p = FALSE;
8273 if (ret) CloseHandle(ret);
8274 return INVALID_HANDLE_VALUE;
8278close_handle(
VALUE h)
8280 CloseHandle((HANDLE)h);
8290call_w32_io_info(
VALUE arg)
8293 return (
VALUE)w32_io_info(p->fname, p->st);
8297rb_w32_file_identical_p(
VALUE fname1,
VALUE fname2)
8300 HANDLE f1 = 0, f2 = 0;
8302 f1 = w32_io_info(&fname1, &st1);
8303 if (f1 == INVALID_HANDLE_VALUE)
return Qfalse;
8306 arg.fname = &fname2;
8311 f2 = w32_io_info(&fname2, &st2);
8313 if (f2 == INVALID_HANDLE_VALUE)
return Qfalse;
8314 if (f2) CloseHandle(f2);
8316 if (st1.file_id_p != st2.file_id_p)
return Qfalse;
8317 if (!st1.file_id_p) {
8318 if (st1.info.bhfi.dwVolumeSerialNumber == st2.info.bhfi.dwVolumeSerialNumber &&
8319 st1.info.bhfi.nFileIndexHigh == st2.info.bhfi.nFileIndexHigh &&
8320 st1.info.bhfi.nFileIndexLow == st2.info.bhfi.nFileIndexLow)
8324 if (st1.info.fii.VolumeSerialNumber == st2.info.fii.VolumeSerialNumber &&
8325 memcmp(&st1.info.fii.FileId, &st2.info.fii.FileId,
sizeof(
FILE_ID_128)) == 0)
8332rb_w32_set_thread_description(HANDLE th,
const WCHAR *name)
8335 typedef HRESULT (WINAPI *set_thread_description_func)(HANDLE, PCWSTR);
8336 static set_thread_description_func set_thread_description =
8337 (set_thread_description_func)-1;
8338 if (set_thread_description == (set_thread_description_func)-1) {
8340 set_thread_description = (set_thread_description_func)
8341 get_proc_address(
"kernel32",
"SetThreadDescription", NULL);
8343 if (set_thread_description) {
8344 result = set_thread_description(th, name);
8350rb_w32_set_thread_description_str(HANDLE th,
VALUE name)
8352 int idx, result = FALSE;
8356 return rb_w32_set_thread_description(th, L
"");
8359 idx = rb_enc_get_index(name);
8360 if (idx == ENCINDEX_UTF_16LE) {
8361 result = rb_w32_set_thread_description(th, s);
8364 name =
rb_str_conv_enc(name, rb_enc_from_index(idx), rb_utf8_encoding());
8365 s = mbstr_to_wstr(CP_UTF8, RSTRING_PTR(name), RSTRING_LEN(name)+1, NULL);
8366 result = rb_w32_set_thread_description(th, s);
8376rb_w32_mmap(
void *addr,
size_t len,
int prot,
int flags,
int fd, rb_off_t offset)
8380 DWORD protect = PAGE_EXECUTE_READWRITE;
8382 if (fd > 0 || offset) {
8397 ptr = VirtualAlloc(addr,
len, MEM_RESERVE | MEM_COMMIT, protect);
8399 errno = rb_w32_map_errno(GetLastError());
8407rb_w32_munmap(
void *addr,
size_t len)
8409 if (!VirtualFree(addr, 0, MEM_RELEASE)) {
8410 errno = rb_w32_map_errno(GetLastError());
8418rb_w32_mprotect(
void *addr,
size_t len,
int prot)
8434 if (prot & PROT_EXEC) {
8435 if (!FlushInstructionCache(GetCurrentProcess(), addr,
len)) {
8436 errno = rb_w32_map_errno(GetLastError());
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
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 ALLOC_N
Old name of RB_ALLOC_N.
#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.
#define RBIMPL_ATTR_NONNULL(list)
Wraps (or simulates) __attribute__((nonnull))
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 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.