File size: 8,941 Bytes
902d2bb | 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 | # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: CC-BY-NC-4.0
"""No native build or load at run time: a static check, and a guard inside the eval process."""
from __future__ import annotations
import ast
import importlib.abc
import os
import re
import sys
from .. import harness
# The rule. A Python-language solution may not build or load native code at run time (C++ /
# CUDA extension builds, ctypes library loads, NVRTC kernels, nvcc) and may not start processes.
# A C++-language solution is built by the harness itself; its code may not start processes,
# compile or link code at run time, or run embedded Python. DSL JITs (Triton, CuTe DSL) are fine.
CPP_LANGS = frozenset({"cuda_cpp", "cutlass", "cudnn", "cublas"})
NATIVE_EXTS = (".cu", ".cuh", ".c", ".cc", ".cpp", ".cxx", ".h", ".hpp", ".ptx", ".cubin", ".so")
_EXEC = ("l", "le", "lp", "lpe", "v", "ve", "vp", "vpe")
PY_BANNED = frozenset(
["tvm_ffi.cpp." + f for f in ("load_inline", "load", "build", "build_inline")]
+ ["torch.utils.cpp_extension." + f for f in ("load", "load_inline")]
+ ["os." + f for f in ("system", "popen", "posix_spawn", "posix_spawnp")]
+ ["os.exec" + s for s in _EXEC] + ["os.spawn" + s for s in _EXEC]
+ ["ctypes.CDLL", "ctypes.PyDLL", "torch.ops.load_library", "torch.classes.load_library",
"cupy.RawKernel", "cupy.RawModule", "cuda.core.Program", "cuda.core.experimental.Program"])
PY_BANNED_PREFIXES = ("subprocess.", "ctypes.cdll.", "ctypes.pydll.") # any use of these
_JIT_WORDS = re.compile(r"\bnvcc\b|nvrtc", re.I)
CPP_RULES = (
("process_spawn", re.compile(r"(?<![\w.>:])(?:std::)?(?:popen|system|fork|vfork"
r"|exec[lv]p?e?|posix_spawnp?)\s*\(")),
("runtime_compile", re.compile(r"\b(?:nvrtc(?:CreateProgram|CompileProgram)"
r"|cuLink(?:Create|AddData|AddFile|Complete)\w*|nvJitLink\w+"
r"|nvPTXCompiler\w+)\s*\(|lib(?:nvrtc|nvJitLink|nvptxcompiler)")),
("embedded_python", re.compile(r"\b(?:py::exec|py::eval|PyRun_\w+|Py_(?:Main|BytesMain|RunMain))"
r"\s*\(")),
)
def import_aliases(tree) -> dict:
"""Local name -> dotted path, from the import statements of one Python module."""
out = {}
for n in ast.walk(tree):
if isinstance(n, ast.Import):
for a in n.names:
out[a.asname or a.name.split(".")[0]] = a.name if a.asname else a.name.split(".")[0]
elif isinstance(n, ast.ImportFrom) and n.module and not n.level:
for a in n.names:
out[a.asname or a.name] = n.module + "." + a.name
return out
def dotted(node, aliases) -> str | None:
"""`a.b.c` for a Name / Attribute chain, its first name resolved through the imports."""
parts = []
while isinstance(node, ast.Attribute):
parts.append(node.attr)
node = node.value
if not isinstance(node, ast.Name):
return None
parts.append(aliases.get(node.id, node.id))
return ".".join(reversed(parts))
def _banned(name) -> bool:
name = name or ""
return name in PY_BANNED or name == "subprocess" or name.startswith(PY_BANNED_PREFIXES)
def _py_findings(path, text, native_files) -> list:
try:
tree = ast.parse(text)
except SyntaxError: # the harness will fail it anyway; read the text
hit = re.search(r"\bsubprocess\b|load_inline|cpp_extension|\bos\.system\b|RawKernel",
harness.code_only(path, text))
return [["native_call", path, 0]] if hit else []
aliases, found = import_aliases(tree), []
docs = {id(n.body[0].value) for n in ast.walk(tree)
if isinstance(n, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef))
and n.body and isinstance(n.body[0], ast.Expr)}
for n in ast.walk(tree):
names = []
if isinstance(n, ast.Import):
names = [a.name for a in n.names]
elif isinstance(n, ast.ImportFrom) and n.module and not n.level:
names = [n.module] + [n.module + "." + a.name for a in n.names]
elif isinstance(n, ast.Attribute):
names = [dotted(n, aliases)]
elif isinstance(n, ast.Name):
names = [aliases.get(n.id, n.id)]
elif isinstance(n, ast.Call) and dotted(n.func, aliases) in ("importlib.import_module",
"__import__"):
arg = n.args[0] if n.args else None
names = [arg.value] if isinstance(arg, ast.Constant) and isinstance(arg.value, str) else []
names = [x + ".load_inline" if x.startswith("tvm_ffi.cpp") else x for x in names]
elif isinstance(n, ast.Constant) and isinstance(n.value, str) and id(n) not in docs:
if _JIT_WORDS.search(n.value):
found.append(["jit_compiler", path, n.lineno])
elif os.path.basename(n.value.strip()) in native_files:
found.append(["native_source", path, n.lineno])
if any(_banned(x) for x in names):
found.append(["native_call", path, n.lineno])
return found
def _cpp_findings(path, text) -> list:
code = harness.code_only(path, text)
return [[kind, path, code.count("\n", 0, m.start()) + 1]
for kind, rx in CPP_RULES for m in rx.finditer(code)]
def check(sol: dict) -> dict:
"""{"verdict": "clean" | "violation", "findings": [[kind, path, line]]} for one solution."""
langs = set((sol.get("spec") or {}).get("languages") or [])
srcs = [s for s in sol.get("sources") or [] if isinstance(s, dict)]
native = {os.path.basename(str(s.get("path") or "")) for s in srcs
if str(s.get("path") or "").lower().endswith(NATIVE_EXTS)}
found = []
for s in srcs:
path, text = str(s.get("path") or ""), str(s.get("content") or "")
if langs & CPP_LANGS:
if path.lower().endswith(harness.C_LIKE):
found += _cpp_findings(path, text)
elif path.endswith(".py"):
found += _py_findings(path, text, native)
found = sorted({tuple(f) for f in found}, key=lambda f: (f[1], f[2], f[0]))
return {"verdict": "violation" if found else "clean", "findings": [list(f) for f in found[:20]]}
# -- the guard inside the eval process (Python-language solutions) -------------------------------
# After one of these modules runs its body, its build and load helpers raise instead.
GUARDED = {"tvm_ffi.cpp": ("load_inline", "load", "build", "build_inline"),
"tvm_ffi.cpp.extension": ("load_inline", "load", "build", "build_inline"),
"torch.utils.cpp_extension": ("load", "load_inline")}
GUARD_SNIPPET = ("from compoundingkernel.checks.native_code import install_runtime_guard\n"
"install_runtime_guard()")
def _refuse(*args, **kwargs):
raise RuntimeError("native_build_refused") # a code, like every result of this package
def _patch(module):
for helper in GUARDED.get(getattr(module, "__name__", ""), ()):
if hasattr(module, helper):
setattr(module, helper, _refuse)
class _Loader(importlib.abc.Loader):
"""The real loader, then the patch, before any importer can bind a name."""
def __init__(self, loader):
self._loader = loader
def create_module(self, spec):
return self._loader.create_module(spec)
def exec_module(self, module):
self._loader.exec_module(module)
_patch(module)
def __getattr__(self, name):
return getattr(self._loader, name)
class _Finder(importlib.abc.MetaPathFinder):
def find_spec(self, name, path=None, target=None):
if name not in GUARDED:
return None
for finder in sys.meta_path:
if finder is self or not hasattr(finder, "find_spec"):
continue
spec = finder.find_spec(name, path, target)
if spec is not None:
if spec.loader is not None and hasattr(spec.loader, "exec_module"):
spec.loader = _Loader(spec.loader)
return spec
return None
def install_runtime_guard():
"""Turn the guard on in this process (guard_env runs this in the harness's eval process)."""
for name in GUARDED:
if name in sys.modules:
_patch(sys.modules[name])
if not any(isinstance(f, _Finder) for f in sys.meta_path):
sys.meta_path.insert(0, _Finder())
def guard_env(env, sol: dict, site_dir: str):
"""The harness env with the runtime guard on, for a Python-language solution (else unchanged)."""
if set((sol.get("spec") or {}).get("languages") or []) & CPP_LANGS:
return env
root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
return harness.site_env(env, [GUARD_SNIPPET], site_dir, [root])
|