sanity.bbclass 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  1. #
  2. # Copyright OpenEmbedded Contributors
  3. #
  4. # SPDX-License-Identifier: MIT
  5. #
  6. #
  7. # Sanity check the users setup for common misconfigurations
  8. #
  9. SANITY_REQUIRED_UTILITIES ?= "patch diffstat git bzip2 tar \
  10. gzip gawk chrpath wget cpio perl file which"
  11. def bblayers_conf_file(d):
  12. return os.path.join(d.getVar('TOPDIR'), 'conf/bblayers.conf')
  13. def sanity_conf_read(fn):
  14. with open(fn, 'r') as f:
  15. lines = f.readlines()
  16. return lines
  17. def sanity_conf_find_line(pattern, lines):
  18. import re
  19. return next(((index, line)
  20. for index, line in enumerate(lines)
  21. if re.search(pattern, line)), (None, None))
  22. def sanity_conf_update(fn, lines, version_var_name, new_version):
  23. index, line = sanity_conf_find_line(r"^%s" % version_var_name, lines)
  24. lines[index] = '%s = "%d"\n' % (version_var_name, new_version)
  25. with open(fn, "w") as f:
  26. f.write(''.join(lines))
  27. # Functions added to this variable MUST throw a NotImplementedError exception unless
  28. # they successfully changed the config version in the config file. Exceptions
  29. # are used since exec_func doesn't handle return values.
  30. BBLAYERS_CONF_UPDATE_FUNCS += " \
  31. conf/bblayers.conf:LCONF_VERSION:LAYER_CONF_VERSION:oecore_update_bblayers \
  32. conf/local.conf:CONF_VERSION:LOCALCONF_VERSION:oecore_update_localconf \
  33. conf/site.conf:SCONF_VERSION:SITE_CONF_VERSION:oecore_update_siteconf \
  34. "
  35. SANITY_DIFF_TOOL ?= "meld"
  36. SANITY_LOCALCONF_SAMPLE ?= "${COREBASE}/meta*/conf/templates/default/local.conf.sample"
  37. python oecore_update_localconf() {
  38. # Check we are using a valid local.conf
  39. current_conf = d.getVar('CONF_VERSION')
  40. conf_version = d.getVar('LOCALCONF_VERSION')
  41. failmsg = """Your version of local.conf was generated from an older/newer version of
  42. local.conf.sample and there have been updates made to this file. Please compare the two
  43. files and merge any changes before continuing.
  44. Matching the version numbers will remove this message.
  45. \"${SANITY_DIFF_TOOL} conf/local.conf ${SANITY_LOCALCONF_SAMPLE}\"
  46. is a good way to visualise the changes."""
  47. failmsg = d.expand(failmsg)
  48. raise NotImplementedError(failmsg)
  49. }
  50. SANITY_SITECONF_SAMPLE ?= "${COREBASE}/meta*/conf/templates/default/site.conf.sample"
  51. python oecore_update_siteconf() {
  52. # If we have a site.conf, check it's valid
  53. current_sconf = d.getVar('SCONF_VERSION')
  54. sconf_version = d.getVar('SITE_CONF_VERSION')
  55. failmsg = """Your version of site.conf was generated from an older version of
  56. site.conf.sample and there have been updates made to this file. Please compare the two
  57. files and merge any changes before continuing.
  58. Matching the version numbers will remove this message.
  59. \"${SANITY_DIFF_TOOL} conf/site.conf ${SANITY_SITECONF_SAMPLE}\"
  60. is a good way to visualise the changes."""
  61. failmsg = d.expand(failmsg)
  62. raise NotImplementedError(failmsg)
  63. }
  64. SANITY_BBLAYERCONF_SAMPLE ?= "${COREBASE}/meta*/conf/templates/default/bblayers.conf.sample"
  65. python oecore_update_bblayers() {
  66. # bblayers.conf is out of date, so see if we can resolve that
  67. current_lconf = int(d.getVar('LCONF_VERSION'))
  68. lconf_version = int(d.getVar('LAYER_CONF_VERSION'))
  69. failmsg = """Your version of bblayers.conf has the wrong LCONF_VERSION (has ${LCONF_VERSION}, expecting ${LAYER_CONF_VERSION}).
  70. Please compare your file against bblayers.conf.sample and merge any changes before continuing.
  71. "${SANITY_DIFF_TOOL} conf/bblayers.conf ${SANITY_BBLAYERCONF_SAMPLE}"
  72. is a good way to visualise the changes."""
  73. failmsg = d.expand(failmsg)
  74. if not current_lconf:
  75. raise NotImplementedError(failmsg)
  76. lines = []
  77. if current_lconf < 4:
  78. raise NotImplementedError(failmsg)
  79. bblayers_fn = bblayers_conf_file(d)
  80. lines = sanity_conf_read(bblayers_fn)
  81. if current_lconf == 4 and lconf_version > 4:
  82. topdir_var = '$' + '{TOPDIR}'
  83. index, bbpath_line = sanity_conf_find_line('BBPATH', lines)
  84. if bbpath_line:
  85. start = bbpath_line.find('"')
  86. if start != -1 and (len(bbpath_line) != (start + 1)):
  87. if bbpath_line[start + 1] == '"':
  88. lines[index] = (bbpath_line[:start + 1] +
  89. topdir_var + bbpath_line[start + 1:])
  90. else:
  91. if not topdir_var in bbpath_line:
  92. lines[index] = (bbpath_line[:start + 1] +
  93. topdir_var + ':' + bbpath_line[start + 1:])
  94. else:
  95. raise NotImplementedError(failmsg)
  96. else:
  97. index, bbfiles_line = sanity_conf_find_line('BBFILES', lines)
  98. if bbfiles_line:
  99. lines.insert(index, 'BBPATH = "' + topdir_var + '"\n')
  100. else:
  101. raise NotImplementedError(failmsg)
  102. current_lconf += 1
  103. sanity_conf_update(bblayers_fn, lines, 'LCONF_VERSION', current_lconf)
  104. bb.note("Your conf/bblayers.conf has been automatically updated.")
  105. return
  106. elif current_lconf == 5 and lconf_version > 5:
  107. # Null update, to avoid issues with people switching between poky and other distros
  108. current_lconf = 6
  109. sanity_conf_update(bblayers_fn, lines, 'LCONF_VERSION', current_lconf)
  110. bb.note("Your conf/bblayers.conf has been automatically updated.")
  111. return
  112. status.addresult()
  113. elif current_lconf == 6 and lconf_version > 6:
  114. # Handle rename of meta-yocto -> meta-poky
  115. # This marks the start of separate version numbers but code is needed in OE-Core
  116. # for the migration, one last time.
  117. layers = d.getVar('BBLAYERS').split()
  118. layers = [ os.path.basename(path) for path in layers ]
  119. if 'meta-yocto' in layers:
  120. found = False
  121. while True:
  122. index, meta_yocto_line = sanity_conf_find_line(r'.*meta-yocto[\'"\s\n]', lines)
  123. if meta_yocto_line:
  124. lines[index] = meta_yocto_line.replace('meta-yocto', 'meta-poky')
  125. found = True
  126. else:
  127. break
  128. if not found:
  129. raise NotImplementedError(failmsg)
  130. index, meta_yocto_line = sanity_conf_find_line('LCONF_VERSION.*\n', lines)
  131. if meta_yocto_line:
  132. lines[index] = 'POKY_BBLAYERS_CONF_VERSION = "1"\n'
  133. else:
  134. raise NotImplementedError(failmsg)
  135. with open(bblayers_fn, "w") as f:
  136. f.write(''.join(lines))
  137. bb.note("Your conf/bblayers.conf has been automatically updated.")
  138. return
  139. current_lconf += 1
  140. sanity_conf_update(bblayers_fn, lines, 'LCONF_VERSION', current_lconf)
  141. bb.note("Your conf/bblayers.conf has been automatically updated.")
  142. return
  143. raise NotImplementedError(failmsg)
  144. }
  145. def raise_sanity_error(msg, d, network_error=False):
  146. if d.getVar("SANITY_USE_EVENTS") == "1":
  147. try:
  148. bb.event.fire(bb.event.SanityCheckFailed(msg, network_error), d)
  149. except TypeError:
  150. bb.event.fire(bb.event.SanityCheckFailed(msg), d)
  151. return
  152. bb.fatal(""" OE-core's config sanity checker detected a potential misconfiguration.
  153. Either fix the cause of this error or at your own risk disable the checker (see sanity.conf).
  154. Following is the list of potential problems / advisories:
  155. %s""" % msg)
  156. # Check a single tune for validity.
  157. def check_toolchain_tune(data, tune, multilib):
  158. tune_errors = []
  159. if not tune:
  160. return "No tuning found for %s multilib." % multilib
  161. localdata = bb.data.createCopy(data)
  162. if multilib != "default":
  163. # Apply the overrides so we can look at the details.
  164. overrides = localdata.getVar("OVERRIDES", False) + ":virtclass-multilib-" + multilib
  165. localdata.setVar("OVERRIDES", overrides)
  166. bb.debug(2, "Sanity-checking tuning '%s' (%s) features:" % (tune, multilib))
  167. features = (localdata.getVar("TUNE_FEATURES:tune-%s" % tune) or "").split()
  168. if not features:
  169. return "Tuning '%s' has no defined features, and cannot be used." % tune
  170. valid_tunes = localdata.getVarFlags('TUNEVALID') or {}
  171. conflicts = localdata.getVarFlags('TUNECONFLICTS') or {}
  172. # [doc] is the documentation for the variable, not a real feature
  173. if 'doc' in valid_tunes:
  174. del valid_tunes['doc']
  175. if 'doc' in conflicts:
  176. del conflicts['doc']
  177. for feature in features:
  178. if feature in conflicts:
  179. for conflict in conflicts[feature].split():
  180. if conflict in features:
  181. tune_errors.append("Feature '%s' conflicts with '%s'." %
  182. (feature, conflict))
  183. if feature in valid_tunes:
  184. bb.debug(2, " %s: %s" % (feature, valid_tunes[feature]))
  185. else:
  186. tune_errors.append("Feature '%s' is not defined." % feature)
  187. if tune_errors:
  188. return "Tuning '%s' has the following errors:\n" % tune + '\n'.join(tune_errors)
  189. def check_toolchain(data):
  190. tune_error_set = []
  191. deftune = data.getVar("DEFAULTTUNE")
  192. tune_errors = check_toolchain_tune(data, deftune, 'default')
  193. if tune_errors:
  194. tune_error_set.append(tune_errors)
  195. multilibs = (data.getVar("MULTILIB_VARIANTS") or "").split()
  196. global_multilibs = (data.getVar("MULTILIB_GLOBAL_VARIANTS") or "").split()
  197. if multilibs:
  198. seen_libs = []
  199. seen_tunes = []
  200. for lib in multilibs:
  201. if lib in seen_libs:
  202. tune_error_set.append("The multilib '%s' appears more than once." % lib)
  203. else:
  204. seen_libs.append(lib)
  205. if not lib in global_multilibs:
  206. tune_error_set.append("Multilib %s is not present in MULTILIB_GLOBAL_VARIANTS" % lib)
  207. tune = data.getVar("DEFAULTTUNE:virtclass-multilib-%s" % lib)
  208. if tune in seen_tunes:
  209. tune_error_set.append("The tuning '%s' appears in more than one multilib." % tune)
  210. else:
  211. seen_libs.append(tune)
  212. if tune == deftune:
  213. tune_error_set.append("Multilib '%s' (%s) is also the default tuning." % (lib, deftune))
  214. else:
  215. tune_errors = check_toolchain_tune(data, tune, lib)
  216. if tune_errors:
  217. tune_error_set.append(tune_errors)
  218. if tune_error_set:
  219. return "Toolchain tunings invalid:\n" + '\n'.join(tune_error_set) + "\n"
  220. return ""
  221. def check_conf_exists(fn, data):
  222. bbpath = []
  223. fn = data.expand(fn)
  224. vbbpath = data.getVar("BBPATH", False)
  225. if vbbpath:
  226. bbpath += vbbpath.split(":")
  227. for p in bbpath:
  228. currname = os.path.join(data.expand(p), fn)
  229. if os.access(currname, os.R_OK):
  230. return True
  231. return False
  232. def check_create_long_filename(filepath, pathname):
  233. import string, random
  234. testfile = os.path.join(filepath, ''.join(random.choice(string.ascii_letters) for x in range(200)))
  235. try:
  236. if not os.path.exists(filepath):
  237. bb.utils.mkdirhier(filepath)
  238. f = open(testfile, "w")
  239. f.close()
  240. os.remove(testfile)
  241. except IOError as e:
  242. import errno
  243. err, strerror = e.args
  244. if err == errno.ENAMETOOLONG:
  245. return "Failed to create a file with a long name in %s. Please use a filesystem that does not unreasonably limit filename length.\n" % pathname
  246. else:
  247. return "Failed to create a file in %s: %s.\n" % (pathname, strerror)
  248. except OSError as e:
  249. errno, strerror = e.args
  250. return "Failed to create %s directory in which to run long name sanity check: %s.\n" % (pathname, strerror)
  251. return ""
  252. def check_path_length(filepath, pathname, limit):
  253. if len(filepath) > limit:
  254. return "The length of %s is longer than %s, this would cause unexpected errors, please use a shorter path.\n" % (pathname, limit)
  255. return ""
  256. def get_filesystem_id(path):
  257. import subprocess
  258. try:
  259. return subprocess.check_output(["stat", "-f", "-c", "%t", path]).decode('utf-8').strip()
  260. except subprocess.CalledProcessError:
  261. bb.warn("Can't get filesystem id of: %s" % path)
  262. return None
  263. # Check that the path isn't located on nfs.
  264. def check_not_nfs(path, name):
  265. # The nfs' filesystem id is 6969
  266. if get_filesystem_id(path) == "6969":
  267. return "The %s: %s can't be located on nfs.\n" % (name, path)
  268. return ""
  269. # Check that the path is on a case-sensitive file system
  270. def check_case_sensitive(path, name):
  271. import tempfile
  272. with tempfile.NamedTemporaryFile(prefix='TmP', dir=path) as tmp_file:
  273. if os.path.exists(tmp_file.name.lower()):
  274. return "The %s (%s) can't be on a case-insensitive file system.\n" % (name, path)
  275. return ""
  276. # Check that path isn't a broken symlink
  277. def check_symlink(lnk, data):
  278. if os.path.islink(lnk) and not os.path.exists(lnk):
  279. raise_sanity_error("%s is a broken symlink." % lnk, data)
  280. def check_connectivity(d):
  281. # URI's to check can be set in the CONNECTIVITY_CHECK_URIS variable
  282. # using the same syntax as for SRC_URI. If the variable is not set
  283. # the check is skipped
  284. test_uris = (d.getVar('CONNECTIVITY_CHECK_URIS') or "").split()
  285. retval = ""
  286. bbn = d.getVar('BB_NO_NETWORK')
  287. if bbn not in (None, '0', '1'):
  288. return 'BB_NO_NETWORK should be "0" or "1", but it is "%s"' % bbn
  289. # Only check connectivity if network enabled and the
  290. # CONNECTIVITY_CHECK_URIS are set
  291. network_enabled = not (bbn == '1')
  292. check_enabled = len(test_uris)
  293. if check_enabled and network_enabled:
  294. # Take a copy of the data store and unset MIRRORS and PREMIRRORS
  295. data = bb.data.createCopy(d)
  296. data.delVar('PREMIRRORS')
  297. data.delVar('MIRRORS')
  298. try:
  299. fetcher = bb.fetch2.Fetch(test_uris, data)
  300. fetcher.checkstatus()
  301. except Exception as err:
  302. # Allow the message to be configured so that users can be
  303. # pointed to a support mechanism.
  304. msg = data.getVar('CONNECTIVITY_CHECK_MSG') or ""
  305. if len(msg) == 0:
  306. msg = "%s.\n" % err
  307. msg += " Please ensure your host's network is configured correctly.\n"
  308. msg += " Please ensure CONNECTIVITY_CHECK_URIS is correct and specified URIs are available.\n"
  309. msg += " If your ISP or network is blocking the above URL,\n"
  310. msg += " try with another domain name, for example by setting:\n"
  311. msg += " CONNECTIVITY_CHECK_URIS = \"https://www.example.com/\""
  312. msg += " You could also set BB_NO_NETWORK = \"1\" to disable network\n"
  313. msg += " access if all required sources are on local disk.\n"
  314. retval = msg
  315. return retval
  316. def check_supported_distro(sanity_data):
  317. from fnmatch import fnmatch
  318. tested_distros = sanity_data.getVar('SANITY_TESTED_DISTROS')
  319. if not tested_distros:
  320. return
  321. try:
  322. distro = oe.lsb.distro_identifier()
  323. except Exception:
  324. distro = None
  325. if not distro:
  326. bb.warn('Host distribution could not be determined; you may possibly experience unexpected failures. It is recommended that you use a tested distribution.')
  327. for supported in [x.strip() for x in tested_distros.split('\\n')]:
  328. if fnmatch(distro, supported):
  329. return
  330. bb.warn('Host distribution "%s" has not been validated with this version of the build system; you may possibly experience unexpected failures. It is recommended that you use a tested distribution.' % distro)
  331. # Checks we should only make if MACHINE is set correctly
  332. def check_sanity_validmachine(sanity_data):
  333. messages = ""
  334. # Check TUNE_ARCH is set
  335. if sanity_data.getVar('TUNE_ARCH') == 'INVALID':
  336. messages = messages + 'TUNE_ARCH is unset. Please ensure your MACHINE configuration includes a valid tune configuration file which will set this correctly.\n'
  337. # Check TARGET_OS is set
  338. if sanity_data.getVar('TARGET_OS') == 'INVALID':
  339. messages = messages + 'Please set TARGET_OS directly, or choose a MACHINE or DISTRO that does so.\n'
  340. # Check that we don't have duplicate entries in PACKAGE_ARCHS & that TUNE_PKGARCH is in PACKAGE_ARCHS
  341. pkgarchs = sanity_data.getVar('PACKAGE_ARCHS')
  342. tunepkg = sanity_data.getVar('TUNE_PKGARCH')
  343. defaulttune = sanity_data.getVar('DEFAULTTUNE')
  344. tunefound = False
  345. seen = {}
  346. dups = []
  347. for pa in pkgarchs.split():
  348. if seen.get(pa, 0) == 1:
  349. dups.append(pa)
  350. else:
  351. seen[pa] = 1
  352. if pa == tunepkg:
  353. tunefound = True
  354. if len(dups):
  355. messages = messages + "Error, the PACKAGE_ARCHS variable contains duplicates. The following archs are listed more than once: %s" % " ".join(dups)
  356. if tunefound == False:
  357. messages = messages + "Error, the PACKAGE_ARCHS variable (%s) for DEFAULTTUNE (%s) does not contain TUNE_PKGARCH (%s)." % (pkgarchs, defaulttune, tunepkg)
  358. return messages
  359. # Patch before 2.7 can't handle all the features in git-style diffs. Some
  360. # patches may incorrectly apply, and others won't apply at all.
  361. def check_patch_version(sanity_data):
  362. import re, subprocess
  363. try:
  364. result = subprocess.check_output(["patch", "--version"], stderr=subprocess.STDOUT).decode('utf-8')
  365. version = re.search(r"[0-9.]+", result.splitlines()[0]).group()
  366. if bb.utils.vercmp_string_op(version, "2.7", "<"):
  367. return "Your version of patch is older than 2.7 and has bugs which will break builds. Please install a newer version of patch.\n"
  368. else:
  369. return None
  370. except subprocess.CalledProcessError as e:
  371. return "Unable to execute patch --version, exit code %d:\n%s\n" % (e.returncode, e.output)
  372. # Glibc needs make 4.0 or later, we may as well match at this point
  373. def check_make_version(sanity_data):
  374. import subprocess
  375. try:
  376. result = subprocess.check_output(['make', '--version'], stderr=subprocess.STDOUT).decode('utf-8')
  377. except subprocess.CalledProcessError as e:
  378. return "Unable to execute make --version, exit code %d\n%s\n" % (e.returncode, e.output)
  379. version = result.split()[2]
  380. if bb.utils.vercmp_string_op(version, "4.0", "<"):
  381. return "Please install a make version of 4.0 or later.\n"
  382. if bb.utils.vercmp_string_op(version, "4.2.1", "=="):
  383. distro = oe.lsb.distro_identifier()
  384. if "ubuntu" in distro or "debian" in distro or "linuxmint" in distro:
  385. return None
  386. return "make version 4.2.1 is known to have issues on Centos/OpenSUSE and other non-Ubuntu systems. Please use a buildtools-make-tarball or a newer version of make.\n"
  387. return None
  388. # Check if we're running on WSL (Windows Subsystem for Linux).
  389. # WSLv1 is known not to work but WSLv2 should work properly as
  390. # long as the VHDX file is optimized often, let the user know
  391. # upfront.
  392. # More information on installing WSLv2 at:
  393. # https://docs.microsoft.com/en-us/windows/wsl/wsl2-install
  394. def check_wsl(d):
  395. with open("/proc/version", "r") as f:
  396. verdata = f.readlines()
  397. for l in verdata:
  398. if "Microsoft" in l:
  399. return "OpenEmbedded doesn't work under WSLv1, please upgrade to WSLv2 if you want to run builds on Windows"
  400. elif "microsoft" in l:
  401. bb.warn("You are running bitbake under WSLv2, this works properly but you should optimize your VHDX file eventually to avoid running out of storage space")
  402. return None
  403. # Require at least gcc version 7.5.
  404. #
  405. # This can be fixed on CentOS-7 with devtoolset-6+
  406. # https://www.softwarecollections.org/en/scls/rhscl/devtoolset-6/
  407. #
  408. # A less invasive fix is with scripts/install-buildtools (or with user
  409. # built buildtools-extended-tarball)
  410. #
  411. def check_gcc_version(sanity_data):
  412. import subprocess
  413. build_cc, version = oe.utils.get_host_compiler_version(sanity_data)
  414. if build_cc.strip() == "gcc":
  415. if bb.utils.vercmp_string_op(version, "7.5", "<"):
  416. return "Your version of gcc is older than 7.5 and will break builds. Please install a newer version of gcc (you could use the project's buildtools-extended-tarball or use scripts/install-buildtools).\n"
  417. return None
  418. # Tar version 1.24 and onwards handle overwriting symlinks correctly
  419. # but earlier versions do not; this needs to work properly for sstate
  420. # Version 1.28 is needed so opkg-build works correctly when reproducibile builds are enabled
  421. def check_tar_version(sanity_data):
  422. import subprocess
  423. try:
  424. result = subprocess.check_output(["tar", "--version"], stderr=subprocess.STDOUT).decode('utf-8')
  425. except subprocess.CalledProcessError as e:
  426. return "Unable to execute tar --version, exit code %d\n%s\n" % (e.returncode, e.output)
  427. version = result.split()[3]
  428. if bb.utils.vercmp_string_op(version, "1.28", "<"):
  429. return "Your version of tar is older than 1.28 and does not have the support needed to enable reproducible builds. Please install a newer version of tar (you could use the project's buildtools-tarball from our last release or use scripts/install-buildtools).\n"
  430. try:
  431. result = subprocess.check_output(["tar", "--help"], stderr=subprocess.STDOUT).decode('utf-8')
  432. if "--xattrs" not in result:
  433. return "Your tar doesn't support --xattrs, please use GNU tar.\n"
  434. except subprocess.CalledProcessError as e:
  435. return "Unable to execute tar --help, exit code %d\n%s\n" % (e.returncode, e.output)
  436. return None
  437. # We use git parameters and functionality only found in 1.7.8 or later
  438. # The kernel tools assume git >= 1.8.3.1 (verified needed > 1.7.9.5) see #6162
  439. # The git fetcher also had workarounds for git < 1.7.9.2 which we've dropped
  440. def check_git_version(sanity_data):
  441. import subprocess
  442. try:
  443. result = subprocess.check_output(["git", "--version"], stderr=subprocess.DEVNULL).decode('utf-8')
  444. except subprocess.CalledProcessError as e:
  445. return "Unable to execute git --version, exit code %d\n%s\n" % (e.returncode, e.output)
  446. version = result.split()[2]
  447. if bb.utils.vercmp_string_op(version, "1.8.3.1", "<"):
  448. return "Your version of git is older than 1.8.3.1 and has bugs which will break builds. Please install a newer version of git.\n"
  449. return None
  450. # Check the required perl modules which may not be installed by default
  451. def check_perl_modules(sanity_data):
  452. import subprocess
  453. ret = ""
  454. modules = ( "Text::ParseWords", "Thread::Queue", "Data::Dumper" )
  455. errresult = ''
  456. for m in modules:
  457. try:
  458. subprocess.check_output(["perl", "-e", "use %s" % m])
  459. except subprocess.CalledProcessError as e:
  460. errresult += bytes.decode(e.output)
  461. ret += "%s " % m
  462. if ret:
  463. return "Required perl module(s) not found: %s\n\n%s\n" % (ret, errresult)
  464. return None
  465. def sanity_check_conffiles(d):
  466. funcs = d.getVar('BBLAYERS_CONF_UPDATE_FUNCS').split()
  467. for func in funcs:
  468. conffile, current_version, required_version, func = func.split(":")
  469. if check_conf_exists(conffile, d) and d.getVar(current_version) is not None and \
  470. d.getVar(current_version) != d.getVar(required_version):
  471. try:
  472. bb.build.exec_func(func, d)
  473. except NotImplementedError as e:
  474. bb.fatal(str(e))
  475. d.setVar("BB_INVALIDCONF", True)
  476. def drop_v14_cross_builds(d):
  477. import glob
  478. indexes = glob.glob(d.expand("${SSTATE_MANIFESTS}/index-${BUILD_ARCH}_*"))
  479. for i in indexes:
  480. with open(i, "r") as f:
  481. lines = f.readlines()
  482. for l in reversed(lines):
  483. try:
  484. (stamp, manifest, workdir) = l.split()
  485. except ValueError:
  486. bb.fatal("Invalid line '%s' in sstate manifest '%s'" % (l, i))
  487. for m in glob.glob(manifest + ".*"):
  488. if m.endswith(".postrm"):
  489. continue
  490. sstate_clean_manifest(m, d)
  491. bb.utils.remove(stamp + "*")
  492. bb.utils.remove(workdir, recurse = True)
  493. def sanity_handle_abichanges(status, d):
  494. #
  495. # Check the 'ABI' of TMPDIR
  496. #
  497. import subprocess
  498. current_abi = d.getVar('OELAYOUT_ABI')
  499. abifile = d.getVar('SANITY_ABIFILE')
  500. if os.path.exists(abifile):
  501. with open(abifile, "r") as f:
  502. abi = f.read().strip()
  503. if not abi.isdigit():
  504. with open(abifile, "w") as f:
  505. f.write(current_abi)
  506. elif int(abi) <= 11 and current_abi == "12":
  507. status.addresult("The layout of TMPDIR changed for Recipe Specific Sysroots.\nConversion doesn't make sense and this change will rebuild everything so please delete TMPDIR (%s).\n" % d.getVar("TMPDIR"))
  508. elif int(abi) <= 13 and current_abi == "14":
  509. status.addresult("TMPDIR changed to include path filtering from the pseudo database.\nIt is recommended to use a clean TMPDIR with the new pseudo path filtering so TMPDIR (%s) would need to be removed to continue.\n" % d.getVar("TMPDIR"))
  510. elif int(abi) == 14 and current_abi == "15":
  511. drop_v14_cross_builds(d)
  512. with open(abifile, "w") as f:
  513. f.write(current_abi)
  514. elif (abi != current_abi):
  515. # Code to convert from one ABI to another could go here if possible.
  516. status.addresult("Error, TMPDIR has changed its layout version number (%s to %s) and you need to either rebuild, revert or adjust it at your own risk.\n" % (abi, current_abi))
  517. else:
  518. with open(abifile, "w") as f:
  519. f.write(current_abi)
  520. def check_sanity_sstate_dir_change(sstate_dir, data):
  521. # Sanity checks to be done when the value of SSTATE_DIR changes
  522. # Check that SSTATE_DIR isn't on a filesystem with limited filename length (eg. eCryptFS)
  523. testmsg = ""
  524. if sstate_dir != "":
  525. testmsg = check_create_long_filename(sstate_dir, "SSTATE_DIR")
  526. # If we don't have permissions to SSTATE_DIR, suggest the user set it as an SSTATE_MIRRORS
  527. try:
  528. err = testmsg.split(': ')[1].strip()
  529. if err == "Permission denied.":
  530. testmsg = testmsg + "You could try using %s in SSTATE_MIRRORS rather than as an SSTATE_CACHE.\n" % (sstate_dir)
  531. except IndexError:
  532. pass
  533. return testmsg
  534. def check_sanity_version_change(status, d):
  535. # Sanity checks to be done when SANITY_VERSION or NATIVELSBSTRING changes
  536. # In other words, these tests run once in a given build directory and then
  537. # never again until the sanity version or host distrubution id/version changes.
  538. # Check the python install is complete. Examples that are often removed in
  539. # minimal installations: glib-2.0-natives requries # xml.parsers.expat and icu
  540. # requires distutils.sysconfig.
  541. try:
  542. import xml.parsers.expat
  543. import distutils.sysconfig
  544. except ImportError as e:
  545. status.addresult('Your Python 3 is not a full install. Please install the module %s (see the Getting Started guide for further information).\n' % e.name)
  546. status.addresult(check_gcc_version(d))
  547. status.addresult(check_make_version(d))
  548. status.addresult(check_patch_version(d))
  549. status.addresult(check_tar_version(d))
  550. status.addresult(check_git_version(d))
  551. status.addresult(check_perl_modules(d))
  552. status.addresult(check_wsl(d))
  553. missing = ""
  554. if not check_app_exists("${MAKE}", d):
  555. missing = missing + "GNU make,"
  556. if not check_app_exists('${BUILD_CC}', d):
  557. missing = missing + "C Compiler (%s)," % d.getVar("BUILD_CC")
  558. if not check_app_exists('${BUILD_CXX}', d):
  559. missing = missing + "C++ Compiler (%s)," % d.getVar("BUILD_CXX")
  560. required_utilities = d.getVar('SANITY_REQUIRED_UTILITIES')
  561. for util in required_utilities.split():
  562. if not check_app_exists(util, d):
  563. missing = missing + "%s," % util
  564. if missing:
  565. missing = missing.rstrip(',')
  566. status.addresult("Please install the following missing utilities: %s\n" % missing)
  567. assume_provided = d.getVar('ASSUME_PROVIDED').split()
  568. # Check user doesn't have ASSUME_PROVIDED = instead of += in local.conf
  569. if "diffstat-native" not in assume_provided:
  570. status.addresult('Please use ASSUME_PROVIDED +=, not ASSUME_PROVIDED = in your local.conf\n')
  571. # Check that TMPDIR isn't on a filesystem with limited filename length (eg. eCryptFS)
  572. import stat
  573. tmpdir = d.getVar('TMPDIR')
  574. status.addresult(check_create_long_filename(tmpdir, "TMPDIR"))
  575. tmpdirmode = os.stat(tmpdir).st_mode
  576. if (tmpdirmode & stat.S_ISGID):
  577. status.addresult("TMPDIR is setgid, please don't build in a setgid directory")
  578. if (tmpdirmode & stat.S_ISUID):
  579. status.addresult("TMPDIR is setuid, please don't build in a setuid directory")
  580. # Check that a user isn't building in a path in PSEUDO_IGNORE_PATHS
  581. pseudoignorepaths = d.getVar('PSEUDO_IGNORE_PATHS', expand=True).split(",")
  582. workdir = d.getVar('WORKDIR', expand=True)
  583. for i in pseudoignorepaths:
  584. if i and workdir.startswith(i):
  585. status.addresult("You are building in a path included in PSEUDO_IGNORE_PATHS " + str(i) + " please locate the build outside this path.\n")
  586. # Check if PSEUDO_IGNORE_PATHS and and paths under pseudo control overlap
  587. pseudoignorepaths = d.getVar('PSEUDO_IGNORE_PATHS', expand=True).split(",")
  588. pseudo_control_dir = "${D},${PKGD},${PKGDEST},${IMAGEROOTFS},${SDK_OUTPUT}"
  589. pseudocontroldir = d.expand(pseudo_control_dir).split(",")
  590. for i in pseudoignorepaths:
  591. for j in pseudocontroldir:
  592. if i and j:
  593. if j.startswith(i):
  594. status.addresult("A path included in PSEUDO_IGNORE_PATHS " + str(i) + " and the path " + str(j) + " overlap and this will break pseudo permission and ownership tracking. Please set the path " + str(j) + " to a different directory which does not overlap with pseudo controlled directories. \n")
  595. # Some third-party software apparently relies on chmod etc. being suid root (!!)
  596. import stat
  597. suid_check_bins = "chown chmod mknod".split()
  598. for bin_cmd in suid_check_bins:
  599. bin_path = bb.utils.which(os.environ["PATH"], bin_cmd)
  600. if bin_path:
  601. bin_stat = os.stat(bin_path)
  602. if bin_stat.st_uid == 0 and bin_stat.st_mode & stat.S_ISUID:
  603. status.addresult('%s has the setuid bit set. This interferes with pseudo and may cause other issues that break the build process.\n' % bin_path)
  604. # Check that we can fetch from various network transports
  605. netcheck = check_connectivity(d)
  606. status.addresult(netcheck)
  607. if netcheck:
  608. status.network_error = True
  609. nolibs = d.getVar('NO32LIBS')
  610. if not nolibs:
  611. lib32path = '/lib'
  612. if os.path.exists('/lib64') and ( os.path.islink('/lib64') or os.path.islink('/lib') ):
  613. lib32path = '/lib32'
  614. if os.path.exists('%s/libc.so.6' % lib32path) and not os.path.exists('/usr/include/gnu/stubs-32.h'):
  615. status.addresult("You have a 32-bit libc, but no 32-bit headers. You must install the 32-bit libc headers.\n")
  616. bbpaths = d.getVar('BBPATH').split(":")
  617. if ("." in bbpaths or "./" in bbpaths or "" in bbpaths):
  618. status.addresult("BBPATH references the current directory, either through " \
  619. "an empty entry, a './' or a '.'.\n\t This is unsafe and means your "\
  620. "layer configuration is adding empty elements to BBPATH.\n\t "\
  621. "Please check your layer.conf files and other BBPATH " \
  622. "settings to remove the current working directory " \
  623. "references.\n" \
  624. "Parsed BBPATH is" + str(bbpaths));
  625. oes_bb_conf = d.getVar( 'OES_BITBAKE_CONF')
  626. if not oes_bb_conf:
  627. status.addresult('You are not using the OpenEmbedded version of conf/bitbake.conf. This means your environment is misconfigured, in particular check BBPATH.\n')
  628. # The length of TMPDIR can't be longer than 410
  629. status.addresult(check_path_length(tmpdir, "TMPDIR", 410))
  630. # Check that TMPDIR isn't located on nfs
  631. status.addresult(check_not_nfs(tmpdir, "TMPDIR"))
  632. # Check for case-insensitive file systems (such as Linux in Docker on
  633. # macOS with default HFS+ file system)
  634. status.addresult(check_case_sensitive(tmpdir, "TMPDIR"))
  635. def sanity_check_locale(d):
  636. """
  637. Currently bitbake switches locale to en_US.UTF-8 so check that this locale actually exists.
  638. """
  639. import locale
  640. try:
  641. locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
  642. except locale.Error:
  643. raise_sanity_error("Your system needs to support the en_US.UTF-8 locale.", d)
  644. def check_sanity_everybuild(status, d):
  645. import os, stat
  646. # Sanity tests which test the users environment so need to run at each build (or are so cheap
  647. # it makes sense to always run them.
  648. if 0 == os.getuid():
  649. raise_sanity_error("Do not use Bitbake as root.", d)
  650. # Check the Python version, we now have a minimum of Python 3.6
  651. import sys
  652. if sys.hexversion < 0x030600F0:
  653. status.addresult('The system requires at least Python 3.6 to run. Please update your Python interpreter.\n')
  654. # Check the bitbake version meets minimum requirements
  655. minversion = d.getVar('BB_MIN_VERSION')
  656. if bb.utils.vercmp_string_op(bb.__version__, minversion, "<"):
  657. status.addresult('Bitbake version %s is required and version %s was found\n' % (minversion, bb.__version__))
  658. sanity_check_locale(d)
  659. paths = d.getVar('PATH').split(":")
  660. if "." in paths or "./" in paths or "" in paths:
  661. status.addresult("PATH contains '.', './' or '' (empty element), which will break the build, please remove this.\nParsed PATH is " + str(paths) + "\n")
  662. #Check if bitbake is present in PATH environment variable
  663. bb_check = bb.utils.which(d.getVar('PATH'), 'bitbake')
  664. if not bb_check:
  665. bb.warn("bitbake binary is not found in PATH, did you source the script?")
  666. # Check whether 'inherit' directive is found (used for a class to inherit)
  667. # in conf file it's supposed to be uppercase INHERIT
  668. inherit = d.getVar('inherit')
  669. if inherit:
  670. status.addresult("Please don't use inherit directive in your local.conf. The directive is supposed to be used in classes and recipes only to inherit of bbclasses. Here INHERIT should be used.\n")
  671. # Check that the DISTRO is valid, if set
  672. # need to take into account DISTRO renaming DISTRO
  673. distro = d.getVar('DISTRO')
  674. if distro and distro != "nodistro":
  675. if not ( check_conf_exists("conf/distro/${DISTRO}.conf", d) or check_conf_exists("conf/distro/include/${DISTRO}.inc", d) ):
  676. status.addresult("DISTRO '%s' not found. Please set a valid DISTRO in your local.conf\n" % d.getVar("DISTRO"))
  677. # Check that these variables don't use tilde-expansion as we don't do that
  678. for v in ("TMPDIR", "DL_DIR", "SSTATE_DIR"):
  679. if d.getVar(v).startswith("~"):
  680. status.addresult("%s uses ~ but Bitbake will not expand this, use an absolute path or variables." % v)
  681. # Check that DL_DIR is set, exists and is writable. In theory, we should never even hit the check if DL_DIR isn't
  682. # set, since so much relies on it being set.
  683. dldir = d.getVar('DL_DIR')
  684. if not dldir:
  685. status.addresult("DL_DIR is not set. Your environment is misconfigured, check that DL_DIR is set, and if the directory exists, that it is writable. \n")
  686. if os.path.exists(dldir) and not os.access(dldir, os.W_OK):
  687. status.addresult("DL_DIR: %s exists but you do not appear to have write access to it. \n" % dldir)
  688. check_symlink(dldir, d)
  689. # Check that the MACHINE is valid, if it is set
  690. machinevalid = True
  691. if d.getVar('MACHINE'):
  692. if not check_conf_exists("conf/machine/${MACHINE}.conf", d):
  693. status.addresult('MACHINE=%s is invalid. Please set a valid MACHINE in your local.conf, environment or other configuration file.\n' % (d.getVar('MACHINE')))
  694. machinevalid = False
  695. else:
  696. status.addresult(check_sanity_validmachine(d))
  697. else:
  698. status.addresult('Please set a MACHINE in your local.conf or environment\n')
  699. machinevalid = False
  700. if machinevalid:
  701. status.addresult(check_toolchain(d))
  702. # Check that the SDKMACHINE is valid, if it is set
  703. if d.getVar('SDKMACHINE'):
  704. if not check_conf_exists("conf/machine-sdk/${SDKMACHINE}.conf", d):
  705. status.addresult('Specified SDKMACHINE value is not valid\n')
  706. elif d.getVar('SDK_ARCH', False) == "${BUILD_ARCH}":
  707. status.addresult('SDKMACHINE is set, but SDK_ARCH has not been changed as a result - SDKMACHINE may have been set too late (e.g. in the distro configuration)\n')
  708. # If SDK_VENDOR looks like "-my-sdk" then the triples are badly formed so fail early
  709. sdkvendor = d.getVar("SDK_VENDOR")
  710. if not (sdkvendor.startswith("-") and sdkvendor.count("-") == 1):
  711. status.addresult("SDK_VENDOR should be of the form '-foosdk' with a single dash; found '%s'\n" % sdkvendor)
  712. check_supported_distro(d)
  713. omask = os.umask(0o022)
  714. if omask & 0o755:
  715. status.addresult("Please use a umask which allows a+rx and u+rwx\n")
  716. os.umask(omask)
  717. if d.getVar('TARGET_ARCH') == "arm":
  718. # This path is no longer user-readable in modern (very recent) Linux
  719. try:
  720. if os.path.exists("/proc/sys/vm/mmap_min_addr"):
  721. f = open("/proc/sys/vm/mmap_min_addr", "r")
  722. try:
  723. if (int(f.read().strip()) > 65536):
  724. status.addresult("/proc/sys/vm/mmap_min_addr is not <= 65536. This will cause problems with qemu so please fix the value (as root).\n\nTo fix this in later reboots, set vm.mmap_min_addr = 65536 in /etc/sysctl.conf.\n")
  725. finally:
  726. f.close()
  727. except:
  728. pass
  729. for checkdir in ['COREBASE', 'TMPDIR']:
  730. val = d.getVar(checkdir)
  731. if val.find('..') != -1:
  732. status.addresult("Error, you have '..' in your %s directory path. Please ensure the variable contains an absolute path as this can break some recipe builds in obtuse ways." % checkdir)
  733. if val.find('+') != -1:
  734. status.addresult("Error, you have an invalid character (+) in your %s directory path. Please move the installation to a directory which doesn't include any + characters." % checkdir)
  735. if val.find('@') != -1:
  736. status.addresult("Error, you have an invalid character (@) in your %s directory path. Please move the installation to a directory which doesn't include any @ characters." % checkdir)
  737. if val.find(' ') != -1:
  738. status.addresult("Error, you have a space in your %s directory path. Please move the installation to a directory which doesn't include a space since autotools doesn't support this." % checkdir)
  739. if val.find('%') != -1:
  740. status.addresult("Error, you have an invalid character (%) in your %s directory path which causes problems with python string formatting. Please move the installation to a directory which doesn't include any % characters." % checkdir)
  741. # Check the format of MIRRORS, PREMIRRORS and SSTATE_MIRRORS
  742. import re
  743. mirror_vars = ['MIRRORS', 'PREMIRRORS', 'SSTATE_MIRRORS']
  744. protocols = ['http', 'ftp', 'file', 'https', \
  745. 'git', 'gitsm', 'hg', 'osc', 'p4', 'svn', \
  746. 'bzr', 'cvs', 'npm', 'sftp', 'ssh', 's3', 'az', 'ftps', 'crate']
  747. for mirror_var in mirror_vars:
  748. mirrors = (d.getVar(mirror_var) or '').replace('\\n', ' ').split()
  749. # Split into pairs
  750. if len(mirrors) % 2 != 0:
  751. bb.warn('Invalid mirror variable value for %s: %s, should contain paired members.' % (mirror_var, str(mirrors)))
  752. continue
  753. mirrors = list(zip(*[iter(mirrors)]*2))
  754. for mirror_entry in mirrors:
  755. pattern, mirror = mirror_entry
  756. decoded = bb.fetch2.decodeurl(pattern)
  757. try:
  758. pattern_scheme = re.compile(decoded[0])
  759. except re.error as exc:
  760. bb.warn('Invalid scheme regex (%s) in %s; %s' % (pattern, mirror_var, mirror_entry))
  761. continue
  762. if not any(pattern_scheme.match(protocol) for protocol in protocols):
  763. bb.warn('Invalid protocol (%s) in %s: %s' % (decoded[0], mirror_var, mirror_entry))
  764. continue
  765. if not any(mirror.startswith(protocol + '://') for protocol in protocols):
  766. bb.warn('Invalid protocol in %s: %s' % (mirror_var, mirror_entry))
  767. continue
  768. if mirror.startswith('file://'):
  769. import urllib
  770. check_symlink(urllib.parse.urlparse(mirror).path, d)
  771. # SSTATE_MIRROR ends with a /PATH string
  772. if mirror.endswith('/PATH'):
  773. # remove /PATH$ from SSTATE_MIRROR to get a working
  774. # base directory path
  775. mirror_base = urllib.parse.urlparse(mirror[:-1*len('/PATH')]).path
  776. check_symlink(mirror_base, d)
  777. # Check sstate mirrors aren't being used with a local hash server and no remote
  778. hashserv = d.getVar("BB_HASHSERVE")
  779. if d.getVar("SSTATE_MIRRORS") and hashserv and hashserv.startswith("unix://") and not d.getVar("BB_HASHSERVE_UPSTREAM"):
  780. bb.warn("You are using a local hash equivalence server but have configured an sstate mirror. This will likely mean no sstate will match from the mirror. You may wish to disable the hash equivalence use (BB_HASHSERVE), or use a hash equivalence server alongside the sstate mirror.")
  781. # Check that TMPDIR hasn't changed location since the last time we were run
  782. tmpdir = d.getVar('TMPDIR')
  783. checkfile = os.path.join(tmpdir, "saved_tmpdir")
  784. if os.path.exists(checkfile):
  785. with open(checkfile, "r") as f:
  786. saved_tmpdir = f.read().strip()
  787. if (saved_tmpdir != tmpdir):
  788. status.addresult("Error, TMPDIR has changed location. You need to either move it back to %s or delete it and rebuild\n" % saved_tmpdir)
  789. else:
  790. bb.utils.mkdirhier(tmpdir)
  791. # Remove setuid, setgid and sticky bits from TMPDIR
  792. try:
  793. os.chmod(tmpdir, os.stat(tmpdir).st_mode & ~ stat.S_ISUID)
  794. os.chmod(tmpdir, os.stat(tmpdir).st_mode & ~ stat.S_ISGID)
  795. os.chmod(tmpdir, os.stat(tmpdir).st_mode & ~ stat.S_ISVTX)
  796. except OSError as exc:
  797. bb.warn("Unable to chmod TMPDIR: %s" % exc)
  798. with open(checkfile, "w") as f:
  799. f.write(tmpdir)
  800. # If /bin/sh is a symlink, check that it points to dash or bash
  801. if os.path.islink('/bin/sh'):
  802. real_sh = os.path.realpath('/bin/sh')
  803. # Due to update-alternatives, the shell name may take various
  804. # forms, such as /bin/dash, bin/bash, /bin/bash.bash ...
  805. if '/dash' not in real_sh and '/bash' not in real_sh:
  806. status.addresult("Error, /bin/sh links to %s, must be dash or bash\n" % real_sh)
  807. def check_sanity(sanity_data):
  808. class SanityStatus(object):
  809. def __init__(self):
  810. self.messages = ""
  811. self.network_error = False
  812. def addresult(self, message):
  813. if message:
  814. self.messages = self.messages + message
  815. status = SanityStatus()
  816. tmpdir = sanity_data.getVar('TMPDIR')
  817. sstate_dir = sanity_data.getVar('SSTATE_DIR')
  818. check_symlink(sstate_dir, sanity_data)
  819. # Check saved sanity info
  820. last_sanity_version = 0
  821. last_tmpdir = ""
  822. last_sstate_dir = ""
  823. last_nativelsbstr = ""
  824. sanityverfile = sanity_data.expand("${TOPDIR}/cache/sanity_info")
  825. if os.path.exists(sanityverfile):
  826. with open(sanityverfile, 'r') as f:
  827. for line in f:
  828. if line.startswith('SANITY_VERSION'):
  829. last_sanity_version = int(line.split()[1])
  830. if line.startswith('TMPDIR'):
  831. last_tmpdir = line.split()[1]
  832. if line.startswith('SSTATE_DIR'):
  833. last_sstate_dir = line.split()[1]
  834. if line.startswith('NATIVELSBSTRING'):
  835. last_nativelsbstr = line.split()[1]
  836. check_sanity_everybuild(status, sanity_data)
  837. sanity_version = int(sanity_data.getVar('SANITY_VERSION') or 1)
  838. network_error = False
  839. # NATIVELSBSTRING var may have been overridden with "universal", so
  840. # get actual host distribution id and version
  841. nativelsbstr = lsb_distro_identifier(sanity_data)
  842. if last_sanity_version < sanity_version or last_nativelsbstr != nativelsbstr:
  843. check_sanity_version_change(status, sanity_data)
  844. status.addresult(check_sanity_sstate_dir_change(sstate_dir, sanity_data))
  845. else:
  846. if last_sstate_dir != sstate_dir:
  847. status.addresult(check_sanity_sstate_dir_change(sstate_dir, sanity_data))
  848. if os.path.exists(os.path.dirname(sanityverfile)) and not status.messages:
  849. with open(sanityverfile, 'w') as f:
  850. f.write("SANITY_VERSION %s\n" % sanity_version)
  851. f.write("TMPDIR %s\n" % tmpdir)
  852. f.write("SSTATE_DIR %s\n" % sstate_dir)
  853. f.write("NATIVELSBSTRING %s\n" % nativelsbstr)
  854. sanity_handle_abichanges(status, sanity_data)
  855. if status.messages != "":
  856. raise_sanity_error(sanity_data.expand(status.messages), sanity_data, status.network_error)
  857. # Create a copy of the datastore and finalise it to ensure appends and
  858. # overrides are set - the datastore has yet to be finalised at ConfigParsed
  859. def copy_data(e):
  860. sanity_data = bb.data.createCopy(e.data)
  861. sanity_data.finalize()
  862. return sanity_data
  863. addhandler config_reparse_eventhandler
  864. config_reparse_eventhandler[eventmask] = "bb.event.ConfigParsed"
  865. python config_reparse_eventhandler() {
  866. sanity_check_conffiles(e.data)
  867. }
  868. addhandler check_sanity_eventhandler
  869. check_sanity_eventhandler[eventmask] = "bb.event.SanityCheck bb.event.NetworkTest"
  870. python check_sanity_eventhandler() {
  871. if bb.event.getName(e) == "SanityCheck":
  872. sanity_data = copy_data(e)
  873. check_sanity(sanity_data)
  874. if e.generateevents:
  875. sanity_data.setVar("SANITY_USE_EVENTS", "1")
  876. bb.event.fire(bb.event.SanityCheckPassed(), e.data)
  877. elif bb.event.getName(e) == "NetworkTest":
  878. sanity_data = copy_data(e)
  879. if e.generateevents:
  880. sanity_data.setVar("SANITY_USE_EVENTS", "1")
  881. bb.event.fire(bb.event.NetworkTestFailed() if check_connectivity(sanity_data) else bb.event.NetworkTestPassed(), e.data)
  882. return
  883. }