query.py 23 KB

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