blob: 75b219cd3f9189cb80bde42f9284e6fb2d67e8ca [file] [log] [blame]
Brad Bishopd7bf8c12018-02-25 22:55:05 -05001#
2# Copyright (c) 2013, Intel Corporation.
Brad Bishopd7bf8c12018-02-25 22:55:05 -05003#
Brad Bishopc342db32019-05-15 21:57:59 -04004# SPDX-License-Identifier: GPL-2.0-only
Brad Bishopd7bf8c12018-02-25 22:55:05 -05005#
6# DESCRIPTION
7# This module provides a place to collect various wic-related utils
8# for the OpenEmbedded Image Tools.
9#
10# AUTHORS
11# Tom Zanussi <tom.zanussi (at] linux.intel.com>
12#
13"""Miscellaneous functions."""
14
15import logging
16import os
17import re
18import subprocess
19
20from collections import defaultdict
21from distutils import spawn
22
23from wic import WicError
24
25logger = logging.getLogger('wic')
26
27# executable -> recipe pairs for exec_native_cmd
28NATIVE_RECIPES = {"bmaptool": "bmap-tools",
29 "grub-mkimage": "grub-efi",
30 "isohybrid": "syslinux",
31 "mcopy": "mtools",
32 "mdel" : "mtools",
33 "mdeltree" : "mtools",
34 "mdir" : "mtools",
35 "mkdosfs": "dosfstools",
36 "mkisofs": "cdrtools",
37 "mkfs.btrfs": "btrfs-tools",
38 "mkfs.ext2": "e2fsprogs",
39 "mkfs.ext3": "e2fsprogs",
40 "mkfs.ext4": "e2fsprogs",
41 "mkfs.vfat": "dosfstools",
42 "mksquashfs": "squashfs-tools",
43 "mkswap": "util-linux",
44 "mmd": "mtools",
45 "parted": "parted",
46 "sfdisk": "util-linux",
47 "sgdisk": "gptfdisk",
Andrew Geissler82c905d2020-04-13 13:39:40 -050048 "syslinux": "syslinux",
49 "tar": "tar"
Brad Bishopd7bf8c12018-02-25 22:55:05 -050050 }
51
52def runtool(cmdln_or_args):
53 """ wrapper for most of the subprocess calls
54 input:
55 cmdln_or_args: can be both args and cmdln str (shell=True)
56 return:
57 rc, output
58 """
59 if isinstance(cmdln_or_args, list):
60 cmd = cmdln_or_args[0]
61 shell = False
62 else:
63 import shlex
64 cmd = shlex.split(cmdln_or_args)[0]
65 shell = True
66
67 sout = subprocess.PIPE
68 serr = subprocess.STDOUT
69
70 try:
71 process = subprocess.Popen(cmdln_or_args, stdout=sout,
72 stderr=serr, shell=shell)
73 sout, serr = process.communicate()
74 # combine stdout and stderr, filter None out and decode
75 out = ''.join([out.decode('utf-8') for out in [sout, serr] if out])
76 except OSError as err:
77 if err.errno == 2:
78 # [Errno 2] No such file or directory
79 raise WicError('Cannot run command: %s, lost dependency?' % cmd)
80 else:
81 raise # relay
82
83 return process.returncode, out
84
85def _exec_cmd(cmd_and_args, as_shell=False):
86 """
87 Execute command, catching stderr, stdout
88
89 Need to execute as_shell if the command uses wildcards
90 """
91 logger.debug("_exec_cmd: %s", cmd_and_args)
92 args = cmd_and_args.split()
93 logger.debug(args)
94
95 if as_shell:
96 ret, out = runtool(cmd_and_args)
97 else:
98 ret, out = runtool(args)
99 out = out.strip()
100 if ret != 0:
101 raise WicError("_exec_cmd: %s returned '%s' instead of 0\noutput: %s" % \
102 (cmd_and_args, ret, out))
103
104 logger.debug("_exec_cmd: output for %s (rc = %d): %s",
105 cmd_and_args, ret, out)
106
107 return ret, out
108
109
110def exec_cmd(cmd_and_args, as_shell=False):
111 """
112 Execute command, return output
113 """
114 return _exec_cmd(cmd_and_args, as_shell)[1]
115
Andrew Geissler82c905d2020-04-13 13:39:40 -0500116def find_executable(cmd, paths):
117 recipe = cmd
118 if recipe in NATIVE_RECIPES:
119 recipe = NATIVE_RECIPES[recipe]
120 provided = get_bitbake_var("ASSUME_PROVIDED")
121 if provided and "%s-native" % recipe in provided:
122 return True
123
124 return spawn.find_executable(cmd, paths)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500125
126def exec_native_cmd(cmd_and_args, native_sysroot, pseudo=""):
127 """
128 Execute native command, catching stderr, stdout
129
130 Need to execute as_shell if the command uses wildcards
131
132 Always need to execute native commands as_shell
133 """
134 # The reason -1 is used is because there may be "export" commands.
135 args = cmd_and_args.split(';')[-1].split()
136 logger.debug(args)
137
138 if pseudo:
139 cmd_and_args = pseudo + cmd_and_args
140
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600141 hosttools_dir = get_bitbake_var("HOSTTOOLS_DIR")
142
143 native_paths = "%s/sbin:%s/usr/sbin:%s/usr/bin:%s/bin:%s" % \
Andrew Geisslerc9f78652020-09-18 14:11:35 -0500144 (native_sysroot, native_sysroot,
Andrew Geisslerd1e89492021-02-12 15:35:20 -0600145 native_sysroot, native_sysroot,
146 hosttools_dir)
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500147
148 native_cmd_and_args = "export PATH=%s:$PATH;%s" % \
149 (native_paths, cmd_and_args)
150 logger.debug("exec_native_cmd: %s", native_cmd_and_args)
151
152 # If the command isn't in the native sysroot say we failed.
Andrew Geissler82c905d2020-04-13 13:39:40 -0500153 if find_executable(args[0], native_paths):
Brad Bishopd7bf8c12018-02-25 22:55:05 -0500154 ret, out = _exec_cmd(native_cmd_and_args, True)
155 else:
156 ret = 127
157 out = "can't find native executable %s in %s" % (args[0], native_paths)
158
159 prog = args[0]
160 # shell command-not-found
161 if ret == 127 \
162 or (pseudo and ret == 1 and out == "Can't find '%s' in $PATH." % prog):
163 msg = "A native program %s required to build the image "\
164 "was not found (see details above).\n\n" % prog
165 recipe = NATIVE_RECIPES.get(prog)
166 if recipe:
167 msg += "Please make sure wic-tools have %s-native in its DEPENDS, "\
168 "build it with 'bitbake wic-tools' and try again.\n" % recipe
169 else:
170 msg += "Wic failed to find a recipe to build native %s. Please "\
171 "file a bug against wic.\n" % prog
172 raise WicError(msg)
173
174 return ret, out
175
176BOOTDD_EXTRA_SPACE = 16384
177
178class BitbakeVars(defaultdict):
179 """
180 Container for Bitbake variables.
181 """
182 def __init__(self):
183 defaultdict.__init__(self, dict)
184
185 # default_image and vars_dir attributes should be set from outside
186 self.default_image = None
187 self.vars_dir = None
188
189 def _parse_line(self, line, image, matcher=re.compile(r"^([a-zA-Z0-9\-_+./~]+)=(.*)")):
190 """
191 Parse one line from bitbake -e output or from .env file.
192 Put result key-value pair into the storage.
193 """
194 if "=" not in line:
195 return
196 match = matcher.match(line)
197 if not match:
198 return
199 key, val = match.groups()
200 self[image][key] = val.strip('"')
201
202 def get_var(self, var, image=None, cache=True):
203 """
204 Get bitbake variable from 'bitbake -e' output or from .env file.
205 This is a lazy method, i.e. it runs bitbake or parses file only when
206 only when variable is requested. It also caches results.
207 """
208 if not image:
209 image = self.default_image
210
211 if image not in self:
212 if image and self.vars_dir:
213 fname = os.path.join(self.vars_dir, image + '.env')
214 if os.path.isfile(fname):
215 # parse .env file
216 with open(fname) as varsfile:
217 for line in varsfile:
218 self._parse_line(line, image)
219 else:
220 print("Couldn't get bitbake variable from %s." % fname)
221 print("File %s doesn't exist." % fname)
222 return
223 else:
224 # Get bitbake -e output
225 cmd = "bitbake -e"
226 if image:
227 cmd += " %s" % image
228
229 log_level = logger.getEffectiveLevel()
230 logger.setLevel(logging.INFO)
231 ret, lines = _exec_cmd(cmd)
232 logger.setLevel(log_level)
233
234 if ret:
235 logger.error("Couldn't get '%s' output.", cmd)
236 logger.error("Bitbake failed with error:\n%s\n", lines)
237 return
238
239 # Parse bitbake -e output
240 for line in lines.split('\n'):
241 self._parse_line(line, image)
242
243 # Make first image a default set of variables
244 if cache:
245 images = [key for key in self if key]
246 if len(images) == 1:
247 self[None] = self[image]
248
249 result = self[image].get(var)
250 if not cache:
251 self.pop(image, None)
252
253 return result
254
255# Create BB_VARS singleton
256BB_VARS = BitbakeVars()
257
258def get_bitbake_var(var, image=None, cache=True):
259 """
260 Provide old get_bitbake_var API by wrapping
261 get_var method of BB_VARS singleton.
262 """
263 return BB_VARS.get_var(var, image, cache)