sanity.bbclass 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101
  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 ?= "diff -u"
  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 check_non_ascii(filepath, pathname):
  257. if(not filepath.isascii()):
  258. return "Non-ASCII character(s) in %s path (\"%s\") detected. This would cause build failures as we build software that doesn't support this.\n" % (pathname, filepath)
  259. return ""
  260. def get_filesystem_id(path):
  261. import subprocess
  262. try:
  263. return subprocess.check_output(["stat", "-f", "-c", "%t", path]).decode('utf-8').strip()
  264. except subprocess.CalledProcessError:
  265. bb.warn("Can't get filesystem id of: %s" % path)
  266. return None
  267. # Check that the path isn't located on nfs.
  268. def check_not_nfs(path, name):
  269. # The nfs' filesystem id is 6969
  270. if get_filesystem_id(path) == "6969":
  271. return "The %s: %s can't be located on nfs.\n" % (name, path)
  272. return ""
  273. # Check that the path is on a case-sensitive file system
  274. def check_case_sensitive(path, name):
  275. import tempfile
  276. with tempfile.NamedTemporaryFile(prefix='TmP', dir=path) as tmp_file:
  277. if os.path.exists(tmp_file.name.lower()):
  278. return "The %s (%s) can't be on a case-insensitive file system.\n" % (name, path)
  279. return ""
  280. # Check that path isn't a broken symlink
  281. def check_symlink(lnk, data):
  282. if os.path.islink(lnk) and not os.path.exists(lnk):
  283. raise_sanity_error("%s is a broken symlink." % lnk, data)
  284. def check_connectivity(d):
  285. # URI's to check can be set in the CONNECTIVITY_CHECK_URIS variable
  286. # using the same syntax as for SRC_URI. If the variable is not set
  287. # the check is skipped
  288. test_uris = (d.getVar('CONNECTIVITY_CHECK_URIS') or "").split()
  289. retval = ""
  290. bbn = d.getVar('BB_NO_NETWORK')
  291. if bbn not in (None, '0', '1'):
  292. return 'BB_NO_NETWORK should be "0" or "1", but it is "%s"' % bbn
  293. # Only check connectivity if network enabled and the
  294. # CONNECTIVITY_CHECK_URIS are set
  295. network_enabled = not (bbn == '1')
  296. check_enabled = len(test_uris)
  297. if check_enabled and network_enabled:
  298. # Take a copy of the data store and unset MIRRORS and PREMIRRORS
  299. data = bb.data.createCopy(d)
  300. data.delVar('PREMIRRORS')
  301. data.delVar('MIRRORS')
  302. try:
  303. fetcher = bb.fetch2.Fetch(test_uris, data)
  304. fetcher.checkstatus()
  305. except Exception as err:
  306. # Allow the message to be configured so that users can be
  307. # pointed to a support mechanism.
  308. msg = data.getVar('CONNECTIVITY_CHECK_MSG') or ""
  309. if len(msg) == 0:
  310. msg = "%s.\n" % err
  311. msg += " Please ensure your host's network is configured correctly.\n"
  312. msg += " Please ensure CONNECTIVITY_CHECK_URIS is correct and specified URIs are available.\n"
  313. msg += " If your ISP or network is blocking the above URL,\n"
  314. msg += " try with another domain name, for example by setting:\n"
  315. msg += " CONNECTIVITY_CHECK_URIS = \"https://www.example.com/\""
  316. msg += " You could also set BB_NO_NETWORK = \"1\" to disable network\n"
  317. msg += " access if all required sources are on local disk.\n"
  318. retval = msg
  319. return retval
  320. def check_supported_distro(sanity_data):
  321. from fnmatch import fnmatch
  322. tested_distros = sanity_data.getVar('SANITY_TESTED_DISTROS')
  323. if not tested_distros:
  324. return
  325. try:
  326. distro = oe.lsb.distro_identifier()
  327. except Exception:
  328. distro = None
  329. if not distro:
  330. bb.warn('Host distribution could not be determined; you may possibly experience unexpected failures. It is recommended that you use a tested distribution.')
  331. for supported in [x.strip() for x in tested_distros.split('\\n')]:
  332. if fnmatch(distro, supported):
  333. return
  334. 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)
  335. # Checks we should only make if MACHINE is set correctly
  336. def check_sanity_validmachine(sanity_data):
  337. messages = ""
  338. # Check TUNE_ARCH is set
  339. if sanity_data.getVar('TUNE_ARCH') == 'INVALID':
  340. messages = messages + 'TUNE_ARCH is unset. Please ensure your MACHINE configuration includes a valid tune configuration file which will set this correctly.\n'
  341. # Check TARGET_OS is set
  342. if sanity_data.getVar('TARGET_OS') == 'INVALID':
  343. messages = messages + 'Please set TARGET_OS directly, or choose a MACHINE or DISTRO that does so.\n'
  344. # Check that we don't have duplicate entries in PACKAGE_ARCHS & that TUNE_PKGARCH is in PACKAGE_ARCHS
  345. pkgarchs = sanity_data.getVar('PACKAGE_ARCHS')
  346. tunepkg = sanity_data.getVar('TUNE_PKGARCH')
  347. defaulttune = sanity_data.getVar('DEFAULTTUNE')
  348. tunefound = False
  349. seen = {}
  350. dups = []
  351. for pa in pkgarchs.split():
  352. if seen.get(pa, 0) == 1:
  353. dups.append(pa)
  354. else:
  355. seen[pa] = 1
  356. if pa == tunepkg:
  357. tunefound = True
  358. if len(dups):
  359. messages = messages + "Error, the PACKAGE_ARCHS variable contains duplicates. The following archs are listed more than once: %s" % " ".join(dups)
  360. if tunefound == False:
  361. messages = messages + "Error, the PACKAGE_ARCHS variable (%s) for DEFAULTTUNE (%s) does not contain TUNE_PKGARCH (%s)." % (pkgarchs, defaulttune, tunepkg)
  362. return messages
  363. # Patch before 2.7 can't handle all the features in git-style diffs. Some
  364. # patches may incorrectly apply, and others won't apply at all.
  365. def check_patch_version(sanity_data):
  366. import re, subprocess
  367. try:
  368. result = subprocess.check_output(["patch", "--version"], stderr=subprocess.STDOUT).decode('utf-8')
  369. version = re.search(r"[0-9.]+", result.splitlines()[0]).group()
  370. if bb.utils.vercmp_string_op(version, "2.7", "<"):
  371. 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"
  372. else:
  373. return None
  374. except subprocess.CalledProcessError as e:
  375. return "Unable to execute patch --version, exit code %d:\n%s\n" % (e.returncode, e.output)
  376. # Glibc needs make 4.0 or later, we may as well match at this point
  377. def check_make_version(sanity_data):
  378. import subprocess
  379. try:
  380. result = subprocess.check_output(['make', '--version'], stderr=subprocess.STDOUT).decode('utf-8')
  381. except subprocess.CalledProcessError as e:
  382. return "Unable to execute make --version, exit code %d\n%s\n" % (e.returncode, e.output)
  383. version = result.split()[2]
  384. if bb.utils.vercmp_string_op(version, "4.0", "<"):
  385. return "Please install a make version of 4.0 or later.\n"
  386. if bb.utils.vercmp_string_op(version, "4.2.1", "=="):
  387. distro = oe.lsb.distro_identifier()
  388. if "ubuntu" in distro or "debian" in distro or "linuxmint" in distro:
  389. return None
  390. 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"
  391. return None
  392. # Check if we're running on WSL (Windows Subsystem for Linux).
  393. # WSLv1 is known not to work but WSLv2 should work properly as
  394. # long as the VHDX file is optimized often, let the user know
  395. # upfront.
  396. # More information on installing WSLv2 at:
  397. # https://docs.microsoft.com/en-us/windows/wsl/wsl2-install
  398. def check_wsl(d):
  399. with open("/proc/version", "r") as f:
  400. verdata = f.readlines()
  401. for l in verdata:
  402. if "Microsoft" in l:
  403. return "OpenEmbedded doesn't work under WSLv1, please upgrade to WSLv2 if you want to run builds on Windows"
  404. elif "microsoft" in l:
  405. 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")
  406. return None
  407. def check_userns():
  408. """
  409. Check that user namespaces are functional, as they're used for network isolation.
  410. """
  411. # There is a known failure case with AppAmrmor where the unshare() call
  412. # succeeds (at which point the uid is nobody) but writing to the uid_map
  413. # fails (so the uid isn't reset back to the user's uid). We can detect this.
  414. parentuid = os.getuid()
  415. if not bb.utils.is_local_uid(parentuid):
  416. return None
  417. pid = os.fork()
  418. if not pid:
  419. try:
  420. bb.utils.disable_network()
  421. except:
  422. pass
  423. os._exit(parentuid != os.getuid())
  424. ret = os.waitpid(pid, 0)[1]
  425. if ret:
  426. bb.fatal("User namespaces are not usable by BitBake, possibly due to AppArmor.\n"
  427. "See https://discourse.ubuntu.com/t/ubuntu-24-04-lts-noble-numbat-release-notes/39890#unprivileged-user-namespace-restrictions for more information.")
  428. # Require at least gcc version 8.0
  429. #
  430. # This can be fixed on CentOS-7 with devtoolset-6+
  431. # https://www.softwarecollections.org/en/scls/rhscl/devtoolset-6/
  432. #
  433. # A less invasive fix is with scripts/install-buildtools (or with user
  434. # built buildtools-extended-tarball)
  435. #
  436. def check_gcc_version(sanity_data):
  437. import subprocess
  438. build_cc, version = oe.utils.get_host_compiler_version(sanity_data)
  439. if build_cc.strip() == "gcc":
  440. if bb.utils.vercmp_string_op(version, "8.0", "<"):
  441. return "Your version of gcc is older than 8.0 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"
  442. return None
  443. # Tar version 1.24 and onwards handle overwriting symlinks correctly
  444. # but earlier versions do not; this needs to work properly for sstate
  445. # Version 1.28 is needed so opkg-build works correctly when reproducible builds are enabled
  446. # Gtar is assumed at to be used as tar in poky
  447. def check_tar_version(sanity_data):
  448. import subprocess
  449. try:
  450. result = subprocess.check_output(["tar", "--version"], stderr=subprocess.STDOUT).decode('utf-8')
  451. except subprocess.CalledProcessError as e:
  452. return "Unable to execute tar --version, exit code %d\n%s\n" % (e.returncode, e.output)
  453. if not "GNU" in result:
  454. return "Your version of tar is not gtar. Please install gtar (you could use the project's buildtools-tarball from our last release or use scripts/install-buildtools).\n"
  455. version = result.split()[3]
  456. if bb.utils.vercmp_string_op(version, "1.28", "<"):
  457. 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"
  458. try:
  459. result = subprocess.check_output(["tar", "--help"], stderr=subprocess.STDOUT).decode('utf-8')
  460. if "--xattrs" not in result:
  461. return "Your tar doesn't support --xattrs, please use GNU tar.\n"
  462. except subprocess.CalledProcessError as e:
  463. return "Unable to execute tar --help, exit code %d\n%s\n" % (e.returncode, e.output)
  464. return None
  465. # We use git parameters and functionality only found in 1.7.8 or later
  466. # The kernel tools assume git >= 1.8.3.1 (verified needed > 1.7.9.5) see #6162
  467. # The git fetcher also had workarounds for git < 1.7.9.2 which we've dropped
  468. def check_git_version(sanity_data):
  469. import subprocess
  470. try:
  471. result = subprocess.check_output(["git", "--version"], stderr=subprocess.DEVNULL).decode('utf-8')
  472. except subprocess.CalledProcessError as e:
  473. return "Unable to execute git --version, exit code %d\n%s\n" % (e.returncode, e.output)
  474. version = result.split()[2]
  475. if bb.utils.vercmp_string_op(version, "1.8.3.1", "<"):
  476. 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"
  477. return None
  478. # Check the required perl modules which may not be installed by default
  479. def check_perl_modules(sanity_data):
  480. import subprocess
  481. ret = ""
  482. modules = ( "Text::ParseWords", "Thread::Queue", "Data::Dumper", "File::Compare", "File::Copy", "open ':std'", "FindBin" )
  483. errresult = ''
  484. for m in modules:
  485. try:
  486. subprocess.check_output(["perl", "-e", "use %s" % m])
  487. except subprocess.CalledProcessError as e:
  488. errresult += bytes.decode(e.output)
  489. ret += "%s " % m
  490. if ret:
  491. return "Required perl module(s) not found: %s\n\n%s\n" % (ret, errresult)
  492. return None
  493. def sanity_check_conffiles(d):
  494. funcs = d.getVar('BBLAYERS_CONF_UPDATE_FUNCS').split()
  495. for func in funcs:
  496. conffile, current_version, required_version, func = func.split(":")
  497. if check_conf_exists(conffile, d) and d.getVar(current_version) is not None and \
  498. d.getVar(current_version) != d.getVar(required_version):
  499. try:
  500. bb.build.exec_func(func, d)
  501. except NotImplementedError as e:
  502. bb.fatal(str(e))
  503. d.setVar("BB_INVALIDCONF", True)
  504. def drop_v14_cross_builds(d):
  505. import glob
  506. indexes = glob.glob(d.expand("${SSTATE_MANIFESTS}/index-${BUILD_ARCH}_*"))
  507. for i in indexes:
  508. with open(i, "r") as f:
  509. lines = f.readlines()
  510. for l in reversed(lines):
  511. try:
  512. (stamp, manifest, workdir) = l.split()
  513. except ValueError:
  514. bb.fatal("Invalid line '%s' in sstate manifest '%s'" % (l, i))
  515. for m in glob.glob(manifest + ".*"):
  516. if m.endswith(".postrm"):
  517. continue
  518. sstate_clean_manifest(m, d)
  519. bb.utils.remove(stamp + "*")
  520. bb.utils.remove(workdir, recurse = True)
  521. def check_cpp_toolchain_flag(d, flag, error_message=None):
  522. """
  523. Checks if the C++ toolchain support the given flag
  524. """
  525. import shlex
  526. import subprocess
  527. cpp_code = """
  528. #include <iostream>
  529. int main() {
  530. std::cout << "Hello, World!" << std::endl;
  531. return 0;
  532. }
  533. """
  534. cmd = shlex.split(d.getVar("BUILD_CXX")) + ["-x", "c++","-", "-o", "/dev/null", flag]
  535. try:
  536. subprocess.run(cmd, input=cpp_code, capture_output=True, text=True, check=True)
  537. return None
  538. except subprocess.CalledProcessError as e:
  539. return error_message or f"An unexpected issue occurred during the C++ toolchain check: {str(e)}"
  540. def sanity_handle_abichanges(status, d):
  541. #
  542. # Check the 'ABI' of TMPDIR
  543. #
  544. import subprocess
  545. current_abi = d.getVar('OELAYOUT_ABI')
  546. abifile = d.getVar('SANITY_ABIFILE')
  547. if os.path.exists(abifile):
  548. with open(abifile, "r") as f:
  549. abi = f.read().strip()
  550. if not abi.isdigit():
  551. with open(abifile, "w") as f:
  552. f.write(current_abi)
  553. elif int(abi) <= 11 and current_abi == "12":
  554. 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"))
  555. elif int(abi) <= 13 and current_abi == "14":
  556. 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"))
  557. elif int(abi) == 14 and current_abi == "15":
  558. drop_v14_cross_builds(d)
  559. with open(abifile, "w") as f:
  560. f.write(current_abi)
  561. elif (abi != current_abi):
  562. # Code to convert from one ABI to another could go here if possible.
  563. 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))
  564. else:
  565. with open(abifile, "w") as f:
  566. f.write(current_abi)
  567. def check_sanity_sstate_dir_change(sstate_dir, data):
  568. # Sanity checks to be done when the value of SSTATE_DIR changes
  569. # Check that SSTATE_DIR isn't on a filesystem with limited filename length (eg. eCryptFS)
  570. testmsg = ""
  571. if sstate_dir != "":
  572. testmsg = check_create_long_filename(sstate_dir, "SSTATE_DIR")
  573. # If we don't have permissions to SSTATE_DIR, suggest the user set it as an SSTATE_MIRRORS
  574. try:
  575. err = testmsg.split(': ')[1].strip()
  576. if err == "Permission denied.":
  577. testmsg = testmsg + "You could try using %s in SSTATE_MIRRORS rather than as an SSTATE_CACHE.\n" % (sstate_dir)
  578. except IndexError:
  579. pass
  580. return testmsg
  581. def check_sanity_version_change(status, d):
  582. # Sanity checks to be done when SANITY_VERSION or NATIVELSBSTRING changes
  583. # In other words, these tests run once in a given build directory and then
  584. # never again until the sanity version or host distribution id/version changes.
  585. # Check the python install is complete. Examples that are often removed in
  586. # minimal installations: glib-2.0-natives requires xml.parsers.expat
  587. try:
  588. import xml.parsers.expat
  589. except ImportError as e:
  590. 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)
  591. status.addresult(check_gcc_version(d))
  592. status.addresult(check_make_version(d))
  593. status.addresult(check_patch_version(d))
  594. status.addresult(check_tar_version(d))
  595. status.addresult(check_git_version(d))
  596. status.addresult(check_perl_modules(d))
  597. status.addresult(check_wsl(d))
  598. status.addresult(check_userns())
  599. missing = ""
  600. if not check_app_exists("${MAKE}", d):
  601. missing = missing + "GNU make,"
  602. if not check_app_exists('${BUILD_CC}', d):
  603. missing = missing + "C Compiler (%s)," % d.getVar("BUILD_CC")
  604. if not check_app_exists('${BUILD_CXX}', d):
  605. missing = missing + "C++ Compiler (%s)," % d.getVar("BUILD_CXX")
  606. required_utilities = d.getVar('SANITY_REQUIRED_UTILITIES')
  607. for util in required_utilities.split():
  608. if not check_app_exists(util, d):
  609. missing = missing + "%s," % util
  610. if missing:
  611. missing = missing.rstrip(',')
  612. status.addresult("Please install the following missing utilities: %s\n" % missing)
  613. assume_provided = d.getVar('ASSUME_PROVIDED').split()
  614. # Check user doesn't have ASSUME_PROVIDED = instead of += in local.conf
  615. if "diffstat-native" not in assume_provided:
  616. status.addresult('Please use ASSUME_PROVIDED +=, not ASSUME_PROVIDED = in your local.conf\n')
  617. # Check that TMPDIR isn't on a filesystem with limited filename length (eg. eCryptFS)
  618. import stat
  619. tmpdir = d.getVar('TMPDIR')
  620. topdir = d.getVar('TOPDIR')
  621. status.addresult(check_create_long_filename(tmpdir, "TMPDIR"))
  622. tmpdirmode = os.stat(tmpdir).st_mode
  623. if (tmpdirmode & stat.S_ISGID):
  624. status.addresult("TMPDIR is setgid, please don't build in a setgid directory")
  625. if (tmpdirmode & stat.S_ISUID):
  626. status.addresult("TMPDIR is setuid, please don't build in a setuid directory")
  627. # Check that a user isn't building in a path in PSEUDO_IGNORE_PATHS
  628. pseudoignorepaths = (d.getVar('PSEUDO_IGNORE_PATHS', expand=True) or "").split(",")
  629. workdir = d.getVar('WORKDIR', expand=True)
  630. for i in pseudoignorepaths:
  631. if i and workdir.startswith(i):
  632. status.addresult("You are building in a path included in PSEUDO_IGNORE_PATHS " + str(i) + " please locate the build outside this path.\n")
  633. # Check if PSEUDO_IGNORE_PATHS and paths under pseudo control overlap
  634. pseudoignorepaths = (d.getVar('PSEUDO_IGNORE_PATHS', expand=True) or "").split(",")
  635. pseudo_control_dir = "${D},${PKGD},${PKGDEST},${IMAGEROOTFS},${SDK_OUTPUT}"
  636. pseudocontroldir = d.expand(pseudo_control_dir).split(",")
  637. for i in pseudoignorepaths:
  638. for j in pseudocontroldir:
  639. if i and j:
  640. if j.startswith(i):
  641. 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")
  642. # Some third-party software apparently relies on chmod etc. being suid root (!!)
  643. import stat
  644. suid_check_bins = "chown chmod mknod".split()
  645. for bin_cmd in suid_check_bins:
  646. bin_path = bb.utils.which(os.environ["PATH"], bin_cmd)
  647. if bin_path:
  648. bin_stat = os.stat(bin_path)
  649. if bin_stat.st_uid == 0 and bin_stat.st_mode & stat.S_ISUID:
  650. 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)
  651. # Check that we can fetch from various network transports
  652. netcheck = check_connectivity(d)
  653. status.addresult(netcheck)
  654. if netcheck:
  655. status.network_error = True
  656. nolibs = d.getVar('NO32LIBS')
  657. if not nolibs:
  658. lib32path = '/lib'
  659. if os.path.exists('/lib64') and ( os.path.islink('/lib64') or os.path.islink('/lib') ):
  660. lib32path = '/lib32'
  661. if os.path.exists('%s/libc.so.6' % lib32path) and not os.path.exists('/usr/include/gnu/stubs-32.h'):
  662. status.addresult("You have a 32-bit libc, but no 32-bit headers. You must install the 32-bit libc headers.\n")
  663. bbpaths = d.getVar('BBPATH').split(":")
  664. if ("." in bbpaths or "./" in bbpaths or "" in bbpaths):
  665. status.addresult("BBPATH references the current directory, either through " \
  666. "an empty entry, a './' or a '.'.\n\t This is unsafe and means your "\
  667. "layer configuration is adding empty elements to BBPATH.\n\t "\
  668. "Please check your layer.conf files and other BBPATH " \
  669. "settings to remove the current working directory " \
  670. "references.\n" \
  671. "Parsed BBPATH is" + str(bbpaths));
  672. oes_bb_conf = d.getVar( 'OES_BITBAKE_CONF')
  673. if not oes_bb_conf:
  674. status.addresult('You are not using the OpenEmbedded version of conf/bitbake.conf. This means your environment is misconfigured, in particular check BBPATH.\n')
  675. # The length of TMPDIR can't be longer than 400
  676. status.addresult(check_path_length(tmpdir, "TMPDIR", 400))
  677. # Check that TOPDIR does not contain non ascii chars (perl_5.40.0, Perl-native and shadow-native build failures)
  678. status.addresult(check_non_ascii(topdir, "TOPDIR"))
  679. # Check that TMPDIR isn't located on nfs
  680. status.addresult(check_not_nfs(tmpdir, "TMPDIR"))
  681. # Check for case-insensitive file systems (such as Linux in Docker on
  682. # macOS with default HFS+ file system)
  683. status.addresult(check_case_sensitive(tmpdir, "TMPDIR"))
  684. # Check if linking with lstdc++ is failing
  685. status.addresult(check_cpp_toolchain_flag(d, "-lstdc++"))
  686. # Check if the C++ toochain support the "--std=gnu++20" flag
  687. status.addresult(check_cpp_toolchain_flag(d, "--std=gnu++20",
  688. "An error occurred during checking the C++ toolchain for '--std=gnu++20' support. "
  689. "Please use a g++ compiler that supports C++20 (e.g. g++ version 10 onwards)."))
  690. def sanity_check_locale(d):
  691. """
  692. Currently bitbake switches locale to en_US.UTF-8 so check that this locale actually exists.
  693. """
  694. import locale
  695. try:
  696. locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
  697. except locale.Error:
  698. raise_sanity_error("Your system needs to support the en_US.UTF-8 locale.", d)
  699. def check_sanity_everybuild(status, d):
  700. import os, stat
  701. # Sanity tests which test the users environment so need to run at each build (or are so cheap
  702. # it makes sense to always run them.
  703. if 0 == os.getuid():
  704. raise_sanity_error("Do not use Bitbake as root.", d)
  705. # Check the Python version, we now have a minimum of Python 3.9
  706. import sys
  707. if sys.hexversion < 0x030900F0:
  708. status.addresult('The system requires at least Python 3.9 to run. Please update your Python interpreter.\n')
  709. # Check the bitbake version meets minimum requirements
  710. minversion = d.getVar('BB_MIN_VERSION')
  711. if bb.utils.vercmp_string_op(bb.__version__, minversion, "<"):
  712. status.addresult('Bitbake version %s is required and version %s was found\n' % (minversion, bb.__version__))
  713. sanity_check_locale(d)
  714. paths = d.getVar('PATH').split(":")
  715. if "." in paths or "./" in paths or "" in paths:
  716. status.addresult("PATH contains '.', './' or '' (empty element), which will break the build, please remove this.\nParsed PATH is " + str(paths) + "\n")
  717. #Check if bitbake is present in PATH environment variable
  718. bb_check = bb.utils.which(d.getVar('PATH'), 'bitbake')
  719. if not bb_check:
  720. bb.warn("bitbake binary is not found in PATH, did you source the script?")
  721. # Check whether 'inherit' directive is found (used for a class to inherit)
  722. # in conf file it's supposed to be uppercase INHERIT
  723. inherit = d.getVar('inherit')
  724. if inherit:
  725. 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")
  726. # Check that the DISTRO is valid, if set
  727. # need to take into account DISTRO renaming DISTRO
  728. distro = d.getVar('DISTRO')
  729. if distro and distro != "nodistro":
  730. if not ( check_conf_exists("conf/distro/${DISTRO}.conf", d) or check_conf_exists("conf/distro/include/${DISTRO}.inc", d) ):
  731. status.addresult("DISTRO '%s' not found. Please set a valid DISTRO in your local.conf\n" % d.getVar("DISTRO"))
  732. # Check that these variables don't use tilde-expansion as we don't do that
  733. for v in ("TMPDIR", "DL_DIR", "SSTATE_DIR"):
  734. if d.getVar(v).startswith("~"):
  735. status.addresult("%s uses ~ but Bitbake will not expand this, use an absolute path or variables." % v)
  736. # Check that DL_DIR is set, exists and is writable. In theory, we should never even hit the check if DL_DIR isn't
  737. # set, since so much relies on it being set.
  738. dldir = d.getVar('DL_DIR')
  739. if not dldir:
  740. 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")
  741. if os.path.exists(dldir) and not os.access(dldir, os.W_OK):
  742. status.addresult("DL_DIR: %s exists but you do not appear to have write access to it. \n" % dldir)
  743. check_symlink(dldir, d)
  744. # Check that the MACHINE is valid, if it is set
  745. machinevalid = True
  746. if d.getVar('MACHINE'):
  747. if not check_conf_exists("conf/machine/${MACHINE}.conf", d):
  748. status.addresult('MACHINE=%s is invalid. Please set a valid MACHINE in your local.conf, environment or other configuration file.\n' % (d.getVar('MACHINE')))
  749. machinevalid = False
  750. else:
  751. status.addresult(check_sanity_validmachine(d))
  752. else:
  753. status.addresult('Please set a MACHINE in your local.conf or environment\n')
  754. machinevalid = False
  755. if machinevalid:
  756. status.addresult(check_toolchain(d))
  757. # Check that the SDKMACHINE is valid, if it is set
  758. if d.getVar('SDKMACHINE'):
  759. if not check_conf_exists("conf/machine-sdk/${SDKMACHINE}.conf", d):
  760. status.addresult('Specified SDKMACHINE value is not valid\n')
  761. elif d.getVar('SDK_ARCH', False) == "${BUILD_ARCH}":
  762. 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')
  763. # If SDK_VENDOR looks like "-my-sdk" then the triples are badly formed so fail early
  764. sdkvendor = d.getVar("SDK_VENDOR")
  765. if not (sdkvendor.startswith("-") and sdkvendor.count("-") == 1):
  766. status.addresult("SDK_VENDOR should be of the form '-foosdk' with a single dash; found '%s'\n" % sdkvendor)
  767. check_supported_distro(d)
  768. omask = os.umask(0o022)
  769. if omask & 0o755:
  770. status.addresult("Please use a umask which allows a+rx and u+rwx\n")
  771. os.umask(omask)
  772. # Ensure /tmp is NOT mounted with noexec
  773. if os.statvfs("/tmp").f_flag & os.ST_NOEXEC:
  774. raise_sanity_error("/tmp shouldn't be mounted with noexec.", d)
  775. if d.getVar('TARGET_ARCH') == "arm":
  776. # This path is no longer user-readable in modern (very recent) Linux
  777. try:
  778. if os.path.exists("/proc/sys/vm/mmap_min_addr"):
  779. f = open("/proc/sys/vm/mmap_min_addr", "r")
  780. try:
  781. if (int(f.read().strip()) > 65536):
  782. 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")
  783. finally:
  784. f.close()
  785. except:
  786. pass
  787. for checkdir in ['COREBASE', 'TMPDIR']:
  788. val = d.getVar(checkdir)
  789. if val.find('..') != -1:
  790. 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)
  791. if val.find('+') != -1:
  792. 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)
  793. if val.find('@') != -1:
  794. 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)
  795. if val.find(' ') != -1:
  796. 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)
  797. if val.find('%') != -1:
  798. 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)
  799. # Check the format of MIRRORS, PREMIRRORS and SSTATE_MIRRORS
  800. import re
  801. mirror_vars = ['MIRRORS', 'PREMIRRORS', 'SSTATE_MIRRORS']
  802. protocols = ['http', 'ftp', 'file', 'https', \
  803. 'git', 'gitsm', 'hg', 'osc', 'p4', 'svn', \
  804. 'bzr', 'cvs', 'npm', 'sftp', 'ssh', 's3', \
  805. 'az', 'ftps', 'crate', 'gs']
  806. for mirror_var in mirror_vars:
  807. mirrors = (d.getVar(mirror_var) or '').replace('\\n', ' ').split()
  808. # Split into pairs
  809. if len(mirrors) % 2 != 0:
  810. bb.warn('Invalid mirror variable value for %s: %s, should contain paired members.' % (mirror_var, str(mirrors)))
  811. continue
  812. mirrors = list(zip(*[iter(mirrors)]*2))
  813. for mirror_entry in mirrors:
  814. pattern, mirror = mirror_entry
  815. decoded = bb.fetch2.decodeurl(pattern)
  816. try:
  817. pattern_scheme = re.compile(decoded[0])
  818. except re.error as exc:
  819. bb.warn('Invalid scheme regex (%s) in %s; %s' % (pattern, mirror_var, mirror_entry))
  820. continue
  821. if not any(pattern_scheme.match(protocol) for protocol in protocols):
  822. bb.warn('Invalid protocol (%s) in %s: %s' % (decoded[0], mirror_var, mirror_entry))
  823. continue
  824. if not any(mirror.startswith(protocol + '://') for protocol in protocols):
  825. bb.warn('Invalid protocol in %s: %s' % (mirror_var, mirror_entry))
  826. continue
  827. if mirror.startswith('file://'):
  828. import urllib
  829. check_symlink(urllib.parse.urlparse(mirror).path, d)
  830. # SSTATE_MIRROR ends with a /PATH string
  831. if mirror.endswith('/PATH'):
  832. # remove /PATH$ from SSTATE_MIRROR to get a working
  833. # base directory path
  834. mirror_base = urllib.parse.urlparse(mirror[:-1*len('/PATH')]).path
  835. check_symlink(mirror_base, d)
  836. # Check sstate mirrors aren't being used with a local hash server and no remote
  837. hashserv = d.getVar("BB_HASHSERVE")
  838. if d.getVar("SSTATE_MIRRORS") and hashserv and hashserv.startswith("unix://") and not d.getVar("BB_HASHSERVE_UPSTREAM"):
  839. 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.")
  840. # Check that TMPDIR hasn't changed location since the last time we were run
  841. tmpdir = d.getVar('TMPDIR')
  842. checkfile = os.path.join(tmpdir, "saved_tmpdir")
  843. if os.path.exists(checkfile):
  844. with open(checkfile, "r") as f:
  845. saved_tmpdir = f.read().strip()
  846. if (saved_tmpdir != tmpdir):
  847. status.addresult("Error, TMPDIR has changed location. You need to either move it back to %s or delete it and rebuild\n" % saved_tmpdir)
  848. else:
  849. bb.utils.mkdirhier(tmpdir)
  850. # Remove setuid, setgid and sticky bits from TMPDIR
  851. try:
  852. os.chmod(tmpdir, os.stat(tmpdir).st_mode & ~ stat.S_ISUID)
  853. os.chmod(tmpdir, os.stat(tmpdir).st_mode & ~ stat.S_ISGID)
  854. os.chmod(tmpdir, os.stat(tmpdir).st_mode & ~ stat.S_ISVTX)
  855. except OSError as exc:
  856. bb.warn("Unable to chmod TMPDIR: %s" % exc)
  857. with open(checkfile, "w") as f:
  858. f.write(tmpdir)
  859. # If /bin/sh is a symlink, check that it points to dash or bash
  860. if os.path.islink('/bin/sh'):
  861. real_sh = os.path.realpath('/bin/sh')
  862. # Due to update-alternatives, the shell name may take various
  863. # forms, such as /bin/dash, bin/bash, /bin/bash.bash ...
  864. if '/dash' not in real_sh and '/bash' not in real_sh:
  865. status.addresult("Error, /bin/sh links to %s, must be dash or bash\n" % real_sh)
  866. def check_sanity(sanity_data):
  867. class SanityStatus(object):
  868. def __init__(self):
  869. self.messages = ""
  870. self.network_error = False
  871. def addresult(self, message):
  872. if message:
  873. self.messages = self.messages + message
  874. status = SanityStatus()
  875. tmpdir = sanity_data.getVar('TMPDIR')
  876. sstate_dir = sanity_data.getVar('SSTATE_DIR')
  877. check_symlink(sstate_dir, sanity_data)
  878. # Check saved sanity info
  879. last_sanity_version = 0
  880. last_tmpdir = ""
  881. last_sstate_dir = ""
  882. last_nativelsbstr = ""
  883. sanityverfile = sanity_data.expand("${TOPDIR}/cache/sanity_info")
  884. if os.path.exists(sanityverfile):
  885. with open(sanityverfile, 'r') as f:
  886. for line in f:
  887. if line.startswith('SANITY_VERSION'):
  888. last_sanity_version = int(line.split()[1])
  889. if line.startswith('TMPDIR'):
  890. last_tmpdir = line.split()[1]
  891. if line.startswith('SSTATE_DIR'):
  892. last_sstate_dir = line.split()[1]
  893. if line.startswith('NATIVELSBSTRING'):
  894. last_nativelsbstr = line.split()[1]
  895. check_sanity_everybuild(status, sanity_data)
  896. sanity_version = int(sanity_data.getVar('SANITY_VERSION') or 1)
  897. network_error = False
  898. # NATIVELSBSTRING var may have been overridden with "universal", so
  899. # get actual host distribution id and version
  900. nativelsbstr = lsb_distro_identifier(sanity_data)
  901. if last_sanity_version < sanity_version or last_nativelsbstr != nativelsbstr:
  902. check_sanity_version_change(status, sanity_data)
  903. status.addresult(check_sanity_sstate_dir_change(sstate_dir, sanity_data))
  904. else:
  905. if last_sstate_dir != sstate_dir:
  906. status.addresult(check_sanity_sstate_dir_change(sstate_dir, sanity_data))
  907. if os.path.exists(os.path.dirname(sanityverfile)) and not status.messages:
  908. with open(sanityverfile, 'w') as f:
  909. f.write("SANITY_VERSION %s\n" % sanity_version)
  910. f.write("TMPDIR %s\n" % tmpdir)
  911. f.write("SSTATE_DIR %s\n" % sstate_dir)
  912. f.write("NATIVELSBSTRING %s\n" % nativelsbstr)
  913. sanity_handle_abichanges(status, sanity_data)
  914. if status.messages != "":
  915. raise_sanity_error(sanity_data.expand(status.messages), sanity_data, status.network_error)
  916. addhandler config_reparse_eventhandler
  917. config_reparse_eventhandler[eventmask] = "bb.event.ConfigParsed"
  918. python config_reparse_eventhandler() {
  919. sanity_check_conffiles(e.data)
  920. }
  921. addhandler check_sanity_eventhandler
  922. check_sanity_eventhandler[eventmask] = "bb.event.SanityCheck bb.event.NetworkTest"
  923. python check_sanity_eventhandler() {
  924. if bb.event.getName(e) == "SanityCheck":
  925. sanity_data = bb.data.createCopy(e.data)
  926. check_sanity(sanity_data)
  927. if e.generateevents:
  928. sanity_data.setVar("SANITY_USE_EVENTS", "1")
  929. bb.event.fire(bb.event.SanityCheckPassed(), e.data)
  930. elif bb.event.getName(e) == "NetworkTest":
  931. sanity_data = bb.data.createCopy(e.data)
  932. if e.generateevents:
  933. sanity_data.setVar("SANITY_USE_EVENTS", "1")
  934. bb.event.fire(bb.event.NetworkTestFailed() if check_connectivity(sanity_data) else bb.event.NetworkTestPassed(), e.data)
  935. return
  936. }