59#include "ruby/win32.h"
62#include "win32/file.h"
65#include "internal/enc.h"
66#include "internal/object.h"
67#include "internal/static_assert.h"
70#define isdirsep(x) ((x) == '/' || (x) == '\\')
72static int w32_wopen(
const WCHAR *file,
int oflag,
int perm);
73static int w32_stati128(
const char *path,
struct stati128 *st, UINT cp, BOOL lstat);
74static char *w32_getenv(
const char *name, UINT cp);
80#define DLN_FIND_EXTRA_ARG_DECL ,UINT cp
81#define DLN_FIND_EXTRA_ARG ,cp
82#define rb_w32_stati128(path, st) w32_stati128(path, st, cp, FALSE)
83#define getenv(name) w32_getenv(name, cp)
84#define DLN_CHAR_NEXT(p) CharNextExA(cp, (p), 0)
85#define dln_find_exe_r rb_w32_udln_find_exe_r
86#define dln_find_file_r rb_w32_udln_find_file_r
93#define dln_find_exe_r(fname, path, buf, size) rb_w32_udln_find_exe_r(fname, path, buf, size, cp)
94#define dln_find_file_r(fname, path, buf, size) rb_w32_udln_find_file_r(fname, path, buf, size, cp)
100# define PATH_MAX MAX_PATH
101# elif defined HAVE_SYS_PARAM_H
102# include <sys/param.h>
103# define PATH_MAX MAXPATHLEN
115#define _filbuf _fgetc_nolock
116#define _flsbuf _fputc_nolock
117#define enough_to_get(n) (--(n) >= 0)
118#define enough_to_put(n) (--(n) >= 0)
121#define Debug(something) something
123#define Debug(something)
126#define TO_SOCKET(x) _get_osfhandle(x)
128int rb_w32_reparse_symlink_p(
const WCHAR *path);
130static int has_redirection(
const char *, UINT);
131int rb_w32_wait_events(HANDLE *events,
int num, DWORD timeout);
132static int rb_w32_open_osfhandle(intptr_t osfhandle,
int flags);
133static int wstati128(
const WCHAR *path,
struct stati128 *st, BOOL lstat);
136static FARPROC get_proc_address(
const char *module,
const char *func, HANDLE *mh);
138#define RUBY_CRITICAL if (0) {} else
145 { ERROR_INVALID_FUNCTION, EINVAL },
146 { ERROR_FILE_NOT_FOUND, ENOENT },
147 { ERROR_PATH_NOT_FOUND, ENOENT },
148 { ERROR_TOO_MANY_OPEN_FILES, EMFILE },
149 { ERROR_ACCESS_DENIED, EACCES },
150 { ERROR_INVALID_HANDLE, EBADF },
151 { ERROR_ARENA_TRASHED, ENOMEM },
152 { ERROR_NOT_ENOUGH_MEMORY, ENOMEM },
153 { ERROR_INVALID_BLOCK, ENOMEM },
154 { ERROR_BAD_ENVIRONMENT, E2BIG },
155 { ERROR_BAD_FORMAT, ENOEXEC },
156 { ERROR_INVALID_ACCESS, EINVAL },
157 { ERROR_INVALID_DATA, EINVAL },
158 { ERROR_INVALID_DRIVE, ENOENT },
159 { ERROR_CURRENT_DIRECTORY, EACCES },
160 { ERROR_NOT_SAME_DEVICE, EXDEV },
161 { ERROR_NO_MORE_FILES, ENOENT },
162 { ERROR_WRITE_PROTECT, EROFS },
163 { ERROR_BAD_UNIT, ENODEV },
164 { ERROR_NOT_READY, ENXIO },
165 { ERROR_BAD_COMMAND, EACCES },
166 { ERROR_CRC, EACCES },
167 { ERROR_BAD_LENGTH, EACCES },
169 { ERROR_NOT_DOS_DISK, EACCES },
170 { ERROR_SECTOR_NOT_FOUND, EACCES },
171 { ERROR_OUT_OF_PAPER, EACCES },
172 { ERROR_WRITE_FAULT, EIO },
173 { ERROR_READ_FAULT, EIO },
174 { ERROR_GEN_FAILURE, EACCES },
175 { ERROR_LOCK_VIOLATION, EACCES },
176 { ERROR_SHARING_VIOLATION, EACCES },
177 { ERROR_WRONG_DISK, EACCES },
178 { ERROR_SHARING_BUFFER_EXCEEDED, EACCES },
179 { ERROR_BAD_NETPATH, ENOENT },
180 { ERROR_NETWORK_ACCESS_DENIED, EACCES },
181 { ERROR_BAD_NET_NAME, ENOENT },
182 { ERROR_FILE_EXISTS, EEXIST },
183 { ERROR_CANNOT_MAKE, EACCES },
184 { ERROR_FAIL_I24, EACCES },
185 { ERROR_INVALID_PARAMETER, EINVAL },
186 { ERROR_NO_PROC_SLOTS, EAGAIN },
187 { ERROR_DRIVE_LOCKED, EACCES },
188 { ERROR_BROKEN_PIPE, EPIPE },
189 { ERROR_DISK_FULL, ENOSPC },
190 { ERROR_INVALID_TARGET_HANDLE, EBADF },
191 { ERROR_INVALID_HANDLE, EINVAL },
192 { ERROR_WAIT_NO_CHILDREN, ECHILD },
193 { ERROR_CHILD_NOT_COMPLETE, ECHILD },
194 { ERROR_DIRECT_ACCESS_HANDLE, EBADF },
195 { ERROR_NEGATIVE_SEEK, EINVAL },
196 { ERROR_SEEK_ON_DEVICE, EACCES },
197 { ERROR_DIR_NOT_EMPTY, ENOTEMPTY },
198 { ERROR_DIRECTORY, ENOTDIR },
199 { ERROR_NOT_LOCKED, EACCES },
200 { ERROR_BAD_PATHNAME, ENOENT },
201 { ERROR_MAX_THRDS_REACHED, EAGAIN },
202 { ERROR_LOCK_FAILED, EACCES },
203 { ERROR_ALREADY_EXISTS, EEXIST },
204 { ERROR_INVALID_STARTING_CODESEG, ENOEXEC },
205 { ERROR_INVALID_STACKSEG, ENOEXEC },
206 { ERROR_INVALID_MODULETYPE, ENOEXEC },
207 { ERROR_INVALID_EXE_SIGNATURE, ENOEXEC },
208 { ERROR_EXE_MARKED_INVALID, ENOEXEC },
209 { ERROR_BAD_EXE_FORMAT, ENOEXEC },
210 { ERROR_ITERATED_DATA_EXCEEDS_64k,ENOEXEC },
211 { ERROR_INVALID_MINALLOCSIZE, ENOEXEC },
212 { ERROR_DYNLINK_FROM_INVALID_RING,ENOEXEC },
213 { ERROR_IOPL_NOT_ENABLED, ENOEXEC },
214 { ERROR_INVALID_SEGDPL, ENOEXEC },
215 { ERROR_AUTODATASEG_EXCEEDS_64k, ENOEXEC },
216 { ERROR_RING2SEG_MUST_BE_MOVABLE, ENOEXEC },
217 { ERROR_RELOC_CHAIN_XEEDS_SEGLIM, ENOEXEC },
218 { ERROR_INFLOOP_IN_RELOC_CHAIN, ENOEXEC },
219 { ERROR_FILENAME_EXCED_RANGE, ENOENT },
220 { ERROR_NESTING_NOT_ALLOWED, EAGAIN },
221#ifndef ERROR_PIPE_LOCAL
222#define ERROR_PIPE_LOCAL 229L
224 { ERROR_PIPE_LOCAL, EPIPE },
225 { ERROR_BAD_PIPE, EPIPE },
226 { ERROR_PIPE_BUSY, EAGAIN },
227 { ERROR_NO_DATA, EPIPE },
228 { ERROR_PIPE_NOT_CONNECTED, EPIPE },
229 { ERROR_OPERATION_ABORTED, EINTR },
230 { ERROR_NOT_ENOUGH_QUOTA, ENOMEM },
231 { ERROR_MOD_NOT_FOUND, ENOENT },
232 { ERROR_PRIVILEGE_NOT_HELD, EACCES, },
233 { ERROR_CANT_RESOLVE_FILENAME, ELOOP, },
236 { WSAEACCES, EACCES },
237 { WSAEFAULT, EFAULT },
238 { WSAEINVAL, EINVAL },
239 { WSAEMFILE, EMFILE },
240 { WSAEWOULDBLOCK, EWOULDBLOCK },
241 { WSAEINPROGRESS, EINPROGRESS },
242 { WSAEALREADY, EALREADY },
243 { WSAENOTSOCK, ENOTSOCK },
244 { WSAEDESTADDRREQ, EDESTADDRREQ },
245 { WSAEMSGSIZE, EMSGSIZE },
246 { WSAEPROTOTYPE, EPROTOTYPE },
247 { WSAENOPROTOOPT, ENOPROTOOPT },
248 { WSAEPROTONOSUPPORT, EPROTONOSUPPORT },
249 { WSAESOCKTNOSUPPORT, ESOCKTNOSUPPORT },
250 { WSAEOPNOTSUPP, EOPNOTSUPP },
251 { WSAEPFNOSUPPORT, EPFNOSUPPORT },
252 { WSAEAFNOSUPPORT, EAFNOSUPPORT },
253 { WSAEADDRINUSE, EADDRINUSE },
254 { WSAEADDRNOTAVAIL, EADDRNOTAVAIL },
255 { WSAENETDOWN, ENETDOWN },
256 { WSAENETUNREACH, ENETUNREACH },
257 { WSAENETRESET, ENETRESET },
258 { WSAECONNABORTED, ECONNABORTED },
259 { WSAECONNRESET, ECONNRESET },
260 { WSAENOBUFS, ENOBUFS },
261 { WSAEISCONN, EISCONN },
262 { WSAENOTCONN, ENOTCONN },
263 { WSAESHUTDOWN, ESHUTDOWN },
264 { WSAETOOMANYREFS, ETOOMANYREFS },
265 { WSAETIMEDOUT, ETIMEDOUT },
266 { WSAECONNREFUSED, ECONNREFUSED },
268 { WSAENAMETOOLONG, ENAMETOOLONG },
269 { WSAEHOSTDOWN, EHOSTDOWN },
270 { WSAEHOSTUNREACH, EHOSTUNREACH },
271 { WSAEPROCLIM, EPROCLIM },
272 { WSAENOTEMPTY, ENOTEMPTY },
273 { WSAEUSERS, EUSERS },
274 { WSAEDQUOT, EDQUOT },
275 { WSAESTALE, ESTALE },
276 { WSAEREMOTE, EREMOTE },
281rb_w32_map_errno(DWORD winerr)
289 for (i = 0; i < (int)(
sizeof(errmap) /
sizeof(*errmap)); i++) {
290 if (errmap[i].winerr == winerr) {
291 return errmap[i].err;
295 if (winerr >= WSABASEERR) {
301#define map_errno rb_w32_map_errno
303static const char *NTLoginName;
305static OSVERSIONINFO osver;
311 memset(&osver, 0,
sizeof(OSVERSIONINFO));
312 osver.dwOSVersionInfoSize =
sizeof(OSVERSIONINFO);
313 GetVersionEx(&osver);
320 return osver.dwMajorVersion;
331 DWORD err = GetLastError(); \
332 if (err == ERROR_LOCK_VIOLATION || err == ERROR_IO_PENDING) \
333 errno = EWOULDBLOCK; \
334 else if (err == ERROR_NOT_LOCKED) \
337 errno = map_errno(err); \
340#define LK_LEN ULONG_MAX
344flock_winnt(uintptr_t self,
int argc, uintptr_t* argv)
348 const HANDLE fh = (HANDLE)self;
349 const int oper = argc;
351 memset(&o, 0,
sizeof(o));
355 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, LK_LEN, &o), i);
358 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, LK_LEN, &o), i);
360 case LOCK_SH|LOCK_NB:
361 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, LK_LEN, &o), i);
363 case LOCK_EX|LOCK_NB:
364 LK_ERR(LockFileEx(fh,
365 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
366 0, LK_LEN, LK_LEN, &o), i);
369 case LOCK_UN|LOCK_NB:
370 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, LK_LEN, &o), i);
383flock(
int fd,
int oper)
385 const asynchronous_func_t locker = flock_winnt;
387 return rb_w32_asynchronize(locker,
388 (
VALUE)_get_osfhandle(fd), oper, NULL,
394translate_wchar(WCHAR *p,
int from,
int to)
405translate_char(
char *p,
int from,
int to, UINT cp)
408 if ((
unsigned char)*p == from)
410 p = CharNextExA(cp, p, 0);
415#ifndef CSIDL_LOCAL_APPDATA
416#define CSIDL_LOCAL_APPDATA 28
418#ifndef CSIDL_COMMON_APPDATA
419#define CSIDL_COMMON_APPDATA 35
422#define CSIDL_WINDOWS 36
425#define CSIDL_SYSTEM 37
428#define CSIDL_PROFILE 40
433get_special_folder(
int n, WCHAR *buf,
size_t len)
439 if (SHGetSpecialFolderLocation(NULL, n, &pidl) == 0) {
440 f = SHGetPathFromIDListEx(pidl, buf,
len, 0);
442 alloc->lpVtbl->Free(alloc, pidl);
443 alloc->lpVtbl->Release(alloc);
450regulate_path(WCHAR *path)
452 WCHAR *p = translate_wchar(path, L
'\\', L
'/');
453 if (p - path == 2 && path[1] == L
':') {
461get_proc_address(
const char *module,
const char *func, HANDLE *mh)
467 h = LoadLibrary(module);
469 h = GetModuleHandle(module);
473 ptr = GetProcAddress(h, func);
485rb_w32_special_folder(
int type)
487 WCHAR path[PATH_MAX];
489 if (!get_special_folder(
type, path, numberof(path)))
return Qnil;
491 return rb_w32_conv_from_wchar(path, rb_filesystem_encoding());
496rb_w32_system_tmpdir(WCHAR *path, UINT
len)
498 static const WCHAR temp[] = L
"temp";
501 if (!get_special_folder(CSIDL_LOCAL_APPDATA, path,
len)) {
502 if (GetSystemWindowsDirectoryW(path,
len))
return 0;
504 p = translate_wchar(path, L
'\\', L
'/');
505 if (p == 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;
615rtc_error_handler(
int e, const
char *src,
int line, const
char *exe, const
char *fmt, ...)
620 if (!ruby_w32_rtc_error)
return 0;
621 str = rb_sprintf(
"%s:%d: ", src, line);
623 rb_str_vcatf(str, fmt, ap);
631static CRITICAL_SECTION select_mutex;
633static CRITICAL_SECTION socklist_mutex;
636static CRITICAL_SECTION conlist_mutex;
638#define conlist_disabled ((st_table *)-1)
640#define thread_exclusive(obj) \
641 for (bool exclusive_for_##obj = (EnterCriticalSection(&obj##_mutex), true); \
642 exclusive_for_##obj; \
643 exclusive_for_##obj = (LeaveCriticalSection(&obj##_mutex), false))
645static CRITICAL_SECTION uenvarea_mutex;
646static char *uenvarea;
651 int state, seq[16], reverse;
656enum {constat_init = -2, constat_esc = -1, constat_seq = 0};
660free_conlist(st_data_t key, st_data_t val, st_data_t arg)
668constat_delete(HANDLE h)
670 thread_exclusive(conlist) {
671 if (conlist && conlist != conlist_disabled) {
672 st_data_t key = (st_data_t)h, val;
673 st_delete(conlist, &key, &val);
684 DeleteCriticalSection(&select_mutex);
685 DeleteCriticalSection(&socklist_mutex);
686 DeleteCriticalSection(&conlist_mutex);
687 thread_exclusive(uenvarea) {
693 DeleteCriticalSection(&uenvarea_mutex);
700 EnterCriticalSection(&socklist_mutex);
702 st_free_table(socklist);
705 LeaveCriticalSection(&socklist_mutex);
707 EnterCriticalSection(&conlist_mutex);
708 if (conlist && conlist != conlist_disabled) {
709 st_foreach(conlist, free_conlist, 0);
710 st_free_table(conlist);
713 LeaveCriticalSection(&conlist_mutex);
716#define ATOMIC_LONG_CAS(var, oldval, newval) InterlockedCompareExchange(&(var), (newval), (oldval))
720install_vm_exit_handler(
void)
722 static LONG installed = 0;
725 while ((i = ATOMIC_LONG_CAS(installed, 0, -1)) != 1) {
731 ATOMIC_LONG_CAS(installed, -1, 1);
747 version = MAKEWORD(2, 0);
748 if (WSAStartup(version, &retdata))
749 rb_fatal(
"Unable to locate winsock library!");
750 if (LOBYTE(retdata.wVersion) != 2)
751 rb_fatal(
"could not find version 2 of winsock dll");
753 InitializeCriticalSection(&select_mutex);
754 InitializeCriticalSection(&socklist_mutex);
755 InitializeCriticalSection(&conlist_mutex);
757 atexit(exit_handler);
760#define MAKE_SOCKDATA(af, fl) ((int)((((int)af)<<4)|((fl)&0xFFFF)))
761#define GET_FAMILY(v) ((int)(((v)>>4)&0xFFFF))
762#define GET_FLAGS(v) ((int)((v)&0xFFFF))
766socklist_insert(SOCKET sock,
int flag)
770 thread_exclusive(socklist) {
772 socklist = st_init_numtable();
773 install_vm_exit_handler();
775 ret = st_insert(socklist, (st_data_t)sock, (st_data_t)flag);
783socklist_lookup(SOCKET sock,
int *flagp)
788 thread_exclusive(socklist) {
789 if (!socklist)
continue;
790 ret = st_lookup(socklist, (st_data_t)sock, &data);
800socklist_delete(SOCKET *sockp,
int *flagp)
806 thread_exclusive(socklist) {
807 if (!socklist)
continue;
808 key = (st_data_t)*sockp;
810 data = (st_data_t)*flagp;
811 ret = st_delete(socklist, &key, &data);
813 *sockp = (SOCKET)key;
823# define _CrtSetReportMode(type,mode) ((void)0)
824# define _RTC_SetErrorFunc(func) ((void)0)
826static void set_pioinfo_extra(
void);
827static int w32_cmdvector(
const WCHAR *,
char ***, UINT,
rb_encoding *);
844rb_w32_init_long_paths(
void)
847 enum {peb_bit_field_offset = 3, is_long_path_aware_process = 0x80};
848 typedef long (WINAPI version_func)(OSVERSIONINFOW *);
849 typedef void *(WINAPI peb_func)(
void);
850 version_func *pRtlGetVersion;
851 peb_func *pRtlGetCurrentPeb;
855 pRtlGetVersion = (version_func *)get_proc_address(
"ntdll.dll",
"RtlGetVersion", NULL);
856 if (!pRtlGetVersion)
return;
857 memset(&osvi, 0,
sizeof(osvi));
858 osvi.dwOSVersionInfoSize =
sizeof(osvi);
859 if (pRtlGetVersion(&osvi))
return;
862 if (osvi.dwMajorVersion < 10)
return;
863 if (osvi.dwMajorVersion == 10 && osvi.dwMinorVersion == 0 &&
864 osvi.dwBuildNumber < 15063)
return;
866 pRtlGetCurrentPeb = (peb_func *)get_proc_address(
"ntdll.dll",
"RtlGetCurrentPeb", NULL);
867 if (!pRtlGetCurrentPeb)
return;
868 bit_field = (BYTE *)pRtlGetCurrentPeb() + peb_bit_field_offset;
869 *bit_field |= is_long_path_aware_process;
874rb_w32_sysinit(
int *argc,
char ***argv)
876 _CrtSetReportMode(_CRT_ASSERT, 0);
877 _set_invalid_parameter_handler(invalid_parameter);
878 _RTC_SetErrorFunc(rtc_error_handler);
880 SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX);
887 *argc = w32_cmdvector(GetCommandLineW(), argv, CP_UTF8, &OnigEncodingUTF_8);
895 InitializeCriticalSection(&uenvarea_mutex);
907 return (
char *)NTLoginName;
910#define MAXCHILDNUM 256
919#define FOREACH_CHILD(v) do { \
920 struct ChildRecord* v; \
921 for (v = ChildRecord; v < ChildRecord + sizeof(ChildRecord) / sizeof(ChildRecord[0]); ++v)
922#define END_FOREACH_CHILD } while (0)
926FindChildSlot(rb_pid_t pid)
929 FOREACH_CHILD(child) {
930 if (child->pid == pid) {
939FindChildSlotByHandle(HANDLE h)
942 FOREACH_CHILD(child) {
943 if (child->hProcess == h) {
954 HANDLE h = child->hProcess;
955 child->hProcess = NULL;
962FindFreeChildSlot(
void)
964 FOREACH_CHILD(child) {
967 child->hProcess = NULL;
975#define InternalCmdsMax 8
976static const char szInternalCmds[][InternalCmdsMax+1] = {
1024internal_match(
const void *key,
const void *elem)
1026 return strncmp(key, elem, InternalCmdsMax);
1029static int internal_cmd_match(
const char *cmdname);
1033is_internal_cmd(
const char *cmd)
1035 char cmdname[InternalCmdsMax+1], *b = cmdname, c;
1038 if (!(c = *cmd++))
return 0;
1039 }
while (isspace(c));
1042 while (isalpha(c)) {
1044 if (b == cmdname +
sizeof(cmdname))
return 0;
1047 if (c ==
'.') c = *cmd;
1049 case '<':
case '>':
case '|':
1051 case '\0':
case ' ':
case '\t':
case '\n':
1057 return internal_cmd_match(cmdname);
1062internal_cmd_match(
const char *cmdname)
1066 nm = bsearch(cmdname, szInternalCmds,
1067 numberof(szInternalCmds),
1068 sizeof(*szInternalCmds),
1076rb_w32_get_osfhandle(
int fh)
1078 return _get_osfhandle(fh);
1083join_argv(
char *cmd,
char *
const *argv, BOOL escape, UINT cp,
int backslash, BOOL quote_bs)
1087 int len, n, bs, quote;
1089 for (t = argv, q = cmd,
len = 0; (p = *t) != 0; t++) {
1092 if (!*p || strpbrk(p,
" \t\"'")) {
1097 for (bs = 0; *p; ++p) {
1111 memset(q,
'\\', bs);
1116 case '<':
case '>':
case '|':
case '^':
1117 if (escape && !quote) {
1118 len += (n = p - s) + 1;
1129 p = CharNextExA(cp, p, 0) - 1;
1133 len += (n = p - s) + 1;
1134 if (quote)
len += (quote_bs ? bs : 0) + 1;
1137 if (backslash > 0) {
1140 translate_char(q,
'/',
'\\', cp);
1145 if (quote_bs && bs) {
1146 memset(q,
'\\', bs);
1163#define STRNDUPV(ptr, v, src, len) \
1164 (((char *)memcpy(((ptr) = ALLOCV((v), (len) + 1)), (src), (len)))[len] = 0)
1168check_spawn_mode(
int mode)
1190 if (mode == P_OVERLAY) {
1191 WaitForSingleObject(child->hProcess, INFINITE);
1192 GetExitCodeProcess(child->hProcess, &exitcode);
1193 CloseChildHandle(child);
1201CreateChild(
struct ChildRecord *child,
const WCHAR *cmd,
const WCHAR *prog, HANDLE hInput, HANDLE hOutput, HANDLE hError, DWORD dwCreationFlags)
1204 STARTUPINFOW aStartupInfo;
1205 PROCESS_INFORMATION aProcessInformation;
1206 SECURITY_ATTRIBUTES sa;
1208 if (!cmd && !prog) {
1218 sa.nLength =
sizeof(SECURITY_ATTRIBUTES);
1219 sa.lpSecurityDescriptor = NULL;
1220 sa.bInheritHandle = TRUE;
1222 memset(&aStartupInfo, 0,
sizeof(aStartupInfo));
1223 memset(&aProcessInformation, 0,
sizeof(aProcessInformation));
1224 aStartupInfo.cb =
sizeof(aStartupInfo);
1225 aStartupInfo.dwFlags = STARTF_USESTDHANDLES;
1227 aStartupInfo.hStdInput = hInput;
1230 aStartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
1233 aStartupInfo.hStdOutput = hOutput;
1236 aStartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
1239 aStartupInfo.hStdError = hError;
1242 aStartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
1245 dwCreationFlags |= NORMAL_PRIORITY_CLASS;
1247 if (lstrlenW(cmd) > 32767) {
1254 fRet = CreateProcessW(prog, (WCHAR *)cmd, &sa, &sa,
1255 sa.bInheritHandle, dwCreationFlags, NULL, NULL,
1256 &aStartupInfo, &aProcessInformation);
1257 errno = map_errno(GetLastError());
1265 CloseHandle(aProcessInformation.hThread);
1267 child->hProcess = aProcessInformation.hProcess;
1268 child->pid = (rb_pid_t)aProcessInformation.dwProcessId;
1275is_batch(
const char *cmd)
1277 int len = strlen(cmd);
1278 if (
len <= 4)
return 0;
1280 if (*cmd++ !=
'.')
return 0;
1281 if (strcasecmp(cmd,
"bat") == 0)
return 1;
1282 if (strcasecmp(cmd,
"cmd") == 0)
return 1;
1286#define filecp rb_w32_filecp
1287#define mbstr_to_wstr rb_w32_mbstr_to_wstr
1288#define wstr_to_mbstr rb_w32_wstr_to_mbstr
1289#define acp_to_wstr(str, plen) mbstr_to_wstr(CP_ACP, str, -1, plen)
1290#define wstr_to_acp(str, plen) wstr_to_mbstr(CP_ACP, str, -1, plen)
1291#define filecp_to_wstr(str, plen) mbstr_to_wstr(filecp(), str, -1, plen)
1292#define wstr_to_filecp(str, plen) wstr_to_mbstr(filecp(), str, -1, plen)
1293#define utf8_to_wstr(str, plen) mbstr_to_wstr(CP_UTF8, str, -1, plen)
1294#define wstr_to_utf8(str, plen) wstr_to_mbstr(CP_UTF8, str, -1, plen)
1298w32_spawn(
int mode,
const char *cmd,
const char *prog, UINT cp)
1300 char fbuf[PATH_MAX];
1302 const char *shell = NULL;
1303 WCHAR *wcmd = NULL, *wshell = NULL;
1309 char *cmd_sep = NULL;
1311 if (check_spawn_mode(mode))
return -1;
1314 if (!(p = dln_find_exe_r(prog, NULL, fbuf,
sizeof(fbuf)))) {
1319 translate_char(p,
'/',
'\\', cp);
1325 if ((shell = w32_getenv(
"RUBYSHELL", cp)) && (redir = has_redirection(cmd, cp))) {
1326 size_t shell_len = strlen(shell);
1327 size_t cmd_len = strlen(cmd) +
sizeof(
" -c ") + 2;
1328 char *tmp =
ALLOCV(v, shell_len + cmd_len);
1329 memcpy(tmp, shell, shell_len + 1);
1330 translate_char(tmp,
'/',
'\\', cp);
1331 snprintf(tmp + shell_len, cmd_len,
" -c \"%s\"", cmd);
1334 else if ((shell = w32_getenv(
"COMSPEC", cp)) &&
1335 ((redir < 0 ? has_redirection(cmd, cp) : redir) || is_internal_cmd(cmd))) {
1336 size_t cmd_len = strlen(shell) + strlen(cmd) +
sizeof(
" /c \"\"");
1337 char *tmp =
ALLOCV(v, cmd_len);
1338 snprintf(tmp, cmd_len,
"%s /c \"%s\"", shell, cmd);
1342 int len = 0, quote = (*cmd ==
'"') ?
'"' : (*cmd ==
'\'') ?
'\'' : 0;
1344 for (prog = cmd + !!quote;; prog = CharNextExA(cp, prog, 0)) {
1345 if (*prog ==
'/') slash = 1;
1349 STRNDUPV(p, v2, cmd,
len);
1355 if ((
unsigned char)*prog == quote) {
1356 len = prog++ - cmd - 1;
1357 STRNDUPV(p, v2, cmd + 1,
len);
1361 if (quote)
continue;
1362 if (
ISSPACE(*prog) || strchr(
"<>|*?\"", *prog)) {
1364 STRNDUPV(p, v2, cmd,
len + (slash ? strlen(prog) : 0));
1367 sep = *(cmd_sep = &p[
len]);
1374 shell = dln_find_exe_r(shell, NULL, fbuf,
sizeof(fbuf));
1375 if (p && slash) translate_char(p,
'/',
'\\', cp);
1377 shell = p ? p : cmd;
1380 len = strlen(shell);
1381 if (strchr(shell,
' ')) quote = -1;
1382 if (shell == fbuf) {
1385 else if (shell != p && strchr(shell,
'/')) {
1386 STRNDUPV(p, v2, shell,
len);
1389 if (p) translate_char(p,
'/',
'\\', cp);
1390 if (is_batch(shell)) {
1391 int alen = strlen(prog);
1392 cmd = p =
ALLOCV(v,
len + alen + (quote ? 2 : 0) + 1);
1393 if (quote) *p++ =
'"';
1394 memcpy(p, shell,
len);
1396 if (quote) *p++ =
'"';
1397 memcpy(p, prog, alen + 1);
1404 if (!e && shell && !(wshell = mbstr_to_wstr(cp, shell, -1, NULL))) e = E2BIG;
1405 if (cmd_sep) *cmd_sep = sep;
1406 if (!e && cmd && !(wcmd = mbstr_to_wstr(cp, cmd, -1, NULL))) e = E2BIG;
1412 if (CreateChild(child, wcmd, wshell, NULL, NULL, NULL, 0)) {
1413 ret = child_result(child, mode);
1424rb_w32_spawn(
int mode,
const char *cmd,
const char *prog)
1427 return w32_spawn(mode, cmd, prog, filecp());
1432rb_w32_uspawn(
int mode,
const char *cmd,
const char *prog)
1434 return w32_spawn(mode, cmd, prog, CP_UTF8);
1439w32_spawn_process(
int mode,
const char *prog,
char *
const *argv,
1440 int in_fd,
int out_fd,
int err_fd, DWORD flags, UINT cp)
1445 char *cmd, fbuf[PATH_MAX];
1446 WCHAR *wcmd = NULL, *wprog = NULL;
1450 HANDLE in_handle = NULL, out_handle = NULL, err_handle = NULL;
1452 if (check_spawn_mode(mode))
return -1;
1455 in_handle = (HANDLE)rb_w32_get_osfhandle(in_fd);
1458 out_handle = (HANDLE)rb_w32_get_osfhandle(out_fd);
1461 err_handle = (HANDLE)rb_w32_get_osfhandle(err_fd);
1464 if (!prog) prog = argv[0];
1465 if ((shell = w32_getenv(
"COMSPEC", cp)) && internal_cmd_match(prog)) {
1469 else if ((cmd = dln_find_exe_r(prog, NULL, fbuf,
sizeof(fbuf)))) {
1470 if (cmd == prog) strlcpy(cmd = fbuf, prog,
sizeof(fbuf));
1471 translate_char(cmd,
'/',
'\\', cp);
1474 else if (strchr(prog,
'/')) {
1476 if (
len <
sizeof(fbuf))
1477 strlcpy(cmd = fbuf, prog,
sizeof(fbuf));
1479 STRNDUPV(cmd, v, prog,
len);
1480 translate_char(cmd,
'/',
'\\', cp);
1483 if (c_switch || is_batch(prog)) {
1485 progs[0] = (
char *)prog;
1487 len = join_argv(NULL, progs, TRUE, cp, 1, FALSE);
1488 if (c_switch)
len += 3;
1490 if (argv[0])
len += join_argv(NULL, argv, TRUE, cp, 0, FALSE);
1492 join_argv(cmd, progs, TRUE, cp, 1, FALSE);
1493 if (c_switch) strlcat(cmd,
" /c",
len);
1494 if (argv[0]) join_argv(cmd + strlcat(cmd,
" ",
len), argv, TRUE, cp, 0, FALSE);
1495 prog = c_switch ? shell : 0;
1498 len = join_argv(NULL, argv, FALSE, cp, 1, TRUE);
1500 join_argv(cmd, argv, FALSE, cp, 1, TRUE);
1503 if (!e && cmd && !(wcmd = mbstr_to_wstr(cp, cmd, -1, NULL))) e = E2BIG;
1505 if (!e && prog && !(wprog = mbstr_to_wstr(cp, prog, -1, NULL))) e = E2BIG;
1509 if (CreateChild(child, wcmd, wprog, in_handle, out_handle, err_handle, flags)) {
1510 ret = child_result(child, mode);
1521rb_w32_aspawn_flags(
int mode,
const char *prog,
char *
const *argv, DWORD flags)
1524 return w32_spawn_process(mode, prog, argv, -1, -1, -1, flags, filecp());
1529rb_w32_uaspawn_flags(
int mode,
const char *prog,
char *
const *argv, DWORD flags)
1531 return w32_spawn_process(mode, prog, argv, -1, -1, -1, flags, CP_UTF8);
1536rb_w32_aspawn(
int mode,
const char *prog,
char *
const *argv)
1538 return w32_spawn_process(mode, prog, argv, -1, -1, -1, 0, filecp());
1543rb_w32_uaspawn(
int mode,
const char *prog,
char *
const *argv)
1545 return rb_w32_uaspawn_flags(mode, prog, argv, 0);
1550rb_w32_uspawn_process(
int mode,
const char *prog,
char *
const *argv,
1551 int in_fd,
int out_fd,
int err_fd, DWORD flags)
1553 return w32_spawn_process(mode, prog, argv, in_fd, out_fd, err_fd,
1575insert(
const char *path,
VALUE vinfo,
void *enc)
1581 if (!tmpcurr)
return -1;
1583 tmpcurr->len = strlen(path);
1584 tmpcurr->str =
strdup(path);
1585 if (!tmpcurr->str)
return -1;
1586 tmpcurr->flags |= NTMALLOC;
1588 *tail = &tmpcurr->next;
1597 char buffer[PATH_MAX], *buf = buffer;
1601 if (patt->len >= PATH_MAX)
1602 if (!(buf = malloc(patt->len + 1)))
return 0;
1604 memcpy(buf, patt->str, patt->len);
1605 buf[patt->len] =
'\0';
1606 translate_char(buf,
'\\',
'/', cp);
1607 status = ruby_brace_glob_with_enc(buf, 0, insert, (
VALUE)&tail, enc);
1611 if (status || last == tail)
return 0;
1612 if (patt->flags & NTMALLOC)
1625has_redirection(
const char *cmd, UINT cp)
1635 for (ptr = cmd; *ptr;) {
1641 else if (quote == *ptr)
1657 if (*++ptr !=
'_' && !
ISALPHA(*ptr))
break;
1658 while (*++ptr ==
'_' ||
ISALNUM(*ptr));
1659 if (*ptr && *ptr++ ==
'%')
return TRUE;
1665 ptr = CharNextExA(cp, ptr, 0);
1673static inline WCHAR *
1674skipspace(WCHAR *ptr)
1683w32_cmdvector(
const WCHAR *cmd,
char ***vec, UINT cp,
rb_encoding *enc)
1686 int elements, strsz, done;
1687 int slashes, escape;
1688 WCHAR *ptr, *base, *cmdline;
1689 char *cptr, *buffer;
1705 ptr = cmdline = wcsdup(cmd);
1716 while (*(ptr = skipspace(ptr))) {
1718 quote = slashes = globbing = escape = 0;
1719 for (done = 0; !done && *ptr; ) {
1728 if (quote != L
'\'') slashes++;
1769 if (!(slashes & 1)) {
1772 else if (quote == *ptr) {
1773 if (quote == L
'"' && quote == ptr[1])
1783 ptr = CharNextW(ptr);
1806 slashes = quote = 0;
1807 while (p < base +
len) {
1811 if (quote != L
'\'') slashes++;
1816 if (!(slashes & 1) && quote && quote != c) {
1821 memcpy(p - ((slashes + 1) >> 1), p + (~slashes & 1),
1822 sizeof(WCHAR) * (base +
len - p));
1823 len -= ((slashes + 1) >> 1) + (~slashes & 1);
1824 p -= (slashes + 1) >> 1;
1825 if (!(slashes & 1)) {
1827 if (quote == L
'"' && quote == *p)
1848 if (!curr)
goto do_nothing;
1849 curr->str = rb_w32_wstr_to_mbstr(cp, base,
len, &curr->len);
1850 curr->flags |= NTMALLOC;
1852 if (globbing && (tail = cmdglob(curr, cmdtail, cp, enc))) {
1857 cmdtail = &curr->next;
1867 for (elements = 0, strsz = 0, curr = cmdhead; curr; curr = curr->next) {
1869 strsz += (curr->len + 1);
1872 len = (elements+1)*
sizeof(
char *) + strsz;
1873 buffer = (
char *)malloc(
len);
1876 while ((curr = cmdhead) != 0) {
1877 cmdhead = curr->next;
1878 if (curr->flags & NTMALLOC) free(curr->str);
1882 for (vptr = *vec; *vptr; ++vptr);
1898 vptr = (
char **) buffer;
1900 cptr = buffer + (elements+1) *
sizeof(
char *);
1902 while ((curr = cmdhead) != 0) {
1903 memcpy(cptr, curr->str, curr->len);
1904 cptr[curr->len] =
'\0';
1906 cptr += curr->len + 1;
1907 cmdhead = curr->next;
1908 if (curr->flags & NTMALLOC) free(curr->str);
1913 *vec = (
char **) buffer;
1925open_special(
const WCHAR *path, DWORD access, DWORD flags)
1927 const DWORD share_mode =
1928 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1929 return CreateFileW(path, access, share_mode, NULL, OPEN_EXISTING,
1930 FILE_FLAG_BACKUP_SEMANTICS|flags, NULL);
1940#define GetBit(bits, i) ((bits)[(i) / CHAR_BIT] & (1 << (i) % CHAR_BIT))
1941#define SetBit(bits, i) ((bits)[(i) / CHAR_BIT] |= (1 << (i) % CHAR_BIT))
1943#define BitOfIsDir(n) ((n) * 2)
1944#define BitOfIsRep(n) ((n) * 2 + 1)
1945#define DIRENT_PER_CHAR (CHAR_BIT / 2)
1947static const WCHAR namespace_prefix[] = {L
'\\', L
'\\', L
'?', L
'\\'};
1953get_handle_pathname(HANDLE fh, WCHAR **pathptr, DWORD add)
1955 DWORD
len = GetFinalPathNameByHandleW(fh, NULL, 0, 0);
1957 WCHAR *path = malloc((
len + add + 1) *
sizeof(WCHAR));
1958 if (!(*pathptr = path))
return 0;
1959 len = GetFinalPathNameByHandleW(fh, path,
len + 1, 0);
1969open_dir_handle(
const WCHAR *filename, WIN32_FIND_DATAW *fd)
1973 WCHAR *fullname = 0;
1981 fh = open_special(filename, 0, 0);
1982 if (fh != INVALID_HANDLE_VALUE) {
1983 len = get_handle_pathname(fh, &fullname, wildcard_len);
1987 len = lstrlenW(filename);
1988 fullname = malloc((
len + wildcard_len + 1) *
sizeof(WCHAR));
1989 if (!fullname)
return INVALID_HANDLE_VALUE;
1995 p = &fullname[
len-1];
1996 if (!(isdirsep(*p) || *p == L
':')) *++p = L
'\\';
2003 fh = FindFirstFileW(fullname, fd);
2004 if (fh == INVALID_HANDLE_VALUE) {
2005 errno = map_errno(GetLastError());
2013w32_wopendir(
const WCHAR *wpath)
2016 WIN32_FIND_DATAW fd;
2029 if (wstati128(wpath, &sbuf, FALSE) < 0) {
2032 if (!(sbuf.st_mode & S_IFDIR) &&
2033 (!
ISALPHA(wpath[0]) || wpath[1] != L
':' || wpath[2] != L
'\0' ||
2034 ((1 << ((wpath[0] & 0x5f) -
'A')) & GetLogicalDrives()) == 0)) {
2038 fh = open_dir_handle(wpath, &fd);
2039 if (fh == INVALID_HANDLE_VALUE) {
2046 p = calloc(1,
sizeof(
DIR));
2050 pathlen = lstrlenW(wpath);
2060 len = lstrlenW(fd.cFileName) + 1;
2061 altlen = lstrlenW(fd.cAlternateFileName) + 1;
2067 tmpW = realloc(p->start, (idx +
len + altlen) *
sizeof(WCHAR));
2077 memcpy(&p->start[idx], fd.cFileName,
len *
sizeof(WCHAR));
2078 memcpy(&p->start[idx +
len], fd.cAlternateFileName, altlen *
sizeof(WCHAR));
2080 if (p->nfiles % DIRENT_PER_CHAR == 0) {
2081 tmp = realloc(p->bits, p->nfiles / DIRENT_PER_CHAR + 1);
2085 p->bits[p->nfiles / DIRENT_PER_CHAR] = 0;
2087 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
2088 SetBit(p->bits, BitOfIsDir(p->nfiles));
2089 if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2090 WCHAR *tmppath = malloc((pathlen +
len + 1) *
sizeof(WCHAR));
2091 memcpy(tmppath, wpath, pathlen *
sizeof(WCHAR));
2092 tmppath[pathlen] = L
'\\';
2093 memcpy(tmppath + pathlen + 1, fd.cFileName,
len *
sizeof(WCHAR));
2094 if (rb_w32_reparse_symlink_p(tmppath))
2095 SetBit(p->bits, BitOfIsRep(p->nfiles));
2100 idx +=
len + altlen;
2101 }
while (FindNextFileW(fh, &fd));
2112 UINT cp = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
2118rb_w32_wstr_to_mbstr(UINT cp,
const WCHAR *wstr,
int clen,
long *plen)
2121 int len = WideCharToMultiByte(cp, 0, wstr, clen, NULL, 0, NULL, NULL);
2122 if (!(ptr = malloc(
len)))
return 0;
2123 WideCharToMultiByte(cp, 0, wstr, clen, ptr,
len, NULL, NULL);
2126 if (clen == -1) --
len;
2134rb_w32_mbstr_to_wstr(UINT cp,
const char *str,
int clen,
long *plen)
2137 int len = MultiByteToWideChar(cp, 0, str, clen, NULL, 0);
2138 if (!(ptr = malloc(
sizeof(WCHAR) *
len)))
return 0;
2139 MultiByteToWideChar(cp, 0, str, clen, ptr,
len);
2142 if (clen == -1) --
len;
2150rb_w32_opendir(
const char *filename)
2153 WCHAR *wpath = filecp_to_wstr(filename, NULL);
2156 ret = w32_wopendir(wpath);
2163rb_w32_uopendir(
const char *filename)
2166 WCHAR *wpath = utf8_to_wstr(filename, NULL);
2169 ret = w32_wopendir(wpath);
2180move_to_next_entry(
DIR *dirp)
2184 dirp->curr += lstrlenW(dirp->curr) + 1;
2185 dirp->curr += lstrlenW(dirp->curr) + 1;
2186 if (dirp->curr >= (dirp->start + dirp->size)) {
2198win32_direct_conv(
const WCHAR *file,
const WCHAR *alt,
struct direct *entry,
const void *enc)
2200 UINT cp = *((UINT *)enc);
2201 if (!(entry->d_name = wstr_to_mbstr(cp, file, -1, &entry->d_namlen)))
2205 entry->d_altname = wstr_to_mbstr(cp, alt, -1, &altlen);
2206 entry->d_altlen = altlen;
2213rb_w32_conv_from_wchar(
const WCHAR *wstr,
rb_encoding *enc)
2216 long len = lstrlenW(wstr);
2217 int encindex = rb_enc_to_index(enc);
2219 if (encindex == ENCINDEX_UTF_16LE) {
2220 return rb_enc_str_new((
char *)wstr,
len *
sizeof(WCHAR), enc);
2223#if SIZEOF_INT < SIZEOF_LONG
2224# error long should equal to int on Windows
2227 len = WideCharToMultiByte(CP_UTF8, 0, wstr, clen, NULL, 0, NULL, NULL);
2228 src = rb_enc_str_new(0,
len, rb_enc_from_index(ENCINDEX_UTF_8));
2229 WideCharToMultiByte(CP_UTF8, 0, wstr, clen, RSTRING_PTR(src),
len, NULL, NULL);
2232 case ENCINDEX_ASCII_8BIT:
2233 case ENCINDEX_US_ASCII:
2235 case ENCINDEX_UTF_8:
2244rb_w32_conv_from_wstr(
const WCHAR *wstr,
long *lenp,
rb_encoding *enc)
2246 VALUE str = rb_w32_conv_from_wchar(wstr, enc);
2250 if (
NIL_P(str))
return wstr_to_utf8(wstr, lenp);
2251 *lenp =
len = RSTRING_LEN(str);
2252 memcpy(ptr = malloc(
len + 1), RSTRING_PTR(str),
len);
2259ruby_direct_conv(
const WCHAR *file,
const WCHAR *alt,
struct direct *entry,
const void *enc)
2261 if (!(entry->d_name = rb_w32_conv_from_wstr(file, &entry->d_namlen, enc)))
2265 entry->d_altname = rb_w32_conv_from_wstr(alt, &altlen, enc);
2266 entry->d_altlen = altlen;
2273readdir_internal(
DIR *dirp, BOOL (*conv)(
const WCHAR *,
const WCHAR *,
struct direct *,
const void *),
const void *enc)
2275 static long dummy_ino = 0;
2282 free(dirp->dirstr.d_name);
2283 free(dirp->dirstr.d_altname);
2284 dirp->dirstr.d_altname = 0;
2285 dirp->dirstr.d_altlen = 0;
2286 conv(dirp->curr, dirp->curr + lstrlenW(dirp->curr) + 1, &dirp->dirstr, enc);
2291 dirp->dirstr.d_ino = (ino_t)(InterlockedIncrement(&dummy_ino) - 1);
2297 if (GetBit(dirp->bits, BitOfIsRep(dirp->loc)))
2298 dirp->dirstr.d_type = DT_LNK;
2299 else if (GetBit(dirp->bits, BitOfIsDir(dirp->loc)))
2300 dirp->dirstr.d_type = DT_DIR;
2302 dirp->dirstr.d_type = DT_REG;
2308 move_to_next_entry(dirp);
2310 return &(dirp->dirstr);
2321 int idx = rb_enc_to_index(enc);
2322 if (idx == ENCINDEX_ASCII_8BIT) {
2323 const UINT cp = filecp();
2324 return readdir_internal(dirp, win32_direct_conv, &cp);
2326 else if (idx == ENCINDEX_UTF_8) {
2327 const UINT cp = CP_UTF8;
2328 return readdir_internal(dirp, win32_direct_conv, &cp);
2331 return readdir_internal(dirp, ruby_direct_conv, enc);
2336rb_w32_ureaddir(
DIR *dirp)
2338 const UINT cp = CP_UTF8;
2339 return readdir_internal(dirp, win32_direct_conv, &cp);
2348rb_w32_telldir(
DIR *dirp)
2359rb_w32_seekdir(
DIR *dirp,
long loc)
2361 if (dirp->loc > loc) rb_w32_rewinddir(dirp);
2363 while (dirp->curr && dirp->loc < loc) {
2364 move_to_next_entry(dirp);
2374rb_w32_rewinddir(
DIR *dirp)
2376 dirp->curr = dirp->start;
2386rb_w32_closedir(
DIR *dirp)
2389 free(dirp->dirstr.d_name);
2390 free(dirp->dirstr.d_altname);
2412 CRITICAL_SECTION _lock;
2414#define FILE_COUNT(stream) ((vcruntime_file*)stream)->_cnt
2415#define FILE_READPTR(stream) ((vcruntime_file*)stream)->_ptr
2416#define FILE_FILENO(stream) ((vcruntime_file*)stream)->_file
2419typedef char lowio_text_mode;
2420typedef char lowio_pipe_lookahead[3];
2423 CRITICAL_SECTION lock;
2426 unsigned char osfile;
2427 lowio_text_mode textmode;
2428 lowio_pipe_lookahead _pipe_lookahead;
2430 uint8_t unicode : 1;
2431 uint8_t utf8translations : 1;
2432 uint8_t dbcsBufferUsed : 1;
2436#if !defined _CRTIMP || defined __MINGW32__
2438#define _CRTIMP __declspec(dllimport)
2441static ioinfo ** __pioinfo = NULL;
2443static inline ioinfo* _pioinfo(
int);
2446#define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
2447#define _osfhnd(i) (_pioinfo(i)->osfhnd)
2448#define _osfile(i) (_pioinfo(i)->osfile)
2449#define rb_acrt_lowio_lock_fh(i) EnterCriticalSection(&_pioinfo(i)->lock)
2450#define rb_acrt_lowio_unlock_fh(i) LeaveCriticalSection(&_pioinfo(i)->lock)
2452static size_t pioinfo_extra = 0;
2456set_pioinfo_extra(
void)
2458#define FUNCTION_RET 0xc3
2460# define UCRTBASE "ucrtbased.dll"
2462# define UCRTBASE "ucrtbase.dll"
2477 char *p = (
char*)get_proc_address(UCRTBASE,
"_isatty", NULL);
2480#if defined(_M_ARM64) || defined(__aarch64__)
2481#define IS_INSN(pc, name) ((*(pc) & name##_mask) == name##_id)
2482 const int max_num_inst = 500;
2483 uint32_t *start = (uint32_t*)p;
2484 uint32_t *end_limit = (start + max_num_inst);
2485 uint32_t *pc = start;
2488 fprintf(stderr,
"_isatty proc not found in " UCRTBASE
"\n");
2493 const uint32_t ret_id = 0xd65f0000;
2494 const uint32_t ret_mask = 0xfffffc1f;
2495 for(; pc < end_limit; pc++) {
2496 if (IS_INSN(pc, ret)) {
2500 if (pc == end_limit) {
2501 fprintf(stderr,
"end of _isatty not found in " UCRTBASE
"\n");
2506 const uint32_t adrp_id = 0x90000000;
2507 const uint32_t adrp_mask = 0x9f000000;
2508 const uint32_t add_id = 0x11000000;
2509 const uint32_t add_mask = 0x7fc00000;
2510 for(; pc > start; pc--) {
2511 if (IS_INSN(pc, adrp) && IS_INSN(pc + 1, add)) {
2516 fprintf(stderr,
"pioinfo mark not found in " UCRTBASE
"\n");
2526 const uint32_t adrp_insn = *pc;
2527 const uint32_t adrp_immhi = (adrp_insn & 0x00ffffe0) >> 5;
2528 const uint32_t adrp_immlo = (adrp_insn & 0x60000000) >> (5 + 19 + 5);
2529 const int64_t adrp_sign = (adrp_insn & 0x00800000) ? ~0x001fffff : 0;
2531 const int64_t adrp_imm = (adrp_sign | (adrp_immhi << 2) | adrp_immlo) << 12;
2533 const uint64_t adrp_base = (uint64_t)pc & 0xfffffffffffff000;
2535 const uint32_t add_insn = *(pc + 1);
2536 const uint64_t add_imm = (add_insn & 0x3ffc00) >> (5 + 5);
2538 __pioinfo = (
ioinfo**)(adrp_base + adrp_imm + add_imm);
2546# define FUNCTION_BEFORE_RET_MARK "\x48\x83\xc4"
2547# define FUNCTION_SKIP_BYTES 1
2550# define PIOINFO_MARK "\x48\x8d\x0d"
2553# define PIOINFO_MARK "\x48\x8d\x15"
2558# define FUNCTION_BEFORE_RET_MARK "\x5d"
2560# define FUNCTION_BEFORE_RET_MARK_2 "\xc9"
2561# define FUNCTION_SKIP_BYTES 0
2563# define PIOINFO_MARK "\x8B\x04\x85"
2566 for (pend += 10; pend < p + 500; pend++) {
2568 if ((memcmp(pend, FUNCTION_BEFORE_RET_MARK,
sizeof(FUNCTION_BEFORE_RET_MARK) - 1) == 0
2569# ifdef FUNCTION_BEFORE_RET_MARK_2
2570 || memcmp(pend, FUNCTION_BEFORE_RET_MARK_2,
sizeof(FUNCTION_BEFORE_RET_MARK_2) - 1) == 0
2573 *(pend + (
sizeof(FUNCTION_BEFORE_RET_MARK) - 1) + FUNCTION_SKIP_BYTES) == (
char)FUNCTION_RET) {
2575 for (pend -= (
sizeof(PIOINFO_MARK) - 1); pend > p; pend--) {
2576 if (memcmp(pend, PIOINFO_MARK,
sizeof(PIOINFO_MARK) - 1) == 0) {
2585 fprintf(stderr,
"unexpected " UCRTBASE
"\n");
2589 p +=
sizeof(PIOINFO_MARK) - 1;
2591 rel = *(int32_t*)(p);
2592 rip = p +
sizeof(int32_t);
2593 __pioinfo = (
ioinfo**)(rip + rel);
2595 __pioinfo = *(
ioinfo***)(p);
2600 fd = _open(
"NUL", O_RDONLY);
2601 for (pioinfo_extra = 0; pioinfo_extra <= 64; pioinfo_extra +=
sizeof(
void *)) {
2602 if (_osfhnd(fd) == _get_osfhandle(fd)) {
2608 if (pioinfo_extra > 64) {
2617 const size_t sizeof_ioinfo =
sizeof(
ioinfo) + pioinfo_extra;
2618 return (
ioinfo*)((
char*)__pioinfo[fd >> IOINFO_L2E] +
2619 (fd & (IOINFO_ARRAY_ELTS - 1)) * sizeof_ioinfo);
2622#define _set_osfhnd(fh, osfh) (void)(_osfhnd(fh) = osfh)
2623#define _set_osflags(fh, flags) (_osfile(fh) = (flags))
2628#define FNOINHERIT 0x10
2633static int is_socket(SOCKET);
2634static int is_console(SOCKET);
2638rb_w32_io_cancelable_p(
int fd)
2640 return is_socket(TO_SOCKET(fd)) || !is_console(TO_SOCKET(fd));
2645rb_w32_open_osfhandle(intptr_t osfhandle,
int flags)
2654 if (flags & O_APPEND)
2655 fileflags |= FAPPEND;
2660 if (flags & O_NOINHERIT)
2661 fileflags |= FNOINHERIT;
2664 hF = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
2665 fh = _open_osfhandle((intptr_t)hF, 0);
2673 rb_acrt_lowio_lock_fh(fh);
2675 _set_osfhnd(fh, osfhandle);
2679 _set_osflags(fh, fileflags);
2680 rb_acrt_lowio_unlock_fh(fh);
2691#define open_null(fd) \
2693 (nullfd = open("NUL", O_RDWR)) : 0), \
2694 ((nullfd == (fd)) ? (keep = 1) : dup2(nullfd, fd)), \
2697 if (fileno(stdin) < 0) {
2698 FILE_FILENO(stdin) = open_null(0);
2701 setmode(fileno(stdin), O_BINARY);
2703 if (fileno(stdout) < 0) {
2704 FILE_FILENO(stdout) = open_null(1);
2706 if (fileno(stderr) < 0) {
2707 FILE_FILENO(stderr) = open_null(2);
2709 if (nullfd >= 0 && !keep) close(nullfd);
2710 setvbuf(stderr, NULL, _IONBF, 0);
2713 HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
2715 if (GetConsoleMode(h, &m)) {
2716#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
2717#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x4
2719 SetConsoleMode(h, m | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
2728is_socket(SOCKET sock)
2730 if (socklist_lookup(sock, NULL))
2738rb_w32_is_socket(
int fd)
2740 return is_socket(TO_SOCKET(fd));
2753rb_w32_strerror(
int e)
2755 static char buffer[512];
2760 strlcpy(buffer,
"Unknown Error",
sizeof(buffer));
2761 else if (e > sys_nerr) {
2762#if WSAEWOULDBLOCK != EWOULDBLOCK
2763 if (e >= EADDRINUSE && e <= EWOULDBLOCK) {
2767 for (s = 0; s < (int)(
sizeof(errmap)/
sizeof(*errmap)); s++)
2768 if (errmap[s].winerr == WSAEWOULDBLOCK)
2770 for (i = s; i < (int)(
sizeof(errmap)/
sizeof(*errmap)); i++)
2771 if (errmap[i].err == e) {
2772 e = errmap[i].winerr;
2777 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2778 FORMAT_MESSAGE_IGNORE_INSERTS, &source, e,
2779 MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
2780 buffer,
sizeof(buffer), NULL) == 0 &&
2781 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2782 FORMAT_MESSAGE_IGNORE_INSERTS, &source, e, 0,
2783 buffer,
sizeof(buffer), NULL) == 0)
2784 strlcpy(buffer,
"Unknown Error",
sizeof(buffer));
2787 strlcpy(buffer, strerror(e),
sizeof(buffer));
2790 while ((p = strpbrk(p,
"\r\n")) != NULL) {
2791 memmove(p, p + 1, strlen(p));
2842 return (uid == ROOT_UID ? 0 : -1);
2849 return (gid == ROOT_GID ? 0 : -1);
2858ioctl(
int i,
int u, ...)
2865rb_w32_fdset(
int fd, fd_set *set)
2874rb_w32_fdclr(
int fd, fd_set *set)
2877 SOCKET s = TO_SOCKET(fd);
2879 for (i = 0; i < set->fd_count; i++) {
2880 if (set->fd_array[i] == s) {
2881 memmove(&set->fd_array[i], &set->fd_array[i+1],
2882 sizeof(set->fd_array[0]) * (--set->fd_count - i));
2892rb_w32_fdisset(
int fd, fd_set *set)
2895 SOCKET s = TO_SOCKET(fd);
2896 if (s == (SOCKET)INVALID_HANDLE_VALUE)
2898 RUBY_CRITICAL {ret = __WSAFDIsSet(s, set);}
2906 max = min(src->fd_count, (UINT)max);
2907 if ((UINT)dst->
capa < (UINT)max) {
2908 dst->
capa = (src->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2912 memcpy(dst->
fdset->fd_array, src->fd_array,
2913 max *
sizeof(src->fd_array[0]));
2914 dst->
fdset->fd_count = src->fd_count;
2921 if ((UINT)dst->
capa < src->
fdset->fd_count) {
2922 dst->
capa = (src->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2926 memcpy(dst->
fdset->fd_array, src->
fdset->fd_array,
2927 src->
fdset->fd_count *
sizeof(src->
fdset->fd_array[0]));
2941extract_fd(
rb_fdset_t *dst, fd_set *src,
int (*func)(SOCKET))
2947 while (s < src->fd_count) {
2948 SOCKET fd = src->fd_array[s];
2950 if (!func || (*func)(fd)) {
2954 for (d = 0; d < dst->
fdset->fd_count; d++) {
2955 if (dst->
fdset->fd_array[d] == fd)
2958 if (d == dst->
fdset->fd_count) {
2959 if ((
int)dst->
fdset->fd_count >= dst->
capa) {
2960 dst->
capa = (dst->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2963 dst->
fdset->fd_array[dst->
fdset->fd_count++] = fd;
2967 &src->fd_array[s+1],
2968 sizeof(src->fd_array[0]) * (--src->fd_count - s));
2978 return dst ? dst->
fdset->fd_count : m;
2983copy_fd(fd_set *dst, fd_set *src)
2986 if (!src || !dst)
return 0;
2988 for (s = 0; s < src->fd_count; ++s) {
2989 SOCKET fd = src->fd_array[s];
2991 for (d = 0; d < dst->fd_count; ++d) {
2992 if (dst->fd_array[d] == fd)
2995 if (d == dst->fd_count) {
2996 dst->fd_array[dst->fd_count++] = fd;
3000 return dst->fd_count;
3005save_fd(SOCKET *dst,
const fd_set *src)
3007 if (src) memcpy(dst, src->fd_array, src->fd_count *
sizeof(SOCKET));
3012restore_fd(fd_set *dst,
const SOCKET *src, UINT count)
3015 memcpy(dst->fd_array, src, count *
sizeof(SOCKET));
3016 dst->fd_count = count;
3021is_not_socket(SOCKET sock)
3023 return !is_socket(sock);
3033 ret = (GetFileType((HANDLE)sock) == FILE_TYPE_PIPE);
3041is_readable_pipe(SOCKET sock)
3047 if (PeekNamedPipe((HANDLE)sock, NULL, 0, NULL, &n, NULL)) {
3051 ret = (GetLastError() == ERROR_BROKEN_PIPE);
3060is_console(SOCKET sock)
3067 ret = (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n));
3075is_readable_console(SOCKET sock)
3082 if (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n) && n > 0) {
3083 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
3084 ir.Event.KeyEvent.uChar.UnicodeChar) {
3087 else if (ir.EventType == KEY_EVENT && !ir.Event.KeyEvent.bKeyDown &&
3088 ir.Event.KeyEvent.wVirtualKeyCode == VK_MENU &&
3089 ir.Event.KeyEvent.uChar.UnicodeChar) {
3093 ReadConsoleInputW((HANDLE)sock, &ir, 1, &n);
3103is_invalid_handle(SOCKET sock)
3105 return (HANDLE)sock == INVALID_HANDLE_VALUE;
3110do_select(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3117 rb_w32_sleep(timeout->tv_sec * 1000 + timeout->tv_usec / 1000);
3119 rb_w32_sleep(INFINITE);
3123 thread_exclusive(select) {
3124 r = select(nfds, rd, wr, ex, timeout);
3126 if (r == SOCKET_ERROR) {
3127 errno = map_errno(WSAGetLastError());
3142rb_w32_time_subtract(
struct timeval *rest,
const struct timeval *wait)
3144 if (rest->tv_sec < wait->tv_sec) {
3147 while (rest->tv_usec < wait->tv_usec) {
3148 if (rest->tv_sec <= wait->tv_sec) {
3152 rest->tv_usec += 1000 * 1000;
3154 rest->tv_sec -= wait->tv_sec;
3155 rest->tv_usec -= wait->tv_usec;
3156 return rest->tv_sec != 0 || rest->tv_usec != 0;
3163 if (t1->tv_sec < t2->tv_sec)
3165 if (t1->tv_sec > t2->tv_sec)
3167 if (t1->tv_usec < t2->tv_usec)
3169 if (t1->tv_usec > t2->tv_usec)
3176int rb_w32_check_interrupt(
void *);
3181rb_w32_select_with_thread(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3182 struct timeval *timeout,
void *th)
3191 struct timeval limit = {0, 0};
3193 if (nfds < 0 || (timeout && (timeout->tv_sec < 0 || timeout->tv_usec < 0))) {
3199 if (timeout->tv_sec < 0 ||
3200 timeout->tv_usec < 0 ||
3201 timeout->tv_usec >= 1000000) {
3205 gettimeofday(&limit, NULL);
3206 limit.tv_sec += timeout->tv_sec;
3207 limit.tv_usec += timeout->tv_usec;
3208 if (limit.tv_usec >= 1000000) {
3209 limit.tv_usec -= 1000000;
3221 nonsock += extract_fd(&else_rd, rd, is_not_socket);
3224 nonsock += extract_fd(&else_wr, wr, is_not_socket);
3227 if (extract_fd(NULL, else_rd.
fdset, is_invalid_handle) > 0 ||
3228 extract_fd(NULL, else_wr.
fdset, is_invalid_handle) > 0) {
3236 extract_fd(&pipe_rd, else_rd.
fdset, is_pipe);
3239 extract_fd(&cons_rd, else_rd.
fdset, is_console);
3242 extract_fd(&except, ex, is_not_socket);
3245 if (rd && (
int)rd->fd_count > r) r = (int)rd->fd_count;
3246 if (wr && (
int)wr->fd_count > r) r = (int)wr->fd_count;
3247 if (ex && (
int)ex->fd_count > r) r = (int)ex->fd_count;
3248 if (nfds > r) nfds = r;
3252 const struct timeval wait = {0, 10 * 1000};
3255 UINT nrd = rd ? rd->fd_count : 0;
3256 UINT nwr = wr ? wr->fd_count : 0;
3257 UINT nex = ex ? ex->fd_count : 0;
3258 SOCKET *orig =
ALLOC_N(SOCKET, nrd + nwr + nex);
3261 save_fd(orig + nrd, wr);
3262 save_fd(orig + nrd + nwr, ex);
3264 if (th && rb_w32_check_interrupt(th) != WAIT_TIMEOUT) {
3271 extract_fd(&else_rd, pipe_rd.
fdset, is_readable_pipe);
3272 extract_fd(&else_rd, cons_rd.
fdset, is_readable_console);
3275 if (else_rd.
fdset->fd_count || else_wr.
fdset->fd_count) {
3276 r = do_select(nfds, rd, wr, ex, &zero);
3279 r += copy_fd(rd, else_rd.
fdset);
3280 r += copy_fd(wr, else_wr.
fdset);
3286 const struct timeval *dowait = &wait;
3288 r = do_select(nfds, rd, wr, ex, &zero);
3293 gettimeofday(&now, NULL);
3295 if (!rb_w32_time_subtract(&rest, &now))
break;
3296 if (compare(&rest, &wait) < 0) dowait = &rest;
3298 restore_fd(rd, orig, nrd);
3299 restore_fd(wr, orig + nrd, nwr);
3300 restore_fd(ex, orig + nrd + nwr, nex);
3301 Sleep(dowait->tv_sec * 1000 + (dowait->tv_usec + 999) / 1000);
3304 ruby_xfree_sized(orig,
sizeof(SOCKET) * (nrd + nwr + nex));
3318rb_w32_select(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3321 return rb_w32_select_with_thread(nfds, rd, wr, ex, timeout, 0);
3326get_wsa_extension_function(SOCKET s, GUID guid)
3331 WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid,
sizeof(guid),
3332 &ptr,
sizeof(ptr), &dmy, NULL, NULL);
3342rb_w32_accept(
int s,
struct sockaddr *addr,
int *addrlen)
3348 r = accept(TO_SOCKET(s), addr, addrlen);
3349 if (r != INVALID_SOCKET) {
3350 SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0);
3351 fd = rb_w32_open_osfhandle((intptr_t)r, O_RDWR|O_BINARY|O_NOINHERIT);
3353 socklist_insert(r, 0);
3358 errno = map_errno(WSAGetLastError());
3369rb_w32_bind(
int s,
const struct sockaddr *addr,
int addrlen)
3374 r = bind(TO_SOCKET(s), addr, addrlen);
3375 if (r == SOCKET_ERROR)
3376 errno = map_errno(WSAGetLastError());
3385rb_w32_connect(
int s,
const struct sockaddr *addr,
int addrlen)
3389 r = connect(TO_SOCKET(s), addr, addrlen);
3390 if (r == SOCKET_ERROR) {
3391 int err = WSAGetLastError();
3392 if (err != WSAEWOULDBLOCK)
3393 errno = map_errno(err);
3395 errno = EINPROGRESS;
3406rb_w32_getpeername(
int s,
struct sockaddr *addr,
int *addrlen)
3410 r = getpeername(TO_SOCKET(s), addr, addrlen);
3411 if (r == SOCKET_ERROR)
3412 errno = map_errno(WSAGetLastError());
3421rb_w32_getsockname(
int fd,
struct sockaddr *addr,
int *addrlen)
3426 sock = TO_SOCKET(fd);
3427 r = getsockname(sock, addr, addrlen);
3428 if (r == SOCKET_ERROR) {
3429 DWORD wsaerror = WSAGetLastError();
3430 if (wsaerror == WSAEINVAL) {
3432 if (socklist_lookup(sock, &flags)) {
3433 int af = GET_FAMILY(flags);
3435 memset(addr, 0, *addrlen);
3436 addr->sa_family = af;
3441 errno = map_errno(wsaerror);
3451rb_w32_getsockopt(
int s,
int level,
int optname,
char *optval,
int *optlen)
3455 r = getsockopt(TO_SOCKET(s), level, optname, optval, optlen);
3456 if (r == SOCKET_ERROR)
3457 errno = map_errno(WSAGetLastError());
3461 if (r == 0 && level == SOL_SOCKET && optname == SO_ERROR &&
3462 *optlen == (
int)
sizeof(
int)) {
3464 memcpy(&sockerr, optval,
sizeof(sockerr));
3465 sockerr = map_errno(sockerr);
3466 memcpy(optval, &sockerr,
sizeof(sockerr));
3475rb_w32_ioctlsocket(
int s,
long cmd, u_long *argp)
3479 r = ioctlsocket(TO_SOCKET(s), cmd, argp);
3480 if (r == SOCKET_ERROR)
3481 errno = map_errno(WSAGetLastError());
3490rb_w32_listen(
int s,
int backlog)
3494 r = listen(TO_SOCKET(s), backlog);
3495 if (r == SOCKET_ERROR)
3496 errno = map_errno(WSAGetLastError());
3508finish_overlapped_socket(BOOL input, SOCKET s, WSAOVERLAPPED *wol,
int result, DWORD *
len, DWORD size)
3513 if (result != SOCKET_ERROR)
3515 else if ((err = WSAGetLastError()) == WSA_IO_PENDING) {
3516 switch (rb_w32_wait_events_blocking(&wol->hEvent, 1, INFINITE)) {
3519 result = WSAGetOverlappedResult(s, wol, &size, TRUE, &flg);
3526 result = SOCKET_ERROR;
3529 if ((err = WSAGetLastError()) == WSAECONNABORTED && !input)
3531 else if (err == WSAEMSGSIZE && input) {
3537 errno = map_errno(err);
3539 case WAIT_OBJECT_0 + 1:
3542 CancelIo((HANDLE)s);
3547 if (err == WSAECONNABORTED && !input)
3550 errno = map_errno(err);
3553 CloseHandle(wol->hEvent);
3560overlapped_socket_io(BOOL input,
int fd,
char *buf,
int len,
int flags,
3561 struct sockaddr *addr,
int *addrlen)
3572 socklist_lookup(s, &mode);
3573 if (GET_FLAGS(mode) & O_NONBLOCK) {
3576 if (addr && addrlen)
3577 r = recvfrom(s, buf,
len, flags, addr, addrlen);
3579 r = recv(s, buf,
len, flags);
3580 if (r == SOCKET_ERROR)
3581 errno = map_errno(WSAGetLastError());
3584 if (addr && addrlen)
3585 r = sendto(s, buf,
len, flags, addr, *addrlen);
3587 r = send(s, buf,
len, flags);
3588 if (r == SOCKET_ERROR) {
3589 DWORD err = WSAGetLastError();
3590 if (err == WSAECONNABORTED)
3593 errno = map_errno(err);
3603 memset(&wol, 0,
sizeof(wol));
3605 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3608 if (addr && addrlen)
3609 ret = WSARecvFrom(s, &wbuf, 1, &size, &flg, addr, addrlen,
3612 ret = WSARecv(s, &wbuf, 1, &size, &flg, &wol, NULL);
3615 if (addr && addrlen)
3616 ret = WSASendTo(s, &wbuf, 1, &size, flags, addr, *addrlen,
3619 ret = WSASend(s, &wbuf, 1, &size, flags, &wol, NULL);
3623 finish_overlapped_socket(input, s, &wol, ret, &rlen, size);
3632rb_w32_recv(
int fd,
char *buf,
int len,
int flags)
3634 return overlapped_socket_io(TRUE, fd, buf,
len, flags, NULL, NULL);
3639rb_w32_recvfrom(
int fd,
char *buf,
int len,
int flags,
3640 struct sockaddr *from,
int *fromlen)
3642 return overlapped_socket_io(TRUE, fd, buf,
len, flags, from, fromlen);
3647rb_w32_send(
int fd,
const char *buf,
int len,
int flags)
3649 return overlapped_socket_io(FALSE, fd, (
char *)buf,
len, flags, NULL, NULL);
3654rb_w32_sendto(
int fd,
const char *buf,
int len,
int flags,
3655 const struct sockaddr *to,
int tolen)
3657 return overlapped_socket_io(FALSE, fd, (
char *)buf,
len, flags,
3658 (
struct sockaddr *)to, &tolen);
3661#if !defined(MSG_TRUNC) && !defined(__MINGW32__)
3667 DWORD dwBufferCount;
3672#ifndef WSAID_WSARECVMSG
3673#define WSAID_WSARECVMSG {0xf689d7c8,0x6f1f,0x436b,{0x8a,0x53,0xe5,0x4f,0xe3,0x51,0xc3,0x22}}
3675#ifndef WSAID_WSASENDMSG
3676#define WSAID_WSASENDMSG {0xa441e712,0x754f,0x43ca,{0x84,0xa7,0x0d,0xee,0x44,0xcf,0x60,0x6d}}
3680#define msghdr_to_wsamsg(msg, wsamsg) \
3683 (wsamsg)->name = (msg)->msg_name; \
3684 (wsamsg)->namelen = (msg)->msg_namelen; \
3685 (wsamsg)->lpBuffers = ALLOCA_N(WSABUF, (msg)->msg_iovlen); \
3686 (wsamsg)->dwBufferCount = (msg)->msg_iovlen; \
3687 for (i = 0; i < (msg)->msg_iovlen; ++i) { \
3688 (wsamsg)->lpBuffers[i].buf = (msg)->msg_iov[i].iov_base; \
3689 (wsamsg)->lpBuffers[i].len = (msg)->msg_iov[i].iov_len; \
3691 (wsamsg)->Control.buf = (msg)->msg_control; \
3692 (wsamsg)->Control.len = (msg)->msg_controllen; \
3693 (wsamsg)->dwFlags = (msg)->msg_flags; \
3698recvmsg(
int fd,
struct msghdr *msg,
int flags)
3700 typedef int (WSAAPI *WSARecvMsg_t)(SOCKET,
WSAMSG *, DWORD *, WSAOVERLAPPED *, LPWSAOVERLAPPED_COMPLETION_ROUTINE);
3701 static WSARecvMsg_t pWSARecvMsg = NULL;
3711 static const GUID guid = WSAID_WSARECVMSG;
3712 pWSARecvMsg = (WSARecvMsg_t)get_wsa_extension_function(s, guid);
3717 msghdr_to_wsamsg(msg, &wsamsg);
3718 wsamsg.dwFlags |= flags;
3720 socklist_lookup(s, &mode);
3721 if (GET_FLAGS(mode) & O_NONBLOCK) {
3723 if ((ret = pWSARecvMsg(s, &wsamsg, &
len, NULL, NULL)) == SOCKET_ERROR) {
3724 errno = map_errno(WSAGetLastError());
3732 memset(&wol, 0,
sizeof(wol));
3734 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3735 ret = pWSARecvMsg(s, &wsamsg, &size, &wol, NULL);
3738 ret = finish_overlapped_socket(TRUE, s, &wol, ret, &
len, size);
3740 if (ret == SOCKET_ERROR)
3744 msg->msg_name = wsamsg.name;
3745 msg->msg_namelen = wsamsg.namelen;
3746 msg->msg_flags = wsamsg.dwFlags;
3753sendmsg(
int fd,
const struct msghdr *msg,
int flags)
3755 typedef int (WSAAPI *WSASendMsg_t)(SOCKET,
const WSAMSG *, DWORD, DWORD *, WSAOVERLAPPED *, LPWSAOVERLAPPED_COMPLETION_ROUTINE);
3756 static WSASendMsg_t pWSASendMsg = NULL;
3766 static const GUID guid = WSAID_WSASENDMSG;
3767 pWSASendMsg = (WSASendMsg_t)get_wsa_extension_function(s, guid);
3772 msghdr_to_wsamsg(msg, &wsamsg);
3774 socklist_lookup(s, &mode);
3775 if (GET_FLAGS(mode) & O_NONBLOCK) {
3777 if ((ret = pWSASendMsg(s, &wsamsg, flags, &
len, NULL, NULL)) == SOCKET_ERROR) {
3778 errno = map_errno(WSAGetLastError());
3786 memset(&wol, 0,
sizeof(wol));
3788 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3789 ret = pWSASendMsg(s, &wsamsg, flags, &size, &wol, NULL);
3792 finish_overlapped_socket(FALSE, s, &wol, ret, &
len, size);
3802rb_w32_setsockopt(
int s,
int level,
int optname,
const char *optval,
int optlen)
3806 r = setsockopt(TO_SOCKET(s), level, optname, optval, optlen);
3807 if (r == SOCKET_ERROR)
3808 errno = map_errno(WSAGetLastError());
3817rb_w32_shutdown(
int s,
int how)
3821 r = shutdown(TO_SOCKET(s), how);
3822 if (r == SOCKET_ERROR)
3823 errno = map_errno(WSAGetLastError());
3830open_ifs_socket(
int af,
int type,
int protocol)
3832 unsigned long proto_buffers_len = 0;
3834 SOCKET out = INVALID_SOCKET;
3836 if (WSAEnumProtocols(NULL, NULL, &proto_buffers_len) == SOCKET_ERROR) {
3837 error_code = WSAGetLastError();
3838 if (error_code == WSAENOBUFS) {
3839 WSAPROTOCOL_INFO *proto_buffers;
3840 int protocols_available = 0;
3842 proto_buffers = (WSAPROTOCOL_INFO *)malloc(proto_buffers_len);
3843 if (!proto_buffers) {
3844 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
3845 return INVALID_SOCKET;
3848 protocols_available =
3849 WSAEnumProtocols(NULL, proto_buffers, &proto_buffers_len);
3850 if (protocols_available != SOCKET_ERROR) {
3852 for (i = 0; i < protocols_available; i++) {
3853 if ((af != AF_UNSPEC && af != proto_buffers[i].iAddressFamily) ||
3854 (
type != proto_buffers[i].iSocketType) ||
3855 (protocol != 0 && protocol != proto_buffers[i].iProtocol))
3858 if ((proto_buffers[i].dwServiceFlags1 & XP1_IFS_HANDLES) == 0)
3861 out = WSASocket(af,
type, protocol, &(proto_buffers[i]), 0,
3862 WSA_FLAG_OVERLAPPED);
3865 if (out == INVALID_SOCKET)
3866 out = WSASocket(af,
type, protocol, NULL, 0, 0);
3867 if (out != INVALID_SOCKET)
3868 SetHandleInformation((HANDLE)out, HANDLE_FLAG_INHERIT, 0);
3871 free(proto_buffers);
3882rb_w32_socket(
int af,
int type,
int protocol)
3888 s = open_ifs_socket(af,
type, protocol);
3889 if (s == INVALID_SOCKET) {
3890 errno = map_errno(WSAGetLastError());
3894 fd = rb_w32_open_osfhandle(s, O_RDWR|O_BINARY|O_NOINHERIT);
3896 socklist_insert(s, MAKE_SOCKDATA(af, 0));
3907struct hostent * WSAAPI
3908rb_w32_gethostbyaddr(
const char *addr,
int len,
int type)
3912 r = gethostbyaddr(addr,
len,
type);
3914 errno = map_errno(WSAGetLastError());
3922struct hostent * WSAAPI
3923rb_w32_gethostbyname(
const char *name)
3927 r = gethostbyname(name);
3929 errno = map_errno(WSAGetLastError());
3938rb_w32_gethostname(
char *name,
int len)
3942 r = gethostname(name,
len);
3943 if (r == SOCKET_ERROR)
3944 errno = map_errno(WSAGetLastError());
3949#undef getprotobyname
3952struct protoent * WSAAPI
3953rb_w32_getprotobyname(
const char *name)
3957 r = getprotobyname(name);
3959 errno = map_errno(WSAGetLastError());
3964#undef getprotobynumber
3967struct protoent * WSAAPI
3968rb_w32_getprotobynumber(
int num)
3972 r = getprotobynumber(num);
3974 errno = map_errno(WSAGetLastError());
3982struct servent * WSAAPI
3983rb_w32_getservbyname(
const char *name,
const char *proto)
3987 r = getservbyname(name, proto);
3989 errno = map_errno(WSAGetLastError());
3997struct servent * WSAAPI
3998rb_w32_getservbyport(
int port,
const char *proto)
4002 r = getservbyport(port, proto);
4004 errno = map_errno(WSAGetLastError());
4013socketpair_unix_path(
struct sockaddr_un *sock_un, WCHAR *wpath,
const int maxpath)
4020 listener = socket(AF_UNIX, SOCK_STREAM, 0);
4021 if (listener == INVALID_SOCKET) {
4022 errno = EAFNOSUPPORT;
4026 memset(sock_un, 0,
sizeof(*sock_un));
4027 sock_un->sun_family = AF_UNIX;
4037 for (
int try = 0; ;
try++) {
4038 LARGE_INTEGER ticks;
4040 static const WCHAR FALLBACK_TEMP[] = L
"C:/Temp/";
4041 static const int FALLBACK_TEMP_SIZE = numberof(FALLBACK_TEMP) - 1;
4046 path_len = GetTempPathW(maxpath, wpath);
4047 if (path_len == 0 || path_len >= maxpath) {
4056 if (FALLBACK_TEMP_SIZE >= maxpath)
continue;
4057 wcsncpy(wpath, FALLBACK_TEMP, maxpath);
4058 path_len = FALLBACK_TEMP_SIZE;
4065 closesocket(listener);
4066 errno = EADDRNOTAVAIL;
4071 int un_len = WideCharToMultiByte(CP_UTF8, 0, wpath, path_len, sock_un->sun_path, maxpath, NULL, NULL);
4072 QueryPerformanceCounter(&ticks);
4073 int base_len = snprintf(sock_un->sun_path + un_len,
4077 GetCurrentProcessId());
4078 if (un_len + base_len >= maxpath)
continue;
4081 MultiByteToWideChar(CP_UTF8, 0, sock_un->sun_path + un_len, base_len + 1, wpath + path_len, maxpath - path_len);
4083 if (bind(listener, (
struct sockaddr *)sock_un,
sizeof(*sock_un)) != SOCKET_ERROR)
4086 closesocket(listener);
4088 return sizeof(*sock_un);
4094socketpair_internal(
int af,
int type,
int protocol, SOCKET *sv)
4096 SOCKET svr = INVALID_SOCKET, r = INVALID_SOCKET, w = INVALID_SOCKET;
4097 struct sockaddr_in sock_in4;
4100 struct sockaddr_in6 sock_in6;
4104 struct sockaddr_un sock_un = {0, {0}};
4105 WCHAR wpath[
sizeof(sock_un.sun_path)/
sizeof(*sock_un.sun_path)] = L
"";
4108 struct sockaddr *addr;
4114#if defined PF_INET && PF_INET != AF_INET
4117 sock_in4.sin_family = AF_INET;
4118 sock_in4.sin_port = 0;
4119 sock_in4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4120 addr = (
struct sockaddr *)&sock_in4;
4121 len =
sizeof(sock_in4);
4125 memset(&sock_in6, 0,
sizeof(sock_in6));
4126 sock_in6.sin6_family = AF_INET6;
4127 sock_in6.sin6_addr = IN6ADDR_LOOPBACK_INIT;
4128 addr = (
struct sockaddr *)&sock_in6;
4129 len =
sizeof(sock_in6);
4134 addr = (
struct sockaddr *)&sock_un;
4135 len = socketpair_unix_path(&sock_un, wpath, numberof(wpath));
4136 if (!
len)
return -1;
4140 errno = EAFNOSUPPORT;
4143 if (
type != SOCK_STREAM) {
4148 sv[0] = (SOCKET)INVALID_HANDLE_VALUE;
4149 sv[1] = (SOCKET)INVALID_HANDLE_VALUE;
4152 svr = open_ifs_socket(af,
type, protocol);
4153 if (svr == INVALID_SOCKET)
4155 if (bind(svr, addr,
len) < 0)
4157 if (getsockname(svr, addr, &
len) < 0)
4159 if (
type == SOCK_STREAM)
4162 w = open_ifs_socket(af,
type, protocol);
4163 if (w == INVALID_SOCKET)
4165 if (connect(w, addr,
len) < 0)
4168 r = accept(svr, addr, &
len);
4169 if (r == INVALID_SOCKET)
4171 SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0);
4177 errno = map_errno(WSAGetLastError());
4178 if (r != INVALID_SOCKET)
4180 if (w != INVALID_SOCKET)
4187 if (svr != INVALID_SOCKET)
4190 if (sock_un.sun_family == AF_UNIX)
4200socketpair(
int af,
int type,
int protocol,
int *sv)
4204 if (socketpair_internal(af,
type, protocol, pair) < 0)
4206 sv[0] = rb_w32_open_osfhandle(pair[0], O_RDWR|O_BINARY|O_NOINHERIT);
4208 closesocket(pair[0]);
4209 closesocket(pair[1]);
4212 sv[1] = rb_w32_open_osfhandle(pair[1], O_RDWR|O_BINARY|O_NOINHERIT);
4214 rb_w32_close(sv[0]);
4215 closesocket(pair[1]);
4218 socklist_insert(pair[0], MAKE_SOCKDATA(af, 0));
4219 socklist_insert(pair[1], MAKE_SOCKDATA(af, 0));
4226str2guid(
const char *str, GUID *guid)
4228#define hex2byte(str) \
4229 ((isdigit(*(str)) ? *(str) - '0' : toupper(*(str)) - 'A' + 10) << 4 | (isdigit(*((str) + 1)) ? *((str) + 1) - '0' : toupper(*((str) + 1)) - 'A' + 10))
4232 if (*str ==
'{') str++;
4233 guid->Data1 = (long)strtoul(str, &end, 16);
4235 guid->Data2 = (
unsigned short)strtoul(str, &end, 16);
4237 guid->Data3 = (
unsigned short)strtoul(str, &end, 16);
4239 guid->Data4[0] = hex2byte(str);
4241 guid->Data4[1] = hex2byte(str);
4243 for (i = 0; i < 6; i++) {
4244 guid->Data4[i + 2] = hex2byte(str);
4250#ifndef HAVE_TYPE_NET_LUID
4254 uint64_t Reserved :24;
4255 uint64_t NetLuidIndex :24;
4256 uint64_t IfType :16;
4262getifaddrs(
struct ifaddrs **ifap)
4266 IP_ADAPTER_ADDRESSES *root, *addr;
4269 ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, NULL, &size);
4270 if (ret != ERROR_BUFFER_OVERFLOW) {
4271 errno = map_errno(ret);
4274 root = ruby_xmalloc(size);
4275 ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, root, &size);
4276 if (ret != ERROR_SUCCESS) {
4277 errno = map_errno(ret);
4282 for (prev = NULL, addr = root; addr; addr = addr->Next) {
4283 struct ifaddrs *ifa = ruby_xcalloc(1,
sizeof(*ifa));
4284 char name[IFNAMSIZ];
4289 prev->ifa_next = ifa;
4293 str2guid(addr->AdapterName, &guid);
4294 if (ConvertInterfaceGuidToLuid(&guid, &luid) == NO_ERROR &&
4295 ConvertInterfaceLuidToNameA(&luid, name,
sizeof(name)) == NO_ERROR) {
4302 if (addr->IfType & IF_TYPE_SOFTWARE_LOOPBACK)
4303 ifa->ifa_flags |= IFF_LOOPBACK;
4304 if (addr->OperStatus == IfOperStatusUp) {
4305 ifa->ifa_flags |= IFF_UP;
4307 if (addr->FirstUnicastAddress) {
4308 IP_ADAPTER_UNICAST_ADDRESS *cur;
4310 for (cur = addr->FirstUnicastAddress; cur; cur = cur->Next) {
4311 if (cur->Flags & IP_ADAPTER_ADDRESS_TRANSIENT ||
4312 cur->DadState == IpDadStateDeprecated) {
4317 ifa = ruby_xcalloc(1,
sizeof(*ifa));
4318 prev->ifa_next = ifa;
4320 ifa->ifa_flags = prev->ifa_flags;
4322 ifa->ifa_addr = ruby_xmalloc(cur->Address.iSockaddrLength);
4323 memcpy(ifa->ifa_addr, cur->Address.lpSockaddr,
4324 cur->Address.iSockaddrLength);
4339freeifaddrs(
struct ifaddrs *ifp)
4342 struct ifaddrs *next = ifp->ifa_next;
4343 ruby_xfree(ifp->ifa_addr);
4344 ruby_xfree(ifp->ifa_name);
4355void endhostent(
void) {}
4356void endnetent(
void) {}
4357void endprotoent(
void) {}
4358void endservent(
void) {}
4360struct netent *getnetent (
void) {
return (
struct netent *) NULL;}
4362struct netent *getnetbyaddr(
long net,
int type) {
return (
struct netent *)NULL;}
4364struct netent *getnetbyname(
const char *name) {
return (
struct netent *)NULL;}
4366struct protoent *getprotoent (
void) {
return (
struct protoent *) NULL;}
4368struct servent *getservent (
void) {
return (
struct servent *) NULL;}
4370void sethostent (
int stayopen) {}
4372void setnetent (
int stayopen) {}
4374void setprotoent (
int stayopen) {}
4376void setservent (
int stayopen) {}
4379int rb_w32_set_nonblock2(
int fd,
int nonblock);
4383setfl(SOCKET sock,
int arg)
4390 socklist_lookup(sock, &flag);
4391 af = GET_FAMILY(flag);
4392 flag = GET_FLAGS(flag);
4393 if (arg & O_NONBLOCK) {
4398 flag &= ~O_NONBLOCK;
4402 ret = ioctlsocket(sock, FIONBIO, &ioctlArg);
4404 socklist_insert(sock, MAKE_SOCKDATA(af, flag));
4406 errno = map_errno(WSAGetLastError());
4414dupfd(HANDLE hDup,
int flags,
int minfd)
4422 ret = _open_osfhandle((intptr_t)hDup, flags | FOPEN);
4424 goto close_fds_and_return;
4427 goto close_fds_and_return;
4429 fds[filled++] = ret;
4430 }
while (filled < (
int)numberof(fds));
4432 ret = dupfd(hDup, flags, minfd);
4434 close_fds_and_return:
4436 while (filled > 0) {
4437 int fd = fds[--filled];
4438 _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE);
4448fcntl(
int fd,
int cmd, ...)
4457 arg = va_arg(va,
int);
4459 return rb_w32_set_nonblock2(fd, arg);
4461 case F_DUPFD:
case F_DUPFD_CLOEXEC: {
4465 if (!(DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
4466 GetCurrentProcess(), &hDup, 0L,
4467 cmd == F_DUPFD && !(flag & FNOINHERIT),
4468 DUPLICATE_SAME_ACCESS))) {
4469 errno = map_errno(GetLastError());
4474 arg = va_arg(va,
int);
4480 flag &= ~FNOINHERIT;
4481 if ((ret = dupfd(hDup, flag, arg)) == -1)
4487 if (h == -1)
return -1;
4488 if (!GetHandleInformation((HANDLE)h, &flag)) {
4489 errno = map_errno(GetLastError());
4492 return (flag & HANDLE_FLAG_INHERIT) ? 0 : FD_CLOEXEC;
4496 if (h == -1)
return -1;
4498 arg = va_arg(va,
int);
4500 if (!SetHandleInformation((HANDLE)h, HANDLE_FLAG_INHERIT,
4501 (arg & FD_CLOEXEC) ? 0 : HANDLE_FLAG_INHERIT)) {
4502 errno = map_errno(GetLastError());
4505 if (arg & FD_CLOEXEC)
4506 _osfile(fd) |= FNOINHERIT;
4508 _osfile(fd) &= ~FNOINHERIT;
4519rb_w32_set_nonblock2(
int fd,
int nonblock)
4521 SOCKET sock = TO_SOCKET(fd);
4522 if (is_socket(sock)) {
4523 return setfl(sock, nonblock ? O_NONBLOCK : 0);
4525 else if (is_pipe(sock)) {
4527 if (!GetNamedPipeHandleState((HANDLE)sock, &state, NULL, NULL, NULL, NULL, 0)) {
4528 errno = map_errno(GetLastError());
4532 state |= PIPE_NOWAIT;
4535 state &= ~PIPE_NOWAIT;
4537 if (!SetNamedPipeHandleState((HANDLE)sock, &state, NULL, NULL)) {
4538 errno = map_errno(GetLastError());
4550rb_w32_set_nonblock(
int fd)
4552 return rb_w32_set_nonblock2(fd, TRUE);
4561poll_child_status(
struct ChildRecord *child,
int *stat_loc)
4566 if (!GetExitCodeProcess(child->hProcess, &exitcode)) {
4568 err = GetLastError();
4570 case ERROR_INVALID_PARAMETER:
4573 case ERROR_INVALID_HANDLE:
4577 errno = map_errno(err);
4581 CloseChildHandle(child);
4584 if (exitcode != STILL_ACTIVE) {
4587 if (rb_w32_wait_events_blocking(&child->hProcess, 1, INFINITE) != WAIT_OBJECT_0) {
4591 CloseChildHandle(child);
4593 *stat_loc = exitcode << 8;
4594 if (exitcode & 0xC0000000) {
4595 static const struct {
4599 {STATUS_ACCESS_VIOLATION, SIGSEGV},
4600 {STATUS_ILLEGAL_INSTRUCTION, SIGILL},
4601 {STATUS_PRIVILEGED_INSTRUCTION, SIGILL},
4602 {STATUS_FLOAT_DENORMAL_OPERAND, SIGFPE},
4603 {STATUS_FLOAT_DIVIDE_BY_ZERO, SIGFPE},
4604 {STATUS_FLOAT_INEXACT_RESULT, SIGFPE},
4605 {STATUS_FLOAT_INVALID_OPERATION, SIGFPE},
4606 {STATUS_FLOAT_OVERFLOW, SIGFPE},
4607 {STATUS_FLOAT_STACK_CHECK, SIGFPE},
4608 {STATUS_FLOAT_UNDERFLOW, SIGFPE},
4609#ifdef STATUS_FLOAT_MULTIPLE_FAULTS
4610 {STATUS_FLOAT_MULTIPLE_FAULTS, SIGFPE},
4612#ifdef STATUS_FLOAT_MULTIPLE_TRAPS
4613 {STATUS_FLOAT_MULTIPLE_TRAPS, SIGFPE},
4615 {STATUS_CONTROL_C_EXIT, SIGINT},
4618 for (i = 0; i < (int)numberof(table); i++) {
4619 if (table[i].status == exitcode) {
4620 *stat_loc |= table[i].sig;
4625 if (i >= (
int)numberof(table))
4626 *stat_loc |= SIGSEGV;
4636waitpid(rb_pid_t pid,
int *stat_loc,
int options)
4641 if (options == WNOHANG) {
4652 HANDLE events[MAXCHILDNUM];
4655 FOREACH_CHILD(child) {
4656 if (!child->pid || child->pid < 0)
continue;
4657 if ((pid = poll_child_status(child, stat_loc)))
return pid;
4658 events[count++] = child->hProcess;
4659 } END_FOREACH_CHILD;
4665 ret = rb_w32_wait_events_blocking(events, count, timeout);
4666 if (ret == WAIT_TIMEOUT)
return 0;
4667 if ((ret -= WAIT_OBJECT_0) == count) {
4671 errno = map_errno(GetLastError());
4675 cause = FindChildSlotByHandle(events[ret]);
4680 return poll_child_status(cause, stat_loc);
4690 while (!(pid = poll_child_status(child, stat_loc))) {
4692 int ret = rb_w32_wait_events_blocking(&child->hProcess, 1, timeout);
4693 if (ret == WAIT_OBJECT_0 + 1)
return -1;
4694 if (ret != WAIT_OBJECT_0) {
4696 if (options & WNOHANG) {
4703 if (pid == -1 && retried) pid = 0;
4709#include <sys/timeb.h>
4712#define filetime_unit (10UL * 1000 * 1000)
4713#define filetime_diff_days ((1970-1601)*3652425UL/10000)
4714#define filetime_diff_secs (filetime_diff_days * (24ULL * 60 * 60))
4715#define unix_to_filetime(sec) (((sec) + filetime_diff_secs) * filetime_unit)
4716static const ULONGLONG filetime_unix_offset = unix_to_filetime(0ULL);
4717static const unsigned long secs_in_ns = 1000000000UL;
4729li_time_split(ULONGLONG lt,
long *subsec)
4735 lt -= filetime_unix_offset;
4737 *subsec = (long)(lt % filetime_unit);
4738 return (time_t)(lt / filetime_unit);
4743li_time_split_ns(ULONGLONG lt,
long *ns)
4746 time_t t = li_time_split(lt, &subsec);
4749 if (t < 0)
return 0;
4755filetime_to_li_time(
const FILETIME* ft)
4758 return fi.i.QuadPart;
4768 GetSystemTimePreciseAsFileTime(&ft);
4769 tv->tv_sec = li_time_split(filetime_to_li_time(&ft), &subsec);
4770 tv->tv_usec = subsec / 10;
4777filetime_to_unixtime(
const FILETIME *ft)
4780 time_t t = li_time_split(filetime_to_li_time(ft), &subsec);
4782 if (t < 0)
return 0;
4788filetime_split_ns(
const FILETIME *ft,
long *ns)
4790 return li_time_split_ns(filetime_to_li_time(ft), ns);
4795filetime_to_timespec(FILETIME ft,
struct timespec *sp)
4797 sp->tv_sec = filetime_split_ns(&ft, &sp->tv_nsec);
4802clock_gettime(clockid_t clock_id,
struct timespec *sp)
4805 case CLOCK_REALTIME:
4806 case CLOCK_REALTIME_COARSE:
4810 GetSystemTimePreciseAsFileTime(&ft);
4811 filetime_to_timespec(ft, sp);
4814 case CLOCK_MONOTONIC:
4817 LARGE_INTEGER count;
4818 if (UNLIKELY(!QueryPerformanceFrequency(&freq))) {
4819 errno = map_errno(GetLastError());
4822 if (UNLIKELY(!QueryPerformanceCounter(&count))) {
4823 errno = map_errno(GetLastError());
4826 sp->tv_sec = count.QuadPart / freq.QuadPart;
4827 if (freq.QuadPart < secs_in_ns)
4828 sp->tv_nsec = (count.QuadPart % freq.QuadPart) * secs_in_ns / freq.QuadPart;
4830 sp->tv_nsec = (long)((count.QuadPart % freq.QuadPart) * ((double)secs_in_ns / freq.QuadPart));
4833 case CLOCK_PROCESS_CPUTIME_ID:
4834 case CLOCK_THREAD_CPUTIME_ID:
4838 if (clock_id == CLOCK_PROCESS_CPUTIME_ID) {
4839 ok = GetProcessTimes(GetCurrentProcess(), &c.ft, &e.ft, &k.ft, &u.ft);
4842 ok = GetThreadTimes(GetCurrentThread(), &c.ft, &e.ft, &k.ft, &u.ft);
4844 if (UNLIKELY(!ok)) {
4845 errno = map_errno(GetLastError());
4848 total.i.QuadPart = k.i.QuadPart + u.i.QuadPart;
4849 filetime_to_timespec(total.ft, sp);
4860clock_getres(clockid_t clock_id,
struct timespec *sp)
4863 case CLOCK_REALTIME:
4864 case CLOCK_REALTIME_COARSE:
4870 case CLOCK_MONOTONIC:
4873 if (!QueryPerformanceFrequency(&freq)) {
4874 errno = map_errno(GetLastError());
4878 sp->tv_nsec = (long)((
double)secs_in_ns / freq.QuadPart);
4881 case CLOCK_PROCESS_CPUTIME_ID:
4882 case CLOCK_THREAD_CPUTIME_ID:
4884 const int frames_in_sec = 60;
4886 sp->tv_nsec = (long)(secs_in_ns / frames_in_sec);
4897w32_getcwd(
char *buffer,
int size, UINT cp,
void *alloc(
int,
void *),
void *arg)
4902 len = GetCurrentDirectoryW(0, NULL);
4904 errno = map_errno(GetLastError());
4908 if (buffer && size <
len) {
4914 if (!GetCurrentDirectoryW(
len, p)) {
4915 errno = map_errno(GetLastError());
4919 wlen = translate_wchar(p, L
'\\', L
'/') - p + 1;
4920 len = WideCharToMultiByte(cp, 0, p, wlen, NULL, 0, NULL, NULL);
4928 buffer = (*alloc)(
len, arg);
4934 WideCharToMultiByte(cp, 0, p, wlen, buffer,
len, NULL, NULL);
4941getcwd_alloc(
int size,
void *dummy)
4943 return malloc(size);
4948rb_w32_getcwd(
char *buffer,
int size)
4950 return w32_getcwd(buffer, size, filecp(), getcwd_alloc, NULL);
4955rb_w32_ugetcwd(
char *buffer,
int size)
4957 return w32_getcwd(buffer, size, CP_UTF8, getcwd_alloc, NULL);
4962getcwd_value(
int size,
void *arg)
4965 return RSTRING_PTR(str);
4970rb_dir_getwd_ospath(
void)
4973 w32_getcwd(NULL, 0, CP_UTF8, getcwd_value, &cwd);
4979chown(
const char *path,
int owner,
int group)
4986rb_w32_uchown(
const char *path,
int owner,
int group)
4992lchown(
const char *path,
int owner,
int group)
4998rb_w32_ulchown(
const char *path,
int owner,
int group)
5005kill(rb_pid_t pid,
int sig)
5010 if (pid < 0 || (pid == 0 && sig != SIGINT)) {
5015 if ((
unsigned int)pid == GetCurrentProcessId() &&
5016 (sig != 0 && sig != SIGKILL)) {
5017 if ((ret = raise(sig)) != 0) {
5028 OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid);
5029 if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) {
5030 if (GetLastError() == ERROR_INVALID_PARAMETER) {
5046 DWORD ctrlEvent = CTRL_C_EVENT;
5050 ctrlEvent = CTRL_BREAK_EVENT;
5052 if (!GenerateConsoleCtrlEvent(ctrlEvent, (DWORD)pid)) {
5053 if ((err = GetLastError()) == 0)
5056 errno = map_errno(GetLastError());
5067 hProc = child->hProcess;
5070 hProc = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid);
5072 if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) {
5073 if (GetLastError() == ERROR_INVALID_PARAMETER) {
5083 if (!GetExitCodeProcess(hProc, &status)) {
5084 errno = map_errno(GetLastError());
5087 else if (status == STILL_ACTIVE) {
5088 if (!TerminateProcess(hProc, 0)) {
5115wlink(
const WCHAR *from,
const WCHAR *to)
5117 if (!CreateHardLinkW(to, from, NULL)) {
5118 errno = map_errno(GetLastError());
5127rb_w32_ulink(
const char *from,
const char *to)
5133 if (!(wfrom = utf8_to_wstr(from, NULL)))
5135 if (!(wto = utf8_to_wstr(to, NULL))) {
5139 ret = wlink(wfrom, wto);
5147link(
const char *from,
const char *to)
5153 if (!(wfrom = filecp_to_wstr(from, NULL)))
5155 if (!(wto = filecp_to_wstr(to, NULL))) {
5159 ret = wlink(wfrom, wto);
5166#ifndef FILE_DEVICE_FILE_SYSTEM
5167# define FILE_DEVICE_FILE_SYSTEM 0x00000009
5169#ifndef FSCTL_GET_REPARSE_POINT
5170# define FSCTL_GET_REPARSE_POINT ((0x9<<16)|(42<<2))
5172#ifndef IO_REPARSE_TAG_SYMLINK
5173# define IO_REPARSE_TAG_SYMLINK 0xA000000CL
5184 f = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5185 if (f == INVALID_HANDLE_VALUE) {
5186 return GetLastError();
5189 if (!DeviceIoControl(f, FSCTL_GET_REPARSE_POINT, NULL, 0,
5190 rp, size, &ret, NULL)) {
5193 else if (rp->ReparseTag != IO_REPARSE_TAG_SYMLINK &&
5194 rp->ReparseTag != IO_REPARSE_TAG_MOUNT_POINT) {
5195 e = ERROR_INVALID_PARAMETER;
5203rb_w32_reparse_symlink_p(
const WCHAR *path)
5211 e = rb_w32_read_reparse_point(path, rp,
sizeof(rbuf), &wbuf, &
len);
5212 if (e == ERROR_MORE_DATA) {
5213 size_t size = rb_w32_reparse_buffer_size(
len + 1);
5215 e = rb_w32_read_reparse_point(path, rp, size, &wbuf, &
len);
5220 case ERROR_MORE_DATA:
5229 size_t bufsize, WCHAR **result, DWORD *
len)
5231 int e = reparse_symlink(path, rp, bufsize);
5234 if (!e || e == ERROR_MORE_DATA) {
5236 if (rp->ReparseTag == IO_REPARSE_TAG_SYMLINK) {
5237 name = ((
char *)rp->SymbolicLinkReparseBuffer.PathBuffer +
5238 rp->SymbolicLinkReparseBuffer.PrintNameOffset);
5239 ret = rp->SymbolicLinkReparseBuffer.PrintNameLength;
5240 *
len = ret /
sizeof(WCHAR);
5242 else if (rp->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT) {
5243 static const WCHAR volume[] = L
"Volume{";
5245 name = ((
char *)rp->MountPointReparseBuffer.PathBuffer +
5246 rp->MountPointReparseBuffer.SubstituteNameOffset +
5247 volume_prefix_len *
sizeof(WCHAR));
5248 ret = rp->MountPointReparseBuffer.SubstituteNameLength;
5249 *
len = ret /
sizeof(WCHAR);
5250 ret -= volume_prefix_len *
sizeof(WCHAR);
5251 if (ret >
sizeof(volume) - 1 *
sizeof(WCHAR) &&
5252 memcmp(name, volume,
sizeof(volume) - 1 *
sizeof(WCHAR)) == 0)
5260 if ((
char *)name + ret +
sizeof(WCHAR) > (
char *)rp + bufsize)
5264 ((WCHAR *)name)[ret/
sizeof(WCHAR)] = L
'\0';
5265 translate_wchar(name, L
'\\', L
'/');
5275w32_readlink(UINT cp,
const char *path,
char *buf,
size_t bufsize)
5277 VALUE rp_buf, rp_buf_bigger = 0;
5278 DWORD
len = MultiByteToWideChar(cp, 0, path, -1, NULL, 0);
5279 size_t size = rb_w32_reparse_buffer_size(bufsize);
5281 WCHAR *wpath =
ALLOCV(rp_buf,
sizeof(WCHAR) *
len + size);
5286 MultiByteToWideChar(cp, 0, path, -1, wpath,
len);
5287 e = rb_w32_read_reparse_point(wpath, rp, size, &wname, &
len);
5288 if (e == ERROR_MORE_DATA) {
5289 size = rb_w32_reparse_buffer_size(
len + 1);
5290 rp =
ALLOCV(rp_buf_bigger, size);
5291 e = rb_w32_read_reparse_point(wpath, rp, size, &wname, &
len);
5296 errno = e == -1 ? EINVAL : map_errno(e);
5299 len = lstrlenW(wname);
5300 ret = WideCharToMultiByte(cp, 0, wname,
len, buf, bufsize, NULL, NULL);
5311rb_w32_ureadlink(
const char *path,
char *buf,
size_t bufsize)
5313 return w32_readlink(CP_UTF8, path, buf, bufsize);
5318readlink(
const char *path,
char *buf,
size_t bufsize)
5320 return w32_readlink(filecp(), path, buf, bufsize);
5323#ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5324#define SYMBOLIC_LINK_FLAG_DIRECTORY (0x1)
5326#ifndef SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
5327#define SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE (0x2)
5332w32_symlink(UINT cp,
const char *src,
const char *link)
5334 int atts, len1, len2;
5336 WCHAR *wsrc, *wlink;
5341 static DWORD create_flag = SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
5351 len1 = MultiByteToWideChar(cp, 0, src, -1, NULL, 0);
5352 len2 = MultiByteToWideChar(cp, 0, link, -1, NULL, 0);
5353 wsrc =
ALLOCV_N(WCHAR, buf, len1+len2);
5354 wlink = wsrc + len1;
5355 MultiByteToWideChar(cp, 0, src, -1, wsrc, len1);
5356 MultiByteToWideChar(cp, 0, link, -1, wlink, len2);
5357 translate_wchar(wsrc, L
'/', L
'\\');
5358 translate_wchar(wlink, L
'/', L
'\\');
5368 (((wsrc[0] >= L
'A' && wsrc[0] <= L
'Z') ||
5369 (wsrc[0] >= L
'a' && wsrc[0] <= L
'z')) && wsrc[1] == L
':') ||
5371 if (!independent && (sep = wcsrchr(wlink, L
'\\')) != NULL) {
5373 size_t dirlen = sep - wlink + 1;
5374 size_t srclen = wcslen(wsrc) + 1;
5375 WCHAR *fullsrc =
ALLOCV_N(WCHAR, buf2, dirlen + srclen);
5376 MEMCPY(fullsrc, wlink, WCHAR, dirlen);
5377 MEMCPY(fullsrc + dirlen, wsrc, WCHAR, srclen);
5378 atts = GetFileAttributesW(fullsrc);
5382 atts = GetFileAttributesW(wsrc);
5385 if (atts != -1 && atts & FILE_ATTRIBUTE_DIRECTORY)
5386 flag = SYMBOLIC_LINK_FLAG_DIRECTORY;
5387 ret = CreateSymbolicLinkW(wlink, wsrc, flag |= create_flag);
5389 (e = GetLastError()) == ERROR_INVALID_PARAMETER &&
5390 (flag & SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)) {
5392 flag &= ~SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
5393 ret = CreateSymbolicLinkW(wlink, wsrc, flag);
5394 if (!ret) e = GetLastError();
5399 errno = map_errno(e);
5407rb_w32_usymlink(
const char *src,
const char *link)
5409 return w32_symlink(CP_UTF8, src, link);
5414symlink(
const char *src,
const char *link)
5416 return w32_symlink(filecp(), src, link);
5423 return waitpid(-1, status, 0);
5428w32_getenv(
const char *name, UINT cp)
5430 WCHAR *wenvarea, *wenv;
5431 int len = strlen(name);
5432 char *env, *found = NULL;
5435 if (
len == 0)
return NULL;
5440 return getenv(name);
5443 thread_exclusive(uenvarea) {
5448 wenvarea = GetEnvironmentStringsW();
5450 map_errno(GetLastError());
5453 for (wenv = wenvarea, wlen = 1; *wenv; wenv += lstrlenW(wenv) + 1)
5454 wlen += lstrlenW(wenv) + 1;
5455 uenvarea = wstr_to_mbstr(cp, wenvarea, wlen, NULL);
5456 FreeEnvironmentStringsW(wenvarea);
5460 for (env = uenvarea; *env; env += strlen(env) + 1) {
5461 if (strncasecmp(env, name,
len) == 0 && *(env +
len) ==
'=') {
5462 found = env +
len + 1;
5473rb_w32_ugetenv(
const char *name)
5475 return w32_getenv(name, CP_UTF8);
5480rb_w32_getenv(
const char *name)
5482 return w32_getenv(name, CP_ACP);
5487get_attr_vsn(
const WCHAR *path, DWORD *atts, DWORD *vsn)
5489 BY_HANDLE_FILE_INFORMATION st = {0};
5491 HANDLE h = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5493 if (h == INVALID_HANDLE_VALUE) {
5498 if (!GetFileInformationByHandle(h, &st)) {
5503 *atts = st.dwFileAttributes;
5504 *vsn = st.dwVolumeSerialNumber;
5512wrename(
const WCHAR *oldpath,
const WCHAR *newpath)
5515 DWORD oldatts = 0, newatts = (DWORD)-1;
5516 DWORD oldvsn = 0, newvsn = 0, e;
5518 e = get_attr_vsn(oldpath, &oldatts, &oldvsn);
5520 errno = map_errno(e);
5523 if (oldatts & FILE_ATTRIBUTE_REPARSE_POINT) {
5524 HANDLE fh = open_special(oldpath, 0, 0);
5525 if (fh == INVALID_HANDLE_VALUE) {
5527 if (e == ERROR_CANT_RESOLVE_FILENAME) {
5534 get_attr_vsn(newpath, &newatts, &newvsn);
5537 if (newatts != (DWORD)-1 && newatts & FILE_ATTRIBUTE_READONLY)
5538 SetFileAttributesW(newpath, newatts & ~ FILE_ATTRIBUTE_READONLY);
5540 if (!MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED))
5544 DWORD e = GetLastError();
5545 if ((e == ERROR_ACCESS_DENIED) && (oldatts & FILE_ATTRIBUTE_DIRECTORY) &&
5549 errno = map_errno(e);
5552 SetFileAttributesW(newpath, oldatts);
5560rb_w32_urename(
const char *from,
const char *to)
5566 if (!(wfrom = utf8_to_wstr(from, NULL)))
5568 if (!(wto = utf8_to_wstr(to, NULL))) {
5572 ret = wrename(wfrom, wto);
5580rb_w32_rename(
const char *from,
const char *to)
5586 if (!(wfrom = filecp_to_wstr(from, NULL)))
5588 if (!(wto = filecp_to_wstr(to, NULL))) {
5592 ret = wrename(wfrom, wto);
5600isUNCRoot(
const WCHAR *path)
5602 if (path[0] == L
'\\' && path[1] == L
'\\') {
5603 const WCHAR *p = path + 2;
5604 if (p[0] == L
'?' && p[1] == L
'\\') {
5612 for (p++; *p; p++) {
5616 if (!p[0] || !p[1] || (p[1] == L
'.' && !p[2]))
5623#define COPY_STAT(src, dest, size_cast) do { \
5624 (dest).st_dev = (src).st_dev; \
5625 (dest).st_ino = (src).st_ino; \
5626 (dest).st_mode = (src).st_mode; \
5627 (dest).st_nlink = (src).st_nlink; \
5628 (dest).st_uid = (src).st_uid; \
5629 (dest).st_gid = (src).st_gid; \
5630 (dest).st_rdev = (src).st_rdev; \
5631 (dest).st_size = size_cast(src).st_size; \
5632 (dest).st_atime = (src).st_atime; \
5633 (dest).st_mtime = (src).st_mtime; \
5634 (dest).st_ctime = (src).st_ctime; \
5637static WCHAR *name_for_stat(WCHAR *buf,
const WCHAR *path);
5638static DWORD stati128_handle(HANDLE h,
struct stati128 *st);
5643rb_w32_fstat(
int fd,
struct stat *st)
5645 BY_HANDLE_FILE_INFORMATION info;
5646 int ret = fstat(fd, st);
5648 if (ret)
return ret;
5649 if (GetEnvironmentVariableW(L
"TZ", NULL, 0) == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND)
return ret;
5650 if (GetFileInformationByHandle((HANDLE)_get_osfhandle(fd), &info)) {
5651 st->st_atime = filetime_to_unixtime(&info.ftLastAccessTime);
5652 st->st_mtime = filetime_to_unixtime(&info.ftLastWriteTime);
5653 st->st_ctime = filetime_to_unixtime(&info.ftCreationTime);
5660rb_w32_fstati128(
int fd,
struct stati128 *st)
5663 int ret = fstat(fd, &tmp);
5665 if (ret)
return ret;
5666 COPY_STAT(tmp, *st, +);
5667 stati128_handle((HANDLE)_get_osfhandle(fd), st);
5671#if !defined FILE_INVALID_FILE_ID && !defined __MINGW32__
5673 BYTE Identifier[16];
5677#if !defined(_WIN32_WINNT_WIN8) || _WIN32_WINNT < 0x602
5678#define FileIdInfo 0x12
5689 return GetFileInformationByHandleEx(h, FileIdInfo,
id,
sizeof(*
id));
5694stati128_handle(HANDLE h,
struct stati128 *st)
5696 BY_HANDLE_FILE_INFORMATION info;
5697 DWORD attr = (DWORD)-1;
5699 if (GetFileInformationByHandle(h, &info)) {
5701 st->st_size = ((__int64)info.nFileSizeHigh << 32) | info.nFileSizeLow;
5702 st->st_atime = filetime_split_ns(&info.ftLastAccessTime, &st->st_atimensec);
5703 st->st_mtime = filetime_split_ns(&info.ftLastWriteTime, &st->st_mtimensec);
5704 st->st_ctime = filetime_split_ns(&info.ftCreationTime, &st->st_ctimensec);
5705 st->st_nlink = info.nNumberOfLinks;
5706 attr = info.dwFileAttributes;
5707 if (get_ino(h, &fii)) {
5708 st->st_ino = *((
unsigned __int64 *)&fii.FileId);
5709 st->st_inohigh = *((__int64 *)&fii.FileId + 1);
5712 st->st_ino = ((__int64)info.nFileIndexHigh << 32) | info.nFileIndexLow;
5721fileattr_to_unixmode(DWORD attr,
const WCHAR *path,
unsigned mode)
5723 if (attr & FILE_ATTRIBUTE_READONLY) {
5727 mode |= S_IREAD | S_IWRITE | S_IWUSR;
5730 if (mode & S_IFMT) {
5733 else if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
5737 else if (attr & FILE_ATTRIBUTE_DIRECTORY) {
5738 mode |= S_IFDIR | S_IEXEC;
5744 if (path && (mode & S_IFREG)) {
5745 const WCHAR *end = path + lstrlenW(path);
5746 while (path < end) {
5747 end = CharPrevW(path, end);
5749 if ((_wcsicmp(end, L
".bat") == 0) ||
5750 (_wcsicmp(end, L
".cmd") == 0) ||
5751 (_wcsicmp(end, L
".com") == 0) ||
5752 (_wcsicmp(end, L
".exe") == 0)) {
5757 if (!iswalnum(*end))
break;
5761 mode |= (mode & 0500) >> 3;
5762 mode |= (mode & 0500) >> 6;
5769check_valid_dir(
const WCHAR *path)
5771 WIN32_FIND_DATAW fd;
5773 WCHAR full[PATH_MAX];
5778 if (!(p = wcsstr(path, L
"...")))
5780 q = p + wcsspn(p, L
".");
5781 if ((p == path || wcschr(L
":/\\", *(p - 1))) &&
5782 (!*q || wcschr(L
":/\\", *q))) {
5789 DWORD
len = GetFullPathNameW(path, numberof(full), full, NULL);
5790 if (
len >= numberof(full)) {
5791 WCHAR *fullpath = malloc(
len *
sizeof(WCHAR));
5792 if (!fullpath)
return -1;
5793 len = GetFullPathNameW(path,
len, fullpath, NULL);
5798 errno = map_errno(GetLastError());
5801 if (
len == 3 && full[1] == L
':' && GetDriveTypeW(full) != DRIVE_NO_ROOT_DIR)
5804 fh = open_dir_handle(path, &fd);
5805 if (fh == INVALID_HANDLE_VALUE)
5813stat_by_find(
const WCHAR *path,
struct stati128 *st)
5816 WIN32_FIND_DATAW wfd;
5819 h = FindFirstFileW(path, &wfd);
5820 if (h == INVALID_HANDLE_VALUE) {
5821 errno = map_errno(GetLastError());
5825 st->st_mode = fileattr_to_unixmode(wfd.dwFileAttributes, path, 0);
5826 st->st_atime = filetime_split_ns(&wfd.ftLastAccessTime, &st->st_atimensec);
5827 st->st_mtime = filetime_split_ns(&wfd.ftLastWriteTime, &st->st_mtimensec);
5828 st->st_ctime = filetime_split_ns(&wfd.ftCreationTime, &st->st_ctimensec);
5829 st->st_size = ((__int64)wfd.nFileSizeHigh << 32) | wfd.nFileSizeLow;
5836path_drive(
const WCHAR *path)
5838 if (path[0] && path[1] == L
':') {
5839 if (iswalpha(path[0]))
return towupper(path[0]) - L
'A';
5840 return (
int)path[0];
5842 return _getdrive() - 1;
5845#if !defined(NTDDI_WIN11_ZN) || NTDDI_VERSION < NTDDI_WIN11_ZN
5848#define FileStatBasicByNameInfo 3
5851 LARGE_INTEGER FileId;
5852 LARGE_INTEGER CreationTime;
5853 LARGE_INTEGER LastAccessTime;
5854 LARGE_INTEGER LastWriteTime;
5855 LARGE_INTEGER ChangeTime;
5856 LARGE_INTEGER AllocationSize;
5857 LARGE_INTEGER EndOfFile;
5858 DWORD FileAttributes;
5860 DWORD NumberOfLinks;
5862 DWORD DeviceCharacteristics;
5864 LARGE_INTEGER VolumeSerialNumber;
5869#ifndef FILE_DEVICE_DISK
5870#define FILE_DEVICE_DISK 7
5873typedef BOOL (WINAPI *get_file_information_by_name_func)
5874 (PCWSTR,
int , PVOID, ULONG);
5875static get_file_information_by_name_func get_file_information_by_name =
5876 (get_file_information_by_name_func)-1;
5880large_integer_to_unixtime(
const LARGE_INTEGER *at,
long *nsecp)
5882 time_t t = li_time_split_ns(at->QuadPart, nsecp);
5883 if (t < 0)
return 0;
5889path_drive_serial(
const WCHAR *path)
5894 if (path[0] && path[1] == L
':') {
5895 if (!iswalpha(path[0]))
return 0;
5896 drive = towupper(path[0]) - L
'A';
5899 drive = _getdrive() - 1;
5901 if (drive < 0 || (
int)numberof(serials) <= drive)
return 0;
5902 if (!serials[drive]) {
5904 WCHAR root[] = L
"_:\\";
5905 root[0] = L
'A' + drive;
5906 if (get_file_information_by_name(root, FileStatBasicByNameInfo,
5907 &info,
sizeof(info)))
5908 serials[drive] = info.VolumeSerialNumber.QuadPart;
5910 return serials[drive];
5915stat_by_name(
const WCHAR *path,
struct stati128 *st)
5921 unsigned __int64 ino;
5924 if (get_file_information_by_name == (get_file_information_by_name_func)-1) {
5926 get_file_information_by_name = (get_file_information_by_name_func)
5927 get_proc_address(
"kernel32",
"GetFileInformationByName", NULL);
5929 if (!get_file_information_by_name)
return 1;
5930 if (!get_file_information_by_name(path, FileStatBasicByNameInfo,
5931 &info,
sizeof(info))) {
5932 DWORD e = GetLastError();
5934 case ERROR_FILE_NOT_FOUND:
5935 case ERROR_INVALID_NAME:
5936 case ERROR_PATH_NOT_FOUND:
5937 case ERROR_BAD_NETPATH:
5938 errno = map_errno(e);
5943 if (info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
5945 if (info.DeviceType != FILE_DEVICE_DISK)
5947 if (info.VolumeSerialNumber.QuadPart != path_drive_serial(path))
5949 ino = *((
unsigned __int64 *)&info.FileId128);
5950 inohigh = *((__int64 *)&info.FileId128 + 1);
5951 if (!ino && !inohigh)
5953 if (info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
5954 if (check_valid_dir(path))
return -1;
5957 st->st_inohigh = inohigh;
5958 st->st_size = info.EndOfFile.QuadPart;
5959 st->st_atime = large_integer_to_unixtime(&info.LastAccessTime, &st->st_atimensec);
5960 st->st_mtime = large_integer_to_unixtime(&info.LastWriteTime, &st->st_mtimensec);
5961 st->st_ctime = large_integer_to_unixtime(&info.CreationTime, &st->st_ctimensec);
5962 st->st_nlink = info.NumberOfLinks;
5963 st->st_mode = fileattr_to_unixmode(info.FileAttributes, path, 0);
5964 st->st_dev = st->st_rdev = path_drive(path);
5970winnt_stat(
const WCHAR *path,
struct stati128 *st, BOOL lstat)
5972 DWORD flags = lstat ? FILE_FLAG_OPEN_REPARSE_POINT : 0;
5974 WCHAR *finalname = 0;
5977 memset(st, 0,
sizeof(*st));
5978 switch (stat_by_name(path, st)) {
5984 f = open_special(path, 0, flags);
5985 open_error = GetLastError();
5986 if (f == INVALID_HANDLE_VALUE && !lstat) {
5988 FILE_ATTRIBUTE_TAG_INFO attr_info;
5991 f = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5992 e = GetFileInformationByHandleEx(f, FileAttributeTagInfo,
5993 &attr_info,
sizeof(attr_info));
5994 if (!e || attr_info.ReparseTag != IO_REPARSE_TAG_AF_UNIX) {
5996 f = INVALID_HANDLE_VALUE;
5999 if (f != INVALID_HANDLE_VALUE) {
6000 DWORD attr = stati128_handle(f, st);
6002 switch (GetFileType(f)) {
6003 case FILE_TYPE_CHAR:
6006 case FILE_TYPE_PIPE:
6010 if (attr & FILE_ATTRIBUTE_DIRECTORY) {
6011 if (check_valid_dir(path))
return -1;
6013 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
6014 FILE_ATTRIBUTE_TAG_INFO attr_info;
6017 e = GetFileInformationByHandleEx(f, FileAttributeTagInfo,
6018 &attr_info,
sizeof(attr_info));
6019 if (e && attr_info.ReparseTag == IO_REPARSE_TAG_AF_UNIX) {
6023 else if (rb_w32_reparse_symlink_p(path)) {
6026 mode |= S_IFLNK | S_IEXEC;
6029 mode |= S_IFDIR | S_IEXEC;
6033 const DWORD
len = get_handle_pathname(f, &finalname, 0);
6035 st->st_mode = fileattr_to_unixmode(attr, path, mode);
6038 if (wcsncmp(path, namespace_prefix, numberof(namespace_prefix)) == 0)
6039 path += numberof(namespace_prefix);
6043 switch (open_error) {
6044 case ERROR_FILE_NOT_FOUND:
6045 case ERROR_INVALID_NAME:
6046 case ERROR_PATH_NOT_FOUND:
6047 case ERROR_BAD_NETPATH:
6048 case ERROR_CANT_RESOLVE_FILENAME:
6049 errno = map_errno(open_error);
6053 if (stat_by_find(path, st))
return -1;
6056 st->st_dev = st->st_rdev = path_drive(path);
6057 if (finalname) free(finalname);
6064rb_w32_stat(
const char *path,
struct stat *st)
6068 if (w32_stati128(path, &tmp, filecp(), FALSE))
return -1;
6069 COPY_STAT(tmp, *st, (_off_t));
6075wstati128(
const WCHAR *path,
struct stati128 *st, BOOL lstat)
6085 size = lstrlenW(path) + 2;
6087 if (!(path = name_for_stat(buf1, path)))
6089 ret = winnt_stat(path, st, lstat);
6098name_for_stat(WCHAR *buf1,
const WCHAR *path)
6104 for (p = path, s = buf1; *p; p++, s++) {
6112 if (!
len || L
'\"' == *(--s)) {
6116 end = buf1 +
len - 1;
6118 if (isUNCRoot(buf1)) {
6121 else if (*end != L
'\\')
6122 lstrcatW(buf1, L
"\\");
6124 else if (*end == L
'\\' || (buf1 + 1 == end && *end == L
':'))
6125 lstrcatW(buf1, L
".");
6132rb_w32_ustati128(
const char *path,
struct stati128 *st)
6134 return w32_stati128(path, st, CP_UTF8, FALSE);
6139rb_w32_stati128(
const char *path,
struct stati128 *st)
6141 return w32_stati128(path, st, filecp(), FALSE);
6146w32_stati128(
const char *path,
struct stati128 *st, UINT cp, BOOL lstat)
6151 if (!(wpath = mbstr_to_wstr(cp, path, -1, NULL)))
6153 ret = wstati128(wpath, st, lstat);
6160rb_w32_ulstati128(
const char *path,
struct stati128 *st)
6162 return w32_stati128(path, st, CP_UTF8, TRUE);
6167rb_w32_lstati128(
const char *path,
struct stati128 *st)
6169 return w32_stati128(path, st, filecp(), TRUE);
6174rb_w32_lseek(
int fd, rb_off_t ofs,
int whence)
6176 SOCKET sock = TO_SOCKET(fd);
6177 if (is_socket(sock) || is_pipe(sock)) {
6181 return _lseeki64(fd, ofs, whence);
6186w32_access(
const char *path,
int mode, UINT cp)
6189 if (w32_stati128(path, &stat, cp, FALSE) != 0)
6192 if ((stat.st_mode & mode) != mode) {
6201rb_w32_access(
const char *path,
int mode)
6203 return w32_access(path, mode, filecp());
6208rb_w32_uaccess(
const char *path,
int mode)
6210 return w32_access(path, mode, CP_UTF8);
6215rb_chsize(HANDLE h, rb_off_t size)
6217 long upos, lpos, usize, lsize;
6221 if ((lpos = SetFilePointer(h, 0, (upos = 0, &upos), SEEK_CUR)) == -1L &&
6222 (e = GetLastError())) {
6223 errno = map_errno(e);
6226 usize = (long)(size >> 32);
6228 if (SetFilePointer(h, lsize, &usize, SEEK_SET) == (DWORD)-1L &&
6229 (e = GetLastError())) {
6230 errno = map_errno(e);
6232 else if (!SetEndOfFile(h)) {
6233 errno = map_errno(GetLastError());
6238 SetFilePointer(h, lpos, &upos, SEEK_SET);
6244w32_truncate(
const char *path, rb_off_t length, UINT cp)
6250 if (!(wpath = mbstr_to_wstr(cp, path, -1, NULL)))
6252 h = CreateFileW(wpath, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
6253 if (h == INVALID_HANDLE_VALUE) {
6254 errno = map_errno(GetLastError());
6259 ret = rb_chsize(h, length);
6266rb_w32_utruncate(
const char *path, rb_off_t length)
6268 return w32_truncate(path, length, CP_UTF8);
6273rb_w32_truncate(
const char *path, rb_off_t length)
6275 return w32_truncate(path, length, filecp());
6280rb_w32_ftruncate(
int fd, rb_off_t length)
6284 h = (HANDLE)_get_osfhandle(fd);
6285 if (h == (HANDLE)-1)
return -1;
6286 return rb_chsize(h, length);
6291filetime_to_clock(FILETIME *ft)
6293 __int64 qw = ft->dwHighDateTime;
6295 qw |= ft->dwLowDateTime;
6302rb_w32_times(
struct tms *tmbuf)
6304 FILETIME create, exit, kernel, user;
6306 if (GetProcessTimes(GetCurrentProcess(),&create, &exit, &kernel, &user)) {
6307 tmbuf->tms_utime = filetime_to_clock(&user);
6308 tmbuf->tms_stime = filetime_to_clock(&kernel);
6309 tmbuf->tms_cutime = 0;
6310 tmbuf->tms_cstime = 0;
6313 tmbuf->tms_utime = clock();
6314 tmbuf->tms_stime = 0;
6315 tmbuf->tms_cutime = 0;
6316 tmbuf->tms_cstime = 0;
6323#define yield_once() Sleep(0)
6324#define yield_until(condition) do yield_once(); while (!(condition))
6333 uintptr_t (*func)(uintptr_t self,
int argc, uintptr_t* argv);
6341call_asynchronous(PVOID argp)
6345 arg->stackaddr = &argp;
6346 ret = (DWORD)arg->func(arg->self, arg->argc, arg->argv);
6347 arg->errnum =
errno;
6353rb_w32_asynchronize(asynchronous_func_t func, uintptr_t self,
6354 int argc, uintptr_t* argv, uintptr_t intrval)
6357 BOOL interrupted = FALSE;
6363 arg.stackaddr = NULL;
6370 thr = CreateThread(NULL, 0, call_asynchronous, &arg, 0, &val);
6373 yield_until(arg.stackaddr);
6375 if (rb_w32_wait_events_blocking(&thr, 1, INFINITE) != WAIT_OBJECT_0) {
6378 if (TerminateThread(thr, intrval)) {
6383 GetExitCodeThread(thr, &val);
6388 MEMORY_BASIC_INFORMATION m;
6390 memset(&m, 0,
sizeof(m));
6391 if (!VirtualQuery(arg.stackaddr, &m,
sizeof(m))) {
6392 Debug(fprintf(stderr,
"couldn't get stack base:%p:%d\n",
6393 arg.stackaddr, GetLastError()));
6395 else if (!VirtualFree(m.AllocationBase, 0, MEM_RELEASE)) {
6396 Debug(fprintf(stderr,
"couldn't release stack:%p:%d\n",
6397 m.AllocationBase, GetLastError()));
6408 rb_fatal(
"failed to launch waiter thread:%ld", GetLastError());
6416rb_w32_get_environ(
void)
6418 WCHAR *envtop, *env;
6419 char **myenvtop, **myenv;
6432 envtop = GetEnvironmentStringsW();
6433 for (env = envtop, num = 0; *env; env += lstrlenW(env) + 1)
6434 if (*env !=
'=') num++;
6436 myenvtop = (
char **)malloc(
sizeof(
char *) * (num + 1));
6437 for (env = envtop, myenv = myenvtop; *env; env += lstrlenW(env) + 1) {
6439 if (!(*myenv = wstr_to_utf8(env, NULL))) {
6446 FreeEnvironmentStringsW(envtop);
6453rb_w32_free_environ(
char **env)
6457 while (*t) free(*t++);
6465 return GetCurrentProcessId();
6473 typedef long (WINAPI query_func)(HANDLE, int,
void *, ULONG, ULONG *);
6474 static query_func *pNtQueryInformationProcess = (query_func *)-1;
6477 if (pNtQueryInformationProcess == (query_func *)-1)
6478 pNtQueryInformationProcess = (query_func *)get_proc_address(
"ntdll.dll",
"NtQueryInformationProcess", NULL);
6479 if (pNtQueryInformationProcess) {
6482 void* PebBaseAddress;
6483 uintptr_t AffinityMask;
6484 uintptr_t BasePriority;
6485 uintptr_t UniqueProcessId;
6486 uintptr_t ParentProcessId;
6489 long ret = pNtQueryInformationProcess(GetCurrentProcess(), 0, &pbi,
sizeof(pbi), &
len);
6491 ppid = pbi.ParentProcessId;
6498STATIC_ASSERT(std_handle, (STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)==(STD_ERROR_HANDLE-STD_OUTPUT_HANDLE));
6501#define set_new_std_handle(newfd, handle) do { \
6502 if ((unsigned)(newfd) > 2) break; \
6503 SetStdHandle(STD_INPUT_HANDLE+(STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)*(newfd), \
6506#define set_new_std_fd(newfd) set_new_std_handle(newfd, (HANDLE)rb_w32_get_osfhandle(newfd))
6510rb_w32_dup2(
int oldfd,
int newfd)
6514 if (oldfd == newfd)
return newfd;
6515 ret = dup2(oldfd, newfd);
6516 if (ret < 0)
return ret;
6517 set_new_std_fd(newfd);
6523rb_w32_uopen(
const char *file,
int oflag, ...)
6530 va_start(arg, oflag);
6531 pmode = va_arg(arg,
int);
6534 if (!(wfile = utf8_to_wstr(file, NULL)))
6536 ret = w32_wopen(wfile, oflag, pmode);
6543check_if_wdir(
const WCHAR *wfile)
6545 DWORD attr = GetFileAttributesW(wfile);
6546 if (attr == (DWORD)-1L ||
6547 !(attr & FILE_ATTRIBUTE_DIRECTORY) ||
6548 check_valid_dir(wfile)) {
6557rb_w32_open(
const char *file,
int oflag, ...)
6564 va_start(arg, oflag);
6565 pmode = va_arg(arg,
int);
6568 if (!(wfile = filecp_to_wstr(file, NULL)))
6570 ret = w32_wopen(wfile, oflag, pmode);
6577rb_w32_wopen(
const WCHAR *file,
int oflag, ...)
6581 if (oflag & O_CREAT) {
6583 va_start(arg, oflag);
6584 pmode = va_arg(arg,
int);
6588 return w32_wopen(file, oflag, pmode);
6592w32_wopen(
const WCHAR *file,
int oflag,
int pmode)
6598 DWORD attr = FILE_ATTRIBUTE_NORMAL;
6599 SECURITY_ATTRIBUTES sec;
6603 share_delete = oflag & O_SHARE_DELETE ? FILE_SHARE_DELETE : 0;
6604 oflag &= ~O_SHARE_DELETE;
6605 if ((oflag & O_TEXT) || !(oflag & O_BINARY)) {
6606 fd = _wopen(file, oflag, pmode);
6610 check_if_wdir(file);
6613 errno = map_errno(GetLastError());
6620 sec.nLength =
sizeof(sec);
6621 sec.lpSecurityDescriptor = NULL;
6622 if (oflag & O_NOINHERIT) {
6623 sec.bInheritHandle = FALSE;
6624 flags |= FNOINHERIT;
6627 sec.bInheritHandle = TRUE;
6629 oflag &= ~O_NOINHERIT;
6632 oflag &= ~(O_BINARY | O_TEXT);
6634 switch (oflag & (O_RDWR | O_RDONLY | O_WRONLY)) {
6636 access = GENERIC_READ | GENERIC_WRITE;
6639 access = GENERIC_READ;
6642 access = GENERIC_WRITE;
6648 oflag &= ~(O_RDWR | O_RDONLY | O_WRONLY);
6650 switch (oflag & (O_CREAT | O_EXCL | O_TRUNC)) {
6652 create = OPEN_ALWAYS;
6656 create = OPEN_EXISTING;
6658 case O_CREAT | O_EXCL:
6659 case O_CREAT | O_EXCL | O_TRUNC:
6660 create = CREATE_NEW;
6663 case O_TRUNC | O_EXCL:
6664 create = TRUNCATE_EXISTING;
6666 case O_CREAT | O_TRUNC:
6667 create = CREATE_ALWAYS;
6673 if (oflag & O_CREAT) {
6675 if (!(pmode & S_IWRITE))
6676 attr = FILE_ATTRIBUTE_READONLY;
6678 oflag &= ~(O_CREAT | O_EXCL | O_TRUNC);
6680 if (oflag & O_TEMPORARY) {
6681 attr |= FILE_FLAG_DELETE_ON_CLOSE;
6684 oflag &= ~O_TEMPORARY;
6686 if (oflag & _O_SHORT_LIVED)
6687 attr |= FILE_ATTRIBUTE_TEMPORARY;
6688 oflag &= ~_O_SHORT_LIVED;
6690 switch (oflag & (O_SEQUENTIAL | O_RANDOM)) {
6694 attr |= FILE_FLAG_SEQUENTIAL_SCAN;
6697 attr |= FILE_FLAG_RANDOM_ACCESS;
6703 oflag &= ~(O_SEQUENTIAL | O_RANDOM);
6705 if (oflag & ~O_APPEND) {
6712 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6713 fd = _open_osfhandle((intptr_t)h, 0);
6721 rb_acrt_lowio_lock_fh(fd);
6722 _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE);
6723 _set_osflags(fd, 0);
6725 h = CreateFileW(file, access, FILE_SHARE_READ | FILE_SHARE_WRITE | share_delete, &sec, create, attr, NULL);
6726 if (h == INVALID_HANDLE_VALUE) {
6727 DWORD e = GetLastError();
6728 if (e != ERROR_ACCESS_DENIED || !check_if_wdir(file))
6729 errno = map_errno(e);
6730 rb_acrt_lowio_unlock_fh(fd);
6735 switch (GetFileType(h)) {
6736 case FILE_TYPE_CHAR:
6739 case FILE_TYPE_PIPE:
6742 case FILE_TYPE_UNKNOWN:
6743 errno = map_errno(GetLastError());
6745 rb_acrt_lowio_unlock_fh(fd);
6749 if (!(flags & (FDEV | FPIPE)) && (oflag & O_APPEND))
6752 _set_osfhnd(fd, (intptr_t)h);
6753 _set_osflags(fd, flags | FOPEN);
6755 rb_acrt_lowio_unlock_fh(fd);
6765rb_w32_fclose(
FILE *fp)
6767 int fd = fileno(fp);
6768 SOCKET sock = TO_SOCKET(fd);
6769 int save_errno =
errno;
6771 if (fflush(fp))
return -1;
6772 if (!is_socket(sock)) {
6773 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
6776 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
6779 if (closesocket(sock) == SOCKET_ERROR) {
6780 errno = map_errno(WSAGetLastError());
6788rb_w32_pipe(
int fds[2])
6790 static long serial = 0;
6791 static const char prefix[] =
"\\\\.\\pipe\\ruby";
6793 width_of_prefix = (int)
sizeof(prefix) - 1,
6794 width_of_pid = (int)
sizeof(rb_pid_t) * 2,
6795 width_of_serial = (int)
sizeof(serial) * 2,
6796 width_of_ids = width_of_pid + 1 + width_of_serial + 1
6798 char name[
sizeof(prefix) + width_of_ids];
6799 SECURITY_ATTRIBUTES sec;
6800 HANDLE hRead, hWrite, h;
6801 int fdRead, fdWrite;
6804 memcpy(name, prefix, width_of_prefix);
6805 snprintf(name + width_of_prefix, width_of_ids,
"%.*"PRI_PIDT_PREFIX"x-%.*lx",
6806 width_of_pid, rb_w32_getpid(), width_of_serial, (
unsigned long)(InterlockedIncrement(&serial)-1));
6808 sec.nLength =
sizeof(sec);
6809 sec.lpSecurityDescriptor = NULL;
6810 sec.bInheritHandle = FALSE;
6813 hRead = CreateNamedPipe(name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
6814 0, 2, 65536, 65536, 0, &sec);
6816 if (hRead == INVALID_HANDLE_VALUE) {
6817 DWORD err = GetLastError();
6818 if (err == ERROR_PIPE_BUSY)
6821 errno = map_errno(GetLastError());
6826 hWrite = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, &sec,
6827 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
6829 if (hWrite == INVALID_HANDLE_VALUE) {
6830 errno = map_errno(GetLastError());
6837 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6838 fdRead = _open_osfhandle((intptr_t)h, 0);
6842 CloseHandle(hWrite);
6848 rb_acrt_lowio_lock_fh(fdRead);
6849 _set_osfhnd(fdRead, (intptr_t)hRead);
6850 _set_osflags(fdRead, FOPEN | FPIPE | FNOINHERIT);
6851 rb_acrt_lowio_unlock_fh(fdRead);
6857 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6858 fdWrite = _open_osfhandle((intptr_t)h, 0);
6860 if (fdWrite == -1) {
6862 CloseHandle(hWrite);
6866 rb_acrt_lowio_lock_fh(fdWrite);
6867 _set_osfhnd(fdWrite, (intptr_t)hWrite);
6868 _set_osflags(fdWrite, FOPEN | FPIPE | FNOINHERIT);
6869 rb_acrt_lowio_unlock_fh(fdWrite);
6872 rb_w32_close(fdRead);
6884console_emulator_p(
void)
6886 const void *
const func = WriteConsoleW;
6888 MEMORY_BASIC_INFORMATION m;
6890 memset(&m, 0,
sizeof(m));
6891 if (!VirtualQuery(func, &m,
sizeof(m))) {
6894 k = GetModuleHandle(
"kernel32.dll");
6895 if (!k)
return FALSE;
6896 return (HMODULE)m.AllocationBase != k;
6901constat_handle(HANDLE h)
6905 thread_exclusive(conlist) {
6907 if (console_emulator_p()) {
6908 conlist = conlist_disabled;
6911 conlist = st_init_numtable();
6912 install_vm_exit_handler();
6914 else if (conlist == conlist_disabled) {
6917 if (st_lookup(conlist, (st_data_t)h, &data)) {
6921 CONSOLE_SCREEN_BUFFER_INFO csbi;
6923 p->vt100.state = constat_init;
6924 p->vt100.attr = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
6925 p->vt100.reverse = 0;
6926 p->vt100.saved.X = p->vt100.saved.Y = 0;
6927 if (GetConsoleScreenBufferInfo(h, &csbi)) {
6928 p->vt100.attr = csbi.wAttributes;
6930 st_insert(conlist, (st_data_t)h, (st_data_t)p);
6936#define FOREGROUND_MASK (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY)
6937#define BACKGROUND_MASK (BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY)
6939#define constat_attr_color_reverse(attr) \
6940 ((attr) & ~(FOREGROUND_MASK | BACKGROUND_MASK)) | \
6941 (((attr) & FOREGROUND_MASK) << 4) | \
6942 (((attr) & BACKGROUND_MASK) >> 4)
6946constat_attr(
int count,
const int *seq, WORD attr, WORD default_attr,
int *reverse)
6951 if (!count)
return attr;
6952 if (rev) attr = constat_attr_color_reverse(attr);
6953 bold = attr & FOREGROUND_INTENSITY;
6954 attr &= ~(FOREGROUND_INTENSITY | BACKGROUND_INTENSITY);
6956 while (count-- > 0) {
6959 attr = default_attr;
6964 bold = FOREGROUND_INTENSITY;
6970#ifndef COMMON_LVB_UNDERSCORE
6971#define COMMON_LVB_UNDERSCORE 0x8000
6973 attr |= COMMON_LVB_UNDERSCORE;
6976 attr &= ~COMMON_LVB_UNDERSCORE;
6986 attr &= ~(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
6989 attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_GREEN)) | FOREGROUND_RED;
6992 attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_RED)) | FOREGROUND_GREEN;
6995 attr = (attr & ~FOREGROUND_BLUE) | FOREGROUND_GREEN | FOREGROUND_RED;
6998 attr = (attr & ~(FOREGROUND_GREEN | FOREGROUND_RED)) | FOREGROUND_BLUE;
7001 attr = (attr & ~FOREGROUND_GREEN) | FOREGROUND_BLUE | FOREGROUND_RED;
7004 attr = (attr & ~FOREGROUND_RED) | FOREGROUND_BLUE | FOREGROUND_GREEN;
7007 attr |= FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
7012 attr = (attr & ~FOREGROUND_MASK) | (default_attr & FOREGROUND_MASK);
7016 attr &= ~(BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED);
7019 attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_GREEN)) | BACKGROUND_RED;
7022 attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_RED)) | BACKGROUND_GREEN;
7025 attr = (attr & ~BACKGROUND_BLUE) | BACKGROUND_GREEN | BACKGROUND_RED;
7028 attr = (attr & ~(BACKGROUND_GREEN | BACKGROUND_RED)) | BACKGROUND_BLUE;
7031 attr = (attr & ~BACKGROUND_GREEN) | BACKGROUND_BLUE | BACKGROUND_RED;
7034 attr = (attr & ~BACKGROUND_RED) | BACKGROUND_BLUE | BACKGROUND_GREEN;
7037 attr |= BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED;
7042 attr = (attr & ~BACKGROUND_MASK) | (default_attr & BACKGROUND_MASK);
7047 if (rev) attr = constat_attr_color_reverse(attr);
7054constat_clear(HANDLE handle, WORD attr, DWORD
len, COORD pos)
7058 FillConsoleOutputAttribute(handle, attr,
len, pos, &written);
7059 FillConsoleOutputCharacterW(handle, L
' ',
len, pos, &written);
7064constat_apply(HANDLE handle,
struct constat *s, WCHAR w)
7066 CONSOLE_SCREEN_BUFFER_INFO csbi;
7067 const int *seq = s->vt100.seq;
7068 int count = s->vt100.state;
7072 if (!GetConsoleScreenBufferInfo(handle, &csbi))
return;
7073 arg0 = (count > 0 && seq[0] > 0);
7074 if (arg0) arg1 = seq[0];
7077 SetConsoleTextAttribute(handle, constat_attr(count, seq, csbi.wAttributes, s->vt100.attr, &s->vt100.reverse));
7080 csbi.dwCursorPosition.X = 0;
7082 csbi.dwCursorPosition.Y -= arg1;
7083 if (csbi.dwCursorPosition.Y < csbi.srWindow.Top)
7084 csbi.dwCursorPosition.Y = csbi.srWindow.Top;
7085 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7088 csbi.dwCursorPosition.X = 0;
7091 csbi.dwCursorPosition.Y += arg1;
7092 if (csbi.dwCursorPosition.Y > csbi.srWindow.Bottom)
7093 csbi.dwCursorPosition.Y = csbi.srWindow.Bottom;
7094 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7097 csbi.dwCursorPosition.X += arg1;
7098 if (csbi.dwCursorPosition.X >= csbi.srWindow.Right)
7099 csbi.dwCursorPosition.X = csbi.srWindow.Right;
7100 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7103 csbi.dwCursorPosition.X -= arg1;
7104 if (csbi.dwCursorPosition.X < csbi.srWindow.Left)
7105 csbi.dwCursorPosition.X = csbi.srWindow.Left;
7106 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7110 arg1 += csbi.srWindow.Left;
7111 if (arg1 > csbi.srWindow.Right)
7112 arg1 = csbi.srWindow.Right;
7113 csbi.dwCursorPosition.X = arg1;
7114 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7117 arg1 += csbi.srWindow.Top;
7118 if (arg1 > csbi.srWindow.Bottom)
7119 arg1 = csbi.srWindow.Bottom;
7120 csbi.dwCursorPosition.Y = arg1;
7121 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
7125 pos.Y = arg1 + csbi.srWindow.Top - 1;
7126 if (pos.Y > csbi.srWindow.Bottom) pos.Y = csbi.srWindow.Bottom;
7127 if (count < 2 || (arg1 = seq[1]) <= 0) arg1 = 1;
7128 pos.X = arg1 + csbi.srWindow.Left - 1;
7129 if (pos.X > csbi.srWindow.Right) pos.X = csbi.srWindow.Right;
7130 SetConsoleCursorPosition(handle, pos);
7133 switch (arg0 ? arg1 : 0) {
7135 constat_clear(handle, csbi.wAttributes,
7136 (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.dwCursorPosition.Y + 1)
7137 - csbi.dwCursorPosition.X),
7138 csbi.dwCursorPosition);
7142 pos.Y = csbi.srWindow.Top;
7143 constat_clear(handle, csbi.wAttributes,
7144 (csbi.dwSize.X * (csbi.dwCursorPosition.Y - csbi.srWindow.Top)
7145 + csbi.dwCursorPosition.X + 1),
7150 pos.Y = csbi.srWindow.Top;
7151 constat_clear(handle, csbi.wAttributes,
7152 (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1)),
7158 constat_clear(handle, csbi.wAttributes,
7159 (csbi.dwSize.X * csbi.dwSize.Y),
7165 switch (arg0 ? arg1 : 0) {
7167 constat_clear(handle, csbi.wAttributes,
7168 (csbi.dwSize.X - csbi.dwCursorPosition.X),
7169 csbi.dwCursorPosition);
7173 pos.Y = csbi.dwCursorPosition.Y;
7174 constat_clear(handle, csbi.wAttributes,
7175 csbi.dwCursorPosition.X + 1, pos);
7179 pos.Y = csbi.dwCursorPosition.Y;
7180 constat_clear(handle, csbi.wAttributes,
7181 csbi.dwSize.X, pos);
7186 s->vt100.saved = csbi.dwCursorPosition;
7189 SetConsoleCursorPosition(handle, s->vt100.saved);
7192 if (count >= 2 && seq[0] == -1 && seq[1] == 25) {
7193 CONSOLE_CURSOR_INFO cci;
7194 GetConsoleCursorInfo(handle, &cci);
7195 cci.bVisible = TRUE;
7196 SetConsoleCursorInfo(handle, &cci);
7200 if (count >= 2 && seq[0] == -1 && seq[1] == 25) {
7201 CONSOLE_CURSOR_INFO cci;
7202 GetConsoleCursorInfo(handle, &cci);
7203 cci.bVisible = FALSE;
7204 SetConsoleCursorInfo(handle, &cci);
7212constat_parse(HANDLE h,
struct constat *s,
const WCHAR **ptrp,
long *lenp)
7214 const WCHAR *ptr = *ptrp;
7215 long rest,
len = *lenp;
7219 rest = *lenp -
len - 1;
7220 if (s->vt100.state == constat_esc) {
7223 s->vt100.state = constat_init;
7224 if (
len > 0 && *ptr != L
'[')
continue;
7225 s->vt100.state = constat_esc;
7227 else if (s->vt100.state == constat_esc) {
7230 s->vt100.state = constat_init;
7233 rest = *lenp -
len - 1;
7234 if (rest > 0) --rest;
7235 s->vt100.state = constat_seq;
7236 s->vt100.seq[0] = 0;
7238 else if (s->vt100.state >= constat_seq) {
7239 if (wc >= L
'0' && wc <= L
'9') {
7240 if (s->vt100.state < (
int)numberof(s->vt100.seq)) {
7241 int *seq = &s->vt100.seq[s->vt100.state];
7242 *seq = (*seq * 10) + (wc - L
'0');
7245 else if (s->vt100.state == constat_seq && s->vt100.seq[0] == 0 && wc == L
'?') {
7246 s->vt100.seq[s->vt100.state++] = -1;
7250 if (++s->vt100.state < (
int)numberof(s->vt100.seq)) {
7251 s->vt100.seq[s->vt100.state] = 0;
7254 s->vt100.state = (int)numberof(s->vt100.seq);
7258 constat_apply(h, s, wc);
7259 s->vt100.state = constat_init;
7282 SOCKET sock = TO_SOCKET(fd);
7283 int save_errno =
errno;
7285 if (!is_socket(sock)) {
7286 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
7287 constat_delete((HANDLE)sock);
7290 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
7291 socklist_delete(&sock, NULL);
7294 if (closesocket(sock) == SOCKET_ERROR) {
7295 errno = map_errno(WSAGetLastError());
7301#ifndef INVALID_SET_FILE_POINTER
7302#define INVALID_SET_FILE_POINTER ((DWORD)-1)
7306setup_overlapped(OVERLAPPED *ol,
int fd,
int iswrite, rb_off_t *_offset)
7308 memset(ol, 0,
sizeof(*ol));
7313 DWORD seek_method = ((_osfile(fd) & FAPPEND) && iswrite) ? FILE_END : FILE_CURRENT;
7317 uint64_t offset = *_offset;
7318 ol->Offset = (uint32_t)(offset & 0xFFFFFFFFLL);
7319 ol->OffsetHigh = (uint32_t)((offset & 0xFFFFFFFF00000000LL) >> 32);
7322 LARGE_INTEGER seek_offset = {0}, current_offset = {0};
7323 if (!SetFilePointerEx((HANDLE)_osfhnd(fd), seek_offset, ¤t_offset, seek_method)) {
7324 DWORD last_error = GetLastError();
7325 if (last_error != NO_ERROR) {
7326 errno = map_errno(last_error);
7332 *_offset = current_offset.QuadPart;
7334 else if (!(_osfile(fd) & (FDEV | FPIPE))) {
7336 DWORD low = SetFilePointer((HANDLE)_osfhnd(fd), 0, &high, seek_method);
7338 if (low == INVALID_SET_FILE_POINTER) {
7339 DWORD err = GetLastError();
7340 if (err != NO_ERROR) {
7341 errno = map_errno(err);
7347 ol->OffsetHigh = high;
7350 ol->hEvent = CreateEvent(NULL, TRUE, TRUE, NULL);
7352 errno = map_errno(GetLastError());
7359finish_overlapped(OVERLAPPED *ol,
int fd, DWORD size, rb_off_t *_offset)
7361 CloseHandle(ol->hEvent);
7365 DWORD seek_method = (_osfile(fd) & FAPPEND) ? FILE_END : FILE_BEGIN;
7367 LARGE_INTEGER seek_offset = {0};
7368 if (seek_method == FILE_BEGIN) {
7369 seek_offset.QuadPart = *_offset;
7372 SetFilePointerEx((HANDLE)_osfhnd(fd), seek_offset, NULL, seek_method);
7374 else if (!(_osfile(fd) & (FDEV | FPIPE))) {
7375 LONG high = ol->OffsetHigh;
7376 DWORD low = ol->Offset + size;
7377 if (low < ol->Offset)
7379 SetFilePointer((HANDLE)_osfhnd(fd), low, &high, FILE_BEGIN);
7386rb_w32_read_internal(
int fd,
void *buf,
size_t size, rb_off_t *offset)
7388 SOCKET sock = TO_SOCKET(fd);
7396 if (is_socket(sock))
7397 return rb_w32_recv(fd, buf, size, 0);
7400 if (_get_osfhandle(fd) == -1) {
7404 if (!offset && _osfile(fd) & FTEXT) {
7405 return _read(fd, buf, size);
7408 rb_acrt_lowio_lock_fh(fd);
7410 if (!size || _osfile(fd) & FEOFLAG) {
7411 _set_osflags(fd, _osfile(fd) & ~FEOFLAG);
7412 rb_acrt_lowio_unlock_fh(fd);
7421 if (setup_overlapped(&ol, fd, FALSE, offset)) {
7422 rb_acrt_lowio_unlock_fh(fd);
7426 if (!ReadFile((HANDLE)_osfhnd(fd), buf,
len, &read, &ol)) {
7427 err = GetLastError();
7428 if (err == ERROR_NO_DATA && (_osfile(fd) & FPIPE)) {
7430 if (GetNamedPipeHandleState((HANDLE)_osfhnd(fd), &state, NULL, NULL, NULL, NULL, 0) && (state & PIPE_NOWAIT)) {
7431 errno = EWOULDBLOCK;
7434 errno = map_errno(err);
7436 rb_acrt_lowio_unlock_fh(fd);
7439 else if (err != ERROR_IO_PENDING) {
7440 CloseHandle(ol.hEvent);
7441 if (err == ERROR_ACCESS_DENIED)
7443 else if (err == ERROR_BROKEN_PIPE || err == ERROR_HANDLE_EOF) {
7444 rb_acrt_lowio_unlock_fh(fd);
7448 errno = map_errno(err);
7450 rb_acrt_lowio_unlock_fh(fd);
7454 wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE);
7455 if (wait != WAIT_OBJECT_0) {
7456 if (wait == WAIT_OBJECT_0 + 1)
7459 errno = map_errno(GetLastError());
7460 CloseHandle(ol.hEvent);
7461 CancelIo((HANDLE)_osfhnd(fd));
7462 rb_acrt_lowio_unlock_fh(fd);
7466 if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &read, TRUE) &&
7467 (err = GetLastError()) != ERROR_HANDLE_EOF) {
7469 if (err != ERROR_BROKEN_PIPE) {
7470 errno = map_errno(err);
7473 CloseHandle(ol.hEvent);
7474 CancelIo((HANDLE)_osfhnd(fd));
7475 rb_acrt_lowio_unlock_fh(fd);
7480 err = GetLastError();
7481 errno = map_errno(err);
7484 finish_overlapped(&ol, fd, read, offset);
7488 buf = (
char *)buf + read;
7489 if (err != ERROR_OPERATION_ABORTED && size > 0)
7493 _set_osflags(fd, _osfile(fd) | FEOFLAG);
7496 rb_acrt_lowio_unlock_fh(fd);
7504rb_w32_write_internal(
int fd,
const void *buf,
size_t size, rb_off_t *offset)
7506 SOCKET sock = TO_SOCKET(fd);
7514 if (is_socket(sock))
7515 return rb_w32_send(fd, buf, size, 0);
7518 if (_get_osfhandle(fd) == -1) {
7523 if (!offset && (_osfile(fd) & FTEXT) &&
7524 (!(_osfile(fd) & FPIPE) || fd == fileno(stdout) || fd == fileno(stderr))) {
7525 ssize_t w = _write(fd, buf, size);
7526 if (w == (ssize_t)-1 &&
errno == EINVAL) {
7527 errno = map_errno(GetLastError());
7532 rb_acrt_lowio_lock_fh(fd);
7534 if (!size || _osfile(fd) & FEOFLAG) {
7535 rb_acrt_lowio_unlock_fh(fd);
7546 if (setup_overlapped(&ol, fd, TRUE, offset)) {
7547 rb_acrt_lowio_unlock_fh(fd);
7551 if (!WriteFile((HANDLE)_osfhnd(fd), buf,
len, &written, &ol)) {
7552 err = GetLastError();
7553 if (err != ERROR_IO_PENDING) {
7554 CloseHandle(ol.hEvent);
7555 if (err == ERROR_ACCESS_DENIED)
7558 errno = map_errno(err);
7560 rb_acrt_lowio_unlock_fh(fd);
7564 wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE);
7565 if (wait != WAIT_OBJECT_0) {
7566 if (wait == WAIT_OBJECT_0 + 1)
7569 errno = map_errno(GetLastError());
7570 CloseHandle(ol.hEvent);
7571 CancelIo((HANDLE)_osfhnd(fd));
7572 rb_acrt_lowio_unlock_fh(fd);
7576 if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &written, TRUE)) {
7577 errno = map_errno(GetLastError());
7578 CloseHandle(ol.hEvent);
7579 CancelIo((HANDLE)_osfhnd(fd));
7580 rb_acrt_lowio_unlock_fh(fd);
7585 finish_overlapped(&ol, fd, written, offset);
7588 if (written ==
len) {
7589 buf = (
const char *)buf +
len;
7594 size_t newlen =
len / 2;
7596 size +=
len - newlen;
7601 errno = EWOULDBLOCK;
7604 rb_acrt_lowio_unlock_fh(fd);
7610rb_w32_read(
int fd,
void *buf,
size_t size)
7612 return rb_w32_read_internal(fd, buf, size, NULL);
7616rb_w32_write(
int fd,
const void *buf,
size_t size)
7618 return rb_w32_write_internal(fd, buf, size, NULL);
7622rb_w32_pread(
int descriptor,
void *base,
size_t size, rb_off_t offset)
7624 return rb_w32_read_internal(descriptor, base, size, &offset);
7628rb_w32_pwrite(
int descriptor,
const void *base,
size_t size, rb_off_t offset)
7630 return rb_w32_write_internal(descriptor, base, size, &offset);
7635rb_w32_write_console(uintptr_t strarg,
int fd)
7638 DWORD dwMode, reslen;
7642 const WCHAR *ptr, *next;
7646 handle = (HANDLE)_osfhnd(fd);
7647 if (!GetConsoleMode(handle, &dwMode))
7650 s = constat_handle(handle);
7660 case ENCINDEX_US_ASCII:
7661 case ENCINDEX_ASCII_8BIT:
7663 case ENCINDEX_UTF_8:
7664 ptr = wbuffer = mbstr_to_wstr(CP_UTF8, RSTRING_PTR(str), RSTRING_LEN(str), &
len);
7665 if (!ptr)
return -1L;
7667 case ENCINDEX_UTF_16LE:
7668 ptr = (
const WCHAR *)RSTRING_PTR(str);
7669 len = RSTRING_LEN(str) /
sizeof(WCHAR);
7673 if (dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) {
7674 if (!WriteConsoleW(handle, ptr,
len, &reslen, NULL))
7675 reslen = (DWORD)-1L;
7679 long curlen = constat_parse(handle, s, (next = ptr, &next), &
len);
7680 reslen += next - ptr;
7683 if (!WriteConsoleW(handle, ptr, curlen, &written, NULL)) {
7684 reslen = (DWORD)-1L;
7693 return (
long)reslen;
7698timespec_to_filetime(
const struct timespec *ts, FILETIME *ft)
7702 tmp.QuadPart = unix_to_filetime((ULONGLONG)ts->tv_sec);
7703 tmp.QuadPart += ts->tv_nsec / 100;
7704 ft->dwLowDateTime = tmp.LowPart;
7705 ft->dwHighDateTime = tmp.HighPart;
7711wutimensat(
int dirfd,
const WCHAR *path,
const struct timespec *times,
int flags)
7714 FILETIME atime, mtime;
7719 if (dirfd != AT_FDCWD) {
7729 if (wstati128(path, &stat, FALSE)) {
7734 if (timespec_to_filetime(×[0], &atime)) {
7737 if (timespec_to_filetime(×[1], &mtime)) {
7742 GetSystemTimePreciseAsFileTime(&atime);
7747 const DWORD attr = GetFileAttributesW(path);
7748 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY))
7749 SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY);
7750 hFile = open_special(path, GENERIC_WRITE, 0);
7751 if (hFile == INVALID_HANDLE_VALUE) {
7752 errno = map_errno(GetLastError());
7756 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
7757 errno = map_errno(GetLastError());
7762 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY))
7763 SetFileAttributesW(path, attr);
7771w32_utimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags, UINT cp)
7773 WCHAR *wpath = mbstr_to_wstr(cp, path, -1, NULL);
7777 ret = wutimensat(dirfd, wpath, times, flags);
7785rb_w32_uutime(
const char *path,
const struct utimbuf *times)
7789 ts[0].tv_sec = times->actime;
7791 ts[1].tv_sec = times->modtime;
7793 return w32_utimensat(AT_FDCWD, path, ts, 0, CP_UTF8);
7798rb_w32_utime(
const char *path,
const struct utimbuf *times)
7802 ts[0].tv_sec = times->actime;
7804 ts[1].tv_sec = times->modtime;
7806 return w32_utimensat(AT_FDCWD, path, ts, 0, filecp());
7811rb_w32_uutimes(
const char *path,
const struct timeval *times)
7815 ts[0].tv_sec = times[0].tv_sec;
7816 ts[0].tv_nsec = times[0].tv_usec * 1000;
7817 ts[1].tv_sec = times[1].tv_sec;
7818 ts[1].tv_nsec = times[1].tv_usec * 1000;
7819 return w32_utimensat(AT_FDCWD, path, ts, 0, CP_UTF8);
7824rb_w32_utimes(
const char *path,
const struct timeval *times)
7828 ts[0].tv_sec = times[0].tv_sec;
7829 ts[0].tv_nsec = times[0].tv_usec * 1000;
7830 ts[1].tv_sec = times[1].tv_sec;
7831 ts[1].tv_nsec = times[1].tv_usec * 1000;
7832 return w32_utimensat(AT_FDCWD, path, ts, 0, filecp());
7837rb_w32_uutimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags)
7839 return w32_utimensat(dirfd, path, times, flags, CP_UTF8);
7844rb_w32_utimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags)
7846 return w32_utimensat(dirfd, path, times, flags, filecp());
7851rb_w32_uchdir(
const char *path)
7856 if (!(wpath = utf8_to_wstr(path, NULL)))
7858 ret = _wchdir(wpath);
7865wmkdir(
const WCHAR *wpath,
int mode)
7870 if (CreateDirectoryW(wpath, NULL) == FALSE) {
7871 errno = map_errno(GetLastError());
7874 if (_wchmod(wpath, mode) == -1) {
7875 RemoveDirectoryW(wpath);
7885rb_w32_umkdir(
const char *path,
int mode)
7890 if (!(wpath = utf8_to_wstr(path, NULL)))
7892 ret = wmkdir(wpath, mode);
7899rb_w32_mkdir(
const char *path,
int mode)
7904 if (!(wpath = filecp_to_wstr(path, NULL)))
7906 ret = wmkdir(wpath, mode);
7913wrmdir(
const WCHAR *wpath)
7917 const DWORD attr = GetFileAttributesW(wpath);
7918 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7919 SetFileAttributesW(wpath, attr & ~FILE_ATTRIBUTE_READONLY);
7921 if (RemoveDirectoryW(wpath) == FALSE) {
7922 errno = map_errno(GetLastError());
7924 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7925 SetFileAttributesW(wpath, attr);
7934rb_w32_rmdir(
const char *path)
7939 if (!(wpath = filecp_to_wstr(path, NULL)))
7941 ret = wrmdir(wpath);
7948rb_w32_urmdir(
const char *path)
7953 if (!(wpath = utf8_to_wstr(path, NULL)))
7955 ret = wrmdir(wpath);
7962wunlink(
const WCHAR *path)
7965 const DWORD SYMLINKD = FILE_ATTRIBUTE_REPARSE_POINT|FILE_ATTRIBUTE_DIRECTORY;
7967 const DWORD attr = GetFileAttributesW(path);
7968 if (attr == (DWORD)-1) {
7970 else if ((attr & SYMLINKD) == SYMLINKD) {
7971 ret = RemoveDirectoryW(path);
7974 if (attr & FILE_ATTRIBUTE_READONLY) {
7975 SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY);
7977 ret = DeleteFileW(path);
7980 errno = map_errno(GetLastError());
7982 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7983 SetFileAttributesW(path, attr);
7992rb_w32_uunlink(
const char *path)
7997 if (!(wpath = utf8_to_wstr(path, NULL)))
7999 ret = wunlink(wpath);
8006rb_w32_unlink(
const char *path)
8011 if (!(wpath = filecp_to_wstr(path, NULL)))
8013 ret = wunlink(wpath);
8020rb_w32_uchmod(
const char *path,
int mode)
8025 if (!(wpath = utf8_to_wstr(path, NULL)))
8027 ret = _wchmod(wpath, mode);
8034fchmod(
int fd,
int mode)
8038 LARGE_INTEGER CreationTime;
8039 LARGE_INTEGER LastAccessTime;
8040 LARGE_INTEGER LastWriteTime;
8041 LARGE_INTEGER ChangeTime;
8042 DWORD FileAttributes;
8043 } info = {{{0}}, {{0}}, {{0}},};
8044 HANDLE h = (HANDLE)_get_osfhandle(fd);
8046 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
8047 if (!(mode & 0200)) info.FileAttributes |= FILE_ATTRIBUTE_READONLY;
8048 if (!SetFileInformationByHandle(h, 0, &info,
sizeof(info))) {
8049 errno = map_errno(GetLastError());
8057rb_w32_isatty(
int fd)
8062 if (_get_osfhandle(fd) == -1) {
8065 if (!GetConsoleMode((HANDLE)_osfhnd(fd), &mode)) {
8077 int *ip = (
int *)(&x + 1) - 1;
8084rb_w32_inet_ntop(
int af,
const void *addr,
char *numaddr,
size_t numaddr_len)
8086 return (inet_ntop)(af, (
void *)addr, numaddr, numaddr_len);
8091rb_w32_inet_pton(
int af,
const char *src,
void *dst)
8093 return (inet_pton)(af, src, dst);
8098rb_w32_fd_is_text(
int fd)
8100 return _osfile(fd) & FTEXT;
8103#ifdef HAVE__GMTIME64_S
8104# ifndef HAVE__LOCALTIME64_S
8106# define HAVE__LOCALTIME64_S 1
8108# ifndef MINGW_HAS_SECURE_API
8109 _CRTIMP errno_t __cdecl _gmtime64_s(
struct tm* tm,
const __time64_t *time);
8110 _CRTIMP errno_t __cdecl _localtime64_s(
struct tm* tm,
const __time64_t *time);
8112# define gmtime_s _gmtime64_s
8113# define localtime_s _localtime64_s
8118gmtime_r(
const time_t *tp,
struct tm *rp)
8126 e = gmtime_s(rp, tp);
8127 if (e != 0)
goto error;
8133localtime_r(
const time_t *tp,
struct tm *rp)
8141 e = localtime_s(rp, tp);
8148rb_w32_wrap_io_handle(HANDLE h,
int flags)
8151 int len =
sizeof(tmp);
8152 int r = getsockopt((SOCKET)h, SOL_SOCKET, SO_DEBUG, (
char *)&tmp, &
len);
8153 if (r != SOCKET_ERROR || WSAGetLastError() != WSAENOTSOCK) {
8155 if (flags & O_NONBLOCK) {
8156 flags &= ~O_NONBLOCK;
8159 socklist_insert((SOCKET)h, f);
8161 else if (flags & O_NONBLOCK) {
8165 return rb_w32_open_osfhandle((intptr_t)h, flags);
8170rb_w32_unwrap_io_handle(
int fd)
8172 SOCKET sock = TO_SOCKET(fd);
8173 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
8174 if (!is_socket(sock)) {
8175 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
8176 constat_delete((HANDLE)sock);
8179 socklist_delete(&sock, NULL);
8184#if !defined(__MINGW64__) && defined(__MINGW64_VERSION_MAJOR)
8190rb_w32_pow(
double x,
double y)
8194 unsigned int default_control = _controlfp(0, 0);
8195 _controlfp(_PC_64, _MCW_PC);
8198 _controlfp(default_control, _MCW_PC);
8206 BY_HANDLE_FILE_INFORMATION bhfi;
8217 tmp = rb_check_convert_type_with_id(*file,
T_FILE,
"IO", idTo_io);
8220 if (f == (HANDLE)-1)
return INVALID_HANDLE_VALUE;
8229 tmp = rb_str_encode_ospath(*file);
8230 len = MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, NULL, 0);
8232 MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, ptr,
len);
8233 f = CreateFileW(ptr, 0,
8234 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
8235 FILE_FLAG_BACKUP_SEMANTICS, NULL);
8237 if (f == INVALID_HANDLE_VALUE)
return f;
8240 if (GetFileType(f) == FILE_TYPE_DISK) {
8241 ZeroMemory(st,
sizeof(*st));
8242 if (get_ino(f, &st->info.fii)) {
8243 st->file_id_p = TRUE;
8246 else if (GetLastError() != ERROR_INVALID_PARAMETER) {
8248 return INVALID_HANDLE_VALUE;
8252 if (GetFileInformationByHandle(f, &st->info.bhfi)) {
8253 st->file_id_p = FALSE;
8257 if (ret) CloseHandle(ret);
8258 return INVALID_HANDLE_VALUE;
8262close_handle(
VALUE h)
8264 CloseHandle((HANDLE)h);
8274call_w32_io_info(
VALUE arg)
8277 return (
VALUE)w32_io_info(p->fname, p->st);
8281rb_w32_file_identical_p(
VALUE fname1,
VALUE fname2)
8284 HANDLE f1 = 0, f2 = 0;
8286 f1 = w32_io_info(&fname1, &st1);
8287 if (f1 == INVALID_HANDLE_VALUE)
return Qfalse;
8290 arg.fname = &fname2;
8295 f2 = w32_io_info(&fname2, &st2);
8297 if (f2 == INVALID_HANDLE_VALUE)
return Qfalse;
8298 if (f2) CloseHandle(f2);
8300 if (st1.file_id_p != st2.file_id_p)
return Qfalse;
8301 if (!st1.file_id_p) {
8302 if (st1.info.bhfi.dwVolumeSerialNumber == st2.info.bhfi.dwVolumeSerialNumber &&
8303 st1.info.bhfi.nFileIndexHigh == st2.info.bhfi.nFileIndexHigh &&
8304 st1.info.bhfi.nFileIndexLow == st2.info.bhfi.nFileIndexLow)
8308 if (st1.info.fii.VolumeSerialNumber == st2.info.fii.VolumeSerialNumber &&
8309 memcmp(&st1.info.fii.FileId, &st2.info.fii.FileId,
sizeof(
FILE_ID_128)) == 0)
8316rb_w32_set_thread_description(HANDLE th,
const WCHAR *name)
8319 typedef HRESULT (WINAPI *set_thread_description_func)(HANDLE, PCWSTR);
8320 static set_thread_description_func set_thread_description =
8321 (set_thread_description_func)-1;
8322 if (set_thread_description == (set_thread_description_func)-1) {
8324 set_thread_description = (set_thread_description_func)
8325 get_proc_address(
"kernel32",
"SetThreadDescription", NULL);
8327 if (set_thread_description) {
8328 result = set_thread_description(th, name);
8334rb_w32_set_thread_description_str(HANDLE th,
VALUE name)
8336 int idx, result = FALSE;
8340 return rb_w32_set_thread_description(th, L
"");
8343 idx = rb_enc_get_index(name);
8344 if (idx == ENCINDEX_UTF_16LE) {
8345 result = rb_w32_set_thread_description(th, s);
8348 name =
rb_str_conv_enc(name, rb_enc_from_index(idx), rb_utf8_encoding());
8349 s = mbstr_to_wstr(CP_UTF8, RSTRING_PTR(name), RSTRING_LEN(name)+1, NULL);
8350 result = rb_w32_set_thread_description(th, s);
8360rb_w32_mmap(
void *addr,
size_t len,
int prot,
int flags,
int fd, rb_off_t offset)
8364 DWORD protect = PAGE_EXECUTE_READWRITE;
8366 if (fd > 0 || offset) {
8381 ptr = VirtualAlloc(addr,
len, MEM_RESERVE | MEM_COMMIT, protect);
8383 errno = rb_w32_map_errno(GetLastError());
8391rb_w32_munmap(
void *addr,
size_t len)
8393 if (!VirtualFree(addr, 0, MEM_RELEASE)) {
8394 errno = rb_w32_map_errno(GetLastError());
8402rb_w32_mprotect(
void *addr,
size_t len,
int prot)
8418 if (prot & PROT_EXEC) {
8419 if (!FlushInstructionCache(GetCurrentProcess(), addr,
len)) {
8420 errno = rb_w32_map_errno(GetLastError());
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
int ruby_glob_func(const char *path, VALUE arg, void *enc)
Type of a glob callback function.
#define T_FILE
Old name of RUBY_T_FILE.
#define ALLOCV
Old name of RB_ALLOCV.
#define ISSPACE
Old name of rb_isspace.
#define ALLOC
Old name of RB_ALLOC.
#define xfree
Old name of ruby_xfree.
#define xrealloc
Old name of ruby_xrealloc.
#define ECONV_UNDEF_REPLACE
Old name of RUBY_ECONV_UNDEF_REPLACE.
#define ENCODING_GET(obj)
Old name of RB_ENCODING_GET.
#define ECONV_INVALID_REPLACE
Old name of RUBY_ECONV_INVALID_REPLACE.
#define ASSUME
Old name of RBIMPL_ASSUME.
#define ALLOC_N
Old name of RB_ALLOC_N.
#define ISALPHA
Old name of rb_isalpha.
#define Qtrue
Old name of RUBY_Qtrue.
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
#define ISALNUM
Old name of rb_isalnum.
#define ALLOCV_END
Old name of RB_ALLOCV_END.
#define RBIMPL_ATTR_NONNULL(list)
Wraps (or simulates) __attribute__((nonnull))
VALUE rb_str_conv_enc(VALUE str, rb_encoding *from, rb_encoding *to)
Encoding conversion main routine.
VALUE rb_str_conv_enc_opts(VALUE str, rb_encoding *from, rb_encoding *to, int ecflags, VALUE ecopts)
Identical to rb_str_conv_enc(), except it additionally takes IO encoder options.
int rb_econv_has_convpath_p(const char *from_encoding, const char *to_encoding)
Queries if there is more than one way to convert between the passed two encodings.
void rb_write_error2(const char *str, long len)
Identical to rb_write_error(), except it additionally takes the message's length.
VALUE rb_str_cat(VALUE dst, const char *src, long srclen)
Destructively appends the passed contents to the string.
#define rb_strlen_lit(str)
Length of a string literal.
#define rb_utf8_str_new(str, len)
Identical to rb_str_new, except it generates a string of "UTF-8" encoding.
VALUE rb_f_notimplement(int argc, const VALUE *argv, VALUE obj, VALUE marker)
Raises rb_eNotImpError.
int rb_io_descriptor(VALUE io)
Returns an integer representing the numeric file descriptor for io.
int len
Length of the buffer.
char * ruby_strdup(const char *str)
This is our own version of strdup(3) that uses ruby_xmalloc() instead of system malloc (benefits our ...
#define strdup(s)
Just another name of ruby_strdup.
void ruby_vm_at_exit(void(*func)(ruby_vm_t *))
ruby_vm_at_exit registers a function func to be invoked when a VM passed away.
void rb_w32_fd_dup(rb_fdset_t *dst, const rb_fdset_t *src)
Identical to rb_w32_fd_copy(), except it copies unlimited number of file descriptors.
void rb_w32_fd_copy(rb_fdset_t *dst, const fd_set *src, int max)
Destructively overwrites an fdset with another.
void rb_fd_term(rb_fdset_t *f)
Destroys the rb_fdset_t, releasing any memory and resources it used.
#define rb_long2int
Just another name of rb_long2int_inline.
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
#define ALLOCA_N(type, n)
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
VALUE type(ANYARGS)
ANYARGS-ed function type.
VALUE rb_ensure(type *q, VALUE w, type *e, VALUE r)
An equivalent of ensure clause.
#define PRI_PIDT_PREFIX
A rb_sprintf() format prefix to be used for a pid_t parameter.
#define rb_fd_init
Initialises the :given :rb_fdset_t.
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
#define FilePathValue(v)
Ensures that the parameter object is a path.
#define errno
Ractor-aware version of errno.
The data structure which wraps the fd_set bitmap used by select(2).
fd_set * fdset
File descriptors buffer.
int capa
Maximum allowed number of FDs.
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
uintptr_t VALUE
Type that represents a Ruby object.