File size: 28,191 Bytes
7f50cd1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Run one submission inside an isolated, disposable directory.

The grader and the self-check both run submissions this way. It encodes several grader-integrity
defences; read the comments before changing anything.
"""

from __future__ import annotations

import errno
import os
import pwd
import shutil
import stat
import signal
import subprocess
import tempfile
import threading
import time
from pathlib import Path

# The unprivileged account a method runs under. The grader refuses to start without it.
SOLVER_ACCOUNT = "solver"

# Size cap for submission output; check the size before reading.
MAX_OUTPUT_BYTES = 64 * 1024 * 1024

# build.sh runs once per round, not per instance.
BUILD_TIMEOUT_SEC = 900.0

# Env var carrying the per-instance wall-clock budget into run.sh (the run.sh
# contract is two positional args, so the budget travels in the environment).
BUDGET_ENV = "TASK_BUDGET_SEC"

STATUSES = frozenset({"ok", "timeout", "run_failed", "stray_processes",
                      "unreaped", "output_too_large", "output_not_regular_file"})

# The wall-clock seconds run.sh ran in the last _run call, from its start to its exit (or to the reap
# after a timeout); None when it never started. A round scored by its time reads it through the
# metric's {elapsed}: the caller hands it to package_common.ELAPSED. Every
# _run call sets it afresh, so it never describes another instance's run.
LAST_RUN_SEC: float | None = None

# Single-core timing: a package whose runs are each timed on one CPU runs several at once, each from a
# thread that pinned itself to one CPU first (run_wave). What _run learns about such a run is kept for
# that thread alone, never in a module global a neighbour's run could overwrite: THREAD.cpu, the CPU it
# holds; THREAD.run_sec, run.sh's seconds as LAST_RUN_SEC measures them; THREAD.cpu_sec, the CPU
# seconds of run.sh and of every process it waited for. A thread that pinned nothing runs as before.
THREAD = threading.local()
# What a pinned run's environment adds: one thread for the usual numeric libraries, and TMPDIR in the
# run's own work directory, so that runs going at once never share a temporary file.
ONE_THREAD = ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMEXPR_NUM_THREADS")

# Only a whitelist of env vars reaches the untrusted submission; the budget is added on top.
# CORE_DIR tells the method where the core's code is installed.
ALLOWED_ENV = ("PATH", "HOME", "LANG", "LC_ALL", "LC_CTYPE", "TZ", "TERM",
               "OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS",
               "NUMEXPR_NUM_THREADS", "CORE_DIR")


def _child_env(**extra: str) -> dict:
    env = {k: os.environ[k] for k in ALLOWED_ENV if k in os.environ}
    env.update(extra)
    return env


def solver_ids() -> tuple[int, int] | None:
    try:
        e = pwd.getpwnam(SOLVER_ACCOUNT)
    except KeyError:
        return None
    return e.pw_uid, e.pw_gid


def _exited(entry: str) -> bool:
    # A zombie has exited and holds nothing but its pid until its parent waits for it -- for the
    # method's own process that is proc.wait(), after the reap, so counting it made every timed-out
    # run wait out the reap's two seconds. One thread only: a process whose main thread has exited
    # while another still runs reads "Z" too.
    try:
        with open(f"/proc/{entry}/stat", "rb") as f:
            fields = f.read().rsplit(b") ", 1)[1].split()
    except (OSError, IndexError):
        return False
    return len(fields) > 17 and fields[0] == b"Z" and fields[17] == b"1"


def _group_members(pgid: int) -> list[int]:
    """Read /proc, not killpg(pgid, 0): EPERM there proves the group exists, not that it is empty."""
    members = []
    for entry in os.listdir("/proc"):
        if not entry.isdigit():
            continue
        try:
            with open(f"/proc/{entry}/stat", "rb") as f:
                fields = f.read().rsplit(b") ", 1)[1].split()
        except (OSError, IndexError):
            continue
        if _exited(entry):
            continue
        # Fields after comm: state ppid pgrp ...
        if len(fields) > 2 and fields[2] == str(pgid).encode():
            members.append(int(entry))
    return members


def _reap_group(pgid: int) -> list[int]:
    """Kill the process group and wait; returns pids still alive (empty means clean)."""
    try:
        os.killpg(pgid, signal.SIGKILL)
    except ProcessLookupError:
        return []
    except PermissionError:
        return _group_members(pgid)           # cannot kill: report, do not swallow
    for _ in range(40):
        remaining = _group_members(pgid)
        if not remaining:
            return []
        time.sleep(0.05)
    return _group_members(pgid)


def _uid_processes(uid: int) -> list[int]:
    """Scan by uid, since setsid leaves the process group but cannot change uid."""
    out = []
    for entry in os.listdir("/proc"):
        if not entry.isdigit():
            continue
        if _exited(entry):
            continue
        try:
            with open(f"/proc/{entry}/status", "rb") as f:
                for line in f:
                    if line.startswith(b"Uid:"):
                        if int(line.split()[1]) == uid:
                            out.append(int(entry))
                        break
        except (OSError, IndexError, ValueError):
            continue
    return out


def _reap_uid(uid: int) -> list[int]:
    """Kill every process owned by uid; returns pids still alive."""
    if os.getuid() == uid:
        # Killing by uid would kill the grader itself.
        return []
    me = os.getpid()
    for pid in _uid_processes(uid):
        if pid == me:
            continue
        try:
            os.kill(pid, signal.SIGKILL)
        except (ProcessLookupError, PermissionError):
            pass
    for _ in range(40):
        remaining = _uid_processes(uid)
        if not remaining:
            return []
        time.sleep(0.05)
    return _uid_processes(uid)


def _run(submission_dir: Path, data_dir: Path, out_dir: Path, work_dir: Path,
         budget_sec: float, solver: tuple[int, int] | None) -> str:
    """Returns ok / timeout / run_failed / stray_processes / unreaped."""
    no_new_privs()
    _drop_set_id_bits(submission_dir)
    global LAST_RUN_SEC
    LAST_RUN_SEC = None
    THREAD.run_sec = THREAD.cpu_sec = None
    # An executable run.sh runs by its shebang; without the executable bit, under /bin/sh.
    entry = submission_dir / "run.sh"
    cmd = ([str(entry)] if os.access(entry, os.X_OK) else ["/bin/sh", str(entry)]) + [str(data_dir), str(out_dir)]
    # The run.sh contract is fixed at two arguments, so the budget travels in the environment.
    env = _child_env(**{BUDGET_ENV: f"{budget_sec:.3f}"})
    if pinned():
        env.update(dict.fromkeys(ONE_THREAD, "1"), TMPDIR=str(work_dir))
    if pinned() and OOM_RESTORE is not None:
        # The run gets back the out-of-memory score this process gave up (protect_self) before run.sh starts,
        # or does not start. What it then runs is what Popen below would run, its /bin/sh fallback included.
        if cmd[0] != "/bin/sh" and not _runs_directly(entry):
            cmd = ["/bin/sh"] + cmd
        cmd = ["/bin/sh", "-c", f'echo {OOM_RESTORE} > /proc/self/oom_score_adj || exit 125; exec "$@"', "sh"] + cmd
    kwargs: dict = dict(cwd=str(work_dir), stdout=subprocess.DEVNULL,
                        stderr=subprocess.DEVNULL, start_new_session=True, env=env)
    if solver is not None:
        # extra_groups=[]: otherwise the child keeps root's supplementary groups.
        kwargs["user"], kwargs["group"], kwargs["extra_groups"] = solver[0], solver[1], []

    status = "ok"
    t0 = time.monotonic()
    try:
        proc = subprocess.Popen(cmd, **kwargs)
    except OSError:                               # no usable shebang, or not runnable
        if cmd[0] == "/bin/sh":
            return "run_failed"
        try:
            proc = subprocess.Popen(["/bin/sh", *cmd], **kwargs)
        except OSError:
            return "run_failed"
    pgid = os.getpgid(proc.pid)
    if pinned():
        _count(proc)
    try:
        if proc.wait(timeout=budget_sec) != 0:
            status = "run_failed"
    except subprocess.TimeoutExpired:
        status = "timeout"
        _reap_group(pgid)
        proc.wait()
    LAST_RUN_SEC = round(time.monotonic() - t0, 3)
    THREAD.run_sec = round(time.monotonic() - t0, 3)

    # Check after timeouts too: forked background processes survive proc.wait().
    leftovers = _group_members(pgid)
    if leftovers:
        still = _reap_group(pgid)
        if still:
            status = "unreaped"
        elif status == "ok":
            status = "stray_processes"

    # A pinned run's pass by uid looks only at its own CPU: the account's other processes are its neighbours'.
    if pinned():
        return _reap_core(kwargs.get("user"), status)

    # Second pass by uid: reap the group first, then catch whatever left it.
    if solver is not None and os.getuid() != solver[0]:
        left_group = _uid_processes(solver[0])
        if left_group:
            still = _reap_uid(solver[0])
            if still:
                status = "unreaped"
            elif status == "ok":
                status = "stray_processes"
    return status


def _read_output(out_path: Path, instance_name: str) -> tuple[bytes | None, str | None]:
    """Read one file the submission wrote; returns (text, overriding status or None).

    O_NOFOLLOW: refuse a symlinked output, and fstat for a regular file, so the
    root-owned grader cannot be pointed at sealed data or an infinite device;
    size and read share one fd so the file cannot be swapped underneath.
    """
    try:
        # O_NONBLOCK: opening a FIFO the submission left behind must not hang the grader.
        fd = os.open(out_path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
    except FileNotFoundError:
        return None, None
    except OSError as e:
        if e.errno in (errno.ELOOP, errno.EMLINK):
            return None, "output_not_regular_file"
        raise RuntimeError(
            f"cannot open the output of {instance_name}: {type(e).__name__}: {e}") from e
    try:
        st = os.fstat(fd)
        if not stat.S_ISREG(st.st_mode):
            return None, "output_not_regular_file"
        if st.st_size > MAX_OUTPUT_BYTES:
            return None, "output_too_large"
        # Still read with a cap: st_size need not match what is readable.
        data = b""
        while len(data) <= MAX_OUTPUT_BYTES:
            chunk = os.read(fd, 1 << 20)
            if not chunk:
                break
            data += chunk
        if len(data) > MAX_OUTPUT_BYTES:
            return None, "output_too_large"
    except OSError as e:
        raise RuntimeError(
            f"cannot read the output of {instance_name}: {type(e).__name__}: {e}") from e
    finally:
        os.close(fd)
    return data, None


def stage_and_run(submission_dir: Path, data_dir: Path, outputs: tuple[str, ...],
                  budget_sec: float, solver: tuple[int, int] | None):
    """Run the method once in a disposable staging dir; returns (status, {name: bytes or None}).

    Layout: <root>/data holds the measurements the method may read (read-only), <root>/work
    belongs to the solver and is where it writes its files. The directory names are constant so a
    method cannot tell from the path which instance it is working on.
    """
    root = Path(tempfile.mkdtemp(prefix="run_"))
    try:
        staged, work = root / "data", root / "work"
        shutil.copytree(data_dir, staged)
        for path in staged.rglob("*"):
            path.chmod(0o444 if path.is_file() else 0o555)
        staged.chmod(0o555)
        work.mkdir()
        if solver is not None:
            os.chown(work, solver[0], solver[1])
            work.chmod(0o700)
        else:
            work.chmod(0o755)
        root.chmod(0o755)

        status = _run(submission_dir, staged, work, work, budget_sec, solver)
        texts = {}
        for name in outputs:
            text, read_status = _read_output(work / name, name)
            texts[name] = text
            if read_status is not None:
                status = read_status
        return status, texts
    finally:
        # No ignore_errors: this dir holds a copy of the instance's inputs, which may be sealed,
        # so a failed cleanup is a leak and must be reported.
        try:
            shutil.rmtree(root)
        except OSError as e:
            raise RuntimeError(
                f"cannot clean up staging dir {root}: {type(e).__name__}: {e}") from e
        if root.exists():
            raise RuntimeError(f"staging dir {root} still exists; measurements may leak")


def build_submission(submission_dir: Path, solver) -> tuple[bool, str]:
    """Run the submission's build.sh once; returns (ok, note). No build.sh counts as success.

    stderr goes to a temp file rather than a pipe (a pipe waits for EOF, so a
    build.sh handing stdout to a background process would burn the whole budget);
    the whole process group is reaped, then uid as a backstop; and a failure to
    launch is infrastructure, so it raises instead of scoring the submission 0.
    """
    no_new_privs()
    script = submission_dir / "build.sh"
    if not script.exists():
        return True, "submission has no build.sh"

    # Build artifacts land in the submission dir, and the build runs unprivileged,
    # so the tree has to be handed over first or a compiler write fails with EACCES.
    if solver is not None:
        # Hand the tree to the unprivileged account. Walk without following
        # symlinks and refuse any link, so chown cannot cross into root-owned
        # sealed data; lchown double-guards.
        if submission_dir.is_symlink():
            return False, "submission dir is a symlink"
        try:
            os.lchown(submission_dir, solver[0], solver[1])
            for cur, dirs, files in os.walk(submission_dir):
                for name in dirs + files:
                    p = os.path.join(cur, name)
                    if os.path.islink(p):
                        return False, f"submission contains a symlink: {name}"
                    os.lchown(p, solver[0], solver[1])
        except OSError as e:
            raise RuntimeError(
                f"cannot hand submission dir {submission_dir} to the unprivileged "
                f"account: {type(e).__name__}: {e}") from e

    with tempfile.TemporaryFile() as err:
        kwargs: dict = dict(cwd=str(submission_dir), stdout=subprocess.DEVNULL,
                            stderr=err, start_new_session=True, env=_child_env())
        if solver is not None:
            # extra_groups=[]: otherwise the child keeps root's supplementary groups.
            kwargs["user"], kwargs["group"], kwargs["extra_groups"] = solver[0], solver[1], []
        try:
            proc = subprocess.Popen(["/bin/sh", str(script)], **kwargs)
        except OSError as e:
            raise RuntimeError(
                f"cannot execute {script}: {type(e).__name__}: {e}."
                " This is an infrastructure failure, not the submission's fault,"
                " so the round is aborted rather than scored 0.") from e

        pgid = os.getpgid(proc.pid)
        timed_out = False
        try:
            rc = proc.wait(timeout=BUILD_TIMEOUT_SEC)
        except subprocess.TimeoutExpired:
            timed_out, rc = True, None
            _reap_group(pgid)
            proc.wait()

        left = _reap_group(pgid)      # reap grandchildren even on a clean exit
        if solver is not None:        # the process group cannot hold setsid; uid can
            left = left or _reap_uid(solver[0])
        err.seek(0)
        tail = err.read()[-300:].decode(errors="replace")

    if timed_out:
        return False, f"build.sh did not finish within {BUILD_TIMEOUT_SEC:.0f} s"
    if left:
        return False, f"build.sh left unkillable processes {left}"
    if rc != 0:
        return False, f"build.sh exited with code {rc}: {tail}"
    return True, "build succeeded"


# ---------------------------------------------------------------- single-core timing

# Each CPU's thread_siblings_list names the CPUs of its physical core.
CPU_SYS = Path("/sys/devices/system/cpu")
# The out-of-memory score a run is given back once protect_self() has lowered this process's; None until then.
OOM_RESTORE: str | None = None


def pinned() -> bool:
    """Is this thread running a pinned run (run_wave)?"""
    return getattr(THREAD, "cpu", None) is not None


def _cpu_list(text: str) -> set[int]:
    """"0-1,28" -> {0, 1, 28}."""
    out = set()
    for part in text.strip().split(","):
        lo, _, hi = part.partition("-")
        out.update(range(int(lo), int(hi or lo) + 1))
    return out


def core_cpus(k: int) -> list[int]:
    """k CPUs this process may use, each on a physical core of its own: the lowest allowed CPU of each core,
    cores in order. Two CPUs of one core are hyperthreads sharing it, so a run on each is not a run on one core
    each. Raises RuntimeError when the topology cannot be read or fewer than k cores are allowed: a run timed on
    one core must not be timed on half of one."""
    allowed = sorted(os.sched_getaffinity(0))
    seen, out = set(), []
    for cpu in allowed:
        try:
            core = frozenset(_cpu_list((CPU_SYS / f"cpu{cpu}" / "topology" / "thread_siblings_list").read_text()))
        except (OSError, ValueError) as e:
            raise RuntimeError(f"cannot read which core CPU {cpu} belongs to: {type(e).__name__}: {e}") from e
        if core not in seen:
            seen.add(core)
            out.append(cpu)
    if len(out) < k:
        raise RuntimeError(f"{k} runs at once need {k} physical cores, and this container may use {len(out)} "
                           f"(CPUs {allowed}); stopping rather than time runs on shared cores")
    return out[:k]


def protect_self(on: bool = True) -> bool:
    """While runs go at once, keep the out-of-memory killer off this process where that is permitted, so that it
    takes a run first; each pinned run sets its own score back to this process's before run.sh starts (_run).
    protect_self(False) gives this process its score back too, so that nothing started after the runs inherits
    the protection. Returns whether the protection holds."""
    global OOM_RESTORE
    if not on:
        if OOM_RESTORE is not None:
            try:
                with open("/proc/self/oom_score_adj", "w") as fh:
                    fh.write(OOM_RESTORE)
            except OSError:
                pass
            OOM_RESTORE = None
        return False
    try:
        with open("/proc/self/oom_score_adj") as fh:
            before = str(int(fh.read().strip()))
        with open("/proc/self/oom_score_adj", "w") as fh:
            fh.write("-1000")
    except (OSError, ValueError):
        return False
    OOM_RESTORE = before
    return True


def _runs_directly(entry: Path) -> bool:
    """Would the kernel start this file itself, as Popen tries first? A binary, or a script whose #! names an
    interpreter file it may run (the name ends at a space, a tab or the line's end, so a stray carriage return is
    part of it). Anything else Popen hands to /bin/sh instead."""
    try:
        with open(entry, "rb") as fh:
            head = fh.read(256)
    except OSError:
        return False
    if not head.startswith(b"#!"):
        return head.startswith(b"\x7fELF")
    name = head[2:].split(b"\n", 1)[0].lstrip(b" \t").replace(b"\t", b" ").split(b" ", 1)[0]
    return bool(name) and os.path.isfile(name) and os.access(name, os.X_OK)


def _count(proc) -> None:
    """A pinned run's process: its wait reaps it with wait4, so that this thread learns the run's CPU seconds
    (THREAD.cpu_sec), which the process-wide total of children cannot split between runs going at once."""

    def wait(timeout=None):
        if proc.returncode is not None:
            return proc.returncode
        end = None if timeout is None else time.monotonic() + timeout
        pause = 0.0005
        while True:
            pid, code, usage = os.wait4(proc.pid, 0 if end is None else os.WNOHANG)
            if pid == proc.pid:
                proc.returncode = os.waitstatus_to_exitcode(code)
                THREAD.cpu_sec = round(usage.ru_utime + usage.ru_stime, 3)
                return proc.returncode
            left = end - time.monotonic()
            if left <= 0:
                raise subprocess.TimeoutExpired(proc.args, timeout)
            time.sleep(min(pause, left))
            pause = min(pause * 2, 0.05)
    proc.wait = wait


def _core_processes(uid: int, cpu: int) -> list[int]:
    """The processes of uid whose affinity is this one CPU alone."""
    out = []
    for pid in _uid_processes(uid):
        try:
            if os.sched_getaffinity(pid) == {cpu}:
                out.append(pid)
        except OSError:
            continue
    return out


def _reap_core(uid, status: str) -> str:
    """A pinned run's pass by uid: the account's processes still on this run's CPU, which only this run can have
    left there, are killed, and the run then counts as one that left processes behind. A process that moved off
    its CPU is the wave's to find (run_wave); no neighbour's process is touched here."""
    if uid is None or uid == os.getuid():
        return status
    found = False
    for _ in range(40):
        left = _core_processes(uid, THREAD.cpu)
        if not left:
            return "stray_processes" if found and status == "ok" else status
        found = True
        for pid in left:
            try:
                os.kill(pid, signal.SIGKILL)
            except (ProcessLookupError, PermissionError):
                pass
        time.sleep(0.05)
    return "unreaped"


def read_only_method(method: Path) -> None:
    """The method directory, read-only for every run: runs going at once share it, so a write by one would reach
    the others. Where this process is root the tree becomes root's (an owner could make it writable again); nobody
    else may write it, everyone may read it, and set-id bits are dropped. Links are neither followed nor changed."""
    method = Path(method)
    if method.is_symlink():
        raise RuntimeError(f"the method directory {method} is a link")
    root = os.geteuid() == 0
    entries = [str(method)]
    for cur, dirs, files in os.walk(method):
        entries += [os.path.join(cur, name) for name in dirs + files]
    for p in entries:
        st = os.lstat(p)
        if stat.S_ISLNK(st.st_mode):
            continue
        if root:
            os.lchown(p, 0, 0)
        mode = (stat.S_IMODE(st.st_mode) & ~0o7022) | 0o444
        if stat.S_ISDIR(st.st_mode) or st.st_mode & 0o100:
            mode |= 0o111
        os.chmod(p, mode)


def run_wave(calls: list, cpus: list[int], uid) -> list[dict]:
    """Make every call at once, call j from a thread that first pins itself to cpus[j] alone, so that every process
    its run starts inherits that one CPU. A call is stage_and_run bound to its arguments. Returns, per call:
    status, texts, run_sec (the call's wall seconds, as a run made alone is timed), last_run_sec (run.sh's own, as
    LAST_RUN_SEC reads them), cpu_sec and cpu.

    Once every call has returned, a process of uid still alive has left its CPU and outlived its run, so it cannot
    be traced to one run: it is killed, and every run of the wave that ended "ok" becomes "stray_processes" (all
    of them "unreaped" where it cannot be killed). An error in a call is raised here, after the wave has ended; a
    wave does not start where the container no longer holds one of its CPUs, and one that lost a CPU while it ran
    raises once it has ended."""
    lost = set(cpus) - os.sched_getaffinity(0)
    if lost:
        raise RuntimeError(f"CPUs {sorted(lost)} are no longer this container's; stopping rather than time runs "
                           "on CPUs it no longer holds")
    out: list = [None] * len(calls)

    def one(j: int) -> None:
        try:
            os.sched_setaffinity(0, {cpus[j]})          # this thread alone; what it starts inherits it
            THREAD.cpu = cpus[j]
            t0 = time.time()
            status, texts = calls[j]()
            out[j] = {"status": status, "texts": texts, "run_sec": round(time.time() - t0, 3),
                      "last_run_sec": getattr(THREAD, "run_sec", None),
                      "cpu_sec": getattr(THREAD, "cpu_sec", None), "cpu": cpus[j]}
        except BaseException as e:                     # noqa: BLE001 - raised below, once the wave has ended
            out[j] = e

    threads = [threading.Thread(target=one, args=(j,), daemon=True) for j in range(len(calls))]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    moved = set(cpus) - os.sched_getaffinity(0)       # a CPU taken away while the wave ran unpins its run
    if uid is not None and uid != os.getuid() and _uid_processes(uid):
        still = _reap_uid(uid)
        for r in out:
            if isinstance(r, dict) and (still or r["status"] == "ok"):
                r["status"] = "unreaped" if still else "stray_processes"
    for r in out:
        if isinstance(r, BaseException):
            raise r
    if moved:
        raise RuntimeError(f"CPUs {sorted(moved)} stopped being this container's while a wave ran on them; "
                           "its runs were not timed on one CPU each")
    return out


# ---------------------------------------------------------------- set-id bits, dropped before a method's first run
# A method's files run under the method's account: before the first run of a method directory, every set-id bit of a
# regular file in it is dropped, once per directory and process, and no run starts until that is done. Owners and
# permissions stay as they are.
import os as _os
import stat as _stat
import threading as _threading

_SET_ID_DONE: set = set()
_SET_ID_GUARD = _threading.Lock()
_SET_ID_BITS = _stat.S_ISUID | _stat.S_ISGID


def _drop_set_id_bits(method) -> None:
    """Links are neither followed nor changed: each file is opened without following a link, and checked again."""
    method = _os.path.realpath(method)
    with _SET_ID_GUARD:
        if method in _SET_ID_DONE:
            return
        for cur, _dirs, files in _os.walk(method):
            for name in files:
                p = _os.path.join(cur, name)
                st = _os.lstat(p)
                if not (_stat.S_ISREG(st.st_mode) and st.st_mode & _SET_ID_BITS):
                    continue
                fd = _os.open(p, _os.O_RDONLY | _os.O_NOFOLLOW | _os.O_NONBLOCK)
                try:
                    st = _os.fstat(fd)
                    if _stat.S_ISREG(st.st_mode):
                        _os.fchmod(fd, _stat.S_IMODE(st.st_mode) & ~_SET_ID_BITS)
                finally:
                    _os.close(fd)
        _SET_ID_DONE.add(method)


# ---------------------------------------------------------------- no new privileges, before build.sh and every run
# prctl(2)'s PR_SET_NO_NEW_PRIVS. build.sh and every run start from a thread that has set it (no_new_privs), so
# nothing they start gains privileges by exec: a set-id program, the method's or the image's, runs as their account.
PR_SET_NO_NEW_PRIVS = 38


def no_new_privs() -> None:
    """Set PR_SET_NO_NEW_PRIVS on the calling thread, which every process it starts inherits; this process, root
    already where a submission takes an account, gains nothing by exec and so loses nothing. Raises RuntimeError
    where it cannot, since the submission could then gain privileges its account does not have."""
    try:
        import ctypes
        libc = ctypes.CDLL(None, use_errno=True)
        if libc.prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) == 0:
            return
        why = _os.strerror(ctypes.get_errno())
    except (ImportError, OSError, AttributeError) as e:
        why = f"{type(e).__name__}: {e}"
    raise RuntimeError(f"cannot keep a submission from gaining privileges ({why}); stopping rather than run it")