build.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  1. # ex:ts=4:sw=4:sts=4:et
  2. # -*- tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*-
  3. #
  4. # BitBake 'Build' implementation
  5. #
  6. # Core code for function execution and task handling in the
  7. # BitBake build tools.
  8. #
  9. # Copyright (C) 2003, 2004 Chris Larson
  10. #
  11. # Based on Gentoo's portage.py.
  12. #
  13. # SPDX-License-Identifier: GPL-2.0-only
  14. #
  15. # This program is free software; you can redistribute it and/or modify
  16. # it under the terms of the GNU General Public License version 2 as
  17. # published by the Free Software Foundation.
  18. #
  19. # This program is distributed in the hope that it will be useful,
  20. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  21. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  22. # GNU General Public License for more details.
  23. #
  24. # You should have received a copy of the GNU General Public License along
  25. # with this program; if not, write to the Free Software Foundation, Inc.,
  26. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  27. #
  28. # Based on functions from the base bb module, Copyright 2003 Holger Schurig
  29. import os
  30. import sys
  31. import logging
  32. import shlex
  33. import glob
  34. import time
  35. import stat
  36. import bb
  37. import bb.msg
  38. import bb.process
  39. import bb.progress
  40. from bb import data, event, utils
  41. bblogger = logging.getLogger('BitBake')
  42. logger = logging.getLogger('BitBake.Build')
  43. __mtime_cache = {}
  44. def cached_mtime_noerror(f):
  45. if f not in __mtime_cache:
  46. try:
  47. __mtime_cache[f] = os.stat(f)[stat.ST_MTIME]
  48. except OSError:
  49. return 0
  50. return __mtime_cache[f]
  51. def reset_cache():
  52. global __mtime_cache
  53. __mtime_cache = {}
  54. # When we execute a Python function, we'd like certain things
  55. # in all namespaces, hence we add them to __builtins__.
  56. # If we do not do this and use the exec globals, they will
  57. # not be available to subfunctions.
  58. if hasattr(__builtins__, '__setitem__'):
  59. builtins = __builtins__
  60. else:
  61. builtins = __builtins__.__dict__
  62. builtins['bb'] = bb
  63. builtins['os'] = os
  64. class FuncFailed(Exception):
  65. def __init__(self, name = None, logfile = None):
  66. self.logfile = logfile
  67. self.name = name
  68. if name:
  69. self.msg = 'Function failed: %s' % name
  70. else:
  71. self.msg = "Function failed"
  72. def __str__(self):
  73. if self.logfile and os.path.exists(self.logfile):
  74. msg = ("%s (log file is located at %s)" %
  75. (self.msg, self.logfile))
  76. else:
  77. msg = self.msg
  78. return msg
  79. class TaskBase(event.Event):
  80. """Base class for task events"""
  81. def __init__(self, t, logfile, d):
  82. self._task = t
  83. self._package = d.getVar("PF")
  84. self._mc = d.getVar("BB_CURRENT_MC")
  85. self.taskfile = d.getVar("FILE")
  86. self.taskname = self._task
  87. self.logfile = logfile
  88. self.time = time.time()
  89. event.Event.__init__(self)
  90. self._message = "recipe %s: task %s: %s" % (d.getVar("PF"), t, self.getDisplayName())
  91. def getTask(self):
  92. return self._task
  93. def setTask(self, task):
  94. self._task = task
  95. def getDisplayName(self):
  96. return bb.event.getName(self)[4:]
  97. task = property(getTask, setTask, None, "task property")
  98. class TaskStarted(TaskBase):
  99. """Task execution started"""
  100. def __init__(self, t, logfile, taskflags, d):
  101. super(TaskStarted, self).__init__(t, logfile, d)
  102. self.taskflags = taskflags
  103. class TaskSucceeded(TaskBase):
  104. """Task execution completed"""
  105. class TaskFailed(TaskBase):
  106. """Task execution failed"""
  107. def __init__(self, task, logfile, metadata, errprinted = False):
  108. self.errprinted = errprinted
  109. super(TaskFailed, self).__init__(task, logfile, metadata)
  110. class TaskFailedSilent(TaskBase):
  111. """Task execution failed (silently)"""
  112. def getDisplayName(self):
  113. # Don't need to tell the user it was silent
  114. return "Failed"
  115. class TaskInvalid(TaskBase):
  116. def __init__(self, task, metadata):
  117. super(TaskInvalid, self).__init__(task, None, metadata)
  118. self._message = "No such task '%s'" % task
  119. class TaskProgress(event.Event):
  120. """
  121. Task made some progress that could be reported to the user, usually in
  122. the form of a progress bar or similar.
  123. NOTE: this class does not inherit from TaskBase since it doesn't need
  124. to - it's fired within the task context itself, so we don't have any of
  125. the context information that you do in the case of the other events.
  126. The event PID can be used to determine which task it came from.
  127. The progress value is normally 0-100, but can also be negative
  128. indicating that progress has been made but we aren't able to determine
  129. how much.
  130. The rate is optional, this is simply an extra string to display to the
  131. user if specified.
  132. """
  133. def __init__(self, progress, rate=None):
  134. self.progress = progress
  135. self.rate = rate
  136. event.Event.__init__(self)
  137. class LogTee(object):
  138. def __init__(self, logger, outfile):
  139. self.outfile = outfile
  140. self.logger = logger
  141. self.name = self.outfile.name
  142. def write(self, string):
  143. self.logger.plain(string)
  144. self.outfile.write(string)
  145. def __enter__(self):
  146. self.outfile.__enter__()
  147. return self
  148. def __exit__(self, *excinfo):
  149. self.outfile.__exit__(*excinfo)
  150. def __repr__(self):
  151. return '<LogTee {0}>'.format(self.name)
  152. def flush(self):
  153. self.outfile.flush()
  154. #
  155. # pythonexception allows the python exceptions generated to be raised
  156. # as the real exceptions (not FuncFailed) and without a backtrace at the
  157. # origin of the failure.
  158. #
  159. def exec_func(func, d, dirs = None, pythonexception=False):
  160. """Execute a BB 'function'"""
  161. try:
  162. oldcwd = os.getcwd()
  163. except:
  164. oldcwd = None
  165. flags = d.getVarFlags(func)
  166. cleandirs = flags.get('cleandirs') if flags else None
  167. if cleandirs:
  168. for cdir in d.expand(cleandirs).split():
  169. bb.utils.remove(cdir, True)
  170. bb.utils.mkdirhier(cdir)
  171. if flags and dirs is None:
  172. dirs = flags.get('dirs')
  173. if dirs:
  174. dirs = d.expand(dirs).split()
  175. if dirs:
  176. for adir in dirs:
  177. bb.utils.mkdirhier(adir)
  178. adir = dirs[-1]
  179. else:
  180. adir = None
  181. body = d.getVar(func, False)
  182. if not body:
  183. if body is None:
  184. logger.warning("Function %s doesn't exist", func)
  185. return
  186. ispython = flags.get('python')
  187. lockflag = flags.get('lockfiles')
  188. if lockflag:
  189. lockfiles = [f for f in d.expand(lockflag).split()]
  190. else:
  191. lockfiles = None
  192. tempdir = d.getVar('T')
  193. # or func allows items to be executed outside of the normal
  194. # task set, such as buildhistory
  195. task = d.getVar('BB_RUNTASK') or func
  196. if task == func:
  197. taskfunc = task
  198. else:
  199. taskfunc = "%s.%s" % (task, func)
  200. runfmt = d.getVar('BB_RUNFMT') or "run.{func}.{pid}"
  201. runfn = runfmt.format(taskfunc=taskfunc, task=task, func=func, pid=os.getpid())
  202. runfile = os.path.join(tempdir, runfn)
  203. bb.utils.mkdirhier(os.path.dirname(runfile))
  204. # Setup the courtesy link to the runfn, only for tasks
  205. # we create the link 'just' before the run script is created
  206. # if we create it after, and if the run script fails, then the
  207. # link won't be created as an exception would be fired.
  208. if task == func:
  209. runlink = os.path.join(tempdir, 'run.{0}'.format(task))
  210. if runlink:
  211. bb.utils.remove(runlink)
  212. try:
  213. os.symlink(runfn, runlink)
  214. except OSError:
  215. pass
  216. with bb.utils.fileslocked(lockfiles):
  217. if ispython:
  218. exec_func_python(func, d, runfile, cwd=adir, pythonexception=pythonexception)
  219. else:
  220. exec_func_shell(func, d, runfile, cwd=adir)
  221. try:
  222. curcwd = os.getcwd()
  223. except:
  224. curcwd = None
  225. if oldcwd and curcwd != oldcwd:
  226. try:
  227. bb.warn("Task %s changed cwd to %s" % (func, curcwd))
  228. os.chdir(oldcwd)
  229. except:
  230. pass
  231. _functionfmt = """
  232. {function}(d)
  233. """
  234. logformatter = bb.msg.BBLogFormatter("%(levelname)s: %(message)s")
  235. def exec_func_python(func, d, runfile, cwd=None, pythonexception=False):
  236. """Execute a python BB 'function'"""
  237. code = _functionfmt.format(function=func)
  238. bb.utils.mkdirhier(os.path.dirname(runfile))
  239. with open(runfile, 'w') as script:
  240. bb.data.emit_func_python(func, script, d)
  241. if cwd:
  242. try:
  243. olddir = os.getcwd()
  244. except OSError as e:
  245. bb.warn("%s: Cannot get cwd: %s" % (func, e))
  246. olddir = None
  247. os.chdir(cwd)
  248. bb.debug(2, "Executing python function %s" % func)
  249. try:
  250. text = "def %s(d):\n%s" % (func, d.getVar(func, False))
  251. fn = d.getVarFlag(func, "filename", False)
  252. lineno = int(d.getVarFlag(func, "lineno", False))
  253. bb.methodpool.insert_method(func, text, fn, lineno - 1)
  254. comp = utils.better_compile(code, func, "exec_python_func() autogenerated")
  255. utils.better_exec(comp, {"d": d}, code, "exec_python_func() autogenerated", pythonexception=pythonexception)
  256. except (bb.parse.SkipRecipe, bb.build.FuncFailed):
  257. raise
  258. except Exception as e:
  259. if pythonexception:
  260. raise
  261. logger.error(str(e))
  262. raise FuncFailed(func, None)
  263. finally:
  264. bb.debug(2, "Python function %s finished" % func)
  265. if cwd and olddir:
  266. try:
  267. os.chdir(olddir)
  268. except OSError as e:
  269. bb.warn("%s: Cannot restore cwd %s: %s" % (func, olddir, e))
  270. def shell_trap_code():
  271. return '''#!/bin/sh\n
  272. # Emit a useful diagnostic if something fails:
  273. bb_exit_handler() {
  274. ret=$?
  275. case $ret in
  276. 0) ;;
  277. *) case $BASH_VERSION in
  278. "") echo "WARNING: exit code $ret from a shell command.";;
  279. *) echo "WARNING: ${BASH_SOURCE[0]}:${BASH_LINENO[0]} exit $ret from '$BASH_COMMAND'";;
  280. esac
  281. exit $ret
  282. esac
  283. }
  284. trap 'bb_exit_handler' 0
  285. set -e
  286. '''
  287. def exec_func_shell(func, d, runfile, cwd=None):
  288. """Execute a shell function from the metadata
  289. Note on directory behavior. The 'dirs' varflag should contain a list
  290. of the directories you need created prior to execution. The last
  291. item in the list is where we will chdir/cd to.
  292. """
  293. # Don't let the emitted shell script override PWD
  294. d.delVarFlag('PWD', 'export')
  295. with open(runfile, 'w') as script:
  296. script.write(shell_trap_code())
  297. bb.data.emit_func(func, script, d)
  298. if bb.msg.loggerVerboseLogs:
  299. script.write("set -x\n")
  300. if cwd:
  301. script.write("cd '%s'\n" % cwd)
  302. script.write("%s\n" % func)
  303. script.write('''
  304. # cleanup
  305. ret=$?
  306. trap '' 0
  307. exit $ret
  308. ''')
  309. os.chmod(runfile, 0o775)
  310. cmd = runfile
  311. if d.getVarFlag(func, 'fakeroot', False):
  312. fakerootcmd = d.getVar('FAKEROOT')
  313. if fakerootcmd:
  314. cmd = [fakerootcmd, runfile]
  315. if bb.msg.loggerDefaultVerbose:
  316. logfile = LogTee(logger, sys.stdout)
  317. else:
  318. logfile = sys.stdout
  319. progress = d.getVarFlag(func, 'progress')
  320. if progress:
  321. if progress == 'percent':
  322. # Use default regex
  323. logfile = bb.progress.BasicProgressHandler(d, outfile=logfile)
  324. elif progress.startswith('percent:'):
  325. # Use specified regex
  326. logfile = bb.progress.BasicProgressHandler(d, regex=progress.split(':', 1)[1], outfile=logfile)
  327. elif progress.startswith('outof:'):
  328. # Use specified regex
  329. logfile = bb.progress.OutOfProgressHandler(d, regex=progress.split(':', 1)[1], outfile=logfile)
  330. else:
  331. bb.warn('%s: invalid task progress varflag value "%s", ignoring' % (func, progress))
  332. fifobuffer = bytearray()
  333. def readfifo(data):
  334. nonlocal fifobuffer
  335. fifobuffer.extend(data)
  336. while fifobuffer:
  337. message, token, nextmsg = fifobuffer.partition(b"\00")
  338. if token:
  339. splitval = message.split(b' ', 1)
  340. cmd = splitval[0].decode("utf-8")
  341. if len(splitval) > 1:
  342. value = splitval[1].decode("utf-8")
  343. else:
  344. value = ''
  345. if cmd == 'bbplain':
  346. bb.plain(value)
  347. elif cmd == 'bbnote':
  348. bb.note(value)
  349. elif cmd == 'bbverbnote':
  350. bb.verbnote(value)
  351. elif cmd == 'bbwarn':
  352. bb.warn(value)
  353. elif cmd == 'bberror':
  354. bb.error(value)
  355. elif cmd == 'bbfatal':
  356. # The caller will call exit themselves, so bb.error() is
  357. # what we want here rather than bb.fatal()
  358. bb.error(value)
  359. elif cmd == 'bbfatal_log':
  360. bb.error(value, forcelog=True)
  361. elif cmd == 'bbdebug':
  362. splitval = value.split(' ', 1)
  363. level = int(splitval[0])
  364. value = splitval[1]
  365. bb.debug(level, value)
  366. else:
  367. bb.warn("Unrecognised command '%s' on FIFO" % cmd)
  368. fifobuffer = nextmsg
  369. else:
  370. break
  371. tempdir = d.getVar('T')
  372. fifopath = os.path.join(tempdir, 'fifo.%s' % os.getpid())
  373. if os.path.exists(fifopath):
  374. os.unlink(fifopath)
  375. os.mkfifo(fifopath)
  376. with open(fifopath, 'r+b', buffering=0) as fifo:
  377. try:
  378. bb.debug(2, "Executing shell function %s" % func)
  379. try:
  380. with open(os.devnull, 'r+') as stdin:
  381. bb.process.run(cmd, shell=False, stdin=stdin, log=logfile, extrafiles=[(fifo,readfifo)])
  382. except bb.process.CmdError:
  383. logfn = d.getVar('BB_LOGFILE')
  384. raise FuncFailed(func, logfn)
  385. finally:
  386. os.unlink(fifopath)
  387. bb.debug(2, "Shell function %s finished" % func)
  388. def _task_data(fn, task, d):
  389. localdata = bb.data.createCopy(d)
  390. localdata.setVar('BB_FILENAME', fn)
  391. localdata.setVar('BB_CURRENTTASK', task[3:])
  392. localdata.setVar('OVERRIDES', 'task-%s:%s' %
  393. (task[3:].replace('_', '-'), d.getVar('OVERRIDES', False)))
  394. localdata.finalize()
  395. bb.data.expandKeys(localdata)
  396. return localdata
  397. def _exec_task(fn, task, d, quieterr):
  398. """Execute a BB 'task'
  399. Execution of a task involves a bit more setup than executing a function,
  400. running it with its own local metadata, and with some useful variables set.
  401. """
  402. if not d.getVarFlag(task, 'task', False):
  403. event.fire(TaskInvalid(task, d), d)
  404. logger.error("No such task: %s" % task)
  405. return 1
  406. logger.debug(1, "Executing task %s", task)
  407. localdata = _task_data(fn, task, d)
  408. tempdir = localdata.getVar('T')
  409. if not tempdir:
  410. bb.fatal("T variable not set, unable to build")
  411. # Change nice level if we're asked to
  412. nice = localdata.getVar("BB_TASK_NICE_LEVEL")
  413. if nice:
  414. curnice = os.nice(0)
  415. nice = int(nice) - curnice
  416. newnice = os.nice(nice)
  417. logger.debug(1, "Renice to %s " % newnice)
  418. ionice = localdata.getVar("BB_TASK_IONICE_LEVEL")
  419. if ionice:
  420. try:
  421. cls, prio = ionice.split(".", 1)
  422. bb.utils.ioprio_set(os.getpid(), int(cls), int(prio))
  423. except:
  424. bb.warn("Invalid ionice level %s" % ionice)
  425. bb.utils.mkdirhier(tempdir)
  426. # Determine the logfile to generate
  427. logfmt = localdata.getVar('BB_LOGFMT') or 'log.{task}.{pid}'
  428. logbase = logfmt.format(task=task, pid=os.getpid())
  429. # Document the order of the tasks...
  430. logorder = os.path.join(tempdir, 'log.task_order')
  431. try:
  432. with open(logorder, 'a') as logorderfile:
  433. logorderfile.write('{0} ({1}): {2}\n'.format(task, os.getpid(), logbase))
  434. except OSError:
  435. logger.exception("Opening log file '%s'", logorder)
  436. pass
  437. # Setup the courtesy link to the logfn
  438. loglink = os.path.join(tempdir, 'log.{0}'.format(task))
  439. logfn = os.path.join(tempdir, logbase)
  440. if loglink:
  441. bb.utils.remove(loglink)
  442. try:
  443. os.symlink(logbase, loglink)
  444. except OSError:
  445. pass
  446. prefuncs = localdata.getVarFlag(task, 'prefuncs', expand=True)
  447. postfuncs = localdata.getVarFlag(task, 'postfuncs', expand=True)
  448. class ErrorCheckHandler(logging.Handler):
  449. def __init__(self):
  450. self.triggered = False
  451. logging.Handler.__init__(self, logging.ERROR)
  452. def emit(self, record):
  453. if getattr(record, 'forcelog', False):
  454. self.triggered = False
  455. else:
  456. self.triggered = True
  457. # Handle logfiles
  458. try:
  459. bb.utils.mkdirhier(os.path.dirname(logfn))
  460. logfile = open(logfn, 'w')
  461. except OSError:
  462. logger.exception("Opening log file '%s'", logfn)
  463. pass
  464. # Dup the existing fds so we dont lose them
  465. osi = [os.dup(sys.stdin.fileno()), sys.stdin.fileno()]
  466. oso = [os.dup(sys.stdout.fileno()), sys.stdout.fileno()]
  467. ose = [os.dup(sys.stderr.fileno()), sys.stderr.fileno()]
  468. # Replace those fds with our own
  469. with open('/dev/null', 'r') as si:
  470. os.dup2(si.fileno(), osi[1])
  471. os.dup2(logfile.fileno(), oso[1])
  472. os.dup2(logfile.fileno(), ose[1])
  473. # Ensure Python logging goes to the logfile
  474. handler = logging.StreamHandler(logfile)
  475. handler.setFormatter(logformatter)
  476. # Always enable full debug output into task logfiles
  477. handler.setLevel(logging.DEBUG - 2)
  478. bblogger.addHandler(handler)
  479. errchk = ErrorCheckHandler()
  480. bblogger.addHandler(errchk)
  481. localdata.setVar('BB_LOGFILE', logfn)
  482. localdata.setVar('BB_RUNTASK', task)
  483. localdata.setVar('BB_TASK_LOGGER', bblogger)
  484. flags = localdata.getVarFlags(task)
  485. try:
  486. try:
  487. event.fire(TaskStarted(task, logfn, flags, localdata), localdata)
  488. except (bb.BBHandledException, SystemExit):
  489. return 1
  490. except FuncFailed as exc:
  491. logger.error(str(exc))
  492. return 1
  493. try:
  494. for func in (prefuncs or '').split():
  495. exec_func(func, localdata)
  496. exec_func(task, localdata)
  497. for func in (postfuncs or '').split():
  498. exec_func(func, localdata)
  499. except FuncFailed as exc:
  500. if quieterr:
  501. event.fire(TaskFailedSilent(task, logfn, localdata), localdata)
  502. else:
  503. errprinted = errchk.triggered
  504. logger.error(str(exc))
  505. event.fire(TaskFailed(task, logfn, localdata, errprinted), localdata)
  506. return 1
  507. except bb.BBHandledException:
  508. event.fire(TaskFailed(task, logfn, localdata, True), localdata)
  509. return 1
  510. finally:
  511. sys.stdout.flush()
  512. sys.stderr.flush()
  513. bblogger.removeHandler(handler)
  514. # Restore the backup fds
  515. os.dup2(osi[0], osi[1])
  516. os.dup2(oso[0], oso[1])
  517. os.dup2(ose[0], ose[1])
  518. # Close the backup fds
  519. os.close(osi[0])
  520. os.close(oso[0])
  521. os.close(ose[0])
  522. logfile.close()
  523. if os.path.exists(logfn) and os.path.getsize(logfn) == 0:
  524. logger.debug(2, "Zero size logfn %s, removing", logfn)
  525. bb.utils.remove(logfn)
  526. bb.utils.remove(loglink)
  527. event.fire(TaskSucceeded(task, logfn, localdata), localdata)
  528. if not localdata.getVarFlag(task, 'nostamp', False) and not localdata.getVarFlag(task, 'selfstamp', False):
  529. make_stamp(task, localdata)
  530. return 0
  531. def exec_task(fn, task, d, profile = False):
  532. try:
  533. quieterr = False
  534. if d.getVarFlag(task, "quieterrors", False) is not None:
  535. quieterr = True
  536. if profile:
  537. profname = "profile-%s.log" % (d.getVar("PN") + "-" + task)
  538. try:
  539. import cProfile as profile
  540. except:
  541. import profile
  542. prof = profile.Profile()
  543. ret = profile.Profile.runcall(prof, _exec_task, fn, task, d, quieterr)
  544. prof.dump_stats(profname)
  545. bb.utils.process_profilelog(profname)
  546. return ret
  547. else:
  548. return _exec_task(fn, task, d, quieterr)
  549. except Exception:
  550. from traceback import format_exc
  551. if not quieterr:
  552. logger.error("Build of %s failed" % (task))
  553. logger.error(format_exc())
  554. failedevent = TaskFailed(task, None, d, True)
  555. event.fire(failedevent, d)
  556. return 1
  557. def stamp_internal(taskname, d, file_name, baseonly=False, noextra=False):
  558. """
  559. Internal stamp helper function
  560. Makes sure the stamp directory exists
  561. Returns the stamp path+filename
  562. In the bitbake core, d can be a CacheData and file_name will be set.
  563. When called in task context, d will be a data store, file_name will not be set
  564. """
  565. taskflagname = taskname
  566. if taskname.endswith("_setscene") and taskname != "do_setscene":
  567. taskflagname = taskname.replace("_setscene", "")
  568. if file_name:
  569. stamp = d.stamp[file_name]
  570. extrainfo = d.stamp_extrainfo[file_name].get(taskflagname) or ""
  571. else:
  572. stamp = d.getVar('STAMP')
  573. file_name = d.getVar('BB_FILENAME')
  574. extrainfo = d.getVarFlag(taskflagname, 'stamp-extra-info') or ""
  575. if baseonly:
  576. return stamp
  577. if noextra:
  578. extrainfo = ""
  579. if not stamp:
  580. return
  581. stamp = bb.parse.siggen.stampfile(stamp, file_name, taskname, extrainfo)
  582. stampdir = os.path.dirname(stamp)
  583. if cached_mtime_noerror(stampdir) == 0:
  584. bb.utils.mkdirhier(stampdir)
  585. return stamp
  586. def stamp_cleanmask_internal(taskname, d, file_name):
  587. """
  588. Internal stamp helper function to generate stamp cleaning mask
  589. Returns the stamp path+filename
  590. In the bitbake core, d can be a CacheData and file_name will be set.
  591. When called in task context, d will be a data store, file_name will not be set
  592. """
  593. taskflagname = taskname
  594. if taskname.endswith("_setscene") and taskname != "do_setscene":
  595. taskflagname = taskname.replace("_setscene", "")
  596. if file_name:
  597. stamp = d.stampclean[file_name]
  598. extrainfo = d.stamp_extrainfo[file_name].get(taskflagname) or ""
  599. else:
  600. stamp = d.getVar('STAMPCLEAN')
  601. file_name = d.getVar('BB_FILENAME')
  602. extrainfo = d.getVarFlag(taskflagname, 'stamp-extra-info') or ""
  603. if not stamp:
  604. return []
  605. cleanmask = bb.parse.siggen.stampcleanmask(stamp, file_name, taskname, extrainfo)
  606. return [cleanmask, cleanmask.replace(taskflagname, taskflagname + "_setscene")]
  607. def make_stamp(task, d, file_name = None):
  608. """
  609. Creates/updates a stamp for a given task
  610. (d can be a data dict or dataCache)
  611. """
  612. cleanmask = stamp_cleanmask_internal(task, d, file_name)
  613. for mask in cleanmask:
  614. for name in glob.glob(mask):
  615. # Preserve sigdata files in the stamps directory
  616. if "sigdata" in name or "sigbasedata" in name:
  617. continue
  618. # Preserve taint files in the stamps directory
  619. if name.endswith('.taint'):
  620. continue
  621. os.unlink(name)
  622. stamp = stamp_internal(task, d, file_name)
  623. # Remove the file and recreate to force timestamp
  624. # change on broken NFS filesystems
  625. if stamp:
  626. bb.utils.remove(stamp)
  627. open(stamp, "w").close()
  628. # If we're in task context, write out a signature file for each task
  629. # as it completes
  630. if not task.endswith("_setscene") and task != "do_setscene" and not file_name:
  631. stampbase = stamp_internal(task, d, None, True)
  632. file_name = d.getVar('BB_FILENAME')
  633. bb.parse.siggen.dump_sigtask(file_name, task, stampbase, True)
  634. def del_stamp(task, d, file_name = None):
  635. """
  636. Removes a stamp for a given task
  637. (d can be a data dict or dataCache)
  638. """
  639. stamp = stamp_internal(task, d, file_name)
  640. bb.utils.remove(stamp)
  641. def write_taint(task, d, file_name = None):
  642. """
  643. Creates a "taint" file which will force the specified task and its
  644. dependents to be re-run the next time by influencing the value of its
  645. taskhash.
  646. (d can be a data dict or dataCache)
  647. """
  648. import uuid
  649. if file_name:
  650. taintfn = d.stamp[file_name] + '.' + task + '.taint'
  651. else:
  652. taintfn = d.getVar('STAMP') + '.' + task + '.taint'
  653. bb.utils.mkdirhier(os.path.dirname(taintfn))
  654. # The specific content of the taint file is not really important,
  655. # we just need it to be random, so a random UUID is used
  656. with open(taintfn, 'w') as taintf:
  657. taintf.write(str(uuid.uuid4()))
  658. def stampfile(taskname, d, file_name = None, noextra=False):
  659. """
  660. Return the stamp for a given task
  661. (d can be a data dict or dataCache)
  662. """
  663. return stamp_internal(taskname, d, file_name, noextra=noextra)
  664. def add_tasks(tasklist, d):
  665. task_deps = d.getVar('_task_deps', False)
  666. if not task_deps:
  667. task_deps = {}
  668. if not 'tasks' in task_deps:
  669. task_deps['tasks'] = []
  670. if not 'parents' in task_deps:
  671. task_deps['parents'] = {}
  672. for task in tasklist:
  673. task = d.expand(task)
  674. d.setVarFlag(task, 'task', 1)
  675. if not task in task_deps['tasks']:
  676. task_deps['tasks'].append(task)
  677. flags = d.getVarFlags(task)
  678. def getTask(name):
  679. if not name in task_deps:
  680. task_deps[name] = {}
  681. if name in flags:
  682. deptask = d.expand(flags[name])
  683. task_deps[name][task] = deptask
  684. getTask('mcdepends')
  685. getTask('depends')
  686. getTask('rdepends')
  687. getTask('deptask')
  688. getTask('rdeptask')
  689. getTask('recrdeptask')
  690. getTask('recideptask')
  691. getTask('nostamp')
  692. getTask('fakeroot')
  693. getTask('noexec')
  694. getTask('umask')
  695. task_deps['parents'][task] = []
  696. if 'deps' in flags:
  697. for dep in flags['deps']:
  698. # Check and warn for "addtask task after foo" while foo does not exist
  699. #if not dep in tasklist:
  700. # bb.warn('%s: dependent task %s for %s does not exist' % (d.getVar('PN'), dep, task))
  701. dep = d.expand(dep)
  702. task_deps['parents'][task].append(dep)
  703. # don't assume holding a reference
  704. d.setVar('_task_deps', task_deps)
  705. def addtask(task, before, after, d):
  706. if task[:3] != "do_":
  707. task = "do_" + task
  708. d.setVarFlag(task, "task", 1)
  709. bbtasks = d.getVar('__BBTASKS', False) or []
  710. if task not in bbtasks:
  711. bbtasks.append(task)
  712. d.setVar('__BBTASKS', bbtasks)
  713. existing = d.getVarFlag(task, "deps", False) or []
  714. if after is not None:
  715. # set up deps for function
  716. for entry in after.split():
  717. if entry not in existing:
  718. existing.append(entry)
  719. d.setVarFlag(task, "deps", existing)
  720. if before is not None:
  721. # set up things that depend on this func
  722. for entry in before.split():
  723. existing = d.getVarFlag(entry, "deps", False) or []
  724. if task not in existing:
  725. d.setVarFlag(entry, "deps", [task] + existing)
  726. def deltask(task, d):
  727. if task[:3] != "do_":
  728. task = "do_" + task
  729. bbtasks = d.getVar('__BBTASKS', False) or []
  730. if task in bbtasks:
  731. bbtasks.remove(task)
  732. d.delVarFlag(task, 'task')
  733. d.setVar('__BBTASKS', bbtasks)
  734. d.delVarFlag(task, 'deps')
  735. for bbtask in d.getVar('__BBTASKS', False) or []:
  736. deps = d.getVarFlag(bbtask, 'deps', False) or []
  737. if task in deps:
  738. deps.remove(task)
  739. d.setVarFlag(bbtask, 'deps', deps)
  740. def preceedtask(task, with_recrdeptasks, d):
  741. """
  742. Returns a set of tasks in the current recipe which were specified as
  743. precondition by the task itself ("after") or which listed themselves
  744. as precondition ("before"). Preceeding tasks specified via the
  745. "recrdeptask" are included in the result only if requested. Beware
  746. that this may lead to the task itself being listed.
  747. """
  748. preceed = set()
  749. # Ignore tasks which don't exist
  750. tasks = d.getVar('__BBTASKS', False)
  751. if task not in tasks:
  752. return preceed
  753. preceed.update(d.getVarFlag(task, 'deps') or [])
  754. if with_recrdeptasks:
  755. recrdeptask = d.getVarFlag(task, 'recrdeptask')
  756. if recrdeptask:
  757. preceed.update(recrdeptask.split())
  758. return preceed
  759. def tasksbetween(task_start, task_end, d):
  760. """
  761. Return the list of tasks between two tasks in the current recipe,
  762. where task_start is to start at and task_end is the task to end at
  763. (and task_end has a dependency chain back to task_start).
  764. """
  765. outtasks = []
  766. tasks = list(filter(lambda k: d.getVarFlag(k, "task"), d.keys()))
  767. def follow_chain(task, endtask, chain=None):
  768. if not chain:
  769. chain = []
  770. chain.append(task)
  771. for othertask in tasks:
  772. if othertask == task:
  773. continue
  774. if task == endtask:
  775. for ctask in chain:
  776. if ctask not in outtasks:
  777. outtasks.append(ctask)
  778. else:
  779. deps = d.getVarFlag(othertask, 'deps', False)
  780. if task in deps:
  781. follow_chain(othertask, endtask, chain)
  782. chain.pop()
  783. follow_chain(task_start, task_end)
  784. return outtasks