utils.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. #
  2. # SPDX-License-Identifier: GPL-2.0-only
  3. #
  4. import subprocess
  5. import multiprocessing
  6. import traceback
  7. def read_file(filename):
  8. try:
  9. f = open( filename, "r" )
  10. except IOError as reason:
  11. return "" # WARNING: can't raise an error now because of the new RDEPENDS handling. This is a bit ugly. :M:
  12. else:
  13. data = f.read().strip()
  14. f.close()
  15. return data
  16. return None
  17. def ifelse(condition, iftrue = True, iffalse = False):
  18. if condition:
  19. return iftrue
  20. else:
  21. return iffalse
  22. def conditional(variable, checkvalue, truevalue, falsevalue, d):
  23. if d.getVar(variable) == checkvalue:
  24. return truevalue
  25. else:
  26. return falsevalue
  27. def vartrue(var, iftrue, iffalse, d):
  28. import oe.types
  29. if oe.types.boolean(d.getVar(var)):
  30. return iftrue
  31. else:
  32. return iffalse
  33. def less_or_equal(variable, checkvalue, truevalue, falsevalue, d):
  34. if float(d.getVar(variable)) <= float(checkvalue):
  35. return truevalue
  36. else:
  37. return falsevalue
  38. def version_less_or_equal(variable, checkvalue, truevalue, falsevalue, d):
  39. result = bb.utils.vercmp_string(d.getVar(variable), checkvalue)
  40. if result <= 0:
  41. return truevalue
  42. else:
  43. return falsevalue
  44. def both_contain(variable1, variable2, checkvalue, d):
  45. val1 = d.getVar(variable1)
  46. val2 = d.getVar(variable2)
  47. val1 = set(val1.split())
  48. val2 = set(val2.split())
  49. if isinstance(checkvalue, str):
  50. checkvalue = set(checkvalue.split())
  51. else:
  52. checkvalue = set(checkvalue)
  53. if checkvalue.issubset(val1) and checkvalue.issubset(val2):
  54. return " ".join(checkvalue)
  55. else:
  56. return ""
  57. def set_intersect(variable1, variable2, d):
  58. """
  59. Expand both variables, interpret them as lists of strings, and return the
  60. intersection as a flattened string.
  61. For example:
  62. s1 = "a b c"
  63. s2 = "b c d"
  64. s3 = set_intersect(s1, s2)
  65. => s3 = "b c"
  66. """
  67. val1 = set(d.getVar(variable1).split())
  68. val2 = set(d.getVar(variable2).split())
  69. return " ".join(val1 & val2)
  70. def prune_suffix(var, suffixes, d):
  71. # See if var ends with any of the suffixes listed and
  72. # remove it if found
  73. for suffix in suffixes:
  74. if suffix and var.endswith(suffix):
  75. var = var[:-len(suffix)]
  76. prefix = d.getVar("MLPREFIX")
  77. if prefix and var.startswith(prefix):
  78. var = var[len(prefix):]
  79. return var
  80. def str_filter(f, str, d):
  81. from re import match
  82. return " ".join([x for x in str.split() if match(f, x, 0)])
  83. def str_filter_out(f, str, d):
  84. from re import match
  85. return " ".join([x for x in str.split() if not match(f, x, 0)])
  86. def build_depends_string(depends, task):
  87. """Append a taskname to a string of dependencies as used by the [depends] flag"""
  88. return " ".join(dep + ":" + task for dep in depends.split())
  89. def inherits(d, *classes):
  90. """Return True if the metadata inherits any of the specified classes"""
  91. return any(bb.data.inherits_class(cls, d) for cls in classes)
  92. def features_backfill(var,d):
  93. # This construct allows the addition of new features to variable specified
  94. # as var
  95. # Example for var = "DISTRO_FEATURES"
  96. # This construct allows the addition of new features to DISTRO_FEATURES
  97. # that if not present would disable existing functionality, without
  98. # disturbing distributions that have already set DISTRO_FEATURES.
  99. # Distributions wanting to elide a value in DISTRO_FEATURES_BACKFILL should
  100. # add the feature to DISTRO_FEATURES_BACKFILL_CONSIDERED
  101. features = (d.getVar(var) or "").split()
  102. backfill = (d.getVar(var+"_BACKFILL") or "").split()
  103. considered = (d.getVar(var+"_BACKFILL_CONSIDERED") or "").split()
  104. addfeatures = []
  105. for feature in backfill:
  106. if feature not in features and feature not in considered:
  107. addfeatures.append(feature)
  108. if addfeatures:
  109. d.appendVar(var, " " + " ".join(addfeatures))
  110. def all_distro_features(d, features, truevalue="1", falsevalue=""):
  111. """
  112. Returns truevalue if *all* given features are set in DISTRO_FEATURES,
  113. else falsevalue. The features can be given as single string or anything
  114. that can be turned into a set.
  115. This is a shorter, more flexible version of
  116. bb.utils.contains("DISTRO_FEATURES", features, truevalue, falsevalue, d).
  117. Without explicit true/false values it can be used directly where
  118. Python expects a boolean:
  119. if oe.utils.all_distro_features(d, "foo bar"):
  120. bb.fatal("foo and bar are mutually exclusive DISTRO_FEATURES")
  121. With just a truevalue, it can be used to include files that are meant to be
  122. used only when requested via DISTRO_FEATURES:
  123. require ${@ oe.utils.all_distro_features(d, "foo bar", "foo-and-bar.inc")
  124. """
  125. return bb.utils.contains("DISTRO_FEATURES", features, truevalue, falsevalue, d)
  126. def any_distro_features(d, features, truevalue="1", falsevalue=""):
  127. """
  128. Returns truevalue if at least *one* of the given features is set in DISTRO_FEATURES,
  129. else falsevalue. The features can be given as single string or anything
  130. that can be turned into a set.
  131. This is a shorter, more flexible version of
  132. bb.utils.contains_any("DISTRO_FEATURES", features, truevalue, falsevalue, d).
  133. Without explicit true/false values it can be used directly where
  134. Python expects a boolean:
  135. if not oe.utils.any_distro_features(d, "foo bar"):
  136. bb.fatal("foo, bar or both must be set in DISTRO_FEATURES")
  137. With just a truevalue, it can be used to include files that are meant to be
  138. used only when requested via DISTRO_FEATURES:
  139. require ${@ oe.utils.any_distro_features(d, "foo bar", "foo-or-bar.inc")
  140. """
  141. return bb.utils.contains_any("DISTRO_FEATURES", features, truevalue, falsevalue, d)
  142. def parallel_make(d):
  143. """
  144. Return the integer value for the number of parallel threads to use when
  145. building, scraped out of PARALLEL_MAKE. If no parallelization option is
  146. found, returns None
  147. e.g. if PARALLEL_MAKE = "-j 10", this will return 10 as an integer.
  148. """
  149. pm = (d.getVar('PARALLEL_MAKE') or '').split()
  150. # look for '-j' and throw other options (e.g. '-l') away
  151. while pm:
  152. opt = pm.pop(0)
  153. if opt == '-j':
  154. v = pm.pop(0)
  155. elif opt.startswith('-j'):
  156. v = opt[2:].strip()
  157. else:
  158. continue
  159. return int(v)
  160. return None
  161. def parallel_make_argument(d, fmt, limit=None):
  162. """
  163. Helper utility to construct a parallel make argument from the number of
  164. parallel threads specified in PARALLEL_MAKE.
  165. Returns the input format string `fmt` where a single '%d' will be expanded
  166. with the number of parallel threads to use. If `limit` is specified, the
  167. number of parallel threads will be no larger than it. If no parallelization
  168. option is found in PARALLEL_MAKE, returns an empty string
  169. e.g. if PARALLEL_MAKE = "-j 10", parallel_make_argument(d, "-n %d") will return
  170. "-n 10"
  171. """
  172. v = parallel_make(d)
  173. if v:
  174. if limit:
  175. v = min(limit, v)
  176. return fmt % v
  177. return ''
  178. def packages_filter_out_system(d):
  179. """
  180. Return a list of packages from PACKAGES with the "system" packages such as
  181. PN-dbg PN-doc PN-locale-eb-gb removed.
  182. """
  183. pn = d.getVar('PN')
  184. blacklist = [pn + suffix for suffix in ('', '-dbg', '-dev', '-doc', '-locale', '-staticdev', '-src')]
  185. localepkg = pn + "-locale-"
  186. pkgs = []
  187. for pkg in d.getVar('PACKAGES').split():
  188. if pkg not in blacklist and localepkg not in pkg:
  189. pkgs.append(pkg)
  190. return pkgs
  191. def getstatusoutput(cmd):
  192. return subprocess.getstatusoutput(cmd)
  193. def trim_version(version, num_parts=2):
  194. """
  195. Return just the first <num_parts> of <version>, split by periods. For
  196. example, trim_version("1.2.3", 2) will return "1.2".
  197. """
  198. if type(version) is not str:
  199. raise TypeError("Version should be a string")
  200. if num_parts < 1:
  201. raise ValueError("Cannot split to parts < 1")
  202. parts = version.split(".")
  203. trimmed = ".".join(parts[:num_parts])
  204. return trimmed
  205. def cpu_count():
  206. import multiprocessing
  207. return multiprocessing.cpu_count()
  208. def execute_pre_post_process(d, cmds):
  209. if cmds is None:
  210. return
  211. for cmd in cmds.strip().split(';'):
  212. cmd = cmd.strip()
  213. if cmd != '':
  214. bb.note("Executing %s ..." % cmd)
  215. bb.build.exec_func(cmd, d)
  216. # For each item in items, call the function 'target' with item as the first
  217. # argument, extraargs as the other arguments and handle any exceptions in the
  218. # parent thread
  219. def multiprocess_launch(target, items, d, extraargs=None):
  220. class ProcessLaunch(multiprocessing.Process):
  221. def __init__(self, *args, **kwargs):
  222. multiprocessing.Process.__init__(self, *args, **kwargs)
  223. self._pconn, self._cconn = multiprocessing.Pipe()
  224. self._exception = None
  225. self._result = None
  226. def run(self):
  227. try:
  228. ret = self._target(*self._args, **self._kwargs)
  229. self._cconn.send((None, ret))
  230. except Exception as e:
  231. tb = traceback.format_exc()
  232. self._cconn.send((e, tb))
  233. def update(self):
  234. if self._pconn.poll():
  235. (e, tb) = self._pconn.recv()
  236. if e is not None:
  237. self._exception = (e, tb)
  238. else:
  239. self._result = tb
  240. @property
  241. def exception(self):
  242. self.update()
  243. return self._exception
  244. @property
  245. def result(self):
  246. self.update()
  247. return self._result
  248. max_process = int(d.getVar("BB_NUMBER_THREADS") or os.cpu_count() or 1)
  249. launched = []
  250. errors = []
  251. results = []
  252. items = list(items)
  253. while (items and not errors) or launched:
  254. if not errors and items and len(launched) < max_process:
  255. args = (items.pop(),)
  256. if extraargs is not None:
  257. args = args + extraargs
  258. p = ProcessLaunch(target=target, args=args)
  259. p.start()
  260. launched.append(p)
  261. for q in launched:
  262. # Have to manually call update() to avoid deadlocks. The pipe can be full and
  263. # transfer stalled until we try and read the results object but the subprocess won't exit
  264. # as it still has data to write (https://bugs.python.org/issue8426)
  265. q.update()
  266. # The finished processes are joined when calling is_alive()
  267. if not q.is_alive():
  268. if q.exception:
  269. errors.append(q.exception)
  270. if q.result:
  271. results.append(q.result)
  272. launched.remove(q)
  273. # Paranoia doesn't hurt
  274. for p in launched:
  275. p.join()
  276. if errors:
  277. msg = ""
  278. for (e, tb) in errors:
  279. if isinstance(e, subprocess.CalledProcessError) and e.output:
  280. msg = msg + str(e) + "\n"
  281. msg = msg + "Subprocess output:"
  282. msg = msg + e.output.decode("utf-8", errors="ignore")
  283. else:
  284. msg = msg + str(e) + ": " + str(tb) + "\n"
  285. bb.fatal("Fatal errors occurred in subprocesses:\n%s" % msg)
  286. return results
  287. def squashspaces(string):
  288. import re
  289. return re.sub(r"\s+", " ", string).strip()
  290. def format_pkg_list(pkg_dict, ret_format=None):
  291. output = []
  292. if ret_format == "arch":
  293. for pkg in sorted(pkg_dict):
  294. output.append("%s %s" % (pkg, pkg_dict[pkg]["arch"]))
  295. elif ret_format == "file":
  296. for pkg in sorted(pkg_dict):
  297. output.append("%s %s %s" % (pkg, pkg_dict[pkg]["filename"], pkg_dict[pkg]["arch"]))
  298. elif ret_format == "ver":
  299. for pkg in sorted(pkg_dict):
  300. output.append("%s %s %s" % (pkg, pkg_dict[pkg]["arch"], pkg_dict[pkg]["ver"]))
  301. elif ret_format == "deps":
  302. for pkg in sorted(pkg_dict):
  303. for dep in pkg_dict[pkg]["deps"]:
  304. output.append("%s|%s" % (pkg, dep))
  305. else:
  306. for pkg in sorted(pkg_dict):
  307. output.append(pkg)
  308. output_str = '\n'.join(output)
  309. if output_str:
  310. # make sure last line is newline terminated
  311. output_str += '\n'
  312. return output_str
  313. def host_gcc_version(d, taskcontextonly=False):
  314. import re, subprocess
  315. if taskcontextonly and d.getVar('BB_WORKERCONTEXT') != '1':
  316. return
  317. compiler = d.getVar("BUILD_CC")
  318. # Get rid of ccache since it is not present when parsing.
  319. if compiler.startswith('ccache '):
  320. compiler = compiler[7:]
  321. try:
  322. env = os.environ.copy()
  323. env["PATH"] = d.getVar("PATH")
  324. output = subprocess.check_output("%s --version" % compiler, \
  325. shell=True, env=env, stderr=subprocess.STDOUT).decode("utf-8")
  326. except subprocess.CalledProcessError as e:
  327. bb.fatal("Error running %s --version: %s" % (compiler, e.output.decode("utf-8")))
  328. match = re.match(r".* (\d\.\d)\.\d.*", output.split('\n')[0])
  329. if not match:
  330. bb.fatal("Can't get compiler version from %s --version output" % compiler)
  331. version = match.group(1)
  332. return "-%s" % version if version in ("4.8", "4.9") else ""
  333. def get_multilib_datastore(variant, d):
  334. localdata = bb.data.createCopy(d)
  335. if variant:
  336. overrides = localdata.getVar("OVERRIDES", False) + ":virtclass-multilib-" + variant
  337. localdata.setVar("OVERRIDES", overrides)
  338. localdata.setVar("MLPREFIX", variant + "-")
  339. else:
  340. origdefault = localdata.getVar("DEFAULTTUNE_MULTILIB_ORIGINAL")
  341. if origdefault:
  342. localdata.setVar("DEFAULTTUNE", origdefault)
  343. overrides = localdata.getVar("OVERRIDES", False).split(":")
  344. overrides = ":".join([x for x in overrides if not x.startswith("virtclass-multilib-")])
  345. localdata.setVar("OVERRIDES", overrides)
  346. localdata.setVar("MLPREFIX", "")
  347. return localdata
  348. #
  349. # Python 2.7 doesn't have threaded pools (just multiprocessing)
  350. # so implement a version here
  351. #
  352. from queue import Queue
  353. from threading import Thread
  354. class ThreadedWorker(Thread):
  355. """Thread executing tasks from a given tasks queue"""
  356. def __init__(self, tasks, worker_init, worker_end):
  357. Thread.__init__(self)
  358. self.tasks = tasks
  359. self.daemon = True
  360. self.worker_init = worker_init
  361. self.worker_end = worker_end
  362. def run(self):
  363. from queue import Empty
  364. if self.worker_init is not None:
  365. self.worker_init(self)
  366. while True:
  367. try:
  368. func, args, kargs = self.tasks.get(block=False)
  369. except Empty:
  370. if self.worker_end is not None:
  371. self.worker_end(self)
  372. break
  373. try:
  374. func(self, *args, **kargs)
  375. except Exception as e:
  376. print(e)
  377. finally:
  378. self.tasks.task_done()
  379. class ThreadedPool:
  380. """Pool of threads consuming tasks from a queue"""
  381. def __init__(self, num_workers, num_tasks, worker_init=None,
  382. worker_end=None):
  383. self.tasks = Queue(num_tasks)
  384. self.workers = []
  385. for _ in range(num_workers):
  386. worker = ThreadedWorker(self.tasks, worker_init, worker_end)
  387. self.workers.append(worker)
  388. def start(self):
  389. for worker in self.workers:
  390. worker.start()
  391. def add_task(self, func, *args, **kargs):
  392. """Add a task to the queue"""
  393. self.tasks.put((func, args, kargs))
  394. def wait_completion(self):
  395. """Wait for completion of all the tasks in the queue"""
  396. self.tasks.join()
  397. for worker in self.workers:
  398. worker.join()
  399. def write_ld_so_conf(d):
  400. # Some utils like prelink may not have the correct target library paths
  401. # so write an ld.so.conf to help them
  402. ldsoconf = d.expand("${STAGING_DIR_TARGET}${sysconfdir}/ld.so.conf")
  403. if os.path.exists(ldsoconf):
  404. bb.utils.remove(ldsoconf)
  405. bb.utils.mkdirhier(os.path.dirname(ldsoconf))
  406. with open(ldsoconf, "w") as f:
  407. f.write(d.getVar("base_libdir") + '\n')
  408. f.write(d.getVar("libdir") + '\n')
  409. class ImageQAFailed(bb.build.FuncFailed):
  410. def __init__(self, description, name=None, logfile=None):
  411. self.description = description
  412. self.name = name
  413. self.logfile=logfile
  414. def __str__(self):
  415. msg = 'Function failed: %s' % self.name
  416. if self.description:
  417. msg = msg + ' (%s)' % self.description
  418. return msg
  419. def sh_quote(string):
  420. import shlex
  421. return shlex.quote(string)