insane.bbclass 61 KB

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