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);
81#define DLN_FIND_EXTRA_ARG_DECL ,UINT cp
82#define DLN_FIND_EXTRA_ARG ,cp
83#define rb_w32_stati128(path, st) w32_stati128(path, st, cp, FALSE)
84#define getenv(name) w32_getenv(name, cp)
85#define DLN_CHAR_NEXT(p) CharNextExA(cp, (p), 0)
86#define dln_find_exe_r rb_w32_udln_find_exe_r
87#define dln_find_file_r rb_w32_udln_find_file_r
94#define dln_find_exe_r(fname, path, buf, size) rb_w32_udln_find_exe_r(fname, path, buf, size, cp)
95#define dln_find_file_r(fname, path, buf, size) rb_w32_udln_find_file_r(fname, path, buf, size, cp)
101# define PATH_MAX MAX_PATH
102# elif defined HAVE_SYS_PARAM_H
103# include <sys/param.h>
104# define PATH_MAX MAXPATHLEN
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);
134VALUE rb_w32_conv_from_wchar(
const WCHAR *wstr, rb_encoding *enc);
135int ruby_brace_glob_with_enc(
const char *str,
int flags,
ruby_glob_func *func,
VALUE arg, rb_encoding *enc);
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;
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 == path || *(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 len = 0, len2;
526#define alloc_buffer(len) \
527 if ((buffer = malloc(sizeof(WCHAR) * len)) != NULL) ; \
530 if ((
len = GetEnvironmentVariableW(L
"HOME", NULL, 0)) != 0) {
532 GetEnvironmentVariableW(L
"HOME", buffer,
len);
534 else if ((
len = GetEnvironmentVariableW(L
"USERPROFILE", NULL, 0)) != 0) {
536 GetEnvironmentVariableW(L
"USERPROFILE", buffer,
len);
538 else if ((
len = GetEnvironmentVariableW(L
"HOMEDRIVE", NULL, 0)) != 0 &&
539 (len2 = GetEnvironmentVariableW(L
"HOMEPATH", NULL, 0)) != 0) {
542 len = GetEnvironmentVariableW(L
"HOMEDRIVE", buffer,
len);
543 GetEnvironmentVariableW(L
"HOMEPATH", buffer +
len, len2 -
len);
546 alloc_buffer(MAX_PATH);
547 if (!get_special_folder(CSIDL_PROFILE, buffer, MAX_PATH) &&
548 !get_special_folder(CSIDL_PERSONAL, buffer, MAX_PATH)) {
552 buffer = realloc(buffer,
sizeof(WCHAR) * (lstrlenW(buffer) + 1));
557 regulate_path(buffer);
568 if (!GetEnvironmentVariableW(L
"HOME", env, numberof(env))) {
569 WCHAR *whome = rb_w32_home_dir();
571 _wputenv_s(L
"HOME", whome);
576 if (!GetEnvironmentVariableW(L
"USER", env, numberof(env))) {
578 if (!GetEnvironmentVariableW(L
"USERNAME", env, numberof(env)) &&
579 !GetUserNameW(env, (
len = numberof(env), &
len))) {
580 NTLoginName =
"<Unknown>";
583 _wputenv_s(L
"USER", env);
584 NTLoginName = rb_w32_wstr_to_mbstr(CP_UTF8, env, -1, NULL);
588 NTLoginName = rb_w32_wstr_to_mbstr(CP_UTF8, env, -1, NULL);
591 if (!GetEnvironmentVariableW(L
"TMPDIR", env, numberof(env)) &&
592 !GetEnvironmentVariableW(L
"TMP", env, numberof(env)) &&
593 !GetEnvironmentVariableW(L
"TEMP", env, numberof(env)) &&
594 rb_w32_system_tmpdir(env, numberof(env))) {
595 _wputenv_s(L
"TMPDIR", env);
599static void init_stdhandle(
void);
603invalid_parameter(
const wchar_t *expr,
const wchar_t *func,
const wchar_t *file,
unsigned int line, uintptr_t dummy)
608int ruby_w32_rtc_error;
616rtc_error_handler(
int e, const
char *src,
int line, const
char *exe, const
char *fmt, ...)
621 if (!ruby_w32_rtc_error)
return 0;
622 str = rb_sprintf(
"%s:%d: ", src, line);
624 rb_str_vcatf(str, fmt, ap);
632static CRITICAL_SECTION select_mutex;
634static CRITICAL_SECTION socklist_mutex;
635static st_table *socklist = NULL;
637static CRITICAL_SECTION conlist_mutex;
638static st_table *conlist = NULL;
639#define conlist_disabled ((st_table *)-1)
641#define thread_exclusive(obj) \
642 for (bool exclusive_for_##obj = (EnterCriticalSection(&obj##_mutex), true); \
643 exclusive_for_##obj; \
644 exclusive_for_##obj = (LeaveCriticalSection(&obj##_mutex), false))
648static DWORD uenvarea_key;
652free_uenvarea(
void *uenvarea)
660 int state, seq[16], reverse;
665enum {constat_init = -2, constat_esc = -1, constat_seq = 0};
669free_conlist(st_data_t key, st_data_t val, st_data_t arg)
677constat_delete(HANDLE h)
679 thread_exclusive(conlist) {
680 if (conlist && conlist != conlist_disabled) {
681 st_data_t key = (st_data_t)h, val;
682 st_delete(conlist, &key, &val);
693 DeleteCriticalSection(&select_mutex);
694 DeleteCriticalSection(&socklist_mutex);
695 DeleteCriticalSection(&conlist_mutex);
696 FlsFree(uenvarea_key);
703 EnterCriticalSection(&socklist_mutex);
705 st_free_table(socklist);
708 LeaveCriticalSection(&socklist_mutex);
710 EnterCriticalSection(&conlist_mutex);
711 if (conlist && conlist != conlist_disabled) {
713 st_free_table(conlist);
716 LeaveCriticalSection(&conlist_mutex);
719#define ATOMIC_LONG_CAS(var, oldval, newval) InterlockedCompareExchange(&(var), (newval), (oldval))
723install_vm_exit_handler(
void)
725 static LONG installed = 0;
728 while ((i = ATOMIC_LONG_CAS(installed, 0, -1)) != 1) {
734 ATOMIC_LONG_CAS(installed, -1, 1);
750 version = MAKEWORD(2, 0);
751 if (WSAStartup(version, &retdata))
752 rb_fatal(
"Unable to locate winsock library!");
753 if (LOBYTE(retdata.wVersion) != 2)
754 rb_fatal(
"could not find version 2 of winsock dll");
756 InitializeCriticalSection(&select_mutex);
757 InitializeCriticalSection(&socklist_mutex);
758 InitializeCriticalSection(&conlist_mutex);
760 atexit(exit_handler);
763#define MAKE_SOCKDATA(af, fl) ((int)((((int)af)<<4)|((fl)&0xFFFF)))
764#define GET_FAMILY(v) ((int)(((v)>>4)&0xFFFF))
765#define GET_FLAGS(v) ((int)((v)&0xFFFF))
769socklist_insert(SOCKET sock,
int flag)
773 thread_exclusive(socklist) {
775 socklist = st_init_numtable();
776 install_vm_exit_handler();
778 ret = st_insert(socklist, (st_data_t)sock, (st_data_t)flag);
786socklist_lookup(SOCKET sock,
int *flagp)
791 thread_exclusive(socklist) {
792 if (!socklist)
continue;
793 ret = st_lookup(socklist, (st_data_t)sock, &data);
803socklist_delete(SOCKET *sockp,
int *flagp)
809 thread_exclusive(socklist) {
810 if (!socklist)
continue;
811 key = (st_data_t)*sockp;
813 data = (st_data_t)*flagp;
814 ret = st_delete(socklist, &key, &data);
816 *sockp = (SOCKET)key;
826# define _CrtSetReportMode(type,mode) ((void)0)
827# define _RTC_SetErrorFunc(func) ((void)0)
829static void set_pioinfo_extra(
void);
830static int w32_cmdvector(
const WCHAR *,
char ***, UINT, rb_encoding *);
847rb_w32_init_long_paths(
void)
850 enum {peb_bit_field_offset = 3, is_long_path_aware_process = 0x80};
851 typedef long (WINAPI version_func)(OSVERSIONINFOW *);
852 typedef void *(WINAPI peb_func)(
void);
853 version_func *pRtlGetVersion;
854 peb_func *pRtlGetCurrentPeb;
858 pRtlGetVersion = (version_func *)get_proc_address(
"ntdll.dll",
"RtlGetVersion", NULL);
859 if (!pRtlGetVersion)
return;
860 memset(&osvi, 0,
sizeof(osvi));
861 osvi.dwOSVersionInfoSize =
sizeof(osvi);
862 if (pRtlGetVersion(&osvi))
return;
865 if (osvi.dwMajorVersion < 10)
return;
866 if (osvi.dwMajorVersion == 10 && osvi.dwMinorVersion == 0 &&
867 osvi.dwBuildNumber < 15063)
return;
869 pRtlGetCurrentPeb = (peb_func *)get_proc_address(
"ntdll.dll",
"RtlGetCurrentPeb", NULL);
870 if (!pRtlGetCurrentPeb)
return;
871 bit_field = (BYTE *)pRtlGetCurrentPeb() + peb_bit_field_offset;
872 *bit_field |= is_long_path_aware_process;
877rb_w32_sysinit(
int *argc,
char ***argv)
879 _CrtSetReportMode(_CRT_ASSERT, 0);
880 _set_invalid_parameter_handler(invalid_parameter);
881 _RTC_SetErrorFunc(rtc_error_handler);
885 SetErrorMode(SEM_FAILCRITICALERRORS|(ruby_w32_wer ? 0 : SEM_NOGPFAULTERRORBOX));
892 *argc = w32_cmdvector(GetCommandLineW(), argv, CP_UTF8, &OnigEncodingUTF_8);
900 if ((uenvarea_key = FlsAlloc(free_uenvarea)) == FLS_OUT_OF_INDEXES)
901 rb_bug(
"FlsAlloc() for uenvarea_key fails");
913 return (
char *)NTLoginName;
916#define MAXCHILDNUM 256
925#define FOREACH_CHILD(v) do { \
926 struct ChildRecord* v; \
927 for (v = ChildRecord; v < ChildRecord + sizeof(ChildRecord) / sizeof(ChildRecord[0]); ++v)
928#define END_FOREACH_CHILD } while (0)
932FindChildSlot(rb_pid_t pid)
935 FOREACH_CHILD(child) {
936 if (child->pid == pid) {
945FindChildSlotByHandle(HANDLE h)
948 FOREACH_CHILD(child) {
949 if (child->hProcess == h) {
960 HANDLE h = child->hProcess;
961 child->hProcess = NULL;
968FindFreeChildSlot(
void)
970 FOREACH_CHILD(child) {
973 child->hProcess = NULL;
981#define InternalCmdsMax 8
982static const char szInternalCmds[][InternalCmdsMax+1] = {
1030internal_match(
const void *key,
const void *elem)
1032 return strncmp(key, elem, InternalCmdsMax);
1035static int internal_cmd_match(
const char *cmdname);
1039is_internal_cmd(
const char *cmd)
1041 char cmdname[InternalCmdsMax+1], *b = cmdname, c;
1044 if (!(c = *cmd++))
return 0;
1045 }
while (isspace(c));
1048 while (isalpha(c)) {
1050 if (b == cmdname +
sizeof(cmdname))
return 0;
1053 if (c ==
'.') c = *cmd;
1055 case '<':
case '>':
case '|':
1057 case '\0':
case ' ':
case '\t':
case '\n':
1063 return internal_cmd_match(cmdname);
1068internal_cmd_match(
const char *cmdname)
1072 nm = bsearch(cmdname, szInternalCmds,
1073 numberof(szInternalCmds),
1074 sizeof(*szInternalCmds),
1082rb_w32_get_osfhandle(
int fh)
1084 return _get_osfhandle(fh);
1089join_argv(
char *cmd,
char *
const *argv, BOOL escape, UINT cp,
int backslash, BOOL quote_bs)
1093 int len, n, bs, quote;
1095 for (t = argv, q = cmd,
len = 0; (p = *t) != 0; t++) {
1098 if (!*p || strpbrk(p,
" \t\"'")) {
1103 for (bs = 0; *p; ++p) {
1117 memset(q,
'\\', bs);
1122 case '<':
case '>':
case '|':
case '^':
1123 if (escape && !quote) {
1124 len += (n = p - s) + 1;
1135 p = CharNextExA(cp, p, 0) - 1;
1139 len += (n = p - s) + 1;
1140 if (quote)
len += (quote_bs ? bs : 0) + 1;
1143 if (backslash > 0) {
1146 translate_char(q,
'/',
'\\', cp);
1151 if (quote_bs && bs) {
1152 memset(q,
'\\', bs);
1169#define STRNDUPV(ptr, v, src, len) \
1170 (((char *)memcpy(((ptr) = ALLOCV((v), (len) + 1)), (src), (len)))[len] = 0)
1174check_spawn_mode(
int mode)
1196 if (mode == P_OVERLAY) {
1197 WaitForSingleObject(child->hProcess, INFINITE);
1198 GetExitCodeProcess(child->hProcess, &exitcode);
1199 CloseChildHandle(child);
1207CreateChild(
struct ChildRecord *child,
const WCHAR *cmd,
const WCHAR *prog, HANDLE hInput, HANDLE hOutput, HANDLE hError, DWORD dwCreationFlags)
1210 STARTUPINFOW aStartupInfo;
1211 PROCESS_INFORMATION aProcessInformation;
1212 SECURITY_ATTRIBUTES sa;
1214 if (!cmd && !prog) {
1224 sa.nLength =
sizeof(SECURITY_ATTRIBUTES);
1225 sa.lpSecurityDescriptor = NULL;
1226 sa.bInheritHandle = TRUE;
1228 memset(&aStartupInfo, 0,
sizeof(aStartupInfo));
1229 memset(&aProcessInformation, 0,
sizeof(aProcessInformation));
1230 aStartupInfo.cb =
sizeof(aStartupInfo);
1231 aStartupInfo.dwFlags = STARTF_USESTDHANDLES;
1233 aStartupInfo.hStdInput = hInput;
1236 aStartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
1239 aStartupInfo.hStdOutput = hOutput;
1242 aStartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
1245 aStartupInfo.hStdError = hError;
1248 aStartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
1251 dwCreationFlags |= NORMAL_PRIORITY_CLASS;
1253 if (lstrlenW(cmd) > 32767) {
1260 fRet = CreateProcessW(prog, (WCHAR *)cmd, &sa, &sa,
1261 sa.bInheritHandle, dwCreationFlags, NULL, NULL,
1262 &aStartupInfo, &aProcessInformation);
1263 errno = map_errno(GetLastError());
1271 CloseHandle(aProcessInformation.hThread);
1273 child->hProcess = aProcessInformation.hProcess;
1274 child->pid = (rb_pid_t)aProcessInformation.dwProcessId;
1281is_batch(
const char *cmd)
1283 int len = strlen(cmd);
1284 if (
len <= 4)
return 0;
1286 if (*cmd++ !=
'.')
return 0;
1287 if (strcasecmp(cmd,
"bat") == 0)
return 1;
1288 if (strcasecmp(cmd,
"cmd") == 0)
return 1;
1292#define filecp rb_w32_filecp
1293#define mbstr_to_wstr rb_w32_mbstr_to_wstr
1294#define wstr_to_mbstr rb_w32_wstr_to_mbstr
1295#define acp_to_wstr(str, plen) mbstr_to_wstr(CP_ACP, str, -1, plen)
1296#define wstr_to_acp(str, plen) wstr_to_mbstr(CP_ACP, str, -1, plen)
1297#define filecp_to_wstr(str, plen) mbstr_to_wstr(filecp(), str, -1, plen)
1298#define wstr_to_filecp(str, plen) wstr_to_mbstr(filecp(), str, -1, plen)
1299#define utf8_to_wstr(str, plen) mbstr_to_wstr(CP_UTF8, str, -1, plen)
1300#define wstr_to_utf8(str, plen) wstr_to_mbstr(CP_UTF8, str, -1, plen)
1304w32_spawn(
int mode,
const char *cmd,
const char *prog, UINT cp)
1306 char fbuf[PATH_MAX];
1308 const char *shell = NULL;
1309 WCHAR *wcmd = NULL, *wshell = NULL;
1315 char *cmd_sep = NULL;
1317 if (check_spawn_mode(mode))
return -1;
1320 if (!(p = dln_find_exe_r(prog, NULL, fbuf,
sizeof(fbuf)))) {
1325 translate_char(p,
'/',
'\\', cp);
1331 if ((shell = w32_getenv(
"RUBYSHELL", cp)) && (redir = has_redirection(cmd, cp))) {
1332 size_t shell_len = strlen(shell);
1333 size_t cmd_len = strlen(cmd) +
sizeof(
" -c ") + 2;
1334 char *tmp =
ALLOCV(v, shell_len + cmd_len);
1335 memcpy(tmp, shell, shell_len + 1);
1336 translate_char(tmp,
'/',
'\\', cp);
1337 snprintf(tmp + shell_len, cmd_len,
" -c \"%s\"", cmd);
1340 else if ((shell = w32_getenv(
"COMSPEC", cp)) &&
1341 ((redir < 0 ? has_redirection(cmd, cp) : redir) || is_internal_cmd(cmd))) {
1342 size_t cmd_len = strlen(shell) + strlen(cmd) +
sizeof(
" /c \"\"");
1343 char *tmp =
ALLOCV(v, cmd_len);
1344 snprintf(tmp, cmd_len,
"%s /c \"%s\"", shell, cmd);
1348 int len = 0, quote = (*cmd ==
'"') ?
'"' : (*cmd ==
'\'') ?
'\'' : 0;
1350 for (prog = cmd + !!quote;; prog = CharNextExA(cp, prog, 0)) {
1351 if (*prog ==
'/') slash = 1;
1355 STRNDUPV(p, v2, cmd,
len);
1361 if ((
unsigned char)*prog == quote) {
1362 len = prog++ - cmd - 1;
1363 STRNDUPV(p, v2, cmd + 1,
len);
1367 if (quote)
continue;
1368 if (
ISSPACE(*prog) || strchr(
"<>|*?\"", *prog)) {
1370 STRNDUPV(p, v2, cmd,
len + (slash ? strlen(prog) : 0));
1373 sep = *(cmd_sep = &p[
len]);
1380 shell = dln_find_exe_r(shell, NULL, fbuf,
sizeof(fbuf));
1381 if (p && slash) translate_char(p,
'/',
'\\', cp);
1383 shell = p ? p : cmd;
1386 len = strlen(shell);
1387 if (strchr(shell,
' ')) quote = -1;
1388 if (shell == fbuf) {
1391 else if (shell != p && strchr(shell,
'/')) {
1392 STRNDUPV(p, v2, shell,
len);
1395 if (p) translate_char(p,
'/',
'\\', cp);
1396 if (is_batch(shell)) {
1397 int alen = strlen(prog);
1398 cmd = p =
ALLOCV(v,
len + alen + (quote ? 2 : 0) + 1);
1399 if (quote) *p++ =
'"';
1400 memcpy(p, shell,
len);
1402 if (quote) *p++ =
'"';
1403 memcpy(p, prog, alen + 1);
1410 if (!e && shell && !(wshell = mbstr_to_wstr(cp, shell, -1, NULL))) e = E2BIG;
1411 if (cmd_sep) *cmd_sep = sep;
1412 if (!e && cmd && !(wcmd = mbstr_to_wstr(cp, cmd, -1, NULL))) e = E2BIG;
1418 if (CreateChild(child, wcmd, wshell, NULL, NULL, NULL, 0)) {
1419 ret = child_result(child, mode);
1430rb_w32_spawn(
int mode,
const char *cmd,
const char *prog)
1433 return w32_spawn(mode, cmd, prog, filecp());
1438rb_w32_uspawn(
int mode,
const char *cmd,
const char *prog)
1440 return w32_spawn(mode, cmd, prog, CP_UTF8);
1445w32_spawn_process(
int mode,
const char *prog,
char *
const *argv,
1446 int in_fd,
int out_fd,
int err_fd, DWORD flags, UINT cp)
1451 char *cmd, fbuf[PATH_MAX];
1452 WCHAR *wcmd = NULL, *wprog = NULL;
1456 HANDLE in_handle = NULL, out_handle = NULL, err_handle = NULL;
1458 if (check_spawn_mode(mode))
return -1;
1461 in_handle = (HANDLE)rb_w32_get_osfhandle(in_fd);
1464 out_handle = (HANDLE)rb_w32_get_osfhandle(out_fd);
1467 err_handle = (HANDLE)rb_w32_get_osfhandle(err_fd);
1470 if (!prog) prog = argv[0];
1471 if ((shell = w32_getenv(
"COMSPEC", cp)) && internal_cmd_match(prog)) {
1475 else if ((cmd = dln_find_exe_r(prog, NULL, fbuf,
sizeof(fbuf)))) {
1476 if (cmd == prog) strlcpy(cmd = fbuf, prog,
sizeof(fbuf));
1477 translate_char(cmd,
'/',
'\\', cp);
1480 else if (strchr(prog,
'/')) {
1482 if (
len <
sizeof(fbuf))
1483 strlcpy(cmd = fbuf, prog,
sizeof(fbuf));
1485 STRNDUPV(cmd, v, prog,
len);
1486 translate_char(cmd,
'/',
'\\', cp);
1489 if (c_switch || is_batch(prog)) {
1491 progs[0] = (
char *)prog;
1493 len = join_argv(NULL, progs, TRUE, cp, 1, FALSE);
1494 if (c_switch)
len += 3;
1496 if (argv[0])
len += join_argv(NULL, argv, TRUE, cp, 0, FALSE);
1498 join_argv(cmd, progs, TRUE, cp, 1, FALSE);
1499 if (c_switch) strlcat(cmd,
" /c",
len);
1500 if (argv[0]) join_argv(cmd + strlcat(cmd,
" ",
len), argv, TRUE, cp, 0, FALSE);
1501 prog = c_switch ? shell : 0;
1504 len = join_argv(NULL, argv, FALSE, cp, 1, TRUE);
1506 join_argv(cmd, argv, FALSE, cp, 1, TRUE);
1509 if (!e && cmd && !(wcmd = mbstr_to_wstr(cp, cmd, -1, NULL))) e = E2BIG;
1511 if (!e && prog && !(wprog = mbstr_to_wstr(cp, prog, -1, NULL))) e = E2BIG;
1515 if (CreateChild(child, wcmd, wprog, in_handle, out_handle, err_handle, flags)) {
1516 ret = child_result(child, mode);
1527rb_w32_aspawn_flags(
int mode,
const char *prog,
char *
const *argv, DWORD flags)
1530 return w32_spawn_process(mode, prog, argv, -1, -1, -1, flags, filecp());
1535rb_w32_uaspawn_flags(
int mode,
const char *prog,
char *
const *argv, DWORD flags)
1537 return w32_spawn_process(mode, prog, argv, -1, -1, -1, flags, CP_UTF8);
1542rb_w32_aspawn(
int mode,
const char *prog,
char *
const *argv)
1544 return w32_spawn_process(mode, prog, argv, -1, -1, -1, 0, filecp());
1549rb_w32_uaspawn(
int mode,
const char *prog,
char *
const *argv)
1551 return rb_w32_uaspawn_flags(mode, prog, argv, 0);
1556rb_w32_uspawn_process(
int mode,
const char *prog,
char *
const *argv,
1557 int in_fd,
int out_fd,
int err_fd, DWORD flags)
1559 return w32_spawn_process(mode, prog, argv, in_fd, out_fd, err_fd,
1581insert(
const char *path,
VALUE vinfo,
void *enc)
1583 NtCmdLineElement *tmpcurr;
1584 NtCmdLineElement ***tail = (NtCmdLineElement ***)vinfo;
1586 tmpcurr = (NtCmdLineElement *)malloc(
sizeof(NtCmdLineElement));
1587 if (!tmpcurr)
return -1;
1588 MEMZERO(tmpcurr, NtCmdLineElement, 1);
1589 tmpcurr->len = strlen(path);
1590 tmpcurr->str =
strdup(path);
1591 if (!tmpcurr->str)
return -1;
1592 tmpcurr->flags |= NTMALLOC;
1594 *tail = &tmpcurr->next;
1600static NtCmdLineElement **
1601cmdglob(NtCmdLineElement *patt, NtCmdLineElement **tail, UINT cp, rb_encoding *enc)
1603 char buffer[PATH_MAX], *buf = buffer;
1604 NtCmdLineElement **last = tail;
1607 if (patt->len >= PATH_MAX)
1608 if (!(buf = malloc(patt->len + 1)))
return 0;
1610 memcpy(buf, patt->str, patt->len);
1611 buf[patt->len] =
'\0';
1612 translate_char(buf,
'\\',
'/', cp);
1613 status = ruby_brace_glob_with_enc(buf, 0, insert, (
VALUE)&tail, enc);
1617 if (status || last == tail)
return 0;
1618 if (patt->flags & NTMALLOC)
1631has_redirection(
const char *cmd, UINT cp)
1641 for (ptr = cmd; *ptr;) {
1647 else if (quote == *ptr)
1663 if (*++ptr !=
'_' && !
ISALPHA(*ptr))
break;
1664 while (*++ptr ==
'_' ||
ISALNUM(*ptr));
1665 if (*ptr && *ptr++ ==
'%')
return TRUE;
1671 ptr = CharNextExA(cp, ptr, 0);
1679static inline WCHAR *
1680skipspace(WCHAR *ptr)
1689w32_cmdvector(
const WCHAR *cmd,
char ***vec, UINT cp, rb_encoding *enc)
1692 int elements, strsz, done;
1693 int slashes, escape;
1694 WCHAR *ptr, *base, *cmdline;
1695 char *cptr, *buffer;
1698 NtCmdLineElement *curr, **tail;
1699 NtCmdLineElement *cmdhead = NULL, **cmdtail = &cmdhead;
1711 ptr = cmdline = wcsdup(cmd);
1722 while (*(ptr = skipspace(ptr))) {
1724 quote = slashes = globbing = escape = 0;
1725 for (done = 0; !done && *ptr; ) {
1734 if (quote != L
'\'') slashes++;
1775 if (!(slashes & 1)) {
1778 else if (quote == *ptr) {
1779 if (quote == L
'"' && quote == ptr[1])
1789 ptr = CharNextW(ptr);
1812 slashes = quote = 0;
1813 while (p < base +
len) {
1817 if (quote != L
'\'') slashes++;
1822 if (!(slashes & 1) && quote && quote != c) {
1827 memcpy(p - ((slashes + 1) >> 1), p + (~slashes & 1),
1828 sizeof(WCHAR) * (base +
len - p));
1829 len -= ((slashes + 1) >> 1) + (~slashes & 1);
1830 p -= (slashes + 1) >> 1;
1831 if (!(slashes & 1)) {
1833 if (quote == L
'"' && quote == *p)
1853 curr = (NtCmdLineElement *)calloc(1,
sizeof(NtCmdLineElement));
1854 if (!curr)
goto do_nothing;
1855 curr->str = rb_w32_wstr_to_mbstr(cp, base,
len, &curr->len);
1856 curr->flags |= NTMALLOC;
1858 if (globbing && (tail = cmdglob(curr, cmdtail, cp, enc))) {
1863 cmdtail = &curr->next;
1873 for (elements = 0, strsz = 0, curr = cmdhead; curr; curr = curr->next) {
1875 strsz += (curr->len + 1);
1878 len = (elements+1)*
sizeof(
char *) + strsz;
1879 buffer = (
char *)malloc(
len);
1882 while ((curr = cmdhead) != 0) {
1883 cmdhead = curr->next;
1884 if (curr->flags & NTMALLOC) free(curr->str);
1888 for (vptr = *vec; *vptr; ++vptr);
1904 vptr = (
char **) buffer;
1906 cptr = buffer + (elements+1) *
sizeof(
char *);
1908 while ((curr = cmdhead) != 0) {
1909 memcpy(cptr, curr->str, curr->len);
1910 cptr[curr->len] =
'\0';
1912 cptr += curr->len + 1;
1913 cmdhead = curr->next;
1914 if (curr->flags & NTMALLOC) free(curr->str);
1919 *vec = (
char **) buffer;
1931open_special(
const WCHAR *path, DWORD access, DWORD flags)
1933 const DWORD share_mode =
1934 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1935 return CreateFileW(path, access, share_mode, NULL, OPEN_EXISTING,
1936 FILE_FLAG_BACKUP_SEMANTICS|flags, NULL);
1946#define GetBit(bits, i) ((bits)[(i) / CHAR_BIT] & (1 << (i) % CHAR_BIT))
1947#define SetBit(bits, i) ((bits)[(i) / CHAR_BIT] |= (1 << (i) % CHAR_BIT))
1949#define BitOfIsDir(n) ((n) * 2)
1950#define BitOfIsRep(n) ((n) * 2 + 1)
1951#define DIRENT_PER_CHAR (CHAR_BIT / 2)
1953static const WCHAR namespace_prefix[] = {L
'\\', L
'\\', L
'?', L
'\\'};
1959get_handle_pathname(HANDLE fh, WCHAR **pathptr, DWORD add)
1961 DWORD
len = GetFinalPathNameByHandleW(fh, NULL, 0, 0);
1963 WCHAR *path = malloc((
len + add + 1) *
sizeof(WCHAR));
1964 if (!(*pathptr = path))
return 0;
1965 len = GetFinalPathNameByHandleW(fh, path,
len + 1, 0);
1975open_dir_handle(
const WCHAR *filename, WIN32_FIND_DATAW *fd)
1979 WCHAR *fullname = 0;
1987 fh = open_special(filename, 0, 0);
1988 if (fh != INVALID_HANDLE_VALUE) {
1989 len = get_handle_pathname(fh, &fullname, wildcard_len);
1993 len = lstrlenW(filename);
1994 fullname = malloc((
len + wildcard_len + 1) *
sizeof(WCHAR));
1995 if (!fullname)
return INVALID_HANDLE_VALUE;
2001 p = &fullname[
len-1];
2002 if (!(isdirsep(*p) || *p == L
':')) *++p = L
'\\';
2009 fh = FindFirstFileW(fullname, fd);
2010 if (fh == INVALID_HANDLE_VALUE) {
2011 errno = map_errno(GetLastError());
2019w32_wopendir(
const WCHAR *wpath)
2021 struct stati128 sbuf;
2022 WIN32_FIND_DATAW fd;
2035 if (wstati128(wpath, &sbuf, FALSE) < 0) {
2038 if (!(sbuf.st_mode & S_IFDIR) &&
2039 (!
ISALPHA(wpath[0]) || wpath[1] != L
':' || wpath[2] != L
'\0' ||
2040 ((1 << ((wpath[0] & 0x5f) -
'A')) & GetLogicalDrives()) == 0)) {
2044 fh = open_dir_handle(wpath, &fd);
2045 if (fh == INVALID_HANDLE_VALUE) {
2052 p = calloc(1,
sizeof(
DIR));
2056 pathlen = lstrlenW(wpath);
2066 len = lstrlenW(fd.cFileName) + 1;
2067 altlen = lstrlenW(fd.cAlternateFileName) + 1;
2073 tmpW = realloc(p->start, (idx +
len + altlen) *
sizeof(WCHAR));
2083 memcpy(&p->start[idx], fd.cFileName,
len *
sizeof(WCHAR));
2084 memcpy(&p->start[idx +
len], fd.cAlternateFileName, altlen *
sizeof(WCHAR));
2086 if (p->nfiles % DIRENT_PER_CHAR == 0) {
2087 tmp = realloc(p->bits, p->nfiles / DIRENT_PER_CHAR + 1);
2091 p->bits[p->nfiles / DIRENT_PER_CHAR] = 0;
2093 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
2094 SetBit(p->bits, BitOfIsDir(p->nfiles));
2095 if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2096 WCHAR *tmppath = malloc((pathlen +
len + 1) *
sizeof(WCHAR));
2097 memcpy(tmppath, wpath, pathlen *
sizeof(WCHAR));
2098 tmppath[pathlen] = L
'\\';
2099 memcpy(tmppath + pathlen + 1, fd.cFileName,
len *
sizeof(WCHAR));
2100 if (rb_w32_reparse_symlink_p(tmppath))
2101 SetBit(p->bits, BitOfIsRep(p->nfiles));
2106 idx +=
len + altlen;
2107 }
while (FindNextFileW(fh, &fd));
2118 UINT cp = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
2124rb_w32_wstr_to_mbstr(UINT cp,
const WCHAR *wstr,
int clen,
long *plen)
2127 int len = WideCharToMultiByte(cp, 0, wstr, clen, NULL, 0, NULL, NULL);
2128 if (!(ptr = malloc(
len)))
return 0;
2129 WideCharToMultiByte(cp, 0, wstr, clen, ptr,
len, NULL, NULL);
2132 if (clen == -1) --
len;
2140rb_w32_mbstr_to_wstr(UINT cp,
const char *str,
int clen,
long *plen)
2143 int len = MultiByteToWideChar(cp, 0, str, clen, NULL, 0);
2144 if (!(ptr = malloc(
sizeof(WCHAR) *
len)))
return 0;
2145 MultiByteToWideChar(cp, 0, str, clen, ptr,
len);
2148 if (clen == -1) --
len;
2156rb_w32_opendir(
const char *filename)
2159 WCHAR *wpath = filecp_to_wstr(filename, NULL);
2162 ret = w32_wopendir(wpath);
2169rb_w32_uopendir(
const char *filename)
2172 WCHAR *wpath = utf8_to_wstr(filename, NULL);
2175 ret = w32_wopendir(wpath);
2186move_to_next_entry(
DIR *dirp)
2190 dirp->curr += lstrlenW(dirp->curr) + 1;
2191 dirp->curr += lstrlenW(dirp->curr) + 1;
2192 if (dirp->curr >= (dirp->start + dirp->size)) {
2204win32_direct_conv(
const WCHAR *file,
const WCHAR *alt,
struct direct *entry,
const void *enc)
2206 UINT cp = *((UINT *)enc);
2207 if (!(entry->d_name = wstr_to_mbstr(cp, file, -1, &entry->d_namlen)))
2211 entry->d_altname = wstr_to_mbstr(cp, alt, -1, &altlen);
2212 entry->d_altlen = altlen;
2219rb_w32_conv_from_wchar(
const WCHAR *wstr, rb_encoding *enc)
2222 long len = lstrlenW(wstr);
2223 int encindex = rb_enc_to_index(enc);
2225 if (encindex == ENCINDEX_UTF_16LE) {
2226 return rb_enc_str_new((
char *)wstr,
len *
sizeof(WCHAR), enc);
2229#if SIZEOF_INT < SIZEOF_LONG
2230# error long should equal to int on Windows
2233 len = WideCharToMultiByte(CP_UTF8, 0, wstr, clen, NULL, 0, NULL, NULL);
2234 src = rb_enc_str_new(0,
len, rb_enc_from_index(ENCINDEX_UTF_8));
2235 WideCharToMultiByte(CP_UTF8, 0, wstr, clen, RSTRING_PTR(src),
len, NULL, NULL);
2238 case ENCINDEX_ASCII_8BIT:
2239 case ENCINDEX_US_ASCII:
2241 case ENCINDEX_UTF_8:
2250rb_w32_conv_from_wstr(
const WCHAR *wstr,
long *lenp, rb_encoding *enc)
2252 VALUE str = rb_w32_conv_from_wchar(wstr, enc);
2256 if (
NIL_P(str))
return wstr_to_utf8(wstr, lenp);
2257 *lenp =
len = RSTRING_LEN(str);
2258 memcpy(ptr = malloc(
len + 1), RSTRING_PTR(str),
len);
2265ruby_direct_conv(
const WCHAR *file,
const WCHAR *alt,
struct direct *entry,
const void *enc)
2267 if (!(entry->d_name = rb_w32_conv_from_wstr(file, &entry->d_namlen, enc)))
2271 entry->d_altname = rb_w32_conv_from_wstr(alt, &altlen, enc);
2272 entry->d_altlen = altlen;
2279readdir_internal(
DIR *dirp, BOOL (*conv)(
const WCHAR *,
const WCHAR *,
struct direct *,
const void *),
const void *enc)
2281 static long dummy_ino = 0;
2288 free(dirp->dirstr.d_name);
2289 free(dirp->dirstr.d_altname);
2290 dirp->dirstr.d_altname = 0;
2291 dirp->dirstr.d_altlen = 0;
2292 conv(dirp->curr, dirp->curr + lstrlenW(dirp->curr) + 1, &dirp->dirstr, enc);
2297 dirp->dirstr.d_ino = (ino_t)(InterlockedIncrement(&dummy_ino) - 1);
2303 if (GetBit(dirp->bits, BitOfIsRep(dirp->loc)))
2304 dirp->dirstr.d_type = DT_LNK;
2305 else if (GetBit(dirp->bits, BitOfIsDir(dirp->loc)))
2306 dirp->dirstr.d_type = DT_DIR;
2308 dirp->dirstr.d_type = DT_REG;
2314 move_to_next_entry(dirp);
2316 return &(dirp->dirstr);
2325rb_w32_readdir(
DIR *dirp, rb_encoding *enc)
2327 int idx = rb_enc_to_index(enc);
2328 if (idx == ENCINDEX_ASCII_8BIT) {
2329 const UINT cp = filecp();
2330 return readdir_internal(dirp, win32_direct_conv, &cp);
2332 else if (idx == ENCINDEX_UTF_8) {
2333 const UINT cp = CP_UTF8;
2334 return readdir_internal(dirp, win32_direct_conv, &cp);
2337 return readdir_internal(dirp, ruby_direct_conv, enc);
2342rb_w32_ureaddir(
DIR *dirp)
2344 const UINT cp = CP_UTF8;
2345 return readdir_internal(dirp, win32_direct_conv, &cp);
2354rb_w32_telldir(
DIR *dirp)
2365rb_w32_seekdir(
DIR *dirp,
long loc)
2367 if (dirp->loc > loc) rb_w32_rewinddir(dirp);
2369 while (dirp->curr && dirp->loc < loc) {
2370 move_to_next_entry(dirp);
2380rb_w32_rewinddir(
DIR *dirp)
2382 dirp->curr = dirp->start;
2392rb_w32_closedir(
DIR *dirp)
2395 free(dirp->dirstr.d_name);
2396 free(dirp->dirstr.d_altname);
2418 CRITICAL_SECTION _lock;
2420#define FILE_COUNT(stream) ((vcruntime_file*)stream)->_cnt
2421#define FILE_READPTR(stream) ((vcruntime_file*)stream)->_ptr
2422#define FILE_FILENO(stream) ((vcruntime_file*)stream)->_file
2425typedef char lowio_text_mode;
2426typedef char lowio_pipe_lookahead[3];
2429 CRITICAL_SECTION lock;
2432 unsigned char osfile;
2433 lowio_text_mode textmode;
2434 lowio_pipe_lookahead _pipe_lookahead;
2436 uint8_t unicode : 1;
2437 uint8_t utf8translations : 1;
2438 uint8_t dbcsBufferUsed : 1;
2442#if !defined _CRTIMP || defined __MINGW32__
2444#define _CRTIMP __declspec(dllimport)
2447static ioinfo ** __pioinfo = NULL;
2449static inline ioinfo* _pioinfo(
int);
2452#define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
2453#define _osfhnd(i) (_pioinfo(i)->osfhnd)
2454#define _osfile(i) (_pioinfo(i)->osfile)
2455#define rb_acrt_lowio_lock_fh(i) EnterCriticalSection(&_pioinfo(i)->lock)
2456#define rb_acrt_lowio_unlock_fh(i) LeaveCriticalSection(&_pioinfo(i)->lock)
2458static size_t pioinfo_extra = 0;
2462set_pioinfo_extra(
void)
2464#define FUNCTION_RET 0xc3
2466# define UCRTBASE "ucrtbased.dll"
2468# define UCRTBASE "ucrtbase.dll"
2483 char *p = (
char*)get_proc_address(UCRTBASE,
"_isatty", NULL);
2486#if defined(_M_ARM64) || defined(__aarch64__)
2487#define IS_INSN(pc, name) ((*(pc) & name##_mask) == name##_id)
2488 const int max_num_inst = 500;
2489 uint32_t *start = (uint32_t*)p;
2490 uint32_t *end_limit = (start + max_num_inst);
2491 uint32_t *pc = start;
2494 fprintf(stderr,
"_isatty proc not found in " UCRTBASE
"\n");
2499 const uint32_t ret_id = 0xd65f0000;
2500 const uint32_t ret_mask = 0xfffffc1f;
2501 for(; pc < end_limit; pc++) {
2502 if (IS_INSN(pc, ret)) {
2506 if (pc == end_limit) {
2507 fprintf(stderr,
"end of _isatty not found in " UCRTBASE
"\n");
2512 const uint32_t adrp_id = 0x90000000;
2513 const uint32_t adrp_mask = 0x9f000000;
2514 const uint32_t add_id = 0x11000000;
2515 const uint32_t add_mask = 0x7fc00000;
2516 for(; pc > start; pc--) {
2517 if (IS_INSN(pc, adrp) && IS_INSN(pc + 1, add)) {
2522 fprintf(stderr,
"pioinfo mark not found in " UCRTBASE
"\n");
2532 const uint32_t adrp_insn = *pc;
2533 const uint32_t adrp_immhi = (adrp_insn & 0x00ffffe0) >> 5;
2534 const uint32_t adrp_immlo = (adrp_insn & 0x60000000) >> (5 + 19 + 5);
2535 const int64_t adrp_sign = (adrp_insn & 0x00800000) ? ~0x001fffff : 0;
2537 const int64_t adrp_imm = (adrp_sign | (adrp_immhi << 2) | adrp_immlo) << 12;
2539 const uint64_t adrp_base = (uint64_t)pc & 0xfffffffffffff000;
2541 const uint32_t add_insn = *(pc + 1);
2542 const uint64_t add_imm = (add_insn & 0x3ffc00) >> (5 + 5);
2544 __pioinfo = (
ioinfo**)(adrp_base + adrp_imm + add_imm);
2552# define FUNCTION_BEFORE_RET_MARK "\x48\x83\xc4"
2553# define FUNCTION_SKIP_BYTES 1
2556# define PIOINFO_MARK "\x48\x8d\x0d"
2559# define PIOINFO_MARK "\x48\x8d\x15"
2564# define FUNCTION_BEFORE_RET_MARK "\x5d"
2566# define FUNCTION_BEFORE_RET_MARK_2 "\xc9"
2567# define FUNCTION_SKIP_BYTES 0
2569# define PIOINFO_MARK "\x8B\x04\x85"
2572 for (pend += 10; pend < p + 500; pend++) {
2574 if ((memcmp(pend, FUNCTION_BEFORE_RET_MARK,
sizeof(FUNCTION_BEFORE_RET_MARK) - 1) == 0
2575# ifdef FUNCTION_BEFORE_RET_MARK_2
2576 || memcmp(pend, FUNCTION_BEFORE_RET_MARK_2,
sizeof(FUNCTION_BEFORE_RET_MARK_2) - 1) == 0
2579 *(pend + (
sizeof(FUNCTION_BEFORE_RET_MARK) - 1) + FUNCTION_SKIP_BYTES) == (
char)FUNCTION_RET) {
2581 for (pend -= (
sizeof(PIOINFO_MARK) - 1); pend > p; pend--) {
2582 if (memcmp(pend, PIOINFO_MARK,
sizeof(PIOINFO_MARK) - 1) == 0) {
2591 fprintf(stderr,
"unexpected " UCRTBASE
"\n");
2595 p +=
sizeof(PIOINFO_MARK) - 1;
2597 rel = *(int32_t*)(p);
2598 rip = p +
sizeof(int32_t);
2599 __pioinfo = (
ioinfo**)(rip + rel);
2601 __pioinfo = *(
ioinfo***)(p);
2606 fd = _open(
"NUL", O_RDONLY);
2607 for (pioinfo_extra = 0; pioinfo_extra <= 64; pioinfo_extra +=
sizeof(
void *)) {
2608 if (_osfhnd(fd) == _get_osfhandle(fd)) {
2614 if (pioinfo_extra > 64) {
2623 const size_t sizeof_ioinfo =
sizeof(
ioinfo) + pioinfo_extra;
2624 return (
ioinfo*)((
char*)__pioinfo[fd >> IOINFO_L2E] +
2625 (fd & (IOINFO_ARRAY_ELTS - 1)) * sizeof_ioinfo);
2628#define _set_osfhnd(fh, osfh) (void)(_osfhnd(fh) = osfh)
2629#define _set_osflags(fh, flags) (_osfile(fh) = (flags))
2634#define FNOINHERIT 0x10
2639static int is_socket(SOCKET);
2640static int is_console(SOCKET);
2644rb_w32_io_cancelable_p(
int fd)
2646 return is_socket(TO_SOCKET(fd)) || !is_console(TO_SOCKET(fd));
2651rb_w32_open_osfhandle(intptr_t osfhandle,
int flags)
2660 if (flags & O_APPEND)
2661 fileflags |= FAPPEND;
2666 if (flags & O_NOINHERIT)
2667 fileflags |= FNOINHERIT;
2670 hF = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
2671 fh = _open_osfhandle((intptr_t)hF, 0);
2679 rb_acrt_lowio_lock_fh(fh);
2681 _set_osfhnd(fh, osfhandle);
2685 _set_osflags(fh, fileflags);
2686 rb_acrt_lowio_unlock_fh(fh);
2697#define open_null(fd) \
2699 (nullfd = open("NUL", O_RDWR)) : 0), \
2700 ((nullfd == (fd)) ? (keep = 1) : dup2(nullfd, fd)), \
2703 if (fileno(stdin) < 0) {
2704 FILE_FILENO(stdin) = open_null(0);
2707 setmode(fileno(stdin), O_BINARY);
2709 if (fileno(stdout) < 0) {
2710 FILE_FILENO(stdout) = open_null(1);
2712 if (fileno(stderr) < 0) {
2713 FILE_FILENO(stderr) = open_null(2);
2715 if (nullfd >= 0 && !keep) close(nullfd);
2716 setvbuf(stderr, NULL, _IONBF, 0);
2719 HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
2721 if (GetConsoleMode(h, &m)) {
2722#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
2723#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x4
2725 SetConsoleMode(h, m | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
2734is_socket(SOCKET sock)
2736 if (socklist_lookup(sock, NULL))
2744rb_w32_is_socket(
int fd)
2746 return is_socket(TO_SOCKET(fd));
2759rb_w32_strerror(
int e)
2761 static char buffer[512];
2766 strlcpy(buffer,
"Unknown Error",
sizeof(buffer));
2767 else if (e > sys_nerr) {
2768#if WSAEWOULDBLOCK != EWOULDBLOCK
2769 if (e >= EADDRINUSE && e <= EWOULDBLOCK) {
2773 for (s = 0; s < (int)(
sizeof(errmap)/
sizeof(*errmap)); s++)
2774 if (errmap[s].winerr == WSAEWOULDBLOCK)
2776 for (i = s; i < (int)(
sizeof(errmap)/
sizeof(*errmap)); i++)
2777 if (errmap[i].err == e) {
2778 e = errmap[i].winerr;
2783 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2784 FORMAT_MESSAGE_IGNORE_INSERTS, &source, e,
2785 MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
2786 buffer,
sizeof(buffer), NULL) == 0 &&
2787 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2788 FORMAT_MESSAGE_IGNORE_INSERTS, &source, e, 0,
2789 buffer,
sizeof(buffer), NULL) == 0)
2790 strlcpy(buffer,
"Unknown Error",
sizeof(buffer));
2793 strlcpy(buffer, strerror(e),
sizeof(buffer));
2796 while ((p = strpbrk(p,
"\r\n")) != NULL) {
2797 memmove(p, p + 1, strlen(p));
2848 return (uid == ROOT_UID ? 0 : -1);
2855 return (gid == ROOT_GID ? 0 : -1);
2864ioctl(
int i,
int u, ...)
2871rb_w32_fdset(
int fd, fd_set *set)
2880rb_w32_fdclr(
int fd, fd_set *set)
2883 SOCKET s = TO_SOCKET(fd);
2885 for (i = 0; i < set->fd_count; i++) {
2886 if (set->fd_array[i] == s) {
2887 memmove(&set->fd_array[i], &set->fd_array[i+1],
2888 sizeof(set->fd_array[0]) * (--set->fd_count - i));
2898rb_w32_fdisset(
int fd, fd_set *set)
2901 SOCKET s = TO_SOCKET(fd);
2902 if (s == (SOCKET)INVALID_HANDLE_VALUE)
2904 RUBY_CRITICAL {ret = __WSAFDIsSet(s, set);}
2912 max = min(src->fd_count, (UINT)max);
2913 if ((UINT)dst->
capa < (UINT)max) {
2914 dst->
capa = (src->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2918 memcpy(dst->
fdset->fd_array, src->fd_array,
2919 max *
sizeof(src->fd_array[0]));
2920 dst->
fdset->fd_count = src->fd_count;
2927 if ((UINT)dst->
capa < src->
fdset->fd_count) {
2928 dst->
capa = (src->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2932 memcpy(dst->
fdset->fd_array, src->
fdset->fd_array,
2933 src->
fdset->fd_count *
sizeof(src->
fdset->fd_array[0]));
2947extract_fd(
rb_fdset_t *dst, fd_set *src,
int (*func)(SOCKET))
2953 while (s < src->fd_count) {
2954 SOCKET fd = src->fd_array[s];
2956 if (!func || (*func)(fd)) {
2960 for (d = 0; d < dst->
fdset->fd_count; d++) {
2961 if (dst->
fdset->fd_array[d] == fd)
2964 if (d == dst->
fdset->fd_count) {
2965 if ((
int)dst->
fdset->fd_count >= dst->
capa) {
2966 dst->
capa = (dst->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2969 dst->
fdset->fd_array[dst->
fdset->fd_count++] = fd;
2973 &src->fd_array[s+1],
2974 sizeof(src->fd_array[0]) * (--src->fd_count - s));
2984 return dst ? dst->
fdset->fd_count : m;
2989copy_fd(fd_set *dst, fd_set *src)
2992 if (!src || !dst)
return 0;
2994 for (s = 0; s < src->fd_count; ++s) {
2995 SOCKET fd = src->fd_array[s];
2997 for (d = 0; d < dst->fd_count; ++d) {
2998 if (dst->fd_array[d] == fd)
3001 if (d == dst->fd_count) {
3002 dst->fd_array[dst->fd_count++] = fd;
3006 return dst->fd_count;
3011save_fd(SOCKET *dst,
const fd_set *src)
3013 if (src) memcpy(dst, src->fd_array, src->fd_count *
sizeof(SOCKET));
3018restore_fd(fd_set *dst,
const SOCKET *src, UINT count)
3021 memcpy(dst->fd_array, src, count *
sizeof(SOCKET));
3022 dst->fd_count = count;
3027is_not_socket(SOCKET sock)
3029 return !is_socket(sock);
3039 ret = (GetFileType((HANDLE)sock) == FILE_TYPE_PIPE);
3047is_readable_pipe(SOCKET sock)
3053 if (PeekNamedPipe((HANDLE)sock, NULL, 0, NULL, &n, NULL)) {
3057 ret = (GetLastError() == ERROR_BROKEN_PIPE);
3066is_console(SOCKET sock)
3073 ret = (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n));
3081is_readable_console(SOCKET sock)
3088 if (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n) && n > 0) {
3089 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
3090 ir.Event.KeyEvent.uChar.UnicodeChar) {
3093 else if (ir.EventType == KEY_EVENT && !ir.Event.KeyEvent.bKeyDown &&
3094 ir.Event.KeyEvent.wVirtualKeyCode == VK_MENU &&
3095 ir.Event.KeyEvent.uChar.UnicodeChar) {
3099 ReadConsoleInputW((HANDLE)sock, &ir, 1, &n);
3109is_invalid_handle(SOCKET sock)
3111 return (HANDLE)sock == INVALID_HANDLE_VALUE;
3116do_select(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3123 rb_w32_sleep(timeout->tv_sec * 1000 + timeout->tv_usec / 1000);
3125 rb_w32_sleep(INFINITE);
3129 thread_exclusive(select) {
3130 r = select(nfds, rd, wr, ex, timeout);
3132 if (r == SOCKET_ERROR) {
3133 errno = map_errno(WSAGetLastError());
3148rb_w32_time_subtract(
struct timeval *rest,
const struct timeval *wait)
3150 if (rest->tv_sec < wait->tv_sec) {
3153 while (rest->tv_usec < wait->tv_usec) {
3154 if (rest->tv_sec <= wait->tv_sec) {
3158 rest->tv_usec += 1000 * 1000;
3160 rest->tv_sec -= wait->tv_sec;
3161 rest->tv_usec -= wait->tv_usec;
3162 return rest->tv_sec != 0 || rest->tv_usec != 0;
3169 if (t1->tv_sec < t2->tv_sec)
3171 if (t1->tv_sec > t2->tv_sec)
3173 if (t1->tv_usec < t2->tv_usec)
3175 if (t1->tv_usec > t2->tv_usec)
3182int rb_w32_check_interrupt(
void *);
3187rb_w32_select_with_thread(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3188 struct timeval *timeout,
void *th)
3197 struct timeval limit = {0, 0};
3199 if (nfds < 0 || (timeout && (timeout->tv_sec < 0 || timeout->tv_usec < 0))) {
3205 if (timeout->tv_sec < 0 ||
3206 timeout->tv_usec < 0 ||
3207 timeout->tv_usec >= 1000000) {
3211 gettimeofday(&limit, NULL);
3212 limit.tv_sec += timeout->tv_sec;
3213 limit.tv_usec += timeout->tv_usec;
3214 if (limit.tv_usec >= 1000000) {
3215 limit.tv_usec -= 1000000;
3227 nonsock += extract_fd(&else_rd, rd, is_not_socket);
3230 nonsock += extract_fd(&else_wr, wr, is_not_socket);
3233 if (extract_fd(NULL, else_rd.
fdset, is_invalid_handle) > 0 ||
3234 extract_fd(NULL, else_wr.
fdset, is_invalid_handle) > 0) {
3242 extract_fd(&pipe_rd, else_rd.
fdset, is_pipe);
3245 extract_fd(&cons_rd, else_rd.
fdset, is_console);
3248 extract_fd(&except, ex, is_not_socket);
3251 if (rd && (
int)rd->fd_count > r) r = (int)rd->fd_count;
3252 if (wr && (
int)wr->fd_count > r) r = (int)wr->fd_count;
3253 if (ex && (
int)ex->fd_count > r) r = (int)ex->fd_count;
3254 if (nfds > r) nfds = r;
3258 const struct timeval wait = {0, 10 * 1000};
3261 UINT nrd = rd ? rd->fd_count : 0;
3262 UINT nwr = wr ? wr->fd_count : 0;
3263 UINT nex = ex ? ex->fd_count : 0;
3264 SOCKET *orig =
ALLOC_N(SOCKET, nrd + nwr + nex);
3267 save_fd(orig + nrd, wr);
3268 save_fd(orig + nrd + nwr, ex);
3270 if (th && rb_w32_check_interrupt(th) != WAIT_TIMEOUT) {
3277 extract_fd(&else_rd, pipe_rd.
fdset, is_readable_pipe);
3278 extract_fd(&else_rd, cons_rd.
fdset, is_readable_console);
3281 if (else_rd.
fdset->fd_count || else_wr.
fdset->fd_count) {
3282 r = do_select(nfds, rd, wr, ex, &zero);
3285 r += copy_fd(rd, else_rd.
fdset);
3286 r += copy_fd(wr, else_wr.
fdset);
3292 const struct timeval *dowait = &wait;
3294 r = do_select(nfds, rd, wr, ex, &zero);
3299 gettimeofday(&now, NULL);
3301 if (!rb_w32_time_subtract(&rest, &now))
break;
3302 if (compare(&rest, &wait) < 0) dowait = &rest;
3304 restore_fd(rd, orig, nrd);
3305 restore_fd(wr, orig + nrd, nwr);
3306 restore_fd(ex, orig + nrd + nwr, nex);
3307 Sleep(dowait->tv_sec * 1000 + (dowait->tv_usec + 999) / 1000);
3310 ruby_xfree_sized(orig,
sizeof(SOCKET) * (nrd + nwr + nex));
3324rb_w32_select(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3327 return rb_w32_select_with_thread(nfds, rd, wr, ex, timeout, 0);
3332get_wsa_extension_function(SOCKET s, GUID guid)
3337 WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid,
sizeof(guid),
3338 &ptr,
sizeof(ptr), &dmy, NULL, NULL);
3348rb_w32_accept(
int s,
struct sockaddr *addr,
int *addrlen)
3354 r = accept(TO_SOCKET(s), addr, addrlen);
3355 if (r != INVALID_SOCKET) {
3356 SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0);
3357 fd = rb_w32_open_osfhandle((intptr_t)r, O_RDWR|O_BINARY|O_NOINHERIT);
3359 socklist_insert(r, 0);
3364 errno = map_errno(WSAGetLastError());
3375rb_w32_bind(
int s,
const struct sockaddr *addr,
int addrlen)
3380 r = bind(TO_SOCKET(s), addr, addrlen);
3381 if (r == SOCKET_ERROR)
3382 errno = map_errno(WSAGetLastError());
3391rb_w32_connect(
int s,
const struct sockaddr *addr,
int addrlen)
3395 r = connect(TO_SOCKET(s), addr, addrlen);
3396 if (r == SOCKET_ERROR) {
3397 int err = WSAGetLastError();
3398 if (err != WSAEWOULDBLOCK)
3399 errno = map_errno(err);
3401 errno = EINPROGRESS;
3412rb_w32_getpeername(
int s,
struct sockaddr *addr,
int *addrlen)
3416 r = getpeername(TO_SOCKET(s), addr, addrlen);
3417 if (r == SOCKET_ERROR)
3418 errno = map_errno(WSAGetLastError());
3427rb_w32_getsockname(
int fd,
struct sockaddr *addr,
int *addrlen)
3432 sock = TO_SOCKET(fd);
3433 r = getsockname(sock, addr, addrlen);
3434 if (r == SOCKET_ERROR) {
3435 DWORD wsaerror = WSAGetLastError();
3436 if (wsaerror == WSAEINVAL) {
3438 if (socklist_lookup(sock, &flags)) {
3439 int af = GET_FAMILY(flags);
3441 memset(addr, 0, *addrlen);
3442 addr->sa_family = af;
3447 errno = map_errno(wsaerror);
3457rb_w32_getsockopt(
int s,
int level,
int optname,
char *optval,
int *optlen)
3461 r = getsockopt(TO_SOCKET(s), level, optname, optval, optlen);
3462 if (r == SOCKET_ERROR)
3463 errno = map_errno(WSAGetLastError());
3467 if (r == 0 && level == SOL_SOCKET && optname == SO_ERROR &&
3468 *optlen == (
int)
sizeof(
int)) {
3470 memcpy(&sockerr, optval,
sizeof(sockerr));
3471 sockerr = map_errno(sockerr);
3472 memcpy(optval, &sockerr,
sizeof(sockerr));
3481rb_w32_ioctlsocket(
int s,
long cmd, u_long *argp)
3485 r = ioctlsocket(TO_SOCKET(s), cmd, argp);
3486 if (r == SOCKET_ERROR)
3487 errno = map_errno(WSAGetLastError());
3496rb_w32_listen(
int s,
int backlog)
3500 r = listen(TO_SOCKET(s), backlog);
3501 if (r == SOCKET_ERROR)
3502 errno = map_errno(WSAGetLastError());
3514finish_overlapped_socket(BOOL input, SOCKET s, WSAOVERLAPPED *wol,
int result, DWORD *
len, DWORD size)
3519 if (result != SOCKET_ERROR)
3521 else if ((err = WSAGetLastError()) == WSA_IO_PENDING) {
3522 switch (rb_w32_wait_events_blocking(&wol->hEvent, 1, INFINITE)) {
3525 result = WSAGetOverlappedResult(s, wol, &size, TRUE, &flg);
3532 result = SOCKET_ERROR;
3535 if ((err = WSAGetLastError()) == WSAECONNABORTED && !input)
3537 else if (err == WSAEMSGSIZE && input) {
3543 errno = map_errno(err);
3545 case WAIT_OBJECT_0 + 1:
3548 CancelIo((HANDLE)s);
3553 if (err == WSAECONNABORTED && !input)
3556 errno = map_errno(err);
3559 CloseHandle(wol->hEvent);
3566overlapped_socket_io(BOOL input,
int fd,
char *buf,
int len,
int flags,
3567 struct sockaddr *addr,
int *addrlen)
3578 socklist_lookup(s, &mode);
3579 if (GET_FLAGS(mode) & O_NONBLOCK) {
3582 if (addr && addrlen)
3583 r = recvfrom(s, buf,
len, flags, addr, addrlen);
3585 r = recv(s, buf,
len, flags);
3586 if (r == SOCKET_ERROR)
3587 errno = map_errno(WSAGetLastError());
3590 if (addr && addrlen)
3591 r = sendto(s, buf,
len, flags, addr, *addrlen);
3593 r = send(s, buf,
len, flags);
3594 if (r == SOCKET_ERROR) {
3595 DWORD err = WSAGetLastError();
3596 if (err == WSAECONNABORTED)
3599 errno = map_errno(err);
3609 memset(&wol, 0,
sizeof(wol));
3611 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3614 if (addr && addrlen)
3615 ret = WSARecvFrom(s, &wbuf, 1, &size, &flg, addr, addrlen,
3618 ret = WSARecv(s, &wbuf, 1, &size, &flg, &wol, NULL);
3621 if (addr && addrlen)
3622 ret = WSASendTo(s, &wbuf, 1, &size, flags, addr, *addrlen,
3625 ret = WSASend(s, &wbuf, 1, &size, flags, &wol, NULL);
3629 finish_overlapped_socket(input, s, &wol, ret, &rlen, size);
3638rb_w32_recv(
int fd,
char *buf,
int len,
int flags)
3640 return overlapped_socket_io(TRUE, fd, buf,
len, flags, NULL, NULL);
3645rb_w32_recvfrom(
int fd,
char *buf,
int len,
int flags,
3646 struct sockaddr *from,
int *fromlen)
3648 return overlapped_socket_io(TRUE, fd, buf,
len, flags, from, fromlen);
3653rb_w32_send(
int fd,
const char *buf,
int len,
int flags)
3655 return overlapped_socket_io(FALSE, fd, (
char *)buf,
len, flags, NULL, NULL);
3660rb_w32_sendto(
int fd,
const char *buf,
int len,
int flags,
3661 const struct sockaddr *to,
int tolen)
3663 return overlapped_socket_io(FALSE, fd, (
char *)buf,
len, flags,
3664 (
struct sockaddr *)to, &tolen);
3667#if !defined(MSG_TRUNC) && !defined(__MINGW32__)
3673 DWORD dwBufferCount;
3678#ifndef WSAID_WSARECVMSG
3679#define WSAID_WSARECVMSG {0xf689d7c8,0x6f1f,0x436b,{0x8a,0x53,0xe5,0x4f,0xe3,0x51,0xc3,0x22}}
3681#ifndef WSAID_WSASENDMSG
3682#define WSAID_WSASENDMSG {0xa441e712,0x754f,0x43ca,{0x84,0xa7,0x0d,0xee,0x44,0xcf,0x60,0x6d}}
3686#define msghdr_to_wsamsg(msg, wsamsg) \
3689 (wsamsg)->name = (msg)->msg_name; \
3690 (wsamsg)->namelen = (msg)->msg_namelen; \
3691 (wsamsg)->lpBuffers = ALLOCA_N(WSABUF, (msg)->msg_iovlen); \
3692 (wsamsg)->dwBufferCount = (msg)->msg_iovlen; \
3693 for (i = 0; i < (msg)->msg_iovlen; ++i) { \
3694 (wsamsg)->lpBuffers[i].buf = (msg)->msg_iov[i].iov_base; \
3695 (wsamsg)->lpBuffers[i].len = (msg)->msg_iov[i].iov_len; \
3697 (wsamsg)->Control.buf = (msg)->msg_control; \
3698 (wsamsg)->Control.len = (msg)->msg_controllen; \
3699 (wsamsg)->dwFlags = (msg)->msg_flags; \
3704recvmsg(
int fd,
struct msghdr *msg,
int flags)
3706 typedef int (WSAAPI *WSARecvMsg_t)(SOCKET,
WSAMSG *, DWORD *, WSAOVERLAPPED *, LPWSAOVERLAPPED_COMPLETION_ROUTINE);
3707 static WSARecvMsg_t pWSARecvMsg = NULL;
3717 static const GUID guid = WSAID_WSARECVMSG;
3718 pWSARecvMsg = (WSARecvMsg_t)get_wsa_extension_function(s, guid);
3723 msghdr_to_wsamsg(msg, &wsamsg);
3724 wsamsg.dwFlags |= flags;
3726 socklist_lookup(s, &mode);
3727 if (GET_FLAGS(mode) & O_NONBLOCK) {
3729 if ((ret = pWSARecvMsg(s, &wsamsg, &
len, NULL, NULL)) == SOCKET_ERROR) {
3730 errno = map_errno(WSAGetLastError());
3738 memset(&wol, 0,
sizeof(wol));
3740 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3741 ret = pWSARecvMsg(s, &wsamsg, &size, &wol, NULL);
3744 ret = finish_overlapped_socket(TRUE, s, &wol, ret, &
len, size);
3746 if (ret == SOCKET_ERROR)
3750 msg->msg_name = wsamsg.name;
3751 msg->msg_namelen = wsamsg.namelen;
3752 msg->msg_flags = wsamsg.dwFlags;
3759sendmsg(
int fd,
const struct msghdr *msg,
int flags)
3761 typedef int (WSAAPI *WSASendMsg_t)(SOCKET,
const WSAMSG *, DWORD, DWORD *, WSAOVERLAPPED *, LPWSAOVERLAPPED_COMPLETION_ROUTINE);
3762 static WSASendMsg_t pWSASendMsg = NULL;
3772 static const GUID guid = WSAID_WSASENDMSG;
3773 pWSASendMsg = (WSASendMsg_t)get_wsa_extension_function(s, guid);
3778 msghdr_to_wsamsg(msg, &wsamsg);
3780 socklist_lookup(s, &mode);
3781 if (GET_FLAGS(mode) & O_NONBLOCK) {
3783 if ((ret = pWSASendMsg(s, &wsamsg, flags, &
len, NULL, NULL)) == SOCKET_ERROR) {
3784 errno = map_errno(WSAGetLastError());
3792 memset(&wol, 0,
sizeof(wol));
3794 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3795 ret = pWSASendMsg(s, &wsamsg, flags, &size, &wol, NULL);
3798 finish_overlapped_socket(FALSE, s, &wol, ret, &
len, size);
3808rb_w32_setsockopt(
int s,
int level,
int optname,
const char *optval,
int optlen)
3812 r = setsockopt(TO_SOCKET(s), level, optname, optval, optlen);
3813 if (r == SOCKET_ERROR)
3814 errno = map_errno(WSAGetLastError());
3823rb_w32_shutdown(
int s,
int how)
3827 r = shutdown(TO_SOCKET(s), how);
3828 if (r == SOCKET_ERROR)
3829 errno = map_errno(WSAGetLastError());
3836open_ifs_socket(
int af,
int type,
int protocol)
3838 unsigned long proto_buffers_len = 0;
3840 SOCKET out = INVALID_SOCKET;
3842 if (WSAEnumProtocols(NULL, NULL, &proto_buffers_len) == SOCKET_ERROR) {
3843 error_code = WSAGetLastError();
3844 if (error_code == WSAENOBUFS) {
3845 WSAPROTOCOL_INFO *proto_buffers;
3846 int protocols_available = 0;
3848 proto_buffers = (WSAPROTOCOL_INFO *)malloc(proto_buffers_len);
3849 if (!proto_buffers) {
3850 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
3851 return INVALID_SOCKET;
3854 protocols_available =
3855 WSAEnumProtocols(NULL, proto_buffers, &proto_buffers_len);
3856 if (protocols_available != SOCKET_ERROR) {
3858 for (i = 0; i < protocols_available; i++) {
3859 if ((af != AF_UNSPEC && af != proto_buffers[i].iAddressFamily) ||
3860 (
type != proto_buffers[i].iSocketType) ||
3861 (protocol != 0 && protocol != proto_buffers[i].iProtocol))
3864 if ((proto_buffers[i].dwServiceFlags1 & XP1_IFS_HANDLES) == 0)
3867 out = WSASocket(af,
type, protocol, &(proto_buffers[i]), 0,
3868 WSA_FLAG_OVERLAPPED);
3871 if (out == INVALID_SOCKET)
3872 out = WSASocket(af,
type, protocol, NULL, 0, 0);
3873 if (out != INVALID_SOCKET)
3874 SetHandleInformation((HANDLE)out, HANDLE_FLAG_INHERIT, 0);
3877 free(proto_buffers);
3888rb_w32_socket(
int af,
int type,
int protocol)
3894 s = open_ifs_socket(af,
type, protocol);
3895 if (s == INVALID_SOCKET) {
3896 errno = map_errno(WSAGetLastError());
3900 fd = rb_w32_open_osfhandle(s, O_RDWR|O_BINARY|O_NOINHERIT);
3902 socklist_insert(s, MAKE_SOCKDATA(af, 0));
3913struct hostent * WSAAPI
3914rb_w32_gethostbyaddr(
const char *addr,
int len,
int type)
3918 r = gethostbyaddr(addr,
len,
type);
3920 errno = map_errno(WSAGetLastError());
3928struct hostent * WSAAPI
3929rb_w32_gethostbyname(
const char *name)
3933 r = gethostbyname(name);
3935 errno = map_errno(WSAGetLastError());
3942static INIT_ONCE hostname_once = INIT_ONCE_STATIC_INIT;
3943static char hostname_cache[256];
3947init_hostname(PINIT_ONCE once, PVOID param, PVOID *context)
3949 if (gethostname(hostname_cache,
sizeof(hostname_cache)) == SOCKET_ERROR) {
3950 errno = map_errno(WSAGetLastError());
3958rb_w32_gethostname(
char *name,
int len)
3965 if (GetEnvironmentVariableW(L
"_CLUSTER_NETWORK_NAME_", NULL, 0) > 1) {
3966 int r = gethostname(name,
len);
3967 if (r == SOCKET_ERROR)
3968 errno = map_errno(WSAGetLastError());
3971 if (!InitOnceExecuteOnce(&hostname_once, init_hostname, NULL, NULL))
3972 return SOCKET_ERROR;
3973 n = (int)strlen(hostname_cache);
3974 if (!name || n >=
len) {
3975 WSASetLastError(WSAEFAULT);
3976 errno = map_errno(WSAEFAULT);
3977 return SOCKET_ERROR;
3979 memcpy(name, hostname_cache, n + 1);
3983#undef getprotobyname
3986struct protoent * WSAAPI
3987rb_w32_getprotobyname(
const char *name)
3991 r = getprotobyname(name);
3993 errno = map_errno(WSAGetLastError());
3998#undef getprotobynumber
4001struct protoent * WSAAPI
4002rb_w32_getprotobynumber(
int num)
4006 r = getprotobynumber(num);
4008 errno = map_errno(WSAGetLastError());
4016struct servent * WSAAPI
4017rb_w32_getservbyname(
const char *name,
const char *proto)
4021 r = getservbyname(name, proto);
4023 errno = map_errno(WSAGetLastError());
4031struct servent * WSAAPI
4032rb_w32_getservbyport(
int port,
const char *proto)
4036 r = getservbyport(port, proto);
4038 errno = map_errno(WSAGetLastError());
4047socketpair_unix_path(
struct sockaddr_un *sock_un, WCHAR *wpath,
const int maxpath)
4054 listener = socket(AF_UNIX, SOCK_STREAM, 0);
4055 if (listener == INVALID_SOCKET) {
4056 errno = EAFNOSUPPORT;
4060 memset(sock_un, 0,
sizeof(*sock_un));
4061 sock_un->sun_family = AF_UNIX;
4071 for (
int try = 0; ;
try++) {
4072 LARGE_INTEGER ticks;
4074 static const WCHAR FALLBACK_TEMP[] = L
"C:/Temp/";
4075 static const int FALLBACK_TEMP_SIZE = numberof(FALLBACK_TEMP) - 1;
4080 path_len = GetTempPathW(maxpath, wpath);
4081 if (path_len == 0 || path_len >= maxpath) {
4090 if (FALLBACK_TEMP_SIZE >= maxpath)
continue;
4091 wcsncpy(wpath, FALLBACK_TEMP, maxpath);
4092 path_len = FALLBACK_TEMP_SIZE;
4099 closesocket(listener);
4100 errno = EADDRNOTAVAIL;
4105 int un_len = WideCharToMultiByte(CP_UTF8, 0, wpath, path_len, sock_un->sun_path, maxpath, NULL, NULL);
4106 QueryPerformanceCounter(&ticks);
4107 int base_len = snprintf(sock_un->sun_path + un_len,
4111 GetCurrentProcessId());
4112 if (un_len + base_len >= maxpath)
continue;
4115 MultiByteToWideChar(CP_UTF8, 0, sock_un->sun_path + un_len, base_len + 1, wpath + path_len, maxpath - path_len);
4117 if (bind(listener, (
struct sockaddr *)sock_un,
sizeof(*sock_un)) != SOCKET_ERROR)
4120 closesocket(listener);
4122 return sizeof(*sock_un);
4128socketpair_internal(
int af,
int type,
int protocol, SOCKET *sv)
4130 SOCKET svr = INVALID_SOCKET, r = INVALID_SOCKET, w = INVALID_SOCKET;
4131 struct sockaddr_in sock_in4;
4134 struct sockaddr_in6 sock_in6;
4138 struct sockaddr_un sock_un = {0, {0}};
4139 WCHAR wpath[
sizeof(sock_un.sun_path)/
sizeof(*sock_un.sun_path)] = L
"";
4142 struct sockaddr *addr;
4148#if defined PF_INET && PF_INET != AF_INET
4151 sock_in4.sin_family = AF_INET;
4152 sock_in4.sin_port = 0;
4153 sock_in4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4154 addr = (
struct sockaddr *)&sock_in4;
4155 len =
sizeof(sock_in4);
4159 memset(&sock_in6, 0,
sizeof(sock_in6));
4160 sock_in6.sin6_family = AF_INET6;
4161 sock_in6.sin6_addr = IN6ADDR_LOOPBACK_INIT;
4162 addr = (
struct sockaddr *)&sock_in6;
4163 len =
sizeof(sock_in6);
4168 addr = (
struct sockaddr *)&sock_un;
4169 len = socketpair_unix_path(&sock_un, wpath, numberof(wpath));
4170 if (!
len)
return -1;
4174 errno = EAFNOSUPPORT;
4177 if (
type != SOCK_STREAM) {
4182 sv[0] = (SOCKET)INVALID_HANDLE_VALUE;
4183 sv[1] = (SOCKET)INVALID_HANDLE_VALUE;
4186 svr = open_ifs_socket(af,
type, protocol);
4187 if (svr == INVALID_SOCKET)
4189 if (bind(svr, addr,
len) < 0)
4191 if (getsockname(svr, addr, &
len) < 0)
4193 if (
type == SOCK_STREAM)
4196 w = open_ifs_socket(af,
type, protocol);
4197 if (w == INVALID_SOCKET)
4199 if (connect(w, addr,
len) < 0)
4202 r = accept(svr, addr, &
len);
4203 if (r == INVALID_SOCKET)
4205 SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0);
4211 errno = map_errno(WSAGetLastError());
4212 if (r != INVALID_SOCKET)
4214 if (w != INVALID_SOCKET)
4221 if (svr != INVALID_SOCKET)
4224 if (sock_un.sun_family == AF_UNIX)
4234socketpair(
int af,
int type,
int protocol,
int *sv)
4238 if (socketpair_internal(af,
type, protocol, pair) < 0)
4240 sv[0] = rb_w32_open_osfhandle(pair[0], O_RDWR|O_BINARY|O_NOINHERIT);
4242 closesocket(pair[0]);
4243 closesocket(pair[1]);
4246 sv[1] = rb_w32_open_osfhandle(pair[1], O_RDWR|O_BINARY|O_NOINHERIT);
4248 rb_w32_close(sv[0]);
4249 closesocket(pair[1]);
4252 socklist_insert(pair[0], MAKE_SOCKDATA(af, 0));
4253 socklist_insert(pair[1], MAKE_SOCKDATA(af, 0));
4260str2guid(
const char *str, GUID *guid)
4262#define hex2byte(str) \
4263 ((isdigit(*(str)) ? *(str) - '0' : toupper(*(str)) - 'A' + 10) << 4 | (isdigit(*((str) + 1)) ? *((str) + 1) - '0' : toupper(*((str) + 1)) - 'A' + 10))
4266 if (*str ==
'{') str++;
4267 guid->Data1 = (long)strtoul(str, &end, 16);
4269 guid->Data2 = (
unsigned short)strtoul(str, &end, 16);
4271 guid->Data3 = (
unsigned short)strtoul(str, &end, 16);
4273 guid->Data4[0] = hex2byte(str);
4275 guid->Data4[1] = hex2byte(str);
4277 for (i = 0; i < 6; i++) {
4278 guid->Data4[i + 2] = hex2byte(str);
4284#ifndef HAVE_TYPE_NET_LUID
4288 uint64_t Reserved :24;
4289 uint64_t NetLuidIndex :24;
4290 uint64_t IfType :16;
4296getifaddrs(
struct ifaddrs **ifap)
4300 IP_ADAPTER_ADDRESSES *root, *addr;
4303 ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, NULL, &size);
4304 if (ret != ERROR_BUFFER_OVERFLOW) {
4305 errno = map_errno(ret);
4308 root = ruby_xmalloc(size);
4309 ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, root, &size);
4310 if (ret != ERROR_SUCCESS) {
4311 errno = map_errno(ret);
4316 for (prev = NULL, addr = root; addr; addr = addr->Next) {
4317 struct ifaddrs *ifa = ruby_xcalloc(1,
sizeof(*ifa));
4318 char name[IFNAMSIZ];
4323 prev->ifa_next = ifa;
4327 str2guid(addr->AdapterName, &guid);
4328 if (ConvertInterfaceGuidToLuid(&guid, &luid) == NO_ERROR &&
4329 ConvertInterfaceLuidToNameA(&luid, name,
sizeof(name)) == NO_ERROR) {
4336 if (addr->IfType & IF_TYPE_SOFTWARE_LOOPBACK)
4337 ifa->ifa_flags |= IFF_LOOPBACK;
4338 if (addr->OperStatus == IfOperStatusUp) {
4339 ifa->ifa_flags |= IFF_UP;
4341 if (addr->FirstUnicastAddress) {
4342 IP_ADAPTER_UNICAST_ADDRESS *cur;
4344 for (cur = addr->FirstUnicastAddress; cur; cur = cur->Next) {
4345 if (cur->Flags & IP_ADAPTER_ADDRESS_TRANSIENT ||
4346 cur->DadState == IpDadStateDeprecated) {
4351 ifa = ruby_xcalloc(1,
sizeof(*ifa));
4352 prev->ifa_next = ifa;
4354 ifa->ifa_flags = prev->ifa_flags;
4356 ifa->ifa_addr = ruby_xmalloc(cur->Address.iSockaddrLength);
4357 memcpy(ifa->ifa_addr, cur->Address.lpSockaddr,
4358 cur->Address.iSockaddrLength);
4373freeifaddrs(
struct ifaddrs *ifp)
4376 struct ifaddrs *next = ifp->ifa_next;
4377 ruby_xfree(ifp->ifa_addr);
4378 ruby_xfree(ifp->ifa_name);
4389void endhostent(
void) {}
4390void endnetent(
void) {}
4391void endprotoent(
void) {}
4392void endservent(
void) {}
4394struct netent *getnetent (
void) {
return (
struct netent *) NULL;}
4396struct netent *getnetbyaddr(
long net,
int type) {
return (
struct netent *)NULL;}
4398struct netent *getnetbyname(
const char *name) {
return (
struct netent *)NULL;}
4400struct protoent *getprotoent (
void) {
return (
struct protoent *) NULL;}
4402struct servent *getservent (
void) {
return (
struct servent *) NULL;}
4404void sethostent (
int stayopen) {}
4406void setnetent (
int stayopen) {}
4408void setprotoent (
int stayopen) {}
4410void setservent (
int stayopen) {}
4413int rb_w32_set_nonblock2(
int fd,
int nonblock);
4417setfl(SOCKET sock,
int arg)
4424 socklist_lookup(sock, &flag);
4425 af = GET_FAMILY(flag);
4426 flag = GET_FLAGS(flag);
4427 if (arg & O_NONBLOCK) {
4432 flag &= ~O_NONBLOCK;
4436 ret = ioctlsocket(sock, FIONBIO, &ioctlArg);
4438 socklist_insert(sock, MAKE_SOCKDATA(af, flag));
4440 errno = map_errno(WSAGetLastError());
4448dupfd(HANDLE hDup,
int flags,
int minfd)
4456 ret = _open_osfhandle((intptr_t)hDup, flags | FOPEN);
4458 goto close_fds_and_return;
4461 goto close_fds_and_return;
4463 fds[filled++] = ret;
4464 }
while (filled < (
int)numberof(fds));
4466 ret = dupfd(hDup, flags, minfd);
4468 close_fds_and_return:
4470 while (filled > 0) {
4471 int fd = fds[--filled];
4472 _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE);
4482fcntl(
int fd,
int cmd, ...)
4491 arg = va_arg(va,
int);
4493 return rb_w32_set_nonblock2(fd, arg);
4495 case F_DUPFD:
case F_DUPFD_CLOEXEC: {
4499 if (!(DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
4500 GetCurrentProcess(), &hDup, 0L,
4501 cmd == F_DUPFD && !(flag & FNOINHERIT),
4502 DUPLICATE_SAME_ACCESS))) {
4503 errno = map_errno(GetLastError());
4508 arg = va_arg(va,
int);
4514 flag &= ~FNOINHERIT;
4515 if ((ret = dupfd(hDup, flag, arg)) == -1)
4521 if (h == -1)
return -1;
4522 if (!GetHandleInformation((HANDLE)h, &flag)) {
4523 errno = map_errno(GetLastError());
4526 return (flag & HANDLE_FLAG_INHERIT) ? 0 : FD_CLOEXEC;
4530 if (h == -1)
return -1;
4532 arg = va_arg(va,
int);
4534 if (!SetHandleInformation((HANDLE)h, HANDLE_FLAG_INHERIT,
4535 (arg & FD_CLOEXEC) ? 0 : HANDLE_FLAG_INHERIT)) {
4536 errno = map_errno(GetLastError());
4539 if (arg & FD_CLOEXEC)
4540 _osfile(fd) |= FNOINHERIT;
4542 _osfile(fd) &= ~FNOINHERIT;
4553rb_w32_set_nonblock2(
int fd,
int nonblock)
4555 SOCKET sock = TO_SOCKET(fd);
4556 if (is_socket(sock)) {
4557 return setfl(sock, nonblock ? O_NONBLOCK : 0);
4559 else if (is_pipe(sock)) {
4561 if (!GetNamedPipeHandleState((HANDLE)sock, &state, NULL, NULL, NULL, NULL, 0)) {
4562 errno = map_errno(GetLastError());
4566 mode = state | PIPE_NOWAIT;
4569 mode = state & ~PIPE_NOWAIT;
4571 if (mode != state && !SetNamedPipeHandleState((HANDLE)sock, &mode, NULL, NULL)) {
4572 errno = map_errno(GetLastError());
4584rb_w32_set_nonblock(
int fd)
4586 return rb_w32_set_nonblock2(fd, TRUE);
4595poll_child_status(
struct ChildRecord *child,
int *stat_loc)
4600 if (!GetExitCodeProcess(child->hProcess, &exitcode)) {
4602 err = GetLastError();
4604 case ERROR_INVALID_PARAMETER:
4607 case ERROR_INVALID_HANDLE:
4611 errno = map_errno(err);
4615 CloseChildHandle(child);
4618 if (exitcode != STILL_ACTIVE) {
4621 if (rb_w32_wait_events_blocking(&child->hProcess, 1, INFINITE) != WAIT_OBJECT_0) {
4625 CloseChildHandle(child);
4627 *stat_loc = exitcode << 8;
4628 if (exitcode & 0xC0000000) {
4629 static const struct {
4633 {STATUS_ACCESS_VIOLATION, SIGSEGV},
4634 {STATUS_ILLEGAL_INSTRUCTION, SIGILL},
4635 {STATUS_PRIVILEGED_INSTRUCTION, SIGILL},
4636 {STATUS_FLOAT_DENORMAL_OPERAND, SIGFPE},
4637 {STATUS_FLOAT_DIVIDE_BY_ZERO, SIGFPE},
4638 {STATUS_FLOAT_INEXACT_RESULT, SIGFPE},
4639 {STATUS_FLOAT_INVALID_OPERATION, SIGFPE},
4640 {STATUS_FLOAT_OVERFLOW, SIGFPE},
4641 {STATUS_FLOAT_STACK_CHECK, SIGFPE},
4642 {STATUS_FLOAT_UNDERFLOW, SIGFPE},
4643#ifdef STATUS_FLOAT_MULTIPLE_FAULTS
4644 {STATUS_FLOAT_MULTIPLE_FAULTS, SIGFPE},
4646#ifdef STATUS_FLOAT_MULTIPLE_TRAPS
4647 {STATUS_FLOAT_MULTIPLE_TRAPS, SIGFPE},
4649 {STATUS_CONTROL_C_EXIT, SIGINT},
4652 for (i = 0; i < (int)numberof(table); i++) {
4653 if (table[i].status == exitcode) {
4654 *stat_loc |= table[i].sig;
4659 if (i >= (
int)numberof(table))
4660 *stat_loc |= SIGSEGV;
4670waitpid(rb_pid_t pid,
int *stat_loc,
int options)
4675 if (options == WNOHANG) {
4686 HANDLE events[MAXCHILDNUM];
4689 FOREACH_CHILD(child) {
4690 if (!child->pid || child->pid < 0)
continue;
4691 if ((pid = poll_child_status(child, stat_loc)))
return pid;
4692 events[count++] = child->hProcess;
4693 } END_FOREACH_CHILD;
4699 ret = rb_w32_wait_events_blocking(events, count, timeout);
4700 if (ret == WAIT_TIMEOUT)
return 0;
4701 if ((ret -= WAIT_OBJECT_0) == count) {
4705 errno = map_errno(GetLastError());
4709 cause = FindChildSlotByHandle(events[ret]);
4714 return poll_child_status(cause, stat_loc);
4724 while (!(pid = poll_child_status(child, stat_loc))) {
4726 int ret = rb_w32_wait_events_blocking(&child->hProcess, 1, timeout);
4727 if (ret == WAIT_OBJECT_0 + 1)
return -1;
4728 if (ret != WAIT_OBJECT_0) {
4730 if (options & WNOHANG) {
4737 if (pid == -1 && retried) pid = 0;
4743#include <sys/timeb.h>
4746#define filetime_unit (10UL * 1000 * 1000)
4747#define filetime_diff_days ((1970-1601)*3652425UL/10000)
4748#define filetime_diff_secs (filetime_diff_days * (24ULL * 60 * 60))
4749#define unix_to_filetime(sec) (((sec) + filetime_diff_secs) * filetime_unit)
4750static const ULONGLONG filetime_unix_offset = unix_to_filetime(0ULL);
4751static const unsigned long secs_in_ns = 1000000000UL;
4763li_time_split(ULONGLONG lt,
long *subsec)
4769 lt -= filetime_unix_offset;
4771 *subsec = (long)(lt % filetime_unit);
4772 return (time_t)(lt / filetime_unit);
4777li_time_split_ns(ULONGLONG lt,
long *ns)
4780 time_t t = li_time_split(lt, &subsec);
4783 if (t < 0)
return 0;
4789filetime_to_li_time(
const FILETIME* ft)
4792 return fi.i.QuadPart;
4802 GetSystemTimePreciseAsFileTime(&ft);
4803 tv->tv_sec = li_time_split(filetime_to_li_time(&ft), &subsec);
4804 tv->tv_usec = subsec / 10;
4811filetime_to_unixtime(
const FILETIME *ft)
4814 time_t t = li_time_split(filetime_to_li_time(ft), &subsec);
4816 if (t < 0)
return 0;
4822filetime_split_ns(
const FILETIME *ft,
long *ns)
4824 return li_time_split_ns(filetime_to_li_time(ft), ns);
4829filetime_to_timespec(FILETIME ft,
struct timespec *sp)
4831 sp->tv_sec = filetime_split_ns(&ft, &sp->tv_nsec);
4836clock_gettime(clockid_t clock_id,
struct timespec *sp)
4839 case CLOCK_REALTIME:
4840 case CLOCK_REALTIME_COARSE:
4844 GetSystemTimePreciseAsFileTime(&ft);
4845 filetime_to_timespec(ft, sp);
4848 case CLOCK_MONOTONIC:
4851 LARGE_INTEGER count;
4852 if (UNLIKELY(!QueryPerformanceFrequency(&freq))) {
4853 errno = map_errno(GetLastError());
4856 if (UNLIKELY(!QueryPerformanceCounter(&count))) {
4857 errno = map_errno(GetLastError());
4860 sp->tv_sec = count.QuadPart / freq.QuadPart;
4861 if (freq.QuadPart < secs_in_ns)
4862 sp->tv_nsec = (count.QuadPart % freq.QuadPart) * secs_in_ns / freq.QuadPart;
4864 sp->tv_nsec = (long)((count.QuadPart % freq.QuadPart) * ((
double)secs_in_ns / freq.QuadPart));
4867 case CLOCK_PROCESS_CPUTIME_ID:
4868 case CLOCK_THREAD_CPUTIME_ID:
4872 if (clock_id == CLOCK_PROCESS_CPUTIME_ID) {
4873 ok = GetProcessTimes(GetCurrentProcess(), &c.ft, &e.ft, &k.ft, &u.ft);
4876 ok = GetThreadTimes(GetCurrentThread(), &c.ft, &e.ft, &k.ft, &u.ft);
4878 if (UNLIKELY(!ok)) {
4879 errno = map_errno(GetLastError());
4882 total.i.QuadPart = k.i.QuadPart + u.i.QuadPart;
4883 filetime_to_timespec(total.ft, sp);
4894clock_getres(clockid_t clock_id,
struct timespec *sp)
4897 case CLOCK_REALTIME:
4898 case CLOCK_REALTIME_COARSE:
4904 case CLOCK_MONOTONIC:
4907 if (!QueryPerformanceFrequency(&freq)) {
4908 errno = map_errno(GetLastError());
4912 sp->tv_nsec = (long)((
double)secs_in_ns / freq.QuadPart);
4915 case CLOCK_PROCESS_CPUTIME_ID:
4916 case CLOCK_THREAD_CPUTIME_ID:
4918 const int frames_in_sec = 60;
4920 sp->tv_nsec = (long)(secs_in_ns / frames_in_sec);
4931w32_getcwd(
char *buffer,
int size, UINT cp,
void *alloc(
int,
void *),
void *arg)
4936 len = GetCurrentDirectoryW(0, NULL);
4938 errno = map_errno(GetLastError());
4942 if (buffer && size <
len) {
4948 if (!GetCurrentDirectoryW(
len, p)) {
4949 errno = map_errno(GetLastError());
4953 wlen = translate_wchar(p, L
'\\', L
'/') - p + 1;
4954 len = WideCharToMultiByte(cp, 0, p, wlen, NULL, 0, NULL, NULL);
4962 buffer = (*alloc)(
len, arg);
4968 WideCharToMultiByte(cp, 0, p, wlen, buffer,
len, NULL, NULL);
4975getcwd_alloc(
int size,
void *dummy)
4977 return malloc(size);
4982rb_w32_getcwd(
char *buffer,
int size)
4984 return w32_getcwd(buffer, size, filecp(), getcwd_alloc, NULL);
4989rb_w32_ugetcwd(
char *buffer,
int size)
4991 return w32_getcwd(buffer, size, CP_UTF8, getcwd_alloc, NULL);
4996getcwd_value(
int size,
void *arg)
4999 return RSTRING_PTR(str);
5004rb_dir_getwd_ospath(
void)
5007 w32_getcwd(NULL, 0, CP_UTF8, getcwd_value, &cwd);
5013chown(
const char *path,
int owner,
int group)
5020rb_w32_uchown(
const char *path,
int owner,
int group)
5026lchown(
const char *path,
int owner,
int group)
5032rb_w32_ulchown(
const char *path,
int owner,
int group)
5039kill(rb_pid_t pid,
int sig)
5044 if (pid < 0 || (pid == 0 && sig != SIGINT)) {
5049 if ((
unsigned int)pid == GetCurrentProcessId() &&
5050 (sig != 0 && sig != SIGKILL)) {
5051 if ((ret = raise(sig)) != 0) {
5062 OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid);
5063 if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) {
5064 if (GetLastError() == ERROR_INVALID_PARAMETER) {
5080 DWORD ctrlEvent = CTRL_C_EVENT;
5084 ctrlEvent = CTRL_BREAK_EVENT;
5086 if (!GenerateConsoleCtrlEvent(ctrlEvent, (DWORD)pid)) {
5087 if ((err = GetLastError()) == 0)
5090 errno = map_errno(GetLastError());
5101 hProc = child->hProcess;
5104 hProc = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid);
5106 if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) {
5107 if (GetLastError() == ERROR_INVALID_PARAMETER) {
5117 if (!GetExitCodeProcess(hProc, &status)) {
5118 errno = map_errno(GetLastError());
5121 else if (status == STILL_ACTIVE) {
5122 if (!TerminateProcess(hProc, 0)) {
5149wlink(
const WCHAR *from,
const WCHAR *to)
5151 if (!CreateHardLinkW(to, from, NULL)) {
5152 errno = map_errno(GetLastError());
5161rb_w32_ulink(
const char *from,
const char *to)
5167 if (!(wfrom = utf8_to_wstr(from, NULL)))
5169 if (!(wto = utf8_to_wstr(to, NULL))) {
5173 ret = wlink(wfrom, wto);
5181link(
const char *from,
const char *to)
5187 if (!(wfrom = filecp_to_wstr(from, NULL)))
5189 if (!(wto = filecp_to_wstr(to, NULL))) {
5193 ret = wlink(wfrom, wto);
5200#ifndef FILE_DEVICE_FILE_SYSTEM
5201# define FILE_DEVICE_FILE_SYSTEM 0x00000009
5203#ifndef FSCTL_GET_REPARSE_POINT
5204# define FSCTL_GET_REPARSE_POINT ((0x9<<16)|(42<<2))
5206#ifndef IO_REPARSE_TAG_SYMLINK
5207# define IO_REPARSE_TAG_SYMLINK 0xA000000CL
5218 f = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5219 if (f == INVALID_HANDLE_VALUE) {
5220 return GetLastError();
5223 if (!DeviceIoControl(f, FSCTL_GET_REPARSE_POINT, NULL, 0,
5224 rp, size, &ret, NULL)) {
5227 else if (rp->ReparseTag != IO_REPARSE_TAG_SYMLINK &&
5228 rp->ReparseTag != IO_REPARSE_TAG_MOUNT_POINT) {
5229 e = ERROR_INVALID_PARAMETER;
5237rb_w32_reparse_symlink_p(
const WCHAR *path)
5245 e = rb_w32_read_reparse_point(path, rp,
sizeof(rbuf), &wbuf, &
len);
5246 if (e == ERROR_MORE_DATA) {
5247 size_t size = rb_w32_reparse_buffer_size(
len + 1);
5249 e = rb_w32_read_reparse_point(path, rp, size, &wbuf, &
len);
5254 case ERROR_MORE_DATA:
5263 size_t bufsize, WCHAR **result, DWORD *
len)
5265 int e = reparse_symlink(path, rp, bufsize);
5268 if (!e || e == ERROR_MORE_DATA) {
5270 if (rp->ReparseTag == IO_REPARSE_TAG_SYMLINK) {
5271 name = ((
char *)rp->SymbolicLinkReparseBuffer.PathBuffer +
5272 rp->SymbolicLinkReparseBuffer.PrintNameOffset);
5273 ret = rp->SymbolicLinkReparseBuffer.PrintNameLength;
5274 *
len = ret /
sizeof(WCHAR);
5276 else if (rp->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT) {
5277 static const WCHAR volume[] = L
"Volume{";
5279 name = ((
char *)rp->MountPointReparseBuffer.PathBuffer +
5280 rp->MountPointReparseBuffer.SubstituteNameOffset +
5281 volume_prefix_len *
sizeof(WCHAR));
5282 ret = rp->MountPointReparseBuffer.SubstituteNameLength;
5283 *
len = ret /
sizeof(WCHAR);
5284 ret -= volume_prefix_len *
sizeof(WCHAR);
5285 if (ret >
sizeof(volume) - 1 *
sizeof(WCHAR) &&
5286 memcmp(name, volume,
sizeof(volume) - 1 *
sizeof(WCHAR)) == 0)
5294 if ((
char *)name + ret +
sizeof(WCHAR) > (
char *)rp + bufsize)
5298 ((WCHAR *)name)[ret/
sizeof(WCHAR)] = L
'\0';
5299 translate_wchar(name, L
'\\', L
'/');
5309w32_readlink(UINT cp,
const char *path,
char *buf,
size_t bufsize)
5311 VALUE rp_buf, rp_buf_bigger = 0;
5312 DWORD
len = MultiByteToWideChar(cp, 0, path, -1, NULL, 0);
5313 size_t size = rb_w32_reparse_buffer_size(bufsize);
5315 WCHAR *wpath =
ALLOCV(rp_buf,
sizeof(WCHAR) *
len + size);
5320 MultiByteToWideChar(cp, 0, path, -1, wpath,
len);
5321 e = rb_w32_read_reparse_point(wpath, rp, size, &wname, &
len);
5322 if (e == ERROR_MORE_DATA) {
5323 size = rb_w32_reparse_buffer_size(
len + 1);
5324 rp =
ALLOCV(rp_buf_bigger, size);
5325 e = rb_w32_read_reparse_point(wpath, rp, size, &wname, &
len);
5330 errno = e == -1 ? EINVAL : map_errno(e);
5333 len = lstrlenW(wname);
5334 ret = WideCharToMultiByte(cp, 0, wname,
len, buf, bufsize, NULL, NULL);
5345rb_w32_ureadlink(
const char *path,
char *buf,
size_t bufsize)
5347 return w32_readlink(CP_UTF8, path, buf, bufsize);
5352readlink(
const char *path,
char *buf,
size_t bufsize)
5354 return w32_readlink(filecp(), path, buf, bufsize);
5357#ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5358#define SYMBOLIC_LINK_FLAG_DIRECTORY (0x1)
5360#ifndef SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
5361#define SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE (0x2)
5366w32_symlink(UINT cp,
const char *src,
const char *link)
5368 int atts, len1, len2;
5370 WCHAR *wsrc, *wlink;
5375 static DWORD create_flag = SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
5385 len1 = MultiByteToWideChar(cp, 0, src, -1, NULL, 0);
5386 len2 = MultiByteToWideChar(cp, 0, link, -1, NULL, 0);
5387 wsrc =
ALLOCV_N(WCHAR, buf, len1+len2);
5388 wlink = wsrc + len1;
5389 MultiByteToWideChar(cp, 0, src, -1, wsrc, len1);
5390 MultiByteToWideChar(cp, 0, link, -1, wlink, len2);
5391 translate_wchar(wsrc, L
'/', L
'\\');
5392 translate_wchar(wlink, L
'/', L
'\\');
5402 (((wsrc[0] >= L
'A' && wsrc[0] <= L
'Z') ||
5403 (wsrc[0] >= L
'a' && wsrc[0] <= L
'z')) && wsrc[1] == L
':') ||
5405 if (!independent && (sep = wcsrchr(wlink, L
'\\')) != NULL) {
5407 size_t dirlen = sep - wlink + 1;
5408 size_t srclen = wcslen(wsrc) + 1;
5409 WCHAR *fullsrc =
ALLOCV_N(WCHAR, buf2, dirlen + srclen);
5410 MEMCPY(fullsrc, wlink, WCHAR, dirlen);
5411 MEMCPY(fullsrc + dirlen, wsrc, WCHAR, srclen);
5412 atts = GetFileAttributesW(fullsrc);
5416 atts = GetFileAttributesW(wsrc);
5419 if (atts != -1 && atts & FILE_ATTRIBUTE_DIRECTORY)
5420 flag = SYMBOLIC_LINK_FLAG_DIRECTORY;
5421 ret = CreateSymbolicLinkW(wlink, wsrc, flag |= create_flag);
5423 (e = GetLastError()) == ERROR_INVALID_PARAMETER &&
5424 (flag & SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)) {
5426 flag &= ~SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
5427 ret = CreateSymbolicLinkW(wlink, wsrc, flag);
5428 if (!ret) e = GetLastError();
5433 errno = map_errno(e);
5441rb_w32_usymlink(
const char *src,
const char *link)
5443 return w32_symlink(CP_UTF8, src, link);
5448symlink(
const char *src,
const char *link)
5450 return w32_symlink(filecp(), src, link);
5457 return waitpid(-1, status, 0);
5462w32_getenv(
const char *name, UINT cp)
5464 WCHAR *wname, wbuf[256], *wval = wbuf;
5465 DWORD wlen, size = numberof(wbuf);
5466 char *uenvarea = NULL;
5468 if (!*name)
return NULL;
5473 return getenv(name);
5476 if (!(wname = mbstr_to_wstr(cp, name, -1, NULL)))
return NULL;
5480 SetLastError(NO_ERROR);
5481 wlen = GetEnvironmentVariableW(wname, wval, size);
5482 if (wlen < size)
break;
5483 if (wval != wbuf) free(wval);
5485 if (!(wval = malloc(size *
sizeof(WCHAR))))
break;
5487 if (wval && (wlen || GetLastError() == NO_ERROR))
5488 uenvarea = wstr_to_mbstr(cp, wval, wlen + 1, NULL);
5489 if (wval != wbuf) free(wval);
5492 free(FlsGetValue(uenvarea_key));
5493 FlsSetValue(uenvarea_key, uenvarea);
5499rb_w32_ugetenv(
const char *name)
5501 return w32_getenv(name, CP_UTF8);
5506rb_w32_getenv(
const char *name)
5508 return w32_getenv(name, CP_ACP);
5513get_attr_vsn(
const WCHAR *path, DWORD *atts, DWORD *vsn)
5515 BY_HANDLE_FILE_INFORMATION st = {0};
5517 HANDLE h = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5519 if (h == INVALID_HANDLE_VALUE) {
5524 if (!GetFileInformationByHandle(h, &st)) {
5529 *atts = st.dwFileAttributes;
5530 *vsn = st.dwVolumeSerialNumber;
5538wrename(
const WCHAR *oldpath,
const WCHAR *newpath)
5541 DWORD oldatts = 0, newatts = (DWORD)-1;
5542 DWORD oldvsn = 0, newvsn = 0, e;
5544 e = get_attr_vsn(oldpath, &oldatts, &oldvsn);
5546 errno = map_errno(e);
5549 if (oldatts & FILE_ATTRIBUTE_REPARSE_POINT) {
5550 HANDLE fh = open_special(oldpath, 0, 0);
5551 if (fh == INVALID_HANDLE_VALUE) {
5553 if (e == ERROR_CANT_RESOLVE_FILENAME) {
5560 get_attr_vsn(newpath, &newatts, &newvsn);
5563 if (newatts != (DWORD)-1 && newatts & FILE_ATTRIBUTE_READONLY)
5564 SetFileAttributesW(newpath, newatts & ~ FILE_ATTRIBUTE_READONLY);
5566 if (!MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED))
5570 DWORD e = GetLastError();
5571 if ((e == ERROR_ACCESS_DENIED) && (oldatts & FILE_ATTRIBUTE_DIRECTORY) &&
5575 errno = map_errno(e);
5578 SetFileAttributesW(newpath, oldatts);
5586rb_w32_urename(
const char *from,
const char *to)
5592 if (!(wfrom = utf8_to_wstr(from, NULL)))
5594 if (!(wto = utf8_to_wstr(to, NULL))) {
5598 ret = wrename(wfrom, wto);
5606rb_w32_rename(
const char *from,
const char *to)
5612 if (!(wfrom = filecp_to_wstr(from, NULL)))
5614 if (!(wto = filecp_to_wstr(to, NULL))) {
5618 ret = wrename(wfrom, wto);
5626isUNCRoot(
const WCHAR *path)
5628 if (path[0] == L
'\\' && path[1] == L
'\\') {
5629 const WCHAR *p = path + 2;
5630 if (p[0] == L
'?' && p[1] == L
'\\') {
5638 for (p++; *p; p++) {
5642 if (!p[0] || !p[1] || (p[1] == L
'.' && !p[2]))
5649#define COPY_STAT(src, dest, size_cast) do { \
5650 (dest).st_dev = (src).st_dev; \
5651 (dest).st_ino = (src).st_ino; \
5652 (dest).st_mode = (src).st_mode; \
5653 (dest).st_nlink = (src).st_nlink; \
5654 (dest).st_uid = (src).st_uid; \
5655 (dest).st_gid = (src).st_gid; \
5656 (dest).st_rdev = (src).st_rdev; \
5657 (dest).st_size = size_cast(src).st_size; \
5658 (dest).st_atime = (src).st_atime; \
5659 (dest).st_mtime = (src).st_mtime; \
5660 (dest).st_ctime = (src).st_ctime; \
5663static WCHAR *name_for_stat(WCHAR *buf,
const WCHAR *path);
5664static DWORD stati128_handle(HANDLE h,
struct stati128 *st);
5669rb_w32_fstat(
int fd,
struct stat *st)
5671 BY_HANDLE_FILE_INFORMATION info;
5672 int ret = fstat(fd, st);
5674 if (ret)
return ret;
5675 if (GetEnvironmentVariableW(L
"TZ", NULL, 0) == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND)
return ret;
5676 if (GetFileInformationByHandle((HANDLE)_get_osfhandle(fd), &info)) {
5677 st->st_atime = filetime_to_unixtime(&info.ftLastAccessTime);
5678 st->st_mtime = filetime_to_unixtime(&info.ftLastWriteTime);
5679 st->st_ctime = filetime_to_unixtime(&info.ftCreationTime);
5686rb_w32_fstati128(
int fd,
struct stati128 *st)
5689 int ret = _fstat64(fd, &tmp);
5691 if (ret)
return ret;
5692 COPY_STAT(tmp, *st, +);
5693 stati128_handle((HANDLE)_get_osfhandle(fd), st);
5697#if !defined FILE_INVALID_FILE_ID && !defined __MINGW32__
5699 BYTE Identifier[16];
5703#if !defined(_WIN32_WINNT_WIN8) || _WIN32_WINNT < 0x602
5704#define FileIdInfo 0x12
5715 return GetFileInformationByHandleEx(h, FileIdInfo,
id,
sizeof(*
id));
5720stati128_handle(HANDLE h,
struct stati128 *st)
5722 BY_HANDLE_FILE_INFORMATION info;
5723 DWORD attr = (DWORD)-1;
5725 if (GetFileInformationByHandle(h, &info)) {
5727 st->st_size = ((__int64)info.nFileSizeHigh << 32) | info.nFileSizeLow;
5728 st->st_atime = filetime_split_ns(&info.ftLastAccessTime, &st->st_atimensec);
5729 st->st_mtime = filetime_split_ns(&info.ftLastWriteTime, &st->st_mtimensec);
5730 st->st_ctime = filetime_split_ns(&info.ftCreationTime, &st->st_ctimensec);
5731 st->st_nlink = info.nNumberOfLinks;
5732 attr = info.dwFileAttributes;
5733 if (get_ino(h, &fii)) {
5734 st->st_ino = *((
unsigned __int64 *)&fii.FileId);
5735 st->st_inohigh = *((__int64 *)&fii.FileId + 1);
5738 st->st_ino = ((__int64)info.nFileIndexHigh << 32) | info.nFileIndexLow;
5747fileattr_to_unixmode(DWORD attr,
const WCHAR *path,
unsigned mode)
5749 if (attr & FILE_ATTRIBUTE_READONLY) {
5753 mode |= S_IREAD | S_IWRITE | S_IWUSR;
5756 if (mode & S_IFMT) {
5759 else if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
5763 else if (attr & FILE_ATTRIBUTE_DIRECTORY) {
5764 mode |= S_IFDIR | S_IEXEC;
5770 if (path && (mode & S_IFREG)) {
5771 const WCHAR *end = path + lstrlenW(path);
5772 while (path < end) {
5773 end = CharPrevW(path, end);
5775 if ((_wcsicmp(end, L
".bat") == 0) ||
5776 (_wcsicmp(end, L
".cmd") == 0) ||
5777 (_wcsicmp(end, L
".com") == 0) ||
5778 (_wcsicmp(end, L
".exe") == 0)) {
5783 if (!iswalnum(*end))
break;
5787 mode |= (mode & 0500) >> 3;
5788 mode |= (mode & 0500) >> 6;
5795check_valid_dir(
const WCHAR *path)
5797 WIN32_FIND_DATAW fd;
5799 WCHAR full[PATH_MAX];
5804 if (!(p = wcsstr(path, L
"...")))
5806 q = p + wcsspn(p, L
".");
5807 if ((p == path || wcschr(L
":/\\", *(p - 1))) &&
5808 (!*q || wcschr(L
":/\\", *q))) {
5815 DWORD
len = GetFullPathNameW(path, numberof(full), full, NULL);
5816 if (
len >= numberof(full)) {
5817 WCHAR *fullpath = malloc(
len *
sizeof(WCHAR));
5818 if (!fullpath)
return -1;
5819 len = GetFullPathNameW(path,
len, fullpath, NULL);
5824 errno = map_errno(GetLastError());
5827 if (
len == 3 && full[1] == L
':' && GetDriveTypeW(full) != DRIVE_NO_ROOT_DIR)
5830 fh = open_dir_handle(path, &fd);
5831 if (fh == INVALID_HANDLE_VALUE)
5839stat_by_find(
const WCHAR *path,
struct stati128 *st)
5842 WIN32_FIND_DATAW wfd;
5845 h = FindFirstFileW(path, &wfd);
5846 if (h == INVALID_HANDLE_VALUE) {
5847 errno = map_errno(GetLastError());
5851 st->st_mode = fileattr_to_unixmode(wfd.dwFileAttributes, path, 0);
5852 st->st_atime = filetime_split_ns(&wfd.ftLastAccessTime, &st->st_atimensec);
5853 st->st_mtime = filetime_split_ns(&wfd.ftLastWriteTime, &st->st_mtimensec);
5854 st->st_ctime = filetime_split_ns(&wfd.ftCreationTime, &st->st_ctimensec);
5855 st->st_size = ((__int64)wfd.nFileSizeHigh << 32) | wfd.nFileSizeLow;
5862path_drive(
const WCHAR *path)
5864 if (path[0] && path[1] == L
':') {
5865 if (iswalpha(path[0]))
return towupper(path[0]) - L
'A';
5866 return (
int)path[0];
5868 return _getdrive() - 1;
5871#if !defined(NTDDI_WIN11_ZN) || NTDDI_VERSION < NTDDI_WIN11_ZN
5874#define FileStatBasicByNameInfo 3
5877 LARGE_INTEGER FileId;
5878 LARGE_INTEGER CreationTime;
5879 LARGE_INTEGER LastAccessTime;
5880 LARGE_INTEGER LastWriteTime;
5881 LARGE_INTEGER ChangeTime;
5882 LARGE_INTEGER AllocationSize;
5883 LARGE_INTEGER EndOfFile;
5884 DWORD FileAttributes;
5886 DWORD NumberOfLinks;
5888 DWORD DeviceCharacteristics;
5890 LARGE_INTEGER VolumeSerialNumber;
5895#ifndef FILE_DEVICE_DISK
5896#define FILE_DEVICE_DISK 7
5899typedef BOOL (WINAPI *get_file_information_by_name_func)
5900 (PCWSTR,
int , PVOID, ULONG);
5901static get_file_information_by_name_func get_file_information_by_name =
5902 (get_file_information_by_name_func)-1;
5906large_integer_to_unixtime(
const LARGE_INTEGER *at,
long *nsecp)
5908 time_t t = li_time_split_ns(at->QuadPart, nsecp);
5909 if (t < 0)
return 0;
5915path_drive_serial(
const WCHAR *path)
5920 if (path[0] && path[1] == L
':') {
5921 if (!iswalpha(path[0]))
return 0;
5922 drive = towupper(path[0]) - L
'A';
5925 drive = _getdrive() - 1;
5927 if (drive < 0 || (
int)numberof(serials) <= drive)
return 0;
5928 if (!serials[drive]) {
5930 WCHAR root[] = L
"_:\\";
5931 root[0] = L
'A' + drive;
5932 if (get_file_information_by_name(root, FileStatBasicByNameInfo,
5933 &info,
sizeof(info)))
5934 serials[drive] = info.VolumeSerialNumber.QuadPart;
5936 return serials[drive];
5941stat_by_name(
const WCHAR *path,
struct stati128 *st)
5947 unsigned __int64 ino;
5950 if (get_file_information_by_name == (get_file_information_by_name_func)-1) {
5952 get_file_information_by_name = (get_file_information_by_name_func)
5953 get_proc_address(
"kernel32",
"GetFileInformationByName", NULL);
5955 if (!get_file_information_by_name)
return 1;
5956 if (!get_file_information_by_name(path, FileStatBasicByNameInfo,
5957 &info,
sizeof(info))) {
5958 DWORD e = GetLastError();
5960 case ERROR_FILE_NOT_FOUND:
5961 case ERROR_INVALID_NAME:
5962 case ERROR_PATH_NOT_FOUND:
5963 case ERROR_BAD_NETPATH:
5964 errno = map_errno(e);
5969 if (info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
5971 if (info.DeviceType != FILE_DEVICE_DISK)
5973 if (info.VolumeSerialNumber.QuadPart != path_drive_serial(path))
5975 ino = *((
unsigned __int64 *)&info.FileId128);
5976 inohigh = *((__int64 *)&info.FileId128 + 1);
5977 if (!ino && !inohigh)
5979 if (info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
5980 if (check_valid_dir(path))
return -1;
5983 st->st_inohigh = inohigh;
5984 st->st_size = info.EndOfFile.QuadPart;
5985 st->st_atime = large_integer_to_unixtime(&info.LastAccessTime, &st->st_atimensec);
5986 st->st_mtime = large_integer_to_unixtime(&info.LastWriteTime, &st->st_mtimensec);
5987 st->st_ctime = large_integer_to_unixtime(&info.CreationTime, &st->st_ctimensec);
5988 st->st_nlink = info.NumberOfLinks;
5989 st->st_mode = fileattr_to_unixmode(info.FileAttributes, path, 0);
5990 st->st_dev = st->st_rdev = path_drive(path);
5996winnt_stat(
const WCHAR *path,
struct stati128 *st, BOOL lstat)
5998 DWORD flags = lstat ? FILE_FLAG_OPEN_REPARSE_POINT : 0;
6000 WCHAR *finalname = 0;
6003 memset(st, 0,
sizeof(*st));
6004 switch (stat_by_name(path, st)) {
6010 f = open_special(path, 0, flags);
6011 open_error = GetLastError();
6012 if (f == INVALID_HANDLE_VALUE && !lstat) {
6014 FILE_ATTRIBUTE_TAG_INFO attr_info;
6017 f = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
6018 e = GetFileInformationByHandleEx(f, FileAttributeTagInfo,
6019 &attr_info,
sizeof(attr_info));
6020 if (!e || attr_info.ReparseTag != IO_REPARSE_TAG_AF_UNIX) {
6022 f = INVALID_HANDLE_VALUE;
6025 if (f != INVALID_HANDLE_VALUE) {
6026 DWORD attr = stati128_handle(f, st);
6028 switch (GetFileType(f)) {
6029 case FILE_TYPE_CHAR:
6032 case FILE_TYPE_PIPE:
6036 if (attr & FILE_ATTRIBUTE_DIRECTORY) {
6037 if (check_valid_dir(path))
return -1;
6039 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
6040 FILE_ATTRIBUTE_TAG_INFO attr_info;
6043 e = GetFileInformationByHandleEx(f, FileAttributeTagInfo,
6044 &attr_info,
sizeof(attr_info));
6045 if (e && attr_info.ReparseTag == IO_REPARSE_TAG_AF_UNIX) {
6049 else if (rb_w32_reparse_symlink_p(path)) {
6052 mode |= S_IFLNK | S_IEXEC;
6055 mode |= S_IFDIR | S_IEXEC;
6059 const DWORD
len = get_handle_pathname(f, &finalname, 0);
6061 st->st_mode = fileattr_to_unixmode(attr, path, mode);
6064 if (wcsncmp(path, namespace_prefix, numberof(namespace_prefix)) == 0)
6065 path += numberof(namespace_prefix);
6069 switch (open_error) {
6070 case ERROR_FILE_NOT_FOUND:
6071 case ERROR_INVALID_NAME:
6072 case ERROR_PATH_NOT_FOUND:
6073 case ERROR_BAD_NETPATH:
6074 case ERROR_CANT_RESOLVE_FILENAME:
6075 errno = map_errno(open_error);
6079 if (stat_by_find(path, st))
return -1;
6082 st->st_dev = st->st_rdev = path_drive(path);
6083 if (finalname) free(finalname);
6090rb_w32_stat(
const char *path,
struct stat *st)
6092 struct stati128 tmp;
6094 if (w32_stati128(path, &tmp, filecp(), FALSE))
return -1;
6095 COPY_STAT(tmp, *st, (_off_t));
6101wstati128(
const WCHAR *path,
struct stati128 *st, BOOL lstat)
6111 size = lstrlenW(path) + 2;
6113 if (!(path = name_for_stat(buf1, path)))
6115 ret = winnt_stat(path, st, lstat);
6124name_for_stat(WCHAR *buf1,
const WCHAR *path)
6130 for (p = path, s = buf1; *p; p++, s++) {
6138 if (!
len || L
'\"' == *(--s)) {
6142 end = buf1 +
len - 1;
6144 if (isUNCRoot(buf1)) {
6147 else if (*end != L
'\\')
6148 lstrcatW(buf1, L
"\\");
6150 else if (*end == L
'\\' || (buf1 + 1 == end && *end == L
':'))
6151 lstrcatW(buf1, L
".");
6158rb_w32_ustati128(
const char *path,
struct stati128 *st)
6160 return w32_stati128(path, st, CP_UTF8, FALSE);
6165rb_w32_stati128(
const char *path,
struct stati128 *st)
6167 return w32_stati128(path, st, filecp(), FALSE);
6172w32_stati128(
const char *path,
struct stati128 *st, UINT cp, BOOL lstat)
6177 if (!(wpath = mbstr_to_wstr(cp, path, -1, NULL)))
6179 ret = wstati128(wpath, st, lstat);
6186rb_w32_ulstati128(
const char *path,
struct stati128 *st)
6188 return w32_stati128(path, st, CP_UTF8, TRUE);
6193rb_w32_lstati128(
const char *path,
struct stati128 *st)
6195 return w32_stati128(path, st, filecp(), TRUE);
6200rb_w32_lseek(
int fd, rb_off_t ofs,
int whence)
6202 SOCKET sock = TO_SOCKET(fd);
6203 if (is_socket(sock) || is_pipe(sock)) {
6207 return _lseeki64(fd, ofs, whence);
6212w32_access(
const char *path,
int mode, UINT cp)
6214 struct stati128 stat;
6215 if (w32_stati128(path, &stat, cp, FALSE) != 0)
6218 if ((stat.st_mode & mode) != mode) {
6227rb_w32_access(
const char *path,
int mode)
6229 return w32_access(path, mode, filecp());
6234rb_w32_uaccess(
const char *path,
int mode)
6236 return w32_access(path, mode, CP_UTF8);
6241rb_chsize(HANDLE h, rb_off_t size)
6243 long upos, lpos, usize, lsize;
6247 if ((lpos = SetFilePointer(h, 0, (upos = 0, &upos), SEEK_CUR)) == -1L &&
6248 (e = GetLastError())) {
6249 errno = map_errno(e);
6252 usize = (long)(size >> 32);
6254 if (SetFilePointer(h, lsize, &usize, SEEK_SET) == (DWORD)-1L &&
6255 (e = GetLastError())) {
6256 errno = map_errno(e);
6258 else if (!SetEndOfFile(h)) {
6259 errno = map_errno(GetLastError());
6264 SetFilePointer(h, lpos, &upos, SEEK_SET);
6270w32_truncate(
const char *path, rb_off_t length, UINT cp)
6276 if (!(wpath = mbstr_to_wstr(cp, path, -1, NULL)))
6278 h = CreateFileW(wpath, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
6279 if (h == INVALID_HANDLE_VALUE) {
6280 errno = map_errno(GetLastError());
6285 ret = rb_chsize(h, length);
6292rb_w32_utruncate(
const char *path, rb_off_t length)
6294 return w32_truncate(path, length, CP_UTF8);
6299rb_w32_truncate(
const char *path, rb_off_t length)
6301 return w32_truncate(path, length, filecp());
6306rb_w32_ftruncate(
int fd, rb_off_t length)
6310 h = (HANDLE)_get_osfhandle(fd);
6311 if (h == (HANDLE)-1)
return -1;
6312 return rb_chsize(h, length);
6317filetime_to_clock(FILETIME *ft)
6319 __int64 qw = ft->dwHighDateTime;
6321 qw |= ft->dwLowDateTime;
6328rb_w32_times(
struct tms *tmbuf)
6330 FILETIME create, exit, kernel, user;
6332 if (GetProcessTimes(GetCurrentProcess(),&create, &exit, &kernel, &user)) {
6333 tmbuf->tms_utime = filetime_to_clock(&user);
6334 tmbuf->tms_stime = filetime_to_clock(&kernel);
6335 tmbuf->tms_cutime = 0;
6336 tmbuf->tms_cstime = 0;
6339 tmbuf->tms_utime = clock();
6340 tmbuf->tms_stime = 0;
6341 tmbuf->tms_cutime = 0;
6342 tmbuf->tms_cstime = 0;
6349#define yield_once() Sleep(0)
6350#define yield_until(condition) do yield_once(); while (!(condition))
6359 uintptr_t (*func)(uintptr_t self,
int argc, uintptr_t* argv);
6367call_asynchronous(PVOID argp)
6371 arg->stackaddr = &argp;
6372 ret = (DWORD)arg->func(arg->self, arg->argc, arg->argv);
6373 arg->errnum =
errno;
6379rb_w32_asynchronize(asynchronous_func_t func, uintptr_t self,
6380 int argc, uintptr_t* argv, uintptr_t intrval)
6383 BOOL interrupted = FALSE;
6389 arg.stackaddr = NULL;
6396 thr = CreateThread(NULL, 0, call_asynchronous, &arg, 0, &val);
6399 yield_until(arg.stackaddr);
6401 if (rb_w32_wait_events_blocking(&thr, 1, INFINITE) != WAIT_OBJECT_0) {
6404 if (TerminateThread(thr, intrval)) {
6409 GetExitCodeThread(thr, &val);
6414 MEMORY_BASIC_INFORMATION m;
6416 memset(&m, 0,
sizeof(m));
6417 if (!VirtualQuery(arg.stackaddr, &m,
sizeof(m))) {
6418 Debug(fprintf(stderr,
"couldn't get stack base:%p:%d\n",
6419 arg.stackaddr, GetLastError()));
6421 else if (!VirtualFree(m.AllocationBase, 0, MEM_RELEASE)) {
6422 Debug(fprintf(stderr,
"couldn't release stack:%p:%d\n",
6423 m.AllocationBase, GetLastError()));
6434 rb_fatal(
"failed to launch waiter thread:%ld", GetLastError());
6442rb_w32_get_environ(
void)
6444 WCHAR *envtop, *env;
6445 char **myenvtop, **myenv;
6458 envtop = GetEnvironmentStringsW();
6459 for (env = envtop, num = 0; *env; env += lstrlenW(env) + 1)
6460 if (*env !=
'=') num++;
6462 myenvtop = (
char **)malloc(
sizeof(
char *) * (num + 1));
6463 for (env = envtop, myenv = myenvtop; *env; env += lstrlenW(env) + 1) {
6465 if (!(*myenv = wstr_to_utf8(env, NULL))) {
6472 FreeEnvironmentStringsW(envtop);
6479rb_w32_free_environ(
char **env)
6483 while (*t) free(*t++);
6491 return GetCurrentProcessId();
6499 typedef long (WINAPI query_func)(HANDLE, int,
void *, ULONG, ULONG *);
6500 static query_func *pNtQueryInformationProcess = (query_func *)-1;
6503 if (pNtQueryInformationProcess == (query_func *)-1)
6504 pNtQueryInformationProcess = (query_func *)get_proc_address(
"ntdll.dll",
"NtQueryInformationProcess", NULL);
6505 if (pNtQueryInformationProcess) {
6508 void* PebBaseAddress;
6509 uintptr_t AffinityMask;
6510 uintptr_t BasePriority;
6511 uintptr_t UniqueProcessId;
6512 uintptr_t ParentProcessId;
6515 long ret = pNtQueryInformationProcess(GetCurrentProcess(), 0, &pbi,
sizeof(pbi), &
len);
6517 ppid = pbi.ParentProcessId;
6524STATIC_ASSERT(std_handle, (STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)==(STD_ERROR_HANDLE-STD_OUTPUT_HANDLE));
6527#define set_new_std_handle(newfd, handle) do { \
6528 if ((unsigned)(newfd) > 2) break; \
6529 SetStdHandle(STD_INPUT_HANDLE+(STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)*(newfd), \
6532#define set_new_std_fd(newfd) set_new_std_handle(newfd, (HANDLE)rb_w32_get_osfhandle(newfd))
6536rb_w32_dup2(
int oldfd,
int newfd)
6540 if (oldfd == newfd)
return newfd;
6541 ret = dup2(oldfd, newfd);
6542 if (ret < 0)
return ret;
6543 set_new_std_fd(newfd);
6549rb_w32_uopen(
const char *file,
int oflag, ...)
6556 va_start(arg, oflag);
6557 pmode = va_arg(arg,
int);
6560 if (!(wfile = utf8_to_wstr(file, NULL)))
6562 ret = w32_wopen(wfile, oflag, pmode);
6569check_if_wdir(
const WCHAR *wfile)
6571 DWORD attr = GetFileAttributesW(wfile);
6572 if (attr == (DWORD)-1L ||
6573 !(attr & FILE_ATTRIBUTE_DIRECTORY) ||
6574 check_valid_dir(wfile)) {
6583rb_w32_open(
const char *file,
int oflag, ...)
6590 va_start(arg, oflag);
6591 pmode = va_arg(arg,
int);
6594 if (!(wfile = filecp_to_wstr(file, NULL)))
6596 ret = w32_wopen(wfile, oflag, pmode);
6603rb_w32_wopen(
const WCHAR *file,
int oflag, ...)
6607 if (oflag & O_CREAT) {
6609 va_start(arg, oflag);
6610 pmode = va_arg(arg,
int);
6614 return w32_wopen(file, oflag, pmode);
6618w32_wopen(
const WCHAR *file,
int oflag,
int pmode)
6624 DWORD attr = FILE_ATTRIBUTE_NORMAL;
6625 SECURITY_ATTRIBUTES sec;
6629 share_delete = oflag & O_SHARE_DELETE ? FILE_SHARE_DELETE : 0;
6630 oflag &= ~O_SHARE_DELETE;
6631 if ((oflag & O_TEXT) || !(oflag & O_BINARY)) {
6632 fd = _wopen(file, oflag, pmode);
6636 check_if_wdir(file);
6639 errno = map_errno(GetLastError());
6646 sec.nLength =
sizeof(sec);
6647 sec.lpSecurityDescriptor = NULL;
6648 if (oflag & O_NOINHERIT) {
6649 sec.bInheritHandle = FALSE;
6650 flags |= FNOINHERIT;
6653 sec.bInheritHandle = TRUE;
6655 oflag &= ~O_NOINHERIT;
6658 oflag &= ~(O_BINARY | O_TEXT);
6660 switch (oflag & (O_RDWR | O_RDONLY | O_WRONLY)) {
6662 access = GENERIC_READ | GENERIC_WRITE;
6665 access = GENERIC_READ;
6668 access = GENERIC_WRITE;
6674 oflag &= ~(O_RDWR | O_RDONLY | O_WRONLY);
6676 switch (oflag & (O_CREAT | O_EXCL | O_TRUNC)) {
6678 create = OPEN_ALWAYS;
6682 create = OPEN_EXISTING;
6684 case O_CREAT | O_EXCL:
6685 case O_CREAT | O_EXCL | O_TRUNC:
6686 create = CREATE_NEW;
6689 case O_TRUNC | O_EXCL:
6690 create = TRUNCATE_EXISTING;
6692 case O_CREAT | O_TRUNC:
6693 create = CREATE_ALWAYS;
6699 if (oflag & O_CREAT) {
6701 if (!(pmode & S_IWRITE))
6702 attr = FILE_ATTRIBUTE_READONLY;
6704 oflag &= ~(O_CREAT | O_EXCL | O_TRUNC);
6706 if (oflag & O_TEMPORARY) {
6707 attr |= FILE_FLAG_DELETE_ON_CLOSE;
6710 oflag &= ~O_TEMPORARY;
6712 if (oflag & _O_SHORT_LIVED)
6713 attr |= FILE_ATTRIBUTE_TEMPORARY;
6714 oflag &= ~_O_SHORT_LIVED;
6716 switch (oflag & (O_SEQUENTIAL | O_RANDOM)) {
6720 attr |= FILE_FLAG_SEQUENTIAL_SCAN;
6723 attr |= FILE_FLAG_RANDOM_ACCESS;
6729 oflag &= ~(O_SEQUENTIAL | O_RANDOM);
6731 if (oflag & ~O_APPEND) {
6738 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6739 fd = _open_osfhandle((intptr_t)h, 0);
6747 rb_acrt_lowio_lock_fh(fd);
6748 _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE);
6749 _set_osflags(fd, 0);
6751 h = CreateFileW(file, access, FILE_SHARE_READ | FILE_SHARE_WRITE | share_delete, &sec, create, attr, NULL);
6752 if (h == INVALID_HANDLE_VALUE) {
6753 DWORD e = GetLastError();
6754 if (e != ERROR_ACCESS_DENIED || !check_if_wdir(file))
6755 errno = map_errno(e);
6756 rb_acrt_lowio_unlock_fh(fd);
6761 switch (GetFileType(h)) {
6762 case FILE_TYPE_CHAR:
6765 case FILE_TYPE_PIPE:
6768 case FILE_TYPE_UNKNOWN:
6769 errno = map_errno(GetLastError());
6771 rb_acrt_lowio_unlock_fh(fd);
6775 if (!(flags & (FDEV | FPIPE)) && (oflag & O_APPEND))
6778 _set_osfhnd(fd, (intptr_t)h);
6779 _set_osflags(fd, flags | FOPEN);
6781 rb_acrt_lowio_unlock_fh(fd);
6791rb_w32_fclose(FILE *fp)
6793 int fd = fileno(fp);
6794 SOCKET sock = TO_SOCKET(fd);
6795 int save_errno =
errno;
6797 if (fflush(fp))
return -1;
6798 if (!is_socket(sock)) {
6799 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
6802 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
6805 if (closesocket(sock) == SOCKET_ERROR) {
6806 errno = map_errno(WSAGetLastError());
6814rb_w32_pipe(
int fds[2])
6816 static long serial = 0;
6817 static const char prefix[] =
"\\\\.\\pipe\\ruby";
6819 width_of_prefix = (int)
sizeof(prefix) - 1,
6820 width_of_pid = (int)
sizeof(rb_pid_t) * 2,
6821 width_of_serial = (int)
sizeof(serial) * 2,
6822 width_of_ids = width_of_pid + 1 + width_of_serial + 1
6824 char name[
sizeof(prefix) + width_of_ids];
6825 SECURITY_ATTRIBUTES sec;
6826 HANDLE hRead, hWrite, h;
6827 int fdRead, fdWrite;
6830 memcpy(name, prefix, width_of_prefix);
6831 snprintf(name + width_of_prefix, width_of_ids,
"%.*"PRI_PIDT_PREFIX"x-%.*lx",
6832 width_of_pid, rb_w32_getpid(), width_of_serial, (
unsigned long)(InterlockedIncrement(&serial)-1));
6834 sec.nLength =
sizeof(sec);
6835 sec.lpSecurityDescriptor = NULL;
6836 sec.bInheritHandle = FALSE;
6839 hRead = CreateNamedPipe(name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
6840 0, 2, 65536, 65536, 0, &sec);
6842 if (hRead == INVALID_HANDLE_VALUE) {
6843 DWORD err = GetLastError();
6844 if (err == ERROR_PIPE_BUSY)
6847 errno = map_errno(GetLastError());
6852 hWrite = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, &sec,
6853 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
6855 if (hWrite == INVALID_HANDLE_VALUE) {
6856 errno = map_errno(GetLastError());
6863 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6864 fdRead = _open_osfhandle((intptr_t)h, 0);
6868 CloseHandle(hWrite);
6874 rb_acrt_lowio_lock_fh(fdRead);
6875 _set_osfhnd(fdRead, (intptr_t)hRead);
6876 _set_osflags(fdRead, FOPEN | FPIPE | FNOINHERIT);
6877 rb_acrt_lowio_unlock_fh(fdRead);
6883 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6884 fdWrite = _open_osfhandle((intptr_t)h, 0);
6886 if (fdWrite == -1) {
6888 CloseHandle(hWrite);
6892 rb_acrt_lowio_lock_fh(fdWrite);
6893 _set_osfhnd(fdWrite, (intptr_t)hWrite);
6894 _set_osflags(fdWrite, FOPEN | FPIPE | FNOINHERIT);
6895 rb_acrt_lowio_unlock_fh(fdWrite);
6898 rb_w32_close(fdRead);
6910console_emulator_p(
void)
6912 const void *
const func = WriteConsoleW;
6914 MEMORY_BASIC_INFORMATION m;
6916 memset(&m, 0,
sizeof(m));
6917 if (!VirtualQuery(func, &m,
sizeof(m))) {
6920 k = GetModuleHandle(
"kernel32.dll");
6921 if (!k)
return FALSE;
6922 return (HMODULE)m.AllocationBase != k;
6927constat_handle(HANDLE h)
6931 thread_exclusive(conlist) {
6933 if (console_emulator_p()) {
6934 conlist = conlist_disabled;
6937 conlist = st_init_numtable();
6938 install_vm_exit_handler();
6940 else if (conlist == conlist_disabled) {
6943 if (st_lookup(conlist, (st_data_t)h, &data)) {
6947 CONSOLE_SCREEN_BUFFER_INFO csbi;
6949 p->vt100.state = constat_init;
6950 p->vt100.attr = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
6951 p->vt100.reverse = 0;
6952 p->vt100.saved.X = p->vt100.saved.Y = 0;
6953 if (GetConsoleScreenBufferInfo(h, &csbi)) {
6954 p->vt100.attr = csbi.wAttributes;
6956 st_insert(conlist, (st_data_t)h, (st_data_t)p);
6962#define FOREGROUND_MASK (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY)
6963#define BACKGROUND_MASK (BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY)
6965#define constat_attr_color_reverse(attr) \
6966 ((attr) & ~(FOREGROUND_MASK | BACKGROUND_MASK)) | \
6967 (((attr) & FOREGROUND_MASK) << 4) | \
6968 (((attr) & BACKGROUND_MASK) >> 4)
6972constat_attr(
int count,
const int *seq, WORD attr, WORD default_attr,
int *reverse)
6977 if (!count)
return attr;
6978 if (rev) attr = constat_attr_color_reverse(attr);
6979 bold = attr & FOREGROUND_INTENSITY;
6980 attr &= ~(FOREGROUND_INTENSITY | BACKGROUND_INTENSITY);
6982 while (count-- > 0) {
6985 attr = default_attr;
6990 bold = FOREGROUND_INTENSITY;
6996#ifndef COMMON_LVB_UNDERSCORE
6997#define COMMON_LVB_UNDERSCORE 0x8000
6999 attr |= COMMON_LVB_UNDERSCORE;
7002 attr &= ~COMMON_LVB_UNDERSCORE;
7012 attr &= ~(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
7015 attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_GREEN)) | FOREGROUND_RED;
7018 attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_RED)) | FOREGROUND_GREEN;
7021 attr = (attr & ~FOREGROUND_BLUE) | FOREGROUND_GREEN | FOREGROUND_RED;
7024 attr = (attr & ~(FOREGROUND_GREEN | FOREGROUND_RED)) | FOREGROUND_BLUE;
7027 attr = (attr & ~FOREGROUND_GREEN) | FOREGROUND_BLUE | FOREGROUND_RED;
7030 attr = (attr & ~FOREGROUND_RED) | FOREGROUND_BLUE | FOREGROUND_GREEN;
7033 attr |= FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
7038 attr = (attr & ~FOREGROUND_MASK) | (default_attr & FOREGROUND_MASK);
7042 attr &= ~(BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED);
7045 attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_GREEN)) | BACKGROUND_RED;
7048 attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_RED)) | BACKGROUND_GREEN;
7051 attr = (attr & ~BACKGROUND_BLUE) | BACKGROUND_GREEN | BACKGROUND_RED;
7054 attr = (attr & ~(BACKGROUND_GREEN | BACKGROUND_RED)) | BACKGROUND_BLUE;
7057 attr = (attr & ~BACKGROUND_GREEN) | BACKGROUND_BLUE | BACKGROUND_RED;
7060 attr = (attr & ~BACKGROUND_RED) | BACKGROUND_BLUE | BACKGROUND_GREEN;
7063 attr |= BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED;
7068 attr = (attr & ~BACKGROUND_MASK) | (default_attr & BACKGROUND_MASK);
7073 if (rev) attr = constat_attr_color_reverse(attr);
7080constat_clear(HANDLE handle, WORD attr, DWORD
len, COORD pos)
7084 FillConsoleOutputAttribute(handle, attr,
len, pos, &written);
7085 FillConsoleOutputCharacterW(handle, L
' ',
len, pos, &written);
7090constat_apply(HANDLE handle,
struct constat *s, WCHAR w)
7092 CONSOLE_SCREEN_BUFFER_INFO csbi;
7093 const int *seq = s->vt100.seq;
7094 int count = s->vt100.state;
7098 if (!GetConsoleScreenBufferInfo(handle, &csbi))
return;
7099 arg0 = (count > 0 && seq[0] > 0);
7100 if (arg0) arg1 = seq[0];
7103 SetConsoleTextAttribute(handle, constat_attr(count, seq, csbi.wAttributes, s->vt100.attr, &s->vt100.reverse));
7106 csbi.dwCursorPosition.X = 0;
7108 csbi.dwCursorPosition.Y -= arg1;
7109 if (csbi.dwCursorPosition.Y < csbi.srWindow.Top)
7110 csbi.dwCursorPosition.Y = csbi.srWindow.Top;
7111 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7114 csbi.dwCursorPosition.X = 0;
7117 csbi.dwCursorPosition.Y += arg1;
7118 if (csbi.dwCursorPosition.Y > csbi.srWindow.Bottom)
7119 csbi.dwCursorPosition.Y = csbi.srWindow.Bottom;
7120 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7123 csbi.dwCursorPosition.X += arg1;
7124 if (csbi.dwCursorPosition.X >= csbi.srWindow.Right)
7125 csbi.dwCursorPosition.X = csbi.srWindow.Right;
7126 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7129 csbi.dwCursorPosition.X -= arg1;
7130 if (csbi.dwCursorPosition.X < csbi.srWindow.Left)
7131 csbi.dwCursorPosition.X = csbi.srWindow.Left;
7132 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7136 arg1 += csbi.srWindow.Left;
7137 if (arg1 > csbi.srWindow.Right)
7138 arg1 = csbi.srWindow.Right;
7139 csbi.dwCursorPosition.X = arg1;
7140 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7143 arg1 += csbi.srWindow.Top;
7144 if (arg1 > csbi.srWindow.Bottom)
7145 arg1 = csbi.srWindow.Bottom;
7146 csbi.dwCursorPosition.Y = arg1;
7147 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7151 pos.Y = arg1 + csbi.srWindow.Top - 1;
7152 if (pos.Y > csbi.srWindow.Bottom) pos.Y = csbi.srWindow.Bottom;
7153 if (count < 2 || (arg1 = seq[1]) <= 0) arg1 = 1;
7154 pos.X = arg1 + csbi.srWindow.Left - 1;
7155 if (pos.X > csbi.srWindow.Right) pos.X = csbi.srWindow.Right;
7156 SetConsoleCursorPosition(handle, pos);
7159 switch (arg0 ? arg1 : 0) {
7161 constat_clear(handle, csbi.wAttributes,
7162 (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.dwCursorPosition.Y + 1)
7163 - csbi.dwCursorPosition.X),
7164 csbi.dwCursorPosition);
7168 pos.Y = csbi.srWindow.Top;
7169 constat_clear(handle, csbi.wAttributes,
7170 (csbi.dwSize.X * (csbi.dwCursorPosition.Y - csbi.srWindow.Top)
7171 + csbi.dwCursorPosition.X + 1),
7176 pos.Y = csbi.srWindow.Top;
7177 constat_clear(handle, csbi.wAttributes,
7178 (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1)),
7184 constat_clear(handle, csbi.wAttributes,
7185 (csbi.dwSize.X * csbi.dwSize.Y),
7191 switch (arg0 ? arg1 : 0) {
7193 constat_clear(handle, csbi.wAttributes,
7194 (csbi.dwSize.X - csbi.dwCursorPosition.X),
7195 csbi.dwCursorPosition);
7199 pos.Y = csbi.dwCursorPosition.Y;
7200 constat_clear(handle, csbi.wAttributes,
7201 csbi.dwCursorPosition.X + 1, pos);
7205 pos.Y = csbi.dwCursorPosition.Y;
7206 constat_clear(handle, csbi.wAttributes,
7207 csbi.dwSize.X, pos);
7212 s->vt100.saved = csbi.dwCursorPosition;
7215 SetConsoleCursorPosition(handle, s->vt100.saved);
7218 if (count >= 2 && seq[0] == -1 && seq[1] == 25) {
7219 CONSOLE_CURSOR_INFO cci;
7220 GetConsoleCursorInfo(handle, &cci);
7221 cci.bVisible = TRUE;
7222 SetConsoleCursorInfo(handle, &cci);
7226 if (count >= 2 && seq[0] == -1 && seq[1] == 25) {
7227 CONSOLE_CURSOR_INFO cci;
7228 GetConsoleCursorInfo(handle, &cci);
7229 cci.bVisible = FALSE;
7230 SetConsoleCursorInfo(handle, &cci);
7238constat_parse(HANDLE h,
struct constat *s,
const WCHAR **ptrp,
long *lenp)
7240 const WCHAR *ptr = *ptrp;
7241 long rest,
len = *lenp;
7245 rest = *lenp -
len - 1;
7246 if (s->vt100.state == constat_esc) {
7249 s->vt100.state = constat_init;
7250 if (
len > 0 && *ptr != L
'[')
continue;
7251 s->vt100.state = constat_esc;
7253 else if (s->vt100.state == constat_esc) {
7256 s->vt100.state = constat_init;
7259 rest = *lenp -
len - 1;
7260 if (rest > 0) --rest;
7261 s->vt100.state = constat_seq;
7262 s->vt100.seq[0] = 0;
7264 else if (s->vt100.state >= constat_seq) {
7265 if (wc >= L
'0' && wc <= L
'9') {
7266 if (s->vt100.state < (
int)numberof(s->vt100.seq)) {
7267 int *seq = &s->vt100.seq[s->vt100.state];
7268 *seq = (*seq * 10) + (wc - L
'0');
7271 else if (s->vt100.state == constat_seq && s->vt100.seq[0] == 0 && wc == L
'?') {
7272 s->vt100.seq[s->vt100.state++] = -1;
7276 if (++s->vt100.state < (
int)numberof(s->vt100.seq)) {
7277 s->vt100.seq[s->vt100.state] = 0;
7280 s->vt100.state = (int)numberof(s->vt100.seq);
7284 constat_apply(h, s, wc);
7285 s->vt100.state = constat_init;
7308 SOCKET sock = TO_SOCKET(fd);
7309 int save_errno =
errno;
7311 if (!is_socket(sock)) {
7312 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
7313 constat_delete((HANDLE)sock);
7316 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
7317 socklist_delete(&sock, NULL);
7320 if (closesocket(sock) == SOCKET_ERROR) {
7321 errno = map_errno(WSAGetLastError());
7327#ifndef INVALID_SET_FILE_POINTER
7328#define INVALID_SET_FILE_POINTER ((DWORD)-1)
7332setup_overlapped(OVERLAPPED *ol,
int fd,
int iswrite, rb_off_t *_offset)
7334 memset(ol, 0,
sizeof(*ol));
7339 DWORD seek_method = ((_osfile(fd) & FAPPEND) && iswrite) ? FILE_END : FILE_CURRENT;
7343 uint64_t offset = *_offset;
7344 ol->Offset = (uint32_t)(offset & 0xFFFFFFFFLL);
7345 ol->OffsetHigh = (uint32_t)((offset & 0xFFFFFFFF00000000LL) >> 32);
7348 LARGE_INTEGER seek_offset = {0}, current_offset = {0};
7349 if (!SetFilePointerEx((HANDLE)_osfhnd(fd), seek_offset, ¤t_offset, seek_method)) {
7350 DWORD last_error = GetLastError();
7351 if (last_error != NO_ERROR) {
7352 errno = map_errno(last_error);
7358 *_offset = current_offset.QuadPart;
7360 else if (!(_osfile(fd) & (FDEV | FPIPE))) {
7362 DWORD low = SetFilePointer((HANDLE)_osfhnd(fd), 0, &high, seek_method);
7364 if (low == INVALID_SET_FILE_POINTER) {
7365 DWORD err = GetLastError();
7366 if (err != NO_ERROR) {
7367 errno = map_errno(err);
7373 ol->OffsetHigh = high;
7376 ol->hEvent = CreateEvent(NULL, TRUE, TRUE, NULL);
7378 errno = map_errno(GetLastError());
7385finish_overlapped(OVERLAPPED *ol,
int fd, DWORD size, rb_off_t *_offset)
7387 CloseHandle(ol->hEvent);
7391 DWORD seek_method = (_osfile(fd) & FAPPEND) ? FILE_END : FILE_BEGIN;
7393 LARGE_INTEGER seek_offset = {0};
7394 if (seek_method == FILE_BEGIN) {
7395 seek_offset.QuadPart = *_offset;
7398 SetFilePointerEx((HANDLE)_osfhnd(fd), seek_offset, NULL, seek_method);
7400 else if (!(_osfile(fd) & (FDEV | FPIPE))) {
7401 LONG high = ol->OffsetHigh;
7402 DWORD low = ol->Offset + size;
7403 if (low < ol->Offset)
7405 SetFilePointer((HANDLE)_osfhnd(fd), low, &high, FILE_BEGIN);
7412rb_w32_read_internal(
int fd,
void *buf,
size_t size, rb_off_t *offset)
7414 SOCKET sock = TO_SOCKET(fd);
7423 if (size > INT_MAX) size = INT_MAX;
7425 if (is_socket(sock))
7426 return rb_w32_recv(fd, buf, size, 0);
7429 if (_get_osfhandle(fd) == -1) {
7433 if (!offset && _osfile(fd) & FTEXT) {
7434 return _read(fd, buf, size);
7437 rb_acrt_lowio_lock_fh(fd);
7439 if (!size || _osfile(fd) & FEOFLAG) {
7440 _set_osflags(fd, _osfile(fd) & ~FEOFLAG);
7441 rb_acrt_lowio_unlock_fh(fd);
7450 if (setup_overlapped(&ol, fd, FALSE, offset)) {
7451 rb_acrt_lowio_unlock_fh(fd);
7455 if (!ReadFile((HANDLE)_osfhnd(fd), buf,
len, &read, &ol)) {
7456 err = GetLastError();
7457 if (err == ERROR_NO_DATA && (_osfile(fd) & FPIPE)) {
7459 CloseHandle(ol.hEvent);
7460 if (GetNamedPipeHandleState((HANDLE)_osfhnd(fd), &state, NULL, NULL, NULL, NULL, 0) && (state & PIPE_NOWAIT)) {
7461 errno = EWOULDBLOCK;
7464 errno = map_errno(err);
7466 rb_acrt_lowio_unlock_fh(fd);
7469 else if (err != ERROR_IO_PENDING) {
7470 CloseHandle(ol.hEvent);
7471 if (err == ERROR_ACCESS_DENIED)
7473 else if (err == ERROR_BROKEN_PIPE || err == ERROR_HANDLE_EOF) {
7474 rb_acrt_lowio_unlock_fh(fd);
7478 errno = map_errno(err);
7480 rb_acrt_lowio_unlock_fh(fd);
7484 wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE);
7485 if (wait != WAIT_OBJECT_0) {
7486 if (wait == WAIT_OBJECT_0 + 1)
7489 errno = map_errno(GetLastError());
7490 CancelIo((HANDLE)_osfhnd(fd));
7493 GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &read, TRUE);
7495 CloseHandle(ol.hEvent);
7496 rb_acrt_lowio_unlock_fh(fd);
7500 else if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &read, TRUE) &&
7501 (err = GetLastError()) != ERROR_HANDLE_EOF) {
7503 if (err != ERROR_BROKEN_PIPE) {
7504 errno = map_errno(err);
7507 CloseHandle(ol.hEvent);
7508 CancelIo((HANDLE)_osfhnd(fd));
7509 rb_acrt_lowio_unlock_fh(fd);
7514 err = GetLastError();
7515 errno = map_errno(err);
7518 finish_overlapped(&ol, fd, read, offset);
7522 buf = (
char *)buf + read;
7523 if (err != ERROR_OPERATION_ABORTED && size > 0)
7527 _set_osflags(fd, _osfile(fd) | FEOFLAG);
7530 rb_acrt_lowio_unlock_fh(fd);
7538rb_w32_write_internal(
int fd,
const void *buf,
size_t size, rb_off_t *offset)
7540 SOCKET sock = TO_SOCKET(fd);
7549 if (size > INT_MAX) size = INT_MAX;
7551 if (is_socket(sock))
7552 return rb_w32_send(fd, buf, size, 0);
7555 if (_get_osfhandle(fd) == -1) {
7560 if (!offset && (_osfile(fd) & FTEXT) &&
7561 (!(_osfile(fd) & FPIPE) || fd == fileno(stdout) || fd == fileno(stderr))) {
7562 ssize_t w = _write(fd, buf, size);
7563 if (w == (ssize_t)-1 &&
errno == EINVAL) {
7564 errno = map_errno(GetLastError());
7569 rb_acrt_lowio_lock_fh(fd);
7571 if (!size || _osfile(fd) & FEOFLAG) {
7572 rb_acrt_lowio_unlock_fh(fd);
7583 if (setup_overlapped(&ol, fd, TRUE, offset)) {
7584 rb_acrt_lowio_unlock_fh(fd);
7588 if (!WriteFile((HANDLE)_osfhnd(fd), buf,
len, &written, &ol)) {
7589 err = GetLastError();
7590 if (err != ERROR_IO_PENDING) {
7591 CloseHandle(ol.hEvent);
7592 if (err == ERROR_ACCESS_DENIED)
7595 errno = map_errno(err);
7597 rb_acrt_lowio_unlock_fh(fd);
7601 wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE);
7602 if (wait != WAIT_OBJECT_0) {
7603 if (wait == WAIT_OBJECT_0 + 1)
7606 errno = map_errno(GetLastError());
7607 CancelIo((HANDLE)_osfhnd(fd));
7608 GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &written, TRUE);
7610 CloseHandle(ol.hEvent);
7611 rb_acrt_lowio_unlock_fh(fd);
7615 else if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &written, TRUE)) {
7616 errno = map_errno(GetLastError());
7617 CloseHandle(ol.hEvent);
7618 CancelIo((HANDLE)_osfhnd(fd));
7619 rb_acrt_lowio_unlock_fh(fd);
7624 finish_overlapped(&ol, fd, written, offset);
7627 if (written ==
len) {
7628 buf = (
const char *)buf +
len;
7633 size_t newlen =
len / 2;
7635 size +=
len - newlen;
7640 errno = EWOULDBLOCK;
7643 rb_acrt_lowio_unlock_fh(fd);
7649rb_w32_read(
int fd,
void *buf,
size_t size)
7651 return rb_w32_read_internal(fd, buf, size, NULL);
7655rb_w32_write(
int fd,
const void *buf,
size_t size)
7657 return rb_w32_write_internal(fd, buf, size, NULL);
7661rb_w32_pread(
int descriptor,
void *base,
size_t size, rb_off_t offset)
7663 return rb_w32_read_internal(descriptor, base, size, &offset);
7667rb_w32_pwrite(
int descriptor,
const void *base,
size_t size, rb_off_t offset)
7669 return rb_w32_write_internal(descriptor, base, size, &offset);
7674rb_w32_write_console(uintptr_t strarg,
int fd)
7677 DWORD dwMode, reslen;
7681 const WCHAR *ptr, *next;
7685 handle = (HANDLE)_osfhnd(fd);
7686 if (!GetConsoleMode(handle, &dwMode))
7689 s = constat_handle(handle);
7699 case ENCINDEX_US_ASCII:
7700 case ENCINDEX_ASCII_8BIT:
7702 case ENCINDEX_UTF_8:
7704 if (RSTRING_LEN(str) > INT_MAX)
return -1L;
7705 ptr = wbuffer = mbstr_to_wstr(CP_UTF8, RSTRING_PTR(str), (
int)RSTRING_LEN(str), &
len);
7706 if (!ptr)
return -1L;
7708 case ENCINDEX_UTF_16LE:
7709 if (RSTRING_LEN(str) > INT_MAX)
return -1L;
7710 ptr = (
const WCHAR *)RSTRING_PTR(str);
7711 len = RSTRING_LEN(str) /
sizeof(WCHAR);
7715 if (dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) {
7716 if (!WriteConsoleW(handle, ptr,
len, &reslen, NULL))
7717 reslen = (DWORD)-1L;
7721 long curlen = constat_parse(handle, s, (next = ptr, &next), &
len);
7722 reslen += next - ptr;
7725 if (!WriteConsoleW(handle, ptr, curlen, &written, NULL)) {
7726 reslen = (DWORD)-1L;
7735 return (
long)reslen;
7740timespec_to_filetime(
const struct timespec *ts, FILETIME *ft)
7744 tmp.QuadPart = unix_to_filetime((ULONGLONG)ts->tv_sec);
7745 tmp.QuadPart += ts->tv_nsec / 100;
7746 ft->dwLowDateTime = tmp.LowPart;
7747 ft->dwHighDateTime = tmp.HighPart;
7753wutimensat(
int dirfd,
const WCHAR *path,
const struct timespec *times,
int flags)
7756 FILETIME atime, mtime;
7757 struct stati128 stat;
7761 if (dirfd != AT_FDCWD) {
7771 if (wstati128(path, &stat, FALSE)) {
7776 if (timespec_to_filetime(×[0], &atime)) {
7779 if (timespec_to_filetime(×[1], &mtime)) {
7784 GetSystemTimePreciseAsFileTime(&atime);
7789 const DWORD attr = GetFileAttributesW(path);
7790 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY))
7791 SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY);
7792 hFile = open_special(path, GENERIC_WRITE, 0);
7793 if (hFile == INVALID_HANDLE_VALUE) {
7794 errno = map_errno(GetLastError());
7798 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
7799 errno = map_errno(GetLastError());
7804 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY))
7805 SetFileAttributesW(path, attr);
7813w32_utimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags, UINT cp)
7815 WCHAR *wpath = mbstr_to_wstr(cp, path, -1, NULL);
7819 ret = wutimensat(dirfd, wpath, times, flags);
7827rb_w32_uutime(
const char *path,
const struct utimbuf *times)
7831 ts[0].tv_sec = times->actime;
7833 ts[1].tv_sec = times->modtime;
7835 return w32_utimensat(AT_FDCWD, path, ts, 0, CP_UTF8);
7840rb_w32_utime(
const char *path,
const struct utimbuf *times)
7844 ts[0].tv_sec = times->actime;
7846 ts[1].tv_sec = times->modtime;
7848 return w32_utimensat(AT_FDCWD, path, ts, 0, filecp());
7853rb_w32_uutimes(
const char *path,
const struct timeval *times)
7857 ts[0].tv_sec = times[0].tv_sec;
7858 ts[0].tv_nsec = times[0].tv_usec * 1000;
7859 ts[1].tv_sec = times[1].tv_sec;
7860 ts[1].tv_nsec = times[1].tv_usec * 1000;
7861 return w32_utimensat(AT_FDCWD, path, ts, 0, CP_UTF8);
7866rb_w32_utimes(
const char *path,
const struct timeval *times)
7870 ts[0].tv_sec = times[0].tv_sec;
7871 ts[0].tv_nsec = times[0].tv_usec * 1000;
7872 ts[1].tv_sec = times[1].tv_sec;
7873 ts[1].tv_nsec = times[1].tv_usec * 1000;
7874 return w32_utimensat(AT_FDCWD, path, ts, 0, filecp());
7879rb_w32_uutimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags)
7881 return w32_utimensat(dirfd, path, times, flags, CP_UTF8);
7886rb_w32_utimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags)
7888 return w32_utimensat(dirfd, path, times, flags, filecp());
7893rb_w32_uchdir(
const char *path)
7898 if (!(wpath = utf8_to_wstr(path, NULL)))
7900 ret = _wchdir(wpath);
7907wmkdir(
const WCHAR *wpath,
int mode)
7912 if (CreateDirectoryW(wpath, NULL) == FALSE) {
7913 errno = map_errno(GetLastError());
7916 if (_wchmod(wpath, mode) == -1) {
7917 RemoveDirectoryW(wpath);
7927rb_w32_umkdir(
const char *path,
int mode)
7932 if (!(wpath = utf8_to_wstr(path, NULL)))
7934 ret = wmkdir(wpath, mode);
7941rb_w32_mkdir(
const char *path,
int mode)
7946 if (!(wpath = filecp_to_wstr(path, NULL)))
7948 ret = wmkdir(wpath, mode);
7955wrmdir(
const WCHAR *wpath)
7959 const DWORD attr = GetFileAttributesW(wpath);
7960 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7961 SetFileAttributesW(wpath, attr & ~FILE_ATTRIBUTE_READONLY);
7963 if (RemoveDirectoryW(wpath) == FALSE) {
7964 errno = map_errno(GetLastError());
7966 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7967 SetFileAttributesW(wpath, attr);
7976rb_w32_rmdir(
const char *path)
7981 if (!(wpath = filecp_to_wstr(path, NULL)))
7983 ret = wrmdir(wpath);
7990rb_w32_urmdir(
const char *path)
7995 if (!(wpath = utf8_to_wstr(path, NULL)))
7997 ret = wrmdir(wpath);
8004wunlink(
const WCHAR *path)
8007 const DWORD SYMLINKD = FILE_ATTRIBUTE_REPARSE_POINT|FILE_ATTRIBUTE_DIRECTORY;
8009 const DWORD attr = GetFileAttributesW(path);
8010 if (attr == (DWORD)-1) {
8012 else if ((attr & SYMLINKD) == SYMLINKD) {
8013 ret = RemoveDirectoryW(path);
8016 if (attr & FILE_ATTRIBUTE_READONLY) {
8017 SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY);
8019 ret = DeleteFileW(path);
8022 errno = map_errno(GetLastError());
8024 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
8025 SetFileAttributesW(path, attr);
8034rb_w32_uunlink(
const char *path)
8039 if (!(wpath = utf8_to_wstr(path, NULL)))
8041 ret = wunlink(wpath);
8048rb_w32_unlink(
const char *path)
8053 if (!(wpath = filecp_to_wstr(path, NULL)))
8055 ret = wunlink(wpath);
8062rb_w32_uchmod(
const char *path,
int mode)
8067 if (!(wpath = utf8_to_wstr(path, NULL)))
8069 ret = _wchmod(wpath, mode);
8076fchmod(
int fd,
int mode)
8080 LARGE_INTEGER CreationTime;
8081 LARGE_INTEGER LastAccessTime;
8082 LARGE_INTEGER LastWriteTime;
8083 LARGE_INTEGER ChangeTime;
8084 DWORD FileAttributes;
8085 } info = {{{0}}, {{0}}, {{0}},};
8086 HANDLE h = (HANDLE)_get_osfhandle(fd);
8088 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
8089 if (!(mode & 0200)) info.FileAttributes |= FILE_ATTRIBUTE_READONLY;
8090 if (!SetFileInformationByHandle(h, 0, &info,
sizeof(info))) {
8091 errno = map_errno(GetLastError());
8099rb_w32_isatty(
int fd)
8104 if (_get_osfhandle(fd) == -1) {
8107 if (!GetConsoleMode((HANDLE)_osfhnd(fd), &mode)) {
8119 int *ip = (
int *)(&x + 1) - 1;
8126rb_w32_inet_ntop(
int af,
const void *addr,
char *numaddr,
size_t numaddr_len)
8128 return (inet_ntop)(af, (
void *)addr, numaddr, numaddr_len);
8133rb_w32_inet_pton(
int af,
const char *src,
void *dst)
8135 return (inet_pton)(af, src, dst);
8140rb_w32_fd_is_text(
int fd)
8142 return _osfile(fd) & FTEXT;
8145#ifdef HAVE__GMTIME64_S
8146# ifndef HAVE__LOCALTIME64_S
8148# define HAVE__LOCALTIME64_S 1
8150# ifndef MINGW_HAS_SECURE_API
8151 _CRTIMP errno_t __cdecl _gmtime64_s(
struct tm* tm,
const __time64_t *time);
8152 _CRTIMP errno_t __cdecl _localtime64_s(
struct tm* tm,
const __time64_t *time);
8154# define gmtime_s _gmtime64_s
8155# define localtime_s _localtime64_s
8160gmtime_r(
const time_t *tp,
struct tm *rp)
8168 e = gmtime_s(rp, tp);
8169 if (e != 0)
goto error;
8175localtime_r(
const time_t *tp,
struct tm *rp)
8183 e = localtime_s(rp, tp);
8190rb_w32_wrap_io_handle(HANDLE h,
int flags)
8193 int len =
sizeof(tmp);
8194 int r = getsockopt((SOCKET)h, SOL_SOCKET, SO_DEBUG, (
char *)&tmp, &
len);
8195 if (r != SOCKET_ERROR || WSAGetLastError() != WSAENOTSOCK) {
8197 if (flags & O_NONBLOCK) {
8198 flags &= ~O_NONBLOCK;
8201 socklist_insert((SOCKET)h, f);
8203 else if (flags & O_NONBLOCK) {
8207 return rb_w32_open_osfhandle((intptr_t)h, flags);
8212rb_w32_unwrap_io_handle(
int fd)
8214 SOCKET sock = TO_SOCKET(fd);
8215 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
8216 if (!is_socket(sock)) {
8217 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
8218 constat_delete((HANDLE)sock);
8221 socklist_delete(&sock, NULL);
8226#if !defined(__MINGW64__) && defined(__MINGW64_VERSION_MAJOR)
8232rb_w32_pow(
double x,
double y)
8236 unsigned int default_control = _controlfp(0, 0);
8237 _controlfp(_PC_64, _MCW_PC);
8240 _controlfp(default_control, _MCW_PC);
8248 BY_HANDLE_FILE_INFORMATION bhfi;
8259 tmp = rb_check_convert_type_with_id(*file,
T_FILE,
"IO", idTo_io);
8262 if (f == (HANDLE)-1)
return INVALID_HANDLE_VALUE;
8271 tmp = rb_str_encode_ospath(*file);
8272 len = MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, NULL, 0);
8274 MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, ptr,
len);
8275 f = CreateFileW(ptr, 0,
8276 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
8277 FILE_FLAG_BACKUP_SEMANTICS, NULL);
8279 if (f == INVALID_HANDLE_VALUE)
return f;
8282 if (GetFileType(f) == FILE_TYPE_DISK) {
8283 ZeroMemory(st,
sizeof(*st));
8284 if (get_ino(f, &st->info.fii)) {
8285 st->file_id_p = TRUE;
8288 else if (GetLastError() != ERROR_INVALID_PARAMETER) {
8290 return INVALID_HANDLE_VALUE;
8294 if (GetFileInformationByHandle(f, &st->info.bhfi)) {
8295 st->file_id_p = FALSE;
8299 if (ret) CloseHandle(ret);
8300 return INVALID_HANDLE_VALUE;
8304close_handle(
VALUE h)
8306 CloseHandle((HANDLE)h);
8316call_w32_io_info(
VALUE arg)
8319 return (
VALUE)w32_io_info(p->fname, p->st);
8323rb_w32_file_identical_p(
VALUE fname1,
VALUE fname2)
8326 HANDLE f1 = 0, f2 = 0;
8328 f1 = w32_io_info(&fname1, &st1);
8329 if (f1 == INVALID_HANDLE_VALUE)
return Qfalse;
8332 arg.fname = &fname2;
8337 f2 = w32_io_info(&fname2, &st2);
8339 if (f2 == INVALID_HANDLE_VALUE)
return Qfalse;
8340 if (f2) CloseHandle(f2);
8342 if (st1.file_id_p != st2.file_id_p)
return Qfalse;
8343 if (!st1.file_id_p) {
8344 if (st1.info.bhfi.dwVolumeSerialNumber == st2.info.bhfi.dwVolumeSerialNumber &&
8345 st1.info.bhfi.nFileIndexHigh == st2.info.bhfi.nFileIndexHigh &&
8346 st1.info.bhfi.nFileIndexLow == st2.info.bhfi.nFileIndexLow)
8350 if (st1.info.fii.VolumeSerialNumber == st2.info.fii.VolumeSerialNumber &&
8351 memcmp(&st1.info.fii.FileId, &st2.info.fii.FileId,
sizeof(
FILE_ID_128)) == 0)
8358rb_w32_set_thread_description(HANDLE th,
const WCHAR *name)
8361 typedef HRESULT (WINAPI *set_thread_description_func)(HANDLE, PCWSTR);
8362 static set_thread_description_func set_thread_description =
8363 (set_thread_description_func)-1;
8364 if (set_thread_description == (set_thread_description_func)-1) {
8366 set_thread_description = (set_thread_description_func)
8367 get_proc_address(
"kernel32",
"SetThreadDescription", NULL);
8369 if (set_thread_description) {
8370 result = set_thread_description(th, name);
8376rb_w32_set_thread_description_str(HANDLE th,
VALUE name)
8378 int idx, result = FALSE;
8382 return rb_w32_set_thread_description(th, L
"");
8385 idx = rb_enc_get_index(name);
8386 if (idx == ENCINDEX_UTF_16LE) {
8387 result = rb_w32_set_thread_description(th, s);
8391 s = mbstr_to_wstr(CP_UTF8, RSTRING_PTR(name), RSTRING_LEN(name)+1, NULL);
8392 result = rb_w32_set_thread_description(th, s);
8402rb_w32_mmap(
void *addr,
size_t len,
int prot,
int flags,
int fd, rb_off_t offset)
8406 DWORD protect = PAGE_EXECUTE_READWRITE;
8408 if (fd > 0 || offset) {
8423 ptr = VirtualAlloc(addr,
len, MEM_RESERVE | MEM_COMMIT, protect);
8425 errno = rb_w32_map_errno(GetLastError());
8433rb_w32_munmap(
void *addr,
size_t len)
8435 if (!VirtualFree(addr, 0, MEM_RELEASE)) {
8436 errno = rb_w32_map_errno(GetLastError());
8444rb_w32_mprotect(
void *addr,
size_t len,
int prot)
8460 if (prot & PROT_EXEC) {
8461 if (!FlushInstructionCache(GetCurrentProcess(), addr,
len)) {
8462 errno = rb_w32_map_errno(GetLastError());
#define ISSPACE
@old{rb_isspace}
#define ISALPHA
@old{rb_isalpha}
#define ISALNUM
@old{rb_isalnum}
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 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 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 ALLOCV_END
Old name of RB_ALLOCV_END.
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
#define RBIMPL_ATTR_NONNULL(list)
Wraps (or simulates) __attribute__((nonnull)).
rb_encoding * rb_utf8_encoding(void)
Queries the encoding that represents UTF-8.
rb_encoding * rb_filesystem_encoding(void)
Queries the "filesystem" encoding.
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, rb_len_t len)
Identical to rb_write_error(), except it additionally takes the message's length.
VALUE rb_str_cat(VALUE dst, const char *src, rb_len_t 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.
struct rb_vm_struct ruby_vm_t
The opaque struct to hold VM internals.
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.
int st_foreach(st_table *q, int_type *w, st_data_t e)
Iteration over the given table.
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.
C99 shim for <stdbool.h>.
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.