query.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. #
  2. # Copyright BitBake Contributors
  3. #
  4. # SPDX-License-Identifier: GPL-2.0-only
  5. #
  6. import collections
  7. import fnmatch
  8. import logging
  9. import sys
  10. import os
  11. import re
  12. import bb.utils
  13. from bblayers.common import LayerPlugin
  14. logger = logging.getLogger('bitbake-layers')
  15. def plugin_init(plugins):
  16. return QueryPlugin()
  17. class QueryPlugin(LayerPlugin):
  18. def __init__(self):
  19. super(QueryPlugin, self).__init__()
  20. self.collection_res = {}
  21. def do_show_layers(self, args):
  22. """show current configured layers."""
  23. logger.plain("%s %s %s" % ("layer".ljust(20), "path".ljust(70), "priority"))
  24. logger.plain('=' * 104)
  25. for layer, _, regex, pri in self.tinfoil.cooker.bbfile_config_priorities:
  26. layerdir = self.bbfile_collections.get(layer, None)
  27. layername = layer
  28. logger.plain("%s %s %s" % (layername.ljust(20), layerdir.ljust(70), pri))
  29. def version_str(self, pe, pv, pr = None):
  30. verstr = "%s" % pv
  31. if pr:
  32. verstr = "%s-%s" % (verstr, pr)
  33. if pe:
  34. verstr = "%s:%s" % (pe, verstr)
  35. return verstr
  36. def do_show_overlayed(self, args):
  37. """list overlayed recipes (where the same recipe exists in another layer)
  38. Lists the names of overlayed recipes and the available versions in each
  39. layer, with the preferred version first. Note that skipped recipes that
  40. are overlayed will also be listed, with a " (skipped)" suffix.
  41. """
  42. items_listed = self.list_recipes('Overlayed recipes', None, True, args.same_version, args.filenames, False, True, None, False, None, args.mc)
  43. # Check for overlayed .bbclass files
  44. classes = collections.defaultdict(list)
  45. for layerdir in self.bblayers:
  46. for c in ["classes-global", "classes-recipe", "classes"]:
  47. classdir = os.path.join(layerdir, c)
  48. if os.path.exists(classdir):
  49. for classfile in os.listdir(classdir):
  50. if os.path.splitext(classfile)[1] == '.bbclass':
  51. classes[classfile].append(classdir)
  52. # Locating classes and other files is a bit more complicated than recipes -
  53. # layer priority is not a factor; instead BitBake uses the first matching
  54. # file in BBPATH, which is manipulated directly by each layer's
  55. # conf/layer.conf in turn, thus the order of layers in bblayers.conf is a
  56. # factor - however, each layer.conf is free to either prepend or append to
  57. # BBPATH (or indeed do crazy stuff with it). Thus the order in BBPATH might
  58. # not be exactly the order present in bblayers.conf either.
  59. bbpath = str(self.tinfoil.config_data.getVar('BBPATH'))
  60. overlayed_class_found = False
  61. for (classfile, classdirs) in classes.items():
  62. if len(classdirs) > 1:
  63. if not overlayed_class_found:
  64. logger.plain('=== Overlayed classes ===')
  65. overlayed_class_found = True
  66. mainfile = bb.utils.which(bbpath, os.path.join('classes', classfile))
  67. if args.filenames:
  68. logger.plain('%s' % mainfile)
  69. else:
  70. # We effectively have to guess the layer here
  71. logger.plain('%s:' % classfile)
  72. mainlayername = '?'
  73. for layerdir in self.bblayers:
  74. classdir = os.path.join(layerdir, 'classes')
  75. if mainfile.startswith(classdir):
  76. mainlayername = self.get_layer_name(layerdir)
  77. logger.plain(' %s' % mainlayername)
  78. for classdir in classdirs:
  79. fullpath = os.path.join(classdir, classfile)
  80. if fullpath != mainfile:
  81. if args.filenames:
  82. print(' %s' % fullpath)
  83. else:
  84. print(' %s' % self.get_layer_name(os.path.dirname(classdir)))
  85. if overlayed_class_found:
  86. items_listed = True;
  87. if not items_listed:
  88. logger.plain('No overlayed files found.')
  89. def do_show_recipes(self, args):
  90. """list available recipes, showing the layer they are provided by
  91. Lists the names of recipes and the available versions in each
  92. layer, with the preferred version first. Optionally you may specify
  93. pnspec to match a specified recipe name (supports wildcards). Note that
  94. skipped recipes will also be listed, with a " (skipped)" suffix.
  95. """
  96. inheritlist = args.inherits.split(',') if args.inherits else []
  97. if inheritlist or args.pnspec or args.multiple:
  98. title = 'Matching recipes:'
  99. else:
  100. title = 'Available recipes:'
  101. self.list_recipes(title, args.pnspec, False, False, args.filenames, args.recipes_only, args.multiple, args.layer, args.bare, inheritlist, args.mc)
  102. def list_recipes(self, title, pnspec, show_overlayed_only, show_same_ver_only, show_filenames, show_recipes_only, show_multi_provider_only, selected_layer, bare, inherits, mc):
  103. if inherits:
  104. bbpath = str(self.tinfoil.config_data.getVar('BBPATH'))
  105. for classname in inherits:
  106. found = False
  107. for c in ["classes-global", "classes-recipe", "classes"]:
  108. cfile = c + '/%s.bbclass' % classname
  109. if bb.utils.which(bbpath, cfile, history=False):
  110. found = True
  111. break
  112. if not found:
  113. logger.error('No class named %s found in BBPATH', classname)
  114. sys.exit(1)
  115. pkg_pn = self.tinfoil.cooker.recipecaches[mc].pkg_pn
  116. (latest_versions, preferred_versions, required_versions) = self.tinfoil.find_providers(mc)
  117. allproviders = self.tinfoil.get_all_providers(mc)
  118. # Ensure we list skipped recipes
  119. # We are largely guessing about PN, PV and the preferred version here,
  120. # but we have no choice since skipped recipes are not fully parsed
  121. skiplist = list(self.tinfoil.cooker.skiplist_by_mc[mc].keys())
  122. if mc:
  123. skiplist = [s.removeprefix(f'mc:{mc}:') for s in skiplist]
  124. for fn in skiplist:
  125. recipe_parts = os.path.splitext(os.path.basename(fn))[0].split('_')
  126. p = recipe_parts[0]
  127. if len(recipe_parts) > 1:
  128. ver = (None, recipe_parts[1], None)
  129. else:
  130. ver = (None, 'unknown', None)
  131. allproviders[p].append((ver, fn))
  132. if not p in pkg_pn:
  133. pkg_pn[p] = 'dummy'
  134. preferred_versions[p] = (ver, fn)
  135. def print_item(f, pn, ver, layer, ispref):
  136. if not selected_layer or layer == selected_layer:
  137. if not bare and f in skiplist:
  138. skipped = ' (skipped: %s)' % self.tinfoil.cooker.skiplist_by_mc[mc][f].skipreason
  139. else:
  140. skipped = ''
  141. if show_filenames:
  142. if ispref:
  143. logger.plain("%s%s", f, skipped)
  144. else:
  145. logger.plain(" %s%s", f, skipped)
  146. elif show_recipes_only:
  147. if pn not in show_unique_pn:
  148. show_unique_pn.append(pn)
  149. logger.plain("%s%s", pn, skipped)
  150. else:
  151. if ispref:
  152. logger.plain("%s:", pn)
  153. logger.plain(" %s %s%s", layer.ljust(20), ver, skipped)
  154. global_inherit = (self.tinfoil.config_data.getVar('INHERIT') or "").split()
  155. cls_re = re.compile('classes.*/')
  156. preffiles = []
  157. show_unique_pn = []
  158. items_listed = False
  159. for p in sorted(pkg_pn):
  160. if pnspec:
  161. found=False
  162. for pnm in pnspec:
  163. if fnmatch.fnmatch(p, pnm):
  164. found=True
  165. break
  166. if not found:
  167. continue
  168. if len(allproviders[p]) > 1 or not show_multi_provider_only:
  169. pref = preferred_versions[p]
  170. realfn = bb.cache.virtualfn2realfn(pref[1])
  171. preffile = realfn[0]
  172. # We only display once per recipe, we should prefer non extended versions of the
  173. # recipe if present (so e.g. in OpenEmbedded, openssl rather than nativesdk-openssl
  174. # which would otherwise sort first).
  175. if realfn[1] and realfn[0] in self.tinfoil.cooker.recipecaches[mc].pkg_fn:
  176. continue
  177. if inherits:
  178. matchcount = 0
  179. recipe_inherits = self.tinfoil.cooker_data.inherits.get(preffile, [])
  180. for cls in recipe_inherits:
  181. if cls_re.match(cls):
  182. continue
  183. classname = os.path.splitext(os.path.basename(cls))[0]
  184. if classname in global_inherit:
  185. continue
  186. elif classname in inherits:
  187. matchcount += 1
  188. if matchcount != len(inherits):
  189. # No match - skip this recipe
  190. continue
  191. if preffile not in preffiles:
  192. preflayer = self.get_file_layer(preffile)
  193. multilayer = False
  194. same_ver = True
  195. provs = []
  196. for prov in allproviders[p]:
  197. provfile = bb.cache.virtualfn2realfn(prov[1])[0]
  198. provlayer = self.get_file_layer(provfile)
  199. provs.append((provfile, provlayer, prov[0]))
  200. if provlayer != preflayer:
  201. multilayer = True
  202. if prov[0] != pref[0]:
  203. same_ver = False
  204. if (multilayer or not show_overlayed_only) and (same_ver or not show_same_ver_only):
  205. if not items_listed:
  206. logger.plain('=== %s ===' % title)
  207. items_listed = True
  208. print_item(preffile, p, self.version_str(pref[0][0], pref[0][1]), preflayer, True)
  209. for (provfile, provlayer, provver) in provs:
  210. if provfile != preffile:
  211. print_item(provfile, p, self.version_str(provver[0], provver[1]), provlayer, False)
  212. # Ensure we don't show two entries for BBCLASSEXTENDed recipes
  213. preffiles.append(preffile)
  214. return items_listed
  215. def get_file_layer(self, filename):
  216. layerdir = self.get_file_layerdir(filename)
  217. if layerdir:
  218. return self.get_layer_name(layerdir)
  219. else:
  220. return '?'
  221. def get_collection_res(self):
  222. if not self.collection_res:
  223. self.collection_res = bb.utils.get_collection_res(self.tinfoil.config_data)
  224. return self.collection_res
  225. def get_file_layerdir(self, filename):
  226. layer = bb.utils.get_file_layer(filename, self.tinfoil.config_data, self.get_collection_res())
  227. return self.bbfile_collections.get(layer, None)
  228. def remove_layer_prefix(self, f):
  229. """Remove the layer_dir prefix, e.g., f = /path/to/layer_dir/foo/blah, the
  230. return value will be: layer_dir/foo/blah"""
  231. f_layerdir = self.get_file_layerdir(f)
  232. if not f_layerdir:
  233. return f
  234. prefix = os.path.join(os.path.dirname(f_layerdir), '')
  235. return f[len(prefix):] if f.startswith(prefix) else f
  236. def do_show_appends(self, args):
  237. """list bbappend files and recipe files they apply to
  238. Lists recipes with the bbappends that apply to them as subitems.
  239. """
  240. if args.pnspec:
  241. logger.plain('=== Matched appended recipes ===')
  242. else:
  243. logger.plain('=== Appended recipes ===')
  244. cooker_data = self.tinfoil.cooker.recipecaches[args.mc]
  245. pnlist = list(cooker_data.pkg_pn.keys())
  246. pnlist.sort()
  247. appends = False
  248. for pn in pnlist:
  249. if args.pnspec:
  250. found=False
  251. for pnm in args.pnspec:
  252. if fnmatch.fnmatch(pn, pnm):
  253. found=True
  254. break
  255. if not found:
  256. continue
  257. if self.show_appends_for_pn(pn, cooker_data, args.mc):
  258. appends = True
  259. if not args.pnspec and self.show_appends_for_skipped(args.mc):
  260. appends = True
  261. if not appends:
  262. logger.plain('No append files found')
  263. def show_appends_for_pn(self, pn, cooker_data, mc):
  264. filenames = cooker_data.pkg_pn[pn]
  265. if mc:
  266. pn = "mc:%s:%s" % (mc, pn)
  267. best = self.tinfoil.find_best_provider(pn)
  268. best_filename = os.path.basename(best[3])
  269. return self.show_appends_output(filenames, best_filename)
  270. def show_appends_for_skipped(self, mc):
  271. filenames = [os.path.basename(f)
  272. for f in self.tinfoil.cooker.skiplist_by_mc[mc].keys()]
  273. return self.show_appends_output(filenames, None, " (skipped)")
  274. def show_appends_output(self, filenames, best_filename, name_suffix = ''):
  275. appended, missing = self.get_appends_for_files(filenames)
  276. if appended:
  277. for basename, appends in appended:
  278. logger.plain('%s%s:', basename, name_suffix)
  279. for append in appends:
  280. logger.plain(' %s', append)
  281. if best_filename:
  282. if best_filename in missing:
  283. logger.warning('%s: missing append for preferred version',
  284. best_filename)
  285. return True
  286. else:
  287. return False
  288. def get_appends_for_files(self, filenames):
  289. appended, notappended = [], []
  290. for filename in filenames:
  291. _, cls, mc = bb.cache.virtualfn2realfn(filename)
  292. if cls:
  293. continue
  294. basename = os.path.basename(filename)
  295. appends = self.tinfoil.cooker.collections[mc].get_file_appends(basename)
  296. if appends:
  297. appended.append((basename, list(appends)))
  298. else:
  299. notappended.append(basename)
  300. return appended, notappended
  301. def do_show_cross_depends(self, args):
  302. """Show dependencies between recipes that cross layer boundaries.
  303. Figure out the dependencies between recipes that cross layer boundaries.
  304. NOTE: .bbappend files can impact the dependencies.
  305. """
  306. ignore_layers = (args.ignore or '').split(',')
  307. pkg_fn = self.tinfoil.cooker_data.pkg_fn
  308. bbpath = str(self.tinfoil.config_data.getVar('BBPATH'))
  309. self.require_re = re.compile(r"require\s+(.+)")
  310. self.include_re = re.compile(r"include\s+(.+)")
  311. self.inherit_re = re.compile(r"inherit\s+(.+)")
  312. global_inherit = (self.tinfoil.config_data.getVar('INHERIT') or "").split()
  313. # The bb's DEPENDS and RDEPENDS
  314. for f in pkg_fn:
  315. f = bb.cache.virtualfn2realfn(f)[0]
  316. # Get the layername that the file is in
  317. layername = self.get_file_layer(f)
  318. # The DEPENDS
  319. deps = self.tinfoil.cooker_data.deps[f]
  320. for pn in deps:
  321. if pn in self.tinfoil.cooker_data.pkg_pn:
  322. best = self.tinfoil.find_best_provider(pn)
  323. self.check_cross_depends("DEPENDS", layername, f, best[3], args.filenames, ignore_layers)
  324. # The RDPENDS
  325. all_rdeps = self.tinfoil.cooker_data.rundeps[f].values()
  326. # Remove the duplicated or null one.
  327. sorted_rdeps = {}
  328. # The all_rdeps is the list in list, so we need two for loops
  329. for k1 in all_rdeps:
  330. for k2 in k1:
  331. sorted_rdeps[k2] = 1
  332. all_rdeps = sorted_rdeps.keys()
  333. for rdep in all_rdeps:
  334. all_p, best = self.tinfoil.get_runtime_providers(rdep)
  335. if all_p:
  336. if f in all_p:
  337. # The recipe provides this one itself, ignore
  338. continue
  339. self.check_cross_depends("RDEPENDS", layername, f, best, args.filenames, ignore_layers)
  340. # The RRECOMMENDS
  341. all_rrecs = self.tinfoil.cooker_data.runrecs[f].values()
  342. # Remove the duplicated or null one.
  343. sorted_rrecs = {}
  344. # The all_rrecs is the list in list, so we need two for loops
  345. for k1 in all_rrecs:
  346. for k2 in k1:
  347. sorted_rrecs[k2] = 1
  348. all_rrecs = sorted_rrecs.keys()
  349. for rrec in all_rrecs:
  350. all_p, best = self.tinfoil.get_runtime_providers(rrec)
  351. if all_p:
  352. if f in all_p:
  353. # The recipe provides this one itself, ignore
  354. continue
  355. self.check_cross_depends("RRECOMMENDS", layername, f, best, args.filenames, ignore_layers)
  356. # The inherit class
  357. cls_re = re.compile('classes.*/')
  358. if f in self.tinfoil.cooker_data.inherits:
  359. inherits = self.tinfoil.cooker_data.inherits[f]
  360. for cls in inherits:
  361. # The inherits' format is [classes/cls, /path/to/classes/cls]
  362. # ignore the classes/cls.
  363. if not cls_re.match(cls):
  364. classname = os.path.splitext(os.path.basename(cls))[0]
  365. if classname in global_inherit:
  366. continue
  367. inherit_layername = self.get_file_layer(cls)
  368. if inherit_layername != layername and not inherit_layername in ignore_layers:
  369. if not args.filenames:
  370. f_short = self.remove_layer_prefix(f)
  371. cls = self.remove_layer_prefix(cls)
  372. else:
  373. f_short = f
  374. logger.plain("%s inherits %s" % (f_short, cls))
  375. # The 'require/include xxx' in the bb file
  376. pv_re = re.compile(r"\${PV}")
  377. with open(f, 'r') as fnfile:
  378. line = fnfile.readline()
  379. while line:
  380. m, keyword = self.match_require_include(line)
  381. # Found the 'require/include xxxx'
  382. if m:
  383. needed_file = m.group(1)
  384. # Replace the ${PV} with the real PV
  385. if pv_re.search(needed_file) and f in self.tinfoil.cooker_data.pkg_pepvpr:
  386. pv = self.tinfoil.cooker_data.pkg_pepvpr[f][1]
  387. needed_file = re.sub(r"\${PV}", pv, needed_file)
  388. self.print_cross_files(bbpath, keyword, layername, f, needed_file, args.filenames, ignore_layers)
  389. line = fnfile.readline()
  390. # The "require/include xxx" in conf/machine/*.conf, .inc and .bbclass
  391. conf_re = re.compile(r".*/conf/machine/[^\/]*\.conf$")
  392. inc_re = re.compile(r".*\.inc$")
  393. # The "inherit xxx" in .bbclass
  394. bbclass_re = re.compile(r".*\.bbclass$")
  395. for layerdir in self.bblayers:
  396. layername = self.get_layer_name(layerdir)
  397. for dirpath, dirnames, filenames in os.walk(layerdir):
  398. for name in filenames:
  399. f = os.path.join(dirpath, name)
  400. s = conf_re.match(f) or inc_re.match(f) or bbclass_re.match(f)
  401. if s:
  402. with open(f, 'r') as ffile:
  403. line = ffile.readline()
  404. while line:
  405. m, keyword = self.match_require_include(line)
  406. # Only bbclass has the "inherit xxx" here.
  407. bbclass=""
  408. if not m and f.endswith(".bbclass"):
  409. m, keyword = self.match_inherit(line)
  410. bbclass=".bbclass"
  411. # Find a 'require/include xxxx'
  412. if m:
  413. self.print_cross_files(bbpath, keyword, layername, f, m.group(1) + bbclass, args.filenames, ignore_layers)
  414. line = ffile.readline()
  415. def print_cross_files(self, bbpath, keyword, layername, f, needed_filename, show_filenames, ignore_layers):
  416. """Print the depends that crosses a layer boundary"""
  417. needed_file = bb.utils.which(bbpath, needed_filename)
  418. if needed_file:
  419. # Which layer is this file from
  420. needed_layername = self.get_file_layer(needed_file)
  421. if needed_layername != layername and not needed_layername in ignore_layers:
  422. if not show_filenames:
  423. f = self.remove_layer_prefix(f)
  424. needed_file = self.remove_layer_prefix(needed_file)
  425. logger.plain("%s %s %s" %(f, keyword, needed_file))
  426. def match_inherit(self, line):
  427. """Match the inherit xxx line"""
  428. return (self.inherit_re.match(line), "inherits")
  429. def match_require_include(self, line):
  430. """Match the require/include xxx line"""
  431. m = self.require_re.match(line)
  432. keyword = "requires"
  433. if not m:
  434. m = self.include_re.match(line)
  435. keyword = "includes"
  436. return (m, keyword)
  437. def check_cross_depends(self, keyword, layername, f, needed_file, show_filenames, ignore_layers):
  438. """Print the DEPENDS/RDEPENDS file that crosses a layer boundary"""
  439. best_realfn = bb.cache.virtualfn2realfn(needed_file)[0]
  440. needed_layername = self.get_file_layer(best_realfn)
  441. if needed_layername != layername and not needed_layername in ignore_layers:
  442. if not show_filenames:
  443. f = self.remove_layer_prefix(f)
  444. best_realfn = self.remove_layer_prefix(best_realfn)
  445. logger.plain("%s %s %s" % (f, keyword, best_realfn))
  446. def register_commands(self, sp):
  447. self.add_command(sp, 'show-layers', self.do_show_layers, parserecipes=False)
  448. parser_show_overlayed = self.add_command(sp, 'show-overlayed', self.do_show_overlayed)
  449. parser_show_overlayed.add_argument('-f', '--filenames', help='instead of the default formatting, list filenames of higher priority recipes with the ones they overlay indented underneath', action='store_true')
  450. parser_show_overlayed.add_argument('-s', '--same-version', help='only list overlayed recipes where the version is the same', action='store_true')
  451. parser_show_overlayed.add_argument('--mc', help='use specified multiconfig', default='')
  452. parser_show_recipes = self.add_command(sp, 'show-recipes', self.do_show_recipes)
  453. parser_show_recipes.add_argument('-f', '--filenames', help='instead of the default formatting, list filenames of higher priority recipes with the ones they overlay indented underneath', action='store_true')
  454. parser_show_recipes.add_argument('-r', '--recipes-only', help='instead of the default formatting, list recipes only', action='store_true')
  455. parser_show_recipes.add_argument('-m', '--multiple', help='only list where multiple recipes (in the same layer or different layers) exist for the same recipe name', action='store_true')
  456. parser_show_recipes.add_argument('-i', '--inherits', help='only list recipes that inherit the named class(es) - separate multiple classes using , (without spaces)', metavar='CLASS', default='')
  457. parser_show_recipes.add_argument('-l', '--layer', help='only list recipes from the selected layer', default='')
  458. parser_show_recipes.add_argument('-b', '--bare', help='output just names without the "(skipped)" marker', action='store_true')
  459. parser_show_recipes.add_argument('--mc', help='use specified multiconfig', default='')
  460. parser_show_recipes.add_argument('pnspec', nargs='*', help='optional recipe name specification (wildcards allowed, enclose in quotes to avoid shell expansion)')
  461. parser_show_appends = self.add_command(sp, 'show-appends', self.do_show_appends)
  462. parser_show_appends.add_argument('pnspec', nargs='*', help='optional recipe name specification (wildcards allowed, enclose in quotes to avoid shell expansion)')
  463. parser_show_appends.add_argument('--mc', help='use specified multiconfig', default='')
  464. parser_show_cross_depends = self.add_command(sp, 'show-cross-depends', self.do_show_cross_depends)
  465. parser_show_cross_depends.add_argument('-f', '--filenames', help='show full file path', action='store_true')
  466. parser_show_cross_depends.add_argument('-i', '--ignore', help='ignore dependencies on items in the specified layer(s) (split multiple layer names with commas, no spaces)', metavar='LAYERNAME')