build 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. #!/usr/bin/env python3
  2. import re
  3. import os
  4. import cli_function
  5. import collections
  6. import common
  7. import copy
  8. import subprocess
  9. import shell_helpers
  10. from shell_helpers import LF
  11. import lkmc
  12. class _Component:
  13. '''
  14. Yes, we are re-inventing a crappy dependency resolution system,
  15. reminiscent of scons or apt or Buildroot. I can't believe it.
  16. The hard part is that we have optional dependencies as well...
  17. e.g. Buildroot optionally depends on m5 to put m5 in the root filesystem,
  18. and Buildroot optionally depends on QEMU to build the qcow2 version
  19. of the image.
  20. '''
  21. def __init__(
  22. self,
  23. build_callback=None,
  24. supported_archs=None,
  25. dependencies=None,
  26. apt_get_pkgs=None,
  27. apt_build_deps=None,
  28. submodules=None,
  29. submodules_shallow=None,
  30. python2_pkgs=None,
  31. python3_pkgs=None,
  32. ):
  33. self.build_callback = build_callback
  34. self.supported_archs = supported_archs
  35. self.dependencies = dependencies or set()
  36. self.apt_get_pkgs = apt_get_pkgs or set()
  37. self.apt_build_deps = apt_build_deps or set()
  38. self.submodules = submodules or set()
  39. self.submodules_shallow = submodules_shallow or set()
  40. self.python2_pkgs = python2_pkgs or set()
  41. self.python3_pkgs = python3_pkgs or set()
  42. def build(self, arch):
  43. if (
  44. (self.build_callback is not None) and
  45. (self.supported_archs is None or arch in self.supported_archs)
  46. ):
  47. self.build_callback()
  48. class Main(common.LkmcCliFunction):
  49. def __init__(self):
  50. super().__init__(
  51. description='''\
  52. Build a component and all its dependencies.
  53. Our build-* scripts don't build any dependencies to make iterative
  54. development fast and more predictable.
  55. It is currently not possible to configure individual components from the command line
  56. when you build with this script. TODO.
  57. Without any args, build only what is necessary for:
  58. https://github.com/cirosantilli/linux-kernel-module-cheat#qemu-buildroot-setup
  59. ....
  60. ./%(prog)s
  61. ....
  62. This is equivalent to:
  63. ....
  64. ./%(prog)s --arch x86_64 qemu-buildroot
  65. ....
  66. Another important target is `all`:
  67. ....
  68. ./%(prog)s all
  69. ....
  70. This does not truly build ALL configurations: that would be impractical.
  71. But more precisely: build the reference configuration of each major component.
  72. So e.g.: one config of Linux kernel, Buildroot, gem5 and QEMU.
  73. Don't do for example all possible gem5 configs: debug, opt and fast,
  74. as that would be huge. This ensures that every piece of software
  75. builds in at least one config.
  76. TODO looping over emulators is not currently supported by this script, e.g.:
  77. ....
  78. ./%(prog)s --arch x86_64 --arch aarch64 all
  79. ....
  80. Instead, for the targets that are emulator dependent, you must select the
  81. taret version for the desired emulator, e.g.:
  82. ....
  83. ./build --arch aarch64 baremetal-qemu baremetal-gem5
  84. ....
  85. The reason is that some targets depend on emulator, while others don't,
  86. so looping over all of them would waste time.
  87. ''',
  88. )
  89. buildroot_component = _Component(
  90. self._build_file('build-buildroot'),
  91. submodules_shallow = {
  92. 'buildroot',
  93. 'binutils-gdb',
  94. 'gcc',
  95. 'glibc',
  96. },
  97. # https://buildroot.org/downloads/manual/manual.html#requirement
  98. apt_get_pkgs={
  99. 'bash',
  100. 'bc',
  101. 'binutils',
  102. 'build-essential',
  103. 'bzip2',
  104. 'cpio',
  105. 'g++',
  106. 'gcc',
  107. 'graphviz',
  108. 'gzip',
  109. 'make',
  110. 'patch',
  111. 'perl',
  112. 'python-matplotlib',
  113. 'python3',
  114. 'rsync',
  115. 'sed',
  116. 'tar',
  117. 'unzip',
  118. },
  119. )
  120. buildroot_overlay_qemu_component = copy.copy(buildroot_component)
  121. # We need to build QEMU before the final Buildroot to get qemu-img.
  122. buildroot_overlay_qemu_component.dependencies = ['overlay', 'qemu']
  123. buildroot_overlay_gem5_component = copy.copy(buildroot_component)
  124. buildroot_overlay_gem5_component.dependencies = ['overlay-gem5']
  125. gem5_deps = {
  126. # TODO test it out on Docker and answer that question properly:
  127. # https://askubuntu.com/questions/350475/how-can-i-install-gem5
  128. 'apt_get_pkgs': {
  129. 'device-tree-compiler',
  130. 'diod',
  131. 'libgoogle-perftools-dev',
  132. 'libboost-all-dev',
  133. 'm4',
  134. 'protobuf-compiler',
  135. 'python-dev',
  136. 'python-pip',
  137. # For prebuilt qcow2 unpack.
  138. 'qemu-utils',
  139. 'scons',
  140. 'zlib1g-dev',
  141. },
  142. 'python2_pkgs': {
  143. # Generate graphs of config.ini under m5out.
  144. 'pydot',
  145. },
  146. 'submodules_shallow': {'gem5'},
  147. }
  148. self.name_to_component_map = {
  149. 'all': _Component(dependencies=[
  150. 'qemu-gem5-buildroot',
  151. 'all-baremetal',
  152. 'user-mode-qemu',
  153. 'doc',
  154. ]),
  155. 'all-baremetal': _Component(dependencies=[
  156. 'qemu-baremetal',
  157. 'gem5-baremetal',
  158. 'baremetal-gem5-pbx',
  159. ],
  160. supported_archs=common.consts['crosstool_ng_supported_archs'],
  161. ),
  162. 'baremetal': _Component(dependencies=[
  163. 'baremetal-gem5',
  164. 'baremetal-qemu',
  165. ]),
  166. 'baremetal-qemu': _Component(
  167. self._build_file('build-baremetal', emulators=['qemu']),
  168. supported_archs=common.consts['crosstool_ng_supported_archs'],
  169. dependencies=['crosstool-ng'],
  170. ),
  171. 'baremetal-gem5': _Component(
  172. self._build_file('build-baremetal', emulators=['gem5']),
  173. supported_archs=common.consts['crosstool_ng_supported_archs'],
  174. dependencies=['crosstool-ng'],
  175. ),
  176. 'baremetal-gem5-pbx': _Component(
  177. self._build_file('build-baremetal', emulators=['gem5'], machine='RealViewPBX'),
  178. supported_archs=common.consts['crosstool_ng_supported_archs'],
  179. dependencies=['crosstool-ng'],
  180. ),
  181. 'buildroot': buildroot_component,
  182. # We need those to avoid circular dependencies, since we need to run Buildroot
  183. # twice: once to get the toolchain, and a second time to put the overlay into
  184. # the root filesystem.
  185. 'buildroot-overlay-qemu': buildroot_overlay_qemu_component,
  186. 'buildroot-overlay-gem5': buildroot_overlay_gem5_component,
  187. 'copy-overlay': _Component(
  188. self._build_file('copy-overlay'),
  189. ),
  190. 'crosstool-ng': _Component(
  191. self._build_file('build-crosstool-ng'),
  192. supported_archs=common.consts['crosstool_ng_supported_archs'],
  193. # http://crosstool-ng.github.io/docs/os-setup/
  194. apt_get_pkgs={
  195. 'bison',
  196. 'docbook2x',
  197. 'flex',
  198. 'gawk',
  199. 'gcc',
  200. 'gperf',
  201. 'help2man',
  202. 'libncurses5-dev',
  203. 'libtool-bin',
  204. 'make',
  205. 'python-dev',
  206. 'texinfo',
  207. },
  208. submodules_shallow={'crosstool-ng'},
  209. ),
  210. 'doc': _Component(
  211. self._build_file('build-doc'),
  212. ),
  213. 'gem5': _Component(
  214. self._build_file('build-gem5'),
  215. **gem5_deps
  216. ),
  217. 'gem5-baremetal': _Component(dependencies=[
  218. 'gem5',
  219. 'baremetal-gem5',
  220. ]),
  221. 'gem5-buildroot': _Component(dependencies=[
  222. 'buildroot-overlay-gem5',
  223. 'linux',
  224. 'gem5',
  225. ]),
  226. 'gem5-debug': _Component(
  227. self._build_file('build-gem5', gem5_build_type='debug'),
  228. **gem5_deps
  229. ),
  230. 'gem5-fast': _Component(
  231. self._build_file('build-gem5', gem5_build_type='fast'),
  232. **gem5_deps
  233. ),
  234. 'linux': _Component(
  235. self._build_file('build-linux'),
  236. dependencies={'buildroot'},
  237. submodules_shallow={'linux'},
  238. apt_get_pkgs={
  239. 'bison',
  240. 'flex',
  241. # Without this started failing in kernel 4.15 with:
  242. # Makefile:932: *** "Cannot generate ORC metadata for CONFIG_UNWINDER_ORC=y, please install libelf-dev, libelf-devel or elfutils-libelf-devel". Stop.
  243. 'libelf-dev',
  244. },
  245. ),
  246. 'modules': _Component(
  247. self._build_file('build-modules'),
  248. dependencies=['buildroot', 'linux'],
  249. ),
  250. 'm5': _Component(
  251. self._build_file('build-m5'),
  252. dependencies=['buildroot'],
  253. submodules_shallow={'gem5'},
  254. ),
  255. 'overlay': _Component(dependencies=[
  256. 'copy-overlay',
  257. 'modules',
  258. 'userland',
  259. ]),
  260. 'overlay-gem5': _Component(dependencies=[
  261. 'm5',
  262. 'overlay',
  263. ]),
  264. 'parsec-benchmark': _Component(
  265. submodules_shallow={'parsec-benchmark'},
  266. dependencies=['buildroot'],
  267. ),
  268. 'qemu': _Component(
  269. self._build_file('build-qemu'),
  270. apt_build_deps={'qemu'},
  271. apt_get_pkgs={'libsdl2-dev'},
  272. submodules={'qemu'},
  273. ),
  274. 'qemu-baremetal': _Component(dependencies=[
  275. 'qemu',
  276. 'baremetal-qemu',
  277. ]),
  278. 'qemu-buildroot': _Component(dependencies=[
  279. 'buildroot-overlay-qemu',
  280. 'linux',
  281. ]),
  282. 'qemu-gem5-buildroot': _Component(dependencies=[
  283. 'qemu',
  284. 'gem5-buildroot',
  285. ]),
  286. 'qemu-user': _Component(
  287. self._build_file('build-qemu', user_mode=True),
  288. apt_build_deps = {'qemu'},
  289. apt_get_pkgs={'libsdl2-dev'},
  290. submodules={'qemu'},
  291. ),
  292. 'release': _Component(dependencies=[
  293. 'qemu-buildroot',
  294. 'doc',
  295. ]),
  296. 'test-gdb': _Component(dependencies=[
  297. 'all-baremetal',
  298. ],
  299. supported_archs=common.consts['crosstool_ng_supported_archs'],
  300. ),
  301. 'test-user-mode': _Component(dependencies=[
  302. 'test-user-mode-qemu',
  303. 'test-user-mode-gem5',
  304. ]),
  305. 'test-user-mode-qemu': _Component(dependencies=[
  306. 'user-mode-qemu',
  307. 'userland',
  308. ]),
  309. 'test-user-mode-gem5': _Component(dependencies=[
  310. 'gem5',
  311. 'userland-gem5',
  312. ]),
  313. 'user-mode-qemu': _Component(
  314. dependencies=['qemu-user', 'userland'],
  315. ),
  316. 'userland': _Component(
  317. self._build_file('build-userland'),
  318. dependencies=['buildroot'],
  319. ),
  320. 'userland-host': _Component(
  321. self._build_file('build-userland-in-tree'),
  322. apt_get_pkgs={
  323. 'libdrm-dev',
  324. 'libeigen3-dev',
  325. 'libopenblas-dev',
  326. },
  327. ),
  328. 'userland-gem5': _Component(
  329. self._build_file('build-userland', static=True, userland_build_id='static'),
  330. dependencies=['buildroot'],
  331. ),
  332. }
  333. self.component_to_name_map = {self.name_to_component_map[key]:key for key in self.name_to_component_map}
  334. self.add_argument(
  335. '--apt',
  336. default=True,
  337. help='''\
  338. Don't run any apt-get commands. To make it easier to use with other archs:
  339. https://github.com/cirosantilli/linux-kernel-module-cheat#supported-hosts
  340. '''
  341. )
  342. self.add_argument(
  343. '--download-dependencies',
  344. default=False,
  345. help='''\
  346. Also download all dependencies required for a given build: Ubuntu packages,
  347. Python packages and git submodules.
  348. '''
  349. )
  350. self.add_argument(
  351. '--print-components',
  352. default=False,
  353. help='''\
  354. Print the components that would be built, including dependencies, but don't
  355. build them, nor show the build commands.
  356. '''
  357. )
  358. self.add_argument(
  359. '--travis',
  360. default=False,
  361. help='''\
  362. Extra args to pass to all scripts.
  363. '''
  364. )
  365. self.add_argument(
  366. 'components',
  367. choices=list(self.name_to_component_map.keys()) + [[]],
  368. default=[],
  369. nargs='*',
  370. help='''\
  371. Which components to build. Default: qemu-buildroot
  372. '''
  373. )
  374. def _build_file(self, component_file, **extra_args):
  375. '''
  376. Build something based on a component file that defines a Main class.
  377. '''
  378. def f():
  379. args = self.get_common_args()
  380. args.update(extra_args)
  381. args['show_time'] = False
  382. lkmc.import_path.import_path_main(component_file)(**args)
  383. return f
  384. def timed_main(self):
  385. self.sh = shell_helpers.ShellHelpers(dry_run=self.env['dry_run'])
  386. # Decide components.
  387. components = self.env['components']
  388. if components == []:
  389. components = ['qemu-buildroot']
  390. selected_components = []
  391. for component_name in components:
  392. todo = [component_name]
  393. while todo:
  394. current_name = todo.pop(0)
  395. component = self.name_to_component_map[current_name]
  396. selected_components.insert(0, component)
  397. todo.extend(component.dependencies)
  398. # Remove duplicates, keep only the first one of each.
  399. # https://stackoverflow.com/questions/7961363/removing-duplicates-in-lists/7961390#7961390
  400. selected_components = collections.OrderedDict.fromkeys(selected_components)
  401. if self.env['download_dependencies']:
  402. apt_get_pkgs = {
  403. # Core requirements for this repo.
  404. 'git',
  405. 'moreutils', # ts
  406. 'python3-pip',
  407. 'tmux',
  408. 'vinagre',
  409. 'wget',
  410. }
  411. # E.g. on an ARM host, the package gcc-arm-linux-gnueabihf
  412. # is called just gcc.
  413. processor = self.env['host_arch']
  414. if processor != 'arm':
  415. apt_get_pkgs.update({
  416. 'gcc-arm-linux-gnueabihf',
  417. 'g++-arm-linux-gnueabihf',
  418. })
  419. if processor != 'aarch64':
  420. apt_get_pkgs.update({
  421. 'gcc-aarch64-linux-gnu',
  422. 'g++-aarch64-linux-gnu',
  423. })
  424. apt_build_deps = set()
  425. submodules = set()
  426. submodules_shallow = set()
  427. python2_pkgs = set()
  428. python3_pkgs = {
  429. 'pexpect==4.6.0',
  430. }
  431. for component in selected_components:
  432. apt_get_pkgs.update(component.apt_get_pkgs)
  433. apt_build_deps.update(component.apt_build_deps)
  434. submodules.update(component.submodules)
  435. submodules_shallow.update(component.submodules_shallow)
  436. python2_pkgs.update(component.python2_pkgs)
  437. python3_pkgs.update(component.python3_pkgs)
  438. if apt_get_pkgs or apt_build_deps:
  439. if self.env['travis']:
  440. interacive_pkgs = {
  441. 'libsdl2-dev',
  442. }
  443. apt_get_pkgs.difference_update(interacive_pkgs)
  444. if common.consts['in_docker']:
  445. sudo = []
  446. # https://askubuntu.com/questions/909277/avoiding-user-interaction-with-tzdata-when-installing-certbot-in-a-docker-contai
  447. os.environ['DEBIAN_FRONTEND'] = 'noninteractive'
  448. # https://askubuntu.com/questions/496549/error-you-must-put-some-source-uris-in-your-sources-list
  449. sources_path = os.path.join('/etc', 'apt', 'sources.list')
  450. with open(sources_path, 'r') as f:
  451. sources_txt = f.read()
  452. sources_txt = re.sub('^# deb-src ', 'deb-src ', sources_txt, flags=re.MULTILINE)
  453. with open(sources_path, 'w') as f:
  454. f.write(sources_txt)
  455. else:
  456. sudo = ['sudo']
  457. if common.consts['in_docker'] or self.env['travis']:
  458. y = ['-y']
  459. else:
  460. y = []
  461. if self.env['apt']:
  462. self.sh.run_cmd(
  463. sudo + ['apt-get', 'update', LF]
  464. )
  465. if apt_get_pkgs:
  466. self.sh.run_cmd(
  467. sudo + ['apt-get', 'install'] + y + [LF] +
  468. self.sh.add_newlines(sorted(apt_get_pkgs))
  469. )
  470. if apt_build_deps:
  471. self.sh.run_cmd(
  472. sudo +
  473. ['apt-get', 'build-dep'] + y + [LF] +
  474. self.sh.add_newlines(sorted(apt_build_deps))
  475. )
  476. if python2_pkgs:
  477. self.sh.run_cmd(
  478. ['python', '-m', 'pip', 'install', '--user', LF] +
  479. self.sh.add_newlines(sorted(python2_pkgs))
  480. )
  481. if python3_pkgs:
  482. # Not with pip executable directly:
  483. # https://stackoverflow.com/questions/49836676/error-after-upgrading-pip-cannot-import-name-main/51846054#51846054
  484. self.sh.run_cmd(
  485. ['python3', '-m', 'pip', 'install', '--user', LF] +
  486. self.sh.add_newlines(sorted(python3_pkgs))
  487. )
  488. git_version_tuple = tuple(int(x) for x in subprocess.check_output(['git', '--version']).decode().split(' ')[-1].split('.'))
  489. git_cmd_common = [
  490. 'git', LF,
  491. 'submodule', LF,
  492. 'update', LF,
  493. '--init', LF,
  494. '--recursive', LF,
  495. ]
  496. if git_version_tuple >= (2, 9, 0):
  497. # https://stackoverflow.com/questions/26957237/how-to-make-git-clone-faster-with-multiple-threads/52327638#52327638
  498. git_cmd_common.extend(['--jobs', str(len(os.sched_getaffinity(0))), LF])
  499. if git_version_tuple >= (2, 10, 0):
  500. # * https://stackoverflow.com/questions/32944468/how-to-show-progress-for-submodule-fetching
  501. # * https://stackoverflow.com/questions/4640020/progress-indicator-for-git-clone
  502. git_cmd_common.extend(['--progress', LF])
  503. def submodule_ids_to_cmd(submodules):
  504. return self.sh.add_newlines([os.path.join(common.consts['submodules_dir'], x) for x in sorted(submodules)])
  505. if submodules:
  506. self.sh.run_cmd(git_cmd_common + ['--', LF] + submodule_ids_to_cmd(submodules))
  507. if submodules_shallow:
  508. # TODO Ideally we should shallow clone --depth 1 all of them.
  509. #
  510. # However, most git servers out there are crap or craply configured
  511. # and don't allow shallow cloning except for branches.
  512. #
  513. # So for now I'm keeping all mirrors in my GitHub.
  514. # and always have a lkmc-* branch pointint to it.
  515. #
  516. # However, QEMU has a bunch of submodules itself, and I'm not in the mood
  517. # to mirror all of them...
  518. #
  519. # See also:
  520. #
  521. # * https://stackoverflow.com/questions/3489173/how-to-clone-git-repository-with-specific-revision-changeset
  522. # * https://stackoverflow.com/questions/2144406/git-shallow-submodules/47374702#47374702
  523. # * https://unix.stackexchange.com/questions/338578/why-is-the-git-clone-of-the-linux-kernel-source-code-much-larger-than-the-extrac
  524. cmd = git_cmd_common.copy()
  525. if git_version_tuple > (2, 7, 4):
  526. # Then there is a bug in Ubuntu 16.04 git 2.7.4 where --depth 1 fails...
  527. # OMG git submodules implementation sucks:
  528. # * https://stackoverflow.com/questions/2155887/git-submodule-head-reference-is-not-a-tree-error/25875273#25875273
  529. # * https://github.com/boostorg/boost/issues/245
  530. cmd.extend(['--depth', '1', LF])
  531. else:
  532. self.log_warn('your git is too old for git submodule update --depth 1')
  533. self.log_warn('update to git 2.17 or newer and you will save clone time')
  534. self.log_warn('see: https://github.com/cirosantilli/linux-kernel-module-cheat/issues/44')
  535. self.sh.run_cmd(cmd + ['--', LF] + submodule_ids_to_cmd(submodules_shallow))
  536. # Do the build.
  537. for component in selected_components:
  538. if self.env['print_components']:
  539. print(self.component_to_name_map[component])
  540. else:
  541. component.build(self.env['arch'])
  542. if __name__ == '__main__':
  543. Main().cli()