build.py 34 KB

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