build-many-glibcs.py 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683
  1. #!/usr/bin/python3
  2. # Build many configurations of glibc.
  3. # Copyright (C) 2016-2019 Free Software Foundation, Inc.
  4. # This file is part of the GNU C Library.
  5. #
  6. # The GNU C Library is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU Lesser General Public
  8. # License as published by the Free Software Foundation; either
  9. # version 2.1 of the License, or (at your option) any later version.
  10. #
  11. # The GNU C Library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. # Lesser General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Lesser General Public
  17. # License along with the GNU C Library; if not, see
  18. # <http://www.gnu.org/licenses/>.
  19. """Build many configurations of glibc.
  20. This script takes as arguments a directory name (containing a src
  21. subdirectory with sources of the relevant toolchain components) and a
  22. description of what to do: 'checkout', to check out sources into that
  23. directory, 'bot-cycle', to run a series of checkout and build steps,
  24. 'bot', to run 'bot-cycle' repeatedly, 'host-libraries', to build
  25. libraries required by the toolchain, 'compilers', to build
  26. cross-compilers for various configurations, or 'glibcs', to build
  27. glibc for various configurations and run the compilation parts of the
  28. testsuite. Subsequent arguments name the versions of components to
  29. check out (<component>-<version), for 'checkout', or, for actions
  30. other than 'checkout' and 'bot-cycle', name configurations for which
  31. compilers or glibc are to be built.
  32. """
  33. import argparse
  34. import datetime
  35. import email.mime.text
  36. import email.utils
  37. import json
  38. import os
  39. import re
  40. import shutil
  41. import smtplib
  42. import stat
  43. import subprocess
  44. import sys
  45. import time
  46. import urllib.request
  47. try:
  48. subprocess.run
  49. except:
  50. class _CompletedProcess:
  51. def __init__(self, args, returncode, stdout=None, stderr=None):
  52. self.args = args
  53. self.returncode = returncode
  54. self.stdout = stdout
  55. self.stderr = stderr
  56. def _run(*popenargs, input=None, timeout=None, check=False, **kwargs):
  57. assert(timeout is None)
  58. with subprocess.Popen(*popenargs, **kwargs) as process:
  59. try:
  60. stdout, stderr = process.communicate(input)
  61. except:
  62. process.kill()
  63. process.wait()
  64. raise
  65. returncode = process.poll()
  66. if check and returncode:
  67. raise subprocess.CalledProcessError(returncode, popenargs)
  68. return _CompletedProcess(popenargs, returncode, stdout, stderr)
  69. subprocess.run = _run
  70. class Context(object):
  71. """The global state associated with builds in a given directory."""
  72. def __init__(self, topdir, parallelism, keep, replace_sources, strip,
  73. full_gcc, action):
  74. """Initialize the context."""
  75. self.topdir = topdir
  76. self.parallelism = parallelism
  77. self.keep = keep
  78. self.replace_sources = replace_sources
  79. self.strip = strip
  80. self.full_gcc = full_gcc
  81. self.srcdir = os.path.join(topdir, 'src')
  82. self.versions_json = os.path.join(self.srcdir, 'versions.json')
  83. self.build_state_json = os.path.join(topdir, 'build-state.json')
  84. self.bot_config_json = os.path.join(topdir, 'bot-config.json')
  85. self.installdir = os.path.join(topdir, 'install')
  86. self.host_libraries_installdir = os.path.join(self.installdir,
  87. 'host-libraries')
  88. self.builddir = os.path.join(topdir, 'build')
  89. self.logsdir = os.path.join(topdir, 'logs')
  90. self.logsdir_old = os.path.join(topdir, 'logs-old')
  91. self.makefile = os.path.join(self.builddir, 'Makefile')
  92. self.wrapper = os.path.join(self.builddir, 'wrapper')
  93. self.save_logs = os.path.join(self.builddir, 'save-logs')
  94. self.script_text = self.get_script_text()
  95. if action != 'checkout':
  96. self.build_triplet = self.get_build_triplet()
  97. self.glibc_version = self.get_glibc_version()
  98. self.configs = {}
  99. self.glibc_configs = {}
  100. self.makefile_pieces = ['.PHONY: all\n']
  101. self.add_all_configs()
  102. self.load_versions_json()
  103. self.load_build_state_json()
  104. self.status_log_list = []
  105. self.email_warning = False
  106. def get_script_text(self):
  107. """Return the text of this script."""
  108. with open(sys.argv[0], 'r') as f:
  109. return f.read()
  110. def exec_self(self):
  111. """Re-execute this script with the same arguments."""
  112. sys.stdout.flush()
  113. os.execv(sys.executable, [sys.executable] + sys.argv)
  114. def get_build_triplet(self):
  115. """Determine the build triplet with config.guess."""
  116. config_guess = os.path.join(self.component_srcdir('gcc'),
  117. 'config.guess')
  118. cg_out = subprocess.run([config_guess], stdout=subprocess.PIPE,
  119. check=True, universal_newlines=True).stdout
  120. return cg_out.rstrip()
  121. def get_glibc_version(self):
  122. """Determine the glibc version number (major.minor)."""
  123. version_h = os.path.join(self.component_srcdir('glibc'), 'version.h')
  124. with open(version_h, 'r') as f:
  125. lines = f.readlines()
  126. starttext = '#define VERSION "'
  127. for l in lines:
  128. if l.startswith(starttext):
  129. l = l[len(starttext):]
  130. l = l.rstrip('"\n')
  131. m = re.fullmatch('([0-9]+)\.([0-9]+)[.0-9]*', l)
  132. return '%s.%s' % m.group(1, 2)
  133. print('error: could not determine glibc version')
  134. exit(1)
  135. def add_all_configs(self):
  136. """Add all known glibc build configurations."""
  137. self.add_config(arch='aarch64',
  138. os_name='linux-gnu',
  139. extra_glibcs=[{'variant': 'disable-multi-arch',
  140. 'cfg': ['--disable-multi-arch']}])
  141. self.add_config(arch='aarch64_be',
  142. os_name='linux-gnu')
  143. self.add_config(arch='alpha',
  144. os_name='linux-gnu')
  145. self.add_config(arch='arm',
  146. os_name='linux-gnueabi')
  147. self.add_config(arch='armeb',
  148. os_name='linux-gnueabi')
  149. self.add_config(arch='armeb',
  150. os_name='linux-gnueabi',
  151. variant='be8',
  152. gcc_cfg=['--with-arch=armv7-a'])
  153. self.add_config(arch='arm',
  154. os_name='linux-gnueabihf',
  155. gcc_cfg=['--with-float=hard', '--with-cpu=arm926ej-s'],
  156. extra_glibcs=[{'variant': 'v7a',
  157. 'ccopts': '-march=armv7-a -mfpu=vfpv3'},
  158. {'variant': 'v7a-disable-multi-arch',
  159. 'ccopts': '-march=armv7-a -mfpu=vfpv3',
  160. 'cfg': ['--disable-multi-arch']}])
  161. self.add_config(arch='armeb',
  162. os_name='linux-gnueabihf',
  163. gcc_cfg=['--with-float=hard', '--with-cpu=arm926ej-s'])
  164. self.add_config(arch='armeb',
  165. os_name='linux-gnueabihf',
  166. variant='be8',
  167. gcc_cfg=['--with-float=hard', '--with-arch=armv7-a',
  168. '--with-fpu=vfpv3'])
  169. self.add_config(arch='csky',
  170. os_name='linux-gnuabiv2',
  171. variant='soft',
  172. gcc_cfg=['--disable-multilib'])
  173. self.add_config(arch='csky',
  174. os_name='linux-gnuabiv2',
  175. gcc_cfg=['--with-float=hard', '--disable-multilib'])
  176. self.add_config(arch='hppa',
  177. os_name='linux-gnu')
  178. self.add_config(arch='i686',
  179. os_name='gnu')
  180. self.add_config(arch='ia64',
  181. os_name='linux-gnu',
  182. first_gcc_cfg=['--with-system-libunwind'])
  183. self.add_config(arch='m68k',
  184. os_name='linux-gnu',
  185. gcc_cfg=['--disable-multilib'])
  186. self.add_config(arch='m68k',
  187. os_name='linux-gnu',
  188. variant='coldfire',
  189. gcc_cfg=['--with-arch=cf', '--disable-multilib'])
  190. self.add_config(arch='m68k',
  191. os_name='linux-gnu',
  192. variant='coldfire-soft',
  193. gcc_cfg=['--with-arch=cf', '--with-cpu=54455',
  194. '--disable-multilib'])
  195. self.add_config(arch='microblaze',
  196. os_name='linux-gnu',
  197. gcc_cfg=['--disable-multilib'])
  198. self.add_config(arch='microblazeel',
  199. os_name='linux-gnu',
  200. gcc_cfg=['--disable-multilib'])
  201. self.add_config(arch='mips64',
  202. os_name='linux-gnu',
  203. gcc_cfg=['--with-mips-plt'],
  204. glibcs=[{'variant': 'n32'},
  205. {'arch': 'mips',
  206. 'ccopts': '-mabi=32'},
  207. {'variant': 'n64',
  208. 'ccopts': '-mabi=64'}])
  209. self.add_config(arch='mips64',
  210. os_name='linux-gnu',
  211. variant='soft',
  212. gcc_cfg=['--with-mips-plt', '--with-float=soft'],
  213. glibcs=[{'variant': 'n32-soft'},
  214. {'variant': 'soft',
  215. 'arch': 'mips',
  216. 'ccopts': '-mabi=32'},
  217. {'variant': 'n64-soft',
  218. 'ccopts': '-mabi=64'}])
  219. self.add_config(arch='mips64',
  220. os_name='linux-gnu',
  221. variant='nan2008',
  222. gcc_cfg=['--with-mips-plt', '--with-nan=2008',
  223. '--with-arch-64=mips64r2',
  224. '--with-arch-32=mips32r2'],
  225. glibcs=[{'variant': 'n32-nan2008'},
  226. {'variant': 'nan2008',
  227. 'arch': 'mips',
  228. 'ccopts': '-mabi=32'},
  229. {'variant': 'n64-nan2008',
  230. 'ccopts': '-mabi=64'}])
  231. self.add_config(arch='mips64',
  232. os_name='linux-gnu',
  233. variant='nan2008-soft',
  234. gcc_cfg=['--with-mips-plt', '--with-nan=2008',
  235. '--with-arch-64=mips64r2',
  236. '--with-arch-32=mips32r2',
  237. '--with-float=soft'],
  238. glibcs=[{'variant': 'n32-nan2008-soft'},
  239. {'variant': 'nan2008-soft',
  240. 'arch': 'mips',
  241. 'ccopts': '-mabi=32'},
  242. {'variant': 'n64-nan2008-soft',
  243. 'ccopts': '-mabi=64'}])
  244. self.add_config(arch='mips64el',
  245. os_name='linux-gnu',
  246. gcc_cfg=['--with-mips-plt'],
  247. glibcs=[{'variant': 'n32'},
  248. {'arch': 'mipsel',
  249. 'ccopts': '-mabi=32'},
  250. {'variant': 'n64',
  251. 'ccopts': '-mabi=64'}])
  252. self.add_config(arch='mips64el',
  253. os_name='linux-gnu',
  254. variant='soft',
  255. gcc_cfg=['--with-mips-plt', '--with-float=soft'],
  256. glibcs=[{'variant': 'n32-soft'},
  257. {'variant': 'soft',
  258. 'arch': 'mipsel',
  259. 'ccopts': '-mabi=32'},
  260. {'variant': 'n64-soft',
  261. 'ccopts': '-mabi=64'}])
  262. self.add_config(arch='mips64el',
  263. os_name='linux-gnu',
  264. variant='nan2008',
  265. gcc_cfg=['--with-mips-plt', '--with-nan=2008',
  266. '--with-arch-64=mips64r2',
  267. '--with-arch-32=mips32r2'],
  268. glibcs=[{'variant': 'n32-nan2008'},
  269. {'variant': 'nan2008',
  270. 'arch': 'mipsel',
  271. 'ccopts': '-mabi=32'},
  272. {'variant': 'n64-nan2008',
  273. 'ccopts': '-mabi=64'}])
  274. self.add_config(arch='mips64el',
  275. os_name='linux-gnu',
  276. variant='nan2008-soft',
  277. gcc_cfg=['--with-mips-plt', '--with-nan=2008',
  278. '--with-arch-64=mips64r2',
  279. '--with-arch-32=mips32r2',
  280. '--with-float=soft'],
  281. glibcs=[{'variant': 'n32-nan2008-soft'},
  282. {'variant': 'nan2008-soft',
  283. 'arch': 'mipsel',
  284. 'ccopts': '-mabi=32'},
  285. {'variant': 'n64-nan2008-soft',
  286. 'ccopts': '-mabi=64'}])
  287. self.add_config(arch='nios2',
  288. os_name='linux-gnu')
  289. self.add_config(arch='powerpc',
  290. os_name='linux-gnu',
  291. gcc_cfg=['--disable-multilib', '--enable-secureplt'],
  292. extra_glibcs=[{'variant': 'power4',
  293. 'ccopts': '-mcpu=power4',
  294. 'cfg': ['--with-cpu=power4']}])
  295. self.add_config(arch='powerpc',
  296. os_name='linux-gnu',
  297. variant='soft',
  298. gcc_cfg=['--disable-multilib', '--with-float=soft',
  299. '--enable-secureplt'])
  300. self.add_config(arch='powerpc64',
  301. os_name='linux-gnu',
  302. gcc_cfg=['--disable-multilib', '--enable-secureplt'])
  303. self.add_config(arch='powerpc64le',
  304. os_name='linux-gnu',
  305. gcc_cfg=['--disable-multilib', '--enable-secureplt'])
  306. self.add_config(arch='powerpc',
  307. os_name='linux-gnuspe',
  308. gcc_cfg=['--disable-multilib', '--enable-secureplt',
  309. '--enable-e500-double', '--enable-obsolete'])
  310. self.add_config(arch='powerpc',
  311. os_name='linux-gnuspe',
  312. variant='e500v1',
  313. gcc_cfg=['--disable-multilib', '--enable-secureplt',
  314. '--enable-obsolete'])
  315. self.add_config(arch='riscv64',
  316. os_name='linux-gnu',
  317. variant='rv64imac-lp64',
  318. gcc_cfg=['--with-arch=rv64imac', '--with-abi=lp64',
  319. '--disable-multilib'])
  320. self.add_config(arch='riscv64',
  321. os_name='linux-gnu',
  322. variant='rv64imafdc-lp64',
  323. gcc_cfg=['--with-arch=rv64imafdc', '--with-abi=lp64',
  324. '--disable-multilib'])
  325. self.add_config(arch='riscv64',
  326. os_name='linux-gnu',
  327. variant='rv64imafdc-lp64d',
  328. gcc_cfg=['--with-arch=rv64imafdc', '--with-abi=lp64d',
  329. '--disable-multilib'])
  330. self.add_config(arch='s390x',
  331. os_name='linux-gnu',
  332. glibcs=[{},
  333. {'arch': 's390', 'ccopts': '-m31'}])
  334. self.add_config(arch='sh3',
  335. os_name='linux-gnu')
  336. self.add_config(arch='sh3eb',
  337. os_name='linux-gnu')
  338. self.add_config(arch='sh4',
  339. os_name='linux-gnu')
  340. self.add_config(arch='sh4eb',
  341. os_name='linux-gnu')
  342. self.add_config(arch='sh4',
  343. os_name='linux-gnu',
  344. variant='soft',
  345. gcc_cfg=['--without-fp'])
  346. self.add_config(arch='sh4eb',
  347. os_name='linux-gnu',
  348. variant='soft',
  349. gcc_cfg=['--without-fp'])
  350. self.add_config(arch='sparc64',
  351. os_name='linux-gnu',
  352. glibcs=[{},
  353. {'arch': 'sparcv9',
  354. 'ccopts': '-m32 -mlong-double-128'}],
  355. extra_glibcs=[{'variant': 'disable-multi-arch',
  356. 'cfg': ['--disable-multi-arch']},
  357. {'variant': 'disable-multi-arch',
  358. 'arch': 'sparcv9',
  359. 'ccopts': '-m32 -mlong-double-128',
  360. 'cfg': ['--disable-multi-arch']}])
  361. self.add_config(arch='x86_64',
  362. os_name='linux-gnu',
  363. gcc_cfg=['--with-multilib-list=m64,m32,mx32'],
  364. glibcs=[{},
  365. {'variant': 'x32', 'ccopts': '-mx32'},
  366. {'arch': 'i686', 'ccopts': '-m32 -march=i686'}],
  367. extra_glibcs=[{'variant': 'disable-multi-arch',
  368. 'cfg': ['--disable-multi-arch']},
  369. {'variant': 'enable-obsolete',
  370. 'cfg': ['--enable-obsolete-rpc',
  371. '--enable-obsolete-nsl']},
  372. {'variant': 'static-pie',
  373. 'cfg': ['--enable-static-pie']},
  374. {'variant': 'x32-static-pie',
  375. 'ccopts': '-mx32',
  376. 'cfg': ['--enable-static-pie']},
  377. {'variant': 'static-pie',
  378. 'arch': 'i686',
  379. 'ccopts': '-m32 -march=i686',
  380. 'cfg': ['--enable-static-pie']},
  381. {'variant': 'disable-multi-arch',
  382. 'arch': 'i686',
  383. 'ccopts': '-m32 -march=i686',
  384. 'cfg': ['--disable-multi-arch']},
  385. {'variant': 'enable-obsolete',
  386. 'arch': 'i686',
  387. 'ccopts': '-m32 -march=i686',
  388. 'cfg': ['--enable-obsolete-rpc',
  389. '--enable-obsolete-nsl']},
  390. {'arch': 'i486',
  391. 'ccopts': '-m32 -march=i486'},
  392. {'arch': 'i586',
  393. 'ccopts': '-m32 -march=i586'}])
  394. def add_config(self, **args):
  395. """Add an individual build configuration."""
  396. cfg = Config(self, **args)
  397. if cfg.name in self.configs:
  398. print('error: duplicate config %s' % cfg.name)
  399. exit(1)
  400. self.configs[cfg.name] = cfg
  401. for c in cfg.all_glibcs:
  402. if c.name in self.glibc_configs:
  403. print('error: duplicate glibc config %s' % c.name)
  404. exit(1)
  405. self.glibc_configs[c.name] = c
  406. def component_srcdir(self, component):
  407. """Return the source directory for a given component, e.g. gcc."""
  408. return os.path.join(self.srcdir, component)
  409. def component_builddir(self, action, config, component, subconfig=None):
  410. """Return the directory to use for a build."""
  411. if config is None:
  412. # Host libraries.
  413. assert subconfig is None
  414. return os.path.join(self.builddir, action, component)
  415. if subconfig is None:
  416. return os.path.join(self.builddir, action, config, component)
  417. else:
  418. # glibc build as part of compiler build.
  419. return os.path.join(self.builddir, action, config, component,
  420. subconfig)
  421. def compiler_installdir(self, config):
  422. """Return the directory in which to install a compiler."""
  423. return os.path.join(self.installdir, 'compilers', config)
  424. def compiler_bindir(self, config):
  425. """Return the directory in which to find compiler binaries."""
  426. return os.path.join(self.compiler_installdir(config), 'bin')
  427. def compiler_sysroot(self, config):
  428. """Return the sysroot directory for a compiler."""
  429. return os.path.join(self.compiler_installdir(config), 'sysroot')
  430. def glibc_installdir(self, config):
  431. """Return the directory in which to install glibc."""
  432. return os.path.join(self.installdir, 'glibcs', config)
  433. def run_builds(self, action, configs):
  434. """Run the requested builds."""
  435. if action == 'checkout':
  436. self.checkout(configs)
  437. return
  438. if action == 'bot-cycle':
  439. if configs:
  440. print('error: configurations specified for bot-cycle')
  441. exit(1)
  442. self.bot_cycle()
  443. return
  444. if action == 'bot':
  445. if configs:
  446. print('error: configurations specified for bot')
  447. exit(1)
  448. self.bot()
  449. return
  450. if action == 'host-libraries' and configs:
  451. print('error: configurations specified for host-libraries')
  452. exit(1)
  453. self.clear_last_build_state(action)
  454. build_time = datetime.datetime.utcnow()
  455. if action == 'host-libraries':
  456. build_components = ('gmp', 'mpfr', 'mpc')
  457. old_components = ()
  458. old_versions = {}
  459. self.build_host_libraries()
  460. elif action == 'compilers':
  461. build_components = ('binutils', 'gcc', 'glibc', 'linux', 'mig',
  462. 'gnumach', 'hurd')
  463. old_components = ('gmp', 'mpfr', 'mpc')
  464. old_versions = self.build_state['host-libraries']['build-versions']
  465. self.build_compilers(configs)
  466. else:
  467. build_components = ('glibc',)
  468. old_components = ('gmp', 'mpfr', 'mpc', 'binutils', 'gcc', 'linux',
  469. 'mig', 'gnumach', 'hurd')
  470. old_versions = self.build_state['compilers']['build-versions']
  471. self.build_glibcs(configs)
  472. self.write_files()
  473. self.do_build()
  474. if configs:
  475. # Partial build, do not update stored state.
  476. return
  477. build_versions = {}
  478. for k in build_components:
  479. if k in self.versions:
  480. build_versions[k] = {'version': self.versions[k]['version'],
  481. 'revision': self.versions[k]['revision']}
  482. for k in old_components:
  483. if k in old_versions:
  484. build_versions[k] = {'version': old_versions[k]['version'],
  485. 'revision': old_versions[k]['revision']}
  486. self.update_build_state(action, build_time, build_versions)
  487. @staticmethod
  488. def remove_dirs(*args):
  489. """Remove directories and their contents if they exist."""
  490. for dir in args:
  491. shutil.rmtree(dir, ignore_errors=True)
  492. @staticmethod
  493. def remove_recreate_dirs(*args):
  494. """Remove directories if they exist, and create them as empty."""
  495. Context.remove_dirs(*args)
  496. for dir in args:
  497. os.makedirs(dir, exist_ok=True)
  498. def add_makefile_cmdlist(self, target, cmdlist, logsdir):
  499. """Add makefile text for a list of commands."""
  500. commands = cmdlist.makefile_commands(self.wrapper, logsdir)
  501. self.makefile_pieces.append('all: %s\n.PHONY: %s\n%s:\n%s\n' %
  502. (target, target, target, commands))
  503. self.status_log_list.extend(cmdlist.status_logs(logsdir))
  504. def write_files(self):
  505. """Write out the Makefile and wrapper script."""
  506. mftext = ''.join(self.makefile_pieces)
  507. with open(self.makefile, 'w') as f:
  508. f.write(mftext)
  509. wrapper_text = (
  510. '#!/bin/sh\n'
  511. 'prev_base=$1\n'
  512. 'this_base=$2\n'
  513. 'desc=$3\n'
  514. 'dir=$4\n'
  515. 'path=$5\n'
  516. 'shift 5\n'
  517. 'prev_status=$prev_base-status.txt\n'
  518. 'this_status=$this_base-status.txt\n'
  519. 'this_log=$this_base-log.txt\n'
  520. 'date > "$this_log"\n'
  521. 'echo >> "$this_log"\n'
  522. 'echo "Description: $desc" >> "$this_log"\n'
  523. 'printf "%s" "Command:" >> "$this_log"\n'
  524. 'for word in "$@"; do\n'
  525. ' if expr "$word" : "[]+,./0-9@A-Z_a-z-]\\\\{1,\\\\}\\$" > /dev/null; then\n'
  526. ' printf " %s" "$word"\n'
  527. ' else\n'
  528. ' printf " \'"\n'
  529. ' printf "%s" "$word" | sed -e "s/\'/\'\\\\\\\\\'\'/"\n'
  530. ' printf "\'"\n'
  531. ' fi\n'
  532. 'done >> "$this_log"\n'
  533. 'echo >> "$this_log"\n'
  534. 'echo "Directory: $dir" >> "$this_log"\n'
  535. 'echo "Path addition: $path" >> "$this_log"\n'
  536. 'echo >> "$this_log"\n'
  537. 'record_status ()\n'
  538. '{\n'
  539. ' echo >> "$this_log"\n'
  540. ' echo "$1: $desc" > "$this_status"\n'
  541. ' echo "$1: $desc" >> "$this_log"\n'
  542. ' echo >> "$this_log"\n'
  543. ' date >> "$this_log"\n'
  544. ' echo "$1: $desc"\n'
  545. ' exit 0\n'
  546. '}\n'
  547. 'check_error ()\n'
  548. '{\n'
  549. ' if [ "$1" != "0" ]; then\n'
  550. ' record_status FAIL\n'
  551. ' fi\n'
  552. '}\n'
  553. 'if [ "$prev_base" ] && ! grep -q "^PASS" "$prev_status"; then\n'
  554. ' record_status UNRESOLVED\n'
  555. 'fi\n'
  556. 'if [ "$dir" ]; then\n'
  557. ' cd "$dir"\n'
  558. ' check_error "$?"\n'
  559. 'fi\n'
  560. 'if [ "$path" ]; then\n'
  561. ' PATH=$path:$PATH\n'
  562. 'fi\n'
  563. '"$@" < /dev/null >> "$this_log" 2>&1\n'
  564. 'check_error "$?"\n'
  565. 'record_status PASS\n')
  566. with open(self.wrapper, 'w') as f:
  567. f.write(wrapper_text)
  568. # Mode 0o755.
  569. mode_exec = (stat.S_IRWXU|stat.S_IRGRP|stat.S_IXGRP|
  570. stat.S_IROTH|stat.S_IXOTH)
  571. os.chmod(self.wrapper, mode_exec)
  572. save_logs_text = (
  573. '#!/bin/sh\n'
  574. 'if ! [ -f tests.sum ]; then\n'
  575. ' echo "No test summary available."\n'
  576. ' exit 0\n'
  577. 'fi\n'
  578. 'save_file ()\n'
  579. '{\n'
  580. ' echo "Contents of $1:"\n'
  581. ' echo\n'
  582. ' cat "$1"\n'
  583. ' echo\n'
  584. ' echo "End of contents of $1."\n'
  585. ' echo\n'
  586. '}\n'
  587. 'save_file tests.sum\n'
  588. 'non_pass_tests=$(grep -v "^PASS: " tests.sum | sed -e "s/^PASS: //")\n'
  589. 'for t in $non_pass_tests; do\n'
  590. ' if [ -f "$t.out" ]; then\n'
  591. ' save_file "$t.out"\n'
  592. ' fi\n'
  593. 'done\n')
  594. with open(self.save_logs, 'w') as f:
  595. f.write(save_logs_text)
  596. os.chmod(self.save_logs, mode_exec)
  597. def do_build(self):
  598. """Do the actual build."""
  599. cmd = ['make', '-j%d' % self.parallelism]
  600. subprocess.run(cmd, cwd=self.builddir, check=True)
  601. def build_host_libraries(self):
  602. """Build the host libraries."""
  603. installdir = self.host_libraries_installdir
  604. builddir = os.path.join(self.builddir, 'host-libraries')
  605. logsdir = os.path.join(self.logsdir, 'host-libraries')
  606. self.remove_recreate_dirs(installdir, builddir, logsdir)
  607. cmdlist = CommandList('host-libraries', self.keep)
  608. self.build_host_library(cmdlist, 'gmp')
  609. self.build_host_library(cmdlist, 'mpfr',
  610. ['--with-gmp=%s' % installdir])
  611. self.build_host_library(cmdlist, 'mpc',
  612. ['--with-gmp=%s' % installdir,
  613. '--with-mpfr=%s' % installdir])
  614. cmdlist.add_command('done', ['touch', os.path.join(installdir, 'ok')])
  615. self.add_makefile_cmdlist('host-libraries', cmdlist, logsdir)
  616. def build_host_library(self, cmdlist, lib, extra_opts=None):
  617. """Build one host library."""
  618. srcdir = self.component_srcdir(lib)
  619. builddir = self.component_builddir('host-libraries', None, lib)
  620. installdir = self.host_libraries_installdir
  621. cmdlist.push_subdesc(lib)
  622. cmdlist.create_use_dir(builddir)
  623. cfg_cmd = [os.path.join(srcdir, 'configure'),
  624. '--prefix=%s' % installdir,
  625. '--disable-shared']
  626. if extra_opts:
  627. cfg_cmd.extend (extra_opts)
  628. cmdlist.add_command('configure', cfg_cmd)
  629. cmdlist.add_command('build', ['make'])
  630. cmdlist.add_command('check', ['make', 'check'])
  631. cmdlist.add_command('install', ['make', 'install'])
  632. cmdlist.cleanup_dir()
  633. cmdlist.pop_subdesc()
  634. def build_compilers(self, configs):
  635. """Build the compilers."""
  636. if not configs:
  637. self.remove_dirs(os.path.join(self.builddir, 'compilers'))
  638. self.remove_dirs(os.path.join(self.installdir, 'compilers'))
  639. self.remove_dirs(os.path.join(self.logsdir, 'compilers'))
  640. configs = sorted(self.configs.keys())
  641. for c in configs:
  642. self.configs[c].build()
  643. def build_glibcs(self, configs):
  644. """Build the glibcs."""
  645. if not configs:
  646. self.remove_dirs(os.path.join(self.builddir, 'glibcs'))
  647. self.remove_dirs(os.path.join(self.installdir, 'glibcs'))
  648. self.remove_dirs(os.path.join(self.logsdir, 'glibcs'))
  649. configs = sorted(self.glibc_configs.keys())
  650. for c in configs:
  651. self.glibc_configs[c].build()
  652. def load_versions_json(self):
  653. """Load information about source directory versions."""
  654. if not os.access(self.versions_json, os.F_OK):
  655. self.versions = {}
  656. return
  657. with open(self.versions_json, 'r') as f:
  658. self.versions = json.load(f)
  659. def store_json(self, data, filename):
  660. """Store information in a JSON file."""
  661. filename_tmp = filename + '.tmp'
  662. with open(filename_tmp, 'w') as f:
  663. json.dump(data, f, indent=2, sort_keys=True)
  664. os.rename(filename_tmp, filename)
  665. def store_versions_json(self):
  666. """Store information about source directory versions."""
  667. self.store_json(self.versions, self.versions_json)
  668. def set_component_version(self, component, version, explicit, revision):
  669. """Set the version information for a component."""
  670. self.versions[component] = {'version': version,
  671. 'explicit': explicit,
  672. 'revision': revision}
  673. self.store_versions_json()
  674. def checkout(self, versions):
  675. """Check out the desired component versions."""
  676. default_versions = {'binutils': 'vcs-2.32',
  677. 'gcc': 'vcs-8',
  678. 'glibc': 'vcs-mainline',
  679. 'gmp': '6.1.2',
  680. 'linux': '4.20',
  681. 'mpc': '1.1.0',
  682. 'mpfr': '4.0.1',
  683. 'mig': 'vcs-mainline',
  684. 'gnumach': 'vcs-mainline',
  685. 'hurd': 'vcs-mainline'}
  686. use_versions = {}
  687. explicit_versions = {}
  688. for v in versions:
  689. found_v = False
  690. for k in default_versions.keys():
  691. kx = k + '-'
  692. if v.startswith(kx):
  693. vx = v[len(kx):]
  694. if k in use_versions:
  695. print('error: multiple versions for %s' % k)
  696. exit(1)
  697. use_versions[k] = vx
  698. explicit_versions[k] = True
  699. found_v = True
  700. break
  701. if not found_v:
  702. print('error: unknown component in %s' % v)
  703. exit(1)
  704. for k in default_versions.keys():
  705. if k not in use_versions:
  706. if k in self.versions and self.versions[k]['explicit']:
  707. use_versions[k] = self.versions[k]['version']
  708. explicit_versions[k] = True
  709. else:
  710. use_versions[k] = default_versions[k]
  711. explicit_versions[k] = False
  712. os.makedirs(self.srcdir, exist_ok=True)
  713. for k in sorted(default_versions.keys()):
  714. update = os.access(self.component_srcdir(k), os.F_OK)
  715. v = use_versions[k]
  716. if (update and
  717. k in self.versions and
  718. v != self.versions[k]['version']):
  719. if not self.replace_sources:
  720. print('error: version of %s has changed from %s to %s, '
  721. 'use --replace-sources to check out again' %
  722. (k, self.versions[k]['version'], v))
  723. exit(1)
  724. shutil.rmtree(self.component_srcdir(k))
  725. update = False
  726. if v.startswith('vcs-'):
  727. revision = self.checkout_vcs(k, v[4:], update)
  728. else:
  729. self.checkout_tar(k, v, update)
  730. revision = v
  731. self.set_component_version(k, v, explicit_versions[k], revision)
  732. if self.get_script_text() != self.script_text:
  733. # Rerun the checkout process in case the updated script
  734. # uses different default versions or new components.
  735. self.exec_self()
  736. def checkout_vcs(self, component, version, update):
  737. """Check out the given version of the given component from version
  738. control. Return a revision identifier."""
  739. if component == 'binutils':
  740. git_url = 'git://sourceware.org/git/binutils-gdb.git'
  741. if version == 'mainline':
  742. git_branch = 'master'
  743. else:
  744. trans = str.maketrans({'.': '_'})
  745. git_branch = 'binutils-%s-branch' % version.translate(trans)
  746. return self.git_checkout(component, git_url, git_branch, update)
  747. elif component == 'gcc':
  748. if version == 'mainline':
  749. branch = 'trunk'
  750. else:
  751. trans = str.maketrans({'.': '_'})
  752. branch = 'branches/gcc-%s-branch' % version.translate(trans)
  753. svn_url = 'svn://gcc.gnu.org/svn/gcc/%s' % branch
  754. return self.gcc_checkout(svn_url, update)
  755. elif component == 'glibc':
  756. git_url = 'git://sourceware.org/git/glibc.git'
  757. if version == 'mainline':
  758. git_branch = 'master'
  759. else:
  760. git_branch = 'release/%s/master' % version
  761. r = self.git_checkout(component, git_url, git_branch, update)
  762. self.fix_glibc_timestamps()
  763. return r
  764. elif component == 'gnumach':
  765. git_url = 'git://git.savannah.gnu.org/hurd/gnumach.git'
  766. git_branch = 'master'
  767. r = self.git_checkout(component, git_url, git_branch, update)
  768. subprocess.run(['autoreconf', '-i'],
  769. cwd=self.component_srcdir(component), check=True)
  770. return r
  771. elif component == 'mig':
  772. git_url = 'git://git.savannah.gnu.org/hurd/mig.git'
  773. git_branch = 'master'
  774. r = self.git_checkout(component, git_url, git_branch, update)
  775. subprocess.run(['autoreconf', '-i'],
  776. cwd=self.component_srcdir(component), check=True)
  777. return r
  778. elif component == 'hurd':
  779. git_url = 'git://git.savannah.gnu.org/hurd/hurd.git'
  780. git_branch = 'master'
  781. r = self.git_checkout(component, git_url, git_branch, update)
  782. subprocess.run(['autoconf'],
  783. cwd=self.component_srcdir(component), check=True)
  784. return r
  785. else:
  786. print('error: component %s coming from VCS' % component)
  787. exit(1)
  788. def git_checkout(self, component, git_url, git_branch, update):
  789. """Check out a component from git. Return a commit identifier."""
  790. if update:
  791. subprocess.run(['git', 'remote', 'prune', 'origin'],
  792. cwd=self.component_srcdir(component), check=True)
  793. if self.replace_sources:
  794. subprocess.run(['git', 'clean', '-dxfq'],
  795. cwd=self.component_srcdir(component), check=True)
  796. subprocess.run(['git', 'pull', '-q'],
  797. cwd=self.component_srcdir(component), check=True)
  798. else:
  799. subprocess.run(['git', 'clone', '-q', '-b', git_branch, git_url,
  800. self.component_srcdir(component)], check=True)
  801. r = subprocess.run(['git', 'rev-parse', 'HEAD'],
  802. cwd=self.component_srcdir(component),
  803. stdout=subprocess.PIPE,
  804. check=True, universal_newlines=True).stdout
  805. return r.rstrip()
  806. def fix_glibc_timestamps(self):
  807. """Fix timestamps in a glibc checkout."""
  808. # Ensure that builds do not try to regenerate generated files
  809. # in the source tree.
  810. srcdir = self.component_srcdir('glibc')
  811. # These files have Makefile dependencies to regenerate them in
  812. # the source tree that may be active during a normal build.
  813. # Some other files have such dependencies but do not need to
  814. # be touched because nothing in a build depends on the files
  815. # in question.
  816. for f in ('sysdeps/gnu/errlist.c',
  817. 'sysdeps/mach/hurd/bits/errno.h',
  818. 'sysdeps/sparc/sparc32/rem.S',
  819. 'sysdeps/sparc/sparc32/sdiv.S',
  820. 'sysdeps/sparc/sparc32/udiv.S',
  821. 'sysdeps/sparc/sparc32/urem.S'):
  822. to_touch = os.path.join(srcdir, f)
  823. subprocess.run(['touch', '-c', to_touch], check=True)
  824. for dirpath, dirnames, filenames in os.walk(srcdir):
  825. for f in filenames:
  826. if (f == 'configure' or
  827. f == 'preconfigure' or
  828. f.endswith('-kw.h')):
  829. to_touch = os.path.join(dirpath, f)
  830. subprocess.run(['touch', to_touch], check=True)
  831. def gcc_checkout(self, svn_url, update):
  832. """Check out GCC from SVN. Return the revision number."""
  833. if not update:
  834. subprocess.run(['svn', 'co', '-q', svn_url,
  835. self.component_srcdir('gcc')], check=True)
  836. subprocess.run(['contrib/gcc_update', '--silent'],
  837. cwd=self.component_srcdir('gcc'), check=True)
  838. r = subprocess.run(['svnversion', self.component_srcdir('gcc')],
  839. stdout=subprocess.PIPE,
  840. check=True, universal_newlines=True).stdout
  841. return r.rstrip()
  842. def checkout_tar(self, component, version, update):
  843. """Check out the given version of the given component from a
  844. tarball."""
  845. if update:
  846. return
  847. url_map = {'binutils': 'https://ftp.gnu.org/gnu/binutils/binutils-%(version)s.tar.bz2',
  848. 'gcc': 'https://ftp.gnu.org/gnu/gcc/gcc-%(version)s/gcc-%(version)s.tar.gz',
  849. 'gmp': 'https://ftp.gnu.org/gnu/gmp/gmp-%(version)s.tar.xz',
  850. 'linux': 'https://www.kernel.org/pub/linux/kernel/v4.x/linux-%(version)s.tar.xz',
  851. 'mpc': 'https://ftp.gnu.org/gnu/mpc/mpc-%(version)s.tar.gz',
  852. 'mpfr': 'https://ftp.gnu.org/gnu/mpfr/mpfr-%(version)s.tar.xz',
  853. 'mig': 'https://ftp.gnu.org/gnu/mig/mig-%(version)s.tar.bz2',
  854. 'gnumach': 'https://ftp.gnu.org/gnu/gnumach/gnumach-%(version)s.tar.bz2',
  855. 'hurd': 'https://ftp.gnu.org/gnu/hurd/hurd-%(version)s.tar.bz2'}
  856. if component not in url_map:
  857. print('error: component %s coming from tarball' % component)
  858. exit(1)
  859. url = url_map[component] % {'version': version}
  860. filename = os.path.join(self.srcdir, url.split('/')[-1])
  861. response = urllib.request.urlopen(url)
  862. data = response.read()
  863. with open(filename, 'wb') as f:
  864. f.write(data)
  865. subprocess.run(['tar', '-C', self.srcdir, '-x', '-f', filename],
  866. check=True)
  867. os.rename(os.path.join(self.srcdir, '%s-%s' % (component, version)),
  868. self.component_srcdir(component))
  869. os.remove(filename)
  870. def load_build_state_json(self):
  871. """Load information about the state of previous builds."""
  872. if os.access(self.build_state_json, os.F_OK):
  873. with open(self.build_state_json, 'r') as f:
  874. self.build_state = json.load(f)
  875. else:
  876. self.build_state = {}
  877. for k in ('host-libraries', 'compilers', 'glibcs'):
  878. if k not in self.build_state:
  879. self.build_state[k] = {}
  880. if 'build-time' not in self.build_state[k]:
  881. self.build_state[k]['build-time'] = ''
  882. if 'build-versions' not in self.build_state[k]:
  883. self.build_state[k]['build-versions'] = {}
  884. if 'build-results' not in self.build_state[k]:
  885. self.build_state[k]['build-results'] = {}
  886. if 'result-changes' not in self.build_state[k]:
  887. self.build_state[k]['result-changes'] = {}
  888. if 'ever-passed' not in self.build_state[k]:
  889. self.build_state[k]['ever-passed'] = []
  890. def store_build_state_json(self):
  891. """Store information about the state of previous builds."""
  892. self.store_json(self.build_state, self.build_state_json)
  893. def clear_last_build_state(self, action):
  894. """Clear information about the state of part of the build."""
  895. # We clear the last build time and versions when starting a
  896. # new build. The results of the last build are kept around,
  897. # as comparison is still meaningful if this build is aborted
  898. # and a new one started.
  899. self.build_state[action]['build-time'] = ''
  900. self.build_state[action]['build-versions'] = {}
  901. self.store_build_state_json()
  902. def update_build_state(self, action, build_time, build_versions):
  903. """Update the build state after a build."""
  904. build_time = build_time.replace(microsecond=0)
  905. self.build_state[action]['build-time'] = str(build_time)
  906. self.build_state[action]['build-versions'] = build_versions
  907. build_results = {}
  908. for log in self.status_log_list:
  909. with open(log, 'r') as f:
  910. log_text = f.read()
  911. log_text = log_text.rstrip()
  912. m = re.fullmatch('([A-Z]+): (.*)', log_text)
  913. result = m.group(1)
  914. test_name = m.group(2)
  915. assert test_name not in build_results
  916. build_results[test_name] = result
  917. old_build_results = self.build_state[action]['build-results']
  918. self.build_state[action]['build-results'] = build_results
  919. result_changes = {}
  920. all_tests = set(old_build_results.keys()) | set(build_results.keys())
  921. for t in all_tests:
  922. if t in old_build_results:
  923. old_res = old_build_results[t]
  924. else:
  925. old_res = '(New test)'
  926. if t in build_results:
  927. new_res = build_results[t]
  928. else:
  929. new_res = '(Test removed)'
  930. if old_res != new_res:
  931. result_changes[t] = '%s -> %s' % (old_res, new_res)
  932. self.build_state[action]['result-changes'] = result_changes
  933. old_ever_passed = {t for t in self.build_state[action]['ever-passed']
  934. if t in build_results}
  935. new_passes = {t for t in build_results if build_results[t] == 'PASS'}
  936. self.build_state[action]['ever-passed'] = sorted(old_ever_passed |
  937. new_passes)
  938. self.store_build_state_json()
  939. def load_bot_config_json(self):
  940. """Load bot configuration."""
  941. with open(self.bot_config_json, 'r') as f:
  942. self.bot_config = json.load(f)
  943. def part_build_old(self, action, delay):
  944. """Return whether the last build for a given action was at least a
  945. given number of seconds ago, or does not have a time recorded."""
  946. old_time_str = self.build_state[action]['build-time']
  947. if not old_time_str:
  948. return True
  949. old_time = datetime.datetime.strptime(old_time_str,
  950. '%Y-%m-%d %H:%M:%S')
  951. new_time = datetime.datetime.utcnow()
  952. delta = new_time - old_time
  953. return delta.total_seconds() >= delay
  954. def bot_cycle(self):
  955. """Run a single round of checkout and builds."""
  956. print('Bot cycle starting %s.' % str(datetime.datetime.utcnow()))
  957. self.load_bot_config_json()
  958. actions = ('host-libraries', 'compilers', 'glibcs')
  959. self.bot_run_self(['--replace-sources'], 'checkout')
  960. self.load_versions_json()
  961. if self.get_script_text() != self.script_text:
  962. print('Script changed, re-execing.')
  963. # On script change, all parts of the build should be rerun.
  964. for a in actions:
  965. self.clear_last_build_state(a)
  966. self.exec_self()
  967. check_components = {'host-libraries': ('gmp', 'mpfr', 'mpc'),
  968. 'compilers': ('binutils', 'gcc', 'glibc', 'linux',
  969. 'mig', 'gnumach', 'hurd'),
  970. 'glibcs': ('glibc',)}
  971. must_build = {}
  972. for a in actions:
  973. build_vers = self.build_state[a]['build-versions']
  974. must_build[a] = False
  975. if not self.build_state[a]['build-time']:
  976. must_build[a] = True
  977. old_vers = {}
  978. new_vers = {}
  979. for c in check_components[a]:
  980. if c in build_vers:
  981. old_vers[c] = build_vers[c]
  982. new_vers[c] = {'version': self.versions[c]['version'],
  983. 'revision': self.versions[c]['revision']}
  984. if new_vers == old_vers:
  985. print('Versions for %s unchanged.' % a)
  986. else:
  987. print('Versions changed or rebuild forced for %s.' % a)
  988. if a == 'compilers' and not self.part_build_old(
  989. a, self.bot_config['compilers-rebuild-delay']):
  990. print('Not requiring rebuild of compilers this soon.')
  991. else:
  992. must_build[a] = True
  993. if must_build['host-libraries']:
  994. must_build['compilers'] = True
  995. if must_build['compilers']:
  996. must_build['glibcs'] = True
  997. for a in actions:
  998. if must_build[a]:
  999. print('Must rebuild %s.' % a)
  1000. self.clear_last_build_state(a)
  1001. else:
  1002. print('No need to rebuild %s.' % a)
  1003. if os.access(self.logsdir, os.F_OK):
  1004. shutil.rmtree(self.logsdir_old, ignore_errors=True)
  1005. shutil.copytree(self.logsdir, self.logsdir_old)
  1006. for a in actions:
  1007. if must_build[a]:
  1008. build_time = datetime.datetime.utcnow()
  1009. print('Rebuilding %s at %s.' % (a, str(build_time)))
  1010. self.bot_run_self([], a)
  1011. self.load_build_state_json()
  1012. self.bot_build_mail(a, build_time)
  1013. print('Bot cycle done at %s.' % str(datetime.datetime.utcnow()))
  1014. def bot_build_mail(self, action, build_time):
  1015. """Send email with the results of a build."""
  1016. if not ('email-from' in self.bot_config and
  1017. 'email-server' in self.bot_config and
  1018. 'email-subject' in self.bot_config and
  1019. 'email-to' in self.bot_config):
  1020. if not self.email_warning:
  1021. print("Email not configured, not sending.")
  1022. self.email_warning = True
  1023. return
  1024. build_time = build_time.replace(microsecond=0)
  1025. subject = (self.bot_config['email-subject'] %
  1026. {'action': action,
  1027. 'build-time': str(build_time)})
  1028. results = self.build_state[action]['build-results']
  1029. changes = self.build_state[action]['result-changes']
  1030. ever_passed = set(self.build_state[action]['ever-passed'])
  1031. versions = self.build_state[action]['build-versions']
  1032. new_regressions = {k for k in changes if changes[k] == 'PASS -> FAIL'}
  1033. all_regressions = {k for k in ever_passed if results[k] == 'FAIL'}
  1034. all_fails = {k for k in results if results[k] == 'FAIL'}
  1035. if new_regressions:
  1036. new_reg_list = sorted(['FAIL: %s' % k for k in new_regressions])
  1037. new_reg_text = ('New regressions:\n\n%s\n\n' %
  1038. '\n'.join(new_reg_list))
  1039. else:
  1040. new_reg_text = ''
  1041. if all_regressions:
  1042. all_reg_list = sorted(['FAIL: %s' % k for k in all_regressions])
  1043. all_reg_text = ('All regressions:\n\n%s\n\n' %
  1044. '\n'.join(all_reg_list))
  1045. else:
  1046. all_reg_text = ''
  1047. if all_fails:
  1048. all_fail_list = sorted(['FAIL: %s' % k for k in all_fails])
  1049. all_fail_text = ('All failures:\n\n%s\n\n' %
  1050. '\n'.join(all_fail_list))
  1051. else:
  1052. all_fail_text = ''
  1053. if changes:
  1054. changes_list = sorted(changes.keys())
  1055. changes_list = ['%s: %s' % (changes[k], k) for k in changes_list]
  1056. changes_text = ('All changed results:\n\n%s\n\n' %
  1057. '\n'.join(changes_list))
  1058. else:
  1059. changes_text = ''
  1060. results_text = (new_reg_text + all_reg_text + all_fail_text +
  1061. changes_text)
  1062. if not results_text:
  1063. results_text = 'Clean build with unchanged results.\n\n'
  1064. versions_list = sorted(versions.keys())
  1065. versions_list = ['%s: %s (%s)' % (k, versions[k]['version'],
  1066. versions[k]['revision'])
  1067. for k in versions_list]
  1068. versions_text = ('Component versions for this build:\n\n%s\n' %
  1069. '\n'.join(versions_list))
  1070. body_text = results_text + versions_text
  1071. msg = email.mime.text.MIMEText(body_text)
  1072. msg['Subject'] = subject
  1073. msg['From'] = self.bot_config['email-from']
  1074. msg['To'] = self.bot_config['email-to']
  1075. msg['Message-ID'] = email.utils.make_msgid()
  1076. msg['Date'] = email.utils.format_datetime(datetime.datetime.utcnow())
  1077. with smtplib.SMTP(self.bot_config['email-server']) as s:
  1078. s.send_message(msg)
  1079. def bot_run_self(self, opts, action, check=True):
  1080. """Run a copy of this script with given options."""
  1081. cmd = [sys.executable, sys.argv[0], '--keep=none',
  1082. '-j%d' % self.parallelism]
  1083. if self.full_gcc:
  1084. cmd.append('--full-gcc')
  1085. cmd.extend(opts)
  1086. cmd.extend([self.topdir, action])
  1087. sys.stdout.flush()
  1088. subprocess.run(cmd, check=check)
  1089. def bot(self):
  1090. """Run repeated rounds of checkout and builds."""
  1091. while True:
  1092. self.load_bot_config_json()
  1093. if not self.bot_config['run']:
  1094. print('Bot exiting by request.')
  1095. exit(0)
  1096. self.bot_run_self([], 'bot-cycle', check=False)
  1097. self.load_bot_config_json()
  1098. if not self.bot_config['run']:
  1099. print('Bot exiting by request.')
  1100. exit(0)
  1101. time.sleep(self.bot_config['delay'])
  1102. if self.get_script_text() != self.script_text:
  1103. print('Script changed, bot re-execing.')
  1104. self.exec_self()
  1105. class Config(object):
  1106. """A configuration for building a compiler and associated libraries."""
  1107. def __init__(self, ctx, arch, os_name, variant=None, gcc_cfg=None,
  1108. first_gcc_cfg=None, glibcs=None, extra_glibcs=None):
  1109. """Initialize a Config object."""
  1110. self.ctx = ctx
  1111. self.arch = arch
  1112. self.os = os_name
  1113. self.variant = variant
  1114. if variant is None:
  1115. self.name = '%s-%s' % (arch, os_name)
  1116. else:
  1117. self.name = '%s-%s-%s' % (arch, os_name, variant)
  1118. self.triplet = '%s-glibc-%s' % (arch, os_name)
  1119. if gcc_cfg is None:
  1120. self.gcc_cfg = []
  1121. else:
  1122. self.gcc_cfg = gcc_cfg
  1123. if first_gcc_cfg is None:
  1124. self.first_gcc_cfg = []
  1125. else:
  1126. self.first_gcc_cfg = first_gcc_cfg
  1127. if glibcs is None:
  1128. glibcs = [{'variant': variant}]
  1129. if extra_glibcs is None:
  1130. extra_glibcs = []
  1131. glibcs = [Glibc(self, **g) for g in glibcs]
  1132. extra_glibcs = [Glibc(self, **g) for g in extra_glibcs]
  1133. self.all_glibcs = glibcs + extra_glibcs
  1134. self.compiler_glibcs = glibcs
  1135. self.installdir = ctx.compiler_installdir(self.name)
  1136. self.bindir = ctx.compiler_bindir(self.name)
  1137. self.sysroot = ctx.compiler_sysroot(self.name)
  1138. self.builddir = os.path.join(ctx.builddir, 'compilers', self.name)
  1139. self.logsdir = os.path.join(ctx.logsdir, 'compilers', self.name)
  1140. def component_builddir(self, component):
  1141. """Return the directory to use for a (non-glibc) build."""
  1142. return self.ctx.component_builddir('compilers', self.name, component)
  1143. def build(self):
  1144. """Generate commands to build this compiler."""
  1145. self.ctx.remove_recreate_dirs(self.installdir, self.builddir,
  1146. self.logsdir)
  1147. cmdlist = CommandList('compilers-%s' % self.name, self.ctx.keep)
  1148. cmdlist.add_command('check-host-libraries',
  1149. ['test', '-f',
  1150. os.path.join(self.ctx.host_libraries_installdir,
  1151. 'ok')])
  1152. cmdlist.use_path(self.bindir)
  1153. self.build_cross_tool(cmdlist, 'binutils', 'binutils',
  1154. ['--disable-gdb',
  1155. '--disable-libdecnumber',
  1156. '--disable-readline',
  1157. '--disable-sim'])
  1158. if self.os.startswith('linux'):
  1159. self.install_linux_headers(cmdlist)
  1160. self.build_gcc(cmdlist, True)
  1161. if self.os == 'gnu':
  1162. self.install_gnumach_headers(cmdlist)
  1163. self.build_cross_tool(cmdlist, 'mig', 'mig')
  1164. self.install_hurd_headers(cmdlist)
  1165. for g in self.compiler_glibcs:
  1166. cmdlist.push_subdesc('glibc')
  1167. cmdlist.push_subdesc(g.name)
  1168. g.build_glibc(cmdlist, True)
  1169. cmdlist.pop_subdesc()
  1170. cmdlist.pop_subdesc()
  1171. self.build_gcc(cmdlist, False)
  1172. cmdlist.add_command('done', ['touch',
  1173. os.path.join(self.installdir, 'ok')])
  1174. self.ctx.add_makefile_cmdlist('compilers-%s' % self.name, cmdlist,
  1175. self.logsdir)
  1176. def build_cross_tool(self, cmdlist, tool_src, tool_build, extra_opts=None):
  1177. """Build one cross tool."""
  1178. srcdir = self.ctx.component_srcdir(tool_src)
  1179. builddir = self.component_builddir(tool_build)
  1180. cmdlist.push_subdesc(tool_build)
  1181. cmdlist.create_use_dir(builddir)
  1182. cfg_cmd = [os.path.join(srcdir, 'configure'),
  1183. '--prefix=%s' % self.installdir,
  1184. '--build=%s' % self.ctx.build_triplet,
  1185. '--host=%s' % self.ctx.build_triplet,
  1186. '--target=%s' % self.triplet,
  1187. '--with-sysroot=%s' % self.sysroot]
  1188. if extra_opts:
  1189. cfg_cmd.extend(extra_opts)
  1190. cmdlist.add_command('configure', cfg_cmd)
  1191. cmdlist.add_command('build', ['make'])
  1192. # Parallel "make install" for GCC has race conditions that can
  1193. # cause it to fail; see
  1194. # <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=42980>. Such
  1195. # problems are not known for binutils, but doing the
  1196. # installation in parallel within a particular toolchain build
  1197. # (as opposed to installation of one toolchain from
  1198. # build-many-glibcs.py running in parallel to the installation
  1199. # of other toolchains being built) is not known to be
  1200. # significantly beneficial, so it is simplest just to disable
  1201. # parallel install for cross tools here.
  1202. cmdlist.add_command('install', ['make', '-j1', 'install'])
  1203. cmdlist.cleanup_dir()
  1204. cmdlist.pop_subdesc()
  1205. def install_linux_headers(self, cmdlist):
  1206. """Install Linux kernel headers."""
  1207. arch_map = {'aarch64': 'arm64',
  1208. 'alpha': 'alpha',
  1209. 'arm': 'arm',
  1210. 'csky': 'csky',
  1211. 'hppa': 'parisc',
  1212. 'i486': 'x86',
  1213. 'i586': 'x86',
  1214. 'i686': 'x86',
  1215. 'i786': 'x86',
  1216. 'ia64': 'ia64',
  1217. 'm68k': 'm68k',
  1218. 'microblaze': 'microblaze',
  1219. 'mips': 'mips',
  1220. 'nios2': 'nios2',
  1221. 'powerpc': 'powerpc',
  1222. 's390': 's390',
  1223. 'riscv32': 'riscv',
  1224. 'riscv64': 'riscv',
  1225. 'sh': 'sh',
  1226. 'sparc': 'sparc',
  1227. 'x86_64': 'x86'}
  1228. linux_arch = None
  1229. for k in arch_map:
  1230. if self.arch.startswith(k):
  1231. linux_arch = arch_map[k]
  1232. break
  1233. assert linux_arch is not None
  1234. srcdir = self.ctx.component_srcdir('linux')
  1235. builddir = self.component_builddir('linux')
  1236. headers_dir = os.path.join(self.sysroot, 'usr')
  1237. cmdlist.push_subdesc('linux')
  1238. cmdlist.create_use_dir(builddir)
  1239. cmdlist.add_command('install-headers',
  1240. ['make', '-C', srcdir, 'O=%s' % builddir,
  1241. 'ARCH=%s' % linux_arch,
  1242. 'INSTALL_HDR_PATH=%s' % headers_dir,
  1243. 'headers_install'])
  1244. cmdlist.cleanup_dir()
  1245. cmdlist.pop_subdesc()
  1246. def install_gnumach_headers(self, cmdlist):
  1247. """Install GNU Mach headers."""
  1248. srcdir = self.ctx.component_srcdir('gnumach')
  1249. builddir = self.component_builddir('gnumach')
  1250. cmdlist.push_subdesc('gnumach')
  1251. cmdlist.create_use_dir(builddir)
  1252. cmdlist.add_command('configure',
  1253. [os.path.join(srcdir, 'configure'),
  1254. '--build=%s' % self.ctx.build_triplet,
  1255. '--host=%s' % self.triplet,
  1256. '--prefix=',
  1257. 'CC=%s-gcc -nostdlib' % self.triplet])
  1258. cmdlist.add_command('install', ['make', 'DESTDIR=%s' % self.sysroot,
  1259. 'install-data'])
  1260. cmdlist.cleanup_dir()
  1261. cmdlist.pop_subdesc()
  1262. def install_hurd_headers(self, cmdlist):
  1263. """Install Hurd headers."""
  1264. srcdir = self.ctx.component_srcdir('hurd')
  1265. builddir = self.component_builddir('hurd')
  1266. cmdlist.push_subdesc('hurd')
  1267. cmdlist.create_use_dir(builddir)
  1268. cmdlist.add_command('configure',
  1269. [os.path.join(srcdir, 'configure'),
  1270. '--build=%s' % self.ctx.build_triplet,
  1271. '--host=%s' % self.triplet,
  1272. '--prefix=',
  1273. '--disable-profile', '--without-parted',
  1274. 'CC=%s-gcc -nostdlib' % self.triplet])
  1275. cmdlist.add_command('install', ['make', 'prefix=%s' % self.sysroot,
  1276. 'no_deps=t', 'install-headers'])
  1277. cmdlist.cleanup_dir()
  1278. cmdlist.pop_subdesc()
  1279. def build_gcc(self, cmdlist, bootstrap):
  1280. """Build GCC."""
  1281. # libssp is of little relevance with glibc's own stack
  1282. # checking support. libcilkrts does not support GNU/Hurd (and
  1283. # has been removed in GCC 8, so --disable-libcilkrts can be
  1284. # removed once glibc no longer supports building with older
  1285. # GCC versions).
  1286. cfg_opts = list(self.gcc_cfg)
  1287. cfg_opts += ['--disable-libssp', '--disable-libcilkrts']
  1288. host_libs = self.ctx.host_libraries_installdir
  1289. cfg_opts += ['--with-gmp=%s' % host_libs,
  1290. '--with-mpfr=%s' % host_libs,
  1291. '--with-mpc=%s' % host_libs]
  1292. if bootstrap:
  1293. tool_build = 'gcc-first'
  1294. # Building a static-only, C-only compiler that is
  1295. # sufficient to build glibc. Various libraries and
  1296. # features that may require libc headers must be disabled.
  1297. # When configuring with a sysroot, --with-newlib is
  1298. # required to define inhibit_libc (to stop some parts of
  1299. # libgcc including libc headers); --without-headers is not
  1300. # sufficient.
  1301. cfg_opts += ['--enable-languages=c', '--disable-shared',
  1302. '--disable-threads',
  1303. '--disable-libatomic',
  1304. '--disable-decimal-float',
  1305. '--disable-libffi',
  1306. '--disable-libgomp',
  1307. '--disable-libitm',
  1308. '--disable-libmpx',
  1309. '--disable-libquadmath',
  1310. '--disable-libsanitizer',
  1311. '--without-headers', '--with-newlib',
  1312. '--with-glibc-version=%s' % self.ctx.glibc_version
  1313. ]
  1314. cfg_opts += self.first_gcc_cfg
  1315. else:
  1316. tool_build = 'gcc'
  1317. # libsanitizer commonly breaks because of glibc header
  1318. # changes, or on unusual targets.
  1319. if not self.ctx.full_gcc:
  1320. cfg_opts += ['--disable-libsanitizer']
  1321. langs = 'all' if self.ctx.full_gcc else 'c,c++'
  1322. cfg_opts += ['--enable-languages=%s' % langs,
  1323. '--enable-shared', '--enable-threads']
  1324. self.build_cross_tool(cmdlist, 'gcc', tool_build, cfg_opts)
  1325. class Glibc(object):
  1326. """A configuration for building glibc."""
  1327. def __init__(self, compiler, arch=None, os_name=None, variant=None,
  1328. cfg=None, ccopts=None):
  1329. """Initialize a Glibc object."""
  1330. self.ctx = compiler.ctx
  1331. self.compiler = compiler
  1332. if arch is None:
  1333. self.arch = compiler.arch
  1334. else:
  1335. self.arch = arch
  1336. if os_name is None:
  1337. self.os = compiler.os
  1338. else:
  1339. self.os = os_name
  1340. self.variant = variant
  1341. if variant is None:
  1342. self.name = '%s-%s' % (self.arch, self.os)
  1343. else:
  1344. self.name = '%s-%s-%s' % (self.arch, self.os, variant)
  1345. self.triplet = '%s-glibc-%s' % (self.arch, self.os)
  1346. if cfg is None:
  1347. self.cfg = []
  1348. else:
  1349. self.cfg = cfg
  1350. self.ccopts = ccopts
  1351. def tool_name(self, tool):
  1352. """Return the name of a cross-compilation tool."""
  1353. ctool = '%s-%s' % (self.compiler.triplet, tool)
  1354. if self.ccopts and (tool == 'gcc' or tool == 'g++'):
  1355. ctool = '%s %s' % (ctool, self.ccopts)
  1356. return ctool
  1357. def build(self):
  1358. """Generate commands to build this glibc."""
  1359. builddir = self.ctx.component_builddir('glibcs', self.name, 'glibc')
  1360. installdir = self.ctx.glibc_installdir(self.name)
  1361. logsdir = os.path.join(self.ctx.logsdir, 'glibcs', self.name)
  1362. self.ctx.remove_recreate_dirs(installdir, builddir, logsdir)
  1363. cmdlist = CommandList('glibcs-%s' % self.name, self.ctx.keep)
  1364. cmdlist.add_command('check-compilers',
  1365. ['test', '-f',
  1366. os.path.join(self.compiler.installdir, 'ok')])
  1367. cmdlist.use_path(self.compiler.bindir)
  1368. self.build_glibc(cmdlist, False)
  1369. self.ctx.add_makefile_cmdlist('glibcs-%s' % self.name, cmdlist,
  1370. logsdir)
  1371. def build_glibc(self, cmdlist, for_compiler):
  1372. """Generate commands to build this glibc, either as part of a compiler
  1373. build or with the bootstrapped compiler (and in the latter case, run
  1374. tests as well)."""
  1375. srcdir = self.ctx.component_srcdir('glibc')
  1376. if for_compiler:
  1377. builddir = self.ctx.component_builddir('compilers',
  1378. self.compiler.name, 'glibc',
  1379. self.name)
  1380. installdir = self.compiler.sysroot
  1381. else:
  1382. builddir = self.ctx.component_builddir('glibcs', self.name,
  1383. 'glibc')
  1384. installdir = self.ctx.glibc_installdir(self.name)
  1385. cmdlist.create_use_dir(builddir)
  1386. use_usr = self.os != 'gnu'
  1387. prefix = '/usr' if use_usr else ''
  1388. cfg_cmd = [os.path.join(srcdir, 'configure'),
  1389. '--prefix=%s' % prefix,
  1390. '--enable-profile',
  1391. '--build=%s' % self.ctx.build_triplet,
  1392. '--host=%s' % self.triplet,
  1393. 'CC=%s' % self.tool_name('gcc'),
  1394. 'CXX=%s' % self.tool_name('g++'),
  1395. 'AR=%s' % self.tool_name('ar'),
  1396. 'AS=%s' % self.tool_name('as'),
  1397. 'LD=%s' % self.tool_name('ld'),
  1398. 'NM=%s' % self.tool_name('nm'),
  1399. 'OBJCOPY=%s' % self.tool_name('objcopy'),
  1400. 'OBJDUMP=%s' % self.tool_name('objdump'),
  1401. 'RANLIB=%s' % self.tool_name('ranlib'),
  1402. 'READELF=%s' % self.tool_name('readelf'),
  1403. 'STRIP=%s' % self.tool_name('strip')]
  1404. if self.os == 'gnu':
  1405. cfg_cmd += ['MIG=%s' % self.tool_name('mig')]
  1406. cfg_cmd += self.cfg
  1407. cmdlist.add_command('configure', cfg_cmd)
  1408. cmdlist.add_command('build', ['make'])
  1409. cmdlist.add_command('install', ['make', 'install',
  1410. 'install_root=%s' % installdir])
  1411. # GCC uses paths such as lib/../lib64, so make sure lib
  1412. # directories always exist.
  1413. mkdir_cmd = ['mkdir', '-p',
  1414. os.path.join(installdir, 'lib')]
  1415. if use_usr:
  1416. mkdir_cmd += [os.path.join(installdir, 'usr', 'lib')]
  1417. cmdlist.add_command('mkdir-lib', mkdir_cmd)
  1418. if not for_compiler:
  1419. if self.ctx.strip:
  1420. cmdlist.add_command('strip',
  1421. ['sh', '-c',
  1422. ('%s $(find %s/lib* -name "*.so")' %
  1423. (self.tool_name('strip'), installdir))])
  1424. cmdlist.add_command('check', ['make', 'check'])
  1425. cmdlist.add_command('save-logs', [self.ctx.save_logs],
  1426. always_run=True)
  1427. cmdlist.cleanup_dir()
  1428. class Command(object):
  1429. """A command run in the build process."""
  1430. def __init__(self, desc, num, dir, path, command, always_run=False):
  1431. """Initialize a Command object."""
  1432. self.dir = dir
  1433. self.path = path
  1434. self.desc = desc
  1435. trans = str.maketrans({' ': '-'})
  1436. self.logbase = '%03d-%s' % (num, desc.translate(trans))
  1437. self.command = command
  1438. self.always_run = always_run
  1439. @staticmethod
  1440. def shell_make_quote_string(s):
  1441. """Given a string not containing a newline, quote it for use by the
  1442. shell and make."""
  1443. assert '\n' not in s
  1444. if re.fullmatch('[]+,./0-9@A-Z_a-z-]+', s):
  1445. return s
  1446. strans = str.maketrans({"'": "'\\''"})
  1447. s = "'%s'" % s.translate(strans)
  1448. mtrans = str.maketrans({'$': '$$'})
  1449. return s.translate(mtrans)
  1450. @staticmethod
  1451. def shell_make_quote_list(l, translate_make):
  1452. """Given a list of strings not containing newlines, quote them for use
  1453. by the shell and make, returning a single string. If translate_make
  1454. is true and the first string is 'make', change it to $(MAKE)."""
  1455. l = [Command.shell_make_quote_string(s) for s in l]
  1456. if translate_make and l[0] == 'make':
  1457. l[0] = '$(MAKE)'
  1458. return ' '.join(l)
  1459. def shell_make_quote(self):
  1460. """Return this command quoted for the shell and make."""
  1461. return self.shell_make_quote_list(self.command, True)
  1462. class CommandList(object):
  1463. """A list of commands run in the build process."""
  1464. def __init__(self, desc, keep):
  1465. """Initialize a CommandList object."""
  1466. self.cmdlist = []
  1467. self.dir = None
  1468. self.path = None
  1469. self.desc = [desc]
  1470. self.keep = keep
  1471. def desc_txt(self, desc):
  1472. """Return the description to use for a command."""
  1473. return '%s %s' % (' '.join(self.desc), desc)
  1474. def use_dir(self, dir):
  1475. """Set the default directory for subsequent commands."""
  1476. self.dir = dir
  1477. def use_path(self, path):
  1478. """Set a directory to be prepended to the PATH for subsequent
  1479. commands."""
  1480. self.path = path
  1481. def push_subdesc(self, subdesc):
  1482. """Set the default subdescription for subsequent commands (e.g., the
  1483. name of a component being built, within the series of commands
  1484. building it)."""
  1485. self.desc.append(subdesc)
  1486. def pop_subdesc(self):
  1487. """Pop a subdescription from the list of descriptions."""
  1488. self.desc.pop()
  1489. def create_use_dir(self, dir):
  1490. """Remove and recreate a directory and use it for subsequent
  1491. commands."""
  1492. self.add_command_dir('rm', None, ['rm', '-rf', dir])
  1493. self.add_command_dir('mkdir', None, ['mkdir', '-p', dir])
  1494. self.use_dir(dir)
  1495. def add_command_dir(self, desc, dir, command, always_run=False):
  1496. """Add a command to run in a given directory."""
  1497. cmd = Command(self.desc_txt(desc), len(self.cmdlist), dir, self.path,
  1498. command, always_run)
  1499. self.cmdlist.append(cmd)
  1500. def add_command(self, desc, command, always_run=False):
  1501. """Add a command to run in the default directory."""
  1502. cmd = Command(self.desc_txt(desc), len(self.cmdlist), self.dir,
  1503. self.path, command, always_run)
  1504. self.cmdlist.append(cmd)
  1505. def cleanup_dir(self, desc='cleanup', dir=None):
  1506. """Clean up a build directory. If no directory is specified, the
  1507. default directory is cleaned up and ceases to be the default
  1508. directory."""
  1509. if dir is None:
  1510. dir = self.dir
  1511. self.use_dir(None)
  1512. if self.keep != 'all':
  1513. self.add_command_dir(desc, None, ['rm', '-rf', dir],
  1514. always_run=(self.keep == 'none'))
  1515. def makefile_commands(self, wrapper, logsdir):
  1516. """Return the sequence of commands in the form of text for a Makefile.
  1517. The given wrapper script takes arguments: base of logs for
  1518. previous command, or empty; base of logs for this command;
  1519. description; directory; PATH addition; the command itself."""
  1520. # prev_base is the base of the name for logs of the previous
  1521. # command that is not always-run (that is, a build command,
  1522. # whose failure should stop subsequent build commands from
  1523. # being run, as opposed to a cleanup command, which is run
  1524. # even if previous commands failed).
  1525. prev_base = ''
  1526. cmds = []
  1527. for c in self.cmdlist:
  1528. ctxt = c.shell_make_quote()
  1529. if prev_base and not c.always_run:
  1530. prev_log = os.path.join(logsdir, prev_base)
  1531. else:
  1532. prev_log = ''
  1533. this_log = os.path.join(logsdir, c.logbase)
  1534. if not c.always_run:
  1535. prev_base = c.logbase
  1536. if c.dir is None:
  1537. dir = ''
  1538. else:
  1539. dir = c.dir
  1540. if c.path is None:
  1541. path = ''
  1542. else:
  1543. path = c.path
  1544. prelims = [wrapper, prev_log, this_log, c.desc, dir, path]
  1545. prelim_txt = Command.shell_make_quote_list(prelims, False)
  1546. cmds.append('\t@%s %s' % (prelim_txt, ctxt))
  1547. return '\n'.join(cmds)
  1548. def status_logs(self, logsdir):
  1549. """Return the list of log files with command status."""
  1550. return [os.path.join(logsdir, '%s-status.txt' % c.logbase)
  1551. for c in self.cmdlist]
  1552. def get_parser():
  1553. """Return an argument parser for this module."""
  1554. parser = argparse.ArgumentParser(description=__doc__)
  1555. parser.add_argument('-j', dest='parallelism',
  1556. help='Run this number of jobs in parallel',
  1557. type=int, default=os.cpu_count())
  1558. parser.add_argument('--keep', dest='keep',
  1559. help='Whether to keep all build directories, '
  1560. 'none or only those from failed builds',
  1561. default='none', choices=('none', 'all', 'failed'))
  1562. parser.add_argument('--replace-sources', action='store_true',
  1563. help='Remove and replace source directories '
  1564. 'with the wrong version of a component')
  1565. parser.add_argument('--strip', action='store_true',
  1566. help='Strip installed glibc libraries')
  1567. parser.add_argument('--full-gcc', action='store_true',
  1568. help='Build GCC with all languages and libsanitizer')
  1569. parser.add_argument('topdir',
  1570. help='Toplevel working directory')
  1571. parser.add_argument('action',
  1572. help='What to do',
  1573. choices=('checkout', 'bot-cycle', 'bot',
  1574. 'host-libraries', 'compilers', 'glibcs'))
  1575. parser.add_argument('configs',
  1576. help='Versions to check out or configurations to build',
  1577. nargs='*')
  1578. return parser
  1579. def main(argv):
  1580. """The main entry point."""
  1581. parser = get_parser()
  1582. opts = parser.parse_args(argv)
  1583. topdir = os.path.abspath(opts.topdir)
  1584. ctx = Context(topdir, opts.parallelism, opts.keep, opts.replace_sources,
  1585. opts.strip, opts.full_gcc, opts.action)
  1586. ctx.run_builds(opts.action, opts.configs)
  1587. if __name__ == '__main__':
  1588. main(sys.argv[1:])