Repository navigation
Expand file tree
/
Copy pathfetch_kernel_source.py
More file actions
182 lines (156 loc) · 7.02 KB
/
Copy pathfetch_kernel_source.py
File metadata and controls
182 lines (156 loc) · 7.02 KB
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
#!/usr/bin/env python3
"""Resolve one ModAVD system-image kernel target to its exact kernel/common source.
Steps (no device, no full 1.5 GiB system image download):
1. Range-read `kernel-ranchu` out of the official Google system image zip.
2. Verify its bzImage version string matches `kernel_release` and `build_id`.
3. Fetch the ci.android.com manifest for that Build ID and extract `kernel/common` revision.
4. Fetch that exact Git commit and archive the verified tree.
"""
import argparse
import hashlib
import io
import json
import re
import shlex
import subprocess
import struct
import sys
import time
from tempfile import TemporaryDirectory
import urllib.request
import xml.etree.ElementTree as ET
import zipfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent
TARGETS = ROOT / "targets.json"
MANIFEST_URL = "https://ci.android.com/builds/submitted/{bid}/kernel_virt_x86_64/latest/raw/manifest_{bid}.xml"
KERNEL_REMOTE = "https://android.googlesource.com/kernel/common"
UA = {"User-Agent": "ModAVD-ksu-lkm"}
def http_get(url, headers=None, retries=4):
for i in range(retries):
try:
req = urllib.request.Request(url, headers={**UA, **(headers or {})})
return urllib.request.urlopen(req, timeout=120)
except Exception as e:
if i == retries - 1:
raise
print(f" retry {url}: {e}", file=sys.stderr)
time.sleep(5 * (i + 1))
class HttpRangeFile(io.RawIOBase):
"""Seekable read-only stream over HTTP Range requests (for zipfile central directory)."""
def __init__(self, url):
self.url, self.pos = url, 0
with http_get(url, {"Range": "bytes=0-0"}) as r:
cr = r.headers.get("Content-Range", "")
if not cr.startswith("bytes "):
raise RuntimeError(f"server does not support Range: {url}")
self.size = int(cr.rsplit("/", 1)[1])
def seekable(self):
return True
def readable(self):
return True
def tell(self):
return self.pos
def seek(self, off, whence=0):
self.pos = {0: off, 1: self.pos + off, 2: self.size + off}[whence]
return self.pos
def readinto(self, b):
if self.pos >= self.size or len(b) == 0:
return 0
end = min(self.pos + len(b), self.size) - 1
with http_get(self.url, {"Range": f"bytes={self.pos}-{end}"}) as r:
expected = f"bytes {self.pos}-{end}/{self.size}"
if r.status != 206 or r.headers.get("Content-Range") != expected:
raise RuntimeError(f"unexpected Content-Range for {self.url}")
data = r.read(end - self.pos + 2)
if len(data) != end - self.pos + 1:
raise RuntimeError(f"incomplete HTTP range for {self.url}")
b[: len(data)] = data
self.pos += len(data)
return len(data)
def kernel_release(bzimage: bytes) -> str:
"""Read x86 bzImage boot-protocol kernel_version string (offset at 0x20E + 0x200)."""
off = struct.unpack_from("<H", bzimage, 0x20E)[0] + 0x200
return bzimage[off : bzimage.index(b"\0", off)].decode("ascii").split(" ")[0]
def load_target(tid: str):
cfg = json.loads(TARGETS.read_text(encoding="utf-8"))
for t in cfg["targets"]:
if t["id"] == tid:
return cfg, t
sys.exit(f"unknown target {tid}; known: {[t['id'] for t in cfg['targets']]}")
def main():
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--target", required=True)
ap.add_argument("--out", required=True, type=Path)
ap.add_argument("--skip-tarball", action="store_true")
a = ap.parse_args()
cfg, t = load_target(a.target)
a.out.mkdir(parents=True, exist_ok=True)
url = cfg["image_base_url"] + t["probe_image"]
print(f"== kernel-ranchu from {url}")
with zipfile.ZipFile(io.BufferedReader(HttpRangeFile(url), 1 << 20)) as z:
name = next(n for n in z.namelist() if n.endswith("/kernel-ranchu") or n == "kernel-ranchu")
kernel = z.read(name)
ksha = hashlib.sha256(kernel).hexdigest()
rel = kernel_release(kernel)
if ksha != t["kernel_sha256"]:
sys.exit(f"kernel SHA-256 mismatch: expected {t['kernel_sha256']}, got {ksha}")
print(f" release={rel} sha256={ksha}")
if rel != t["kernel_release"] or not rel.endswith("-ab" + t["build_id"]):
sys.exit(f"kernel mismatch: image has {rel}, target expects {t['kernel_release']}")
(a.out / "kernel-ranchu").write_bytes(kernel)
print(f"== manifest for build {t['build_id']}")
with http_get(MANIFEST_URL.format(bid=t["build_id"])) as response:
manifest = response.read()
(a.out / "manifest.xml").write_bytes(manifest)
common = next(p for p in ET.fromstring(manifest).iter("project") if p.get("name") == "kernel/common")
sha = common.get("revision")
if not re.fullmatch(r"[0-9a-f]{40}", sha or ""):
sys.exit(f"unexpected kernel/common revision {sha!r}")
if sha != t["kernel_commit"] or f"-g{sha[:12]}" not in rel:
sys.exit(f"manifest revision {sha} does not match kernel release {rel}")
print(f" kernel/common {sha}")
tgz = a.out / f"common-{sha}.tar.gz"
if not a.skip_tarball:
print(f"== fetch verified kernel source {sha}")
with TemporaryDirectory(dir=a.out) as scratch:
repo = Path(scratch) / "common.git"
subprocess.run(["git", "init", "--bare", "--quiet", repo], check=True)
git = ["git", "--git-dir", repo]
subprocess.run([*git, "fetch", "--no-tags", "--depth=1", KERNEL_REMOTE, sha], check=True)
fetched = subprocess.check_output([*git, "rev-parse", "FETCH_HEAD^{commit}"], text=True).strip()
if fetched != sha:
sys.exit(f"kernel Git commit mismatch: expected {sha}, got {fetched}")
archive = Path(scratch) / tgz.name
subprocess.run([*git, "archive", "--format=tar.gz", "-o", archive, sha], check=True)
archive.replace(tgz)
env = {
"TARGET_ID": t["id"],
"KMI": t["kmi"],
"BUILD_ID": t["build_id"],
"KERNEL_RELEASE": rel,
"KERNEL_SHA256": ksha,
"COMMON_SHA": sha,
"SRC_TGZ": tgz.name,
"DDK_IMAGE": t["ddk_image"],
"KSU_VERSION": t["ksu_version"],
"KSU_COMMIT": t["ksu_commit"],
"KSU_COMMIT_COUNT": str(t["ksu_commit_count"]),
"LKM_SHA256": t["lkm_sha256"] or "",
"LKM_SIZE": "",
"PATCHES": " ".join(t.get("patches", [])),
}
if env["LKM_SHA256"] and not re.fullmatch(r"[0-9a-f]{64}", env["LKM_SHA256"]):
sys.exit("invalid expected LKM SHA-256")
lkm_size = t.get("lkm_size")
if lkm_size is not None:
if type(lkm_size) is not int or lkm_size <= 0:
sys.exit("invalid expected LKM size")
env["LKM_SIZE"] = str(lkm_size)
if bool(env["LKM_SHA256"]) != bool(env["LKM_SIZE"]):
sys.exit("lkm_sha256 and lkm_size must be pinned together")
(a.out / "target.env").write_text(
"".join(f"{k}={shlex.quote(v)}\n" for k, v in env.items()), encoding="utf-8"
)
if __name__ == "__main__":
main()