license.bbclass 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. # Populates LICENSE_DIRECTORY as set in distro config with the license files as set by
  2. # LIC_FILES_CHKSUM.
  3. # TODO:
  4. # - There is a real issue revolving around license naming standards.
  5. LICENSE_DIRECTORY ??= "${DEPLOY_DIR}/licenses"
  6. LICSSTATEDIR = "${WORKDIR}/license-destdir/"
  7. # Create extra package with license texts and add it to RRECOMMENDS_${PN}
  8. LICENSE_CREATE_PACKAGE[type] = "boolean"
  9. LICENSE_CREATE_PACKAGE ??= "0"
  10. LICENSE_PACKAGE_SUFFIX ??= "-lic"
  11. LICENSE_FILES_DIRECTORY ??= "${datadir}/licenses/"
  12. addtask populate_lic after do_patch before do_build
  13. do_populate_lic[dirs] = "${LICSSTATEDIR}/${PN}"
  14. do_populate_lic[cleandirs] = "${LICSSTATEDIR}"
  15. python write_package_manifest() {
  16. # Get list of installed packages
  17. license_image_dir = d.expand('${LICENSE_DIRECTORY}/${IMAGE_NAME}')
  18. bb.utils.mkdirhier(license_image_dir)
  19. from oe.rootfs import image_list_installed_packages
  20. open(os.path.join(license_image_dir, 'package.manifest'),
  21. 'w+').write(image_list_installed_packages(d))
  22. }
  23. python write_deploy_manifest() {
  24. license_deployed_manifest(d)
  25. }
  26. python license_create_manifest() {
  27. import oe.packagedata
  28. from oe.rootfs import image_list_installed_packages
  29. build_images_from_feeds = d.getVar('BUILD_IMAGES_FROM_FEEDS', True)
  30. if build_images_from_feeds == "1":
  31. return 0
  32. pkg_dic = {}
  33. for pkg in image_list_installed_packages(d).splitlines():
  34. pkg_info = os.path.join(d.getVar('PKGDATA_DIR', True),
  35. 'runtime-reverse', pkg)
  36. pkg_name = os.path.basename(os.readlink(pkg_info))
  37. pkg_dic[pkg_name] = oe.packagedata.read_pkgdatafile(pkg_info)
  38. if not "LICENSE" in pkg_dic[pkg_name].keys():
  39. pkg_lic_name = "LICENSE_" + pkg_name
  40. pkg_dic[pkg_name]["LICENSE"] = pkg_dic[pkg_name][pkg_lic_name]
  41. rootfs_license_manifest = os.path.join(d.getVar('LICENSE_DIRECTORY', True),
  42. d.getVar('IMAGE_NAME', True), 'license.manifest')
  43. write_license_files(d, rootfs_license_manifest, pkg_dic)
  44. }
  45. def write_license_files(d, license_manifest, pkg_dic):
  46. import re
  47. bad_licenses = (d.getVar("INCOMPATIBLE_LICENSE", True) or "").split()
  48. bad_licenses = map(lambda l: canonical_license(d, l), bad_licenses)
  49. bad_licenses = expand_wildcard_licenses(d, bad_licenses)
  50. with open(license_manifest, "w") as license_file:
  51. for pkg in sorted(pkg_dic):
  52. if bad_licenses:
  53. try:
  54. (pkg_dic[pkg]["LICENSE"], pkg_dic[pkg]["LICENSES"]) = \
  55. oe.license.manifest_licenses(pkg_dic[pkg]["LICENSE"],
  56. bad_licenses, canonical_license, d)
  57. except oe.license.LicenseError as exc:
  58. bb.fatal('%s: %s' % (d.getVar('P', True), exc))
  59. else:
  60. pkg_dic[pkg]["LICENSES"] = re.sub('[|&()*]', '', pkg_dic[pkg]["LICENSE"])
  61. pkg_dic[pkg]["LICENSES"] = re.sub(' *', ' ', pkg_dic[pkg]["LICENSES"])
  62. pkg_dic[pkg]["LICENSES"] = pkg_dic[pkg]["LICENSES"].split()
  63. if not "IMAGE_MANIFEST" in pkg_dic[pkg]:
  64. # Rootfs manifest
  65. license_file.write("PACKAGE NAME: %s\n" % pkg)
  66. license_file.write("PACKAGE VERSION: %s\n" % pkg_dic[pkg]["PV"])
  67. license_file.write("RECIPE NAME: %s\n" % pkg_dic[pkg]["PN"])
  68. license_file.write("LICENSE: %s\n\n" % pkg_dic[pkg]["LICENSE"])
  69. # If the package doesn't contain any file, that is, its size is 0, the license
  70. # isn't relevant as far as the final image is concerned. So doing license check
  71. # doesn't make much sense, skip it.
  72. if pkg_dic[pkg]["PKGSIZE_%s" % pkg] == "0":
  73. continue
  74. else:
  75. # Image manifest
  76. license_file.write("RECIPE NAME: %s\n" % pkg_dic[pkg]["PN"])
  77. license_file.write("VERSION: %s\n" % pkg_dic[pkg]["PV"])
  78. license_file.write("LICENSE: %s\n" % pkg_dic[pkg]["LICENSE"])
  79. license_file.write("FILES: %s\n\n" % pkg_dic[pkg]["FILES"])
  80. for lic in pkg_dic[pkg]["LICENSES"]:
  81. lic_file = os.path.join(d.getVar('LICENSE_DIRECTORY', True),
  82. pkg_dic[pkg]["PN"], "generic_%s" %
  83. re.sub('\+', '', lic))
  84. # add explicity avoid of CLOSED license because isn't generic
  85. if lic == "CLOSED":
  86. continue
  87. if not os.path.exists(lic_file):
  88. bb.warn("The license listed %s was not in the "\
  89. "licenses collected for recipe %s"
  90. % (lic, pkg_dic[pkg]["PN"]))
  91. # Two options here:
  92. # - Just copy the manifest
  93. # - Copy the manifest and the license directories
  94. # With both options set we see a .5 M increase in core-image-minimal
  95. copy_lic_manifest = d.getVar('COPY_LIC_MANIFEST', True)
  96. copy_lic_dirs = d.getVar('COPY_LIC_DIRS', True)
  97. if copy_lic_manifest == "1":
  98. rootfs_license_dir = os.path.join(d.getVar('IMAGE_ROOTFS', 'True'),
  99. 'usr', 'share', 'common-licenses')
  100. bb.utils.mkdirhier(rootfs_license_dir)
  101. rootfs_license_manifest = os.path.join(rootfs_license_dir,
  102. os.path.split(license_manifest)[1])
  103. if not os.path.exists(rootfs_license_manifest):
  104. os.link(license_manifest, rootfs_license_manifest)
  105. if copy_lic_dirs == "1":
  106. for pkg in sorted(pkg_dic):
  107. pkg_rootfs_license_dir = os.path.join(rootfs_license_dir, pkg)
  108. bb.utils.mkdirhier(pkg_rootfs_license_dir)
  109. pkg_license_dir = os.path.join(d.getVar('LICENSE_DIRECTORY', True),
  110. pkg_dic[pkg]["PN"])
  111. licenses = os.listdir(pkg_license_dir)
  112. for lic in licenses:
  113. rootfs_license = os.path.join(rootfs_license_dir, lic)
  114. pkg_license = os.path.join(pkg_license_dir, lic)
  115. pkg_rootfs_license = os.path.join(pkg_rootfs_license_dir, lic)
  116. if re.match("^generic_.*$", lic):
  117. generic_lic = re.search("^generic_(.*)$", lic).group(1)
  118. if oe.license.license_ok(canonical_license(d,
  119. generic_lic), bad_licenses) == False:
  120. continue
  121. if not os.path.exists(rootfs_license):
  122. os.link(pkg_license, rootfs_license)
  123. if not os.path.exists(pkg_rootfs_license):
  124. os.symlink(os.path.join('..', lic), pkg_rootfs_license)
  125. else:
  126. if (oe.license.license_ok(canonical_license(d,
  127. lic), bad_licenses) == False or
  128. os.path.exists(pkg_rootfs_license)):
  129. continue
  130. os.link(pkg_license, pkg_rootfs_license)
  131. def license_deployed_manifest(d):
  132. """
  133. Write the license manifest for the deployed recipes.
  134. The deployed recipes usually includes the bootloader
  135. and extra files to boot the target.
  136. """
  137. dep_dic = {}
  138. man_dic = {}
  139. lic_dir = d.getVar("LICENSE_DIRECTORY", True)
  140. dep_dic = get_deployed_dependencies(d)
  141. for dep in dep_dic.keys():
  142. man_dic[dep] = {}
  143. # It is necessary to mark this will be used for image manifest
  144. man_dic[dep]["IMAGE_MANIFEST"] = True
  145. man_dic[dep]["PN"] = dep
  146. man_dic[dep]["FILES"] = \
  147. " ".join(get_deployed_files(dep_dic[dep]))
  148. with open(os.path.join(lic_dir, dep, "recipeinfo"), "r") as f:
  149. for line in f.readlines():
  150. key,val = line.split(": ", 1)
  151. man_dic[dep][key] = val[:-1]
  152. image_license_manifest = os.path.join(d.getVar('LICENSE_DIRECTORY', True),
  153. d.getVar('IMAGE_NAME', True), 'image_license.manifest')
  154. write_license_files(d, image_license_manifest, man_dic)
  155. def get_deployed_dependencies(d):
  156. """
  157. Get all the deployed dependencies of an image
  158. """
  159. deploy = {}
  160. # Get all the dependencies for the current task (rootfs).
  161. # Also get EXTRA_IMAGEDEPENDS because the bootloader is
  162. # usually in this var and not listed in rootfs.
  163. # At last, get the dependencies from boot classes because
  164. # it might contain the bootloader.
  165. taskdata = d.getVar("BB_TASKDEPDATA", False)
  166. depends = list(set([dep[0] for dep
  167. in taskdata.itervalues()
  168. if not dep[0].endswith("-native")]))
  169. extra_depends = d.getVar("EXTRA_IMAGEDEPENDS", True)
  170. boot_depends = get_boot_dependencies(d)
  171. depends.extend(extra_depends.split())
  172. depends.extend(boot_depends)
  173. depends = list(set(depends))
  174. # To verify what was deployed it checks the rootfs dependencies against
  175. # the SSTATE_MANIFESTS for "deploy" task.
  176. # The manifest file name contains the arch. Because we are not running
  177. # in the recipe context it is necessary to check every arch used.
  178. sstate_manifest_dir = d.getVar("SSTATE_MANIFESTS", True)
  179. sstate_archs = d.getVar("SSTATE_ARCHS", True)
  180. extra_archs = d.getVar("PACKAGE_EXTRA_ARCHS", True)
  181. archs = list(set(("%s %s" % (sstate_archs, extra_archs)).split()))
  182. for dep in depends:
  183. # Some recipes have an arch on their own, so we try that first.
  184. special_arch = d.getVar("PACKAGE_ARCH_pn-%s" % dep, True)
  185. if special_arch:
  186. sstate_manifest_file = os.path.join(sstate_manifest_dir,
  187. "manifest-%s-%s.deploy" % (special_arch, dep))
  188. if os.path.exists(sstate_manifest_file):
  189. deploy[dep] = sstate_manifest_file
  190. continue
  191. for arch in archs:
  192. sstate_manifest_file = os.path.join(sstate_manifest_dir,
  193. "manifest-%s-%s.deploy" % (arch, dep))
  194. if os.path.exists(sstate_manifest_file):
  195. deploy[dep] = sstate_manifest_file
  196. break
  197. return deploy
  198. get_deployed_dependencies[vardepsexclude] = "BB_TASKDEPDATA"
  199. def get_boot_dependencies(d):
  200. """
  201. Return the dependencies from boot tasks
  202. """
  203. depends = []
  204. boot_depends_string = ""
  205. taskdepdata = d.getVar("BB_TASKDEPDATA", False)
  206. # Only bootimg and bootdirectdisk include the depends flag
  207. boot_tasks = ["do_bootimg", "do_bootdirectdisk",]
  208. for task in boot_tasks:
  209. boot_depends_string = "%s %s" % (boot_depends_string,
  210. d.getVarFlag(task, "depends", True) or "")
  211. boot_depends = [dep.split(":")[0] for dep
  212. in boot_depends_string.split()
  213. if not dep.split(":")[0].endswith("-native")]
  214. for dep in boot_depends:
  215. info_file = os.path.join(d.getVar("LICENSE_DIRECTORY", True),
  216. dep, "recipeinfo")
  217. # If the recipe and dependency name is the same
  218. if os.path.exists(info_file):
  219. depends.append(dep)
  220. # We need to search for the provider of the dependency
  221. else:
  222. for taskdep in taskdepdata.itervalues():
  223. # The fifth field contains what the task provides
  224. if dep in taskdep[4]:
  225. info_file = os.path.join(
  226. d.getVar("LICENSE_DIRECTORY", True),
  227. taskdep[0], "recipeinfo")
  228. if os.path.exists(info_file):
  229. depends.append(taskdep[0])
  230. break
  231. return depends
  232. get_boot_dependencies[vardepsexclude] = "BB_TASKDEPDATA"
  233. def get_deployed_files(man_file):
  234. """
  235. Get the files deployed from the sstate manifest
  236. """
  237. dep_files = []
  238. excluded_files = ["README_-_DO_NOT_DELETE_FILES_IN_THIS_DIRECTORY.txt"]
  239. with open(man_file, "r") as manifest:
  240. all_files = manifest.read()
  241. for f in all_files.splitlines():
  242. if ((not (os.path.islink(f) or os.path.isdir(f))) and
  243. not os.path.basename(f) in excluded_files):
  244. dep_files.append(os.path.basename(f))
  245. return dep_files
  246. python do_populate_lic() {
  247. """
  248. Populate LICENSE_DIRECTORY with licenses.
  249. """
  250. lic_files_paths = find_license_files(d)
  251. # The base directory we wrangle licenses to
  252. destdir = os.path.join(d.getVar('LICSSTATEDIR', True), d.getVar('PN', True))
  253. copy_license_files(lic_files_paths, destdir)
  254. info = get_recipe_info(d)
  255. with open(os.path.join(destdir, "recipeinfo"), "w") as f:
  256. for key in sorted(info.keys()):
  257. f.write("%s: %s\n" % (key, info[key]))
  258. }
  259. # it would be better to copy them in do_install_append, but find_license_filesa is python
  260. python perform_packagecopy_prepend () {
  261. enabled = oe.data.typed_value('LICENSE_CREATE_PACKAGE', d)
  262. if d.getVar('CLASSOVERRIDE', True) == 'class-target' and enabled:
  263. lic_files_paths = find_license_files(d)
  264. # LICENSE_FILES_DIRECTORY starts with '/' so os.path.join cannot be used to join D and LICENSE_FILES_DIRECTORY
  265. destdir = d.getVar('D', True) + os.path.join(d.getVar('LICENSE_FILES_DIRECTORY', True), d.getVar('PN', True))
  266. copy_license_files(lic_files_paths, destdir)
  267. add_package_and_files(d)
  268. }
  269. def get_recipe_info(d):
  270. info = {}
  271. info["PV"] = d.getVar("PV", True)
  272. info["PR"] = d.getVar("PR", True)
  273. info["LICENSE"] = d.getVar("LICENSE", True)
  274. return info
  275. def add_package_and_files(d):
  276. packages = d.getVar('PACKAGES', True)
  277. files = d.getVar('LICENSE_FILES_DIRECTORY', True)
  278. pn = d.getVar('PN', True)
  279. pn_lic = "%s%s" % (pn, d.getVar('LICENSE_PACKAGE_SUFFIX', False))
  280. if pn_lic in packages:
  281. bb.warn("%s package already existed in %s." % (pn_lic, pn))
  282. else:
  283. # first in PACKAGES to be sure that nothing else gets LICENSE_FILES_DIRECTORY
  284. d.setVar('PACKAGES', "%s %s" % (pn_lic, packages))
  285. d.setVar('FILES_' + pn_lic, files)
  286. rrecommends_pn = d.getVar('RRECOMMENDS_' + pn, True)
  287. if rrecommends_pn:
  288. d.setVar('RRECOMMENDS_' + pn, "%s %s" % (pn_lic, rrecommends_pn))
  289. else:
  290. d.setVar('RRECOMMENDS_' + pn, "%s" % (pn_lic))
  291. def copy_license_files(lic_files_paths, destdir):
  292. import shutil
  293. bb.utils.mkdirhier(destdir)
  294. for (basename, path) in lic_files_paths:
  295. try:
  296. src = path
  297. dst = os.path.join(destdir, basename)
  298. if os.path.exists(dst):
  299. os.remove(dst)
  300. if os.access(src, os.W_OK) and (os.stat(src).st_dev == os.stat(destdir).st_dev):
  301. os.link(src, dst)
  302. else:
  303. shutil.copyfile(src, dst)
  304. except Exception as e:
  305. bb.warn("Could not copy license file %s to %s: %s" % (src, dst, e))
  306. def find_license_files(d):
  307. """
  308. Creates list of files used in LIC_FILES_CHKSUM and generic LICENSE files.
  309. """
  310. import shutil
  311. import oe.license
  312. pn = d.getVar('PN', True)
  313. for package in d.getVar('PACKAGES', True):
  314. if d.getVar('LICENSE_' + package, True):
  315. license_types = license_types + ' & ' + \
  316. d.getVar('LICENSE_' + package, True)
  317. #If we get here with no license types, then that means we have a recipe
  318. #level license. If so, we grab only those.
  319. try:
  320. license_types
  321. except NameError:
  322. # All the license types at the recipe level
  323. license_types = d.getVar('LICENSE', True)
  324. # All the license files for the package
  325. lic_files = d.getVar('LIC_FILES_CHKSUM', True)
  326. pn = d.getVar('PN', True)
  327. # The license files are located in S/LIC_FILE_CHECKSUM.
  328. srcdir = d.getVar('S', True)
  329. # Directory we store the generic licenses as set in the distro configuration
  330. generic_directory = d.getVar('COMMON_LICENSE_DIR', True)
  331. # List of basename, path tuples
  332. lic_files_paths = []
  333. license_source_dirs = []
  334. license_source_dirs.append(generic_directory)
  335. try:
  336. additional_lic_dirs = d.getVar('LICENSE_PATH', True).split()
  337. for lic_dir in additional_lic_dirs:
  338. license_source_dirs.append(lic_dir)
  339. except:
  340. pass
  341. class FindVisitor(oe.license.LicenseVisitor):
  342. def visit_Str(self, node):
  343. #
  344. # Until I figure out what to do with
  345. # the two modifiers I support (or greater = +
  346. # and "with exceptions" being *
  347. # we'll just strip out the modifier and put
  348. # the base license.
  349. find_license(node.s.replace("+", "").replace("*", ""))
  350. self.generic_visit(node)
  351. def find_license(license_type):
  352. try:
  353. bb.utils.mkdirhier(gen_lic_dest)
  354. except:
  355. pass
  356. spdx_generic = None
  357. license_source = None
  358. # If the generic does not exist we need to check to see if there is an SPDX mapping to it,
  359. # unless NO_GENERIC_LICENSE is set.
  360. for lic_dir in license_source_dirs:
  361. if not os.path.isfile(os.path.join(lic_dir, license_type)):
  362. if d.getVarFlag('SPDXLICENSEMAP', license_type) != None:
  363. # Great, there is an SPDXLICENSEMAP. We can copy!
  364. bb.debug(1, "We need to use a SPDXLICENSEMAP for %s" % (license_type))
  365. spdx_generic = d.getVarFlag('SPDXLICENSEMAP', license_type)
  366. license_source = lic_dir
  367. break
  368. elif os.path.isfile(os.path.join(lic_dir, license_type)):
  369. spdx_generic = license_type
  370. license_source = lic_dir
  371. break
  372. if spdx_generic and license_source:
  373. # we really should copy to generic_ + spdx_generic, however, that ends up messing the manifest
  374. # audit up. This should be fixed in emit_pkgdata (or, we actually got and fix all the recipes)
  375. lic_files_paths.append(("generic_" + license_type, os.path.join(license_source, spdx_generic)))
  376. # The user may attempt to use NO_GENERIC_LICENSE for a generic license which doesn't make sense
  377. # and should not be allowed, warn the user in this case.
  378. if d.getVarFlag('NO_GENERIC_LICENSE', license_type):
  379. bb.warn("%s: %s is a generic license, please don't use NO_GENERIC_LICENSE for it." % (pn, license_type))
  380. elif d.getVarFlag('NO_GENERIC_LICENSE', license_type):
  381. # if NO_GENERIC_LICENSE is set, we copy the license files from the fetched source
  382. # of the package rather than the license_source_dirs.
  383. for (basename, path) in lic_files_paths:
  384. if d.getVarFlag('NO_GENERIC_LICENSE', license_type) == basename:
  385. lic_files_paths.append(("generic_" + license_type, path))
  386. break
  387. else:
  388. # Add explicity avoid of CLOSED license because this isn't generic
  389. if license_type != 'CLOSED':
  390. # And here is where we warn people that their licenses are lousy
  391. bb.warn("%s: No generic license file exists for: %s in any provider" % (pn, license_type))
  392. pass
  393. if not generic_directory:
  394. raise bb.build.FuncFailed("COMMON_LICENSE_DIR is unset. Please set this in your distro config")
  395. if not lic_files:
  396. # No recipe should have an invalid license file. This is checked else
  397. # where, but let's be pedantic
  398. bb.note(pn + ": Recipe file does not have license file information.")
  399. return lic_files_paths
  400. for url in lic_files.split():
  401. try:
  402. (type, host, path, user, pswd, parm) = bb.fetch.decodeurl(url)
  403. except bb.fetch.MalformedUrl:
  404. raise bb.build.FuncFailed("%s: LIC_FILES_CHKSUM contains an invalid URL: %s" % (d.getVar('PF', True), url))
  405. # We want the license filename and path
  406. srclicfile = os.path.join(srcdir, path)
  407. lic_files_paths.append((os.path.basename(path), srclicfile))
  408. v = FindVisitor()
  409. try:
  410. v.visit_string(license_types)
  411. except oe.license.InvalidLicense as exc:
  412. bb.fatal('%s: %s' % (d.getVar('PF', True), exc))
  413. except SyntaxError:
  414. bb.warn("%s: Failed to parse it's LICENSE field." % (d.getVar('PF', True)))
  415. return lic_files_paths
  416. def return_spdx(d, license):
  417. """
  418. This function returns the spdx mapping of a license if it exists.
  419. """
  420. return d.getVarFlag('SPDXLICENSEMAP', license, True)
  421. def canonical_license(d, license):
  422. """
  423. Return the canonical (SPDX) form of the license if available (so GPLv3
  424. becomes GPL-3.0), for the license named 'X+', return canonical form of
  425. 'X' if availabel and the tailing '+' (so GPLv3+ becomes GPL-3.0+),
  426. or the passed license if there is no canonical form.
  427. """
  428. lic = d.getVarFlag('SPDXLICENSEMAP', license, True) or ""
  429. if not lic and license.endswith('+'):
  430. lic = d.getVarFlag('SPDXLICENSEMAP', license.rstrip('+'), True)
  431. if lic:
  432. lic += '+'
  433. return lic or license
  434. def expand_wildcard_licenses(d, wildcard_licenses):
  435. """
  436. Return actual spdx format license names if wildcard used. We expand
  437. wildcards from SPDXLICENSEMAP flags and SRC_DISTRIBUTE_LICENSES values.
  438. """
  439. import fnmatch
  440. licenses = []
  441. spdxmapkeys = d.getVarFlags('SPDXLICENSEMAP').keys()
  442. for wld_lic in wildcard_licenses:
  443. spdxflags = fnmatch.filter(spdxmapkeys, wld_lic)
  444. licenses += [d.getVarFlag('SPDXLICENSEMAP', flag) for flag in spdxflags]
  445. spdx_lics = (d.getVar('SRC_DISTRIBUTE_LICENSES', False) or '').split()
  446. for wld_lic in wildcard_licenses:
  447. licenses += fnmatch.filter(spdx_lics, wld_lic)
  448. licenses = list(set(licenses))
  449. return licenses
  450. def incompatible_license_contains(license, truevalue, falsevalue, d):
  451. license = canonical_license(d, license)
  452. bad_licenses = (d.getVar('INCOMPATIBLE_LICENSE', True) or "").split()
  453. bad_licenses = expand_wildcard_licenses(d, bad_licenses)
  454. return truevalue if license in bad_licenses else falsevalue
  455. def incompatible_license(d, dont_want_licenses, package=None):
  456. """
  457. This function checks if a recipe has only incompatible licenses. It also
  458. take into consideration 'or' operand. dont_want_licenses should be passed
  459. as canonical (SPDX) names.
  460. """
  461. import oe.license
  462. license = d.getVar("LICENSE_%s" % package, True) if package else None
  463. if not license:
  464. license = d.getVar('LICENSE', True)
  465. # Handles an "or" or two license sets provided by
  466. # flattened_licenses(), pick one that works if possible.
  467. def choose_lic_set(a, b):
  468. return a if all(oe.license.license_ok(canonical_license(d, lic),
  469. dont_want_licenses) for lic in a) else b
  470. try:
  471. licenses = oe.license.flattened_licenses(license, choose_lic_set)
  472. except oe.license.LicenseError as exc:
  473. bb.fatal('%s: %s' % (d.getVar('P', True), exc))
  474. return any(not oe.license.license_ok(canonical_license(d, l), \
  475. dont_want_licenses) for l in licenses)
  476. def check_license_flags(d):
  477. """
  478. This function checks if a recipe has any LICENSE_FLAGS that
  479. aren't whitelisted.
  480. If it does, it returns the first LICENSE_FLAGS item missing from the
  481. whitelist, or all of the LICENSE_FLAGS if there is no whitelist.
  482. If everything is is properly whitelisted, it returns None.
  483. """
  484. def license_flag_matches(flag, whitelist, pn):
  485. """
  486. Return True if flag matches something in whitelist, None if not.
  487. Before we test a flag against the whitelist, we append _${PN}
  488. to it. We then try to match that string against the
  489. whitelist. This covers the normal case, where we expect
  490. LICENSE_FLAGS to be a simple string like 'commercial', which
  491. the user typically matches exactly in the whitelist by
  492. explicitly appending the package name e.g 'commercial_foo'.
  493. If we fail the match however, we then split the flag across
  494. '_' and append each fragment and test until we either match or
  495. run out of fragments.
  496. """
  497. flag_pn = ("%s_%s" % (flag, pn))
  498. for candidate in whitelist:
  499. if flag_pn == candidate:
  500. return True
  501. flag_cur = ""
  502. flagments = flag_pn.split("_")
  503. flagments.pop() # we've already tested the full string
  504. for flagment in flagments:
  505. if flag_cur:
  506. flag_cur += "_"
  507. flag_cur += flagment
  508. for candidate in whitelist:
  509. if flag_cur == candidate:
  510. return True
  511. return False
  512. def all_license_flags_match(license_flags, whitelist):
  513. """ Return first unmatched flag, None if all flags match """
  514. pn = d.getVar('PN', True)
  515. split_whitelist = whitelist.split()
  516. for flag in license_flags.split():
  517. if not license_flag_matches(flag, split_whitelist, pn):
  518. return flag
  519. return None
  520. license_flags = d.getVar('LICENSE_FLAGS', True)
  521. if license_flags:
  522. whitelist = d.getVar('LICENSE_FLAGS_WHITELIST', True)
  523. if not whitelist:
  524. return license_flags
  525. unmatched_flag = all_license_flags_match(license_flags, whitelist)
  526. if unmatched_flag:
  527. return unmatched_flag
  528. return None
  529. def check_license_format(d):
  530. """
  531. This function checks if LICENSE is well defined,
  532. Validate operators in LICENSES.
  533. No spaces are allowed between LICENSES.
  534. """
  535. pn = d.getVar('PN', True)
  536. licenses = d.getVar('LICENSE', True)
  537. from oe.license import license_operator, license_operator_chars, license_pattern
  538. elements = filter(lambda x: x.strip(), license_operator.split(licenses))
  539. for pos, element in enumerate(elements):
  540. if license_pattern.match(element):
  541. if pos > 0 and license_pattern.match(elements[pos - 1]):
  542. bb.warn('%s: LICENSE value "%s" has an invalid format - license names ' \
  543. 'must be separated by the following characters to indicate ' \
  544. 'the license selection: %s' %
  545. (pn, licenses, license_operator_chars))
  546. elif not license_operator.match(element):
  547. bb.warn('%s: LICENSE value "%s" has an invalid separator "%s" that is not ' \
  548. 'in the valid list of separators (%s)' %
  549. (pn, licenses, element, license_operator_chars))
  550. SSTATETASKS += "do_populate_lic"
  551. do_populate_lic[sstate-inputdirs] = "${LICSSTATEDIR}"
  552. do_populate_lic[sstate-outputdirs] = "${LICENSE_DIRECTORY}/"
  553. ROOTFS_POSTPROCESS_COMMAND_prepend = "write_package_manifest; write_deploy_manifest; license_create_manifest; "
  554. do_rootfs[recrdeptask] += "do_populate_lic"
  555. do_populate_lic_setscene[dirs] = "${LICSSTATEDIR}/${PN}"
  556. do_populate_lic_setscene[cleandirs] = "${LICSSTATEDIR}"
  557. python do_populate_lic_setscene () {
  558. sstate_setscene(d)
  559. }
  560. addtask do_populate_lic_setscene