Module: Winproc
- Defined in:
- lib/winproc.rb,
lib/winproc/version.rb,
ext/winproc/winproc.c
Overview
winproc — Windows process control for Ruby: job-object process trees that can never leak, ConPTY terminals, hygienic spawning, and UAC-aware elevation helpers — safe by default, cooperative with a fiber scheduler.
require "winproc"
Winproc::Job.new do |job| # kill_on_close: true (default)
p = Winproc.spawn("ruby", "-e", "puts 6*7", stdout: :pipe, job: job)
out = +""
while (chunk = p.stdout.read) then out << chunk end
p.wait # => 0
p.close
end # any stragglers die with the job
Defined Under Namespace
Classes: AccessDenied, BrokenPipe, Canceled, Closed, ElevationRequired, Error, Job, ModeError, NotFound, OSError, PTY, PrivilegeNotHeld, Process, Stream, Unsupported
Constant Summary collapse
- PRIVILEGE_NAMES =
The four privilege names winproc supports (process-wide, scoped by #with_privilege). The token must already HOLD the privilege.
{ debug: "SeDebugPrivilege", backup: "SeBackupPrivilege", restore: "SeRestorePrivilege", increase_quota: "SeIncreaseQuotaPrivilege" }.freeze
- MS_MAX =
Seconds -> milliseconds for the native waits. nil => -1 (INFINITE); a tiny positive value rounds up to 1 ms (never collapse a wait into a poll). A finite timeout always yields a finite, in-range ms: the result is clamped to the signed 64-bit ceiling the C waits accept (NUM2LL), so an absurdly large timeout becomes a very long finite wait (~292 million years) instead of a RangeError — never an INFINITE wait. Clamping here also means the in-flight guards in the C waits can never wedge on a conversion raise.
0x7FFF_FFFF_FFFF_FFFF- VERSION =
"0.1.0"- SW_HIDE =
0
INT2FIX(SW_HIDE)
- SW_SHOWNORMAL =
1
INT2FIX(SW_SHOWNORMAL)
- SW_SHOWMINIMIZED =
2
INT2FIX(SW_SHOWMINIMIZED)
- SW_SHOWMAXIMIZED =
3
INT2FIX(SW_SHOWMAXIMIZED)
- CREATE_NEW_PROCESS_GROUP =
CreateProcess creation-flag bits exposed to the Ruby layer (verified).
ULONG2NUM(CREATE_NEW_PROCESS_GROUP)
- CREATE_NO_WINDOW =
ULONG2NUM(CREATE_NO_WINDOW)
- SLOT_INHERIT =
stdio slot kinds shared with the Ruby layer
INT2FIX(SLOT_INHERIT)
- SLOT_NULL =
INT2FIX(SLOT_NULL)
- SLOT_PIPE =
INT2FIX(SLOT_PIPE)
- SLOT_IO =
INT2FIX(SLOT_IO)
- SLOT_MERGE =
INT2FIX(SLOT_MERGE)
Class Method Summary collapse
- .__admin ⇒ Object
-
.__elevated ⇒ Object
Elevation helpers =====================================================================.
-
.__privilege(vname, venable) ⇒ Object
Winproc.__privilege(se_name_w8, enable_bool) -> prev_enabled_bool.
- .__pty_available ⇒ Object
-
.__runas(vexe, vparams, vcwd, vsw) ⇒ Object
Winproc.__runas(exe_w8, params_w8, cwd_w8_or_nil, sw_int) -> Process | nil.
-
._spawn(*args) ⇒ Object
Winproc._spawn(app, cmdline, cwd, envblock, flags, job, pty_cols, pty_rows, in_kind, in_io, out_kind, out_io, err_kind, err_io).
-
.admin? ⇒ Boolean
Is the current USER an administrator, even if not currently elevated?.
-
.elevated? ⇒ Boolean
Is the current process running with an elevated token? (TokenElevation).
-
.ms_for(timeout) ⇒ Object
LLONG_MAX: the largest ms NUM2LL accepts.
-
.pty(*argv, cols: 80, rows: 24, app: nil, cwd: nil, env: nil, job: nil) ⇒ Object
Spawn a child attached to a ConPTY pseudoconsole.
-
.pty_available? ⇒ Boolean
Is ConPTY available on this OS? (GetProcAddress probe; never raises.).
-
.quote_argv(argv) ⇒ Object
Quote an argv Array into a single command line per the CommandLineToArgvW / CRT rules ("everyone quotes command line arguments the wrong way").
-
.run_blocking ⇒ Object
Run a blocking native call cooperatively.
-
.runas(exe, args = [], cwd: nil, show: :normal) ⇒ Object
Relaunch/launch a program elevated via the shell "runas" verb (UAC prompt).
-
.spawn(*argv, app: nil, cwd: nil, env: nil, stdin: nil, stdout: nil, stderr: nil, job: nil, new_process_group: false, no_window: false) ⇒ Object
Spawn a child process from an argv ARRAY (no shell is ever invoked).
-
.with_privilege(name) ⇒ Object
Enable a process-token privilege for the duration of the block, restoring its previous state afterwards (even on raise).
Class Method Details
.__admin ⇒ Object
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 |
# File 'ext/winproc/winproc.c', line 1643
static VALUE
winproc_admin_p(VALUE self)
{
HANDLE tok = NULL, linked = NULL, check = NULL;
TOKEN_ELEVATION_TYPE et;
DWORD n = 0;
PSID sid = NULL;
SID_IDENTIFIER_AUTHORITY nt = SECURITY_NT_AUTHORITY;
BOOL member = FALSE;
DWORD gle;
(void)self;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &tok))
raise_gle("OpenProcessToken", GetLastError());
if (!GetTokenInformation(tok, TokenElevationType, &et, sizeof(et), &n)) {
gle = GetLastError(); CloseHandle(tok); raise_gle("GetTokenInformation(ElevationType)", gle);
}
if (et == TokenElevationTypeLimited) {
TOKEN_LINKED_TOKEN lt;
memset(<, 0, sizeof(lt));
if (!GetTokenInformation(tok, TokenLinkedToken, <, sizeof(lt), &n)) {
gle = GetLastError(); CloseHandle(tok); raise_gle("GetTokenInformation(LinkedToken)", gle);
}
linked = lt.LinkedToken; /* impersonation token already */
check = linked;
} else {
check = NULL; /* NULL => effective token */
}
CloseHandle(tok);
if (!AllocateAndInitializeSid(&nt, 2, SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &sid)) {
gle = GetLastError(); if (linked) CloseHandle(linked); raise_gle("AllocateAndInitializeSid", gle);
}
if (!CheckTokenMembership(check, sid, &member)) {
gle = GetLastError(); FreeSid(sid); if (linked) CloseHandle(linked);
raise_gle("CheckTokenMembership", gle);
}
FreeSid(sid);
if (linked) CloseHandle(linked);
return member ? Qtrue : Qfalse;
}
|
.__elevated ⇒ Object
=====================================================================
Elevation helpers
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 |
# File 'ext/winproc/winproc.c', line 1624
static VALUE
winproc_elevated_p(VALUE self)
{
HANDLE tok = NULL;
TOKEN_ELEVATION te;
DWORD n = 0;
BOOL elevated;
(void)self;
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &tok))
raise_gle("OpenProcessToken", GetLastError());
if (!GetTokenInformation(tok, TokenElevation, &te, sizeof(te), &n)) {
DWORD gle = GetLastError(); CloseHandle(tok);
raise_gle("GetTokenInformation(Elevation)", gle);
}
elevated = (te.TokenIsElevated != 0);
CloseHandle(tok);
return elevated ? Qtrue : Qfalse;
}
|
.__privilege(vname, venable) ⇒ Object
Winproc.__privilege(se_name_w8, enable_bool) -> prev_enabled_bool
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 |
# File 'ext/winproc/winproc.c', line 1780
static VALUE
winproc_privilege(VALUE self, VALUE vname, VALUE venable)
{
HANDLE tok = NULL;
WCHAR *name = to_wide(vname);
LUID luid;
TOKEN_PRIVILEGES tp, prev;
DWORD prev_len = sizeof(prev);
int enable = RTEST(venable);
int was_enabled;
DWORD gle;
(void)self;
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &tok)) {
gle = GetLastError(); xfree(name); raise_gle("OpenProcessToken", gle);
}
if (!LookupPrivilegeValueW(NULL, name, &luid)) {
gle = GetLastError(); xfree(name); CloseHandle(tok);
raise_gle("LookupPrivilegeValue", gle);
}
xfree(name);
memset(&tp, 0, sizeof(tp));
memset(&prev, 0, sizeof(prev));
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
tp.Privileges[0].Attributes = enable ? SE_PRIVILEGE_ENABLED : 0;
if (!AdjustTokenPrivileges(tok, FALSE, &tp, sizeof(prev), &prev, &prev_len)) {
gle = GetLastError(); CloseHandle(tok); raise_gle("AdjustTokenPrivileges", gle);
}
/* AdjustTokenPrivileges "succeeds" with ERROR_NOT_ALL_ASSIGNED even when the
* token doesn't hold the privilege — check GLE after success (E-19). */
gle = GetLastError();
if (gle == ERROR_NOT_ALL_ASSIGNED) {
CloseHandle(tok);
raise_code(ePrivilegeNotHeld, "AdjustTokenPrivileges", gle);
}
/* previous enabled-state from PreviousState (empty count => was disabled) */
was_enabled = (prev.PrivilegeCount >= 1 &&
(prev.Privileges[0].Attributes & SE_PRIVILEGE_ENABLED)) ? 1 : 0;
CloseHandle(tok);
return was_enabled ? Qtrue : Qfalse;
}
|
.__pty_available ⇒ Object
1686 1687 1688 1689 1690 1691 1692 |
# File 'ext/winproc/winproc.c', line 1686
static VALUE
winproc_pty_available_p(VALUE self)
{
(void)self;
return (p_CreatePseudoConsole && p_ResizePseudoConsole && p_ClosePseudoConsole)
? Qtrue : Qfalse;
}
|
.__runas(vexe, vparams, vcwd, vsw) ⇒ Object
Winproc.__runas(exe_w8, params_w8, cwd_w8_or_nil, sw_int) -> Process | nil
1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 |
# File 'ext/winproc/winproc.c', line 1736
static VALUE
winproc_runas(VALUE self, VALUE vexe, VALUE vparams, VALUE vcwd, VALUE vsw)
{
runas_t r;
VALUE obj;
process_t *pr;
(void)self;
memset(&r, 0, sizeof(r));
r.file = to_wide(vexe);
r.params = NIL_P(vparams) ? NULL : to_wide(vparams);
r.dir = NIL_P(vcwd) ? NULL : to_wide(vcwd);
r.nshow = NUM2INT(vsw);
rb_thread_call_without_gvl(runas_fn, &r, NULL, NULL);
{
DWORD gle = r.gle;
BOOL ok = r.ok;
HANDLE hproc = r.hproc;
if (r.file) xfree(r.file);
if (r.params) xfree(r.params);
if (r.dir) xfree(r.dir);
if (!ok) raise_gle("ShellExecuteExW", gle); /* 1223 -> Canceled */
if (hproc == NULL) return Qnil; /* launched without a handle */
obj = process_alloc(cProcess);
pr = process_get(obj);
pr->h = hproc;
pr->pid = GetProcessId(hproc);
pr->cancel_event = CreateEventW(NULL, TRUE, FALSE, NULL);
if (!pr->cancel_event) {
DWORD e = GetLastError();
/* the Process owns hproc now; close it via process_close path */
CloseHandle(hproc); pr->h = INVALID_HANDLE_VALUE; pr->closed = 1;
raise_gle("CreateEvent", e);
}
return obj;
}
}
|
._spawn(*args) ⇒ Object
Winproc._spawn(app, cmdline, cwd, envblock, flags, job, pty_cols, pty_rows, in_kind, in_io, out_kind, out_io, err_kind, err_io)
flags: the extra CreationFlags bits the Ruby layer computed (CREATE_NEW_PROCESS_GROUP / CREATE_NO_WINDOW). The base flags (CREATE_UNICODE_ENVIRONMENT|EXTENDED_STARTUPINFO_PRESENT) are added here. pty_cols > 0 selects ConPTY mode (redirection kwargs are absent in that path). Returns the Process (redirected) or the PTY (pty mode).
1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 |
# File 'ext/winproc/winproc.c', line 1390
static VALUE
winproc_spawn(int argc, VALUE *argv, VALUE self)
{
spawn_ctx c;
VALUE v_app, v_cmd, v_cwd, v_env, v_flags, v_job,
v_pcols, v_prows, v_ik, v_iio, v_ok, v_oio, v_ek, v_eio;
DWORD base_flags, extra_flags;
int pty_mode;
BOOL inherit;
STARTUPINFOEXW si;
DWORD attr_count = 0;
DWORD need;
process_t *pr;
DWORD gle;
(void)self;
if (argc != 14) rb_raise(rb_eArgError, "winproc: _spawn arity");
v_app=argv[0]; v_cmd=argv[1]; v_cwd=argv[2]; v_env=argv[3]; v_flags=argv[4];
v_job=argv[5]; v_pcols=argv[6]; v_prows=argv[7];
v_ik=argv[8]; v_iio=argv[9]; v_ok=argv[10]; v_oio=argv[11]; v_ek=argv[12]; v_eio=argv[13];
memset(&c, 0, sizeof(c));
c.proc_obj = c.in_obj = c.out_obj = c.err_obj = Qnil;
c.pty_obj = c.pty_in_obj = c.pty_out_obj = Qnil;
c.pi.hProcess = NULL; c.pi.hThread = NULL;
extra_flags = (DWORD)NUM2ULONG(v_flags);
pty_mode = (NUM2INT(v_pcols) > 0);
/* ---- coerce strings up front (TypeError here: no HANDLE exists yet) ---- */
if (!NIL_P(v_app)) c.app = to_wide(v_app);
c.cmdline = to_wide(v_cmd); /* writable private copy (E-1) */
if (!NIL_P(v_cwd)) c.cwd = to_wide(v_cwd);
if (!NIL_P(v_env)) c.envblock = env_to_wide(v_env);
if (!NIL_P(v_job)) {
job_t *j;
if (!rb_typeddata_is_kind_of(v_job, &job_type)) {
spawn_cleanup_partial(&c);
rb_raise(rb_eTypeError, "winproc: job: must be a Winproc::Job");
}
j = job_get(v_job);
if (j->closed || !j->job) {
spawn_cleanup_partial(&c);
rb_raise(eClosed, "winproc: job is closed");
}
c.hjob = j->job;
}
memset(&si, 0, sizeof(si));
si.StartupInfo.cb = sizeof(STARTUPINFOEXW);
base_flags = CREATE_UNICODE_ENVIRONMENT | EXTENDED_STARTUPINFO_PRESENT;
if (pty_mode) {
COORD size;
HRESULT hr;
/* ConPTY availability is checked in Ruby (pty_available?); guard anyway. */
if (!p_CreatePseudoConsole) {
spawn_cleanup_partial(&c);
raise_code(eUnsupported, "CreatePseudoConsole", ERROR_PROC_NOT_FOUND);
}
size.X = (SHORT)NUM2INT(v_pcols); size.Y = (SHORT)NUM2INT(v_prows);
/* two pipes */
if (!CreatePipe(&c.pty_in_r, &c.pty_in_w, NULL, 0)) {
gle = GetLastError(); spawn_cleanup_partial(&c); raise_gle("CreatePipe", gle);
}
if (!CreatePipe(&c.pty_out_r, &c.pty_out_w, NULL, 0)) {
gle = GetLastError(); spawn_cleanup_partial(&c); raise_gle("CreatePipe", gle);
}
hr = p_CreatePseudoConsole(size, c.pty_in_r, c.pty_out_w, 0, &c.hpcon);
if (FAILED(hr)) {
spawn_cleanup_partial(&c);
raise_code(eOSError, "CreatePseudoConsole", (DWORD)(hr & 0xFFFF));
}
/* The PTY-side ends (pty_in_r / pty_out_w) are closed AFTER CreateProcess
* (E-8 / creating-a-pseudoconsole-session: "Upon completion of the
* CreateProcess call ... the handles given during creation should be
* freed from this process"). Closing them BEFORE CreateProcess can leave
* the child unattached. They are tracked in the ctx so the fail path also
* closes them. */
attr_count = 1 + (c.hjob ? 1 : 0);
inherit = FALSE; /* no STARTF_USESTDHANDLES, no HANDLE_LIST (E-9) */
} else {
/* ---- redirected/inherit mode: build the 3 child stdio handles ---- */
int ik = NUM2INT(v_ik), ok = NUM2INT(v_ok), ek = NUM2INT(v_ek);
int any_redirect = (ik != SLOT_INHERIT || ok != SLOT_INHERIT || ek != SLOT_INHERIT);
if (any_redirect) {
int pw;
HANDLE child, parent;
/* stdin */
if (ik == SLOT_INHERIT)
child = inherit_std_or_nul(STD_INPUT_HANDLE), parent = NULL;
else { build_slot(ik, v_iio, 1, &child, &parent, &pw); }
c.child_in = child;
if (ik == SLOT_PIPE) c.par_in_w = parent;
/* stdout */
if (ok == SLOT_INHERIT)
child = inherit_std_or_nul(STD_OUTPUT_HANDLE), parent = NULL;
else { build_slot(ok, v_oio, 0, &child, &parent, &pw); }
c.child_out = child;
if (ok == SLOT_PIPE) c.par_out_r = parent;
/* stderr (SLOT_MERGE => reuse stdout child handle) */
if (ek == SLOT_MERGE) {
c.child_err = c.child_out;
} else if (ek == SLOT_INHERIT) {
c.child_err = inherit_std_or_nul(STD_ERROR_HANDLE);
} else {
build_slot(ek, v_eio, 0, &child, &parent, &pw);
c.child_err = child;
if (ek == SLOT_PIPE) c.par_err_r = parent;
}
si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
si.StartupInfo.hStdInput = c.child_in;
si.StartupInfo.hStdOutput = c.child_out;
si.StartupInfo.hStdError = c.child_err;
hlist_add(&c, c.child_in);
hlist_add(&c, c.child_out);
hlist_add(&c, c.child_err);
inherit = TRUE;
attr_count = 1 + (c.hjob ? 1 : 0); /* HANDLE_LIST + maybe JOB_LIST */
} else {
inherit = FALSE;
attr_count = (c.hjob ? 1 : 0);
}
}
/* ---- attribute list (E-4 double-call idiom) ---- */
if (attr_count > 0) {
need = 0;
InitializeProcThreadAttributeList(NULL, attr_count, 0, &c.attr_size);
c.attr = (LPPROC_THREAD_ATTRIBUTE_LIST)malloc(c.attr_size);
if (!c.attr) { spawn_cleanup_partial(&c); rb_raise(rb_eNoMemError, "winproc: out of memory"); }
if (!InitializeProcThreadAttributeList(c.attr, attr_count, 0, &c.attr_size)) {
gle = GetLastError(); spawn_cleanup_partial(&c); raise_gle("InitializeProcThreadAttributeList", gle);
}
c.attr_inited = 1;
(void)need;
if (pty_mode) {
if (!UpdateProcThreadAttribute(c.attr, 0, PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
c.hpcon, sizeof(c.hpcon), NULL, NULL)) {
gle = GetLastError(); spawn_cleanup_partial(&c); raise_gle("UpdateProcThreadAttribute(pty)", gle);
}
} else if (c.hcount > 0) {
if (!UpdateProcThreadAttribute(c.attr, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
c.hlist, c.hcount * sizeof(HANDLE), NULL, NULL)) {
gle = GetLastError(); spawn_cleanup_partial(&c); raise_gle("UpdateProcThreadAttribute(handles)", gle);
}
}
if (c.hjob) {
if (!UpdateProcThreadAttribute(c.attr, 0, PROC_THREAD_ATTRIBUTE_JOB_LIST,
&c.hjob, sizeof(HANDLE), NULL, NULL)) {
gle = GetLastError(); spawn_cleanup_partial(&c); raise_gle("UpdateProcThreadAttribute(job)", gle);
}
}
si.lpAttributeList = c.attr;
}
/* ---- pre-allocate every raise-capable resource (E-31) ---- */
c.cancel_event = CreateEventW(NULL, TRUE, FALSE, NULL);
if (!c.cancel_event) { gle = GetLastError(); spawn_cleanup_partial(&c); raise_gle("CreateEvent", gle); }
c.proc_obj = process_alloc(cProcess);
if (pty_mode) {
c.pty_obj = pty_alloc(cPTY);
c.pty_in_obj = stream_alloc(cStream); /* writable */
c.pty_out_obj = stream_alloc(cStream); /* readable */
rb_ivar_set(c.pty_obj, rb_intern("@process"), c.proc_obj);
rb_ivar_set(c.pty_obj, rb_intern("@input"), c.pty_in_obj);
rb_ivar_set(c.pty_obj, rb_intern("@output"), c.pty_out_obj);
} else {
if (!NIL_P(v_ik) && NUM2INT(v_ik) == SLOT_PIPE) c.in_obj = stream_alloc(cStream);
if (NUM2INT(v_ok) == SLOT_PIPE) c.out_obj = stream_alloc(cStream);
if (NUM2INT(v_ek) == SLOT_PIPE) c.err_obj = stream_alloc(cStream);
if (!NIL_P(c.in_obj)) rb_ivar_set(c.proc_obj, rb_intern("@stdin"), c.in_obj);
if (!NIL_P(c.out_obj)) rb_ivar_set(c.proc_obj, rb_intern("@stdout"), c.out_obj);
if (!NIL_P(c.err_obj)) rb_ivar_set(c.proc_obj, rb_intern("@stderr"), c.err_obj);
}
/* ---- CreateProcessW (NO Ruby allocation past this point) ---- */
if (!CreateProcessW(c.app, c.cmdline, NULL, NULL, inherit,
base_flags | extra_flags,
c.envblock, c.cwd, &si.StartupInfo, &c.pi)) {
gle = GetLastError();
spawn_cleanup_partial(&c);
raise_gle("CreateProcessW", gle);
}
c.created = 1;
/* tidy attr list + child-side handles + pi.hThread (plain CloseHandle) */
if (c.attr_inited) { DeleteProcThreadAttributeList(c.attr); c.attr_inited = 0; }
if (c.attr) { free(c.attr); c.attr = NULL; }
if (c.pi.hThread) { CloseHandle(c.pi.hThread); c.pi.hThread = NULL; }
if (c.child_in) { CloseHandle(c.child_in); c.child_in = NULL; }
if (c.child_err && c.child_err != c.child_out) { CloseHandle(c.child_err); c.child_err = NULL; }
if (c.child_out) { CloseHandle(c.child_out); c.child_out = NULL; c.child_err = NULL; }
/* PTY-side ends: now that the child is attached, drop our refs so our read
* end can detect a broken channel (EOF) when the PTY tears down. */
if (c.pty_in_r) { CloseHandle(c.pty_in_r); c.pty_in_r = NULL; }
if (c.pty_out_w) { CloseHandle(c.pty_out_w); c.pty_out_w = NULL; }
/* free wide strings */
if (c.app) { xfree(c.app); c.app = NULL; }
if (c.cmdline) { xfree(c.cmdline); c.cmdline = NULL; }
if (c.cwd) { xfree(c.cwd); c.cwd = NULL; }
if (c.envblock) { xfree(c.envblock); c.envblock = NULL; }
/* ---- populate pre-allocated structs (plain stores; cannot raise) ---- */
pr = process_get(c.proc_obj);
pr->h = c.pi.hProcess;
pr->cancel_event = c.cancel_event;
pr->pid = c.pi.dwProcessId;
c.cancel_event = NULL; /* ownership moved to the Process */
if (pty_mode) {
pty_t *t = pty_get(c.pty_obj);
stream_t *sin = stream_get(c.pty_in_obj);
stream_t *sout = stream_get(c.pty_out_obj);
t->hpc = c.hpcon; c.hpcon = NULL;
t->cols = NUM2INT(v_pcols); t->rows = NUM2INT(v_prows);
sin->h = c.pty_in_w; sin->writable = 1; c.pty_in_w = NULL;
sout->h = c.pty_out_r; sout->writable = 0; c.pty_out_r = NULL;
return c.pty_obj;
} else {
if (!NIL_P(c.in_obj)) { stream_t *s = stream_get(c.in_obj); s->h = c.par_in_w; s->writable = 1; c.par_in_w = NULL; }
if (!NIL_P(c.out_obj)) { stream_t *s = stream_get(c.out_obj); s->h = c.par_out_r; s->writable = 0; c.par_out_r = NULL; }
if (!NIL_P(c.err_obj)) { stream_t *s = stream_get(c.err_obj); s->h = c.par_err_r; s->writable = 0; c.par_err_r = NULL; }
return c.proc_obj;
}
}
|
.admin? ⇒ Boolean
Is the current USER an administrator, even if not currently elevated?
253 254 255 |
# File 'lib/winproc.rb', line 253 def admin? __admin end |
.elevated? ⇒ Boolean
Is the current process running with an elevated token? (TokenElevation)
248 249 250 |
# File 'lib/winproc.rb', line 248 def elevated? __elevated end |
.ms_for(timeout) ⇒ Object
LLONG_MAX: the largest ms NUM2LL accepts
76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/winproc.rb', line 76 def ms_for(timeout) return -1 if timeout.nil? t = Float(timeout) raise ArgumentError, "timeout must be non-negative, got #{timeout.inspect}" if t.negative? ms = (t * 1000).round return 1 if ms.zero? && t.positive? ms > MS_MAX ? MS_MAX : ms end |
.pty(*argv, cols: 80, rows: 24, app: nil, cwd: nil, env: nil, job: nil) ⇒ Object
Spawn a child attached to a ConPTY pseudoconsole. Returns a Winproc::PTY; with a block, yields it and ensure-closes (kill: true). stdio redirection kwargs are deliberately absent (ConPTY and pipe redirection are mutually exclusive).
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 |
# File 'lib/winproc.rb', line 221 def pty(*argv, cols: 80, rows: 24, app: nil, cwd: nil, env: nil, job: nil) raise Unsupported, "winproc: ConPTY requires Windows 10 1809+" unless pty_available? c = Integer(cols) r = Integer(rows) raise ArgumentError, "cols/rows must be 1..32767" unless (1..0x7FFF).cover?(c) && (1..0x7FFF).cover?(r) cmdline = quote_argv(argv) envblock = build_env_block(env) pty = _spawn(app && String(app), cmdline, cwd && String(cwd), envblock, 0, job, c, r, SLOT_INHERIT, nil, SLOT_INHERIT, nil, SLOT_INHERIT, nil) return pty unless block_given? begin yield pty ensure pty.close(kill: true) end end |
.pty_available? ⇒ Boolean
Is ConPTY available on this OS? (GetProcAddress probe; never raises.)
243 244 245 |
# File 'lib/winproc.rb', line 243 def pty_available? __pty_available end |
.quote_argv(argv) ⇒ Object
Quote an argv Array into a single command line per the CommandLineToArgvW / CRT rules ("everyone quotes command line arguments the wrong way"). Pure, unit-tested. Raises ArgumentError on an empty argv or a NUL in any element.
NOTE: these are the rules of the C runtime / CommandLineToArgvW parser.
cmd.exe batch files and programs that parse their own command line
differently (notably cmd /c) have their own metacharacter rules — winproc
never invokes a shell and does not escape for cmd.exe.
96 97 98 99 100 |
# File 'lib/winproc.rb', line 96 def quote_argv(argv) raise ArgumentError, "argv must not be empty" if argv.empty? argv.map { |arg| quote_one(arg) }.join(" ") end |
.run_blocking ⇒ Object
Run a blocking native call cooperatively. Under a Fiber scheduler (e.g. winloop) the call is offloaded to a worker Thread so the calling fiber parks (Thread#value routes through the scheduler's block/unblock hooks) and the event loop keeps serving other fibers; with no scheduler it runs inline (the C call already releases the GVL). On fiber unwind the worker is killed + joined so it can't leak or consume data destined for a later op.
Caveat (same as winipc): a fiber unwound in the instant after the worker acquired a resource but before the value was delivered loses that acquisition — the inherent cancelled-read-already-pulled-bytes limitation.
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/winproc.rb', line 49 def run_blocking sched = Fiber.scheduler return yield unless sched worker = Thread.new do Thread.current.report_on_exception = false yield end begin worker.value ensure if worker.alive? worker.kill worker.join end end end |
.runas(exe, args = [], cwd: nil, show: :normal) ⇒ Object
Relaunch/launch a program elevated via the shell "runas" verb (UAC prompt).
args is an argv-style Array quoted by winproc with the same quote_argv
rules as spawn (a String raises TypeError). Returns a Winproc::Process when
the shell reports a new process handle; nil when it launched without one.
261 262 263 264 265 266 267 268 269 270 271 272 273 |
# File 'lib/winproc.rb', line 261 def runas(exe, args = [], cwd: nil, show: :normal) raise TypeError, "runas args must be an Array, got #{args.class}" unless args.is_a?(Array) params = args.empty? ? nil : quote_argv(args) sw = case show when :normal then SW_SHOWNORMAL when :hide then SW_HIDE when :minimized then SW_SHOWMINIMIZED when :maximized then SW_SHOWMAXIMIZED else raise ArgumentError, "show must be :normal/:hide/:minimized/:maximized, got #{show.inspect}" end run_blocking { __runas(String(exe), params, cwd && String(cwd), sw) } end |
.spawn(*argv, app: nil, cwd: nil, env: nil, stdin: nil, stdout: nil, stderr: nil, job: nil, new_process_group: false, no_window: false) ⇒ Object
Spawn a child process from an argv ARRAY (no shell is ever invoked). Returns a Winproc::Process; with a block, yields it and ensure-closes the handles (closing does NOT kill the child — use job: for guaranteed reaping).
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 |
# File 'lib/winproc.rb', line 193 def spawn(*argv, app: nil, cwd: nil, env: nil, stdin: nil, stdout: nil, stderr: nil, job: nil, new_process_group: false, no_window: false) cmdline = quote_argv(argv) envblock = build_env_block(env) ik, iio = stdio_spec(stdin) ok, oio = stdio_spec(stdout) ek, eio = stdio_spec(stderr, allow_merge: true) flags = 0 flags |= CREATE_NEW_PROCESS_GROUP if new_process_group flags |= CREATE_NO_WINDOW if no_window process = _spawn(app && String(app), cmdline, cwd && String(cwd), envblock, flags, job, 0, 0, ik, iio, ok, oio, ek, eio) return process unless block_given? begin yield process ensure process.close end end |
.with_privilege(name) ⇒ Object
Enable a process-token privilege for the duration of the block, restoring its previous state afterwards (even on raise). The token is PROCESS-wide.
277 278 279 280 281 282 283 284 285 286 287 |
# File 'lib/winproc.rb', line 277 def with_privilege(name) se = PRIVILEGE_NAMES[name] raise ArgumentError, "unknown privilege #{name.inspect}; one of #{PRIVILEGE_NAMES.keys.inspect}" unless se was_enabled = __privilege(se, true) # raises PrivilegeNotHeld if not held begin yield ensure __privilege(se, was_enabled) end end |