-
Notifications
You must be signed in to change notification settings - Fork 1
/
build.py
executable file
·359 lines (306 loc) · 12.6 KB
/
build.py
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#!/usr/bin/env python3.7
import argparse
import json
import os
import pprint
import subprocess
import sys
from pathlib import Path
_interactive = True
def resolve_path(pathname, config, is_dir, required=False, must_exist=False):
if required:
if pathname not in config:
sys.exit("Missing argument '%s'" % pathname)
if not config[pathname]:
# Empty path resolves to current directory. We don't want that.
sys.exit("Empty argument '%s'" % pathname)
if pathname not in config:
return
if not config[pathname]:
# Delete empty pathname, it is not resolved to a Path object and it will
# cause a lot of pain if it is used later.
# Invoking the script with an empty from from the command line can be
# used to remove paths set in the configuration file, if present.
del config[pathname]
return
config[pathname] = Path(config[pathname]).absolute()
if must_exist and not config[pathname].exists():
sys.exit("%s location '%s' must exist" \
% (pathname, config[pathname]))
if is_dir:
if config[pathname].exists() and not config[pathname].is_dir():
# Path points to file and not directory.
sys.exit("%s location '%s' is not a directory" \
% (pathname, config[pathname]))
if not config[pathname].exists():
# Create directory paths.
config[pathname].mkdir(mode=0o777, parents=True)
else:
if config[pathname].exists() and not config[pathname].is_file():
sys.exit("%s location '%s' is not a file" \
% (pathname, config[pathname]))
def command(cmd, **kwargs):
print(cmd)
cmd_str = ' '.join(map(str, cmd))
print()
print("Running command: '%s'" % cmd_str)
if kwargs:
print('Extra arguments: %s' % str(kwargs))
if _interactive:
input('Press any key to continue...')
subprocess.check_call(cmd, **kwargs)
def make_buildworld(config):
make_cmd = [
'make',
'-j', str(config['ncpu']),
'TARGET=' + config['target'],
'TARGET_ARCH=' + config['target_arch'],
]
make_cmd.extend(config['make_args'])
make_cmd.append('buildworld')
command(make_cmd, cwd=config['src'])
def make_installworld(config):
if config['no_root'] == 'yes' and 'rootfs' not in config:
sys.exit("Missing argument when building installworld with -DNO_ROOT: --rootfs")
make_cmd = [
'make',
'-j', str(config['ncpu']),
]
if config['no_root'] == 'yes':
make_cmd.append('-DNO_ROOT')
if 'rootfs' in config:
make_cmd.append('DESTDIR=' + str(config['rootfs']))
make_cmd.extend(config['make_args'])
make_cmd.append('installworld')
command(make_cmd, cwd=config['src'])
def create_ramdisk(config):
resolve_path('ramdisk_dir', config, is_dir=True,
required=True, must_exist=True)
resolve_path('ramdisk_file', config, is_dir=False,
required=True)
resolve_path('ramdisk_mtree', config, is_dir=False,
required=True, must_exist=True)
if config['ramdisk_file'].exists():
command(['rm', config['ramdisk_file']],
cwd=config['ramdisk_dir'])
makefs_cmd = [
'makefs',
'-t', 'ffs',
'-B', 'little',
'-o', 'optimization=space',
'-o', 'version=1',
config['ramdisk_file'],
config['ramdisk_mtree']
]
command(makefs_cmd, cwd=config['ramdisk_dir'])
def make_buildkernel(config):
if config['with_ramdisk'] == 'yes':
create_ramdisk(config)
make_cmd = [
'make',
'-j', str(config['ncpu'])
]
if 'kernconf' in config:
make_cmd.append('KERNCONF=' + config['kernconf'])
make_cmd.extend(config['make_args'])
make_cmd.append('buildkernel')
command(make_cmd, cwd=config['src'])
def make_installkernel(config):
if config['no_root'] == 'yes' and 'rootfs' not in config:
sys.exit("Missing argument when building installkernel with -DNO_ROOT: --rootfs")
make_cmd = [
'make',
'-j', str(config['ncpu'])
]
if config['no_root'] == 'yes':
make_cmd.append('-DNO_ROOT')
if 'kernconf' in config:
make_cmd.append('KERNCONF=' + config['kernconf'])
if 'rootfs' in config:
make_cmd.append('DESTDIR=' + str(config['rootfs']))
make_cmd.extend(config['make_args'])
make_cmd.append('installkernel')
command(make_cmd, cwd=config['src'])
def make_distribution(config):
if config['target'] == 'arm64':
sys.exit('Distribution not implemented for architecture: arm64')
make_cmd = [
'make',
'-j', str(config['ncpu'])
]
if config['no_root'] == 'yes':
make_cmd.append('-DNO_ROOT')
if 'rootfs' in config:
make_cmd.append('DESTDIR=' + str(config['rootfs']))
make_cmd.extend(config['make_args'])
make_cmd.append('distribution')
command(make_cmd, cwd=config['src'])
def get_new_env(config):
new_env = {
'SRC' : config['src'],
'WORKSPACE' : config['workspace'],
'MAKEOBJDIRPREFIX': config['makeobjdirprefix'],
'MAKESYSPATH': config['makesyspath'],
'OBJDIR' : config['objdir'],
'TARGET' : config['target'],
'TARGET_ARCH': config['target_arch']
}
if config['with_meta_mode'] == 'yes':
new_env['WITH_META_MODE'] = 'YES'
if 'rootfs' in config:
new_env['ROOTFS'] = config['rootfs']
if 'srcconf' in config:
new_env['SRCCONF'] = config['srcconf']
if config['with_ramdisk'] == 'yes':
new_env['RAMDISK_DIR'] = config['ramdisk_dir']
if 'modules_override' in config:
new_env['MODULES_OVERRIDE'] = config['modules_override']
if config['no_modules'] == 'yes':
new_env['NO_MODULES'] = 'YES'
new_env = {var: str(val) for var, val in new_env.items()}
return new_env
def get_config(args, yesno_argnames):
if args.config is not None:
with open(args.config, 'r') as f:
config = json.load(f)
else:
config = dict()
# Override config values with arguments.
for argname, argval in vars(args).items():
if argval is None:
if argname in yesno_argnames and argname not in config:
# Replace empty (equal to None) yes/no arguments with 'no'.
config[argname] = 'no'
else:
# All other empty arguments are discarded.
pass
else:
config[argname] = argval
return config
targets = [
'arm64',
'amd64'
]
def main(args, yesno_argnames):
global _interactive
config = get_config(args, yesno_argnames)
if 'build' not in config or not config['build']:
sys.exit('Missing build target; please specify a --build parameter')
if config['interactive'] == 'no':
_interactive = False
if 'target' not in config:
sys.exit('Target architecture is missing; please specify a --target parameter')
if config['target'] not in targets:
sys.exit("Unsupported target architecture '%s'" % config['target'])
if 'target_arch' not in config:
if config['target'] == 'amd64':
config['target_arch'] = 'amd64'
if config['target'] == 'arm64':
config['target_arch'] = 'aarch64'
config['build'] = list(config['build'].split(','))
config['build'] = list(map(str.strip, config['build']))
resolve_path('src', config, is_dir=True, required=True, must_exist=True)
resolve_path('srcconf', config, is_dir=False)
resolve_path('makeobjdirprefix', config, is_dir=True, required=True)
if 'workspace' not in config:
config['workspace'] = Path(__file__).absolute()
resolve_path('workspace', config, is_dir=True)
resolve_path('rootfs', config, is_dir=True)
config['objdir'] = "%s/%s/%s.%s" \
% (config['makeobjdirprefix'], config['src'], \
config['target'], config['target_arch'])
resolve_path('objdir', config, is_dir=True)
config['makesyspath'] = config['src'] / 'share' / 'mk'
resolve_path('makesyspath', config, is_dir=True, must_exist=True)
if 'ncpu' not in config:
config['ncpu'] = os.cpu_count()
if 'make_args' not in config or config['make_args'] is None:
config['make_args'] = []
if isinstance(config['make_args'], str):
config['make_args'] = config['make_args'].split()
if config['no_clean'] == 'yes':
config['make_args'].append('-DNO_CLEAN')
new_env = get_new_env(config)
os.environ.update(new_env)
print("\nBuild configuration:\n")
pprint.pprint(config)
print("\nNew environment:\n")
pprint.pprint(new_env)
print("\n" + '-' * 69 + "\n")
if _interactive:
input('Press any key to continue...')
build_funcs = {
'buildworld' : make_buildworld,
'installworld' : make_installworld,
'buildkernel' : make_buildkernel,
'installkernel' : make_installkernel,
'distribution' : make_distribution
}
for k, build_target in enumerate(config['build']):
if build_target in build_funcs:
if build_target == 'installworld' \
and 'buildworld' in config['build'][k+1:]:
print('installworld build target comes before buildworld target')
input('Press any key to continue...')
if build_target == 'installkernel' \
and 'buildkernel' in config['build'][k+1:]:
print('installkernel build target comes before buildkernel target')
input('Press any key to continue...')
build_funcs[build_target](config)
else:
make_cmd = [
'make',
'-j', str(config['ncpu']),
]
if config['no_root'] == 'yes':
make_cmd.append('-DNO_ROOT')
if 'rootfs' in config:
make_cmd.append('DESTDIR=' + str(config['rootfs']))
if 'kernconf' in config:
make_cmd.append('KERNCONF=' + config['kernconf'])
make_cmd.extend(config['make_args'])
make_cmd.append(build_target)
command(make_cmd, cwd=config['src'])
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--target', help='Target hardware platform',
choices=targets)
parser.add_argument('--target_arch', help='Target architecture')
parser.add_argument('--build',
help='Targets for the build system. Multiple comma-separated targets can be specified')
parser.add_argument('--ncpu', help='Number of cpus', type=int)
parser.add_argument('--kernconf', help='Kernel configuration file name')
parser.add_argument('--srcconf', help='Custom src.conf file path')
parser.add_argument('--src', help='Source directory')
parser.add_argument('--workspace', help='Workspace directory')
parser.add_argument('--makeobjdirprefix', help='Object directory')
parser.add_argument('--rootfs',
help='Destination directory used by installworld, distribution, installkernel build targets')
parser.add_argument('--make_args',
help='Extra arguments to pass to make during all stages')
parser.add_argument('--modules_override',
help='A space-separated list of modules to build')
parser.add_argument('--ramdisk_dir', help='Ramdisk directory')
parser.add_argument('--ramdisk_file', help='Ramdisk file name')
parser.add_argument('--ramdisk_mtree', help='Ramdisk mtree file name')
yes_no = ['yes', 'no']
parser.add_argument('-i', '--interactive',
help='Wait for user input before executing commands',
choices=yes_no)
parser.add_argument('--no_clean', help='Build with -DNO_CLEAN',
choices=yes_no)
parser.add_argument('--no_root', help='Install without using root privilege',
choices=yes_no)
parser.add_argument('--no_modules',
help='Do not build any standalone kernel modules', choices=yes_no)
parser.add_argument('--with_meta_mode',
help='Build with WITH_META_MODE=YES. The filemon module must be loaded',
choices=yes_no)
parser.add_argument('--with_ramdisk',
help='Create a ramdisk when building the kernel',
choices=yes_no)
yesno_argnames = ['interactive', 'no_clean', 'no_root', 'no_modules',
'with_meta_mode', 'with_ramdisk']
parser.add_argument('-c', '--config', help='Configuration file in JSON format')
args = parser.parse_args()
main(args, yesno_argnames)