vinix-ports / tests / installed-root.v
254 lines · 242 sloc · 8.59 KB
Raw
1// Check a clean signed vpac client before booting its root on Vinix.
2module main
3
4import os
5import strconv
6
7struct VersionUse {
8 consumer string
9 provider string
10 version string
11}
12
13struct Client {
14 root string
15 arch string
16mut:
17 owners map[string]string
18 exports map[string][]string
19 imports []VersionUse
20 files int
21 elfs int
22}
23
24fn field(body string, key string) string {
25 return ('\n' + body).all_after('\n%' + key + '%\n').all_before('\n')
26}
27
28// Resolve every component inside the guest. A host realpath would follow
29// guest-absolute links such as /lib/libc.so into the build machine.
30fn (client &Client) resolve(path string) !string {
31 mut rest := path.split('/')
32 mut parts := []string{}
33 mut links := 0
34 for rest.len != 0 {
35 name := rest[0]
36 rest = rest[1..].clone()
37 if name in ['', '.'] {
38 continue
39 }
40 if name == '..' {
41 if parts.len != 0 { parts.delete_last() }
42 continue
43 }
44 parts << name
45 current := client.root + '/' + parts.join('/')
46 if os.is_link(current) {
47 links++
48 if links > 40 { return error('symlink loop at ${path}') }
49 target := os.readlink(current)!
50 parts.delete_last()
51 if target.starts_with('/') { parts.clear() }
52 rest.prepend(target.split('/'))
53 }
54 }
55 return parts.join('/')
56}
57
58fn (mut client Client) load_owners(database string) !int {
59 mut packages := 0
60 for entry in os.ls(database)! {
61 if entry == 'ALPM_DB_VERSION' {
62 continue
63 }
64 dir := os.join_path(database, entry)
65 desc := os.read_file(os.join_path(dir, 'desc'))!
66 pkg := field(desc, 'NAME')
67 if pkg == '' || field(desc, 'ARCH') !in ['any', client.arch]
68 || field(desc, 'VALIDATION') != 'pgp' {
69 return error('missing name, wrong architecture or missing PGP validation: ${entry}')
70 }
71 packages++
72 list := os.read_file(os.join_path(dir, 'files'))!
73 if !list.starts_with('%FILES%\n') { return error('missing file list for ${entry}') }
74 for file in list.all_after('%FILES%\n').all_before('\n\n').split_into_lines() {
75 if file == '' || file.ends_with('/') {
76 continue
77 }
78 if file.starts_with('/') || file.split('/').any(it in ['', '.', '..']) {
79 return error('invalid package path in ${entry}: ${file}')
80 }
81 if other := client.owners[file] {
82 return error('${file} claimed by both ${pkg} and ${other}')
83 }
84 client.owners[file] = pkg
85 }
86 }
87 if packages == 0 { return error('empty package database') }
88 return packages
89}
90
91fn (client &Client) library(name string, search []string) string {
92 for dir in search {
93 path := client.resolve(dir + '/' + name) or { continue }
94 if path in client.owners && os.is_file(client.root + '/' + path) { return path }
95 }
96 return ''
97}
98
99fn (mut client Client) symbol_versions(path string, providers map[string]string) ! {
100 // objdump -p prints the version tables without dumping a line per symbol.
101 result := os.exec(['objdump', '-p', client.root + '/' + path])
102 if result.exit_code != 0 { return error('objdump ${path}: ${result.output}') }
103 mut section := ''
104 mut provider := ''
105 for line in result.output.split_into_lines() {
106 entry := line.trim_space()
107 if entry in ['Version definitions:', 'Version References:'] {
108 section = entry
109 } else if entry == '' {
110 section = ''
111 } else if section == 'Version definitions:' {
112 words := entry.fields()
113 // A single indented name is an inherited version.
114 if words.len == 4 { client.exports[path] << words[3] }
115 } else if section == 'Version References:' {
116 if entry.starts_with('required from ') {
117 lib := entry.all_after('required from ').trim_right(':')
118 provider = providers[lib] or { return error('${path} names unknown version provider ${lib}') }
119 } else {
120 words := entry.fields()
121 if provider == '' || words.len != 4 { return error('unexpected version reference in ${path}: ${entry}') }
122 // VER_FLG_WEAK lets the requested version be absent.
123 flags := strconv.parse_uint(words[1], 0, 16)!
124 if (flags & 2) == 0 {
125 client.imports << VersionUse{consumer: path, provider: provider, version: words[3]}
126 }
127 }
128 }
129 }
130}
131
132fn (mut client Client) inspect(path string, defaults []string) ! {
133 full := client.root + '/' + path
134 client.files++
135 if os.is_link(full) { return }
136 if !os.is_file(full) { return error('unexpected file type: ${path}') }
137 mut fd := os.open(full)!
138 header := fd.read_bytes(20)
139 fd.close()
140 if header.len < 4 || header[..4] != [u8(127), 69, 76, 70] { return }
141 machine := if client.arch == 'aarch64' { u8(183) } else { u8(62) }
142 if header.len < 20 || header[4] != 2 || header[5] != 1 || header[18] != machine
143 || header[19] != 0 {
144 return error('wrong target ELF machine, class or byte order: ${path}')
145 }
146 client.elfs++
147 if header[16] == 1 && header[17] == 0 { return } // Relocatable SDK object.
148 result := os.exec(['readelf', '--wide', '-l', '-d', full])
149 if result.exit_code != 0 { return error('readelf ${path}: ${result.output}') }
150 mut needed := []string{}
151 mut search := []string{}
152 page := if client.arch == 'aarch64' { u64(16384) } else { u64(4096) }
153 mut loads := 0
154 for line in result.output.split_into_lines() {
155 if line.trim_space().starts_with('LOAD ') {
156 words := line.fields()
157 if words.len < 8 { return error('malformed LOAD header in ${path}') }
158 offset := strconv.parse_uint(words[1], 0, 64)!
159 address := strconv.parse_uint(words[2], 0, 64)!
160 memsz := strconv.parse_uint(words[5], 0, 64)!
161 if memsz == 0 { continue }
162 if address % page != offset % page {
163 return error('${path}: PT_LOAD offset 0x${offset:x} and virtual address 0x${address:x} disagree on ${page}-byte Vinix pages')
164 }
165 loads++
166 } else if line.contains('Requesting program interpreter: ') {
167 interp := line.all_after('Requesting program interpreter: ').all_before(']')
168 if interp != '/lib/ld-musl-' + client.arch + '.so.1'
169 || client.library(os.base(interp), ['/lib']) == '' {
170 return error('wrong or unowned interpreter ${interp} in ${path}')
171 }
172 } else if line.contains('(NEEDED)') {
173 needed << line.all_after('[').all_before(']')
174 } else if line.contains('(RUNPATH)') || line.contains('(RPATH)') {
175 for item in line.all_after('[').all_before(']').split(':') {
176 dir := item.replace(r'${ORIGIN}', '/' + os.dir(path)).replace(r'$ORIGIN', '/' +
177 os.dir(path))
178 if !dir.starts_with('/') || dir.contains('$') {
179 return error('unsupported library search path ${item} in ${path}')
180 }
181 search << dir
182 }
183 }
184 }
185 if header[16] in [u8(2), 3] && loads == 0 { return error('no loadable segments in ${path}') }
186 search << defaults
187 mut providers := map[string]string{}
188 for lib in needed {
189 provider := client.library(lib, search)
190 if lib.contains('/') || provider == '' {
191 return error('${path} (${client.owners[path]}) needs missing or unowned library ${lib}')
192 }
193 providers[lib] = provider
194 }
195 if result.output.contains('(VERNEED)') || result.output.contains('(VERDEF)') {
196 client.symbol_versions(path, providers)!
197 }
198}
199
200fn (mut client Client) walk(dir string, defaults []string, mut seen map[string]bool) ! {
201 for entry in os.ls(os.join_path(client.root, dir))! {
202 path := if dir == '' { entry } else { dir + '/' + entry }
203 full := client.root + '/' + path
204 if !os.is_link(full) && os.is_dir(full) {
205 client.walk(path, defaults, mut seen)!
206 continue
207 }
208 if path !in client.owners { return error('unowned file: ${path}') }
209 seen[path] = true
210 client.inspect(path, defaults)!
211 }
212}
213
214fn audit(arch string, sdk string) ! {
215 if arch !in ['x86_64', 'aarch64'] { return error('unknown architecture: ${arch}') }
216 os.setenv('LC_ALL', 'C', true)
217 mut client := Client{
218 root: os.real_path(os.join_path(sdk, 'root'))
219 arch: arch
220 }
221 packages := client.load_owners(os.join_path(sdk, 'db/local'))!
222 conf := client.resolve('/etc/ld-musl-' + arch + '.path')!
223 mut defaults := ['/lib', '/usr/local/lib', '/usr/lib']
224 if os.is_file(client.root + '/' + conf) {
225 defaults =
226 os.read_file(client.root + '/' + conf)!.replace('\n', ':').split(':').filter(it != '')
227 if defaults.any(!it.starts_with('/')) {
228 return error('relative directory in musl library path')
229 }
230 }
231 mut seen := map[string]bool{}
232 client.walk('', defaults, mut seen)!
233 for requirement in client.imports {
234 if requirement.version !in client.exports[requirement.provider] {
235 return error('${requirement.consumer} requires ABI version ${requirement.version} from ${requirement.provider}')
236 }
237 }
238 for path, pkg in client.owners {
239 if path !in seen { return error('absent package file: ${pkg} ${path}') }
240 }
241 if client.elfs == 0 { return error('root has no target ELF') }
242 println('${arch}: ${packages} PGP-validated package records, ${client.files} owned files and links, ${client.elfs} target ELFs')
243}
244
245fn main() {
246 if os.args.len != 3 {
247 eprintln('usage: installed-root ARCH SDK_DIRECTORY')
248 exit(2)
249 }
250 audit(os.args[1], os.args[2]) or {
251 eprintln(err)
252 exit(1)
253 }
254}
255