GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — rchitect/rchitect/utils.py at master · randy3k/rchitect

Expand file tree

/

utils.py

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
700 lines (596 loc) · 25 KB
/

utils.py

Copy path

File metadata and controls

700 lines (596 loc) · 25 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
import ctypes
import os
import platform
import re
import subprocess
import sys
from shutil import which
from packaging.version import parse as parse_version
if sys.platform.startswith("win"):
from winreg import OpenKey, QueryValueEx, HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER
# =============================================================================
# 1. R Discovery & Version
# =============================================================================
def is_arm():
if sys.platform.startswith("win"):
return "(arm64)" in sys.version.lower()
return platform.machine().lower() in ("arm64", "aarch64")
def read_registry_from_local_machine(key, valueex):
with OpenKey(HKEY_LOCAL_MACHINE, key) as k:
return QueryValueEx(k, valueex)
def read_registry_from_current_user(key, valueex):
with OpenKey(HKEY_CURRENT_USER, key) as k:
return QueryValueEx(k, valueex)
def read_registry(key, valueex):
try:
return read_registry_from_current_user(key, valueex)
except Exception:
return read_registry_from_local_machine(key, valueex)
def read_r_install_path_from_registry():
keys = (
"Software\\R-Core\\R",
"Software\\WOW6432Node\\R-Core\\R",
)
fallback = None
for key in keys:
for reader in (read_registry_from_current_user, read_registry_from_local_machine):
try:
path = reader(key, "InstallPath")[0]
except Exception:
continue
if path and os.path.isdir(path):
if fallback is None:
fallback = path
dll_rel = (
os.path.join("bin", "R.dll")
if is_arm()
else os.path.join("bin", "x64", "R.dll")
)
if os.path.isfile(os.path.join(path, dll_rel)):
return path
return fallback
def get_rhome_from_binary(rbinary):
if rbinary:
rbinary = os.path.expanduser(rbinary)
if sys.platform.startswith("win"):
if rbinary and not rbinary.lower().endswith((".exe", ".bat", ".cmd")):
rbinary = rbinary + ".exe"
if not which(rbinary):
return None
try:
env = {k: v for k, v in os.environ.items() if k != "R_HOME"}
return subprocess.check_output([rbinary, "RHOME"], env=env).decode("utf-8").strip()
except Exception:
pass
return None
def get_rhome():
rhome = None
if os.environ.get("R_BINARY"):
rbinary = os.environ["R_BINARY"]
cached_rhome = os.environ.get("R_HOME")
if (
cached_rhome
and os.environ.get("_RCHITECT_R_BINARY") == rbinary
and os.environ.get("_RCHITECT_R_HOME") == cached_rhome
and os.path.isdir(cached_rhome)
):
return cached_rhome
rhome = get_rhome_from_binary(rbinary)
if not rhome:
raise RuntimeError("R binary ({}) does not exist.".format(rbinary))
os.environ["R_HOME"] = rhome
os.environ["_RCHITECT_R_BINARY"] = rbinary
os.environ["_RCHITECT_R_HOME"] = rhome
return rhome
if os.environ.get("R_HOME"):
rhome = os.environ["R_HOME"]
if not os.path.isdir(rhome):
raise RuntimeError("R_HOME ({}) does not exist.".format(rhome))
return rhome
rhome = get_rhome_from_binary("R")
if not rhome and sys.platform.startswith("win"):
rhome = read_r_install_path_from_registry()
if rhome:
os.environ["R_HOME"] = rhome
else:
raise RuntimeError("Cannot determine R HOME.")
return rhome
_R_VERSION_MAJOR_RE = re.compile(r'^#define\s+R_MAJOR\s+"([^"]+)"', re.M)
_R_VERSION_MINOR_RE = re.compile(r'^#define\s+R_MINOR\s+"([^"]+)"', re.M)
_R_DESC_VERSION_RE = re.compile(r"^Version:\s*(\S+)", re.M)
_rversion_cache = {}
def rversion(rhome=None):
if not rhome:
rhome = get_rhome()
if rhome in _rversion_cache:
return _rversion_cache[rhome]
rversion_h = os.path.join(rhome, "include", "Rversion.h")
if os.path.isfile(rversion_h):
try:
with open(rversion_h, "r", encoding="utf-8", errors="ignore") as f:
content = f.read()
m_major = _R_VERSION_MAJOR_RE.search(content)
m_minor = _R_VERSION_MINOR_RE.search(content)
if m_major and m_minor:
version = parse_version("{}.{}".format(m_major.group(1), m_minor.group(1)))
_rversion_cache[rhome] = version
return version
except Exception:
pass
base_desc = os.path.join(rhome, "library", "base", "DESCRIPTION")
if os.path.isfile(base_desc):
try:
with open(base_desc, "r", encoding="utf-8", errors="ignore") as f:
content = f.read()
m_ver = _R_DESC_VERSION_RE.search(content)
if m_ver:
version = parse_version(m_ver.group(1))
_rversion_cache[rhome] = version
return version
except Exception:
pass
try:
output = (
subprocess.check_output(
[
os.path.join(rhome, "bin", "R"),
"--no-echo",
"--vanilla",
"-e",
"cat(as.character(getRversion()))",
],
stderr=subprocess.STDOUT,
)
.decode("utf-8")
.strip()
)
version = parse_version(output)
except Exception:
version = parse_version("1000.0.0")
_rversion_cache[rhome] = version
return version
def ensure_path_for_dll(libr_path):
libr_dir = os.path.dirname(libr_path)
env_path = os.environ.get("PATH", "")
norm_dir = os.path.normcase(os.path.normpath(libr_dir))
path_entries = [
os.path.normcase(os.path.normpath(p))
for p in env_path.split(os.pathsep)
if p
]
if norm_dir not in path_entries:
os.environ["PATH"] = (
libr_dir + os.pathsep + env_path if env_path else libr_dir
)
def get_libr_path(rhome, ensure_path=False):
# TODO: better support R_ARCH
if sys.platform.startswith("win"):
if is_arm():
libr_path = os.path.join(rhome, "bin", "R.dll")
else:
libr_path = os.path.join(rhome, "bin", "x64", "R.dll")
elif sys.platform == "darwin":
libr_path = os.path.join(rhome, "lib", "libR.dylib")
else:
libr_path = os.path.join(rhome, "lib", "libR.so")
if not os.path.exists(libr_path):
if sys.platform.startswith("win"):
other_path = (
os.path.join(rhome, "bin", "x64", "R.dll")
if is_arm()
else os.path.join(rhome, "bin", "R.dll")
)
if os.path.exists(other_path):
raise RuntimeError(
"R ({}) and Python ({}) architectures do not match.".format(
"x64" if is_arm() else "ARM64",
"ARM64" if is_arm() else "x64",
)
)
raise RuntimeError("R share library ({}) does not exist.".format(libr_path))
if sys.platform.startswith("win") and ensure_path:
ensure_path_for_dll(libr_path)
return libr_path
# =============================================================================
# 2. Shared Library Loading & Preload State
# =============================================================================
_libr_loaded = False
_external_libr = False
_host_active = False
_dll_dir_cookies = []
def _is_libr_in_process():
try:
if sys.platform.startswith("win"):
kernel32 = ctypes.windll.kernel32
kernel32.GetModuleHandleW.argtypes = [ctypes.c_wchar_p]
kernel32.GetModuleHandleW.restype = ctypes.c_void_p
return bool(kernel32.GetModuleHandleW("R.dll"))
else:
return hasattr(ctypes.CDLL(None), "R_GlobalEnv")
except Exception:
return False
def reset_preload_env():
global _libr_loaded, _external_libr, _host_active
if not _host_active and not _libr_loaded:
if (
"_RCHITECT_HOST_ACTIVE" not in os.environ
and "_RCHITECT_LIBR_LOADED" not in os.environ
and _is_libr_in_process()
):
_external_libr = True
_libr_loaded = True
if os.environ.pop("_RCHITECT_HOST_ACTIVE", None) == "1":
_host_active = True
if os.environ.pop("_RCHITECT_LIBR_LOADED", None) == "1":
if sys.platform.startswith("win"):
_libr_loaded = True
else:
_libr_loaded = _is_libr_in_process()
preload_libs = os.environ.pop("_RCHITECT_PRELOAD_LIBS", None)
if not preload_libs:
return
var = "DYLD_INSERT_LIBRARIES" if sys.platform == "darwin" else "LD_PRELOAD"
if var not in os.environ:
return
injected = set(preload_libs.split(":"))
libs = [lib for lib in os.environ[var].split(":") if lib and lib not in injected]
if libs:
os.environ[var] = ":".join(libs)
else:
del os.environ[var]
def setup_r_dll_dir(rhome=None):
if not rhome:
rhome = get_rhome()
libr_path = get_libr_path(rhome, ensure_path=True)
libr_dir = os.path.dirname(libr_path)
try:
_dll_dir_cookies.append(os.add_dll_directory(libr_dir))
except Exception:
pass
class _LinkMap(ctypes.Structure):
# Matches the prefix of `struct link_map` from `<link.h>` on Linux/glibc.
# On Linux, the `void *` handle returned by `dlopen()` (`CDLL._handle`) is
# a `struct link_map *`.
_fields_ = [
("l_addr", ctypes.c_void_p),
("l_name", ctypes.c_void_p),
]
# Keep string buffers alive for the lifetime of the process since `l_name`
# stores a raw `char *` pointer read by the dynamic linker.
_soname_bufs = []
def _register_linux_soname(handle, soname):
"""Register a short SONAME on an already-loaded `ctypes.CDLL` handle on Linux.
R on Linux builds `libR.so`, `libRblas.so`, and `libRlapack.so` without a
`DT_SONAME` ELF header entry, while R's base package shared libraries
(e.g., `utils.so`, `methods.so`, `stats.so`, `grDevices.so`, `lapack.so`)
declare `DT_NEEDED` for the bare filename `"libR.so"` (or `"libRlapack.so"`
/ `"libRblas.so"`) without an `RPATH`.
When `ctypes.CDLL(full_path, mode=ctypes.RTLD_GLOBAL)` loads `libR.so` by
absolute path in a process started without `LD_LIBRARY_PATH` containing
`$R_HOME/lib`, glibc only records the full path in `link_map->l_name`.
Subsequent `dlopen()` calls from R for `utils.so` then fail to find
`"libR.so"` because glibc's `_dl_name_match_p(name, map)` only sees the
full path in `map->l_name` and has no `DT_SONAME` in `map->l_libname`.
Pointing `link_map->l_name` to a pinned buffer containing the bare SONAME
(e.g., `"libR.so"`) makes `_dl_name_match_p` match the in-memory library
immediately without requiring `LD_LIBRARY_PATH` or process re-exec.
"""
if not sys.platform.startswith("linux") or not getattr(handle, "_handle", None):
return
try:
buf = ctypes.create_string_buffer(soname.encode("utf-8"))
_soname_bufs.append(buf)
_LinkMap.from_address(handle._handle).l_name = ctypes.addressof(buf)
except Exception:
pass
def load_libr(rhome=None):
if not rhome:
rhome = get_rhome()
libr_path = get_libr_path(rhome)
libr_dir = os.path.dirname(libr_path)
if sys.platform != "darwin":
rblas_path = os.path.join(libr_dir, "libRblas.so")
if os.path.exists(rblas_path):
try:
h_blas = ctypes.CDLL(rblas_path, mode=ctypes.RTLD_GLOBAL)
_register_linux_soname(h_blas, "libRblas.so")
except OSError:
pass
try:
h_r = ctypes.CDLL(libr_path, mode=ctypes.RTLD_GLOBAL)
_register_linux_soname(h_r, "libR.so")
except OSError as e:
raise Exception("Cannot load shared library: {}".format(e))
if sys.platform != "darwin":
rlapack_path = os.path.join(libr_dir, "libRlapack.so")
if os.path.exists(rlapack_path):
try:
h_lapack = ctypes.CDLL(rlapack_path, mode=ctypes.RTLD_GLOBAL)
_register_linux_soname(h_lapack, "libRlapack.so")
except OSError:
pass
def ensure_libr():
global _libr_loaded
reset_preload_env()
rhome = get_rhome()
if rversion(rhome) < parse_version("4.2.0"):
raise RuntimeError("R >= 4.2.0 is required")
if _libr_loaded:
return
if sys.platform.startswith("win"):
setup_r_dll_dir(rhome)
else:
load_libr(rhome)
_libr_loaded = True
# =============================================================================
# 3. Host Launcher & Process Re-Exec
# =============================================================================
def get_host():
if not sys.platform.startswith("win"):
return None
host = os.path.join(os.path.dirname(os.path.abspath(__file__)), "host.exe")
if os.path.isfile(host):
return host
return None
def should_use_host():
reset_preload_env()
if _host_active or _external_libr:
return False
if os.environ.get("RCHITECT_HOST_DISABLED", "0") == "1":
return False
if sys.platform.startswith("win") and not get_host():
return False
return True
def _get_macos_blas_path(libr_path):
"""Resolve the actual BLAS dylib path used by `libR.dylib` on macOS.
On macOS, the Python executable links against `CoreFoundation.framework`,
which transitively pulls Apple's `Accelerate.framework` (`libBLAS.dylib`)
into the process at `execve` time. Because `dlsym(RTLD_DEFAULT, ...)`
searches images in load order, loading R's BLAS later via `ctypes.CDLL`
places it behind `Accelerate.framework`, causing `extSoftVersion()["BLAS"]`
and flat-namespace lookups to resolve `dgemm_` to `Accelerate` instead of
R's configured BLAS. Preloading R's BLAS via `DYLD_INSERT_LIBRARIES` places
it ahead of `Accelerate.framework` in `RTLD_DEFAULT` load order.
Different macOS R distributions link BLAS in different ways:
- CRAN R links `@rpath/libRblas.dylib` in `$R_HOME/lib` (which may symlink
to `libRblas.0.dylib` or `libRblas.vecLib.dylib`).
- Homebrew R links external OpenBLAS (`libopenblas.dylib`) directly and does
not ship `$R_HOME/lib/libRblas.dylib` at all.
Rather than manually parsing Mach-O load commands, we open `libR.dylib`
with `dlopen(..., RTLD_LAZY | RTLD_LOCAL)`, look up `dgemm_` via `dlsym`,
and query `dladdr` (`Dl_info.dli_fname`) so `dyld` itself reports the exact
file path of the library providing `libR.dylib`'s BLAS symbols.
"""
class _Dl_info(ctypes.Structure):
_fields_ = [
("dli_fname", ctypes.c_char_p),
("dli_fbase", ctypes.c_void_p),
("dli_sname", ctypes.c_char_p),
("dli_saddr", ctypes.c_void_p),
]
lib_dir = os.path.dirname(libr_path)
open_path = os.path.realpath(libr_path)
try:
libc = ctypes.CDLL(None)
libc.dlopen.argtypes = [ctypes.c_char_p, ctypes.c_int]
libc.dlopen.restype = ctypes.c_void_p
libc.dlsym.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
libc.dlsym.restype = ctypes.c_void_p
libc.dladdr.argtypes = [ctypes.c_void_p, ctypes.POINTER(_Dl_info)]
libc.dladdr.restype = ctypes.c_int
libc.dlclose.argtypes = [ctypes.c_void_p]
libc.dlclose.restype = ctypes.c_int
# RTLD_LAZY (0x1) | RTLD_LOCAL (0x4)
handle = libc.dlopen(open_path.encode("utf-8"), 0x1 | 0x4)
if handle:
try:
addr = libc.dlsym(handle, b"dgemm_")
info = _Dl_info()
if addr and libc.dladdr(addr, ctypes.byref(info)) and info.dli_fname:
blas_path = info.dli_fname.decode("utf-8", "ignore")
if blas_path:
return blas_path
finally:
libc.dlclose(handle)
except Exception:
pass
fallback = os.path.join(lib_dir, "libRblas.dylib")
if os.path.isfile(fallback):
return fallback
return None
def _setup_unix_preload_env(rhome, env):
"""Configure dynamic linker search paths and preloaded R libraries before `os.execve`.
This function prepares `env` for the re-execed Unix process in two steps:
1. Dynamic linker library search paths (`R_LD_LIBRARY_PATH` and
`LD_LIBRARY_PATH` on Linux / `DYLD_FALLBACK_LIBRARY_PATH` on macOS):
Sources `$R_HOME/etc/ldpaths` (mirroring R's `/usr/bin/R` startup script)
so `$R_HOME/lib`, `$R_JAVA_LD_LIBRARY_PATH` (e.g., `libjvm.so` for
`rJava`), and any build-time library directories are registered with
`ld.so` / `dyld` at process startup (`execve`), which is the only time
the OS dynamic linker reads these environment variables.
2. Early BLAS + `libR` preloading (`DYLD_INSERT_LIBRARIES` on macOS /
`LD_PRELOAD` on Linux):
Places R's BLAS library and `libR` at the front of the `RTLD_DEFAULT`
symbol search order before the host `python` executable's own transitive
dependencies (such as macOS `CoreFoundation` -> `Accelerate.framework`
`libBLAS.dylib`). In the re-execed child, `reset_preload_env()` strips
the injected paths from `DYLD_INSERT_LIBRARIES` / `LD_PRELOAD` so child
subprocesses do not inherit them.
"""
lib_path = os.path.join(rhome, "lib")
ldpaths = os.path.join(rhome, "etc", "ldpaths")
ldpaths_out = ""
if os.path.isfile(ldpaths):
try:
sub_env = env.copy()
sub_env["R_HOME"] = rhome
sub_env["_RCHITECT_TMP_LDPATHS"] = ldpaths
ldpaths_out = (
subprocess.check_output(
[
"/bin/sh",
"-c",
'. "$_RCHITECT_TMP_LDPATHS" >/dev/null 2>&1; printf "%s" "$R_LD_LIBRARY_PATH"',
],
env=sub_env,
)
.decode("utf-8", "ignore")
.strip()
)
except Exception:
pass
else:
ldpaths_out = env.get("R_LD_LIBRARY_PATH", "")
if not ldpaths_out:
r_ld_library_path = lib_path
elif lib_path not in ldpaths_out.split(":"):
r_ld_library_path = "{}:{}".format(lib_path, ldpaths_out)
else:
r_ld_library_path = ldpaths_out
env["R_LD_LIBRARY_PATH"] = r_ld_library_path
ld_var = "DYLD_FALLBACK_LIBRARY_PATH" if sys.platform == "darwin" else "LD_LIBRARY_PATH"
existing_ld = env.get(ld_var, "")
# Keep any pre-existing entries (e.g. Python's own libpython directory from
# actions/setup-python, conda, or custom builds) ahead of R_LD_LIBRARY_PATH,
# which may contain system library dirs like /usr/lib/x86_64-linux-gnu that
# would otherwise shadow the host interpreter's libpython on os.execve.
env[ld_var] = (
"{}:{}".format(existing_ld, r_ld_library_path) if existing_ld else r_ld_library_path
)
if sys.platform == "darwin":
libr_path = os.path.join(lib_path, "libR.dylib")
if os.path.isfile(libr_path):
open_path = os.path.realpath(libr_path)
blas_path = _get_macos_blas_path(libr_path)
if blas_path and blas_path != libr_path and blas_path != open_path:
preload_libs = "{}:{}".format(blas_path, libr_path)
else:
preload_libs = libr_path
existing_insert = env.get("DYLD_INSERT_LIBRARIES", "")
env["DYLD_INSERT_LIBRARIES"] = (
"{}:{}".format(existing_insert, preload_libs) if existing_insert else preload_libs
)
env["_RCHITECT_PRELOAD_LIBS"] = preload_libs
env["_RCHITECT_LIBR_LOADED"] = "1"
else:
libr_path = os.path.join(lib_path, "libR.so")
rblas_path = os.path.join(lib_path, "libRblas.so")
if os.path.isfile(libr_path):
if os.path.isfile(rblas_path):
preload_libs = "{}:{}".format(rblas_path, libr_path)
else:
preload_libs = libr_path
existing_preload = env.get("LD_PRELOAD", "")
env["LD_PRELOAD"] = (
"{}:{}".format(existing_preload, preload_libs) if existing_preload else preload_libs
)
env["_RCHITECT_PRELOAD_LIBS"] = preload_libs
env["_RCHITECT_LIBR_LOADED"] = "1"
def _assign_job_kill_on_close(proc_handle):
try:
from ctypes import wintypes
kernel32 = ctypes.windll.kernel32
kernel32.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR]
kernel32.CreateJobObjectW.restype = wintypes.HANDLE
kernel32.SetInformationJobObject.argtypes = [
wintypes.HANDLE,
ctypes.c_int,
ctypes.c_void_p,
wintypes.DWORD,
]
kernel32.SetInformationJobObject.restype = wintypes.BOOL
kernel32.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]
kernel32.AssignProcessToJobObject.restype = wintypes.BOOL
class JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure):
_fields_ = [
("PerProcessUserTimeLimit", ctypes.c_int64),
("PerJobUserTimeLimit", ctypes.c_int64),
("LimitFlags", wintypes.DWORD),
("MinimumWorkingSetSize", ctypes.c_size_t),
("MaximumWorkingSetSize", ctypes.c_size_t),
("ActiveProcessLimit", wintypes.DWORD),
("Affinity", ctypes.c_size_t),
("PriorityClass", wintypes.DWORD),
("SchedulingClass", wintypes.DWORD),
]
class IO_COUNTERS(ctypes.Structure):
_fields_ = [
("ReadOperationCount", ctypes.c_uint64),
("WriteOperationCount", ctypes.c_uint64),
("OtherOperationCount", ctypes.c_uint64),
("ReadTransferCount", ctypes.c_uint64),
("WriteTransferCount", ctypes.c_uint64),
("OtherTransferCount", ctypes.c_uint64),
]
class JOBOBJECT_EXTENDED_LIMIT_INFORMATION(ctypes.Structure):
_fields_ = [
("BasicLimitInformation", JOBOBJECT_BASIC_LIMIT_INFORMATION),
("IoInfo", IO_COUNTERS),
("ProcessMemoryLimit", ctypes.c_size_t),
("JobMemoryLimit", ctypes.c_size_t),
("PeakProcessMemoryUsed", ctypes.c_size_t),
("PeakJobMemoryUsed", ctypes.c_size_t),
]
job = kernel32.CreateJobObjectW(None, None)
if not job:
return None
info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION()
# JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE (0x2000) | JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK (0x1000)
info.BasicLimitInformation.LimitFlags = 0x2000 | 0x1000
# JobObjectExtendedLimitInformation = 9
if not kernel32.SetInformationJobObject(job, 9, ctypes.byref(info), ctypes.sizeof(info)):
return None
kernel32.AssignProcessToJobObject(job, wintypes.HANDLE(proc_handle))
return job
except Exception:
return None
def exec_host(args=None):
if args is None:
args = sys.argv[1:]
args = list(args)
if sys.platform.startswith("win"):
host = get_host()
if not host:
return
env = os.environ.copy()
env["_RCHITECT_HOST_ACTIVE"] = "1"
buf = ctypes.create_unicode_buffer(32768)
ctypes.windll.kernel32.GetModuleFileNameW(ctypes.c_void_p(sys.dllhandle), buf, 32768)
dll_path = buf.value
base_exe = getattr(sys, "_base_executable", sys.executable)
env["_RCHITECT_PYTHON_DLL"] = dll_path
env["_RCHITECT_BASE_EXE"] = base_exe
if os.path.normcase(sys.executable) != os.path.normcase(base_exe):
env["__PYVENV_LAUNCHER__"] = sys.executable
ctypes.windll.kernel32.SetConsoleCtrlHandler(None, True)
p = subprocess.Popen([host] + args, env=env)
_job = _assign_job_kill_on_close(int(p._handle)) # noqa: F841
sys.exit(p.wait())
else:
for i, arg in enumerate(args):
if arg.startswith("--r-binary=") and arg[11:]:
os.environ["R_BINARY"] = arg[11:]
elif arg == "--r-binary" and i + 1 < len(args) and args[i + 1]:
os.environ["R_BINARY"] = args[i + 1]
rhome = None
try:
rhome = get_rhome()
except Exception:
pass
env = os.environ.copy()
env["_RCHITECT_HOST_ACTIVE"] = "1"
if rhome and os.path.isdir(rhome):
_setup_unix_preload_env(rhome, env)
os.execve(sys.executable, [sys.executable] + args, env)
def maybe_reexec(args=None, module=None):
if not should_use_host():
return
if args is None:
reexec_args = ["-P"] if sys.version_info >= (3, 11) else []
if module:
reexec_args += ["-m", module] + sys.argv[1:]
else:
reexec_args += sys.argv
else:
reexec_args = list(args)
exec_host(reexec_args)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.