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)
85#define CharNext(p) CharNextExA(cp, (p), 0)
86#define dln_find_exe_r rb_w32_udln_find_exe_r
87#define dln_find_file_r rb_w32_udln_find_file_r
94#define dln_find_exe_r(fname, path, buf, size) rb_w32_udln_find_exe_r(fname, path, buf, size, cp)
95#define dln_find_file_r(fname, path, buf, size) rb_w32_udln_find_file_r(fname, path, buf, size, cp)
101# define PATH_MAX MAX_PATH
102# elif defined HAVE_SYS_PARAM_H
103# include <sys/param.h>
104# define PATH_MAX MAXPATHLEN
116#define _filbuf _fgetc_nolock
117#define _flsbuf _fputc_nolock
118#define enough_to_get(n) (--(n) >= 0)
119#define enough_to_put(n) (--(n) >= 0)
122#define Debug(something) something
124#define Debug(something)
127#define TO_SOCKET(x) _get_osfhandle(x)
129int rb_w32_reparse_symlink_p(
const WCHAR *path);
131static int has_redirection(
const char *, UINT);
132int rb_w32_wait_events(HANDLE *events,
int num, DWORD timeout);
133static int rb_w32_open_osfhandle(intptr_t osfhandle,
int flags);
134static int wstati128(
const WCHAR *path,
struct stati128 *st, BOOL lstat);
135VALUE rb_w32_conv_from_wchar(
const WCHAR *wstr, rb_encoding *enc);
136int ruby_brace_glob_with_enc(
const char *str,
int flags,
ruby_glob_func *func,
VALUE arg, rb_encoding *enc);
137static FARPROC get_proc_address(
const char *module,
const char *func, HANDLE *mh);
139#define RUBY_CRITICAL if (0) {} else
146 { ERROR_INVALID_FUNCTION, EINVAL },
147 { ERROR_FILE_NOT_FOUND, ENOENT },
148 { ERROR_PATH_NOT_FOUND, ENOENT },
149 { ERROR_TOO_MANY_OPEN_FILES, EMFILE },
150 { ERROR_ACCESS_DENIED, EACCES },
151 { ERROR_INVALID_HANDLE, EBADF },
152 { ERROR_ARENA_TRASHED, ENOMEM },
153 { ERROR_NOT_ENOUGH_MEMORY, ENOMEM },
154 { ERROR_INVALID_BLOCK, ENOMEM },
155 { ERROR_BAD_ENVIRONMENT, E2BIG },
156 { ERROR_BAD_FORMAT, ENOEXEC },
157 { ERROR_INVALID_ACCESS, EINVAL },
158 { ERROR_INVALID_DATA, EINVAL },
159 { ERROR_INVALID_DRIVE, ENOENT },
160 { ERROR_CURRENT_DIRECTORY, EACCES },
161 { ERROR_NOT_SAME_DEVICE, EXDEV },
162 { ERROR_NO_MORE_FILES, ENOENT },
163 { ERROR_WRITE_PROTECT, EROFS },
164 { ERROR_BAD_UNIT, ENODEV },
165 { ERROR_NOT_READY, ENXIO },
166 { ERROR_BAD_COMMAND, EACCES },
167 { ERROR_CRC, EACCES },
168 { ERROR_BAD_LENGTH, EACCES },
170 { ERROR_NOT_DOS_DISK, EACCES },
171 { ERROR_SECTOR_NOT_FOUND, EACCES },
172 { ERROR_OUT_OF_PAPER, EACCES },
173 { ERROR_WRITE_FAULT, EIO },
174 { ERROR_READ_FAULT, EIO },
175 { ERROR_GEN_FAILURE, EACCES },
176 { ERROR_LOCK_VIOLATION, EACCES },
177 { ERROR_SHARING_VIOLATION, EACCES },
178 { ERROR_WRONG_DISK, EACCES },
179 { ERROR_SHARING_BUFFER_EXCEEDED, EACCES },
180 { ERROR_BAD_NETPATH, ENOENT },
181 { ERROR_NETWORK_ACCESS_DENIED, EACCES },
182 { ERROR_BAD_NET_NAME, ENOENT },
183 { ERROR_FILE_EXISTS, EEXIST },
184 { ERROR_CANNOT_MAKE, EACCES },
185 { ERROR_FAIL_I24, EACCES },
186 { ERROR_INVALID_PARAMETER, EINVAL },
187 { ERROR_NO_PROC_SLOTS, EAGAIN },
188 { ERROR_DRIVE_LOCKED, EACCES },
189 { ERROR_BROKEN_PIPE, EPIPE },
190 { ERROR_DISK_FULL, ENOSPC },
191 { ERROR_INVALID_TARGET_HANDLE, EBADF },
192 { ERROR_INVALID_HANDLE, EINVAL },
193 { ERROR_WAIT_NO_CHILDREN, ECHILD },
194 { ERROR_CHILD_NOT_COMPLETE, ECHILD },
195 { ERROR_DIRECT_ACCESS_HANDLE, EBADF },
196 { ERROR_NEGATIVE_SEEK, EINVAL },
197 { ERROR_SEEK_ON_DEVICE, EACCES },
198 { ERROR_DIR_NOT_EMPTY, ENOTEMPTY },
199 { ERROR_DIRECTORY, ENOTDIR },
200 { ERROR_NOT_LOCKED, EACCES },
201 { ERROR_BAD_PATHNAME, ENOENT },
202 { ERROR_MAX_THRDS_REACHED, EAGAIN },
203 { ERROR_LOCK_FAILED, EACCES },
204 { ERROR_ALREADY_EXISTS, EEXIST },
205 { ERROR_INVALID_STARTING_CODESEG, ENOEXEC },
206 { ERROR_INVALID_STACKSEG, ENOEXEC },
207 { ERROR_INVALID_MODULETYPE, ENOEXEC },
208 { ERROR_INVALID_EXE_SIGNATURE, ENOEXEC },
209 { ERROR_EXE_MARKED_INVALID, ENOEXEC },
210 { ERROR_BAD_EXE_FORMAT, ENOEXEC },
211 { ERROR_ITERATED_DATA_EXCEEDS_64k,ENOEXEC },
212 { ERROR_INVALID_MINALLOCSIZE, ENOEXEC },
213 { ERROR_DYNLINK_FROM_INVALID_RING,ENOEXEC },
214 { ERROR_IOPL_NOT_ENABLED, ENOEXEC },
215 { ERROR_INVALID_SEGDPL, ENOEXEC },
216 { ERROR_AUTODATASEG_EXCEEDS_64k, ENOEXEC },
217 { ERROR_RING2SEG_MUST_BE_MOVABLE, ENOEXEC },
218 { ERROR_RELOC_CHAIN_XEEDS_SEGLIM, ENOEXEC },
219 { ERROR_INFLOOP_IN_RELOC_CHAIN, ENOEXEC },
220 { ERROR_FILENAME_EXCED_RANGE, ENOENT },
221 { ERROR_NESTING_NOT_ALLOWED, EAGAIN },
222#ifndef ERROR_PIPE_LOCAL
223#define ERROR_PIPE_LOCAL 229L
225 { ERROR_PIPE_LOCAL, EPIPE },
226 { ERROR_BAD_PIPE, EPIPE },
227 { ERROR_PIPE_BUSY, EAGAIN },
228 { ERROR_NO_DATA, EPIPE },
229 { ERROR_PIPE_NOT_CONNECTED, EPIPE },
230 { ERROR_OPERATION_ABORTED, EINTR },
231 { ERROR_NOT_ENOUGH_QUOTA, ENOMEM },
232 { ERROR_MOD_NOT_FOUND, ENOENT },
233 { ERROR_PRIVILEGE_NOT_HELD, EACCES, },
234 { ERROR_CANT_RESOLVE_FILENAME, ELOOP, },
237 { WSAEACCES, EACCES },
238 { WSAEFAULT, EFAULT },
239 { WSAEINVAL, EINVAL },
240 { WSAEMFILE, EMFILE },
241 { WSAEWOULDBLOCK, EWOULDBLOCK },
242 { WSAEINPROGRESS, EINPROGRESS },
243 { WSAEALREADY, EALREADY },
244 { WSAENOTSOCK, ENOTSOCK },
245 { WSAEDESTADDRREQ, EDESTADDRREQ },
246 { WSAEMSGSIZE, EMSGSIZE },
247 { WSAEPROTOTYPE, EPROTOTYPE },
248 { WSAENOPROTOOPT, ENOPROTOOPT },
249 { WSAEPROTONOSUPPORT, EPROTONOSUPPORT },
250 { WSAESOCKTNOSUPPORT, ESOCKTNOSUPPORT },
251 { WSAEOPNOTSUPP, EOPNOTSUPP },
252 { WSAEPFNOSUPPORT, EPFNOSUPPORT },
253 { WSAEAFNOSUPPORT, EAFNOSUPPORT },
254 { WSAEADDRINUSE, EADDRINUSE },
255 { WSAEADDRNOTAVAIL, EADDRNOTAVAIL },
256 { WSAENETDOWN, ENETDOWN },
257 { WSAENETUNREACH, ENETUNREACH },
258 { WSAENETRESET, ENETRESET },
259 { WSAECONNABORTED, ECONNABORTED },
260 { WSAECONNRESET, ECONNRESET },
261 { WSAENOBUFS, ENOBUFS },
262 { WSAEISCONN, EISCONN },
263 { WSAENOTCONN, ENOTCONN },
264 { WSAESHUTDOWN, ESHUTDOWN },
265 { WSAETOOMANYREFS, ETOOMANYREFS },
266 { WSAETIMEDOUT, ETIMEDOUT },
267 { WSAECONNREFUSED, ECONNREFUSED },
269 { WSAENAMETOOLONG, ENAMETOOLONG },
270 { WSAEHOSTDOWN, EHOSTDOWN },
271 { WSAEHOSTUNREACH, EHOSTUNREACH },
272 { WSAEPROCLIM, EPROCLIM },
273 { WSAENOTEMPTY, ENOTEMPTY },
274 { WSAEUSERS, EUSERS },
275 { WSAEDQUOT, EDQUOT },
276 { WSAESTALE, ESTALE },
277 { WSAEREMOTE, EREMOTE },
282rb_w32_map_errno(DWORD winerr)
290 for (i = 0; i < (int)(
sizeof(errmap) /
sizeof(*errmap)); i++) {
291 if (errmap[i].winerr == winerr) {
292 return errmap[i].err;
296 if (winerr >= WSABASEERR) {
302#define map_errno rb_w32_map_errno
304static const char *NTLoginName;
306static OSVERSIONINFO osver;
312 memset(&osver, 0,
sizeof(OSVERSIONINFO));
313 osver.dwOSVersionInfoSize =
sizeof(OSVERSIONINFO);
314 GetVersionEx(&osver);
321 return osver.dwMajorVersion;
332 DWORD err = GetLastError(); \
333 if (err == ERROR_LOCK_VIOLATION || err == ERROR_IO_PENDING) \
334 errno = EWOULDBLOCK; \
335 else if (err == ERROR_NOT_LOCKED) \
338 errno = map_errno(err); \
341#define LK_LEN ULONG_MAX
345flock_winnt(uintptr_t self,
int argc, uintptr_t* argv)
349 const HANDLE fh = (HANDLE)self;
350 const int oper = argc;
352 memset(&o, 0,
sizeof(o));
356 LK_ERR(LockFileEx(fh, 0, 0, LK_LEN, LK_LEN, &o), i);
359 LK_ERR(LockFileEx(fh, LOCKFILE_EXCLUSIVE_LOCK, 0, LK_LEN, LK_LEN, &o), i);
361 case LOCK_SH|LOCK_NB:
362 LK_ERR(LockFileEx(fh, LOCKFILE_FAIL_IMMEDIATELY, 0, LK_LEN, LK_LEN, &o), i);
364 case LOCK_EX|LOCK_NB:
365 LK_ERR(LockFileEx(fh,
366 LOCKFILE_EXCLUSIVE_LOCK|LOCKFILE_FAIL_IMMEDIATELY,
367 0, LK_LEN, LK_LEN, &o), i);
370 case LOCK_UN|LOCK_NB:
371 LK_ERR(UnlockFileEx(fh, 0, LK_LEN, LK_LEN, &o), i);
384flock(
int fd,
int oper)
386 const asynchronous_func_t locker = flock_winnt;
388 return rb_w32_asynchronize(locker,
389 (
VALUE)_get_osfhandle(fd), oper, NULL,
395translate_wchar(WCHAR *p,
int from,
int to)
406translate_char(
char *p,
int from,
int to, UINT cp)
409 if ((
unsigned char)*p == from)
411 p = CharNextExA(cp, p, 0);
416#ifndef CSIDL_LOCAL_APPDATA
417#define CSIDL_LOCAL_APPDATA 28
419#ifndef CSIDL_COMMON_APPDATA
420#define CSIDL_COMMON_APPDATA 35
423#define CSIDL_WINDOWS 36
426#define CSIDL_SYSTEM 37
429#define CSIDL_PROFILE 40
434get_special_folder(
int n, WCHAR *buf,
size_t len)
440 if (SHGetSpecialFolderLocation(NULL, n, &pidl) == 0) {
441 f = SHGetPathFromIDListEx(pidl, buf,
len, 0);
443 alloc->lpVtbl->Free(alloc, pidl);
444 alloc->lpVtbl->Release(alloc);
451regulate_path(WCHAR *path)
453 WCHAR *p = translate_wchar(path, L
'\\', L
'/');
454 if (p - path == 2 && path[1] == L
':') {
462get_proc_address(
const char *module,
const char *func, HANDLE *mh)
468 h = LoadLibrary(module);
470 h = GetModuleHandle(module);
474 ptr = GetProcAddress(h, func);
486rb_w32_special_folder(
int type)
488 WCHAR path[PATH_MAX];
490 if (!get_special_folder(
type, path, numberof(path)))
return Qnil;
492 return rb_w32_conv_from_wchar(path, rb_filesystem_encoding());
497rb_w32_system_tmpdir(WCHAR *path, UINT
len)
499 static const WCHAR temp[] = L
"temp";
502 if (!get_special_folder(CSIDL_LOCAL_APPDATA, path,
len)) {
503 if (GetSystemWindowsDirectoryW(path,
len))
return 0;
505 p = translate_wchar(path, L
'\\', L
'/');
506 if (p == path || *(p - 1) != L
'/') *p++ = L
'/';
507 if ((UINT)(p - path + numberof(temp)) >=
len)
return 0;
508 memcpy(p, temp,
sizeof(temp));
509 return (UINT)(p - path + numberof(temp) - 1);
524 WCHAR *buffer = NULL;
525 size_t buffer_len = MAX_PATH,
len = 0;
527 HOME_NONE, ENV_HOME, ENV_USERPROFILE, ENV_DRIVEPATH
528 } home_type = HOME_NONE;
530 if ((
len = GetEnvironmentVariableW(L
"HOME", NULL, 0)) != 0) {
532 home_type = ENV_HOME;
534 else if ((
len = GetEnvironmentVariableW(L
"USERPROFILE", NULL, 0)) != 0) {
536 home_type = ENV_USERPROFILE;
538 else if ((
len = GetEnvironmentVariableW(L
"HOMEDRIVE", NULL, 0)) != 0) {
540 if ((
len = GetEnvironmentVariableW(L
"HOMEPATH", NULL, 0)) != 0) {
542 home_type = ENV_DRIVEPATH;
547 buffer = malloc(
sizeof(WCHAR) * buffer_len);
548 if (buffer == NULL)
return NULL;
552 GetEnvironmentVariableW(L
"HOME", buffer, buffer_len);
554 case ENV_USERPROFILE:
555 GetEnvironmentVariableW(L
"USERPROFILE", buffer, buffer_len);
558 len = GetEnvironmentVariableW(L
"HOMEDRIVE", buffer, buffer_len);
559 GetEnvironmentVariableW(L
"HOMEPATH", buffer +
len, buffer_len -
len);
562 if (!get_special_folder(CSIDL_PROFILE, buffer, buffer_len) &&
563 !get_special_folder(CSIDL_PERSONAL, buffer, buffer_len)) {
567 buffer = realloc(buffer,
sizeof(WCHAR) * (lstrlenW(buffer) + 1));
572 regulate_path(buffer);
583 if (!GetEnvironmentVariableW(L
"HOME", env, numberof(env))) {
584 WCHAR *whome = rb_w32_home_dir();
586 _wputenv_s(L
"HOME", whome);
591 if (!GetEnvironmentVariableW(L
"USER", env, numberof(env))) {
593 if (!GetEnvironmentVariableW(L
"USERNAME", env, numberof(env)) &&
594 !GetUserNameW(env, (
len = numberof(env), &
len))) {
595 NTLoginName =
"<Unknown>";
598 _wputenv_s(L
"USER", env);
599 NTLoginName = rb_w32_wstr_to_mbstr(CP_UTF8, env, -1, NULL);
603 NTLoginName = rb_w32_wstr_to_mbstr(CP_UTF8, env, -1, NULL);
606 if (!GetEnvironmentVariableW(L
"TMPDIR", env, numberof(env)) &&
607 !GetEnvironmentVariableW(L
"TMP", env, numberof(env)) &&
608 !GetEnvironmentVariableW(L
"TEMP", env, numberof(env)) &&
609 rb_w32_system_tmpdir(env, numberof(env))) {
610 _wputenv_s(L
"TMPDIR", env);
614static void init_stdhandle(
void);
618invalid_parameter(
const wchar_t *expr,
const wchar_t *func,
const wchar_t *file,
unsigned int line, uintptr_t dummy)
623int ruby_w32_rtc_error;
630rtc_error_handler(
int e, const
char *src,
int line, const
char *exe, const
char *fmt, ...)
635 if (!ruby_w32_rtc_error)
return 0;
636 str = rb_sprintf(
"%s:%d: ", src, line);
638 rb_str_vcatf(str, fmt, ap);
646static CRITICAL_SECTION select_mutex;
648static CRITICAL_SECTION socklist_mutex;
649static st_table *socklist = NULL;
651static CRITICAL_SECTION conlist_mutex;
652static st_table *conlist = NULL;
653#define conlist_disabled ((st_table *)-1)
655#define thread_exclusive(obj) \
656 for (bool exclusive_for_##obj = (EnterCriticalSection(&obj##_mutex), true); \
657 exclusive_for_##obj; \
658 exclusive_for_##obj = (LeaveCriticalSection(&obj##_mutex), false))
662static DWORD uenvarea_key;
666free_uenvarea(
void *uenvarea)
674 int state, seq[16], reverse;
679enum {constat_init = -2, constat_esc = -1, constat_seq = 0};
683free_conlist(st_data_t key, st_data_t val, st_data_t arg)
691constat_delete(HANDLE h)
693 thread_exclusive(conlist) {
694 if (conlist && conlist != conlist_disabled) {
695 st_data_t key = (st_data_t)h, val;
696 st_delete(conlist, &key, &val);
707 DeleteCriticalSection(&select_mutex);
708 DeleteCriticalSection(&socklist_mutex);
709 DeleteCriticalSection(&conlist_mutex);
710 FlsFree(uenvarea_key);
717 EnterCriticalSection(&socklist_mutex);
719 st_free_table(socklist);
722 LeaveCriticalSection(&socklist_mutex);
724 EnterCriticalSection(&conlist_mutex);
725 if (conlist && conlist != conlist_disabled) {
726 st_foreach(conlist, free_conlist, 0);
727 st_free_table(conlist);
730 LeaveCriticalSection(&conlist_mutex);
733#define ATOMIC_LONG_CAS(var, oldval, newval) InterlockedCompareExchange(&(var), (newval), (oldval))
737install_vm_exit_handler(
void)
739 static LONG installed = 0;
742 while ((i = ATOMIC_LONG_CAS(installed, 0, -1)) != 1) {
748 ATOMIC_LONG_CAS(installed, -1, 1);
764 version = MAKEWORD(2, 0);
765 if (WSAStartup(version, &retdata))
766 rb_fatal(
"Unable to locate winsock library!");
767 if (LOBYTE(retdata.wVersion) != 2)
768 rb_fatal(
"could not find version 2 of winsock dll");
770 InitializeCriticalSection(&select_mutex);
771 InitializeCriticalSection(&socklist_mutex);
772 InitializeCriticalSection(&conlist_mutex);
774 atexit(exit_handler);
777#define MAKE_SOCKDATA(af, fl) ((int)((((int)af)<<4)|((fl)&0xFFFF)))
778#define GET_FAMILY(v) ((int)(((v)>>4)&0xFFFF))
779#define GET_FLAGS(v) ((int)((v)&0xFFFF))
783socklist_insert(SOCKET sock,
int flag)
787 thread_exclusive(socklist) {
789 socklist = st_init_numtable();
790 install_vm_exit_handler();
792 ret = st_insert(socklist, (st_data_t)sock, (st_data_t)flag);
800socklist_lookup(SOCKET sock,
int *flagp)
805 thread_exclusive(socklist) {
806 if (!socklist)
continue;
807 ret = st_lookup(socklist, (st_data_t)sock, &data);
817socklist_delete(SOCKET *sockp,
int *flagp)
823 thread_exclusive(socklist) {
824 if (!socklist)
continue;
825 key = (st_data_t)*sockp;
827 data = (st_data_t)*flagp;
828 ret = st_delete(socklist, &key, &data);
830 *sockp = (SOCKET)key;
840# define _CrtSetReportMode(type,mode) ((void)0)
841# define _RTC_SetErrorFunc(func) ((void)0)
843static void set_pioinfo_extra(
void);
844static int w32_cmdvector(
const WCHAR *,
char ***, UINT, rb_encoding *);
850rb_w32_sysinit(
int *argc,
char ***argv)
852 _CrtSetReportMode(_CRT_ASSERT, 0);
853 _set_invalid_parameter_handler(invalid_parameter);
854 _RTC_SetErrorFunc(rtc_error_handler);
856 SetErrorMode(SEM_FAILCRITICALERRORS|SEM_NOGPFAULTERRORBOX);
863 *argc = w32_cmdvector(GetCommandLineW(), argv, CP_UTF8, &OnigEncodingUTF_8);
871 if ((uenvarea_key = FlsAlloc(free_uenvarea)) == FLS_OUT_OF_INDEXES)
872 rb_bug(
"FlsAlloc() for uenvarea_key fails");
884 return (
char *)NTLoginName;
887#define MAXCHILDNUM 256
896#define FOREACH_CHILD(v) do { \
897 struct ChildRecord* v; \
898 for (v = ChildRecord; v < ChildRecord + sizeof(ChildRecord) / sizeof(ChildRecord[0]); ++v)
899#define END_FOREACH_CHILD } while (0)
903FindChildSlot(rb_pid_t pid)
906 FOREACH_CHILD(child) {
907 if (child->pid == pid) {
916FindChildSlotByHandle(HANDLE h)
919 FOREACH_CHILD(child) {
920 if (child->hProcess == h) {
931 HANDLE h = child->hProcess;
932 child->hProcess = NULL;
939FindFreeChildSlot(
void)
941 FOREACH_CHILD(child) {
944 child->hProcess = NULL;
958#define InternalCmdsMax 8
959static const char szInternalCmds[][InternalCmdsMax+2] = {
1013internal_match(
const void *key,
const void *elem)
1015 return strncmp(key, ((
const char *)elem) + 1, InternalCmdsMax);
1020is_command_com(
const char *interp)
1022 int i = strlen(interp) - 11;
1024 if ((i == 0 || (i > 0 && isdirsep(interp[i-1]))) &&
1025 strcasecmp(interp+i,
"command.com") == 0) {
1031static int internal_cmd_match(
const char *cmdname,
int nt);
1035is_internal_cmd(
const char *cmd,
int nt)
1037 char cmdname[9], *b = cmdname, c;
1040 if (!(c = *cmd++))
return 0;
1041 }
while (isspace(c));
1044 while (isalpha(c)) {
1046 if (b == cmdname +
sizeof(cmdname))
return 0;
1049 if (c ==
'.') c = *cmd;
1051 case '<':
case '>':
case '|':
1053 case '\0':
case ' ':
case '\t':
case '\n':
1059 return internal_cmd_match(cmdname, nt);
1064internal_cmd_match(
const char *cmdname,
int nt)
1068 nm = bsearch(cmdname, szInternalCmds,
1069 sizeof(szInternalCmds) /
sizeof(*szInternalCmds),
1070 sizeof(*szInternalCmds),
1072 if (!nm || !(nm[0] & (nt ? 2 : 1)))
1079rb_w32_get_osfhandle(
int fh)
1081 return _get_osfhandle(fh);
1086join_argv(
char *cmd,
char *
const *argv, BOOL escape, UINT cp,
int backslash)
1090 int len, n, bs, quote;
1092 for (t = argv, q = cmd,
len = 0; (p = *t) != 0; t++) {
1095 if (!*p || strpbrk(p,
" \t\"'")) {
1100 for (bs = 0; *p; ++p) {
1114 memset(q,
'\\', bs);
1119 case '<':
case '>':
case '|':
case '^':
1120 if (escape && !quote) {
1121 len += (n = p - s) + 1;
1132 p = CharNextExA(cp, p, 0) - 1;
1136 len += (n = p - s) + 1;
1140 if (backslash > 0) {
1143 translate_char(q,
'/',
'\\', cp);
1146 if (quote) *q++ =
'"';
1159#define STRNDUPV(ptr, v, src, len) \
1160 (((char *)memcpy(((ptr) = ALLOCV((v), (len) + 1)), (src), (len)))[len] = 0)
1164check_spawn_mode(
int mode)
1186 if (mode == P_OVERLAY) {
1187 WaitForSingleObject(child->hProcess, INFINITE);
1188 GetExitCodeProcess(child->hProcess, &exitcode);
1189 CloseChildHandle(child);
1197CreateChild(
struct ChildRecord *child,
const WCHAR *cmd,
const WCHAR *prog, HANDLE hInput, HANDLE hOutput, HANDLE hError, DWORD dwCreationFlags)
1200 STARTUPINFOW aStartupInfo;
1201 PROCESS_INFORMATION aProcessInformation;
1202 SECURITY_ATTRIBUTES sa;
1204 if (!cmd && !prog) {
1214 sa.nLength =
sizeof(SECURITY_ATTRIBUTES);
1215 sa.lpSecurityDescriptor = NULL;
1216 sa.bInheritHandle = TRUE;
1218 memset(&aStartupInfo, 0,
sizeof(aStartupInfo));
1219 memset(&aProcessInformation, 0,
sizeof(aProcessInformation));
1220 aStartupInfo.cb =
sizeof(aStartupInfo);
1221 aStartupInfo.dwFlags = STARTF_USESTDHANDLES;
1223 aStartupInfo.hStdInput = hInput;
1226 aStartupInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
1229 aStartupInfo.hStdOutput = hOutput;
1232 aStartupInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
1235 aStartupInfo.hStdError = hError;
1238 aStartupInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
1241 dwCreationFlags |= NORMAL_PRIORITY_CLASS;
1243 if (lstrlenW(cmd) > 32767) {
1250 fRet = CreateProcessW(prog, (WCHAR *)cmd, &sa, &sa,
1251 sa.bInheritHandle, dwCreationFlags, NULL, NULL,
1252 &aStartupInfo, &aProcessInformation);
1253 errno = map_errno(GetLastError());
1261 CloseHandle(aProcessInformation.hThread);
1263 child->hProcess = aProcessInformation.hProcess;
1264 child->pid = (rb_pid_t)aProcessInformation.dwProcessId;
1271is_batch(
const char *cmd)
1273 int len = strlen(cmd);
1274 if (
len <= 4)
return 0;
1276 if (*cmd++ !=
'.')
return 0;
1277 if (strcasecmp(cmd,
"bat") == 0)
return 1;
1278 if (strcasecmp(cmd,
"cmd") == 0)
return 1;
1282#define filecp rb_w32_filecp
1283#define mbstr_to_wstr rb_w32_mbstr_to_wstr
1284#define wstr_to_mbstr rb_w32_wstr_to_mbstr
1285#define acp_to_wstr(str, plen) mbstr_to_wstr(CP_ACP, str, -1, plen)
1286#define wstr_to_acp(str, plen) wstr_to_mbstr(CP_ACP, str, -1, plen)
1287#define filecp_to_wstr(str, plen) mbstr_to_wstr(filecp(), str, -1, plen)
1288#define wstr_to_filecp(str, plen) wstr_to_mbstr(filecp(), str, -1, plen)
1289#define utf8_to_wstr(str, plen) mbstr_to_wstr(CP_UTF8, str, -1, plen)
1290#define wstr_to_utf8(str, plen) wstr_to_mbstr(CP_UTF8, str, -1, plen)
1294w32_spawn(
int mode,
const char *cmd,
const char *prog, UINT cp)
1296 char fbuf[PATH_MAX];
1298 const char *shell = NULL;
1299 WCHAR *wcmd = NULL, *wshell = NULL;
1305 char *cmd_sep = NULL;
1307 if (check_spawn_mode(mode))
return -1;
1310 if (!(p = dln_find_exe_r(prog, NULL, fbuf,
sizeof(fbuf)))) {
1315 translate_char(p,
'/',
'\\', cp);
1322 if ((shell = w32_getenv(
"RUBYSHELL", cp)) && (redir = has_redirection(cmd, cp))) {
1323 size_t shell_len = strlen(shell);
1324 size_t cmd_len = strlen(cmd) +
sizeof(
" -c ") + 2;
1325 char *tmp =
ALLOCV(v, shell_len + cmd_len);
1326 memcpy(tmp, shell, shell_len + 1);
1327 translate_char(tmp,
'/',
'\\', cp);
1328 snprintf(tmp + shell_len, cmd_len,
" -c \"%s\"", cmd);
1331 else if ((shell = w32_getenv(
"COMSPEC", cp)) &&
1332 (nt = !is_command_com(shell),
1333 (redir < 0 ? has_redirection(cmd, cp) : redir) ||
1334 is_internal_cmd(cmd, nt))) {
1335 size_t cmd_len = strlen(shell) + strlen(cmd) +
sizeof(
" /c ") + (nt ? 2 : 0);
1336 char *tmp =
ALLOCV(v, cmd_len);
1337 snprintf(tmp, cmd_len, nt ?
"%s /c \"%s\"" :
"%s /c %s", shell, cmd);
1341 int len = 0, quote = (*cmd ==
'"') ?
'"' : (*cmd ==
'\'') ?
'\'' : 0;
1343 for (prog = cmd + !!quote;; prog = CharNextExA(cp, prog, 0)) {
1344 if (*prog ==
'/') slash = 1;
1348 STRNDUPV(p, v2, cmd,
len);
1354 if ((
unsigned char)*prog == quote) {
1355 len = prog++ - cmd - 1;
1356 STRNDUPV(p, v2, cmd + 1,
len);
1360 if (quote)
continue;
1361 if (
ISSPACE(*prog) || strchr(
"<>|*?\"", *prog)) {
1363 STRNDUPV(p, v2, cmd,
len + (slash ? strlen(prog) : 0));
1366 sep = *(cmd_sep = &p[
len]);
1373 shell = dln_find_exe_r(shell, NULL, fbuf,
sizeof(fbuf));
1374 if (p && slash) translate_char(p,
'/',
'\\', cp);
1376 shell = p ? p : cmd;
1379 len = strlen(shell);
1380 if (strchr(shell,
' ')) quote = -1;
1381 if (shell == fbuf) {
1384 else if (shell != p && strchr(shell,
'/')) {
1385 STRNDUPV(p, v2, shell,
len);
1388 if (p) translate_char(p,
'/',
'\\', cp);
1389 if (is_batch(shell)) {
1390 int alen = strlen(prog);
1391 cmd = p =
ALLOCV(v,
len + alen + (quote ? 2 : 0) + 1);
1392 if (quote) *p++ =
'"';
1393 memcpy(p, shell,
len);
1395 if (quote) *p++ =
'"';
1396 memcpy(p, prog, alen + 1);
1403 if (!e && shell && !(wshell = mbstr_to_wstr(cp, shell, -1, NULL))) e = E2BIG;
1404 if (cmd_sep) *cmd_sep = sep;
1405 if (!e && cmd && !(wcmd = mbstr_to_wstr(cp, cmd, -1, NULL))) e = E2BIG;
1411 if (CreateChild(child, wcmd, wshell, NULL, NULL, NULL, 0)) {
1412 ret = child_result(child, mode);
1423rb_w32_spawn(
int mode,
const char *cmd,
const char *prog)
1426 return w32_spawn(mode, cmd, prog, filecp());
1431rb_w32_uspawn(
int mode,
const char *cmd,
const char *prog)
1433 return w32_spawn(mode, cmd, prog, CP_UTF8);
1438w32_spawn_process(
int mode,
const char *prog,
char *
const *argv,
1439 int in_fd,
int out_fd,
int err_fd, DWORD flags, UINT cp)
1443 BOOL ntcmd = FALSE, tmpnt;
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)) &&
1466 internal_cmd_match(prog, tmpnt = !is_command_com(shell))) {
1471 else if ((cmd = dln_find_exe_r(prog, NULL, fbuf,
sizeof(fbuf)))) {
1472 if (cmd == prog) strlcpy(cmd = fbuf, prog,
sizeof(fbuf));
1473 translate_char(cmd,
'/',
'\\', cp);
1476 else if (strchr(prog,
'/')) {
1478 if (
len <
sizeof(fbuf))
1479 strlcpy(cmd = fbuf, prog,
sizeof(fbuf));
1481 STRNDUPV(cmd, v, prog,
len);
1482 translate_char(cmd,
'/',
'\\', cp);
1485 if (c_switch || is_batch(prog)) {
1487 progs[0] = (
char *)prog;
1489 len = join_argv(NULL, progs, ntcmd, cp, 1);
1490 if (c_switch)
len += 3;
1492 if (argv[0])
len += join_argv(NULL, argv, ntcmd, cp, 0);
1494 join_argv(cmd, progs, ntcmd, cp, 1);
1495 if (c_switch) strlcat(cmd,
" /c",
len);
1496 if (argv[0]) join_argv(cmd + strlcat(cmd,
" ",
len), argv, ntcmd, cp, 0);
1497 prog = c_switch ? shell : 0;
1500 len = join_argv(NULL, argv, FALSE, cp, 1);
1502 join_argv(cmd, argv, FALSE, cp, 1);
1505 if (!e && cmd && !(wcmd = mbstr_to_wstr(cp, cmd, -1, NULL))) e = E2BIG;
1507 if (!e && prog && !(wprog = mbstr_to_wstr(cp, prog, -1, NULL))) e = E2BIG;
1511 if (CreateChild(child, wcmd, wprog, in_handle, out_handle, err_handle, flags)) {
1512 ret = child_result(child, mode);
1523rb_w32_aspawn_flags(
int mode,
const char *prog,
char *
const *argv, DWORD flags)
1526 return w32_spawn_process(mode, prog, argv, -1, -1, -1, flags, filecp());
1531rb_w32_uaspawn_flags(
int mode,
const char *prog,
char *
const *argv, DWORD flags)
1533 return w32_spawn_process(mode, prog, argv, -1, -1, -1, flags, CP_UTF8);
1538rb_w32_aspawn(
int mode,
const char *prog,
char *
const *argv)
1540 return w32_spawn_process(mode, prog, argv, -1, -1, -1, 0, filecp());
1545rb_w32_uaspawn(
int mode,
const char *prog,
char *
const *argv)
1547 return rb_w32_uaspawn_flags(mode, prog, argv, 0);
1552rb_w32_uspawn_process(
int mode,
const char *prog,
char *
const *argv,
1553 int in_fd,
int out_fd,
int err_fd, DWORD flags)
1555 return w32_spawn_process(mode, prog, argv, in_fd, out_fd, err_fd,
1577insert(
const char *path,
VALUE vinfo,
void *enc)
1579 NtCmdLineElement *tmpcurr;
1580 NtCmdLineElement ***tail = (NtCmdLineElement ***)vinfo;
1582 tmpcurr = (NtCmdLineElement *)malloc(
sizeof(NtCmdLineElement));
1583 if (!tmpcurr)
return -1;
1584 MEMZERO(tmpcurr, NtCmdLineElement, 1);
1585 tmpcurr->len = strlen(path);
1586 tmpcurr->str =
strdup(path);
1587 if (!tmpcurr->str)
return -1;
1588 tmpcurr->flags |= NTMALLOC;
1590 *tail = &tmpcurr->next;
1596static NtCmdLineElement **
1597cmdglob(NtCmdLineElement *patt, NtCmdLineElement **tail, UINT cp, rb_encoding *enc)
1599 char buffer[PATH_MAX], *buf = buffer;
1600 NtCmdLineElement **last = tail;
1603 if (patt->len >= PATH_MAX)
1604 if (!(buf = malloc(patt->len + 1)))
return 0;
1606 memcpy(buf, patt->str, patt->len);
1607 buf[patt->len] =
'\0';
1608 translate_char(buf,
'\\',
'/', cp);
1609 status = ruby_brace_glob_with_enc(buf, 0, insert, (
VALUE)&tail, enc);
1613 if (status || last == tail)
return 0;
1614 if (patt->flags & NTMALLOC)
1627has_redirection(
const char *cmd, UINT cp)
1643 else if (quote == *
ptr)
1661 if (*
ptr && *
ptr++ ==
'%')
return TRUE;
1667 ptr = CharNextExA(cp,
ptr, 0);
1675static inline WCHAR *
1676skipspace(WCHAR *
ptr)
1685w32_cmdvector(
const WCHAR *cmd,
char ***vec, UINT cp, rb_encoding *enc)
1688 int elements, strsz, done;
1689 int slashes, escape;
1690 WCHAR *
ptr, *base, *cmdline;
1691 char *cptr, *buffer;
1694 NtCmdLineElement *curr, **tail;
1695 NtCmdLineElement *cmdhead = NULL, **cmdtail = &cmdhead;
1707 ptr = cmdline = wcsdup(cmd);
1718 while (*(
ptr = skipspace(
ptr))) {
1720 quote = slashes = globbing = escape = 0;
1721 for (done = 0; !done && *
ptr; ) {
1730 if (quote != L
'\'') slashes++;
1770 if (!(slashes & 1)) {
1773 else if (quote == *
ptr) {
1774 if (quote == L
'"' && quote ==
ptr[1])
1807 slashes = quote = 0;
1808 while (p < base +
len) {
1812 if (quote != L
'\'') slashes++;
1817 if (!(slashes & 1) && quote && quote != c) {
1822 memcpy(p - ((slashes + 1) >> 1), p + (~slashes & 1),
1823 sizeof(WCHAR) * (base +
len - p));
1824 len -= ((slashes + 1) >> 1) + (~slashes & 1);
1825 p -= (slashes + 1) >> 1;
1826 if (!(slashes & 1)) {
1828 if (quote == L
'"' && quote == *p)
1848 curr = (NtCmdLineElement *)calloc(1,
sizeof(NtCmdLineElement));
1849 if (!curr)
goto do_nothing;
1850 curr->str = rb_w32_wstr_to_mbstr(cp, base,
len, &curr->len);
1851 curr->flags |= NTMALLOC;
1853 if (globbing && (tail = cmdglob(curr, cmdtail, cp, enc))) {
1858 cmdtail = &curr->next;
1868 for (elements = 0, strsz = 0, curr = cmdhead; curr; curr = curr->next) {
1870 strsz += (curr->len + 1);
1873 len = (elements+1)*
sizeof(
char *) + strsz;
1874 buffer = (
char *)malloc(
len);
1877 while ((curr = cmdhead) != 0) {
1878 cmdhead = curr->next;
1879 if (curr->flags & NTMALLOC) free(curr->str);
1883 for (vptr = *vec; *vptr; ++vptr);
1899 vptr = (
char **) buffer;
1901 cptr = buffer + (elements+1) *
sizeof(
char *);
1903 while ((curr = cmdhead) != 0) {
1904 memcpy(cptr, curr->str, curr->len);
1905 cptr[curr->len] =
'\0';
1907 cptr += curr->len + 1;
1908 cmdhead = curr->next;
1909 if (curr->flags & NTMALLOC) free(curr->str);
1914 *vec = (
char **) buffer;
1926open_special(
const WCHAR *path, DWORD access, DWORD flags)
1928 const DWORD share_mode =
1929 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
1930 return CreateFileW(path, access, share_mode, NULL, OPEN_EXISTING,
1931 FILE_FLAG_BACKUP_SEMANTICS|flags, NULL);
1941#define GetBit(bits, i) ((bits)[(i) / CHAR_BIT] & (1 << (i) % CHAR_BIT))
1942#define SetBit(bits, i) ((bits)[(i) / CHAR_BIT] |= (1 << (i) % CHAR_BIT))
1944#define BitOfIsDir(n) ((n) * 2)
1945#define BitOfIsRep(n) ((n) * 2 + 1)
1946#define DIRENT_PER_CHAR (CHAR_BIT / 2)
1948static const WCHAR namespace_prefix[] = {L
'\\', L
'\\', L
'?', L
'\\'};
1954get_handle_pathname(HANDLE fh, WCHAR **pathptr, DWORD add)
1956 DWORD
len = GetFinalPathNameByHandleW(fh, NULL, 0, 0);
1958 WCHAR *path = malloc((
len + add + 1) *
sizeof(WCHAR));
1959 if (!(*pathptr = path))
return 0;
1960 len = GetFinalPathNameByHandleW(fh, path,
len + 1, 0);
1970open_dir_handle(
const WCHAR *filename, WIN32_FIND_DATAW *fd)
1974 WCHAR *fullname = 0;
1982 fh = open_special(filename, 0, 0);
1983 if (fh != INVALID_HANDLE_VALUE) {
1984 len = get_handle_pathname(fh, &fullname, wildcard_len);
1988 len = lstrlenW(filename);
1989 fullname = malloc((
len + wildcard_len + 1) *
sizeof(WCHAR));
1990 if (!fullname)
return INVALID_HANDLE_VALUE;
1996 p = &fullname[
len-1];
1997 if (!(isdirsep(*p) || *p == L
':')) *++p = L
'\\';
2004 fh = FindFirstFileW(fullname, fd);
2005 if (fh == INVALID_HANDLE_VALUE) {
2006 errno = map_errno(GetLastError());
2014w32_wopendir(
const WCHAR *wpath)
2016 struct stati128 sbuf;
2017 WIN32_FIND_DATAW fd;
2030 if (wstati128(wpath, &sbuf, FALSE) < 0) {
2033 if (!(sbuf.st_mode & S_IFDIR) &&
2034 (!
ISALPHA(wpath[0]) || wpath[1] != L
':' || wpath[2] != L
'\0' ||
2035 ((1 << ((wpath[0] & 0x5f) -
'A')) & GetLogicalDrives()) == 0)) {
2039 fh = open_dir_handle(wpath, &fd);
2040 if (fh == INVALID_HANDLE_VALUE) {
2047 p = calloc(1,
sizeof(
DIR));
2051 pathlen = lstrlenW(wpath);
2061 len = lstrlenW(fd.cFileName) + 1;
2062 altlen = lstrlenW(fd.cAlternateFileName) + 1;
2068 tmpW = realloc(p->start, (idx +
len + altlen) *
sizeof(WCHAR));
2078 memcpy(&p->start[idx], fd.cFileName,
len *
sizeof(WCHAR));
2079 memcpy(&p->start[idx +
len], fd.cAlternateFileName, altlen *
sizeof(WCHAR));
2081 if (p->nfiles % DIRENT_PER_CHAR == 0) {
2082 tmp = realloc(p->bits, p->nfiles / DIRENT_PER_CHAR + 1);
2086 p->bits[p->nfiles / DIRENT_PER_CHAR] = 0;
2088 if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
2089 SetBit(p->bits, BitOfIsDir(p->nfiles));
2090 if (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
2091 WCHAR *tmppath = malloc((pathlen +
len + 1) *
sizeof(WCHAR));
2092 memcpy(tmppath, wpath, pathlen *
sizeof(WCHAR));
2093 tmppath[pathlen] = L
'\\';
2094 memcpy(tmppath + pathlen + 1, fd.cFileName,
len *
sizeof(WCHAR));
2095 if (rb_w32_reparse_symlink_p(tmppath))
2096 SetBit(p->bits, BitOfIsRep(p->nfiles));
2101 idx +=
len + altlen;
2102 }
while (FindNextFileW(fh, &fd));
2113 UINT cp = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
2119rb_w32_wstr_to_mbstr(UINT cp,
const WCHAR *wstr,
int clen,
long *plen)
2122 int len = WideCharToMultiByte(cp, 0, wstr, clen, NULL, 0, NULL, NULL);
2123 if (!(
ptr = malloc(
len)))
return 0;
2124 WideCharToMultiByte(cp, 0, wstr, clen,
ptr,
len, NULL, NULL);
2127 if (clen == -1) --
len;
2135rb_w32_mbstr_to_wstr(UINT cp,
const char *str,
int clen,
long *plen)
2138 int len = MultiByteToWideChar(cp, 0, str, clen, NULL, 0);
2139 if (!(
ptr = malloc(
sizeof(WCHAR) *
len)))
return 0;
2140 MultiByteToWideChar(cp, 0, str, clen,
ptr,
len);
2143 if (clen == -1) --
len;
2151rb_w32_opendir(
const char *filename)
2154 WCHAR *wpath = filecp_to_wstr(filename, NULL);
2157 ret = w32_wopendir(wpath);
2164rb_w32_uopendir(
const char *filename)
2167 WCHAR *wpath = utf8_to_wstr(filename, NULL);
2170 ret = w32_wopendir(wpath);
2181move_to_next_entry(
DIR *dirp)
2185 dirp->curr += lstrlenW(dirp->curr) + 1;
2186 dirp->curr += lstrlenW(dirp->curr) + 1;
2187 if (dirp->curr >= (dirp->start + dirp->size)) {
2199win32_direct_conv(
const WCHAR *file,
const WCHAR *alt,
struct direct *entry,
const void *enc)
2201 UINT cp = *((UINT *)enc);
2202 if (!(entry->d_name = wstr_to_mbstr(cp, file, -1, &entry->d_namlen)))
2206 entry->d_altname = wstr_to_mbstr(cp, alt, -1, &altlen);
2207 entry->d_altlen = altlen;
2214rb_w32_conv_from_wchar(
const WCHAR *wstr, rb_encoding *enc)
2217 long len = lstrlenW(wstr);
2218 int encindex = rb_enc_to_index(enc);
2220 if (encindex == ENCINDEX_UTF_16LE) {
2221 return rb_enc_str_new((
char *)wstr,
len *
sizeof(WCHAR), enc);
2224#if SIZEOF_INT < SIZEOF_LONG
2225# error long should equal to int on Windows
2228 len = WideCharToMultiByte(CP_UTF8, 0, wstr, clen, NULL, 0, NULL, NULL);
2229 src = rb_enc_str_new(0,
len, rb_enc_from_index(ENCINDEX_UTF_8));
2230 WideCharToMultiByte(CP_UTF8, 0, wstr, clen, RSTRING_PTR(src),
len, NULL, NULL);
2233 case ENCINDEX_ASCII_8BIT:
2234 case ENCINDEX_US_ASCII:
2236 case ENCINDEX_UTF_8:
2245rb_w32_conv_from_wstr(
const WCHAR *wstr,
long *lenp, rb_encoding *enc)
2247 VALUE str = rb_w32_conv_from_wchar(wstr, enc);
2251 if (
NIL_P(str))
return wstr_to_utf8(wstr, lenp);
2252 *lenp =
len = RSTRING_LEN(str);
2253 memcpy(
ptr = malloc(
len + 1), RSTRING_PTR(str),
len);
2260ruby_direct_conv(
const WCHAR *file,
const WCHAR *alt,
struct direct *entry,
const void *enc)
2262 if (!(entry->d_name = rb_w32_conv_from_wstr(file, &entry->d_namlen, enc)))
2266 entry->d_altname = rb_w32_conv_from_wstr(alt, &altlen, enc);
2267 entry->d_altlen = altlen;
2274readdir_internal(
DIR *dirp, BOOL (*conv)(
const WCHAR *,
const WCHAR *,
struct direct *,
const void *),
const void *enc)
2276 static long dummy_ino = 0;
2283 free(dirp->dirstr.d_name);
2284 free(dirp->dirstr.d_altname);
2285 dirp->dirstr.d_altname = 0;
2286 dirp->dirstr.d_altlen = 0;
2287 conv(dirp->curr, dirp->curr + lstrlenW(dirp->curr) + 1, &dirp->dirstr, enc);
2292 dirp->dirstr.d_ino = (ino_t)(InterlockedIncrement(&dummy_ino) - 1);
2298 if (GetBit(dirp->bits, BitOfIsRep(dirp->loc)))
2299 dirp->dirstr.d_type = DT_LNK;
2300 else if (GetBit(dirp->bits, BitOfIsDir(dirp->loc)))
2301 dirp->dirstr.d_type = DT_DIR;
2303 dirp->dirstr.d_type = DT_REG;
2309 move_to_next_entry(dirp);
2311 return &(dirp->dirstr);
2320rb_w32_readdir(
DIR *dirp, rb_encoding *enc)
2322 int idx = rb_enc_to_index(enc);
2323 if (idx == ENCINDEX_ASCII_8BIT) {
2324 const UINT cp = filecp();
2325 return readdir_internal(dirp, win32_direct_conv, &cp);
2327 else if (idx == ENCINDEX_UTF_8) {
2328 const UINT cp = CP_UTF8;
2329 return readdir_internal(dirp, win32_direct_conv, &cp);
2332 return readdir_internal(dirp, ruby_direct_conv, enc);
2337rb_w32_ureaddir(
DIR *dirp)
2339 const UINT cp = CP_UTF8;
2340 return readdir_internal(dirp, win32_direct_conv, &cp);
2349rb_w32_telldir(
DIR *dirp)
2360rb_w32_seekdir(
DIR *dirp,
long loc)
2362 if (dirp->loc > loc) rb_w32_rewinddir(dirp);
2364 while (dirp->curr && dirp->loc < loc) {
2365 move_to_next_entry(dirp);
2375rb_w32_rewinddir(
DIR *dirp)
2377 dirp->curr = dirp->start;
2387rb_w32_closedir(
DIR *dirp)
2390 free(dirp->dirstr.d_name);
2391 free(dirp->dirstr.d_altname);
2413 CRITICAL_SECTION _lock;
2415#define FILE_COUNT(stream) ((vcruntime_file*)stream)->_cnt
2416#define FILE_READPTR(stream) ((vcruntime_file*)stream)->_ptr
2417#define FILE_FILENO(stream) ((vcruntime_file*)stream)->_file
2420typedef char lowio_text_mode;
2421typedef char lowio_pipe_lookahead[3];
2424 CRITICAL_SECTION lock;
2427 unsigned char osfile;
2428 lowio_text_mode textmode;
2429 lowio_pipe_lookahead _pipe_lookahead;
2431 uint8_t unicode : 1;
2432 uint8_t utf8translations : 1;
2433 uint8_t dbcsBufferUsed : 1;
2437#if !defined _CRTIMP || defined __MINGW32__
2439#define _CRTIMP __declspec(dllimport)
2442static ioinfo ** __pioinfo = NULL;
2444static inline ioinfo* _pioinfo(
int);
2447#define IOINFO_ARRAY_ELTS (1 << IOINFO_L2E)
2448#define _osfhnd(i) (_pioinfo(i)->osfhnd)
2449#define _osfile(i) (_pioinfo(i)->osfile)
2450#define rb_acrt_lowio_lock_fh(i) EnterCriticalSection(&_pioinfo(i)->lock)
2451#define rb_acrt_lowio_unlock_fh(i) LeaveCriticalSection(&_pioinfo(i)->lock)
2453static size_t pioinfo_extra = 0;
2457set_pioinfo_extra(
void)
2459#define FUNCTION_RET 0xc3
2461# define UCRTBASE "ucrtbased.dll"
2463# define UCRTBASE "ucrtbase.dll"
2478 char *p = (
char*)get_proc_address(UCRTBASE,
"_isatty", NULL);
2481#if defined(_M_ARM64) || defined(__aarch64__)
2482#define IS_INSN(pc, name) ((*(pc) & name##_mask) == name##_id)
2483 const int max_num_inst = 500;
2484 uint32_t *start = (uint32_t*)p;
2485 uint32_t *end_limit = (start + max_num_inst);
2486 uint32_t *pc = start;
2489 fprintf(stderr,
"_isatty proc not found in " UCRTBASE
"\n");
2494 const uint32_t ret_id = 0xd65f0000;
2495 const uint32_t ret_mask = 0xfffffc1f;
2496 for(; pc < end_limit; pc++) {
2497 if (IS_INSN(pc, ret)) {
2501 if (pc == end_limit) {
2502 fprintf(stderr,
"end of _isatty not found in " UCRTBASE
"\n");
2507 const uint32_t adrp_id = 0x90000000;
2508 const uint32_t adrp_mask = 0x9f000000;
2509 const uint32_t add_id = 0x11000000;
2510 const uint32_t add_mask = 0x7fc00000;
2511 for(; pc > start; pc--) {
2512 if (IS_INSN(pc, adrp) && IS_INSN(pc + 1, add)) {
2517 fprintf(stderr,
"pioinfo mark not found in " UCRTBASE
"\n");
2527 const uint32_t adrp_insn = *pc;
2528 const uint32_t adrp_immhi = (adrp_insn & 0x00ffffe0) >> 5;
2529 const uint32_t adrp_immlo = (adrp_insn & 0x60000000) >> (5 + 19 + 5);
2530 const int64_t adrp_sign = (adrp_insn & 0x00800000) ? ~0x001fffff : 0;
2532 const int64_t adrp_imm = (adrp_sign | (adrp_immhi << 2) | adrp_immlo) << 12;
2534 const uint64_t adrp_base = (uint64_t)pc & 0xfffffffffffff000;
2536 const uint32_t add_insn = *(pc + 1);
2537 const uint64_t add_imm = (add_insn & 0x3ffc00) >> (5 + 5);
2539 __pioinfo = (
ioinfo**)(adrp_base + adrp_imm + add_imm);
2547# define FUNCTION_BEFORE_RET_MARK "\x48\x83\xc4"
2548# define FUNCTION_SKIP_BYTES 1
2551# define PIOINFO_MARK "\x48\x8d\x0d"
2554# define PIOINFO_MARK "\x48\x8d\x15"
2559# define FUNCTION_BEFORE_RET_MARK "\x5d"
2561# define FUNCTION_BEFORE_RET_MARK_2 "\xc9"
2562# define FUNCTION_SKIP_BYTES 0
2564# define PIOINFO_MARK "\x8B\x04\x85"
2567 for (pend += 10; pend < p + 500; pend++) {
2569 if ((memcmp(pend, FUNCTION_BEFORE_RET_MARK,
sizeof(FUNCTION_BEFORE_RET_MARK) - 1) == 0
2570# ifdef FUNCTION_BEFORE_RET_MARK_2
2571 || memcmp(pend, FUNCTION_BEFORE_RET_MARK_2,
sizeof(FUNCTION_BEFORE_RET_MARK_2) - 1) == 0
2574 *(pend + (
sizeof(FUNCTION_BEFORE_RET_MARK) - 1) + FUNCTION_SKIP_BYTES) == (
char)FUNCTION_RET) {
2576 for (pend -= (
sizeof(PIOINFO_MARK) - 1); pend > p; pend--) {
2577 if (memcmp(pend, PIOINFO_MARK,
sizeof(PIOINFO_MARK) - 1) == 0) {
2586 fprintf(stderr,
"unexpected " UCRTBASE
"\n");
2590 p +=
sizeof(PIOINFO_MARK) - 1;
2592 rel = *(int32_t*)(p);
2593 rip = p +
sizeof(int32_t);
2594 __pioinfo = (
ioinfo**)(rip + rel);
2596 __pioinfo = *(
ioinfo***)(p);
2601 fd = _open(
"NUL", O_RDONLY);
2602 for (pioinfo_extra = 0; pioinfo_extra <= 64; pioinfo_extra +=
sizeof(
void *)) {
2603 if (_osfhnd(fd) == _get_osfhandle(fd)) {
2609 if (pioinfo_extra > 64) {
2618 const size_t sizeof_ioinfo =
sizeof(
ioinfo) + pioinfo_extra;
2619 return (
ioinfo*)((
char*)__pioinfo[fd >> IOINFO_L2E] +
2620 (fd & (IOINFO_ARRAY_ELTS - 1)) * sizeof_ioinfo);
2623#define _set_osfhnd(fh, osfh) (void)(_osfhnd(fh) = osfh)
2624#define _set_osflags(fh, flags) (_osfile(fh) = (flags))
2629#define FNOINHERIT 0x10
2634static int is_socket(SOCKET);
2635static int is_console(SOCKET);
2639rb_w32_io_cancelable_p(
int fd)
2641 return is_socket(TO_SOCKET(fd)) || !is_console(TO_SOCKET(fd));
2646rb_w32_open_osfhandle(intptr_t osfhandle,
int flags)
2655 if (flags & O_APPEND)
2656 fileflags |= FAPPEND;
2661 if (flags & O_NOINHERIT)
2662 fileflags |= FNOINHERIT;
2665 hF = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
2666 fh = _open_osfhandle((intptr_t)hF, 0);
2674 rb_acrt_lowio_lock_fh(fh);
2676 _set_osfhnd(fh, osfhandle);
2680 _set_osflags(fh, fileflags);
2681 rb_acrt_lowio_unlock_fh(fh);
2692#define open_null(fd) \
2694 (nullfd = open("NUL", O_RDWR)) : 0), \
2695 ((nullfd == (fd)) ? (keep = 1) : dup2(nullfd, fd)), \
2698 if (fileno(stdin) < 0) {
2699 FILE_FILENO(stdin) = open_null(0);
2702 setmode(fileno(stdin), O_BINARY);
2704 if (fileno(stdout) < 0) {
2705 FILE_FILENO(stdout) = open_null(1);
2707 if (fileno(stderr) < 0) {
2708 FILE_FILENO(stderr) = open_null(2);
2710 if (nullfd >= 0 && !keep) close(nullfd);
2711 setvbuf(stderr, NULL, _IONBF, 0);
2714 HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
2716 if (GetConsoleMode(h, &m)) {
2717#ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
2718#define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x4
2720 SetConsoleMode(h, m | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
2729is_socket(SOCKET sock)
2731 if (socklist_lookup(sock, NULL))
2739rb_w32_is_socket(
int fd)
2741 return is_socket(TO_SOCKET(fd));
2754rb_w32_strerror(
int e)
2756 static char buffer[512];
2761 strlcpy(buffer,
"Unknown Error",
sizeof(buffer));
2762 else if (e > sys_nerr) {
2763#if WSAEWOULDBLOCK != EWOULDBLOCK
2764 if (e >= EADDRINUSE && e <= EWOULDBLOCK) {
2768 for (s = 0; s < (int)(
sizeof(errmap)/
sizeof(*errmap)); s++)
2769 if (errmap[s].winerr == WSAEWOULDBLOCK)
2771 for (i = s; i < (int)(
sizeof(errmap)/
sizeof(*errmap)); i++)
2772 if (errmap[i].err == e) {
2773 e = errmap[i].winerr;
2778 if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2779 FORMAT_MESSAGE_IGNORE_INSERTS, &source, e,
2780 MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
2781 buffer,
sizeof(buffer), NULL) == 0 &&
2782 FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
2783 FORMAT_MESSAGE_IGNORE_INSERTS, &source, e, 0,
2784 buffer,
sizeof(buffer), NULL) == 0)
2785 strlcpy(buffer,
"Unknown Error",
sizeof(buffer));
2788 strlcpy(buffer, strerror(e),
sizeof(buffer));
2791 while ((p = strpbrk(p,
"\r\n")) != NULL) {
2792 memmove(p, p + 1, strlen(p));
2843 return (uid == ROOT_UID ? 0 : -1);
2850 return (gid == ROOT_GID ? 0 : -1);
2859ioctl(
int i,
int u, ...)
2866rb_w32_fdset(
int fd, fd_set *set)
2875rb_w32_fdclr(
int fd, fd_set *set)
2878 SOCKET s = TO_SOCKET(fd);
2880 for (i = 0; i < set->fd_count; i++) {
2881 if (set->fd_array[i] == s) {
2882 memmove(&set->fd_array[i], &set->fd_array[i+1],
2883 sizeof(set->fd_array[0]) * (--set->fd_count - i));
2893rb_w32_fdisset(
int fd, fd_set *set)
2896 SOCKET s = TO_SOCKET(fd);
2897 if (s == (SOCKET)INVALID_HANDLE_VALUE)
2899 RUBY_CRITICAL {ret = __WSAFDIsSet(s, set);}
2907 max = min(src->fd_count, (UINT)max);
2908 if ((UINT)dst->
capa < (UINT)max) {
2909 dst->
capa = (src->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2913 memcpy(dst->
fdset->fd_array, src->fd_array,
2914 max *
sizeof(src->fd_array[0]));
2915 dst->
fdset->fd_count = src->fd_count;
2922 if ((UINT)dst->
capa < src->
fdset->fd_count) {
2923 dst->
capa = (src->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2927 memcpy(dst->
fdset->fd_array, src->
fdset->fd_array,
2928 src->
fdset->fd_count *
sizeof(src->
fdset->fd_array[0]));
2942extract_fd(
rb_fdset_t *dst, fd_set *src,
int (*func)(SOCKET))
2948 while (s < src->fd_count) {
2949 SOCKET fd = src->fd_array[s];
2951 if (!func || (*func)(fd)) {
2955 for (d = 0; d < dst->
fdset->fd_count; d++) {
2956 if (dst->
fdset->fd_array[d] == fd)
2959 if (d == dst->
fdset->fd_count) {
2960 if ((
int)dst->
fdset->fd_count >= dst->
capa) {
2961 dst->
capa = (dst->
fdset->fd_count / FD_SETSIZE + 1) * FD_SETSIZE;
2964 dst->
fdset->fd_array[dst->
fdset->fd_count++] = fd;
2968 &src->fd_array[s+1],
2969 sizeof(src->fd_array[0]) * (--src->fd_count - s));
2979 return dst ? dst->
fdset->fd_count : m;
2984copy_fd(fd_set *dst, fd_set *src)
2987 if (!src || !dst)
return 0;
2989 for (s = 0; s < src->fd_count; ++s) {
2990 SOCKET fd = src->fd_array[s];
2992 for (d = 0; d < dst->fd_count; ++d) {
2993 if (dst->fd_array[d] == fd)
2996 if (d == dst->fd_count && d < FD_SETSIZE) {
2997 dst->fd_array[dst->fd_count++] = fd;
3001 return dst->fd_count;
3006is_not_socket(SOCKET sock)
3008 return !is_socket(sock);
3018 ret = (GetFileType((HANDLE)sock) == FILE_TYPE_PIPE);
3026is_readable_pipe(SOCKET sock)
3032 if (PeekNamedPipe((HANDLE)sock, NULL, 0, NULL, &n, NULL)) {
3036 ret = (GetLastError() == ERROR_BROKEN_PIPE);
3045is_console(SOCKET sock)
3052 ret = (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n));
3060is_readable_console(SOCKET sock)
3067 if (PeekConsoleInputW((HANDLE)sock, &ir, 1, &n) && n > 0) {
3068 if (ir.EventType == KEY_EVENT && ir.Event.KeyEvent.bKeyDown &&
3069 ir.Event.KeyEvent.uChar.UnicodeChar) {
3072 else if (ir.EventType == KEY_EVENT && !ir.Event.KeyEvent.bKeyDown &&
3073 ir.Event.KeyEvent.wVirtualKeyCode == VK_MENU &&
3074 ir.Event.KeyEvent.uChar.UnicodeChar) {
3078 ReadConsoleInputW((HANDLE)sock, &ir, 1, &n);
3088is_invalid_handle(SOCKET sock)
3090 return (HANDLE)sock == INVALID_HANDLE_VALUE;
3095do_select(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3102 rb_w32_sleep(timeout->tv_sec * 1000 + timeout->tv_usec / 1000);
3104 rb_w32_sleep(INFINITE);
3108 thread_exclusive(select) {
3109 r = select(nfds, rd, wr, ex, timeout);
3111 if (r == SOCKET_ERROR) {
3112 errno = map_errno(WSAGetLastError());
3127rb_w32_time_subtract(
struct timeval *rest,
const struct timeval *wait)
3129 if (rest->tv_sec < wait->tv_sec) {
3132 while (rest->tv_usec < wait->tv_usec) {
3133 if (rest->tv_sec <= wait->tv_sec) {
3137 rest->tv_usec += 1000 * 1000;
3139 rest->tv_sec -= wait->tv_sec;
3140 rest->tv_usec -= wait->tv_usec;
3141 return rest->tv_sec != 0 || rest->tv_usec != 0;
3148 if (t1->tv_sec < t2->tv_sec)
3150 if (t1->tv_sec > t2->tv_sec)
3152 if (t1->tv_usec < t2->tv_usec)
3154 if (t1->tv_usec > t2->tv_usec)
3161int rb_w32_check_interrupt(
void *);
3166rb_w32_select_with_thread(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3167 struct timeval *timeout,
void *th)
3176 struct timeval limit = {0, 0};
3178 if (nfds < 0 || (timeout && (timeout->tv_sec < 0 || timeout->tv_usec < 0))) {
3184 if (timeout->tv_sec < 0 ||
3185 timeout->tv_usec < 0 ||
3186 timeout->tv_usec >= 1000000) {
3190 gettimeofday(&limit, NULL);
3191 limit.tv_sec += timeout->tv_sec;
3192 limit.tv_usec += timeout->tv_usec;
3193 if (limit.tv_usec >= 1000000) {
3194 limit.tv_usec -= 1000000;
3206 nonsock += extract_fd(&else_rd, rd, is_not_socket);
3209 nonsock += extract_fd(&else_wr, wr, is_not_socket);
3212 if (extract_fd(NULL, else_rd.
fdset, is_invalid_handle) > 0 ||
3213 extract_fd(NULL, else_wr.
fdset, is_invalid_handle) > 0) {
3221 extract_fd(&pipe_rd, else_rd.
fdset, is_pipe);
3224 extract_fd(&cons_rd, else_rd.
fdset, is_console);
3227 extract_fd(&except, ex, is_not_socket);
3230 if (rd && (
int)rd->fd_count > r) r = (int)rd->fd_count;
3231 if (wr && (
int)wr->fd_count > r) r = (int)wr->fd_count;
3232 if (ex && (
int)ex->fd_count > r) r = (int)ex->fd_count;
3233 if (nfds > r) nfds = r;
3237 const struct timeval wait = {0, 10 * 1000};
3240 if (th && rb_w32_check_interrupt(th) != WAIT_TIMEOUT) {
3247 extract_fd(&else_rd, pipe_rd.
fdset, is_readable_pipe);
3248 extract_fd(&else_rd, cons_rd.
fdset, is_readable_console);
3251 if (else_rd.
fdset->fd_count || else_wr.
fdset->fd_count) {
3252 r = do_select(nfds, rd, wr, ex, &zero);
3254 r += copy_fd(rd, else_rd.
fdset);
3255 r += copy_fd(wr, else_wr.
fdset);
3261 const struct timeval *dowait = &wait;
3271 if (rd) copy_fd(&orig_rd, rd);
3272 if (wr) copy_fd(&orig_wr, wr);
3273 if (ex) copy_fd(&orig_ex, ex);
3274 r = do_select(nfds, rd, wr, ex, &zero);
3276 if (rd) copy_fd(rd, &orig_rd);
3277 if (wr) copy_fd(wr, &orig_wr);
3278 if (ex) copy_fd(ex, &orig_ex);
3282 gettimeofday(&now, NULL);
3284 if (!rb_w32_time_subtract(&rest, &now))
break;
3285 if (compare(&rest, &wait) < 0) dowait = &rest;
3287 Sleep(dowait->tv_sec * 1000 + (dowait->tv_usec + 999) / 1000);
3303rb_w32_select(
int nfds, fd_set *rd, fd_set *wr, fd_set *ex,
3306 return rb_w32_select_with_thread(nfds, rd, wr, ex, timeout, 0);
3311get_wsa_extension_function(SOCKET s, GUID guid)
3316 WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid,
sizeof(guid),
3317 &
ptr,
sizeof(
ptr), &dmy, NULL, NULL);
3327rb_w32_accept(
int s,
struct sockaddr *addr,
int *addrlen)
3333 r = accept(TO_SOCKET(s), addr, addrlen);
3334 if (r != INVALID_SOCKET) {
3335 SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0);
3336 fd = rb_w32_open_osfhandle((intptr_t)r, O_RDWR|O_BINARY|O_NOINHERIT);
3338 socklist_insert(r, 0);
3343 errno = map_errno(WSAGetLastError());
3354rb_w32_bind(
int s,
const struct sockaddr *addr,
int addrlen)
3359 r = bind(TO_SOCKET(s), addr, addrlen);
3360 if (r == SOCKET_ERROR)
3361 errno = map_errno(WSAGetLastError());
3370rb_w32_connect(
int s,
const struct sockaddr *addr,
int addrlen)
3374 r = connect(TO_SOCKET(s), addr, addrlen);
3375 if (r == SOCKET_ERROR) {
3376 int err = WSAGetLastError();
3377 if (err != WSAEWOULDBLOCK)
3378 errno = map_errno(err);
3380 errno = EINPROGRESS;
3391rb_w32_getpeername(
int s,
struct sockaddr *addr,
int *addrlen)
3395 r = getpeername(TO_SOCKET(s), addr, addrlen);
3396 if (r == SOCKET_ERROR)
3397 errno = map_errno(WSAGetLastError());
3406rb_w32_getsockname(
int fd,
struct sockaddr *addr,
int *addrlen)
3411 sock = TO_SOCKET(fd);
3412 r = getsockname(sock, addr, addrlen);
3413 if (r == SOCKET_ERROR) {
3414 DWORD wsaerror = WSAGetLastError();
3415 if (wsaerror == WSAEINVAL) {
3417 if (socklist_lookup(sock, &flags)) {
3418 int af = GET_FAMILY(flags);
3420 memset(addr, 0, *addrlen);
3421 addr->sa_family = af;
3426 errno = map_errno(wsaerror);
3436rb_w32_getsockopt(
int s,
int level,
int optname,
char *optval,
int *optlen)
3440 r = getsockopt(TO_SOCKET(s), level, optname, optval, optlen);
3441 if (r == SOCKET_ERROR)
3442 errno = map_errno(WSAGetLastError());
3451rb_w32_ioctlsocket(
int s,
long cmd, u_long *argp)
3455 r = ioctlsocket(TO_SOCKET(s), cmd, argp);
3456 if (r == SOCKET_ERROR)
3457 errno = map_errno(WSAGetLastError());
3466rb_w32_listen(
int s,
int backlog)
3470 r = listen(TO_SOCKET(s), backlog);
3471 if (r == SOCKET_ERROR)
3472 errno = map_errno(WSAGetLastError());
3484finish_overlapped_socket(BOOL input, SOCKET s, WSAOVERLAPPED *wol,
int result, DWORD *
len, DWORD size)
3489 if (result != SOCKET_ERROR)
3491 else if ((err = WSAGetLastError()) == WSA_IO_PENDING) {
3492 switch (rb_w32_wait_events_blocking(&wol->hEvent, 1, INFINITE)) {
3495 result = WSAGetOverlappedResult(s, wol, &size, TRUE, &flg);
3502 result = SOCKET_ERROR;
3505 if ((err = WSAGetLastError()) == WSAECONNABORTED && !input)
3507 else if (err == WSAEMSGSIZE && input) {
3513 errno = map_errno(err);
3515 case WAIT_OBJECT_0 + 1:
3518 CancelIo((HANDLE)s);
3523 if (err == WSAECONNABORTED && !input)
3526 errno = map_errno(err);
3529 CloseHandle(wol->hEvent);
3536overlapped_socket_io(BOOL input,
int fd,
char *buf,
int len,
int flags,
3537 struct sockaddr *addr,
int *addrlen)
3548 socklist_lookup(s, &mode);
3549 if (GET_FLAGS(mode) & O_NONBLOCK) {
3552 if (addr && addrlen)
3553 r = recvfrom(s, buf,
len, flags, addr, addrlen);
3555 r = recv(s, buf,
len, flags);
3556 if (r == SOCKET_ERROR)
3557 errno = map_errno(WSAGetLastError());
3560 if (addr && addrlen)
3561 r = sendto(s, buf,
len, flags, addr, *addrlen);
3563 r = send(s, buf,
len, flags);
3564 if (r == SOCKET_ERROR) {
3565 DWORD err = WSAGetLastError();
3566 if (err == WSAECONNABORTED)
3569 errno = map_errno(err);
3579 memset(&wol, 0,
sizeof(wol));
3581 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3584 if (addr && addrlen)
3585 ret = WSARecvFrom(s, &wbuf, 1, &size, &flg, addr, addrlen,
3588 ret = WSARecv(s, &wbuf, 1, &size, &flg, &wol, NULL);
3591 if (addr && addrlen)
3592 ret = WSASendTo(s, &wbuf, 1, &size, flags, addr, *addrlen,
3595 ret = WSASend(s, &wbuf, 1, &size, flags, &wol, NULL);
3599 finish_overlapped_socket(input, s, &wol, ret, &rlen, size);
3608rb_w32_recv(
int fd,
char *buf,
int len,
int flags)
3610 return overlapped_socket_io(TRUE, fd, buf,
len, flags, NULL, NULL);
3615rb_w32_recvfrom(
int fd,
char *buf,
int len,
int flags,
3616 struct sockaddr *from,
int *fromlen)
3618 return overlapped_socket_io(TRUE, fd, buf,
len, flags, from, fromlen);
3623rb_w32_send(
int fd,
const char *buf,
int len,
int flags)
3625 return overlapped_socket_io(FALSE, fd, (
char *)buf,
len, flags, NULL, NULL);
3630rb_w32_sendto(
int fd,
const char *buf,
int len,
int flags,
3631 const struct sockaddr *to,
int tolen)
3633 return overlapped_socket_io(FALSE, fd, (
char *)buf,
len, flags,
3634 (
struct sockaddr *)to, &tolen);
3637#if !defined(MSG_TRUNC) && !defined(__MINGW32__)
3643 DWORD dwBufferCount;
3648#ifndef WSAID_WSARECVMSG
3649#define WSAID_WSARECVMSG {0xf689d7c8,0x6f1f,0x436b,{0x8a,0x53,0xe5,0x4f,0xe3,0x51,0xc3,0x22}}
3651#ifndef WSAID_WSASENDMSG
3652#define WSAID_WSASENDMSG {0xa441e712,0x754f,0x43ca,{0x84,0xa7,0x0d,0xee,0x44,0xcf,0x60,0x6d}}
3656#define msghdr_to_wsamsg(msg, wsamsg) \
3659 (wsamsg)->name = (msg)->msg_name; \
3660 (wsamsg)->namelen = (msg)->msg_namelen; \
3661 (wsamsg)->lpBuffers = ALLOCA_N(WSABUF, (msg)->msg_iovlen); \
3662 (wsamsg)->dwBufferCount = (msg)->msg_iovlen; \
3663 for (i = 0; i < (msg)->msg_iovlen; ++i) { \
3664 (wsamsg)->lpBuffers[i].buf = (msg)->msg_iov[i].iov_base; \
3665 (wsamsg)->lpBuffers[i].len = (msg)->msg_iov[i].iov_len; \
3667 (wsamsg)->Control.buf = (msg)->msg_control; \
3668 (wsamsg)->Control.len = (msg)->msg_controllen; \
3669 (wsamsg)->dwFlags = (msg)->msg_flags; \
3674recvmsg(
int fd,
struct msghdr *msg,
int flags)
3676 typedef int (WSAAPI *WSARecvMsg_t)(SOCKET,
WSAMSG *, DWORD *, WSAOVERLAPPED *, LPWSAOVERLAPPED_COMPLETION_ROUTINE);
3677 static WSARecvMsg_t pWSARecvMsg = NULL;
3687 static const GUID guid = WSAID_WSARECVMSG;
3688 pWSARecvMsg = (WSARecvMsg_t)get_wsa_extension_function(s, guid);
3693 msghdr_to_wsamsg(msg, &wsamsg);
3694 wsamsg.dwFlags |= flags;
3696 socklist_lookup(s, &mode);
3697 if (GET_FLAGS(mode) & O_NONBLOCK) {
3699 if ((ret = pWSARecvMsg(s, &wsamsg, &
len, NULL, NULL)) == SOCKET_ERROR) {
3700 errno = map_errno(WSAGetLastError());
3708 memset(&wol, 0,
sizeof(wol));
3710 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3711 ret = pWSARecvMsg(s, &wsamsg, &size, &wol, NULL);
3714 ret = finish_overlapped_socket(TRUE, s, &wol, ret, &
len, size);
3716 if (ret == SOCKET_ERROR)
3720 msg->msg_name = wsamsg.name;
3721 msg->msg_namelen = wsamsg.namelen;
3722 msg->msg_flags = wsamsg.dwFlags;
3729sendmsg(
int fd,
const struct msghdr *msg,
int flags)
3731 typedef int (WSAAPI *WSASendMsg_t)(SOCKET,
const WSAMSG *, DWORD, DWORD *, WSAOVERLAPPED *, LPWSAOVERLAPPED_COMPLETION_ROUTINE);
3732 static WSASendMsg_t pWSASendMsg = NULL;
3742 static const GUID guid = WSAID_WSASENDMSG;
3743 pWSASendMsg = (WSASendMsg_t)get_wsa_extension_function(s, guid);
3748 msghdr_to_wsamsg(msg, &wsamsg);
3750 socklist_lookup(s, &mode);
3751 if (GET_FLAGS(mode) & O_NONBLOCK) {
3753 if ((ret = pWSASendMsg(s, &wsamsg, flags, &
len, NULL, NULL)) == SOCKET_ERROR) {
3754 errno = map_errno(WSAGetLastError());
3762 memset(&wol, 0,
sizeof(wol));
3764 wol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3765 ret = pWSASendMsg(s, &wsamsg, flags, &size, &wol, NULL);
3768 finish_overlapped_socket(FALSE, s, &wol, ret, &
len, size);
3778rb_w32_setsockopt(
int s,
int level,
int optname,
const char *optval,
int optlen)
3782 r = setsockopt(TO_SOCKET(s), level, optname, optval, optlen);
3783 if (r == SOCKET_ERROR)
3784 errno = map_errno(WSAGetLastError());
3793rb_w32_shutdown(
int s,
int how)
3797 r = shutdown(TO_SOCKET(s), how);
3798 if (r == SOCKET_ERROR)
3799 errno = map_errno(WSAGetLastError());
3806open_ifs_socket(
int af,
int type,
int protocol)
3808 unsigned long proto_buffers_len = 0;
3810 SOCKET out = INVALID_SOCKET;
3812 if (WSAEnumProtocols(NULL, NULL, &proto_buffers_len) == SOCKET_ERROR) {
3813 error_code = WSAGetLastError();
3814 if (error_code == WSAENOBUFS) {
3815 WSAPROTOCOL_INFO *proto_buffers;
3816 int protocols_available = 0;
3818 proto_buffers = (WSAPROTOCOL_INFO *)malloc(proto_buffers_len);
3819 if (!proto_buffers) {
3820 WSASetLastError(WSA_NOT_ENOUGH_MEMORY);
3821 return INVALID_SOCKET;
3824 protocols_available =
3825 WSAEnumProtocols(NULL, proto_buffers, &proto_buffers_len);
3826 if (protocols_available != SOCKET_ERROR) {
3828 for (i = 0; i < protocols_available; i++) {
3829 if ((af != AF_UNSPEC && af != proto_buffers[i].iAddressFamily) ||
3830 (
type != proto_buffers[i].iSocketType) ||
3831 (protocol != 0 && protocol != proto_buffers[i].iProtocol))
3834 if ((proto_buffers[i].dwServiceFlags1 & XP1_IFS_HANDLES) == 0)
3837 out = WSASocket(af,
type, protocol, &(proto_buffers[i]), 0,
3838 WSA_FLAG_OVERLAPPED);
3841 if (out == INVALID_SOCKET)
3842 out = WSASocket(af,
type, protocol, NULL, 0, 0);
3843 if (out != INVALID_SOCKET)
3844 SetHandleInformation((HANDLE)out, HANDLE_FLAG_INHERIT, 0);
3847 free(proto_buffers);
3858rb_w32_socket(
int af,
int type,
int protocol)
3864 s = open_ifs_socket(af,
type, protocol);
3865 if (s == INVALID_SOCKET) {
3866 errno = map_errno(WSAGetLastError());
3870 fd = rb_w32_open_osfhandle(s, O_RDWR|O_BINARY|O_NOINHERIT);
3872 socklist_insert(s, MAKE_SOCKDATA(af, 0));
3883struct hostent * WSAAPI
3884rb_w32_gethostbyaddr(
const char *addr,
int len,
int type)
3888 r = gethostbyaddr(addr,
len,
type);
3890 errno = map_errno(WSAGetLastError());
3898struct hostent * WSAAPI
3899rb_w32_gethostbyname(
const char *name)
3903 r = gethostbyname(name);
3905 errno = map_errno(WSAGetLastError());
3914rb_w32_gethostname(
char *name,
int len)
3918 r = gethostname(name,
len);
3919 if (r == SOCKET_ERROR)
3920 errno = map_errno(WSAGetLastError());
3925#undef getprotobyname
3928struct protoent * WSAAPI
3929rb_w32_getprotobyname(
const char *name)
3933 r = getprotobyname(name);
3935 errno = map_errno(WSAGetLastError());
3940#undef getprotobynumber
3943struct protoent * WSAAPI
3944rb_w32_getprotobynumber(
int num)
3948 r = getprotobynumber(num);
3950 errno = map_errno(WSAGetLastError());
3958struct servent * WSAAPI
3959rb_w32_getservbyname(
const char *name,
const char *proto)
3963 r = getservbyname(name, proto);
3965 errno = map_errno(WSAGetLastError());
3973struct servent * WSAAPI
3974rb_w32_getservbyport(
int port,
const char *proto)
3978 r = getservbyport(port, proto);
3980 errno = map_errno(WSAGetLastError());
3989socketpair_unix_path(
struct sockaddr_un *sock_un, WCHAR *wpath,
const int maxpath)
3996 listener = socket(AF_UNIX, SOCK_STREAM, 0);
3997 if (listener == INVALID_SOCKET) {
3998 errno = EAFNOSUPPORT;
4002 memset(sock_un, 0,
sizeof(*sock_un));
4003 sock_un->sun_family = AF_UNIX;
4013 for (
int try = 0; ;
try++) {
4014 LARGE_INTEGER ticks;
4016 static const WCHAR FALLBACK_TEMP[] = L
"C:/Temp/";
4017 static const int FALLBACK_TEMP_SIZE = numberof(FALLBACK_TEMP) - 1;
4022 path_len = GetTempPathW(maxpath, wpath);
4023 if (path_len == 0 || path_len >= maxpath) {
4032 if (FALLBACK_TEMP_SIZE >= maxpath)
continue;
4033 wcsncpy(wpath, FALLBACK_TEMP, maxpath);
4034 path_len = FALLBACK_TEMP_SIZE;
4041 closesocket(listener);
4042 errno = EADDRNOTAVAIL;
4047 int un_len = WideCharToMultiByte(CP_UTF8, 0, wpath, path_len, sock_un->sun_path, maxpath, NULL, NULL);
4048 QueryPerformanceCounter(&ticks);
4049 int base_len = snprintf(sock_un->sun_path + un_len,
4053 GetCurrentProcessId());
4054 if (un_len + base_len >= maxpath)
continue;
4057 MultiByteToWideChar(CP_UTF8, 0, sock_un->sun_path + un_len, base_len + 1, wpath + path_len, maxpath - path_len);
4059 if (bind(listener, (
struct sockaddr *)sock_un,
sizeof(*sock_un)) != SOCKET_ERROR)
4062 closesocket(listener);
4064 return sizeof(*sock_un);
4070socketpair_internal(
int af,
int type,
int protocol, SOCKET *sv)
4072 SOCKET svr = INVALID_SOCKET, r = INVALID_SOCKET, w = INVALID_SOCKET;
4073 struct sockaddr_in sock_in4;
4076 struct sockaddr_in6 sock_in6;
4080 struct sockaddr_un sock_un = {0, {0}};
4081 WCHAR wpath[
sizeof(sock_un.sun_path)/
sizeof(*sock_un.sun_path)] = L
"";
4084 struct sockaddr *addr;
4090#if defined PF_INET && PF_INET != AF_INET
4093 sock_in4.sin_family = AF_INET;
4094 sock_in4.sin_port = 0;
4095 sock_in4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
4096 addr = (
struct sockaddr *)&sock_in4;
4097 len =
sizeof(sock_in4);
4101 memset(&sock_in6, 0,
sizeof(sock_in6));
4102 sock_in6.sin6_family = AF_INET6;
4103 sock_in6.sin6_addr = IN6ADDR_LOOPBACK_INIT;
4104 addr = (
struct sockaddr *)&sock_in6;
4105 len =
sizeof(sock_in6);
4110 addr = (
struct sockaddr *)&sock_un;
4111 len = socketpair_unix_path(&sock_un, wpath, numberof(wpath));
4112 if (!
len)
return -1;
4116 errno = EAFNOSUPPORT;
4119 if (
type != SOCK_STREAM) {
4124 sv[0] = (SOCKET)INVALID_HANDLE_VALUE;
4125 sv[1] = (SOCKET)INVALID_HANDLE_VALUE;
4128 svr = open_ifs_socket(af,
type, protocol);
4129 if (svr == INVALID_SOCKET)
4131 if (bind(svr, addr,
len) < 0)
4133 if (getsockname(svr, addr, &
len) < 0)
4135 if (
type == SOCK_STREAM)
4138 w = open_ifs_socket(af,
type, protocol);
4139 if (w == INVALID_SOCKET)
4141 if (connect(w, addr,
len) < 0)
4144 r = accept(svr, addr, &
len);
4145 if (r == INVALID_SOCKET)
4147 SetHandleInformation((HANDLE)r, HANDLE_FLAG_INHERIT, 0);
4153 errno = map_errno(WSAGetLastError());
4154 if (r != INVALID_SOCKET)
4156 if (w != INVALID_SOCKET)
4163 if (svr != INVALID_SOCKET)
4166 if (sock_un.sun_family == AF_UNIX)
4176socketpair(
int af,
int type,
int protocol,
int *sv)
4180 if (socketpair_internal(af,
type, protocol, pair) < 0)
4182 sv[0] = rb_w32_open_osfhandle(pair[0], O_RDWR|O_BINARY|O_NOINHERIT);
4184 closesocket(pair[0]);
4185 closesocket(pair[1]);
4188 sv[1] = rb_w32_open_osfhandle(pair[1], O_RDWR|O_BINARY|O_NOINHERIT);
4190 rb_w32_close(sv[0]);
4191 closesocket(pair[1]);
4194 socklist_insert(pair[0], MAKE_SOCKDATA(af, 0));
4195 socklist_insert(pair[1], MAKE_SOCKDATA(af, 0));
4202str2guid(
const char *str, GUID *guid)
4204#define hex2byte(str) \
4205 ((isdigit(*(str)) ? *(str) - '0' : toupper(*(str)) - 'A' + 10) << 4 | (isdigit(*((str) + 1)) ? *((str) + 1) - '0' : toupper(*((str) + 1)) - 'A' + 10))
4208 if (*str ==
'{') str++;
4209 guid->Data1 = (long)strtoul(str, &end, 16);
4211 guid->Data2 = (
unsigned short)strtoul(str, &end, 16);
4213 guid->Data3 = (
unsigned short)strtoul(str, &end, 16);
4215 guid->Data4[0] = hex2byte(str);
4217 guid->Data4[1] = hex2byte(str);
4219 for (i = 0; i < 6; i++) {
4220 guid->Data4[i + 2] = hex2byte(str);
4226#ifndef HAVE_TYPE_NET_LUID
4230 uint64_t Reserved :24;
4231 uint64_t NetLuidIndex :24;
4232 uint64_t IfType :16;
4238getifaddrs(
struct ifaddrs **ifap)
4242 IP_ADAPTER_ADDRESSES *root, *addr;
4245 ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, NULL, &size);
4246 if (ret != ERROR_BUFFER_OVERFLOW) {
4247 errno = map_errno(ret);
4250 root = ruby_xmalloc(size);
4251 ret = GetAdaptersAddresses(AF_UNSPEC, 0, NULL, root, &size);
4252 if (ret != ERROR_SUCCESS) {
4253 errno = map_errno(ret);
4258 for (prev = NULL, addr = root; addr; addr = addr->Next) {
4259 struct ifaddrs *ifa = ruby_xcalloc(1,
sizeof(*ifa));
4260 char name[IFNAMSIZ];
4265 prev->ifa_next = ifa;
4269 str2guid(addr->AdapterName, &guid);
4270 if (ConvertInterfaceGuidToLuid(&guid, &luid) == NO_ERROR &&
4271 ConvertInterfaceLuidToNameA(&luid, name,
sizeof(name)) == NO_ERROR) {
4278 if (addr->IfType & IF_TYPE_SOFTWARE_LOOPBACK)
4279 ifa->ifa_flags |= IFF_LOOPBACK;
4280 if (addr->OperStatus == IfOperStatusUp) {
4281 ifa->ifa_flags |= IFF_UP;
4283 if (addr->FirstUnicastAddress) {
4284 IP_ADAPTER_UNICAST_ADDRESS *cur;
4286 for (cur = addr->FirstUnicastAddress; cur; cur = cur->Next) {
4287 if (cur->Flags & IP_ADAPTER_ADDRESS_TRANSIENT ||
4288 cur->DadState == IpDadStateDeprecated) {
4293 ifa = ruby_xcalloc(1,
sizeof(*ifa));
4294 prev->ifa_next = ifa;
4296 ifa->ifa_flags = prev->ifa_flags;
4298 ifa->ifa_addr = ruby_xmalloc(cur->Address.iSockaddrLength);
4299 memcpy(ifa->ifa_addr, cur->Address.lpSockaddr,
4300 cur->Address.iSockaddrLength);
4315freeifaddrs(
struct ifaddrs *ifp)
4318 struct ifaddrs *next = ifp->ifa_next;
4319 ruby_xfree(ifp->ifa_addr);
4320 ruby_xfree(ifp->ifa_name);
4331void endhostent(
void) {}
4332void endnetent(
void) {}
4333void endprotoent(
void) {}
4334void endservent(
void) {}
4336struct netent *getnetent (
void) {
return (
struct netent *) NULL;}
4338struct netent *getnetbyaddr(
long net,
int type) {
return (
struct netent *)NULL;}
4340struct netent *getnetbyname(
const char *name) {
return (
struct netent *)NULL;}
4342struct protoent *getprotoent (
void) {
return (
struct protoent *) NULL;}
4344struct servent *getservent (
void) {
return (
struct servent *) NULL;}
4346void sethostent (
int stayopen) {}
4348void setnetent (
int stayopen) {}
4350void setprotoent (
int stayopen) {}
4352void setservent (
int stayopen) {}
4355int rb_w32_set_nonblock2(
int fd,
int nonblock);
4359setfl(SOCKET sock,
int arg)
4366 socklist_lookup(sock, &flag);
4367 af = GET_FAMILY(flag);
4368 flag = GET_FLAGS(flag);
4369 if (arg & O_NONBLOCK) {
4374 flag &= ~O_NONBLOCK;
4378 ret = ioctlsocket(sock, FIONBIO, &ioctlArg);
4380 socklist_insert(sock, MAKE_SOCKDATA(af, flag));
4382 errno = map_errno(WSAGetLastError());
4390dupfd(HANDLE hDup,
int flags,
int minfd)
4398 ret = _open_osfhandle((intptr_t)hDup, flags | FOPEN);
4400 goto close_fds_and_return;
4403 goto close_fds_and_return;
4405 fds[filled++] = ret;
4406 }
while (filled < (
int)numberof(fds));
4408 ret = dupfd(hDup, flags, minfd);
4410 close_fds_and_return:
4412 while (filled > 0) {
4413 int fd = fds[--filled];
4414 _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE);
4424fcntl(
int fd,
int cmd, ...)
4433 arg = va_arg(va,
int);
4435 return rb_w32_set_nonblock2(fd, arg);
4437 case F_DUPFD:
case F_DUPFD_CLOEXEC: {
4441 if (!(DuplicateHandle(GetCurrentProcess(), (HANDLE)_get_osfhandle(fd),
4442 GetCurrentProcess(), &hDup, 0L,
4443 cmd == F_DUPFD && !(flag & FNOINHERIT),
4444 DUPLICATE_SAME_ACCESS))) {
4445 errno = map_errno(GetLastError());
4450 arg = va_arg(va,
int);
4456 flag &= ~FNOINHERIT;
4457 if ((ret = dupfd(hDup, flag, arg)) == -1)
4463 if (h == -1)
return -1;
4464 if (!GetHandleInformation((HANDLE)h, &flag)) {
4465 errno = map_errno(GetLastError());
4468 return (flag & HANDLE_FLAG_INHERIT) ? 0 : FD_CLOEXEC;
4472 if (h == -1)
return -1;
4474 arg = va_arg(va,
int);
4476 if (!SetHandleInformation((HANDLE)h, HANDLE_FLAG_INHERIT,
4477 (arg & FD_CLOEXEC) ? 0 : HANDLE_FLAG_INHERIT)) {
4478 errno = map_errno(GetLastError());
4481 if (arg & FD_CLOEXEC)
4482 _osfile(fd) |= FNOINHERIT;
4484 _osfile(fd) &= ~FNOINHERIT;
4495rb_w32_set_nonblock2(
int fd,
int nonblock)
4497 SOCKET sock = TO_SOCKET(fd);
4498 if (is_socket(sock)) {
4499 return setfl(sock, nonblock ? O_NONBLOCK : 0);
4501 else if (is_pipe(sock)) {
4503 if (!GetNamedPipeHandleState((HANDLE)sock, &state, NULL, NULL, NULL, NULL, 0)) {
4504 errno = map_errno(GetLastError());
4508 state |= PIPE_NOWAIT;
4511 state &= ~PIPE_NOWAIT;
4513 if (!SetNamedPipeHandleState((HANDLE)sock, &state, NULL, NULL)) {
4514 errno = map_errno(GetLastError());
4526rb_w32_set_nonblock(
int fd)
4528 return rb_w32_set_nonblock2(fd, TRUE);
4537poll_child_status(
struct ChildRecord *child,
int *stat_loc)
4542 if (!GetExitCodeProcess(child->hProcess, &exitcode)) {
4544 err = GetLastError();
4546 case ERROR_INVALID_PARAMETER:
4549 case ERROR_INVALID_HANDLE:
4553 errno = map_errno(err);
4557 CloseChildHandle(child);
4560 if (exitcode != STILL_ACTIVE) {
4563 if (rb_w32_wait_events_blocking(&child->hProcess, 1, INFINITE) != WAIT_OBJECT_0) {
4567 CloseChildHandle(child);
4569 *stat_loc = exitcode << 8;
4570 if (exitcode & 0xC0000000) {
4571 static const struct {
4575 {STATUS_ACCESS_VIOLATION, SIGSEGV},
4576 {STATUS_ILLEGAL_INSTRUCTION, SIGILL},
4577 {STATUS_PRIVILEGED_INSTRUCTION, SIGILL},
4578 {STATUS_FLOAT_DENORMAL_OPERAND, SIGFPE},
4579 {STATUS_FLOAT_DIVIDE_BY_ZERO, SIGFPE},
4580 {STATUS_FLOAT_INEXACT_RESULT, SIGFPE},
4581 {STATUS_FLOAT_INVALID_OPERATION, SIGFPE},
4582 {STATUS_FLOAT_OVERFLOW, SIGFPE},
4583 {STATUS_FLOAT_STACK_CHECK, SIGFPE},
4584 {STATUS_FLOAT_UNDERFLOW, SIGFPE},
4585#ifdef STATUS_FLOAT_MULTIPLE_FAULTS
4586 {STATUS_FLOAT_MULTIPLE_FAULTS, SIGFPE},
4588#ifdef STATUS_FLOAT_MULTIPLE_TRAPS
4589 {STATUS_FLOAT_MULTIPLE_TRAPS, SIGFPE},
4591 {STATUS_CONTROL_C_EXIT, SIGINT},
4594 for (i = 0; i < (int)numberof(table); i++) {
4595 if (table[i].status == exitcode) {
4596 *stat_loc |= table[i].sig;
4601 if (i >= (
int)numberof(table))
4602 *stat_loc |= SIGSEGV;
4612waitpid(rb_pid_t pid,
int *stat_loc,
int options)
4617 if (options == WNOHANG) {
4628 HANDLE events[MAXCHILDNUM];
4631 FOREACH_CHILD(child) {
4632 if (!child->pid || child->pid < 0)
continue;
4633 if ((pid = poll_child_status(child, stat_loc)))
return pid;
4634 events[count++] = child->hProcess;
4635 } END_FOREACH_CHILD;
4641 ret = rb_w32_wait_events_blocking(events, count, timeout);
4642 if (ret == WAIT_TIMEOUT)
return 0;
4643 if ((ret -= WAIT_OBJECT_0) == count) {
4647 errno = map_errno(GetLastError());
4651 cause = FindChildSlotByHandle(events[ret]);
4656 return poll_child_status(cause, stat_loc);
4666 while (!(pid = poll_child_status(child, stat_loc))) {
4668 int ret = rb_w32_wait_events_blocking(&child->hProcess, 1, timeout);
4669 if (ret == WAIT_OBJECT_0 + 1)
return -1;
4670 if (ret != WAIT_OBJECT_0) {
4672 if (options & WNOHANG) {
4679 if (pid == -1 && retried) pid = 0;
4685#include <sys/timeb.h>
4688#define filetime_unit (10UL * 1000 * 1000)
4689#define filetime_diff_days ((1970-1601)*3652425UL/10000)
4690#define filetime_diff_secs (filetime_diff_days * (24ULL * 60 * 60))
4691#define unix_to_filetime(sec) (((sec) + filetime_diff_secs) * filetime_unit)
4692#define filetime_unix_offset unix_to_filetime(0ULL)
4704filetime_split(
const FILETIME* ft,
long *subsec)
4707 ULONGLONG lt = fi.i.QuadPart;
4713 lt -= unix_to_filetime(0);
4715 *subsec = (long)(lt % filetime_unit);
4716 return (time_t)(lt / filetime_unit);
4726 GetSystemTimePreciseAsFileTime(&ft);
4727 tv->tv_sec = filetime_split(&ft, &subsec);
4728 tv->tv_usec = subsec / 10;
4735filetime_to_timespec(FILETIME ft,
struct timespec *sp)
4738 sp->tv_sec = filetime_split(&ft, &subsec);
4739 sp->tv_nsec = subsec * 100;
4743static const long secs_in_ns = 1000000000;
4747clock_gettime(clockid_t clock_id,
struct timespec *sp)
4750 case CLOCK_REALTIME:
4751 case CLOCK_REALTIME_COARSE:
4755 GetSystemTimePreciseAsFileTime(&ft);
4756 filetime_to_timespec(ft, sp);
4759 case CLOCK_MONOTONIC:
4762 LARGE_INTEGER count;
4763 if (UNLIKELY(!QueryPerformanceFrequency(&freq))) {
4764 errno = map_errno(GetLastError());
4767 if (UNLIKELY(!QueryPerformanceCounter(&count))) {
4768 errno = map_errno(GetLastError());
4771 sp->tv_sec = count.QuadPart / freq.QuadPart;
4772 if (freq.QuadPart < secs_in_ns)
4773 sp->tv_nsec = (count.QuadPart % freq.QuadPart) * secs_in_ns / freq.QuadPart;
4775 sp->tv_nsec = (long)((count.QuadPart % freq.QuadPart) * ((
double)secs_in_ns / freq.QuadPart));
4778 case CLOCK_PROCESS_CPUTIME_ID:
4779 case CLOCK_THREAD_CPUTIME_ID:
4783 if (clock_id == CLOCK_PROCESS_CPUTIME_ID) {
4784 ok = GetProcessTimes(GetCurrentProcess(), &c.ft, &e.ft, &k.ft, &u.ft);
4787 ok = GetThreadTimes(GetCurrentThread(), &c.ft, &e.ft, &k.ft, &u.ft);
4789 if (UNLIKELY(!ok)) {
4790 errno = map_errno(GetLastError());
4793 total.i.QuadPart = k.i.QuadPart + u.i.QuadPart;
4794 filetime_to_timespec(total.ft, sp);
4805clock_getres(clockid_t clock_id,
struct timespec *sp)
4808 case CLOCK_REALTIME:
4809 case CLOCK_REALTIME_COARSE:
4815 case CLOCK_MONOTONIC:
4818 if (!QueryPerformanceFrequency(&freq)) {
4819 errno = map_errno(GetLastError());
4823 sp->tv_nsec = (long)((
double)secs_in_ns / freq.QuadPart);
4826 case CLOCK_PROCESS_CPUTIME_ID:
4827 case CLOCK_THREAD_CPUTIME_ID:
4829 const int frames_in_sec = 60;
4831 sp->tv_nsec = (long)(secs_in_ns / frames_in_sec);
4842w32_getcwd(
char *buffer,
int size, UINT cp,
void *alloc(
int,
void *),
void *arg)
4847 len = GetCurrentDirectoryW(0, NULL);
4849 errno = map_errno(GetLastError());
4853 if (buffer && size <
len) {
4859 if (!GetCurrentDirectoryW(
len, p)) {
4860 errno = map_errno(GetLastError());
4864 wlen = translate_wchar(p, L
'\\', L
'/') - p + 1;
4865 len = WideCharToMultiByte(cp, 0, p, wlen, NULL, 0, NULL, NULL);
4873 buffer = (*alloc)(
len, arg);
4879 WideCharToMultiByte(cp, 0, p, wlen, buffer,
len, NULL, NULL);
4886getcwd_alloc(
int size,
void *dummy)
4888 return malloc(size);
4893rb_w32_getcwd(
char *buffer,
int size)
4895 return w32_getcwd(buffer, size, filecp(), getcwd_alloc, NULL);
4900rb_w32_ugetcwd(
char *buffer,
int size)
4902 return w32_getcwd(buffer, size, CP_UTF8, getcwd_alloc, NULL);
4907getcwd_value(
int size,
void *arg)
4910 return RSTRING_PTR(str);
4915rb_dir_getwd_ospath(
void)
4918 w32_getcwd(NULL, 0, CP_UTF8, getcwd_value, &cwd);
4924chown(
const char *path,
int owner,
int group)
4931rb_w32_uchown(
const char *path,
int owner,
int group)
4937lchown(
const char *path,
int owner,
int group)
4943rb_w32_ulchown(
const char *path,
int owner,
int group)
4950kill(rb_pid_t pid,
int sig)
4955 if (pid < 0 || (pid == 0 && sig != SIGINT)) {
4960 if ((
unsigned int)pid == GetCurrentProcessId() &&
4961 (sig != 0 && sig != SIGKILL)) {
4962 if ((ret = raise(sig)) != 0) {
4973 OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid);
4974 if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) {
4975 if (GetLastError() == ERROR_INVALID_PARAMETER) {
4991 DWORD ctrlEvent = CTRL_C_EVENT;
4995 ctrlEvent = CTRL_BREAK_EVENT;
4997 if (!GenerateConsoleCtrlEvent(ctrlEvent, (DWORD)pid)) {
4998 if ((err = GetLastError()) == 0)
5001 errno = map_errno(GetLastError());
5012 hProc = child->hProcess;
5015 hProc = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, FALSE, (DWORD)pid);
5017 if (hProc == NULL || hProc == INVALID_HANDLE_VALUE) {
5018 if (GetLastError() == ERROR_INVALID_PARAMETER) {
5028 if (!GetExitCodeProcess(hProc, &status)) {
5029 errno = map_errno(GetLastError());
5032 else if (status == STILL_ACTIVE) {
5033 if (!TerminateProcess(hProc, 0)) {
5060wlink(
const WCHAR *from,
const WCHAR *to)
5062 if (!CreateHardLinkW(to, from, NULL)) {
5063 errno = map_errno(GetLastError());
5072rb_w32_ulink(
const char *from,
const char *to)
5078 if (!(wfrom = utf8_to_wstr(from, NULL)))
5080 if (!(wto = utf8_to_wstr(to, NULL))) {
5084 ret = wlink(wfrom, wto);
5092link(
const char *from,
const char *to)
5098 if (!(wfrom = filecp_to_wstr(from, NULL)))
5100 if (!(wto = filecp_to_wstr(to, NULL))) {
5104 ret = wlink(wfrom, wto);
5111#ifndef FILE_DEVICE_FILE_SYSTEM
5112# define FILE_DEVICE_FILE_SYSTEM 0x00000009
5114#ifndef FSCTL_GET_REPARSE_POINT
5115# define FSCTL_GET_REPARSE_POINT ((0x9<<16)|(42<<2))
5117#ifndef IO_REPARSE_TAG_SYMLINK
5118# define IO_REPARSE_TAG_SYMLINK 0xA000000CL
5129 f = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5130 if (f == INVALID_HANDLE_VALUE) {
5131 return GetLastError();
5134 if (!DeviceIoControl(f, FSCTL_GET_REPARSE_POINT, NULL, 0,
5135 rp, size, &ret, NULL)) {
5138 else if (rp->ReparseTag != IO_REPARSE_TAG_SYMLINK &&
5139 rp->ReparseTag != IO_REPARSE_TAG_MOUNT_POINT) {
5140 e = ERROR_INVALID_PARAMETER;
5148rb_w32_reparse_symlink_p(
const WCHAR *path)
5156 e = rb_w32_read_reparse_point(path, rp,
sizeof(rbuf), &wbuf, &
len);
5157 if (e == ERROR_MORE_DATA) {
5158 size_t size = rb_w32_reparse_buffer_size(
len + 1);
5160 e = rb_w32_read_reparse_point(path, rp, size, &wbuf, &
len);
5165 case ERROR_MORE_DATA:
5174 size_t bufsize, WCHAR **result, DWORD *
len)
5176 int e = reparse_symlink(path, rp, bufsize);
5179 if (!e || e == ERROR_MORE_DATA) {
5181 if (rp->ReparseTag == IO_REPARSE_TAG_SYMLINK) {
5182 name = ((
char *)rp->SymbolicLinkReparseBuffer.PathBuffer +
5183 rp->SymbolicLinkReparseBuffer.PrintNameOffset);
5184 ret = rp->SymbolicLinkReparseBuffer.PrintNameLength;
5185 *
len = ret /
sizeof(WCHAR);
5187 else if (rp->ReparseTag == IO_REPARSE_TAG_MOUNT_POINT) {
5188 static const WCHAR volume[] = L
"Volume{";
5190 name = ((
char *)rp->MountPointReparseBuffer.PathBuffer +
5191 rp->MountPointReparseBuffer.SubstituteNameOffset +
5192 volume_prefix_len *
sizeof(WCHAR));
5193 ret = rp->MountPointReparseBuffer.SubstituteNameLength;
5194 *
len = ret /
sizeof(WCHAR);
5195 ret -= volume_prefix_len *
sizeof(WCHAR);
5196 if (ret >
sizeof(volume) - 1 *
sizeof(WCHAR) &&
5197 memcmp(name, volume,
sizeof(volume) - 1 *
sizeof(WCHAR)) == 0)
5205 if ((
char *)name + ret +
sizeof(WCHAR) > (
char *)rp + bufsize)
5209 ((WCHAR *)name)[ret/
sizeof(WCHAR)] = L
'\0';
5210 translate_wchar(name, L
'\\', L
'/');
5220w32_readlink(UINT cp,
const char *path,
char *buf,
size_t bufsize)
5222 VALUE rp_buf, rp_buf_bigger = 0;
5223 DWORD
len = MultiByteToWideChar(cp, 0, path, -1, NULL, 0);
5224 size_t size = rb_w32_reparse_buffer_size(bufsize);
5226 WCHAR *wpath =
ALLOCV(rp_buf,
sizeof(WCHAR) *
len + size);
5231 MultiByteToWideChar(cp, 0, path, -1, wpath,
len);
5232 e = rb_w32_read_reparse_point(wpath, rp, size, &wname, &
len);
5233 if (e == ERROR_MORE_DATA) {
5234 size = rb_w32_reparse_buffer_size(
len + 1);
5235 rp =
ALLOCV(rp_buf_bigger, size);
5236 e = rb_w32_read_reparse_point(wpath, rp, size, &wname, &
len);
5241 errno = e == -1 ? EINVAL : map_errno(e);
5244 len = lstrlenW(wname);
5245 ret = WideCharToMultiByte(cp, 0, wname,
len, buf, bufsize, NULL, NULL);
5256rb_w32_ureadlink(
const char *path,
char *buf,
size_t bufsize)
5258 return w32_readlink(CP_UTF8, path, buf, bufsize);
5263readlink(
const char *path,
char *buf,
size_t bufsize)
5265 return w32_readlink(filecp(), path, buf, bufsize);
5268#ifndef SYMBOLIC_LINK_FLAG_DIRECTORY
5269#define SYMBOLIC_LINK_FLAG_DIRECTORY (0x1)
5271#ifndef SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
5272#define SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE (0x2)
5277w32_symlink(UINT cp,
const char *src,
const char *link)
5279 int atts, len1, len2;
5281 WCHAR *wsrc, *wlink;
5286 static DWORD create_flag = SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
5296 len1 = MultiByteToWideChar(cp, 0, src, -1, NULL, 0);
5297 len2 = MultiByteToWideChar(cp, 0, link, -1, NULL, 0);
5298 wsrc =
ALLOCV_N(WCHAR, buf, len1+len2);
5299 wlink = wsrc + len1;
5300 MultiByteToWideChar(cp, 0, src, -1, wsrc, len1);
5301 MultiByteToWideChar(cp, 0, link, -1, wlink, len2);
5302 translate_wchar(wsrc, L
'/', L
'\\');
5303 translate_wchar(wlink, L
'/', L
'\\');
5313 (((wsrc[0] >= L
'A' && wsrc[0] <= L
'Z') ||
5314 (wsrc[0] >= L
'a' && wsrc[0] <= L
'z')) && wsrc[1] == L
':') ||
5316 if (!independent && (sep = wcsrchr(wlink, L
'\\')) != NULL) {
5318 size_t dirlen = sep - wlink + 1;
5319 size_t srclen = wcslen(wsrc) + 1;
5320 WCHAR *fullsrc =
ALLOCV_N(WCHAR, buf2, dirlen + srclen);
5321 MEMCPY(fullsrc, wlink, WCHAR, dirlen);
5322 MEMCPY(fullsrc + dirlen, wsrc, WCHAR, srclen);
5323 atts = GetFileAttributesW(fullsrc);
5327 atts = GetFileAttributesW(wsrc);
5330 if (atts != -1 && atts & FILE_ATTRIBUTE_DIRECTORY)
5331 flag = SYMBOLIC_LINK_FLAG_DIRECTORY;
5332 ret = CreateSymbolicLinkW(wlink, wsrc, flag |= create_flag);
5334 (e = GetLastError()) == ERROR_INVALID_PARAMETER &&
5335 (flag & SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE)) {
5337 flag &= ~SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE;
5338 ret = CreateSymbolicLinkW(wlink, wsrc, flag);
5339 if (!ret) e = GetLastError();
5344 errno = map_errno(e);
5352rb_w32_usymlink(
const char *src,
const char *link)
5354 return w32_symlink(CP_UTF8, src, link);
5359symlink(
const char *src,
const char *link)
5361 return w32_symlink(filecp(), src, link);
5368 return waitpid(-1, status, 0);
5373w32_getenv(
const char *name, UINT cp)
5375 WCHAR *wenvarea, *wenv;
5376 int len = strlen(name);
5377 char *uenvarea, *env, *found = NULL;
5380 if (
len == 0)
return NULL;
5385 return getenv(name);
5388 free(FlsGetValue(uenvarea_key));
5389 FlsSetValue(uenvarea_key, NULL);
5390 wenvarea = GetEnvironmentStringsW();
5392 map_errno(GetLastError());
5395 for (wenv = wenvarea, wlen = 1; *wenv; wenv += lstrlenW(wenv) + 1)
5396 wlen += lstrlenW(wenv) + 1;
5397 uenvarea = wstr_to_mbstr(cp, wenvarea, wlen, NULL);
5398 FreeEnvironmentStringsW(wenvarea);
5401 FlsSetValue(uenvarea_key, uenvarea);
5403 for (env = uenvarea; *env; env += strlen(env) + 1) {
5404 if (strncasecmp(env, name,
len) == 0 && *(env +
len) ==
'=') {
5405 found = env +
len + 1;
5415rb_w32_ugetenv(
const char *name)
5417 return w32_getenv(name, CP_UTF8);
5422rb_w32_getenv(
const char *name)
5424 return w32_getenv(name, CP_ACP);
5429get_attr_vsn(
const WCHAR *path, DWORD *atts, DWORD *vsn)
5431 BY_HANDLE_FILE_INFORMATION st = {0};
5433 HANDLE h = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5435 if (h == INVALID_HANDLE_VALUE) {
5440 if (!GetFileInformationByHandle(h, &st)) {
5445 *atts = st.dwFileAttributes;
5446 *vsn = st.dwVolumeSerialNumber;
5454wrename(
const WCHAR *oldpath,
const WCHAR *newpath)
5457 DWORD oldatts = 0, newatts = (DWORD)-1;
5458 DWORD oldvsn = 0, newvsn = 0, e;
5460 e = get_attr_vsn(oldpath, &oldatts, &oldvsn);
5462 errno = map_errno(e);
5465 if (oldatts & FILE_ATTRIBUTE_REPARSE_POINT) {
5466 HANDLE fh = open_special(oldpath, 0, 0);
5467 if (fh == INVALID_HANDLE_VALUE) {
5469 if (e == ERROR_CANT_RESOLVE_FILENAME) {
5476 get_attr_vsn(newpath, &newatts, &newvsn);
5479 if (newatts != (DWORD)-1 && newatts & FILE_ATTRIBUTE_READONLY)
5480 SetFileAttributesW(newpath, newatts & ~ FILE_ATTRIBUTE_READONLY);
5482 if (!MoveFileExW(oldpath, newpath, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED))
5486 DWORD e = GetLastError();
5487 if ((e == ERROR_ACCESS_DENIED) && (oldatts & FILE_ATTRIBUTE_DIRECTORY) &&
5491 errno = map_errno(e);
5494 SetFileAttributesW(newpath, oldatts);
5502rb_w32_urename(
const char *from,
const char *to)
5508 if (!(wfrom = utf8_to_wstr(from, NULL)))
5510 if (!(wto = utf8_to_wstr(to, NULL))) {
5514 ret = wrename(wfrom, wto);
5522rb_w32_rename(
const char *from,
const char *to)
5528 if (!(wfrom = filecp_to_wstr(from, NULL)))
5530 if (!(wto = filecp_to_wstr(to, NULL))) {
5534 ret = wrename(wfrom, wto);
5542isUNCRoot(
const WCHAR *path)
5544 if (path[0] == L
'\\' && path[1] == L
'\\') {
5545 const WCHAR *p = path + 2;
5546 if (p[0] == L
'?' && p[1] == L
'\\') {
5554 for (p++; *p; p++) {
5558 if (!p[0] || !p[1] || (p[1] == L
'.' && !p[2]))
5565#define COPY_STAT(src, dest, size_cast) do { \
5566 (dest).st_dev = (src).st_dev; \
5567 (dest).st_ino = (src).st_ino; \
5568 (dest).st_mode = (src).st_mode; \
5569 (dest).st_nlink = (src).st_nlink; \
5570 (dest).st_uid = (src).st_uid; \
5571 (dest).st_gid = (src).st_gid; \
5572 (dest).st_rdev = (src).st_rdev; \
5573 (dest).st_size = size_cast(src).st_size; \
5574 (dest).st_atime = (src).st_atime; \
5575 (dest).st_mtime = (src).st_mtime; \
5576 (dest).st_ctime = (src).st_ctime; \
5579static time_t filetime_to_unixtime(
const FILETIME *ft);
5580static long filetime_to_nsec(
const FILETIME *ft);
5581static WCHAR *name_for_stat(WCHAR *buf,
const WCHAR *path);
5582static DWORD stati128_handle(HANDLE h,
struct stati128 *st);
5587rb_w32_fstat(
int fd,
struct stat *st)
5589 BY_HANDLE_FILE_INFORMATION info;
5590 int ret = fstat(fd, st);
5592 if (ret)
return ret;
5593 if (GetEnvironmentVariableW(L
"TZ", NULL, 0) == 0 && GetLastError() == ERROR_ENVVAR_NOT_FOUND)
return ret;
5594 if (GetFileInformationByHandle((HANDLE)_get_osfhandle(fd), &info)) {
5595 st->st_atime = filetime_to_unixtime(&info.ftLastAccessTime);
5596 st->st_mtime = filetime_to_unixtime(&info.ftLastWriteTime);
5597 st->st_ctime = filetime_to_unixtime(&info.ftCreationTime);
5604rb_w32_fstati128(
int fd,
struct stati128 *st)
5607 int ret = fstat(fd, &tmp);
5609 if (ret)
return ret;
5610 COPY_STAT(tmp, *st, +);
5611 stati128_handle((HANDLE)_get_osfhandle(fd), st);
5615#if !defined FILE_INVALID_FILE_ID && !defined __MINGW32__
5617 BYTE Identifier[16];
5621#if !defined(_WIN32_WINNT_WIN8) || _WIN32_WINNT < 0x602
5622#define FileIdInfo 0x12
5633 return GetFileInformationByHandleEx(h, FileIdInfo,
id,
sizeof(*
id));
5638stati128_handle(HANDLE h,
struct stati128 *st)
5640 BY_HANDLE_FILE_INFORMATION info;
5641 DWORD attr = (DWORD)-1;
5643 if (GetFileInformationByHandle(h, &info)) {
5645 st->st_size = ((__int64)info.nFileSizeHigh << 32) | info.nFileSizeLow;
5646 st->st_atime = filetime_to_unixtime(&info.ftLastAccessTime);
5647 st->st_atimensec = filetime_to_nsec(&info.ftLastAccessTime);
5648 st->st_mtime = filetime_to_unixtime(&info.ftLastWriteTime);
5649 st->st_mtimensec = filetime_to_nsec(&info.ftLastWriteTime);
5650 st->st_ctime = filetime_to_unixtime(&info.ftCreationTime);
5651 st->st_ctimensec = filetime_to_nsec(&info.ftCreationTime);
5652 st->st_nlink = info.nNumberOfLinks;
5653 attr = info.dwFileAttributes;
5654 if (get_ino(h, &fii)) {
5655 st->st_ino = *((
unsigned __int64 *)&fii.FileId);
5656 st->st_inohigh = *((__int64 *)&fii.FileId + 1);
5659 st->st_ino = ((__int64)info.nFileIndexHigh << 32) | info.nFileIndexLow;
5668filetime_to_unixtime(
const FILETIME *ft)
5671 time_t t = filetime_split(ft, &subsec);
5673 if (t < 0)
return 0;
5679filetime_to_nsec(
const FILETIME *ft)
5682 tmp.LowPart = ft->dwLowDateTime;
5683 tmp.HighPart = ft->dwHighDateTime;
5684 return (
long)(tmp.QuadPart % 10000000) * 100;
5689fileattr_to_unixmode(DWORD attr,
const WCHAR *path,
unsigned mode)
5691 if (attr & FILE_ATTRIBUTE_READONLY) {
5695 mode |= S_IREAD | S_IWRITE | S_IWUSR;
5698 if (mode & S_IFMT) {
5701 else if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
5705 else if (attr & FILE_ATTRIBUTE_DIRECTORY) {
5706 mode |= S_IFDIR | S_IEXEC;
5712 if (path && (mode & S_IFREG)) {
5713 const WCHAR *end = path + lstrlenW(path);
5714 while (path < end) {
5715 end = CharPrevW(path, end);
5717 if ((_wcsicmp(end, L
".bat") == 0) ||
5718 (_wcsicmp(end, L
".cmd") == 0) ||
5719 (_wcsicmp(end, L
".com") == 0) ||
5720 (_wcsicmp(end, L
".exe") == 0)) {
5725 if (!iswalnum(*end))
break;
5729 mode |= (mode & 0500) >> 3;
5730 mode |= (mode & 0500) >> 6;
5737check_valid_dir(
const WCHAR *path)
5739 WIN32_FIND_DATAW fd;
5741 WCHAR full[PATH_MAX];
5746 if (!(p = wcsstr(path, L
"...")))
5748 q = p + wcsspn(p, L
".");
5749 if ((p == path || wcschr(L
":/\\", *(p - 1))) &&
5750 (!*q || wcschr(L
":/\\", *q))) {
5757 DWORD
len = GetFullPathNameW(path, numberof(full), full, NULL);
5758 if (
len >= numberof(full)) {
5759 WCHAR *fullpath = malloc(
len *
sizeof(WCHAR));
5760 if (!fullpath)
return -1;
5761 len = GetFullPathNameW(path,
len, fullpath, NULL);
5766 errno = map_errno(GetLastError());
5769 if (
len == 3 && full[1] == L
':' && GetDriveTypeW(full) != DRIVE_NO_ROOT_DIR)
5772 fh = open_dir_handle(path, &fd);
5773 if (fh == INVALID_HANDLE_VALUE)
5781stat_by_find(
const WCHAR *path,
struct stati128 *st)
5784 WIN32_FIND_DATAW wfd;
5787 h = FindFirstFileW(path, &wfd);
5788 if (h == INVALID_HANDLE_VALUE) {
5789 errno = map_errno(GetLastError());
5793 st->st_mode = fileattr_to_unixmode(wfd.dwFileAttributes, path, 0);
5794 st->st_atime = filetime_to_unixtime(&wfd.ftLastAccessTime);
5795 st->st_atimensec = filetime_to_nsec(&wfd.ftLastAccessTime);
5796 st->st_mtime = filetime_to_unixtime(&wfd.ftLastWriteTime);
5797 st->st_mtimensec = filetime_to_nsec(&wfd.ftLastWriteTime);
5798 st->st_ctime = filetime_to_unixtime(&wfd.ftCreationTime);
5799 st->st_ctimensec = filetime_to_nsec(&wfd.ftCreationTime);
5800 st->st_size = ((__int64)wfd.nFileSizeHigh << 32) | wfd.nFileSizeLow;
5807path_drive(
const WCHAR *path)
5809 if (path[0] && path[1] == L
':') {
5810 if (iswalpha(path[0]))
return towupper(path[0]) - L
'A';
5811 return (
int)path[0];
5813 return _getdrive() - 1;
5818winnt_stat(
const WCHAR *path,
struct stati128 *st, BOOL lstat)
5820 DWORD flags = lstat ? FILE_FLAG_OPEN_REPARSE_POINT : 0;
5822 WCHAR *finalname = 0;
5825 memset(st, 0,
sizeof(*st));
5826 f = open_special(path, 0, flags);
5827 open_error = GetLastError();
5828 if (f == INVALID_HANDLE_VALUE && !lstat) {
5830 FILE_ATTRIBUTE_TAG_INFO attr_info;
5833 f = open_special(path, 0, FILE_FLAG_OPEN_REPARSE_POINT);
5834 e = GetFileInformationByHandleEx(f, FileAttributeTagInfo,
5835 &attr_info,
sizeof(attr_info));
5836 if (!e || attr_info.ReparseTag != IO_REPARSE_TAG_AF_UNIX) {
5838 f = INVALID_HANDLE_VALUE;
5841 if (f != INVALID_HANDLE_VALUE) {
5842 DWORD attr = stati128_handle(f, st);
5844 switch (GetFileType(f)) {
5845 case FILE_TYPE_CHAR:
5848 case FILE_TYPE_PIPE:
5852 if (attr & FILE_ATTRIBUTE_DIRECTORY) {
5853 if (check_valid_dir(path))
return -1;
5855 if (attr & FILE_ATTRIBUTE_REPARSE_POINT) {
5856 FILE_ATTRIBUTE_TAG_INFO attr_info;
5859 e = GetFileInformationByHandleEx(f, FileAttributeTagInfo,
5860 &attr_info,
sizeof(attr_info));
5861 if (e && attr_info.ReparseTag == IO_REPARSE_TAG_AF_UNIX) {
5865 else if (rb_w32_reparse_symlink_p(path)) {
5868 mode |= S_IFLNK | S_IEXEC;
5871 mode |= S_IFDIR | S_IEXEC;
5875 const DWORD
len = get_handle_pathname(f, &finalname, 0);
5877 st->st_mode = fileattr_to_unixmode(attr, path, mode);
5880 if (wcsncmp(path, namespace_prefix, numberof(namespace_prefix)) == 0)
5881 path += numberof(namespace_prefix);
5885 switch (open_error) {
5886 case ERROR_FILE_NOT_FOUND:
5887 case ERROR_INVALID_NAME:
5888 case ERROR_PATH_NOT_FOUND:
5889 case ERROR_BAD_NETPATH:
5890 case ERROR_CANT_RESOLVE_FILENAME:
5891 errno = map_errno(open_error);
5895 if (stat_by_find(path, st))
return -1;
5898 st->st_dev = st->st_rdev = path_drive(path);
5899 if (finalname) free(finalname);
5906rb_w32_stat(
const char *path,
struct stat *st)
5908 struct stati128 tmp;
5910 if (w32_stati128(path, &tmp, filecp(), FALSE))
return -1;
5911 COPY_STAT(tmp, *st, (_off_t));
5917wstati128(
const WCHAR *path,
struct stati128 *st, BOOL lstat)
5927 size = lstrlenW(path) + 2;
5929 if (!(path = name_for_stat(buf1, path)))
5931 ret = winnt_stat(path, st, lstat);
5940name_for_stat(WCHAR *buf1,
const WCHAR *path)
5946 for (p = path, s = buf1; *p; p++, s++) {
5954 if (!
len || L
'\"' == *(--s)) {
5958 end = buf1 +
len - 1;
5960 if (isUNCRoot(buf1)) {
5963 else if (*end != L
'\\')
5964 lstrcatW(buf1, L
"\\");
5966 else if (*end == L
'\\' || (buf1 + 1 == end && *end == L
':'))
5967 lstrcatW(buf1, L
".");
5974rb_w32_ustati128(
const char *path,
struct stati128 *st)
5976 return w32_stati128(path, st, CP_UTF8, FALSE);
5981rb_w32_stati128(
const char *path,
struct stati128 *st)
5983 return w32_stati128(path, st, filecp(), FALSE);
5988w32_stati128(
const char *path,
struct stati128 *st, UINT cp, BOOL lstat)
5993 if (!(wpath = mbstr_to_wstr(cp, path, -1, NULL)))
5995 ret = wstati128(wpath, st, lstat);
6002rb_w32_ulstati128(
const char *path,
struct stati128 *st)
6004 return w32_stati128(path, st, CP_UTF8, TRUE);
6009rb_w32_lstati128(
const char *path,
struct stati128 *st)
6011 return w32_stati128(path, st, filecp(), TRUE);
6016rb_w32_lseek(
int fd, rb_off_t ofs,
int whence)
6018 SOCKET sock = TO_SOCKET(fd);
6019 if (is_socket(sock) || is_pipe(sock)) {
6023 return _lseeki64(fd, ofs, whence);
6028w32_access(
const char *path,
int mode, UINT cp)
6030 struct stati128 stat;
6031 if (w32_stati128(path, &stat, cp, FALSE) != 0)
6034 if ((stat.st_mode & mode) != mode) {
6043rb_w32_access(
const char *path,
int mode)
6045 return w32_access(path, mode, filecp());
6050rb_w32_uaccess(
const char *path,
int mode)
6052 return w32_access(path, mode, CP_UTF8);
6057rb_chsize(HANDLE h, rb_off_t size)
6059 long upos, lpos, usize, lsize;
6063 if ((lpos = SetFilePointer(h, 0, (upos = 0, &upos), SEEK_CUR)) == -1L &&
6064 (e = GetLastError())) {
6065 errno = map_errno(e);
6068 usize = (long)(size >> 32);
6070 if (SetFilePointer(h, lsize, &usize, SEEK_SET) == (DWORD)-1L &&
6071 (e = GetLastError())) {
6072 errno = map_errno(e);
6074 else if (!SetEndOfFile(h)) {
6075 errno = map_errno(GetLastError());
6080 SetFilePointer(h, lpos, &upos, SEEK_SET);
6086w32_truncate(
const char *path, rb_off_t length, UINT cp)
6092 if (!(wpath = mbstr_to_wstr(cp, path, -1, NULL)))
6094 h = CreateFileW(wpath, GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0);
6095 if (h == INVALID_HANDLE_VALUE) {
6096 errno = map_errno(GetLastError());
6101 ret = rb_chsize(h, length);
6108rb_w32_utruncate(
const char *path, rb_off_t length)
6110 return w32_truncate(path, length, CP_UTF8);
6115rb_w32_truncate(
const char *path, rb_off_t length)
6117 return w32_truncate(path, length, filecp());
6122rb_w32_ftruncate(
int fd, rb_off_t length)
6126 h = (HANDLE)_get_osfhandle(fd);
6127 if (h == (HANDLE)-1)
return -1;
6128 return rb_chsize(h, length);
6133filetime_to_clock(FILETIME *ft)
6135 __int64 qw = ft->dwHighDateTime;
6137 qw |= ft->dwLowDateTime;
6144rb_w32_times(
struct tms *tmbuf)
6146 FILETIME create, exit, kernel, user;
6148 if (GetProcessTimes(GetCurrentProcess(),&create, &exit, &kernel, &user)) {
6149 tmbuf->tms_utime = filetime_to_clock(&user);
6150 tmbuf->tms_stime = filetime_to_clock(&kernel);
6151 tmbuf->tms_cutime = 0;
6152 tmbuf->tms_cstime = 0;
6155 tmbuf->tms_utime = clock();
6156 tmbuf->tms_stime = 0;
6157 tmbuf->tms_cutime = 0;
6158 tmbuf->tms_cstime = 0;
6165#define yield_once() Sleep(0)
6166#define yield_until(condition) do yield_once(); while (!(condition))
6175 uintptr_t (*func)(uintptr_t self,
int argc, uintptr_t* argv);
6183call_asynchronous(PVOID argp)
6187 arg->stackaddr = &argp;
6188 ret = (DWORD)arg->func(arg->self, arg->argc, arg->argv);
6189 arg->errnum =
errno;
6195rb_w32_asynchronize(asynchronous_func_t func, uintptr_t self,
6196 int argc, uintptr_t* argv, uintptr_t intrval)
6199 BOOL interrupted = FALSE;
6205 arg.stackaddr = NULL;
6212 thr = CreateThread(NULL, 0, call_asynchronous, &arg, 0, &val);
6215 yield_until(arg.stackaddr);
6217 if (rb_w32_wait_events_blocking(&thr, 1, INFINITE) != WAIT_OBJECT_0) {
6220 if (TerminateThread(thr, intrval)) {
6225 GetExitCodeThread(thr, &val);
6230 MEMORY_BASIC_INFORMATION m;
6232 memset(&m, 0,
sizeof(m));
6233 if (!VirtualQuery(arg.stackaddr, &m,
sizeof(m))) {
6234 Debug(fprintf(stderr,
"couldn't get stack base:%p:%d\n",
6235 arg.stackaddr, GetLastError()));
6237 else if (!VirtualFree(m.AllocationBase, 0, MEM_RELEASE)) {
6238 Debug(fprintf(stderr,
"couldn't release stack:%p:%d\n",
6239 m.AllocationBase, GetLastError()));
6250 rb_fatal(
"failed to launch waiter thread:%ld", GetLastError());
6258rb_w32_get_environ(
void)
6260 WCHAR *envtop, *env;
6261 char **myenvtop, **myenv;
6274 envtop = GetEnvironmentStringsW();
6275 for (env = envtop, num = 0; *env; env += lstrlenW(env) + 1)
6276 if (*env !=
'=') num++;
6278 myenvtop = (
char **)malloc(
sizeof(
char *) * (num + 1));
6279 for (env = envtop, myenv = myenvtop; *env; env += lstrlenW(env) + 1) {
6281 if (!(*myenv = wstr_to_utf8(env, NULL))) {
6288 FreeEnvironmentStringsW(envtop);
6295rb_w32_free_environ(
char **env)
6299 while (*t) free(*t++);
6307 return GetCurrentProcessId();
6315 typedef long (WINAPI query_func)(HANDLE, int,
void *, ULONG, ULONG *);
6316 static query_func *pNtQueryInformationProcess = (query_func *)-1;
6319 if (pNtQueryInformationProcess == (query_func *)-1)
6320 pNtQueryInformationProcess = (query_func *)get_proc_address(
"ntdll.dll",
"NtQueryInformationProcess", NULL);
6321 if (pNtQueryInformationProcess) {
6324 void* PebBaseAddress;
6325 uintptr_t AffinityMask;
6326 uintptr_t BasePriority;
6327 uintptr_t UniqueProcessId;
6328 uintptr_t ParentProcessId;
6331 long ret = pNtQueryInformationProcess(GetCurrentProcess(), 0, &pbi,
sizeof(pbi), &
len);
6333 ppid = pbi.ParentProcessId;
6340STATIC_ASSERT(std_handle, (STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)==(STD_ERROR_HANDLE-STD_OUTPUT_HANDLE));
6343#define set_new_std_handle(newfd, handle) do { \
6344 if ((unsigned)(newfd) > 2) break; \
6345 SetStdHandle(STD_INPUT_HANDLE+(STD_OUTPUT_HANDLE-STD_INPUT_HANDLE)*(newfd), \
6348#define set_new_std_fd(newfd) set_new_std_handle(newfd, (HANDLE)rb_w32_get_osfhandle(newfd))
6352rb_w32_dup2(
int oldfd,
int newfd)
6356 if (oldfd == newfd)
return newfd;
6357 ret = dup2(oldfd, newfd);
6358 if (ret < 0)
return ret;
6359 set_new_std_fd(newfd);
6365rb_w32_uopen(
const char *file,
int oflag, ...)
6372 va_start(arg, oflag);
6373 pmode = va_arg(arg,
int);
6376 if (!(wfile = utf8_to_wstr(file, NULL)))
6378 ret = w32_wopen(wfile, oflag, pmode);
6385check_if_wdir(
const WCHAR *wfile)
6387 DWORD attr = GetFileAttributesW(wfile);
6388 if (attr == (DWORD)-1L ||
6389 !(attr & FILE_ATTRIBUTE_DIRECTORY) ||
6390 check_valid_dir(wfile)) {
6399rb_w32_open(
const char *file,
int oflag, ...)
6406 va_start(arg, oflag);
6407 pmode = va_arg(arg,
int);
6410 if (!(wfile = filecp_to_wstr(file, NULL)))
6412 ret = w32_wopen(wfile, oflag, pmode);
6419rb_w32_wopen(
const WCHAR *file,
int oflag, ...)
6423 if (oflag & O_CREAT) {
6425 va_start(arg, oflag);
6426 pmode = va_arg(arg,
int);
6430 return w32_wopen(file, oflag, pmode);
6434w32_wopen(
const WCHAR *file,
int oflag,
int pmode)
6440 DWORD attr = FILE_ATTRIBUTE_NORMAL;
6441 SECURITY_ATTRIBUTES sec;
6445 share_delete = oflag & O_SHARE_DELETE ? FILE_SHARE_DELETE : 0;
6446 oflag &= ~O_SHARE_DELETE;
6447 if ((oflag & O_TEXT) || !(oflag & O_BINARY)) {
6448 fd = _wopen(file, oflag, pmode);
6452 check_if_wdir(file);
6455 errno = map_errno(GetLastError());
6462 sec.nLength =
sizeof(sec);
6463 sec.lpSecurityDescriptor = NULL;
6464 if (oflag & O_NOINHERIT) {
6465 sec.bInheritHandle = FALSE;
6466 flags |= FNOINHERIT;
6469 sec.bInheritHandle = TRUE;
6471 oflag &= ~O_NOINHERIT;
6474 oflag &= ~(O_BINARY | O_TEXT);
6476 switch (oflag & (O_RDWR | O_RDONLY | O_WRONLY)) {
6478 access = GENERIC_READ | GENERIC_WRITE;
6481 access = GENERIC_READ;
6484 access = GENERIC_WRITE;
6490 oflag &= ~(O_RDWR | O_RDONLY | O_WRONLY);
6492 switch (oflag & (O_CREAT | O_EXCL | O_TRUNC)) {
6494 create = OPEN_ALWAYS;
6498 create = OPEN_EXISTING;
6500 case O_CREAT | O_EXCL:
6501 case O_CREAT | O_EXCL | O_TRUNC:
6502 create = CREATE_NEW;
6505 case O_TRUNC | O_EXCL:
6506 create = TRUNCATE_EXISTING;
6508 case O_CREAT | O_TRUNC:
6509 create = CREATE_ALWAYS;
6515 if (oflag & O_CREAT) {
6517 if (!(pmode & S_IWRITE))
6518 attr = FILE_ATTRIBUTE_READONLY;
6520 oflag &= ~(O_CREAT | O_EXCL | O_TRUNC);
6522 if (oflag & O_TEMPORARY) {
6523 attr |= FILE_FLAG_DELETE_ON_CLOSE;
6526 oflag &= ~O_TEMPORARY;
6528 if (oflag & _O_SHORT_LIVED)
6529 attr |= FILE_ATTRIBUTE_TEMPORARY;
6530 oflag &= ~_O_SHORT_LIVED;
6532 switch (oflag & (O_SEQUENTIAL | O_RANDOM)) {
6536 attr |= FILE_FLAG_SEQUENTIAL_SCAN;
6539 attr |= FILE_FLAG_RANDOM_ACCESS;
6545 oflag &= ~(O_SEQUENTIAL | O_RANDOM);
6547 if (oflag & ~O_APPEND) {
6554 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6555 fd = _open_osfhandle((intptr_t)h, 0);
6563 rb_acrt_lowio_lock_fh(fd);
6564 _set_osfhnd(fd, (intptr_t)INVALID_HANDLE_VALUE);
6565 _set_osflags(fd, 0);
6567 h = CreateFileW(file, access, FILE_SHARE_READ | FILE_SHARE_WRITE | share_delete, &sec, create, attr, NULL);
6568 if (h == INVALID_HANDLE_VALUE) {
6569 DWORD e = GetLastError();
6570 if (e != ERROR_ACCESS_DENIED || !check_if_wdir(file))
6571 errno = map_errno(e);
6572 rb_acrt_lowio_unlock_fh(fd);
6577 switch (GetFileType(h)) {
6578 case FILE_TYPE_CHAR:
6581 case FILE_TYPE_PIPE:
6584 case FILE_TYPE_UNKNOWN:
6585 errno = map_errno(GetLastError());
6587 rb_acrt_lowio_unlock_fh(fd);
6591 if (!(flags & (FDEV | FPIPE)) && (oflag & O_APPEND))
6594 _set_osfhnd(fd, (intptr_t)h);
6595 _set_osflags(fd, flags | FOPEN);
6597 rb_acrt_lowio_unlock_fh(fd);
6607rb_w32_fclose(FILE *fp)
6609 int fd = fileno(fp);
6610 SOCKET sock = TO_SOCKET(fd);
6611 int save_errno =
errno;
6613 if (fflush(fp))
return -1;
6614 if (!is_socket(sock)) {
6615 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
6618 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
6621 if (closesocket(sock) == SOCKET_ERROR) {
6622 errno = map_errno(WSAGetLastError());
6630rb_w32_pipe(
int fds[2])
6632 static long serial = 0;
6633 static const char prefix[] =
"\\\\.\\pipe\\ruby";
6635 width_of_prefix = (int)
sizeof(prefix) - 1,
6636 width_of_pid = (int)
sizeof(rb_pid_t) * 2,
6637 width_of_serial = (int)
sizeof(serial) * 2,
6638 width_of_ids = width_of_pid + 1 + width_of_serial + 1
6640 char name[
sizeof(prefix) + width_of_ids];
6641 SECURITY_ATTRIBUTES sec;
6642 HANDLE hRead, hWrite, h;
6643 int fdRead, fdWrite;
6646 memcpy(name, prefix, width_of_prefix);
6647 snprintf(name + width_of_prefix, width_of_ids,
"%.*"PRI_PIDT_PREFIX"x-%.*lx",
6648 width_of_pid, rb_w32_getpid(), width_of_serial, InterlockedIncrement(&serial)-1);
6650 sec.nLength =
sizeof(sec);
6651 sec.lpSecurityDescriptor = NULL;
6652 sec.bInheritHandle = FALSE;
6655 hRead = CreateNamedPipe(name, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
6656 0, 2, 65536, 65536, 0, &sec);
6658 if (hRead == INVALID_HANDLE_VALUE) {
6659 DWORD err = GetLastError();
6660 if (err == ERROR_PIPE_BUSY)
6663 errno = map_errno(GetLastError());
6668 hWrite = CreateFile(name, GENERIC_READ | GENERIC_WRITE, 0, &sec,
6669 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
6671 if (hWrite == INVALID_HANDLE_VALUE) {
6672 errno = map_errno(GetLastError());
6679 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6680 fdRead = _open_osfhandle((intptr_t)h, 0);
6684 CloseHandle(hWrite);
6690 rb_acrt_lowio_lock_fh(fdRead);
6691 _set_osfhnd(fdRead, (intptr_t)hRead);
6692 _set_osflags(fdRead, FOPEN | FPIPE | FNOINHERIT);
6693 rb_acrt_lowio_unlock_fh(fdRead);
6699 h = CreateFile(
"NUL", 0, 0, NULL, OPEN_ALWAYS, 0, NULL);
6700 fdWrite = _open_osfhandle((intptr_t)h, 0);
6702 if (fdWrite == -1) {
6704 CloseHandle(hWrite);
6708 rb_acrt_lowio_lock_fh(fdWrite);
6709 _set_osfhnd(fdWrite, (intptr_t)hWrite);
6710 _set_osflags(fdWrite, FOPEN | FPIPE | FNOINHERIT);
6711 rb_acrt_lowio_unlock_fh(fdWrite);
6714 rb_w32_close(fdRead);
6726console_emulator_p(
void)
6731 const void *
const func = WriteConsoleW;
6733 MEMORY_BASIC_INFORMATION m;
6735 memset(&m, 0,
sizeof(m));
6736 if (!VirtualQuery(func, &m,
sizeof(m))) {
6739 k = GetModuleHandle(
"kernel32.dll");
6740 if (!k)
return FALSE;
6741 return (HMODULE)m.AllocationBase != k;
6747constat_handle(HANDLE h)
6751 thread_exclusive(conlist) {
6753 if (console_emulator_p()) {
6754 conlist = conlist_disabled;
6757 conlist = st_init_numtable();
6758 install_vm_exit_handler();
6760 else if (conlist == conlist_disabled) {
6763 if (st_lookup(conlist, (st_data_t)h, &data)) {
6767 CONSOLE_SCREEN_BUFFER_INFO csbi;
6769 p->vt100.state = constat_init;
6770 p->vt100.attr = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
6771 p->vt100.reverse = 0;
6772 p->vt100.saved.X = p->vt100.saved.Y = 0;
6773 if (GetConsoleScreenBufferInfo(h, &csbi)) {
6774 p->vt100.attr = csbi.wAttributes;
6776 st_insert(conlist, (st_data_t)h, (st_data_t)p);
6782#define FOREGROUND_MASK (FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY)
6783#define BACKGROUND_MASK (BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY)
6785#define constat_attr_color_reverse(attr) \
6786 ((attr) & ~(FOREGROUND_MASK | BACKGROUND_MASK)) | \
6787 (((attr) & FOREGROUND_MASK) << 4) | \
6788 (((attr) & BACKGROUND_MASK) >> 4)
6792constat_attr(
int count,
const int *seq, WORD attr, WORD default_attr,
int *reverse)
6797 if (!count)
return attr;
6798 if (rev) attr = constat_attr_color_reverse(attr);
6799 bold = attr & FOREGROUND_INTENSITY;
6800 attr &= ~(FOREGROUND_INTENSITY | BACKGROUND_INTENSITY);
6802 while (count-- > 0) {
6805 attr = default_attr;
6810 bold = FOREGROUND_INTENSITY;
6816#ifndef COMMON_LVB_UNDERSCORE
6817#define COMMON_LVB_UNDERSCORE 0x8000
6819 attr |= COMMON_LVB_UNDERSCORE;
6822 attr &= ~COMMON_LVB_UNDERSCORE;
6832 attr &= ~(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
6835 attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_GREEN)) | FOREGROUND_RED;
6838 attr = (attr & ~(FOREGROUND_BLUE | FOREGROUND_RED)) | FOREGROUND_GREEN;
6841 attr = (attr & ~FOREGROUND_BLUE) | FOREGROUND_GREEN | FOREGROUND_RED;
6844 attr = (attr & ~(FOREGROUND_GREEN | FOREGROUND_RED)) | FOREGROUND_BLUE;
6847 attr = (attr & ~FOREGROUND_GREEN) | FOREGROUND_BLUE | FOREGROUND_RED;
6850 attr = (attr & ~FOREGROUND_RED) | FOREGROUND_BLUE | FOREGROUND_GREEN;
6853 attr |= FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
6858 attr = (attr & ~FOREGROUND_MASK) | (default_attr & FOREGROUND_MASK);
6862 attr &= ~(BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED);
6865 attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_GREEN)) | BACKGROUND_RED;
6868 attr = (attr & ~(BACKGROUND_BLUE | BACKGROUND_RED)) | BACKGROUND_GREEN;
6871 attr = (attr & ~BACKGROUND_BLUE) | BACKGROUND_GREEN | BACKGROUND_RED;
6874 attr = (attr & ~(BACKGROUND_GREEN | BACKGROUND_RED)) | BACKGROUND_BLUE;
6877 attr = (attr & ~BACKGROUND_GREEN) | BACKGROUND_BLUE | BACKGROUND_RED;
6880 attr = (attr & ~BACKGROUND_RED) | BACKGROUND_BLUE | BACKGROUND_GREEN;
6883 attr |= BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED;
6888 attr = (attr & ~BACKGROUND_MASK) | (default_attr & BACKGROUND_MASK);
6893 if (rev) attr = constat_attr_color_reverse(attr);
6900constat_clear(HANDLE handle, WORD attr, DWORD
len, COORD pos)
6904 FillConsoleOutputAttribute(handle, attr,
len, pos, &written);
6905 FillConsoleOutputCharacterW(handle, L
' ',
len, pos, &written);
6910constat_apply(HANDLE handle,
struct constat *s, WCHAR w)
6912 CONSOLE_SCREEN_BUFFER_INFO csbi;
6913 const int *seq = s->vt100.seq;
6914 int count = s->vt100.state;
6918 if (!GetConsoleScreenBufferInfo(handle, &csbi))
return;
6919 arg0 = (count > 0 && seq[0] > 0);
6920 if (arg0) arg1 = seq[0];
6923 SetConsoleTextAttribute(handle, constat_attr(count, seq, csbi.wAttributes, s->vt100.attr, &s->vt100.reverse));
6926 csbi.dwCursorPosition.X = 0;
6928 csbi.dwCursorPosition.Y -= arg1;
6929 if (csbi.dwCursorPosition.Y < csbi.srWindow.Top)
6930 csbi.dwCursorPosition.Y = csbi.srWindow.Top;
6931 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6934 csbi.dwCursorPosition.X = 0;
6937 csbi.dwCursorPosition.Y += arg1;
6938 if (csbi.dwCursorPosition.Y > csbi.srWindow.Bottom)
6939 csbi.dwCursorPosition.Y = csbi.srWindow.Bottom;
6940 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6943 csbi.dwCursorPosition.X += arg1;
6944 if (csbi.dwCursorPosition.X >= csbi.srWindow.Right)
6945 csbi.dwCursorPosition.X = csbi.srWindow.Right;
6946 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6949 csbi.dwCursorPosition.X -= arg1;
6950 if (csbi.dwCursorPosition.X < csbi.srWindow.Left)
6951 csbi.dwCursorPosition.X = csbi.srWindow.Left;
6952 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6956 arg1 += csbi.srWindow.Left;
6957 if (arg1 > csbi.srWindow.Right)
6958 arg1 = csbi.srWindow.Right;
6959 csbi.dwCursorPosition.X = arg1;
6960 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6963 arg1 += csbi.srWindow.Top;
6964 if (arg1 > csbi.srWindow.Bottom)
6965 arg1 = csbi.srWindow.Bottom;
6966 csbi.dwCursorPosition.Y = arg1;
6967 SetConsoleCursorPosition(handle, csbi.dwCursorPosition);
6971 pos.Y = arg1 + csbi.srWindow.Top - 1;
6972 if (pos.Y > csbi.srWindow.Bottom) pos.Y = csbi.srWindow.Bottom;
6973 if (count < 2 || (arg1 = seq[1]) <= 0) arg1 = 1;
6974 pos.X = arg1 + csbi.srWindow.Left - 1;
6975 if (pos.X > csbi.srWindow.Right) pos.X = csbi.srWindow.Right;
6976 SetConsoleCursorPosition(handle, pos);
6979 switch (arg0 ? arg1 : 0) {
6981 constat_clear(handle, csbi.wAttributes,
6982 (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.dwCursorPosition.Y + 1)
6983 - csbi.dwCursorPosition.X),
6984 csbi.dwCursorPosition);
6988 pos.Y = csbi.srWindow.Top;
6989 constat_clear(handle, csbi.wAttributes,
6990 (csbi.dwSize.X * (csbi.dwCursorPosition.Y - csbi.srWindow.Top)
6991 + csbi.dwCursorPosition.X + 1),
6996 pos.Y = csbi.srWindow.Top;
6997 constat_clear(handle, csbi.wAttributes,
6998 (csbi.dwSize.X * (csbi.srWindow.Bottom - csbi.srWindow.Top + 1)),
7004 constat_clear(handle, csbi.wAttributes,
7005 (csbi.dwSize.X * csbi.dwSize.Y),
7011 switch (arg0 ? arg1 : 0) {
7013 constat_clear(handle, csbi.wAttributes,
7014 (csbi.dwSize.X - csbi.dwCursorPosition.X),
7015 csbi.dwCursorPosition);
7019 pos.Y = csbi.dwCursorPosition.Y;
7020 constat_clear(handle, csbi.wAttributes,
7021 csbi.dwCursorPosition.X + 1, pos);
7025 pos.Y = csbi.dwCursorPosition.Y;
7026 constat_clear(handle, csbi.wAttributes,
7027 csbi.dwSize.X, pos);
7032 s->vt100.saved = csbi.dwCursorPosition;
7035 SetConsoleCursorPosition(handle, s->vt100.saved);
7038 if (count >= 2 && seq[0] == -1 && seq[1] == 25) {
7039 CONSOLE_CURSOR_INFO cci;
7040 GetConsoleCursorInfo(handle, &cci);
7041 cci.bVisible = TRUE;
7042 SetConsoleCursorInfo(handle, &cci);
7046 if (count >= 2 && seq[0] == -1 && seq[1] == 25) {
7047 CONSOLE_CURSOR_INFO cci;
7048 GetConsoleCursorInfo(handle, &cci);
7049 cci.bVisible = FALSE;
7050 SetConsoleCursorInfo(handle, &cci);
7058static const long MAXSIZE_CONSOLE_WRITING = 31366;
7062constat_parse(HANDLE h,
struct constat *s,
const WCHAR **ptrp,
long *lenp)
7064 const WCHAR *
ptr = *ptrp;
7065 long rest,
len = *lenp;
7069 rest = *lenp -
len - 1;
7070 if (s->vt100.state == constat_esc) {
7073 s->vt100.state = constat_init;
7074 if (
len > 0 && *
ptr != L
'[')
continue;
7075 s->vt100.state = constat_esc;
7077 else if (s->vt100.state == constat_esc) {
7080 s->vt100.state = constat_init;
7083 rest = *lenp -
len - 1;
7084 if (rest > 0) --rest;
7085 s->vt100.state = constat_seq;
7086 s->vt100.seq[0] = 0;
7088 else if (s->vt100.state >= constat_seq) {
7089 if (wc >= L
'0' && wc <= L
'9') {
7090 if (s->vt100.state < (
int)numberof(s->vt100.seq)) {
7091 int *seq = &s->vt100.seq[s->vt100.state];
7092 *seq = (*seq * 10) + (wc - L
'0');
7095 else if (s->vt100.state == constat_seq && s->vt100.seq[0] == 0 && wc == L
'?') {
7096 s->vt100.seq[s->vt100.state++] = -1;
7100 if (++s->vt100.state < (
int)numberof(s->vt100.seq)) {
7101 s->vt100.seq[s->vt100.state] = 0;
7104 s->vt100.state = (int)numberof(s->vt100.seq);
7108 constat_apply(h, s, wc);
7109 s->vt100.state = constat_init;
7114 else if ((rest = *lenp -
len) < MAXSIZE_CONSOLE_WRITING) {
7132 SOCKET sock = TO_SOCKET(fd);
7133 int save_errno =
errno;
7135 if (!is_socket(sock)) {
7136 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
7137 constat_delete((HANDLE)sock);
7140 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
7141 socklist_delete(&sock, NULL);
7144 if (closesocket(sock) == SOCKET_ERROR) {
7145 errno = map_errno(WSAGetLastError());
7151#ifndef INVALID_SET_FILE_POINTER
7152#define INVALID_SET_FILE_POINTER ((DWORD)-1)
7156setup_overlapped(OVERLAPPED *ol,
int fd,
int iswrite, rb_off_t *_offset)
7158 memset(ol, 0,
sizeof(*ol));
7163 DWORD seek_method = ((_osfile(fd) & FAPPEND) && iswrite) ? FILE_END : FILE_CURRENT;
7167 uint64_t offset = *_offset;
7168 ol->Offset = (uint32_t)(offset & 0xFFFFFFFFLL);
7169 ol->OffsetHigh = (uint32_t)((offset & 0xFFFFFFFF00000000LL) >> 32);
7172 LARGE_INTEGER seek_offset = {0}, current_offset = {0};
7173 if (!SetFilePointerEx((HANDLE)_osfhnd(fd), seek_offset, ¤t_offset, seek_method)) {
7174 DWORD last_error = GetLastError();
7175 if (last_error != NO_ERROR) {
7176 errno = map_errno(last_error);
7182 *_offset = current_offset.QuadPart;
7184 else if (!(_osfile(fd) & (FDEV | FPIPE))) {
7186 DWORD low = SetFilePointer((HANDLE)_osfhnd(fd), 0, &high, seek_method);
7188 if (low == INVALID_SET_FILE_POINTER) {
7189 DWORD err = GetLastError();
7190 if (err != NO_ERROR) {
7191 errno = map_errno(err);
7197 ol->OffsetHigh = high;
7200 ol->hEvent = CreateEvent(NULL, TRUE, TRUE, NULL);
7202 errno = map_errno(GetLastError());
7209finish_overlapped(OVERLAPPED *ol,
int fd, DWORD size, rb_off_t *_offset)
7211 CloseHandle(ol->hEvent);
7215 DWORD seek_method = (_osfile(fd) & FAPPEND) ? FILE_END : FILE_BEGIN;
7217 LARGE_INTEGER seek_offset = {0};
7218 if (seek_method == FILE_BEGIN) {
7219 seek_offset.QuadPart = *_offset;
7222 SetFilePointerEx((HANDLE)_osfhnd(fd), seek_offset, NULL, seek_method);
7224 else if (!(_osfile(fd) & (FDEV | FPIPE))) {
7225 LONG high = ol->OffsetHigh;
7226 DWORD low = ol->Offset + size;
7227 if (low < ol->Offset)
7229 SetFilePointer((HANDLE)_osfhnd(fd), low, &high, FILE_BEGIN);
7236rb_w32_read_internal(
int fd,
void *buf,
size_t size, rb_off_t *offset)
7238 SOCKET sock = TO_SOCKET(fd);
7246 if (is_socket(sock))
7247 return rb_w32_recv(fd, buf, size, 0);
7250 if (_get_osfhandle(fd) == -1) {
7254 if (!offset && _osfile(fd) & FTEXT) {
7255 return _read(fd, buf, size);
7258 rb_acrt_lowio_lock_fh(fd);
7260 if (!size || _osfile(fd) & FEOFLAG) {
7261 _set_osflags(fd, _osfile(fd) & ~FEOFLAG);
7262 rb_acrt_lowio_unlock_fh(fd);
7271 if (setup_overlapped(&ol, fd, FALSE, offset)) {
7272 rb_acrt_lowio_unlock_fh(fd);
7276 if (!ReadFile((HANDLE)_osfhnd(fd), buf,
len, &read, &ol)) {
7277 err = GetLastError();
7278 if (err == ERROR_NO_DATA && (_osfile(fd) & FPIPE)) {
7280 if (GetNamedPipeHandleState((HANDLE)_osfhnd(fd), &state, NULL, NULL, NULL, NULL, 0) && (state & PIPE_NOWAIT)) {
7281 errno = EWOULDBLOCK;
7284 errno = map_errno(err);
7286 rb_acrt_lowio_unlock_fh(fd);
7289 else if (err != ERROR_IO_PENDING) {
7290 CloseHandle(ol.hEvent);
7291 if (err == ERROR_ACCESS_DENIED)
7293 else if (err == ERROR_BROKEN_PIPE || err == ERROR_HANDLE_EOF) {
7294 rb_acrt_lowio_unlock_fh(fd);
7298 errno = map_errno(err);
7300 rb_acrt_lowio_unlock_fh(fd);
7304 wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE);
7305 if (wait != WAIT_OBJECT_0) {
7306 if (wait == WAIT_OBJECT_0 + 1)
7309 errno = map_errno(GetLastError());
7310 CancelIo((HANDLE)_osfhnd(fd));
7313 GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &read, TRUE);
7315 CloseHandle(ol.hEvent);
7316 rb_acrt_lowio_unlock_fh(fd);
7320 else if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &read, TRUE) &&
7321 (err = GetLastError()) != ERROR_HANDLE_EOF) {
7323 if (err != ERROR_BROKEN_PIPE) {
7324 errno = map_errno(err);
7327 CloseHandle(ol.hEvent);
7328 CancelIo((HANDLE)_osfhnd(fd));
7329 rb_acrt_lowio_unlock_fh(fd);
7334 err = GetLastError();
7335 errno = map_errno(err);
7338 finish_overlapped(&ol, fd, read, offset);
7342 buf = (
char *)buf + read;
7343 if (err != ERROR_OPERATION_ABORTED && size > 0)
7347 _set_osflags(fd, _osfile(fd) | FEOFLAG);
7350 rb_acrt_lowio_unlock_fh(fd);
7358rb_w32_write_internal(
int fd,
const void *buf,
size_t size, rb_off_t *offset)
7360 SOCKET sock = TO_SOCKET(fd);
7368 if (is_socket(sock))
7369 return rb_w32_send(fd, buf, size, 0);
7372 if (_get_osfhandle(fd) == -1) {
7377 if (!offset && (_osfile(fd) & FTEXT) &&
7378 (!(_osfile(fd) & FPIPE) || fd == fileno(stdout) || fd == fileno(stderr))) {
7379 ssize_t w = _write(fd, buf, size);
7380 if (w == (ssize_t)-1 &&
errno == EINVAL) {
7381 errno = map_errno(GetLastError());
7386 rb_acrt_lowio_lock_fh(fd);
7388 if (!size || _osfile(fd) & FEOFLAG) {
7389 rb_acrt_lowio_unlock_fh(fd);
7395 len = (_osfile(fd) & FDEV) ? min(MAXSIZE_CONSOLE_WRITING, size) : size;
7400 if (setup_overlapped(&ol, fd, TRUE, offset)) {
7401 rb_acrt_lowio_unlock_fh(fd);
7405 if (!WriteFile((HANDLE)_osfhnd(fd), buf,
len, &written, &ol)) {
7406 err = GetLastError();
7407 if (err != ERROR_IO_PENDING) {
7408 CloseHandle(ol.hEvent);
7409 if (err == ERROR_ACCESS_DENIED)
7412 errno = map_errno(err);
7414 rb_acrt_lowio_unlock_fh(fd);
7418 wait = rb_w32_wait_events_blocking(&ol.hEvent, 1, INFINITE);
7419 if (wait != WAIT_OBJECT_0) {
7420 if (wait == WAIT_OBJECT_0 + 1)
7423 errno = map_errno(GetLastError());
7424 CancelIo((HANDLE)_osfhnd(fd));
7425 GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &written, TRUE);
7427 CloseHandle(ol.hEvent);
7428 rb_acrt_lowio_unlock_fh(fd);
7432 else if (!GetOverlappedResult((HANDLE)_osfhnd(fd), &ol, &written, TRUE)) {
7433 errno = map_errno(GetLastError());
7434 CloseHandle(ol.hEvent);
7435 CancelIo((HANDLE)_osfhnd(fd));
7436 rb_acrt_lowio_unlock_fh(fd);
7441 finish_overlapped(&ol, fd, written, offset);
7444 if (written ==
len) {
7445 buf = (
const char *)buf +
len;
7450 size_t newlen =
len / 2;
7452 size +=
len - newlen;
7457 errno = EWOULDBLOCK;
7460 rb_acrt_lowio_unlock_fh(fd);
7466rb_w32_read(
int fd,
void *buf,
size_t size)
7468 return rb_w32_read_internal(fd, buf, size, NULL);
7472rb_w32_write(
int fd,
const void *buf,
size_t size)
7474 return rb_w32_write_internal(fd, buf, size, NULL);
7478rb_w32_pread(
int descriptor,
void *base,
size_t size, rb_off_t offset)
7480 return rb_w32_read_internal(descriptor, base, size, &offset);
7484rb_w32_pwrite(
int descriptor,
const void *base,
size_t size, rb_off_t offset)
7486 return rb_w32_write_internal(descriptor, base, size, &offset);
7491rb_w32_write_console(uintptr_t strarg,
int fd)
7494 DWORD dwMode, reslen;
7498 const WCHAR *
ptr, *next;
7502 handle = (HANDLE)_osfhnd(fd);
7503 if (!GetConsoleMode(handle, &dwMode))
7506 s = constat_handle(handle);
7516 case ENCINDEX_US_ASCII:
7517 case ENCINDEX_ASCII_8BIT:
7519 case ENCINDEX_UTF_8:
7520 ptr = wbuffer = mbstr_to_wstr(CP_UTF8, RSTRING_PTR(str), RSTRING_LEN(str), &
len);
7521 if (!
ptr)
return -1L;
7523 case ENCINDEX_UTF_16LE:
7524 ptr = (
const WCHAR *)RSTRING_PTR(str);
7525 len = RSTRING_LEN(str) /
sizeof(WCHAR);
7529 if (dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING) {
7530 if (!WriteConsoleW(handle,
ptr,
len, &reslen, NULL))
7531 reslen = (DWORD)-1L;
7535 long curlen = constat_parse(handle, s, (next =
ptr, &next), &
len);
7536 reslen += next -
ptr;
7539 if (!WriteConsoleW(handle,
ptr, curlen, &written, NULL)) {
7540 reslen = (DWORD)-1L;
7549 return (
long)reslen;
7554timespec_to_filetime(
const struct timespec *ts, FILETIME *ft)
7558 tmp.QuadPart = unix_to_filetime((ULONGLONG)ts->tv_sec);
7559 tmp.QuadPart += ts->tv_nsec / 100;
7560 ft->dwLowDateTime = tmp.LowPart;
7561 ft->dwHighDateTime = tmp.HighPart;
7567wutimensat(
int dirfd,
const WCHAR *path,
const struct timespec *times,
int flags)
7570 FILETIME atime, mtime;
7571 struct stati128 stat;
7575 if (dirfd != AT_FDCWD) {
7585 if (wstati128(path, &stat, FALSE)) {
7590 if (timespec_to_filetime(×[0], &atime)) {
7593 if (timespec_to_filetime(×[1], &mtime)) {
7598 GetSystemTimePreciseAsFileTime(&atime);
7603 const DWORD attr = GetFileAttributesW(path);
7604 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY))
7605 SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY);
7606 hFile = open_special(path, GENERIC_WRITE, 0);
7607 if (hFile == INVALID_HANDLE_VALUE) {
7608 errno = map_errno(GetLastError());
7612 if (!SetFileTime(hFile, NULL, &atime, &mtime)) {
7613 errno = map_errno(GetLastError());
7618 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY))
7619 SetFileAttributesW(path, attr);
7627w32_utimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags, UINT cp)
7629 WCHAR *wpath = mbstr_to_wstr(cp, path, -1, NULL);
7633 ret = wutimensat(dirfd, wpath, times, flags);
7641rb_w32_uutime(
const char *path,
const struct utimbuf *times)
7645 ts[0].tv_sec = times->actime;
7647 ts[1].tv_sec = times->modtime;
7649 return w32_utimensat(AT_FDCWD, path, ts, 0, CP_UTF8);
7654rb_w32_utime(
const char *path,
const struct utimbuf *times)
7658 ts[0].tv_sec = times->actime;
7660 ts[1].tv_sec = times->modtime;
7662 return w32_utimensat(AT_FDCWD, path, ts, 0, filecp());
7667rb_w32_uutimes(
const char *path,
const struct timeval *times)
7671 ts[0].tv_sec = times[0].tv_sec;
7672 ts[0].tv_nsec = times[0].tv_usec * 1000;
7673 ts[1].tv_sec = times[1].tv_sec;
7674 ts[1].tv_nsec = times[1].tv_usec * 1000;
7675 return w32_utimensat(AT_FDCWD, path, ts, 0, CP_UTF8);
7680rb_w32_utimes(
const char *path,
const struct timeval *times)
7684 ts[0].tv_sec = times[0].tv_sec;
7685 ts[0].tv_nsec = times[0].tv_usec * 1000;
7686 ts[1].tv_sec = times[1].tv_sec;
7687 ts[1].tv_nsec = times[1].tv_usec * 1000;
7688 return w32_utimensat(AT_FDCWD, path, ts, 0, filecp());
7693rb_w32_uutimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags)
7695 return w32_utimensat(dirfd, path, times, flags, CP_UTF8);
7700rb_w32_utimensat(
int dirfd,
const char *path,
const struct timespec *times,
int flags)
7702 return w32_utimensat(dirfd, path, times, flags, filecp());
7707rb_w32_uchdir(
const char *path)
7712 if (!(wpath = utf8_to_wstr(path, NULL)))
7714 ret = _wchdir(wpath);
7721wmkdir(
const WCHAR *wpath,
int mode)
7726 if (CreateDirectoryW(wpath, NULL) == FALSE) {
7727 errno = map_errno(GetLastError());
7730 if (_wchmod(wpath, mode) == -1) {
7731 RemoveDirectoryW(wpath);
7741rb_w32_umkdir(
const char *path,
int mode)
7746 if (!(wpath = utf8_to_wstr(path, NULL)))
7748 ret = wmkdir(wpath, mode);
7755rb_w32_mkdir(
const char *path,
int mode)
7760 if (!(wpath = filecp_to_wstr(path, NULL)))
7762 ret = wmkdir(wpath, mode);
7769wrmdir(
const WCHAR *wpath)
7773 const DWORD attr = GetFileAttributesW(wpath);
7774 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7775 SetFileAttributesW(wpath, attr & ~FILE_ATTRIBUTE_READONLY);
7777 if (RemoveDirectoryW(wpath) == FALSE) {
7778 errno = map_errno(GetLastError());
7780 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7781 SetFileAttributesW(wpath, attr);
7790rb_w32_rmdir(
const char *path)
7795 if (!(wpath = filecp_to_wstr(path, NULL)))
7797 ret = wrmdir(wpath);
7804rb_w32_urmdir(
const char *path)
7809 if (!(wpath = utf8_to_wstr(path, NULL)))
7811 ret = wrmdir(wpath);
7818wunlink(
const WCHAR *path)
7821 const DWORD SYMLINKD = FILE_ATTRIBUTE_REPARSE_POINT|FILE_ATTRIBUTE_DIRECTORY;
7823 const DWORD attr = GetFileAttributesW(path);
7824 if (attr == (DWORD)-1) {
7826 else if ((attr & SYMLINKD) == SYMLINKD) {
7827 ret = RemoveDirectoryW(path);
7830 if (attr & FILE_ATTRIBUTE_READONLY) {
7831 SetFileAttributesW(path, attr & ~FILE_ATTRIBUTE_READONLY);
7833 ret = DeleteFileW(path);
7836 errno = map_errno(GetLastError());
7838 if (attr != (DWORD)-1 && (attr & FILE_ATTRIBUTE_READONLY)) {
7839 SetFileAttributesW(path, attr);
7848rb_w32_uunlink(
const char *path)
7853 if (!(wpath = utf8_to_wstr(path, NULL)))
7855 ret = wunlink(wpath);
7862rb_w32_unlink(
const char *path)
7867 if (!(wpath = filecp_to_wstr(path, NULL)))
7869 ret = wunlink(wpath);
7876rb_w32_uchmod(
const char *path,
int mode)
7881 if (!(wpath = utf8_to_wstr(path, NULL)))
7883 ret = _wchmod(wpath, mode);
7890fchmod(
int fd,
int mode)
7894 LARGE_INTEGER CreationTime;
7895 LARGE_INTEGER LastAccessTime;
7896 LARGE_INTEGER LastWriteTime;
7897 LARGE_INTEGER ChangeTime;
7898 DWORD FileAttributes;
7899 } info = {{{0}}, {{0}}, {{0}},};
7900 HANDLE h = (HANDLE)_get_osfhandle(fd);
7902 info.FileAttributes = FILE_ATTRIBUTE_NORMAL;
7903 if (!(mode & 0200)) info.FileAttributes |= FILE_ATTRIBUTE_READONLY;
7904 if (!SetFileInformationByHandle(h, 0, &info,
sizeof(info))) {
7905 errno = map_errno(GetLastError());
7913rb_w32_isatty(
int fd)
7918 if (_get_osfhandle(fd) == -1) {
7921 if (!GetConsoleMode((HANDLE)_osfhnd(fd), &mode)) {
7933 int *ip = (
int *)(&x + 1) - 1;
7940rb_w32_inet_ntop(
int af,
const void *addr,
char *numaddr,
size_t numaddr_len)
7942 return (inet_ntop)(af, (
void *)addr, numaddr, numaddr_len);
7947rb_w32_inet_pton(
int af,
const char *src,
void *dst)
7949 return (inet_pton)(af, src, dst);
7954rb_w32_fd_is_text(
int fd)
7956 return _osfile(fd) & FTEXT;
7959#ifdef HAVE__GMTIME64_S
7960# ifndef HAVE__LOCALTIME64_S
7962# define HAVE__LOCALTIME64_S 1
7964# ifndef MINGW_HAS_SECURE_API
7965 _CRTIMP errno_t __cdecl _gmtime64_s(
struct tm* tm,
const __time64_t *time);
7966 _CRTIMP errno_t __cdecl _localtime64_s(
struct tm* tm,
const __time64_t *time);
7968# define gmtime_s _gmtime64_s
7969# define localtime_s _localtime64_s
7974gmtime_r(
const time_t *tp,
struct tm *rp)
7982 e = gmtime_s(rp, tp);
7983 if (e != 0)
goto error;
7989localtime_r(
const time_t *tp,
struct tm *rp)
7997 e = localtime_s(rp, tp);
8004rb_w32_wrap_io_handle(HANDLE h,
int flags)
8007 int len =
sizeof(tmp);
8008 int r = getsockopt((SOCKET)h, SOL_SOCKET, SO_DEBUG, (
char *)&tmp, &
len);
8009 if (r != SOCKET_ERROR || WSAGetLastError() != WSAENOTSOCK) {
8011 if (flags & O_NONBLOCK) {
8012 flags &= ~O_NONBLOCK;
8015 socklist_insert((SOCKET)h, f);
8017 else if (flags & O_NONBLOCK) {
8021 return rb_w32_open_osfhandle((intptr_t)h, flags);
8026rb_w32_unwrap_io_handle(
int fd)
8028 SOCKET sock = TO_SOCKET(fd);
8029 _set_osfhnd(fd, (SOCKET)INVALID_HANDLE_VALUE);
8030 if (!is_socket(sock)) {
8031 UnlockFile((HANDLE)sock, 0, 0, LK_LEN, LK_LEN);
8032 constat_delete((HANDLE)sock);
8035 socklist_delete(&sock, NULL);
8040#if !defined(__MINGW64__) && defined(__MINGW64_VERSION_MAJOR)
8046rb_w32_pow(
double x,
double y)
8050 unsigned int default_control = _controlfp(0, 0);
8051 _controlfp(_PC_64, _MCW_PC);
8054 _controlfp(default_control, _MCW_PC);
8062 BY_HANDLE_FILE_INFORMATION bhfi;
8073 tmp = rb_check_convert_type_with_id(*file,
T_FILE,
"IO", idTo_io);
8076 if (f == (HANDLE)-1)
return INVALID_HANDLE_VALUE;
8085 tmp = rb_str_encode_ospath(*file);
8086 len = MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1, NULL, 0);
8088 MultiByteToWideChar(CP_UTF8, 0, RSTRING_PTR(tmp), -1,
ptr,
len);
8089 f = CreateFileW(
ptr, 0,
8090 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
8091 FILE_FLAG_BACKUP_SEMANTICS, NULL);
8093 if (f == INVALID_HANDLE_VALUE)
return f;
8096 if (GetFileType(f) == FILE_TYPE_DISK) {
8097 ZeroMemory(st,
sizeof(*st));
8098 if (get_ino(f, &st->info.fii)) {
8099 st->file_id_p = TRUE;
8102 else if (GetLastError() != ERROR_INVALID_PARAMETER) {
8104 return INVALID_HANDLE_VALUE;
8108 if (GetFileInformationByHandle(f, &st->info.bhfi)) {
8109 st->file_id_p = FALSE;
8113 if (ret) CloseHandle(ret);
8114 return INVALID_HANDLE_VALUE;
8118close_handle(
VALUE h)
8120 CloseHandle((HANDLE)h);
8130call_w32_io_info(
VALUE arg)
8133 return (
VALUE)w32_io_info(p->fname, p->st);
8137rb_w32_file_identical_p(
VALUE fname1,
VALUE fname2)
8140 HANDLE f1 = 0, f2 = 0;
8142 f1 = w32_io_info(&fname1, &st1);
8143 if (f1 == INVALID_HANDLE_VALUE)
return Qfalse;
8146 arg.fname = &fname2;
8151 f2 = w32_io_info(&fname2, &st2);
8153 if (f2 == INVALID_HANDLE_VALUE)
return Qfalse;
8154 if (f2) CloseHandle(f2);
8156 if (st1.file_id_p != st2.file_id_p)
return Qfalse;
8157 if (!st1.file_id_p) {
8158 if (st1.info.bhfi.dwVolumeSerialNumber == st2.info.bhfi.dwVolumeSerialNumber &&
8159 st1.info.bhfi.nFileIndexHigh == st2.info.bhfi.nFileIndexHigh &&
8160 st1.info.bhfi.nFileIndexLow == st2.info.bhfi.nFileIndexLow)
8164 if (st1.info.fii.VolumeSerialNumber == st2.info.fii.VolumeSerialNumber &&
8165 memcmp(&st1.info.fii.FileId, &st2.info.fii.FileId,
sizeof(
FILE_ID_128)) == 0)
8172rb_w32_set_thread_description(HANDLE th,
const WCHAR *name)
8175 typedef HRESULT (WINAPI *set_thread_description_func)(HANDLE, PCWSTR);
8176 static set_thread_description_func set_thread_description =
8177 (set_thread_description_func)-1;
8178 if (set_thread_description == (set_thread_description_func)-1) {
8180 set_thread_description = (set_thread_description_func)
8181 get_proc_address(
"kernel32",
"SetThreadDescription", NULL);
8183 if (set_thread_description) {
8184 result = set_thread_description(th, name);
8190rb_w32_set_thread_description_str(HANDLE th,
VALUE name)
8192 int idx, result = FALSE;
8196 return rb_w32_set_thread_description(th, L
"");
8199 idx = rb_enc_get_index(name);
8200 if (idx == ENCINDEX_UTF_16LE) {
8201 result = rb_w32_set_thread_description(th, s);
8204 name =
rb_str_conv_enc(name, rb_enc_from_index(idx), rb_utf8_encoding());
8205 s = mbstr_to_wstr(CP_UTF8, RSTRING_PTR(name), RSTRING_LEN(name)+1, NULL);
8206 result = rb_w32_set_thread_description(th, s);
8216rb_w32_mmap(
void *addr,
size_t len,
int prot,
int flags,
int fd, rb_off_t offset)
8220 DWORD protect = PAGE_EXECUTE_READWRITE;
8222 if (fd > 0 || offset) {
8237 ptr = VirtualAlloc(addr,
len, MEM_RESERVE | MEM_COMMIT, protect);
8239 errno = rb_w32_map_errno(GetLastError());
8247rb_w32_munmap(
void *addr,
size_t len)
8249 if (!VirtualFree(addr, 0, MEM_RELEASE)) {
8250 errno = rb_w32_map_errno(GetLastError());
8258rb_w32_mprotect(
void *addr,
size_t len,
int prot)
8274 if (prot & PROT_EXEC) {
8275 if (!FlushInstructionCache(GetCurrentProcess(), addr,
len)) {
8276 errno = rb_w32_map_errno(GetLastError());
#define RUBY_ASSERT(...)
Asserts that the given expression is truthy if and only if RUBY_DEBUG is truthy.
#define ISSPACE
@old{rb_isspace}
#define ISALPHA
@old{rb_isalpha}
#define ISALNUM
@old{rb_isalnum}
int ruby_glob_func(const char *path, VALUE arg, void *enc)
Type of a glob callback function.
#define T_FILE
Old name of RUBY_T_FILE.
#define ALLOCV
Old name of RB_ALLOCV.
#define ALLOC
Old name of RB_ALLOC.
#define xfree
Old name of ruby_xfree.
#define xrealloc
Old name of ruby_xrealloc.
#define ECONV_UNDEF_REPLACE
Old name of RUBY_ECONV_UNDEF_REPLACE.
#define ENCODING_GET(obj)
Old name of RB_ENCODING_GET.
#define ECONV_INVALID_REPLACE
Old name of RUBY_ECONV_INVALID_REPLACE.
#define ASSUME
Old name of RBIMPL_ASSUME.
#define Qtrue
Old name of RUBY_Qtrue.
#define Qnil
Old name of RUBY_Qnil.
#define Qfalse
Old name of RUBY_Qfalse.
#define NIL_P
Old name of RB_NIL_P.
#define ALLOCV_N
Old name of RB_ALLOCV_N.
#define ALLOCV_END
Old name of RB_ALLOCV_END.
VALUE rb_ensure(VALUE(*b_proc)(VALUE), VALUE data1, VALUE(*e_proc)(VALUE), VALUE data2)
An equivalent to ensure clause.
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.
char * ptr
Pointer to the underlying memory region, of at least capa bytes.
int len
Length of the buffer.
char * ruby_strdup(const char *str)
This is our own version of strdup(3) that uses ruby_xmalloc() instead of system malloc (benefits our ...
#define strdup(s)
Just another name of ruby_strdup.
void ruby_vm_at_exit(void(*func)(ruby_vm_t *))
ruby_vm_at_exit registers a function func to be invoked when a VM passed away.
struct rb_vm_struct ruby_vm_t
The opaque struct to hold VM internals.
void rb_w32_fd_dup(rb_fdset_t *dst, const rb_fdset_t *src)
Identical to rb_w32_fd_copy(), except it copies unlimited number of file descriptors.
void rb_w32_fd_copy(rb_fdset_t *dst, const fd_set *src, int max)
Destructively overwrites an fdset with another.
void rb_fd_term(rb_fdset_t *f)
Destroys the rb_fdset_t, releasing any memory and resources it used.
#define rb_long2int
Just another name of rb_long2int_inline.
#define MEMCPY(p1, p2, type, n)
Handy macro to call memcpy.
#define ALLOCA_N(type, n)
#define MEMZERO(p, type, n)
Handy macro to erase a region of memory.
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
VALUE type(ANYARGS)
ANYARGS-ed function type.
#define RBIMPL_ATTR_NONNULL(list)
Wraps (or simulates) __attribute__((nonnull)).
#define PRI_PIDT_PREFIX
A rb_sprintf() format prefix to be used for a pid_t parameter.
#define rb_fd_init
Initialises the :given :rb_fdset_t.
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
#define FilePathValue(v)
Ensures that the parameter object is a path.
#define errno
Ractor-aware version of errno.
C99 shim for <stdbool.h>.
The data structure which wraps the fd_set bitmap used by select(2).
fd_set * fdset
File descriptors buffer.
int capa
Maximum allowed number of FDs.
intptr_t SIGNED_VALUE
A signed integer type that has the same width with VALUE.
uintptr_t VALUE
Type that represents a Ruby object.