@raytrace-cli/cli 0.17.17 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,144 @@
1
+ """Regenerates the two generated tables of syscall_catalog.sql from gVisor's own
2
+ source for the runsc release setup.py installs. Run it when that release changes.
3
+
4
+ syscall_numbers every syscall number gVisor's table has, per architecture,
5
+ with whether gVisor implements it (pkg/sentry/syscalls/linux/linux64.go)
6
+ syscall_coverage which syscalls have a typed trace point, and its optional
7
+ fields (pkg/sentry/seccheck/metadata_{amd64,arm64}.go);
8
+ the rest are reported by number and six integers only
9
+
10
+ python3 worker/sandbox/catalog_numbers.py fetch the release and rewrite the file
11
+ python3 worker/sandbox/catalog_numbers.py --source DIR read the three files from DIR instead
12
+ python3 worker/sandbox/catalog_numbers.py --spike report.json
13
+ also record what spike_points.py saw arrive
14
+ python3 worker/sandbox/catalog_numbers.py --check change nothing; say what the catalog lacks
15
+
16
+ A name gVisor has and the catalog lacks is refused: write its row first, so
17
+ nothing the sandbox can be asked for is without a group. What a spike observed
18
+ is kept across runs for the same release and forgotten for a new one.
19
+ """
20
+ import argparse
21
+ import json
22
+ from pathlib import Path
23
+ import re
24
+ import sqlite3
25
+ import sys
26
+ import urllib.request
27
+
28
+ RELEASE = '20260817.0'
29
+ RAW = 'https://raw.githubusercontent.com/google/gvisor/release-{release}/{path}'
30
+ SOURCES = {'linux64.go': 'pkg/sentry/syscalls/linux/linux64.go',
31
+ 'metadata_amd64.go': 'pkg/sentry/seccheck/metadata_amd64.go',
32
+ 'metadata_arm64.go': 'pkg/sentry/seccheck/metadata_arm64.go'}
33
+ CATALOG = Path(__file__).with_name('syscall_catalog.sql')
34
+ SUPPORT = {'Supported': 'supported', 'SupportedPoint': 'supported',
35
+ 'PartiallySupported': 'partial', 'PartiallySupportedPoint': 'partial',
36
+ 'Error': 'unsupported', 'ErrorWithEvent': 'unsupported', 'CapError': 'unsupported'}
37
+ ROW = re.compile(r'^\s+(\d+):\s+syscalls\.(\w+)\("([a-z0-9_]+)"', re.M)
38
+ POINT = re.compile(r'addSyscallPoint\((\d+), "([a-z0-9_]+)", (nil|\[\]FieldDesc\{.*?\n\t\})\)', re.S)
39
+
40
+
41
+ def read(name, source):
42
+ if source:
43
+ return (Path(source) / name).read_text()
44
+ with urllib.request.urlopen(RAW.format(release=RELEASE, path=SOURCES[name]), timeout=60) as response:
45
+ return response.read().decode()
46
+
47
+
48
+ def numbers(table):
49
+ """{arch: [(sysno, name, support)]} from gVisor's two syscall tables."""
50
+ amd, arm, end = table.index('var AMD64'), table.index('var ARM64'), table.index('func init()')
51
+ found = {}
52
+ for arch, text in (('x86_64', table[amd:arm]), ('aarch64', table[arm:end])):
53
+ rows = [(int(number), name, SUPPORT[kind]) for number, kind, name in ROW.findall(text)]
54
+ if len(rows) < 250 or len({name for _, name, _ in rows}) != len(rows):
55
+ raise SystemExit(f'{arch}: gVisor\'s table did not parse as expected ({len(rows)} rows)')
56
+ found[arch] = sorted(rows)
57
+ return found
58
+
59
+
60
+ def points(*metadata):
61
+ """{name: [optional field]} for every syscall with a typed trace point."""
62
+ found = {}
63
+ for text in metadata:
64
+ for _, name, fields in POINT.findall(text):
65
+ found.setdefault(name, set()).update(re.findall(r'Name:\s+"([a-z0-9_]+)"', fields))
66
+ if len(found) < 40:
67
+ raise SystemExit(f'gVisor\'s trace point list did not parse as expected ({len(found)} points)')
68
+ return {name: sorted(fields) for name, fields in found.items()}
69
+
70
+
71
+ def catalog(sql):
72
+ """(each name the catalog has with the engine rule that reads it, what an earlier spike observed for this release)."""
73
+ db = sqlite3.connect(':memory:')
74
+ try:
75
+ db.executescript(sql)
76
+ names = dict(db.execute('SELECT syscall_name, effect_rule FROM syscall_catalog').fetchall())
77
+ seen = {name: (observed, fields) for name, observed, fields in db.execute(
78
+ 'SELECT syscall_name, observed, observed_fields FROM syscall_coverage WHERE gvisor_release = ?', (RELEASE,))}
79
+ finally:
80
+ db.close()
81
+ return names, seen
82
+
83
+
84
+ def quote(value):
85
+ return 'NULL' if value is None else str(value) if isinstance(value, int) else "'" + str(value).replace("'", "''") + "'"
86
+
87
+
88
+ def tuples(rows, per_line):
89
+ text = ['(' + ', '.join(quote(value) for value in row) + ')' for row in rows]
90
+ return ',\n'.join(', '.join(text[start:start + per_line]) for start in range(0, len(text), per_line))
91
+
92
+
93
+ def section(sql, name, body):
94
+ begin, end = f'-- BEGIN GENERATED {name}', f'-- END GENERATED {name}'
95
+ if begin not in sql or end not in sql:
96
+ raise SystemExit(f'{CATALOG.name} has no generated section named {name}')
97
+ head, rest = sql.split(begin, 1)
98
+ return head + begin + ' (catalog_numbers.py, gVisor release ' + RELEASE + '; do not edit by hand)\n' + body + '\n' + end + rest.split(end, 1)[1]
99
+
100
+
101
+ def main():
102
+ parser = argparse.ArgumentParser()
103
+ parser.add_argument('--source', help='a folder holding linux64.go, metadata_amd64.go and metadata_arm64.go')
104
+ parser.add_argument('--spike', help='the report spike_points.py wrote')
105
+ parser.add_argument('--check', action='store_true')
106
+ opts = parser.parse_args()
107
+ sql = CATALOG.read_text()
108
+ table = numbers(read('linux64.go', opts.source))
109
+ typed = points(read('metadata_amd64.go', opts.source), read('metadata_arm64.go', opts.source))
110
+ known, seen = catalog(sql)
111
+ names = sorted({name for rows in table.values() for _, name, _ in rows})
112
+ missing = [name for name in names if name not in known]
113
+ if missing:
114
+ raise SystemExit('The catalog has no row for: ' + ' '.join(missing))
115
+ if opts.spike:
116
+ report = json.loads(Path(opts.spike).read_text())
117
+ if report.get('release') != RELEASE:
118
+ raise SystemExit(f"That spike ran release {report.get('release')}, not {RELEASE}")
119
+ arrived = report.get('observed', {})
120
+ for name, call in arrived.items():
121
+ if name in known:
122
+ seen[name] = (1, json.dumps(sorted(call.get('fields', []))))
123
+ # Silence counts against a call only when the spike's work made that
124
+ # kind of call and none of its kind arrived: a program that deletes
125
+ # with unlinkat says nothing about unlink.
126
+ heard = {known[name] for name in arrived if name in known}
127
+ for name in report.get('subscribed', []):
128
+ if name not in arrived and known.get(name) in report.get('exercised_rules', []) and known[name] not in heard:
129
+ seen[name] = (0, '[]')
130
+ if opts.check:
131
+ print(f'{len(names)} syscall names in gVisor {RELEASE}, all in the catalog; {len(typed)} have a typed trace point.')
132
+ return
133
+ sql = section(sql, 'numbers', 'DELETE FROM syscall_numbers;\nINSERT INTO syscall_numbers (arch, sysno, syscall_name, support) VALUES\n'
134
+ + tuples([(arch, number, name, support) for arch, rows in table.items() for number, name, support in rows], 3) + ';')
135
+ coverage = [(RELEASE, name, 'syscall/' + name if name in typed else None, json.dumps(typed.get(name, [])),
136
+ seen.get(name, (None, '[]'))[0], seen.get(name, (None, '[]'))[1]) for name in names]
137
+ sql = section(sql, 'coverage', 'DELETE FROM syscall_coverage;\nINSERT INTO syscall_coverage (gvisor_release, syscall_name, point, optional_fields, observed, observed_fields) VALUES\n'
138
+ + tuples(coverage, 2) + ';')
139
+ CATALOG.write_text(sql)
140
+ print(f'{CATALOG.name}: {sum(len(rows) for rows in table.values())} numbers, {len(coverage)} coverage rows for gVisor {RELEASE}.', file=sys.stderr)
141
+
142
+
143
+ if __name__ == '__main__':
144
+ main()
@@ -0,0 +1,36 @@
1
+ """The RayTrace sandbox core: what runs on a sandbox host, as a library.
2
+
3
+ Two versions are kept, and checked separately by anything that runs on this core:
4
+
5
+ CORE_API the functions a host layer imports from core.mechanics and
6
+ core.release (arguments, results, errors, side effects),
7
+ written down in CORE_API.md
8
+ EVIDENCE_SCHEMA what the recorder hands on: the collector's event shapes,
9
+ the fact engine's facts and the syscall catalog
10
+
11
+ Raise one when what it covers changes in a way a consumer would notice.
12
+ """
13
+ import json
14
+ from pathlib import Path
15
+
16
+ CORE_API = 1
17
+ EVIDENCE_SCHEMA = 1
18
+
19
+ _HERE = Path(__file__).resolve().parent
20
+
21
+
22
+ def version():
23
+ """This core's package version: from the package it ships in, or the
24
+ VERSION file setup.py writes beside the installed copy; None if neither."""
25
+ for candidate in (_HERE.parent.parent.parent / 'package.json', _HERE.parent / 'VERSION'):
26
+ try:
27
+ text = candidate.read_text()
28
+ except OSError:
29
+ continue
30
+ if candidate.suffix == '.json':
31
+ data = json.loads(text)
32
+ if data.get('name') == '@raytrace-cli/cli':
33
+ return data.get('version')
34
+ elif text.strip():
35
+ return text.strip()
36
+ return None