insane.bbclass 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371
  1. # BB Class inspired by ebuild.sh
  2. #
  3. # This class will test files after installation for certain
  4. # security issues and other kind of issues.
  5. #
  6. # Checks we do:
  7. # -Check the ownership and permissions
  8. # -Check the RUNTIME path for the $TMPDIR
  9. # -Check if .la files wrongly point to workdir
  10. # -Check if .pc files wrongly point to workdir
  11. # -Check if packages contains .debug directories or .so files
  12. # where they should be in -dev or -dbg
  13. # -Check if config.log contains traces to broken autoconf tests
  14. # -Check invalid characters (non-utf8) on some package metadata
  15. # -Ensure that binaries in base_[bindir|sbindir|libdir] do not link
  16. # into exec_prefix
  17. # -Check that scripts in base_[bindir|sbindir|libdir] do not reference
  18. # files under exec_prefix
  19. # -Check if the package name is upper case
  20. QA_SANE = "True"
  21. # Elect whether a given type of error is a warning or error, they may
  22. # have been set by other files.
  23. WARN_QA ?= " libdir xorg-driver-abi \
  24. textrel incompatible-license files-invalid \
  25. infodir build-deps src-uri-bad symlink-to-sysroot multilib \
  26. invalid-packageconfig host-user-contaminated uppercase-pn patch-fuzz \
  27. mime mime-xdg unlisted-pkg-lics unhandled-features-check \
  28. missing-update-alternatives \
  29. "
  30. ERROR_QA ?= "dev-so debug-deps dev-deps debug-files arch pkgconfig la \
  31. perms dep-cmp pkgvarcheck perm-config perm-line perm-link \
  32. split-strip packages-list pkgv-undefined var-undefined \
  33. version-going-backwards expanded-d invalid-chars \
  34. license-checksum dev-elf file-rdeps configure-unsafe \
  35. configure-gettext perllocalpod shebang-size \
  36. already-stripped ldflags compile-host-path \
  37. install-host-path pn-overrides unknown-configure-option \
  38. useless-rpaths rpaths staticdev \
  39. "
  40. # Add usrmerge QA check based on distro feature
  41. ERROR_QA_append = "${@bb.utils.contains('DISTRO_FEATURES', 'usrmerge', ' usrmerge', '', d)}"
  42. FAKEROOT_QA = "host-user-contaminated"
  43. FAKEROOT_QA[doc] = "QA tests which need to run under fakeroot. If any \
  44. enabled tests are listed here, the do_package_qa task will run under fakeroot."
  45. ALL_QA = "${WARN_QA} ${ERROR_QA}"
  46. UNKNOWN_CONFIGURE_WHITELIST ?= "--enable-nls --disable-nls --disable-silent-rules --disable-dependency-tracking --with-libtool-sysroot --disable-static"
  47. def package_qa_clean_path(path, d, pkg=None):
  48. """
  49. Remove redundant paths from the path for display. If pkg isn't set then
  50. TMPDIR is stripped, otherwise PKGDEST/pkg is stripped.
  51. """
  52. if pkg:
  53. path = path.replace(os.path.join(d.getVar("PKGDEST"), pkg), "/")
  54. return path.replace(d.getVar("TMPDIR"), "/").replace("//", "/")
  55. def package_qa_write_error(type, error, d):
  56. logfile = d.getVar('QA_LOGFILE')
  57. if logfile:
  58. p = d.getVar('P')
  59. with open(logfile, "a+") as f:
  60. f.write("%s: %s [%s]\n" % (p, error, type))
  61. def package_qa_handle_error(error_class, error_msg, d):
  62. if error_class in (d.getVar("ERROR_QA") or "").split():
  63. package_qa_write_error(error_class, error_msg, d)
  64. bb.error("QA Issue: %s [%s]" % (error_msg, error_class))
  65. d.setVar("QA_SANE", False)
  66. return False
  67. elif error_class in (d.getVar("WARN_QA") or "").split():
  68. package_qa_write_error(error_class, error_msg, d)
  69. bb.warn("QA Issue: %s [%s]" % (error_msg, error_class))
  70. else:
  71. bb.note("QA Issue: %s [%s]" % (error_msg, error_class))
  72. return True
  73. def package_qa_add_message(messages, section, new_msg):
  74. if section not in messages:
  75. messages[section] = new_msg
  76. else:
  77. messages[section] = messages[section] + "\n" + new_msg
  78. QAPATHTEST[shebang-size] = "package_qa_check_shebang_size"
  79. def package_qa_check_shebang_size(path, name, d, elf, messages):
  80. if os.path.islink(path) or elf:
  81. return
  82. try:
  83. with open(path, 'rb') as f:
  84. stanza = f.readline(130)
  85. except IOError:
  86. return
  87. if stanza.startswith(b'#!'):
  88. #Shebang not found
  89. try:
  90. stanza = stanza.decode("utf-8")
  91. except UnicodeDecodeError:
  92. #If it is not a text file, it is not a script
  93. return
  94. if len(stanza) > 129:
  95. package_qa_add_message(messages, "shebang-size", "%s: %s maximum shebang size exceeded, the maximum size is 128." % (name, package_qa_clean_path(path, d)))
  96. return
  97. QAPATHTEST[libexec] = "package_qa_check_libexec"
  98. def package_qa_check_libexec(path,name, d, elf, messages):
  99. # Skip the case where the default is explicitly /usr/libexec
  100. libexec = d.getVar('libexecdir')
  101. if libexec == "/usr/libexec":
  102. return True
  103. if 'libexec' in path.split(os.path.sep):
  104. package_qa_add_message(messages, "libexec", "%s: %s is using libexec please relocate to %s" % (name, package_qa_clean_path(path, d), libexec))
  105. return False
  106. return True
  107. QAPATHTEST[rpaths] = "package_qa_check_rpath"
  108. def package_qa_check_rpath(file,name, d, elf, messages):
  109. """
  110. Check for dangerous RPATHs
  111. """
  112. if not elf:
  113. return
  114. if os.path.islink(file):
  115. return
  116. bad_dirs = [d.getVar('BASE_WORKDIR'), d.getVar('STAGING_DIR_TARGET')]
  117. phdrs = elf.run_objdump("-p", d)
  118. import re
  119. rpath_re = re.compile(r"\s+RPATH\s+(.*)")
  120. for line in phdrs.split("\n"):
  121. m = rpath_re.match(line)
  122. if m:
  123. rpath = m.group(1)
  124. for dir in bad_dirs:
  125. if dir in rpath:
  126. package_qa_add_message(messages, "rpaths", "package %s contains bad RPATH %s in file %s" % (name, rpath, file))
  127. QAPATHTEST[useless-rpaths] = "package_qa_check_useless_rpaths"
  128. def package_qa_check_useless_rpaths(file, name, d, elf, messages):
  129. """
  130. Check for RPATHs that are useless but not dangerous
  131. """
  132. def rpath_eq(a, b):
  133. return os.path.normpath(a) == os.path.normpath(b)
  134. if not elf:
  135. return
  136. if os.path.islink(file):
  137. return
  138. libdir = d.getVar("libdir")
  139. base_libdir = d.getVar("base_libdir")
  140. phdrs = elf.run_objdump("-p", d)
  141. import re
  142. rpath_re = re.compile(r"\s+RPATH\s+(.*)")
  143. for line in phdrs.split("\n"):
  144. m = rpath_re.match(line)
  145. if m:
  146. rpath = m.group(1)
  147. if rpath_eq(rpath, libdir) or rpath_eq(rpath, base_libdir):
  148. # The dynamic linker searches both these places anyway. There is no point in
  149. # looking there again.
  150. package_qa_add_message(messages, "useless-rpaths", "%s: %s contains probably-redundant RPATH %s" % (name, package_qa_clean_path(file, d), rpath))
  151. QAPATHTEST[dev-so] = "package_qa_check_dev"
  152. def package_qa_check_dev(path, name, d, elf, messages):
  153. """
  154. Check for ".so" library symlinks in non-dev packages
  155. """
  156. if not name.endswith("-dev") and not name.endswith("-dbg") and not name.endswith("-ptest") and not name.startswith("nativesdk-") and path.endswith(".so") and os.path.islink(path):
  157. package_qa_add_message(messages, "dev-so", "non -dev/-dbg/nativesdk- package contains symlink .so: %s path '%s'" % \
  158. (name, package_qa_clean_path(path,d)))
  159. QAPATHTEST[dev-elf] = "package_qa_check_dev_elf"
  160. def package_qa_check_dev_elf(path, name, d, elf, messages):
  161. """
  162. Check that -dev doesn't contain real shared libraries. The test has to
  163. check that the file is not a link and is an ELF object as some recipes
  164. install link-time .so files that are linker scripts.
  165. """
  166. if name.endswith("-dev") and path.endswith(".so") and not os.path.islink(path) and elf:
  167. package_qa_add_message(messages, "dev-elf", "-dev package contains non-symlink .so: %s path '%s'" % \
  168. (name, package_qa_clean_path(path,d)))
  169. QAPATHTEST[staticdev] = "package_qa_check_staticdev"
  170. def package_qa_check_staticdev(path, name, d, elf, messages):
  171. """
  172. Check for ".a" library in non-staticdev packages
  173. There are a number of exceptions to this rule, -pic packages can contain
  174. static libraries, the _nonshared.a belong with their -dev packages and
  175. libgcc.a, libgcov.a will be skipped in their packages
  176. """
  177. if not name.endswith("-pic") and not name.endswith("-staticdev") and not name.endswith("-ptest") and path.endswith(".a") and not path.endswith("_nonshared.a") and not '/usr/lib/debug-static/' in path and not '/.debug-static/' in path:
  178. package_qa_add_message(messages, "staticdev", "non -staticdev package contains static .a library: %s path '%s'" % \
  179. (name, package_qa_clean_path(path,d)))
  180. QAPATHTEST[mime] = "package_qa_check_mime"
  181. def package_qa_check_mime(path, name, d, elf, messages):
  182. """
  183. Check if package installs mime types to /usr/share/mime/packages
  184. while no inheriting mime.bbclass
  185. """
  186. if d.getVar("datadir") + "/mime/packages" in path and path.endswith('.xml') and not bb.data.inherits_class("mime", d):
  187. package_qa_add_message(messages, "mime", "package contains mime types but does not inherit mime: %s path '%s'" % \
  188. (name, package_qa_clean_path(path,d)))
  189. QAPATHTEST[mime-xdg] = "package_qa_check_mime_xdg"
  190. def package_qa_check_mime_xdg(path, name, d, elf, messages):
  191. """
  192. Check if package installs desktop file containing MimeType and requires
  193. mime-types.bbclass to create /usr/share/applications/mimeinfo.cache
  194. """
  195. if d.getVar("datadir") + "/applications" in path and path.endswith('.desktop') and not bb.data.inherits_class("mime-xdg", d):
  196. mime_type_found = False
  197. try:
  198. with open(path, 'r') as f:
  199. for line in f.read().split('\n'):
  200. if 'MimeType' in line:
  201. mime_type_found = True
  202. break;
  203. except:
  204. # At least libreoffice installs symlinks with absolute paths that are dangling here.
  205. # We could implement some magic but for few (one) recipes it is not worth the effort so just warn:
  206. wstr = "%s cannot open %s - is it a symlink with absolute path?\n" % (name, package_qa_clean_path(path,d))
  207. wstr += "Please check if (linked) file contains key 'MimeType'.\n"
  208. pkgname = name
  209. if name == d.getVar('PN'):
  210. pkgname = '${PN}'
  211. wstr += "If yes: add \'inhert mime-xdg\' and \'MIME_XDG_PACKAGES += \"%s\"\' / if no add \'INSANE_SKIP_%s += \"mime-xdg\"\' to recipe." % (pkgname, pkgname)
  212. package_qa_add_message(messages, "mime-xdg", wstr)
  213. if mime_type_found:
  214. package_qa_add_message(messages, "mime-xdg", "package contains desktop file with key 'MimeType' but does not inhert mime-xdg: %s path '%s'" % \
  215. (name, package_qa_clean_path(path,d)))
  216. def package_qa_check_libdir(d):
  217. """
  218. Check for wrong library installation paths. For instance, catch
  219. recipes installing /lib/bar.so when ${base_libdir}="lib32" or
  220. installing in /usr/lib64 when ${libdir}="/usr/lib"
  221. """
  222. import re
  223. pkgdest = d.getVar('PKGDEST')
  224. base_libdir = d.getVar("base_libdir") + os.sep
  225. libdir = d.getVar("libdir") + os.sep
  226. libexecdir = d.getVar("libexecdir") + os.sep
  227. exec_prefix = d.getVar("exec_prefix") + os.sep
  228. messages = []
  229. # The re's are purposely fuzzy, as some there are some .so.x.y.z files
  230. # that don't follow the standard naming convention. It checks later
  231. # that they are actual ELF files
  232. lib_re = re.compile(r"^/lib.+\.so(\..+)?$")
  233. exec_re = re.compile(r"^%s.*/lib.+\.so(\..+)?$" % exec_prefix)
  234. for root, dirs, files in os.walk(pkgdest):
  235. if root == pkgdest:
  236. # Skip subdirectories for any packages with libdir in INSANE_SKIP
  237. skippackages = []
  238. for package in dirs:
  239. if 'libdir' in (d.getVar('INSANE_SKIP_' + package) or "").split():
  240. bb.note("Package %s skipping libdir QA test" % (package))
  241. skippackages.append(package)
  242. elif d.getVar('PACKAGE_DEBUG_SPLIT_STYLE') == 'debug-file-directory' and package.endswith("-dbg"):
  243. bb.note("Package %s skipping libdir QA test for PACKAGE_DEBUG_SPLIT_STYLE equals debug-file-directory" % (package))
  244. skippackages.append(package)
  245. for package in skippackages:
  246. dirs.remove(package)
  247. for file in files:
  248. full_path = os.path.join(root, file)
  249. rel_path = os.path.relpath(full_path, pkgdest)
  250. if os.sep in rel_path:
  251. package, rel_path = rel_path.split(os.sep, 1)
  252. rel_path = os.sep + rel_path
  253. if lib_re.match(rel_path):
  254. if base_libdir not in rel_path:
  255. # make sure it's an actual ELF file
  256. elf = oe.qa.ELFFile(full_path)
  257. try:
  258. elf.open()
  259. messages.append("%s: found library in wrong location: %s" % (package, rel_path))
  260. except (oe.qa.NotELFFileError):
  261. pass
  262. if exec_re.match(rel_path):
  263. if libdir not in rel_path and libexecdir not in rel_path:
  264. # make sure it's an actual ELF file
  265. elf = oe.qa.ELFFile(full_path)
  266. try:
  267. elf.open()
  268. messages.append("%s: found library in wrong location: %s" % (package, rel_path))
  269. except (oe.qa.NotELFFileError):
  270. pass
  271. if messages:
  272. package_qa_handle_error("libdir", "\n".join(messages), d)
  273. QAPATHTEST[debug-files] = "package_qa_check_dbg"
  274. def package_qa_check_dbg(path, name, d, elf, messages):
  275. """
  276. Check for ".debug" files or directories outside of the dbg package
  277. """
  278. if not "-dbg" in name and not "-ptest" in name:
  279. if '.debug' in path.split(os.path.sep):
  280. package_qa_add_message(messages, "debug-files", "non debug package contains .debug directory: %s path %s" % \
  281. (name, package_qa_clean_path(path,d)))
  282. QAPATHTEST[arch] = "package_qa_check_arch"
  283. def package_qa_check_arch(path,name,d, elf, messages):
  284. """
  285. Check if archs are compatible
  286. """
  287. import re, oe.elf
  288. if not elf:
  289. return
  290. target_os = d.getVar('TARGET_OS')
  291. target_arch = d.getVar('TARGET_ARCH')
  292. provides = d.getVar('PROVIDES')
  293. bpn = d.getVar('BPN')
  294. if target_arch == "allarch":
  295. pn = d.getVar('PN')
  296. package_qa_add_message(messages, "arch", pn + ": Recipe inherits the allarch class, but has packaged architecture-specific binaries")
  297. return
  298. # FIXME: Cross package confuse this check, so just skip them
  299. for s in ['cross', 'nativesdk', 'cross-canadian']:
  300. if bb.data.inherits_class(s, d):
  301. return
  302. # avoid following links to /usr/bin (e.g. on udev builds)
  303. # we will check the files pointed to anyway...
  304. if os.path.islink(path):
  305. return
  306. #if this will throw an exception, then fix the dict above
  307. (machine, osabi, abiversion, littleendian, bits) \
  308. = oe.elf.machine_dict(d)[target_os][target_arch]
  309. # Check the architecture and endiannes of the binary
  310. is_32 = (("virtual/kernel" in provides) or bb.data.inherits_class("module", d)) and \
  311. (target_os == "linux-gnux32" or target_os == "linux-muslx32" or \
  312. target_os == "linux-gnu_ilp32" or re.match(r'mips64.*32', d.getVar('DEFAULTTUNE')))
  313. is_bpf = (oe.qa.elf_machine_to_string(elf.machine()) == "BPF")
  314. if not ((machine == elf.machine()) or is_32 or is_bpf):
  315. package_qa_add_message(messages, "arch", "Architecture did not match (%s, expected %s) in %s" % \
  316. (oe.qa.elf_machine_to_string(elf.machine()), oe.qa.elf_machine_to_string(machine), package_qa_clean_path(path, d, name)))
  317. elif not ((bits == elf.abiSize()) or is_32 or is_bpf):
  318. package_qa_add_message(messages, "arch", "Bit size did not match (%d, expected %d) in %s" % \
  319. (elf.abiSize(), bits, package_qa_clean_path(path, d, name)))
  320. elif not ((littleendian == elf.isLittleEndian()) or is_bpf):
  321. package_qa_add_message(messages, "arch", "Endiannes did not match (%d, expected %d) in %s" % \
  322. (elf.isLittleEndian(), littleendian, package_qa_clean_path(path,d, name)))
  323. QAPATHTEST[desktop] = "package_qa_check_desktop"
  324. def package_qa_check_desktop(path, name, d, elf, messages):
  325. """
  326. Run all desktop files through desktop-file-validate.
  327. """
  328. if path.endswith(".desktop"):
  329. desktop_file_validate = os.path.join(d.getVar('STAGING_BINDIR_NATIVE'),'desktop-file-validate')
  330. output = os.popen("%s %s" % (desktop_file_validate, path))
  331. # This only produces output on errors
  332. for l in output:
  333. package_qa_add_message(messages, "desktop", "Desktop file issue: " + l.strip())
  334. QAPATHTEST[textrel] = "package_qa_textrel"
  335. def package_qa_textrel(path, name, d, elf, messages):
  336. """
  337. Check if the binary contains relocations in .text
  338. """
  339. if not elf:
  340. return
  341. if os.path.islink(path):
  342. return
  343. phdrs = elf.run_objdump("-p", d)
  344. sane = True
  345. import re
  346. textrel_re = re.compile(r"\s+TEXTREL\s+")
  347. for line in phdrs.split("\n"):
  348. if textrel_re.match(line):
  349. sane = False
  350. break
  351. if not sane:
  352. path = package_qa_clean_path(path, d, name)
  353. package_qa_add_message(messages, "textrel", "%s: ELF binary %s has relocations in .text" % (name, path))
  354. QAPATHTEST[ldflags] = "package_qa_hash_style"
  355. def package_qa_hash_style(path, name, d, elf, messages):
  356. """
  357. Check if the binary has the right hash style...
  358. """
  359. if not elf:
  360. return
  361. if os.path.islink(path):
  362. return
  363. gnu_hash = "--hash-style=gnu" in d.getVar('LDFLAGS')
  364. if not gnu_hash:
  365. gnu_hash = "--hash-style=both" in d.getVar('LDFLAGS')
  366. if not gnu_hash:
  367. return
  368. sane = False
  369. has_syms = False
  370. phdrs = elf.run_objdump("-p", d)
  371. # If this binary has symbols, we expect it to have GNU_HASH too.
  372. for line in phdrs.split("\n"):
  373. if "SYMTAB" in line:
  374. has_syms = True
  375. if "GNU_HASH" in line or "DT_MIPS_XHASH" in line:
  376. sane = True
  377. if ("[mips32]" in line or "[mips64]" in line) and d.getVar('TCLIBC') == "musl":
  378. sane = True
  379. if has_syms and not sane:
  380. path = package_qa_clean_path(path, d, name)
  381. package_qa_add_message(messages, "ldflags", "File %s in package %s doesn't have GNU_HASH (didn't pass LDFLAGS?)" % (path, name))
  382. QAPATHTEST[buildpaths] = "package_qa_check_buildpaths"
  383. def package_qa_check_buildpaths(path, name, d, elf, messages):
  384. """
  385. Check for build paths inside target files and error if not found in the whitelist
  386. """
  387. # Ignore .debug files, not interesting
  388. if path.find(".debug") != -1:
  389. return
  390. # Ignore symlinks
  391. if os.path.islink(path):
  392. return
  393. tmpdir = bytes(d.getVar('TMPDIR'), encoding="utf-8")
  394. with open(path, 'rb') as f:
  395. file_content = f.read()
  396. if tmpdir in file_content:
  397. trimmed = path.replace(os.path.join (d.getVar("PKGDEST"), name), "")
  398. package_qa_add_message(messages, "buildpaths", "File %s in package %s contains reference to TMPDIR" % (trimmed, name))
  399. QAPATHTEST[xorg-driver-abi] = "package_qa_check_xorg_driver_abi"
  400. def package_qa_check_xorg_driver_abi(path, name, d, elf, messages):
  401. """
  402. Check that all packages containing Xorg drivers have ABI dependencies
  403. """
  404. # Skip dev, dbg or nativesdk packages
  405. if name.endswith("-dev") or name.endswith("-dbg") or name.startswith("nativesdk-"):
  406. return
  407. driverdir = d.expand("${libdir}/xorg/modules/drivers/")
  408. if driverdir in path and path.endswith(".so"):
  409. mlprefix = d.getVar('MLPREFIX') or ''
  410. for rdep in bb.utils.explode_deps(d.getVar('RDEPENDS_' + name) or ""):
  411. if rdep.startswith("%sxorg-abi-" % mlprefix):
  412. return
  413. package_qa_add_message(messages, "xorg-driver-abi", "Package %s contains Xorg driver (%s) but no xorg-abi- dependencies" % (name, os.path.basename(path)))
  414. QAPATHTEST[infodir] = "package_qa_check_infodir"
  415. def package_qa_check_infodir(path, name, d, elf, messages):
  416. """
  417. Check that /usr/share/info/dir isn't shipped in a particular package
  418. """
  419. infodir = d.expand("${infodir}/dir")
  420. if infodir in path:
  421. package_qa_add_message(messages, "infodir", "The /usr/share/info/dir file is not meant to be shipped in a particular package.")
  422. QAPATHTEST[symlink-to-sysroot] = "package_qa_check_symlink_to_sysroot"
  423. def package_qa_check_symlink_to_sysroot(path, name, d, elf, messages):
  424. """
  425. Check that the package doesn't contain any absolute symlinks to the sysroot.
  426. """
  427. if os.path.islink(path):
  428. target = os.readlink(path)
  429. if os.path.isabs(target):
  430. tmpdir = d.getVar('TMPDIR')
  431. if target.startswith(tmpdir):
  432. trimmed = path.replace(os.path.join (d.getVar("PKGDEST"), name), "")
  433. package_qa_add_message(messages, "symlink-to-sysroot", "Symlink %s in %s points to TMPDIR" % (trimmed, name))
  434. # Check license variables
  435. do_populate_lic[postfuncs] += "populate_lic_qa_checksum"
  436. python populate_lic_qa_checksum() {
  437. """
  438. Check for changes in the license files.
  439. """
  440. sane = True
  441. lic_files = d.getVar('LIC_FILES_CHKSUM') or ''
  442. lic = d.getVar('LICENSE')
  443. pn = d.getVar('PN')
  444. if lic == "CLOSED":
  445. return
  446. if not lic_files and d.getVar('SRC_URI'):
  447. sane &= package_qa_handle_error("license-checksum", pn + ": Recipe file fetches files and does not have license file information (LIC_FILES_CHKSUM)", d)
  448. srcdir = d.getVar('S')
  449. corebase_licensefile = d.getVar('COREBASE') + "/LICENSE"
  450. for url in lic_files.split():
  451. try:
  452. (type, host, path, user, pswd, parm) = bb.fetch.decodeurl(url)
  453. except bb.fetch.MalformedUrl:
  454. sane &= package_qa_handle_error("license-checksum", pn + ": LIC_FILES_CHKSUM contains an invalid URL: " + url, d)
  455. continue
  456. srclicfile = os.path.join(srcdir, path)
  457. if not os.path.isfile(srclicfile):
  458. sane &= package_qa_handle_error("license-checksum", pn + ": LIC_FILES_CHKSUM points to an invalid file: " + srclicfile, d)
  459. continue
  460. if (srclicfile == corebase_licensefile):
  461. bb.warn("${COREBASE}/LICENSE is not a valid license file, please use '${COMMON_LICENSE_DIR}/MIT' for a MIT License file in LIC_FILES_CHKSUM. This will become an error in the future")
  462. recipemd5 = parm.get('md5', '')
  463. beginline, endline = 0, 0
  464. if 'beginline' in parm:
  465. beginline = int(parm['beginline'])
  466. if 'endline' in parm:
  467. endline = int(parm['endline'])
  468. if (not beginline) and (not endline):
  469. md5chksum = bb.utils.md5_file(srclicfile)
  470. with open(srclicfile, 'r', errors='replace') as f:
  471. license = f.read().splitlines()
  472. else:
  473. with open(srclicfile, 'rb') as f:
  474. import hashlib
  475. lineno = 0
  476. license = []
  477. m = hashlib.md5()
  478. for line in f:
  479. lineno += 1
  480. if (lineno >= beginline):
  481. if ((lineno <= endline) or not endline):
  482. m.update(line)
  483. license.append(line.decode('utf-8', errors='replace').rstrip())
  484. else:
  485. break
  486. md5chksum = m.hexdigest()
  487. if recipemd5 == md5chksum:
  488. bb.note (pn + ": md5 checksum matched for ", url)
  489. else:
  490. if recipemd5:
  491. msg = pn + ": The LIC_FILES_CHKSUM does not match for " + url
  492. msg = msg + "\n" + pn + ": The new md5 checksum is " + md5chksum
  493. max_lines = int(d.getVar('QA_MAX_LICENSE_LINES') or 20)
  494. if not license or license[-1] != '':
  495. # Ensure that our license text ends with a line break
  496. # (will be added with join() below).
  497. license.append('')
  498. remove = len(license) - max_lines
  499. if remove > 0:
  500. start = max_lines // 2
  501. end = start + remove - 1
  502. del license[start:end]
  503. license.insert(start, '...')
  504. msg = msg + "\n" + pn + ": Here is the selected license text:" + \
  505. "\n" + \
  506. "{:v^70}".format(" beginline=%d " % beginline if beginline else "") + \
  507. "\n" + "\n".join(license) + \
  508. "{:^^70}".format(" endline=%d " % endline if endline else "")
  509. if beginline:
  510. if endline:
  511. srcfiledesc = "%s (lines %d through to %d)" % (srclicfile, beginline, endline)
  512. else:
  513. srcfiledesc = "%s (beginning on line %d)" % (srclicfile, beginline)
  514. elif endline:
  515. srcfiledesc = "%s (ending on line %d)" % (srclicfile, endline)
  516. else:
  517. srcfiledesc = srclicfile
  518. msg = msg + "\n" + pn + ": Check if the license information has changed in %s to verify that the LICENSE value \"%s\" remains valid" % (srcfiledesc, lic)
  519. else:
  520. msg = pn + ": LIC_FILES_CHKSUM is not specified for " + url
  521. msg = msg + "\n" + pn + ": The md5 checksum is " + md5chksum
  522. sane &= package_qa_handle_error("license-checksum", msg, d)
  523. if not sane:
  524. bb.fatal("Fatal QA errors found, failing task.")
  525. }
  526. def qa_check_staged(path,d):
  527. """
  528. Check staged la and pc files for common problems like references to the work
  529. directory.
  530. As this is run after every stage we should be able to find the one
  531. responsible for the errors easily even if we look at every .pc and .la file.
  532. """
  533. sane = True
  534. tmpdir = d.getVar('TMPDIR')
  535. workdir = os.path.join(tmpdir, "work")
  536. recipesysroot = d.getVar("RECIPE_SYSROOT")
  537. if bb.data.inherits_class("native", d) or bb.data.inherits_class("cross", d):
  538. pkgconfigcheck = workdir
  539. else:
  540. pkgconfigcheck = tmpdir
  541. skip = (d.getVar('INSANE_SKIP') or "").split()
  542. skip_la = False
  543. if 'la' in skip:
  544. bb.note("Recipe %s skipping qa checking: la" % d.getVar('PN'))
  545. skip_la = True
  546. skip_pkgconfig = False
  547. if 'pkgconfig' in skip:
  548. bb.note("Recipe %s skipping qa checking: pkgconfig" % d.getVar('PN'))
  549. skip_pkgconfig = True
  550. # find all .la and .pc files
  551. # read the content
  552. # and check for stuff that looks wrong
  553. for root, dirs, files in os.walk(path):
  554. for file in files:
  555. path = os.path.join(root,file)
  556. if file.endswith(".la") and not skip_la:
  557. with open(path) as f:
  558. file_content = f.read()
  559. file_content = file_content.replace(recipesysroot, "")
  560. if workdir in file_content:
  561. error_msg = "%s failed sanity test (workdir) in path %s" % (file,root)
  562. sane &= package_qa_handle_error("la", error_msg, d)
  563. elif file.endswith(".pc") and not skip_pkgconfig:
  564. with open(path) as f:
  565. file_content = f.read()
  566. file_content = file_content.replace(recipesysroot, "")
  567. if pkgconfigcheck in file_content:
  568. error_msg = "%s failed sanity test (tmpdir) in path %s" % (file,root)
  569. sane &= package_qa_handle_error("pkgconfig", error_msg, d)
  570. return sane
  571. # Run all package-wide warnfuncs and errorfuncs
  572. def package_qa_package(warnfuncs, errorfuncs, package, d):
  573. warnings = {}
  574. errors = {}
  575. for func in warnfuncs:
  576. func(package, d, warnings)
  577. for func in errorfuncs:
  578. func(package, d, errors)
  579. for w in warnings:
  580. package_qa_handle_error(w, warnings[w], d)
  581. for e in errors:
  582. package_qa_handle_error(e, errors[e], d)
  583. return len(errors) == 0
  584. # Run all recipe-wide warnfuncs and errorfuncs
  585. def package_qa_recipe(warnfuncs, errorfuncs, pn, d):
  586. warnings = {}
  587. errors = {}
  588. for func in warnfuncs:
  589. func(pn, d, warnings)
  590. for func in errorfuncs:
  591. func(pn, d, errors)
  592. for w in warnings:
  593. package_qa_handle_error(w, warnings[w], d)
  594. for e in errors:
  595. package_qa_handle_error(e, errors[e], d)
  596. return len(errors) == 0
  597. # Walk over all files in a directory and call func
  598. def package_qa_walk(warnfuncs, errorfuncs, package, d):
  599. import oe.qa
  600. #if this will throw an exception, then fix the dict above
  601. target_os = d.getVar('TARGET_OS')
  602. target_arch = d.getVar('TARGET_ARCH')
  603. warnings = {}
  604. errors = {}
  605. for path in pkgfiles[package]:
  606. elf = None
  607. if os.path.isfile(path):
  608. elf = oe.qa.ELFFile(path)
  609. try:
  610. elf.open()
  611. except oe.qa.NotELFFileError:
  612. elf = None
  613. for func in warnfuncs:
  614. func(path, package, d, elf, warnings)
  615. for func in errorfuncs:
  616. func(path, package, d, elf, errors)
  617. for w in warnings:
  618. package_qa_handle_error(w, warnings[w], d)
  619. for e in errors:
  620. package_qa_handle_error(e, errors[e], d)
  621. def package_qa_check_rdepends(pkg, pkgdest, skip, taskdeps, packages, d):
  622. # Don't do this check for kernel/module recipes, there aren't too many debug/development
  623. # packages and you can get false positives e.g. on kernel-module-lirc-dev
  624. if bb.data.inherits_class("kernel", d) or bb.data.inherits_class("module-base", d):
  625. return
  626. if not "-dbg" in pkg and not "packagegroup-" in pkg and not "-image" in pkg:
  627. localdata = bb.data.createCopy(d)
  628. localdata.setVar('OVERRIDES', localdata.getVar('OVERRIDES') + ':' + pkg)
  629. # Now check the RDEPENDS
  630. rdepends = bb.utils.explode_deps(localdata.getVar('RDEPENDS') or "")
  631. # Now do the sanity check!!!
  632. if "build-deps" not in skip:
  633. for rdepend in rdepends:
  634. if "-dbg" in rdepend and "debug-deps" not in skip:
  635. error_msg = "%s rdepends on %s" % (pkg,rdepend)
  636. package_qa_handle_error("debug-deps", error_msg, d)
  637. if (not "-dev" in pkg and not "-staticdev" in pkg) and rdepend.endswith("-dev") and "dev-deps" not in skip:
  638. error_msg = "%s rdepends on %s" % (pkg, rdepend)
  639. package_qa_handle_error("dev-deps", error_msg, d)
  640. if rdepend not in packages:
  641. rdep_data = oe.packagedata.read_subpkgdata(rdepend, d)
  642. if rdep_data and 'PN' in rdep_data and rdep_data['PN'] in taskdeps:
  643. continue
  644. if not rdep_data or not 'PN' in rdep_data:
  645. pkgdata_dir = d.getVar("PKGDATA_DIR")
  646. try:
  647. possibles = os.listdir("%s/runtime-rprovides/%s/" % (pkgdata_dir, rdepend))
  648. except OSError:
  649. possibles = []
  650. for p in possibles:
  651. rdep_data = oe.packagedata.read_subpkgdata(p, d)
  652. if rdep_data and 'PN' in rdep_data and rdep_data['PN'] in taskdeps:
  653. break
  654. if rdep_data and 'PN' in rdep_data and rdep_data['PN'] in taskdeps:
  655. continue
  656. if rdep_data and 'PN' in rdep_data:
  657. error_msg = "%s rdepends on %s, but it isn't a build dependency, missing %s in DEPENDS or PACKAGECONFIG?" % (pkg, rdepend, rdep_data['PN'])
  658. else:
  659. error_msg = "%s rdepends on %s, but it isn't a build dependency?" % (pkg, rdepend)
  660. package_qa_handle_error("build-deps", error_msg, d)
  661. if "file-rdeps" not in skip:
  662. ignored_file_rdeps = set(['/bin/sh', '/usr/bin/env', 'rtld(GNU_HASH)'])
  663. if bb.data.inherits_class('nativesdk', d):
  664. ignored_file_rdeps |= set(['/bin/bash', '/usr/bin/perl', 'perl'])
  665. # For Saving the FILERDEPENDS
  666. filerdepends = {}
  667. rdep_data = oe.packagedata.read_subpkgdata(pkg, d)
  668. for key in rdep_data:
  669. if key.startswith("FILERDEPENDS_"):
  670. for subkey in bb.utils.explode_deps(rdep_data[key]):
  671. if subkey not in ignored_file_rdeps and \
  672. not subkey.startswith('perl('):
  673. # We already know it starts with FILERDEPENDS_
  674. filerdepends[subkey] = key[13:]
  675. if filerdepends:
  676. done = rdepends[:]
  677. # Add the rprovides of itself
  678. if pkg not in done:
  679. done.insert(0, pkg)
  680. # The python is not a package, but python-core provides it, so
  681. # skip checking /usr/bin/python if python is in the rdeps, in
  682. # case there is a RDEPENDS_pkg = "python" in the recipe.
  683. for py in [ d.getVar('MLPREFIX') + "python", "python" ]:
  684. if py in done:
  685. filerdepends.pop("/usr/bin/python",None)
  686. done.remove(py)
  687. for rdep in done:
  688. # The file dependencies may contain package names, e.g.,
  689. # perl
  690. filerdepends.pop(rdep,None)
  691. # For Saving the FILERPROVIDES, RPROVIDES and FILES_INFO
  692. rdep_data = oe.packagedata.read_subpkgdata(rdep, d)
  693. for key in rdep_data:
  694. if key.startswith("FILERPROVIDES_") or key.startswith("RPROVIDES_"):
  695. for subkey in bb.utils.explode_deps(rdep_data[key]):
  696. filerdepends.pop(subkey,None)
  697. # Add the files list to the rprovides
  698. if key == "FILES_INFO":
  699. # Use eval() to make it as a dict
  700. for subkey in eval(rdep_data[key]):
  701. filerdepends.pop(subkey,None)
  702. if not filerdepends:
  703. # Break if all the file rdepends are met
  704. break
  705. if filerdepends:
  706. for key in filerdepends:
  707. error_msg = "%s contained in package %s requires %s, but no providers found in RDEPENDS_%s?" % \
  708. (filerdepends[key].replace("_%s" % pkg, "").replace("@underscore@", "_"), pkg, key, pkg)
  709. package_qa_handle_error("file-rdeps", error_msg, d)
  710. package_qa_check_rdepends[vardepsexclude] = "OVERRIDES"
  711. def package_qa_check_deps(pkg, pkgdest, d):
  712. localdata = bb.data.createCopy(d)
  713. localdata.setVar('OVERRIDES', pkg)
  714. def check_valid_deps(var):
  715. try:
  716. rvar = bb.utils.explode_dep_versions2(localdata.getVar(var) or "")
  717. except ValueError as e:
  718. bb.fatal("%s_%s: %s" % (var, pkg, e))
  719. for dep in rvar:
  720. for v in rvar[dep]:
  721. if v and not v.startswith(('< ', '= ', '> ', '<= ', '>=')):
  722. error_msg = "%s_%s is invalid: %s (%s) only comparisons <, =, >, <=, and >= are allowed" % (var, pkg, dep, v)
  723. package_qa_handle_error("dep-cmp", error_msg, d)
  724. check_valid_deps('RDEPENDS')
  725. check_valid_deps('RRECOMMENDS')
  726. check_valid_deps('RSUGGESTS')
  727. check_valid_deps('RPROVIDES')
  728. check_valid_deps('RREPLACES')
  729. check_valid_deps('RCONFLICTS')
  730. QAPKGTEST[usrmerge] = "package_qa_check_usrmerge"
  731. def package_qa_check_usrmerge(pkg, d, messages):
  732. pkgdest = d.getVar('PKGDEST')
  733. pkg_dir = pkgdest + os.sep + pkg + os.sep
  734. merged_dirs = ['bin', 'sbin', 'lib'] + d.getVar('MULTILIB_VARIANTS').split()
  735. for f in merged_dirs:
  736. if os.path.exists(pkg_dir + f) and not os.path.islink(pkg_dir + f):
  737. msg = "%s package is not obeying usrmerge distro feature. /%s should be relocated to /usr." % (pkg, f)
  738. package_qa_add_message(messages, "usrmerge", msg)
  739. return False
  740. return True
  741. QAPKGTEST[perllocalpod] = "package_qa_check_perllocalpod"
  742. def package_qa_check_perllocalpod(pkg, d, messages):
  743. """
  744. Check that the recipe didn't ship a perlocal.pod file, which shouldn't be
  745. installed in a distribution package. cpan.bbclass sets NO_PERLLOCAL=1 to
  746. handle this for most recipes.
  747. """
  748. import glob
  749. pkgd = oe.path.join(d.getVar('PKGDEST'), pkg)
  750. podpath = oe.path.join(pkgd, d.getVar("libdir"), "perl*", "*", "*", "perllocal.pod")
  751. matches = glob.glob(podpath)
  752. if matches:
  753. matches = [package_qa_clean_path(path, d, pkg) for path in matches]
  754. msg = "%s contains perllocal.pod (%s), should not be installed" % (pkg, " ".join(matches))
  755. package_qa_add_message(messages, "perllocalpod", msg)
  756. QAPKGTEST[expanded-d] = "package_qa_check_expanded_d"
  757. def package_qa_check_expanded_d(package, d, messages):
  758. """
  759. Check for the expanded D (${D}) value in pkg_* and FILES
  760. variables, warn the user to use it correctly.
  761. """
  762. sane = True
  763. expanded_d = d.getVar('D')
  764. for var in 'FILES','pkg_preinst', 'pkg_postinst', 'pkg_prerm', 'pkg_postrm':
  765. bbvar = d.getVar(var + "_" + package) or ""
  766. if expanded_d in bbvar:
  767. if var == 'FILES':
  768. package_qa_add_message(messages, "expanded-d", "FILES in %s recipe should not contain the ${D} variable as it references the local build directory not the target filesystem, best solution is to remove the ${D} reference" % package)
  769. sane = False
  770. else:
  771. package_qa_add_message(messages, "expanded-d", "%s in %s recipe contains ${D}, it should be replaced by $D instead" % (var, package))
  772. sane = False
  773. return sane
  774. QAPKGTEST[unlisted-pkg-lics] = "package_qa_check_unlisted_pkg_lics"
  775. def package_qa_check_unlisted_pkg_lics(package, d, messages):
  776. """
  777. Check that all licenses for a package are among the licenses for the recipe.
  778. """
  779. pkg_lics = d.getVar('LICENSE_' + package)
  780. if not pkg_lics:
  781. return True
  782. recipe_lics_set = oe.license.list_licenses(d.getVar('LICENSE'))
  783. unlisted = oe.license.list_licenses(pkg_lics) - recipe_lics_set
  784. if not unlisted:
  785. return True
  786. package_qa_add_message(messages, "unlisted-pkg-lics",
  787. "LICENSE_%s includes licenses (%s) that are not "
  788. "listed in LICENSE" % (package, ' '.join(unlisted)))
  789. return False
  790. def package_qa_check_encoding(keys, encode, d):
  791. def check_encoding(key, enc):
  792. sane = True
  793. value = d.getVar(key)
  794. if value:
  795. try:
  796. s = value.encode(enc)
  797. except UnicodeDecodeError as e:
  798. error_msg = "%s has non %s characters" % (key,enc)
  799. sane = False
  800. package_qa_handle_error("invalid-chars", error_msg, d)
  801. return sane
  802. for key in keys:
  803. sane = check_encoding(key, encode)
  804. if not sane:
  805. break
  806. HOST_USER_UID := "${@os.getuid()}"
  807. HOST_USER_GID := "${@os.getgid()}"
  808. QAPATHTEST[host-user-contaminated] = "package_qa_check_host_user"
  809. def package_qa_check_host_user(path, name, d, elf, messages):
  810. """Check for paths outside of /home which are owned by the user running bitbake."""
  811. if not os.path.lexists(path):
  812. return
  813. dest = d.getVar('PKGDEST')
  814. pn = d.getVar('PN')
  815. home = os.path.join(dest, 'home')
  816. if path == home or path.startswith(home + os.sep):
  817. return
  818. try:
  819. stat = os.lstat(path)
  820. except OSError as exc:
  821. import errno
  822. if exc.errno != errno.ENOENT:
  823. raise
  824. else:
  825. check_uid = int(d.getVar('HOST_USER_UID'))
  826. if stat.st_uid == check_uid:
  827. package_qa_add_message(messages, "host-user-contaminated", "%s: %s is owned by uid %d, which is the same as the user running bitbake. This may be due to host contamination" % (pn, package_qa_clean_path(path, d, name), check_uid))
  828. return False
  829. check_gid = int(d.getVar('HOST_USER_GID'))
  830. if stat.st_gid == check_gid:
  831. package_qa_add_message(messages, "host-user-contaminated", "%s: %s is owned by gid %d, which is the same as the user running bitbake. This may be due to host contamination" % (pn, package_qa_clean_path(path, d, name), check_gid))
  832. return False
  833. return True
  834. QARECIPETEST[src-uri-bad] = "package_qa_check_src_uri"
  835. def package_qa_check_src_uri(pn, d, messages):
  836. import re
  837. if "${PN}" in d.getVar("SRC_URI", False):
  838. package_qa_handle_error("src-uri-bad", "%s: SRC_URI uses PN not BPN" % pn, d)
  839. for url in d.getVar("SRC_URI").split():
  840. if re.search(r"git(hu|la)b\.com/.+/.+/archive/.+", url):
  841. package_qa_handle_error("src-uri-bad", "%s: SRC_URI uses unstable GitHub/GitLab archives, convert recipe to use git protocol" % pn, d)
  842. QARECIPETEST[unhandled-features-check] = "package_qa_check_unhandled_features_check"
  843. def package_qa_check_unhandled_features_check(pn, d, messages):
  844. if not bb.data.inherits_class('features_check', d):
  845. var_set = False
  846. for kind in ['DISTRO', 'MACHINE', 'COMBINED']:
  847. for var in ['ANY_OF_' + kind + '_FEATURES', 'REQUIRED_' + kind + '_FEATURES', 'CONFLICT_' + kind + '_FEATURES']:
  848. if d.getVar(var) is not None or d.overridedata.get(var) is not None:
  849. var_set = True
  850. if var_set:
  851. package_qa_handle_error("unhandled-features-check", "%s: recipe doesn't inherit features_check" % pn, d)
  852. QARECIPETEST[missing-update-alternatives] = "package_qa_check_missing_update_alternatives"
  853. def package_qa_check_missing_update_alternatives(pn, d, messages):
  854. # Look at all packages and find out if any of those sets ALTERNATIVE variable
  855. # without inheriting update-alternatives class
  856. for pkg in (d.getVar('PACKAGES') or '').split():
  857. if d.getVar('ALTERNATIVE_%s' % pkg) and not bb.data.inherits_class('update-alternatives', d):
  858. package_qa_handle_error("missing-update-alternatives", "%s: recipe defines ALTERNATIVE_%s but doesn't inherit update-alternatives. This might fail during do_rootfs later!" % (pn, pkg), d)
  859. # The PACKAGE FUNC to scan each package
  860. python do_package_qa () {
  861. import subprocess
  862. import oe.packagedata
  863. bb.note("DO PACKAGE QA")
  864. bb.build.exec_func("read_subpackage_metadata", d)
  865. # Check non UTF-8 characters on recipe's metadata
  866. package_qa_check_encoding(['DESCRIPTION', 'SUMMARY', 'LICENSE', 'SECTION'], 'utf-8', d)
  867. logdir = d.getVar('T')
  868. pn = d.getVar('PN')
  869. # Check the compile log for host contamination
  870. compilelog = os.path.join(logdir,"log.do_compile")
  871. if os.path.exists(compilelog):
  872. statement = "grep -e 'CROSS COMPILE Badness:' -e 'is unsafe for cross-compilation' %s > /dev/null" % compilelog
  873. if subprocess.call(statement, shell=True) == 0:
  874. msg = "%s: The compile log indicates that host include and/or library paths were used.\n \
  875. Please check the log '%s' for more information." % (pn, compilelog)
  876. package_qa_handle_error("compile-host-path", msg, d)
  877. # Check the install log for host contamination
  878. installlog = os.path.join(logdir,"log.do_install")
  879. if os.path.exists(installlog):
  880. statement = "grep -e 'CROSS COMPILE Badness:' -e 'is unsafe for cross-compilation' %s > /dev/null" % installlog
  881. if subprocess.call(statement, shell=True) == 0:
  882. msg = "%s: The install log indicates that host include and/or library paths were used.\n \
  883. Please check the log '%s' for more information." % (pn, installlog)
  884. package_qa_handle_error("install-host-path", msg, d)
  885. # Scan the packages...
  886. pkgdest = d.getVar('PKGDEST')
  887. packages = set((d.getVar('PACKAGES') or '').split())
  888. global pkgfiles
  889. pkgfiles = {}
  890. for pkg in packages:
  891. pkgfiles[pkg] = []
  892. pkgdir = os.path.join(pkgdest, pkg)
  893. for walkroot, dirs, files in os.walk(pkgdir):
  894. # Don't walk into top-level CONTROL or DEBIAN directories as these
  895. # are temporary directories created by do_package.
  896. if walkroot == pkgdir:
  897. for control in ("CONTROL", "DEBIAN"):
  898. if control in dirs:
  899. dirs.remove(control)
  900. for file in files:
  901. pkgfiles[pkg].append(os.path.join(walkroot, file))
  902. # no packages should be scanned
  903. if not packages:
  904. return
  905. import re
  906. # The package name matches the [a-z0-9.+-]+ regular expression
  907. pkgname_pattern = re.compile(r"^[a-z0-9.+-]+$")
  908. taskdepdata = d.getVar("BB_TASKDEPDATA", False)
  909. taskdeps = set()
  910. for dep in taskdepdata:
  911. taskdeps.add(taskdepdata[dep][0])
  912. def parse_test_matrix(matrix_name):
  913. testmatrix = d.getVarFlags(matrix_name) or {}
  914. g = globals()
  915. warnchecks = []
  916. for w in (d.getVar("WARN_QA") or "").split():
  917. if w in skip:
  918. continue
  919. if w in testmatrix and testmatrix[w] in g:
  920. warnchecks.append(g[testmatrix[w]])
  921. errorchecks = []
  922. for e in (d.getVar("ERROR_QA") or "").split():
  923. if e in skip:
  924. continue
  925. if e in testmatrix and testmatrix[e] in g:
  926. errorchecks.append(g[testmatrix[e]])
  927. return warnchecks, errorchecks
  928. for package in packages:
  929. skip = set((d.getVar('INSANE_SKIP') or "").split() +
  930. (d.getVar('INSANE_SKIP_' + package) or "").split())
  931. if skip:
  932. bb.note("Package %s skipping QA tests: %s" % (package, str(skip)))
  933. bb.note("Checking Package: %s" % package)
  934. # Check package name
  935. if not pkgname_pattern.match(package):
  936. package_qa_handle_error("pkgname",
  937. "%s doesn't match the [a-z0-9.+-]+ regex" % package, d)
  938. warn_checks, error_checks = parse_test_matrix("QAPATHTEST")
  939. package_qa_walk(warn_checks, error_checks, package, d)
  940. warn_checks, error_checks = parse_test_matrix("QAPKGTEST")
  941. package_qa_package(warn_checks, error_checks, package, d)
  942. package_qa_check_rdepends(package, pkgdest, skip, taskdeps, packages, d)
  943. package_qa_check_deps(package, pkgdest, d)
  944. warn_checks, error_checks = parse_test_matrix("QARECIPETEST")
  945. package_qa_recipe(warn_checks, error_checks, pn, d)
  946. if 'libdir' in d.getVar("ALL_QA").split():
  947. package_qa_check_libdir(d)
  948. qa_sane = d.getVar("QA_SANE")
  949. if not qa_sane:
  950. bb.fatal("QA run found fatal errors. Please consider fixing them.")
  951. bb.note("DONE with PACKAGE QA")
  952. }
  953. # binutils is used for most checks, so need to set as dependency
  954. # POPULATESYSROOTDEPS is defined in staging class.
  955. do_package_qa[depends] += "${POPULATESYSROOTDEPS}"
  956. do_package_qa[vardepsexclude] = "BB_TASKDEPDATA"
  957. do_package_qa[rdeptask] = "do_packagedata"
  958. addtask do_package_qa after do_packagedata do_package before do_build
  959. # Add the package specific INSANE_SKIPs to the sstate dependencies
  960. python() {
  961. pkgs = (d.getVar('PACKAGES') or '').split()
  962. for pkg in pkgs:
  963. d.appendVarFlag("do_package_qa", "vardeps", " INSANE_SKIP_{}".format(pkg))
  964. }
  965. SSTATETASKS += "do_package_qa"
  966. do_package_qa[sstate-inputdirs] = ""
  967. do_package_qa[sstate-outputdirs] = ""
  968. python do_package_qa_setscene () {
  969. sstate_setscene(d)
  970. }
  971. addtask do_package_qa_setscene
  972. python do_qa_staging() {
  973. bb.note("QA checking staging")
  974. if not qa_check_staged(d.expand('${SYSROOT_DESTDIR}${libdir}'), d):
  975. bb.fatal("QA staging was broken by the package built above")
  976. }
  977. python do_qa_patch() {
  978. import subprocess
  979. ###########################################################################
  980. # Check patch.log for fuzz warnings
  981. #
  982. # Further information on why we check for patch fuzz warnings:
  983. # http://lists.openembedded.org/pipermail/openembedded-core/2018-March/148675.html
  984. # https://bugzilla.yoctoproject.org/show_bug.cgi?id=10450
  985. ###########################################################################
  986. logdir = d.getVar('T')
  987. patchlog = os.path.join(logdir,"log.do_patch")
  988. if os.path.exists(patchlog):
  989. fuzzheader = '--- Patch fuzz start ---'
  990. fuzzfooter = '--- Patch fuzz end ---'
  991. statement = "grep -e '%s' %s > /dev/null" % (fuzzheader, patchlog)
  992. if subprocess.call(statement, shell=True) == 0:
  993. msg = "Fuzz detected:\n\n"
  994. fuzzmsg = ""
  995. inFuzzInfo = False
  996. f = open(patchlog, "r")
  997. for line in f:
  998. if fuzzheader in line:
  999. inFuzzInfo = True
  1000. fuzzmsg = ""
  1001. elif fuzzfooter in line:
  1002. fuzzmsg = fuzzmsg.replace('\n\n', '\n')
  1003. msg += fuzzmsg
  1004. msg += "\n"
  1005. inFuzzInfo = False
  1006. elif inFuzzInfo and not 'Now at patch' in line:
  1007. fuzzmsg += line
  1008. f.close()
  1009. msg += "The context lines in the patches can be updated with devtool:\n"
  1010. msg += "\n"
  1011. msg += " devtool modify %s\n" % d.getVar('PN')
  1012. msg += " devtool finish --force-patch-refresh %s <layer_path>\n\n" % d.getVar('PN')
  1013. msg += "Don't forget to review changes done by devtool!\n"
  1014. if 'patch-fuzz' in d.getVar('ERROR_QA'):
  1015. bb.error(msg)
  1016. elif 'patch-fuzz' in d.getVar('WARN_QA'):
  1017. bb.warn(msg)
  1018. msg = "Patch log indicates that patches do not apply cleanly."
  1019. package_qa_handle_error("patch-fuzz", msg, d)
  1020. }
  1021. python do_qa_configure() {
  1022. import subprocess
  1023. ###########################################################################
  1024. # Check config.log for cross compile issues
  1025. ###########################################################################
  1026. configs = []
  1027. workdir = d.getVar('WORKDIR')
  1028. skip = (d.getVar('INSANE_SKIP') or "").split()
  1029. skip_configure_unsafe = False
  1030. if 'configure-unsafe' in skip:
  1031. bb.note("Recipe %s skipping qa checking: configure-unsafe" % d.getVar('PN'))
  1032. skip_configure_unsafe = True
  1033. if bb.data.inherits_class('autotools', d) and not skip_configure_unsafe:
  1034. bb.note("Checking autotools environment for common misconfiguration")
  1035. for root, dirs, files in os.walk(workdir):
  1036. statement = "grep -q -F -e 'CROSS COMPILE Badness:' -e 'is unsafe for cross-compilation' %s" % \
  1037. os.path.join(root,"config.log")
  1038. if "config.log" in files:
  1039. if subprocess.call(statement, shell=True) == 0:
  1040. error_msg = """This autoconf log indicates errors, it looked at host include and/or library paths while determining system capabilities.
  1041. Rerun configure task after fixing this."""
  1042. package_qa_handle_error("configure-unsafe", error_msg, d)
  1043. if "configure.ac" in files:
  1044. configs.append(os.path.join(root,"configure.ac"))
  1045. if "configure.in" in files:
  1046. configs.append(os.path.join(root, "configure.in"))
  1047. ###########################################################################
  1048. # Check gettext configuration and dependencies are correct
  1049. ###########################################################################
  1050. skip_configure_gettext = False
  1051. if 'configure-gettext' in skip:
  1052. bb.note("Recipe %s skipping qa checking: configure-gettext" % d.getVar('PN'))
  1053. skip_configure_gettext = True
  1054. cnf = d.getVar('EXTRA_OECONF') or ""
  1055. if not ("gettext" in d.getVar('P') or "gcc-runtime" in d.getVar('P') or \
  1056. "--disable-nls" in cnf or skip_configure_gettext):
  1057. ml = d.getVar("MLPREFIX") or ""
  1058. if bb.data.inherits_class('cross-canadian', d):
  1059. gt = "nativesdk-gettext"
  1060. else:
  1061. gt = "gettext-native"
  1062. deps = bb.utils.explode_deps(d.getVar('DEPENDS') or "")
  1063. if gt not in deps:
  1064. for config in configs:
  1065. gnu = "grep \"^[[:space:]]*AM_GNU_GETTEXT\" %s >/dev/null" % config
  1066. if subprocess.call(gnu, shell=True) == 0:
  1067. error_msg = "AM_GNU_GETTEXT used but no inherit gettext"
  1068. package_qa_handle_error("configure-gettext", error_msg, d)
  1069. ###########################################################################
  1070. # Check unrecognised configure options (with a white list)
  1071. ###########################################################################
  1072. if bb.data.inherits_class("autotools", d) or bb.data.inherits_class("meson", d):
  1073. bb.note("Checking configure output for unrecognised options")
  1074. try:
  1075. if bb.data.inherits_class("autotools", d):
  1076. flag = "WARNING: unrecognized options:"
  1077. log = os.path.join(d.getVar('B'), 'config.log')
  1078. if bb.data.inherits_class("meson", d):
  1079. flag = "WARNING: Unknown options:"
  1080. log = os.path.join(d.getVar('T'), 'log.do_configure')
  1081. output = subprocess.check_output(['grep', '-F', flag, log]).decode("utf-8").replace(', ', ' ').replace('"', '')
  1082. options = set()
  1083. for line in output.splitlines():
  1084. options |= set(line.partition(flag)[2].split())
  1085. whitelist = set(d.getVar("UNKNOWN_CONFIGURE_WHITELIST").split())
  1086. options -= whitelist
  1087. if options:
  1088. pn = d.getVar('PN')
  1089. error_msg = pn + ": configure was passed unrecognised options: " + " ".join(options)
  1090. package_qa_handle_error("unknown-configure-option", error_msg, d)
  1091. except subprocess.CalledProcessError:
  1092. pass
  1093. # Check invalid PACKAGECONFIG
  1094. pkgconfig = (d.getVar("PACKAGECONFIG") or "").split()
  1095. if pkgconfig:
  1096. pkgconfigflags = d.getVarFlags("PACKAGECONFIG") or {}
  1097. for pconfig in pkgconfig:
  1098. if pconfig not in pkgconfigflags:
  1099. pn = d.getVar('PN')
  1100. error_msg = "%s: invalid PACKAGECONFIG: %s" % (pn, pconfig)
  1101. package_qa_handle_error("invalid-packageconfig", error_msg, d)
  1102. qa_sane = d.getVar("QA_SANE")
  1103. if not qa_sane:
  1104. bb.fatal("Fatal QA errors found, failing task.")
  1105. }
  1106. python do_qa_unpack() {
  1107. src_uri = d.getVar('SRC_URI')
  1108. s_dir = d.getVar('S')
  1109. if src_uri and not os.path.exists(s_dir):
  1110. bb.warn('%s: the directory %s (%s) pointed to by the S variable doesn\'t exist - please set S within the recipe to point to where the source has been unpacked to' % (d.getVar('PN'), d.getVar('S', False), s_dir))
  1111. }
  1112. # The Staging Func, to check all staging
  1113. #addtask qa_staging after do_populate_sysroot before do_build
  1114. do_populate_sysroot[postfuncs] += "do_qa_staging "
  1115. # Check for patch fuzz
  1116. do_patch[postfuncs] += "do_qa_patch "
  1117. # Check broken config.log files, for packages requiring Gettext which
  1118. # don't have it in DEPENDS.
  1119. #addtask qa_configure after do_configure before do_compile
  1120. do_configure[postfuncs] += "do_qa_configure "
  1121. # Check does S exist.
  1122. do_unpack[postfuncs] += "do_qa_unpack"
  1123. python () {
  1124. import re
  1125. tests = d.getVar('ALL_QA').split()
  1126. if "desktop" in tests:
  1127. d.appendVar("PACKAGE_DEPENDS", " desktop-file-utils-native")
  1128. ###########################################################################
  1129. # Check various variables
  1130. ###########################################################################
  1131. # Checking ${FILESEXTRAPATHS}
  1132. extrapaths = (d.getVar("FILESEXTRAPATHS") or "")
  1133. if '__default' not in extrapaths.split(":"):
  1134. msg = "FILESEXTRAPATHS-variable, must always use _prepend (or _append)\n"
  1135. msg += "type of assignment, and don't forget the colon.\n"
  1136. msg += "Please assign it with the format of:\n"
  1137. msg += " FILESEXTRAPATHS_append := \":${THISDIR}/Your_Files_Path\" or\n"
  1138. msg += " FILESEXTRAPATHS_prepend := \"${THISDIR}/Your_Files_Path:\"\n"
  1139. msg += "in your bbappend file\n\n"
  1140. msg += "Your incorrect assignment is:\n"
  1141. msg += "%s\n" % extrapaths
  1142. bb.warn(msg)
  1143. overrides = d.getVar('OVERRIDES').split(':')
  1144. pn = d.getVar('PN')
  1145. if pn in overrides:
  1146. msg = 'Recipe %s has PN of "%s" which is in OVERRIDES, this can result in unexpected behaviour.' % (d.getVar("FILE"), pn)
  1147. package_qa_handle_error("pn-overrides", msg, d)
  1148. prog = re.compile(r'[A-Z]')
  1149. if prog.search(pn):
  1150. package_qa_handle_error("uppercase-pn", 'PN: %s is upper case, this can result in unexpected behavior.' % pn, d)
  1151. # Some people mistakenly use DEPENDS_${PN} instead of DEPENDS and wonder
  1152. # why it doesn't work.
  1153. if (d.getVar(d.expand('DEPENDS_${PN}'))):
  1154. package_qa_handle_error("pkgvarcheck", "recipe uses DEPENDS_${PN}, should use DEPENDS", d)
  1155. issues = []
  1156. if (d.getVar('PACKAGES') or "").split():
  1157. for dep in (d.getVar('QADEPENDS') or "").split():
  1158. d.appendVarFlag('do_package_qa', 'depends', " %s:do_populate_sysroot" % dep)
  1159. for var in 'RDEPENDS', 'RRECOMMENDS', 'RSUGGESTS', 'RCONFLICTS', 'RPROVIDES', 'RREPLACES', 'FILES', 'pkg_preinst', 'pkg_postinst', 'pkg_prerm', 'pkg_postrm', 'ALLOW_EMPTY':
  1160. if d.getVar(var, False):
  1161. issues.append(var)
  1162. fakeroot_tests = d.getVar('FAKEROOT_QA').split()
  1163. if set(tests) & set(fakeroot_tests):
  1164. d.setVarFlag('do_package_qa', 'fakeroot', '1')
  1165. d.appendVarFlag('do_package_qa', 'depends', ' virtual/fakeroot-native:do_populate_sysroot')
  1166. else:
  1167. d.setVarFlag('do_package_qa', 'rdeptask', '')
  1168. for i in issues:
  1169. package_qa_handle_error("pkgvarcheck", "%s: Variable %s is set as not being package specific, please fix this." % (d.getVar("FILE"), i), d)
  1170. qa_sane = d.getVar("QA_SANE")
  1171. if not qa_sane:
  1172. bb.fatal("Fatal QA errors found, failing task.")
  1173. }