edk2-build.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. #!/usr/bin/python3
  2. """
  3. build helper script for edk2, see
  4. https://gitlab.com/kraxel/edk2-build-config
  5. """
  6. import os
  7. import sys
  8. import time
  9. import shutil
  10. import argparse
  11. import subprocess
  12. import configparser
  13. rebase_prefix = ""
  14. version_override = None
  15. release_date = None
  16. # pylint: disable=unused-variable
  17. def check_rebase():
  18. """ detect 'git rebase -x edk2-build.py master' testbuilds """
  19. global rebase_prefix
  20. global version_override
  21. gitdir = '.git'
  22. if os.path.isfile(gitdir):
  23. with open(gitdir, 'r', encoding = 'utf-8') as f:
  24. (unused, gitdir) = f.read().split()
  25. if not os.path.exists(f'{gitdir}/rebase-merge/msgnum'):
  26. return
  27. with open(f'{gitdir}/rebase-merge/msgnum', 'r', encoding = 'utf-8') as f:
  28. msgnum = int(f.read())
  29. with open(f'{gitdir}/rebase-merge/end', 'r', encoding = 'utf-8') as f:
  30. end = int(f.read())
  31. with open(f'{gitdir}/rebase-merge/head-name', 'r', encoding = 'utf-8') as f:
  32. head = f.read().strip().split('/')
  33. rebase_prefix = f'[ {int(msgnum/2)} / {int(end/2)} - {head[-1]} ] '
  34. if msgnum != end and not version_override:
  35. # fixed version speeds up builds
  36. version_override = "test-build-patch-series"
  37. def get_coredir(cfg):
  38. if cfg.has_option('global', 'core'):
  39. return os.path.abspath(cfg['global']['core'])
  40. return os.getcwd()
  41. def get_toolchain(cfg, build):
  42. if cfg.has_option(build, 'tool'):
  43. return cfg[build]['tool']
  44. if cfg.has_option('global', 'tool'):
  45. return cfg['global']['tool']
  46. return 'GCC5'
  47. def get_version(cfg, silent = False):
  48. coredir = get_coredir(cfg)
  49. if version_override:
  50. version = version_override
  51. if not silent:
  52. print('')
  53. print(f'### version [override]: {version}')
  54. return version
  55. if os.environ.get('RPM_PACKAGE_NAME'):
  56. version = os.environ.get('RPM_PACKAGE_NAME')
  57. version += '-' + os.environ.get('RPM_PACKAGE_VERSION')
  58. version += '-' + os.environ.get('RPM_PACKAGE_RELEASE')
  59. if not silent:
  60. print('')
  61. print(f'### version [rpmbuild]: {version}')
  62. return version
  63. if os.path.exists(coredir + '/.git'):
  64. cmdline = [ 'git', 'describe', '--tags', '--abbrev=8',
  65. '--match=edk2-stable*' ]
  66. result = subprocess.run(cmdline, cwd = coredir,
  67. stdout = subprocess.PIPE,
  68. check = True)
  69. version = result.stdout.decode().strip()
  70. if not silent:
  71. print('')
  72. print(f'### version [git]: {version}')
  73. return version
  74. return None
  75. def pcd_string(name, value):
  76. return f'{name}=L{value}\\0'
  77. def pcd_version(cfg, silent = False):
  78. version = get_version(cfg, silent)
  79. if version is None:
  80. return []
  81. return [ '--pcd', pcd_string('PcdFirmwareVersionString', version) ]
  82. def pcd_release_date():
  83. if release_date is None:
  84. return []
  85. return [ '--pcd', pcd_string('PcdFirmwareReleaseDateString', release_date) ]
  86. def build_message(line, line2 = None, silent = False):
  87. if os.environ.get('TERM') in [ 'xterm', 'xterm-256color' ]:
  88. # setxterm title
  89. start = '\x1b]2;'
  90. end = '\x07'
  91. print(f'{start}{rebase_prefix}{line}{end}', end = '')
  92. if silent:
  93. print(f'### {rebase_prefix}{line}', flush = True)
  94. else:
  95. print('')
  96. print('###')
  97. print(f'### {rebase_prefix}{line}')
  98. if line2:
  99. print(f'### {line2}')
  100. print('###', flush = True)
  101. def build_run(cmdline, name, section, silent = False, nologs = False):
  102. if silent:
  103. logfile = f'{section}.log'
  104. if nologs:
  105. print(f'### building in silent mode [no log] ...', flush = True)
  106. else:
  107. print(f'### building in silent mode [{logfile}] ...', flush = True)
  108. start = time.time()
  109. result = subprocess.run(cmdline, check = False,
  110. stdout = subprocess.PIPE,
  111. stderr = subprocess.STDOUT)
  112. if not nologs:
  113. with open(logfile, 'wb') as f:
  114. f.write(result.stdout)
  115. if result.returncode:
  116. print('### BUILD FAILURE')
  117. print('### cmdline')
  118. print(cmdline)
  119. print('### output')
  120. print(result.stdout.decode())
  121. print(f'### exit code: {result.returncode}')
  122. else:
  123. secs = int(time.time() - start)
  124. print(f'### OK ({int(secs/60)}:{secs%60:02d})')
  125. else:
  126. print(cmdline, flush = True)
  127. result = subprocess.run(cmdline, check = False)
  128. if result.returncode:
  129. print(f'ERROR: {cmdline[0]} exited with {result.returncode}'
  130. f' while building {name}')
  131. sys.exit(result.returncode)
  132. def build_copy(plat, tgt, toolchain, dstdir, copy):
  133. srcdir = f'Build/{plat}/{tgt}_{toolchain}'
  134. names = copy.split()
  135. srcfile = names[0]
  136. if len(names) > 1:
  137. dstfile = names[1]
  138. else:
  139. dstfile = os.path.basename(srcfile)
  140. print(f'# copy: {srcdir} / {srcfile} => {dstdir} / {dstfile}')
  141. src = srcdir + '/' + srcfile
  142. dst = dstdir + '/' + dstfile
  143. os.makedirs(os.path.dirname(dst), exist_ok = True)
  144. shutil.copy(src, dst)
  145. def pad_file(dstdir, pad):
  146. args = pad.split()
  147. if len(args) < 2:
  148. raise RuntimeError(f'missing arg for pad ({args})')
  149. name = args[0]
  150. size = args[1]
  151. cmdline = [
  152. 'truncate',
  153. '--size', size,
  154. dstdir + '/' + name,
  155. ]
  156. print(f'# padding: {dstdir} / {name} => {size}')
  157. subprocess.run(cmdline, check = True)
  158. # pylint: disable=too-many-branches
  159. def build_one(cfg, build, jobs = None, silent = False, nologs = False):
  160. b = cfg[build]
  161. cmdline = [ 'build' ]
  162. cmdline += [ '-t', get_toolchain(cfg, build) ]
  163. cmdline += [ '-p', b['conf'] ]
  164. if (b['conf'].startswith('OvmfPkg/') or
  165. b['conf'].startswith('ArmVirtPkg/')):
  166. cmdline += pcd_version(cfg, silent)
  167. cmdline += pcd_release_date()
  168. if jobs:
  169. cmdline += [ '-n', jobs ]
  170. for arch in b['arch'].split():
  171. cmdline += [ '-a', arch ]
  172. if 'opts' in b:
  173. for name in b['opts'].split():
  174. section = 'opts.' + name
  175. for opt in cfg[section]:
  176. cmdline += [ '-D', opt + '=' + cfg[section][opt] ]
  177. if 'pcds' in b:
  178. for name in b['pcds'].split():
  179. section = 'pcds.' + name
  180. for pcd in cfg[section]:
  181. cmdline += [ '--pcd', pcd + '=' + cfg[section][pcd] ]
  182. if 'tgts' in b:
  183. tgts = b['tgts'].split()
  184. else:
  185. tgts = [ 'DEBUG' ]
  186. for tgt in tgts:
  187. desc = None
  188. if 'desc' in b:
  189. desc = b['desc']
  190. build_message(f'building: {b["conf"]} ({b["arch"]}, {tgt})',
  191. f'description: {desc}',
  192. silent = silent)
  193. build_run(cmdline + [ '-b', tgt ],
  194. b['conf'],
  195. build + '.' + tgt,
  196. silent,
  197. nologs)
  198. if 'plat' in b:
  199. # copy files
  200. for cpy in b:
  201. if not cpy.startswith('cpy'):
  202. continue
  203. build_copy(b['plat'], tgt,
  204. get_toolchain(cfg, build),
  205. b['dest'], b[cpy])
  206. # pad builds
  207. for pad in b:
  208. if not pad.startswith('pad'):
  209. continue
  210. pad_file(b['dest'], b[pad])
  211. def build_basetools(silent = False, nologs = False):
  212. build_message('building: BaseTools', silent = silent)
  213. basedir = os.environ['EDK_TOOLS_PATH']
  214. cmdline = [ 'make', '-C', basedir ]
  215. build_run(cmdline, 'BaseTools', 'build.basetools', silent, nologs)
  216. def binary_exists(name):
  217. for pdir in os.environ['PATH'].split(':'):
  218. if os.path.exists(pdir + '/' + name):
  219. return True
  220. return False
  221. def prepare_env(cfg, silent = False):
  222. """ mimic Conf/BuildEnv.sh """
  223. workspace = os.getcwd()
  224. packages = [ workspace, ]
  225. path = os.environ['PATH'].split(':')
  226. dirs = [
  227. 'BaseTools/Bin/Linux-x86_64',
  228. 'BaseTools/BinWrappers/PosixLike'
  229. ]
  230. if cfg.has_option('global', 'pkgs'):
  231. for pkgdir in cfg['global']['pkgs'].split():
  232. packages.append(os.path.abspath(pkgdir))
  233. coredir = get_coredir(cfg)
  234. if coredir != workspace:
  235. packages.append(coredir)
  236. # add basetools to path
  237. for pdir in dirs:
  238. p = coredir + '/' + pdir
  239. if not os.path.exists(p):
  240. continue
  241. if p in path:
  242. continue
  243. path.insert(0, p)
  244. # run edksetup if needed
  245. toolsdef = coredir + '/Conf/tools_def.txt'
  246. if not os.path.exists(toolsdef):
  247. os.makedirs(os.path.dirname(toolsdef), exist_ok = True)
  248. build_message('running BaseTools/BuildEnv', silent = silent)
  249. cmdline = [ 'bash', 'BaseTools/BuildEnv' ]
  250. subprocess.run(cmdline, cwd = coredir, check = True)
  251. # set variables
  252. os.environ['PATH'] = ':'.join(path)
  253. os.environ['PACKAGES_PATH'] = ':'.join(packages)
  254. os.environ['WORKSPACE'] = workspace
  255. os.environ['EDK_TOOLS_PATH'] = coredir + '/BaseTools'
  256. os.environ['CONF_PATH'] = coredir + '/Conf'
  257. os.environ['PYTHON_COMMAND'] = '/usr/bin/python3'
  258. os.environ['PYTHONHASHSEED'] = '1'
  259. # for cross builds
  260. if binary_exists('arm-linux-gnueabi-gcc'):
  261. # ubuntu
  262. os.environ['GCC5_ARM_PREFIX'] = 'arm-linux-gnueabi-'
  263. os.environ['GCC_ARM_PREFIX'] = 'arm-linux-gnueabi-'
  264. elif binary_exists('arm-linux-gnu-gcc'):
  265. # fedora
  266. os.environ['GCC5_ARM_PREFIX'] = 'arm-linux-gnu-'
  267. os.environ['GCC_ARM_PREFIX'] = 'arm-linux-gnu-'
  268. if binary_exists('loongarch64-linux-gnu-gcc'):
  269. os.environ['GCC5_LOONGARCH64_PREFIX'] = 'loongarch64-linux-gnu-'
  270. os.environ['GCC_LOONGARCH64_PREFIX'] = 'loongarch64-linux-gnu-'
  271. hostarch = os.uname().machine
  272. if binary_exists('aarch64-linux-gnu-gcc') and hostarch != 'aarch64':
  273. os.environ['GCC5_AARCH64_PREFIX'] = 'aarch64-linux-gnu-'
  274. os.environ['GCC_AARCH64_PREFIX'] = 'aarch64-linux-gnu-'
  275. if binary_exists('riscv64-linux-gnu-gcc') and hostarch != 'riscv64':
  276. os.environ['GCC5_RISCV64_PREFIX'] = 'riscv64-linux-gnu-'
  277. os.environ['GCC_RISCV64_PREFIX'] = 'riscv64-linux-gnu-'
  278. if binary_exists('x86_64-linux-gnu-gcc') and hostarch != 'x86_64':
  279. os.environ['GCC5_IA32_PREFIX'] = 'x86_64-linux-gnu-'
  280. os.environ['GCC5_X64_PREFIX'] = 'x86_64-linux-gnu-'
  281. os.environ['GCC5_BIN'] = 'x86_64-linux-gnu-'
  282. os.environ['GCC_IA32_PREFIX'] = 'x86_64-linux-gnu-'
  283. os.environ['GCC_X64_PREFIX'] = 'x86_64-linux-gnu-'
  284. os.environ['GCC_BIN'] = 'x86_64-linux-gnu-'
  285. def build_list(cfg):
  286. for build in cfg.sections():
  287. if not build.startswith('build.'):
  288. continue
  289. name = build.lstrip('build.')
  290. desc = 'no description'
  291. if 'desc' in cfg[build]:
  292. desc = cfg[build]['desc']
  293. print(f'# {name:20s} - {desc}')
  294. def main():
  295. parser = argparse.ArgumentParser(prog = 'edk2-build',
  296. description = 'edk2 build helper script')
  297. parser.add_argument('-c', '--config', dest = 'configfile',
  298. type = str, default = '.edk2.builds', metavar = 'FILE',
  299. help = 'read configuration from FILE (default: .edk2.builds)')
  300. parser.add_argument('-C', '--directory', dest = 'directory', type = str,
  301. help = 'change to DIR before building', metavar = 'DIR')
  302. parser.add_argument('-j', '--jobs', dest = 'jobs', type = str,
  303. help = 'allow up to JOBS parallel build jobs',
  304. metavar = 'JOBS')
  305. parser.add_argument('-m', '--match', dest = 'match',
  306. type = str, action = 'append',
  307. help = 'only run builds matching INCLUDE (substring)',
  308. metavar = 'INCLUDE')
  309. parser.add_argument('-x', '--exclude', dest = 'exclude',
  310. type = str, action = 'append',
  311. help = 'skip builds matching EXCLUDE (substring)',
  312. metavar = 'EXCLUDE')
  313. parser.add_argument('-l', '--list', dest = 'list',
  314. action = 'store_true', default = False,
  315. help = 'list build configs available')
  316. parser.add_argument('--silent', dest = 'silent',
  317. action = 'store_true', default = False,
  318. help = 'write build output to logfiles, '
  319. 'write to console only on errors')
  320. parser.add_argument('--no-logs', dest = 'nologs',
  321. action = 'store_true', default = False,
  322. help = 'do not write build log files (with --silent)')
  323. parser.add_argument('--core', dest = 'core', type = str, metavar = 'DIR',
  324. help = 'location of the core edk2 repository '
  325. '(i.e. where BuildTools are located)')
  326. parser.add_argument('--pkg', '--package', dest = 'pkgs',
  327. type = str, action = 'append', metavar = 'DIR',
  328. help = 'location(s) of additional packages '
  329. '(can be specified multiple times)')
  330. parser.add_argument('-t', '--toolchain', dest = 'toolchain',
  331. type = str, metavar = 'NAME',
  332. help = 'tool chain to be used to build edk2')
  333. parser.add_argument('--version-override', dest = 'version_override',
  334. type = str, metavar = 'VERSION',
  335. help = 'set firmware build version')
  336. parser.add_argument('--release-date', dest = 'release_date',
  337. type = str, metavar = 'DATE',
  338. help = 'set firmware build release date (in MM/DD/YYYY format)')
  339. options = parser.parse_args()
  340. if options.directory:
  341. os.chdir(options.directory)
  342. if not os.path.exists(options.configfile):
  343. print(f'config file "{options.configfile}" not found')
  344. return 1
  345. cfg = configparser.ConfigParser()
  346. cfg.optionxform = str
  347. cfg.read(options.configfile)
  348. if options.list:
  349. build_list(cfg)
  350. return 0
  351. if not cfg.has_section('global'):
  352. cfg.add_section('global')
  353. if options.core:
  354. cfg.set('global', 'core', options.core)
  355. if options.pkgs:
  356. cfg.set('global', 'pkgs', ' '.join(options.pkgs))
  357. if options.toolchain:
  358. cfg.set('global', 'tool', options.toolchain)
  359. global version_override
  360. global release_date
  361. check_rebase()
  362. if options.version_override:
  363. version_override = options.version_override
  364. if options.release_date:
  365. release_date = options.release_date
  366. prepare_env(cfg, options.silent)
  367. build_basetools(options.silent, options.nologs)
  368. for build in cfg.sections():
  369. if not build.startswith('build.'):
  370. continue
  371. if options.match:
  372. matching = False
  373. for item in options.match:
  374. if item in build:
  375. matching = True
  376. if not matching:
  377. print(f'# skipping "{build}" (not matching "{"|".join(options.match)}")')
  378. continue
  379. if options.exclude:
  380. exclude = False
  381. for item in options.exclude:
  382. if item in build:
  383. print(f'# skipping "{build}" (matching "{item}")')
  384. exclude = True
  385. if exclude:
  386. continue
  387. build_one(cfg, build, options.jobs, options.silent, options.nologs)
  388. return 0
  389. if __name__ == '__main__':
  390. sys.exit(main())