build.py 29 KB

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