Debian Codegraph @

src/kernel-install/60-ukify.install.in

raw
1 #!/usr/bin/env python3
2 # SPDX-License-Identifier: LGPL-2.1-or-later
3 # -*- mode: python-mode -*-
4 #
5 # This file is part of systemd.
6 #
7 # systemd is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU Lesser General Public License as published by
9 # the Free Software Foundation; either version 2.1 of the License, or
10 # (at your option) any later version.
11 #
12 # systemd is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 # General Public License for more details.
16 #
17 # You should have received a copy of the GNU Lesser General Public License
18 # along with systemd; If not, see <https://www.gnu.org/licenses/>.
19
20 # pylint: disable=import-outside-toplevel,consider-using-with,disable=redefined-builtin
21
22 import argparse
23 import os
24 import shlex
25 import types
26 from shutil import which
27 from pathlib import Path
28 from typing import Optional
29
30 __version__ = '{{PROJECT_VERSION}} ({{VERSION_TAG}})'
31
32 try:
33 VERBOSE = int(os.environ['KERNEL_INSTALL_VERBOSE']) > 0
34 except (KeyError, ValueError):
35 VERBOSE = False
36
37 # Override location of ukify and the boot stub for testing and debugging.
38 UKIFY = os.getenv('KERNEL_INSTALL_UKIFY', which('ukify'))
39 BOOT_STUB = os.getenv('KERNEL_INSTALL_BOOT_STUB')
40
41
42 def shell_join(cmd):
43 # TODO: drop in favour of shlex.join once shlex.join supports pathlib.Path.
44 return ' '.join(shlex.quote(str(x)) for x in cmd)
45
46 def log(*args, **kwargs):
47 if VERBOSE:
48 print(*args, **kwargs)
49
50 def path_is_readable(p: Path, dir=False) -> None:
51 """Verify access to a file or directory."""
52 try:
53 p.open().close()
54 except IsADirectoryError:
55 if dir:
56 return
57 raise
58
59 def mandatory_variable(name):
60 try:
61 return os.environ[name]
62 except KeyError as e:
63 raise KeyError(f'${name} must be set in the environment') from e
64
65 def parse_args(args=None):
66 p = argparse.ArgumentParser(
67 description='kernel-install plugin to build a Unified Kernel Image',
68 allow_abbrev=False,
69 usage='60-ukify.install COMMAND KERNEL_VERSION ENTRY_DIR KERNEL_IMAGE INITRD…',
70 )
71
72 # Suppress printing of usage synopsis on errors
73 p.error = lambda message: p.exit(2, f'{p.prog}: error: {message}\n')
74
75 p.add_argument('command',
76 metavar='COMMAND',
77 help="The action to perform. Only 'add' is supported.")
78 p.add_argument('kernel_version',
79 metavar='KERNEL_VERSION',
80 help='Kernel version string')
81 p.add_argument('entry_dir',
82 metavar='ENTRY_DIR',
83 type=Path,
84 nargs='?',
85 help='Type#1 entry directory (ignored)')
86 p.add_argument('kernel_image',
87 metavar='KERNEL_IMAGE',
88 type=Path,
89 nargs='?',
90 help='Kernel binary')
91 p.add_argument('initrd',
92 metavar='INITRD…',
93 type=Path,
94 nargs='*',
95 help='Initrd files')
96 p.add_argument('--version',
97 action='version',
98 version=f'systemd {__version__}')
99
100 opts = p.parse_args(args)
101
102 if opts.command == 'add':
103 opts.staging_area = Path(mandatory_variable('KERNEL_INSTALL_STAGING_AREA'))
104 path_is_readable(opts.staging_area, dir=True)
105
106 opts.entry_token = mandatory_variable('KERNEL_INSTALL_ENTRY_TOKEN')
107 opts.machine_id = mandatory_variable('KERNEL_INSTALL_MACHINE_ID')
108
109 return opts
110
111 def we_are_wanted() -> bool:
112 KERNEL_INSTALL_IMAGE_TYPE = os.getenv('KERNEL_INSTALL_IMAGE_TYPE')
113
114 if KERNEL_INSTALL_IMAGE_TYPE == 'uki':
115 log('The image being installed is already a UKI, quitting.')
116 return False
117
118 KERNEL_INSTALL_LAYOUT = os.getenv('KERNEL_INSTALL_LAYOUT')
119
120 if KERNEL_INSTALL_LAYOUT != 'uki':
121 log(f'{KERNEL_INSTALL_LAYOUT=}, quitting.')
122 return False
123
124 KERNEL_INSTALL_UKI_GENERATOR = os.getenv('KERNEL_INSTALL_UKI_GENERATOR') or 'ukify'
125
126 if KERNEL_INSTALL_UKI_GENERATOR != 'ukify':
127 log(f'{KERNEL_INSTALL_UKI_GENERATOR=}, quitting.')
128 return False
129
130 log('KERNEL_INSTALL_LAYOUT and KERNEL_INSTALL_UKI_GENERATOR are good')
131 return True
132
133
134 def input_file_location(
135 filename: str,
136 *search_directories: str) -> Optional[Path]:
137
138 if root := os.getenv('KERNEL_INSTALL_CONF_ROOT'):
139 search_directories = (root,)
140 elif not search_directories:
141 # This is the default search path.
142 search_directories = ('/etc/kernel',
143 '/usr/lib/kernel')
144
145 for dir in search_directories:
146 p = Path(dir) / filename
147 if p.exists():
148 return p
149 return None
150
151
152 def uki_conf_location() -> Optional[Path]:
153 return input_file_location('uki.conf',
154 '/etc/kernel',
155 '/run/kernel',
156 '/usr/local/lib/kernel',
157 '/usr/lib/kernel')
158
159
160 def devicetree_config_location() -> Optional[Path]:
161 return input_file_location('devicetree')
162
163
164 def devicetree_file_location(opts) -> Optional[Path]:
165 # This mirrors the logic in 90-loaderentry.install. Keep in sync.
166 configfile = devicetree_config_location()
167 if configfile is None:
168 return None
169
170 devicetree = configfile.read_text().strip()
171 if not devicetree:
172 raise ValueError(f'{configfile!r} is empty')
173
174 path = input_file_location(
175 devicetree,
176 f'/usr/lib/firmware/{opts.kernel_version}/device-tree',
177 f'/usr/lib/linux-image-{opts.kernel_version}',
178 f'/usr/lib/modules/{opts.kernel_version}/dtb',
179 )
180 if path is None:
181 raise FileNotFoundError(f'DeviceTree file {devicetree} not found')
182 return path
183
184
185 def kernel_cmdline_base() -> list[str]:
186 path = input_file_location('cmdline')
187 if path:
188 # Filter out commented out lines from cmdline.
189 lines = path.read_text().splitlines()
190 return [opt
191 for line in lines
192 if not line.startswith('#')
193 for opt in line.split()]
194
195 # If we read /proc/cmdline, we need to do some additional filtering.
196 options = Path('/proc/cmdline').read_text().split()
197 return [opt for opt in options
198 if not opt.startswith(('BOOT_IMAGE=', 'initrd='))]
199
200
201 def kernel_cmdline(opts) -> str:
202 options = kernel_cmdline_base()
203
204 # If the boot entries are named after the machine ID, then suffix the kernel
205 # command line with the machine ID we use, so that the machine ID remains
206 # stable, even during factory reset, in the initrd (where the system's machine
207 # ID is not directly accessible yet), and if the root file system is volatile.
208 if (opts.entry_token == opts.machine_id and
209 not any(opt.startswith('systemd.machine_id=') for opt in options)):
210 options += [f'systemd.machine_id={opts.machine_id}']
211
212 # TODO: we unconditionally set the cmdline here, ignoring the setting in
213 # the config file. Should we not do that?
214
215 # Prepend a space so that '@' does not get misinterpreted
216 return ' ' + ' '.join(options)
217
218
219 def initrd_list(opts) -> list[Path]:
220 microcode = sorted(opts.staging_area.glob('microcode*'))
221 initrd = sorted(opts.staging_area.glob('initrd*'))
222
223 # Order taken from 90-loaderentry.install
224 return [*microcode, *opts.initrd, *initrd]
225
226
227 def load_module(name: str, path: str) -> types.ModuleType:
228 module = types.ModuleType(name)
229 text = open(path).read()
230 exec(compile(text, path, 'exec'), module.__dict__)
231 return module
232
233
234 def call_ukify(opts) -> None:
235 ukify = load_module('ukify', UKIFY)
236
237 # Create "empty" namespace. We want to override just a few settings, so it
238 # doesn't make sense to configure everything. We pretend to parse an empty
239 # argument set to prepopulate the namespace with the defaults.
240 opts2 = ukify.create_parser().parse_args(['build'])
241
242 opts2.config = uki_conf_location()
243 opts2.uname = opts.kernel_version
244 opts2.linux = opts.kernel_image
245 opts2.initrd = initrd_list(opts)
246 # Note that 'uki.efi' is the name required by 90-uki-copy.install.
247 opts2.output = opts.staging_area / 'uki.efi'
248
249 if devicetree := devicetree_file_location(opts):
250 opts2.devicetree = devicetree
251
252 opts2.cmdline = kernel_cmdline(opts)
253 if BOOT_STUB:
254 opts2.stub = BOOT_STUB
255
256 ukify.apply_config(opts2)
257 ukify.finalize_options(opts2)
258 ukify.check_inputs(opts2)
259 ukify.make_uki(opts2)
260
261 log(f'{opts2.output} has been created')
262
263
264 def main():
265 opts = parse_args()
266 if opts.command != 'add':
267 return
268 if not we_are_wanted():
269 return
270
271 call_ukify(opts)
272
273
274 if __name__ == '__main__':
275 main()