engine.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. #
  2. # Copyright (c) 2013, Intel Corporation.
  3. #
  4. # SPDX-License-Identifier: GPL-2.0-only
  5. #
  6. # DESCRIPTION
  7. # This module implements the image creation engine used by 'wic' to
  8. # create images. The engine parses through the OpenEmbedded kickstart
  9. # (wks) file specified and generates images that can then be directly
  10. # written onto media.
  11. #
  12. # AUTHORS
  13. # Tom Zanussi <tom.zanussi (at] linux.intel.com>
  14. #
  15. import logging
  16. import os
  17. import tempfile
  18. import json
  19. import subprocess
  20. import re
  21. from collections import namedtuple, OrderedDict
  22. from distutils.spawn import find_executable
  23. from wic import WicError
  24. from wic.filemap import sparse_copy
  25. from wic.pluginbase import PluginMgr
  26. from wic.misc import get_bitbake_var, exec_cmd
  27. logger = logging.getLogger('wic')
  28. def verify_build_env():
  29. """
  30. Verify that the build environment is sane.
  31. Returns True if it is, false otherwise
  32. """
  33. if not os.environ.get("BUILDDIR"):
  34. raise WicError("BUILDDIR not found, exiting. (Did you forget to source oe-init-build-env?)")
  35. return True
  36. CANNED_IMAGE_DIR = "lib/wic/canned-wks" # relative to scripts
  37. SCRIPTS_CANNED_IMAGE_DIR = "scripts/" + CANNED_IMAGE_DIR
  38. WIC_DIR = "wic"
  39. def build_canned_image_list(path):
  40. layers_path = get_bitbake_var("BBLAYERS")
  41. canned_wks_layer_dirs = []
  42. if layers_path is not None:
  43. for layer_path in layers_path.split():
  44. for wks_path in (WIC_DIR, SCRIPTS_CANNED_IMAGE_DIR):
  45. cpath = os.path.join(layer_path, wks_path)
  46. if os.path.isdir(cpath):
  47. canned_wks_layer_dirs.append(cpath)
  48. cpath = os.path.join(path, CANNED_IMAGE_DIR)
  49. canned_wks_layer_dirs.append(cpath)
  50. return canned_wks_layer_dirs
  51. def find_canned_image(scripts_path, wks_file):
  52. """
  53. Find a .wks file with the given name in the canned files dir.
  54. Return False if not found
  55. """
  56. layers_canned_wks_dir = build_canned_image_list(scripts_path)
  57. for canned_wks_dir in layers_canned_wks_dir:
  58. for root, dirs, files in os.walk(canned_wks_dir):
  59. for fname in files:
  60. if fname.endswith("~") or fname.endswith("#"):
  61. continue
  62. if ((fname.endswith(".wks") and wks_file + ".wks" == fname) or \
  63. (fname.endswith(".wks.in") and wks_file + ".wks.in" == fname)):
  64. fullpath = os.path.join(canned_wks_dir, fname)
  65. return fullpath
  66. return None
  67. def list_canned_images(scripts_path):
  68. """
  69. List the .wks files in the canned image dir, minus the extension.
  70. """
  71. layers_canned_wks_dir = build_canned_image_list(scripts_path)
  72. for canned_wks_dir in layers_canned_wks_dir:
  73. for root, dirs, files in os.walk(canned_wks_dir):
  74. for fname in files:
  75. if fname.endswith("~") or fname.endswith("#"):
  76. continue
  77. if fname.endswith(".wks") or fname.endswith(".wks.in"):
  78. fullpath = os.path.join(canned_wks_dir, fname)
  79. with open(fullpath) as wks:
  80. for line in wks:
  81. desc = ""
  82. idx = line.find("short-description:")
  83. if idx != -1:
  84. desc = line[idx + len("short-description:"):].strip()
  85. break
  86. basename = fname.split('.')[0]
  87. print(" %s\t\t%s" % (basename.ljust(30), desc))
  88. def list_canned_image_help(scripts_path, fullpath):
  89. """
  90. List the help and params in the specified canned image.
  91. """
  92. found = False
  93. with open(fullpath) as wks:
  94. for line in wks:
  95. if not found:
  96. idx = line.find("long-description:")
  97. if idx != -1:
  98. print()
  99. print(line[idx + len("long-description:"):].strip())
  100. found = True
  101. continue
  102. if not line.strip():
  103. break
  104. idx = line.find("#")
  105. if idx != -1:
  106. print(line[idx + len("#:"):].rstrip())
  107. else:
  108. break
  109. def list_source_plugins():
  110. """
  111. List the available source plugins i.e. plugins available for --source.
  112. """
  113. plugins = PluginMgr.get_plugins('source')
  114. for plugin in plugins:
  115. print(" %s" % plugin)
  116. def wic_create(wks_file, rootfs_dir, bootimg_dir, kernel_dir,
  117. native_sysroot, options):
  118. """
  119. Create image
  120. wks_file - user-defined OE kickstart file
  121. rootfs_dir - absolute path to the build's /rootfs dir
  122. bootimg_dir - absolute path to the build's boot artifacts directory
  123. kernel_dir - absolute path to the build's kernel directory
  124. native_sysroot - absolute path to the build's native sysroots dir
  125. image_output_dir - dirname to create for image
  126. options - wic command line options (debug, bmap, etc)
  127. Normally, the values for the build artifacts values are determined
  128. by 'wic -e' from the output of the 'bitbake -e' command given an
  129. image name e.g. 'core-image-minimal' and a given machine set in
  130. local.conf. If that's the case, the variables get the following
  131. values from the output of 'bitbake -e':
  132. rootfs_dir: IMAGE_ROOTFS
  133. kernel_dir: DEPLOY_DIR_IMAGE
  134. native_sysroot: STAGING_DIR_NATIVE
  135. In the above case, bootimg_dir remains unset and the
  136. plugin-specific image creation code is responsible for finding the
  137. bootimg artifacts.
  138. In the case where the values are passed in explicitly i.e 'wic -e'
  139. is not used but rather the individual 'wic' options are used to
  140. explicitly specify these values.
  141. """
  142. try:
  143. oe_builddir = os.environ["BUILDDIR"]
  144. except KeyError:
  145. raise WicError("BUILDDIR not found, exiting. (Did you forget to source oe-init-build-env?)")
  146. if not os.path.exists(options.outdir):
  147. os.makedirs(options.outdir)
  148. pname = options.imager
  149. plugin_class = PluginMgr.get_plugins('imager').get(pname)
  150. if not plugin_class:
  151. raise WicError('Unknown plugin: %s' % pname)
  152. plugin = plugin_class(wks_file, rootfs_dir, bootimg_dir, kernel_dir,
  153. native_sysroot, oe_builddir, options)
  154. plugin.do_create()
  155. logger.info("The image(s) were created using OE kickstart file:\n %s", wks_file)
  156. def wic_list(args, scripts_path):
  157. """
  158. Print the list of images or source plugins.
  159. """
  160. if args.list_type is None:
  161. return False
  162. if args.list_type == "images":
  163. list_canned_images(scripts_path)
  164. return True
  165. elif args.list_type == "source-plugins":
  166. list_source_plugins()
  167. return True
  168. elif len(args.help_for) == 1 and args.help_for[0] == 'help':
  169. wks_file = args.list_type
  170. fullpath = find_canned_image(scripts_path, wks_file)
  171. if not fullpath:
  172. raise WicError("No image named %s found, exiting. "
  173. "(Use 'wic list images' to list available images, "
  174. "or specify a fully-qualified OE kickstart (.wks) "
  175. "filename)" % wks_file)
  176. list_canned_image_help(scripts_path, fullpath)
  177. return True
  178. return False
  179. class Disk:
  180. def __init__(self, imagepath, native_sysroot, fstypes=('fat', 'ext')):
  181. self.imagepath = imagepath
  182. self.native_sysroot = native_sysroot
  183. self.fstypes = fstypes
  184. self._partitions = None
  185. self._partimages = {}
  186. self._lsector_size = None
  187. self._psector_size = None
  188. self._ptable_format = None
  189. # find parted
  190. # read paths from $PATH environment variable
  191. # if it fails, use hardcoded paths
  192. pathlist = "/bin:/usr/bin:/usr/sbin:/sbin/"
  193. try:
  194. self.paths = os.environ['PATH'] + ":" + pathlist
  195. except KeyError:
  196. self.paths = pathlist
  197. if native_sysroot:
  198. for path in pathlist.split(':'):
  199. self.paths = "%s%s:%s" % (native_sysroot, path, self.paths)
  200. self.parted = find_executable("parted", self.paths)
  201. if not self.parted:
  202. raise WicError("Can't find executable parted")
  203. self.partitions = self.get_partitions()
  204. def __del__(self):
  205. for path in self._partimages.values():
  206. os.unlink(path)
  207. def get_partitions(self):
  208. if self._partitions is None:
  209. self._partitions = OrderedDict()
  210. out = exec_cmd("%s -sm %s unit B print" % (self.parted, self.imagepath))
  211. parttype = namedtuple("Part", "pnum start end size fstype")
  212. splitted = out.splitlines()
  213. # skip over possible errors in exec_cmd output
  214. try:
  215. idx =splitted.index("BYT;")
  216. except ValueError:
  217. raise WicError("Error getting partition information from %s" % (self.parted))
  218. lsector_size, psector_size, self._ptable_format = splitted[idx + 1].split(":")[3:6]
  219. self._lsector_size = int(lsector_size)
  220. self._psector_size = int(psector_size)
  221. for line in splitted[idx + 2:]:
  222. pnum, start, end, size, fstype = line.split(':')[:5]
  223. partition = parttype(int(pnum), int(start[:-1]), int(end[:-1]),
  224. int(size[:-1]), fstype)
  225. self._partitions[pnum] = partition
  226. return self._partitions
  227. def __getattr__(self, name):
  228. """Get path to the executable in a lazy way."""
  229. if name in ("mdir", "mcopy", "mdel", "mdeltree", "sfdisk", "e2fsck",
  230. "resize2fs", "mkswap", "mkdosfs", "debugfs","blkid"):
  231. aname = "_%s" % name
  232. if aname not in self.__dict__:
  233. setattr(self, aname, find_executable(name, self.paths))
  234. if aname not in self.__dict__ or self.__dict__[aname] is None:
  235. raise WicError("Can't find executable '{}'".format(name))
  236. return self.__dict__[aname]
  237. return self.__dict__[name]
  238. def _get_part_image(self, pnum):
  239. if pnum not in self.partitions:
  240. raise WicError("Partition %s is not in the image" % pnum)
  241. part = self.partitions[pnum]
  242. # check if fstype is supported
  243. for fstype in self.fstypes:
  244. if part.fstype.startswith(fstype):
  245. break
  246. else:
  247. raise WicError("Not supported fstype: {}".format(part.fstype))
  248. if pnum not in self._partimages:
  249. tmpf = tempfile.NamedTemporaryFile(prefix="wic-part")
  250. dst_fname = tmpf.name
  251. tmpf.close()
  252. sparse_copy(self.imagepath, dst_fname, skip=part.start, length=part.size)
  253. self._partimages[pnum] = dst_fname
  254. return self._partimages[pnum]
  255. def _put_part_image(self, pnum):
  256. """Put partition image into partitioned image."""
  257. sparse_copy(self._partimages[pnum], self.imagepath,
  258. seek=self.partitions[pnum].start)
  259. def dir(self, pnum, path):
  260. if pnum not in self.partitions:
  261. raise WicError("Partition %s is not in the image" % pnum)
  262. if self.partitions[pnum].fstype.startswith('ext'):
  263. return exec_cmd("{} {} -R 'ls -l {}'".format(self.debugfs,
  264. self._get_part_image(pnum),
  265. path), as_shell=True)
  266. else: # fat
  267. return exec_cmd("{} -i {} ::{}".format(self.mdir,
  268. self._get_part_image(pnum),
  269. path))
  270. def copy(self, src, dest):
  271. """Copy partition image into wic image."""
  272. pnum = dest.part if isinstance(src, str) else src.part
  273. if self.partitions[pnum].fstype.startswith('ext'):
  274. if isinstance(src, str):
  275. cmd = "printf 'cd {}\nwrite {} {}\n' | {} -w {}".\
  276. format(os.path.dirname(dest.path), src, os.path.basename(src),
  277. self.debugfs, self._get_part_image(pnum))
  278. else: # copy from wic
  279. # run both dump and rdump to support both files and directory
  280. cmd = "printf 'cd {}\ndump /{} {}\nrdump /{} {}\n' | {} {}".\
  281. format(os.path.dirname(src.path), src.path,
  282. dest, src.path, dest, self.debugfs,
  283. self._get_part_image(pnum))
  284. else: # fat
  285. if isinstance(src, str):
  286. cmd = "{} -i {} -snop {} ::{}".format(self.mcopy,
  287. self._get_part_image(pnum),
  288. src, dest.path)
  289. else:
  290. cmd = "{} -i {} -snop ::{} {}".format(self.mcopy,
  291. self._get_part_image(pnum),
  292. src.path, dest)
  293. exec_cmd(cmd, as_shell=True)
  294. self._put_part_image(pnum)
  295. def remove_ext(self, pnum, path, recursive):
  296. """
  297. Remove files/dirs and their contents from the partition.
  298. This only applies to ext* partition.
  299. """
  300. abs_path = re.sub('\/\/+', '/', path)
  301. cmd = "{} {} -wR 'rm \"{}\"'".format(self.debugfs,
  302. self._get_part_image(pnum),
  303. abs_path)
  304. out = exec_cmd(cmd , as_shell=True)
  305. for line in out.splitlines():
  306. if line.startswith("rm:"):
  307. if "file is a directory" in line:
  308. if recursive:
  309. # loop through content and delete them one by one if
  310. # flaged with -r
  311. subdirs = iter(self.dir(pnum, abs_path).splitlines())
  312. next(subdirs)
  313. for subdir in subdirs:
  314. dir = subdir.split(':')[1].split(" ", 1)[1]
  315. if not dir == "." and not dir == "..":
  316. self.remove_ext(pnum, "%s/%s" % (abs_path, dir), recursive)
  317. rmdir_out = exec_cmd("{} {} -wR 'rmdir \"{}\"'".format(self.debugfs,
  318. self._get_part_image(pnum),
  319. abs_path.rstrip('/'))
  320. , as_shell=True)
  321. for rmdir_line in rmdir_out.splitlines():
  322. if "directory not empty" in rmdir_line:
  323. raise WicError("Could not complete operation: \n%s \n"
  324. "use -r to remove non-empty directory" % rmdir_line)
  325. if rmdir_line.startswith("rmdir:"):
  326. raise WicError("Could not complete operation: \n%s "
  327. "\n%s" % (str(line), rmdir_line))
  328. else:
  329. raise WicError("Could not complete operation: \n%s "
  330. "\nUnable to remove %s" % (str(line), abs_path))
  331. def remove(self, pnum, path, recursive):
  332. """Remove files/dirs from the partition."""
  333. partimg = self._get_part_image(pnum)
  334. if self.partitions[pnum].fstype.startswith('ext'):
  335. self.remove_ext(pnum, path, recursive)
  336. else: # fat
  337. cmd = "{} -i {} ::{}".format(self.mdel, partimg, path)
  338. try:
  339. exec_cmd(cmd)
  340. except WicError as err:
  341. if "not found" in str(err) or "non empty" in str(err):
  342. # mdel outputs 'File ... not found' or 'directory .. non empty"
  343. # try to use mdeltree as path could be a directory
  344. cmd = "{} -i {} ::{}".format(self.mdeltree,
  345. partimg, path)
  346. exec_cmd(cmd)
  347. else:
  348. raise err
  349. self._put_part_image(pnum)
  350. def write(self, target, expand):
  351. """Write disk image to the media or file."""
  352. def write_sfdisk_script(outf, parts):
  353. for key, val in parts['partitiontable'].items():
  354. if key in ("partitions", "device", "firstlba", "lastlba"):
  355. continue
  356. if key == "id":
  357. key = "label-id"
  358. outf.write("{}: {}\n".format(key, val))
  359. outf.write("\n")
  360. for part in parts['partitiontable']['partitions']:
  361. line = ''
  362. for name in ('attrs', 'name', 'size', 'type', 'uuid'):
  363. if name == 'size' and part['type'] == 'f':
  364. # don't write size for extended partition
  365. continue
  366. val = part.get(name)
  367. if val:
  368. line += '{}={}, '.format(name, val)
  369. if line:
  370. line = line[:-2] # strip ', '
  371. if part.get('bootable'):
  372. line += ' ,bootable'
  373. outf.write("{}\n".format(line))
  374. outf.flush()
  375. def read_ptable(path):
  376. out = exec_cmd("{} -J {}".format(self.sfdisk, path))
  377. return json.loads(out)
  378. def write_ptable(parts, target):
  379. with tempfile.NamedTemporaryFile(prefix="wic-sfdisk-", mode='w') as outf:
  380. write_sfdisk_script(outf, parts)
  381. cmd = "{} --no-reread {} < {} ".format(self.sfdisk, target, outf.name)
  382. exec_cmd(cmd, as_shell=True)
  383. if expand is None:
  384. sparse_copy(self.imagepath, target)
  385. else:
  386. # copy first sectors that may contain bootloader
  387. sparse_copy(self.imagepath, target, length=2048 * self._lsector_size)
  388. # copy source partition table to the target
  389. parts = read_ptable(self.imagepath)
  390. write_ptable(parts, target)
  391. # get size of unpartitioned space
  392. free = None
  393. for line in exec_cmd("{} -F {}".format(self.sfdisk, target)).splitlines():
  394. if line.startswith("Unpartitioned space ") and line.endswith("sectors"):
  395. free = int(line.split()[-2])
  396. # Align free space to a 2048 sector boundary. YOCTO #12840.
  397. free = free - (free % 2048)
  398. if free is None:
  399. raise WicError("Can't get size of unpartitioned space")
  400. # calculate expanded partitions sizes
  401. sizes = {}
  402. num_auto_resize = 0
  403. for num, part in enumerate(parts['partitiontable']['partitions'], 1):
  404. if num in expand:
  405. if expand[num] != 0: # don't resize partition if size is set to 0
  406. sectors = expand[num] // self._lsector_size
  407. free -= sectors - part['size']
  408. part['size'] = sectors
  409. sizes[num] = sectors
  410. elif part['type'] != 'f':
  411. sizes[num] = -1
  412. num_auto_resize += 1
  413. for num, part in enumerate(parts['partitiontable']['partitions'], 1):
  414. if sizes.get(num) == -1:
  415. part['size'] += free // num_auto_resize
  416. # write resized partition table to the target
  417. write_ptable(parts, target)
  418. # read resized partition table
  419. parts = read_ptable(target)
  420. # copy partitions content
  421. for num, part in enumerate(parts['partitiontable']['partitions'], 1):
  422. pnum = str(num)
  423. fstype = self.partitions[pnum].fstype
  424. # copy unchanged partition
  425. if part['size'] == self.partitions[pnum].size // self._lsector_size:
  426. logger.info("copying unchanged partition {}".format(pnum))
  427. sparse_copy(self._get_part_image(pnum), target, seek=part['start'] * self._lsector_size)
  428. continue
  429. # resize or re-create partitions
  430. if fstype.startswith('ext') or fstype.startswith('fat') or \
  431. fstype.startswith('linux-swap'):
  432. partfname = None
  433. with tempfile.NamedTemporaryFile(prefix="wic-part{}-".format(pnum)) as partf:
  434. partfname = partf.name
  435. if fstype.startswith('ext'):
  436. logger.info("resizing ext partition {}".format(pnum))
  437. partimg = self._get_part_image(pnum)
  438. sparse_copy(partimg, partfname)
  439. exec_cmd("{} -pf {}".format(self.e2fsck, partfname))
  440. exec_cmd("{} {} {}s".format(\
  441. self.resize2fs, partfname, part['size']))
  442. elif fstype.startswith('fat'):
  443. logger.info("copying content of the fat partition {}".format(pnum))
  444. with tempfile.TemporaryDirectory(prefix='wic-fatdir-') as tmpdir:
  445. # copy content to the temporary directory
  446. cmd = "{} -snompi {} :: {}".format(self.mcopy,
  447. self._get_part_image(pnum),
  448. tmpdir)
  449. exec_cmd(cmd)
  450. # create new msdos partition
  451. label = part.get("name")
  452. label_str = "-n {}".format(label) if label else ''
  453. cmd = "{} {} -C {} {}".format(self.mkdosfs, label_str, partfname,
  454. part['size'])
  455. exec_cmd(cmd)
  456. # copy content from the temporary directory to the new partition
  457. cmd = "{} -snompi {} {}/* ::".format(self.mcopy, partfname, tmpdir)
  458. exec_cmd(cmd, as_shell=True)
  459. elif fstype.startswith('linux-swap'):
  460. logger.info("creating swap partition {}".format(pnum))
  461. label = part.get("name")
  462. label_str = "-L {}".format(label) if label else ''
  463. out = exec_cmd("{} --probe {}".format(self.blkid, self._get_part_image(pnum)))
  464. uuid = out[out.index("UUID=\"")+6:out.index("UUID=\"")+42]
  465. uuid_str = "-U {}".format(uuid) if uuid else ''
  466. with open(partfname, 'w') as sparse:
  467. os.ftruncate(sparse.fileno(), part['size'] * self._lsector_size)
  468. exec_cmd("{} {} {} {}".format(self.mkswap, label_str, uuid_str, partfname))
  469. sparse_copy(partfname, target, seek=part['start'] * self._lsector_size)
  470. os.unlink(partfname)
  471. elif part['type'] != 'f':
  472. logger.warning("skipping partition {}: unsupported fstype {}".format(pnum, fstype))
  473. def wic_ls(args, native_sysroot):
  474. """List contents of partitioned image or vfat partition."""
  475. disk = Disk(args.path.image, native_sysroot)
  476. if not args.path.part:
  477. if disk.partitions:
  478. print('Num Start End Size Fstype')
  479. for part in disk.partitions.values():
  480. print("{:2d} {:12d} {:12d} {:12d} {}".format(\
  481. part.pnum, part.start, part.end,
  482. part.size, part.fstype))
  483. else:
  484. path = args.path.path or '/'
  485. print(disk.dir(args.path.part, path))
  486. def wic_cp(args, native_sysroot):
  487. """
  488. Copy file or directory to/from the vfat/ext partition of
  489. partitioned image.
  490. """
  491. if isinstance(args.dest, str):
  492. disk = Disk(args.src.image, native_sysroot)
  493. else:
  494. disk = Disk(args.dest.image, native_sysroot)
  495. disk.copy(args.src, args.dest)
  496. def wic_rm(args, native_sysroot):
  497. """
  498. Remove files or directories from the vfat partition of
  499. partitioned image.
  500. """
  501. disk = Disk(args.path.image, native_sysroot)
  502. disk.remove(args.path.part, args.path.path, args.recursive_delete)
  503. def wic_write(args, native_sysroot):
  504. """
  505. Write image to a target device.
  506. """
  507. disk = Disk(args.image, native_sysroot, ('fat', 'ext', 'linux-swap'))
  508. disk.write(args.target, args.expand)
  509. def find_canned(scripts_path, file_name):
  510. """
  511. Find a file either by its path or by name in the canned files dir.
  512. Return None if not found
  513. """
  514. if os.path.exists(file_name):
  515. return file_name
  516. layers_canned_wks_dir = build_canned_image_list(scripts_path)
  517. for canned_wks_dir in layers_canned_wks_dir:
  518. for root, dirs, files in os.walk(canned_wks_dir):
  519. for fname in files:
  520. if fname == file_name:
  521. fullpath = os.path.join(canned_wks_dir, fname)
  522. return fullpath
  523. def get_custom_config(boot_file):
  524. """
  525. Get the custom configuration to be used for the bootloader.
  526. Return None if the file can't be found.
  527. """
  528. # Get the scripts path of poky
  529. scripts_path = os.path.abspath("%s/../.." % os.path.dirname(__file__))
  530. cfg_file = find_canned(scripts_path, boot_file)
  531. if cfg_file:
  532. with open(cfg_file, "r") as f:
  533. config = f.read()
  534. return config