1 # SPDX-License-Identifier: GPL-2.0+
3 # Copyright (c) 2016 Google, Inc
6 from __future__ import print_function
18 # Output directly (generally this is temporary)
21 # True to keep the output directory around after exiting
22 preserve_outdir = False
24 # Path to the Chrome OS chroot, if we know it
27 # Search paths to use for Filename(), used to find files
30 tool_search_paths = []
32 # Tools and the packages that contain them, on debian
37 # List of paths to use when looking for an input file
40 def PrepareOutputDir(dirname, preserve=False):
41 """Select an output directory, ensuring it exists.
43 This either creates a temporary directory or checks that the one supplied
44 by the user is valid. For a temporary directory, it makes a note to
45 remove it later if required.
48 dirname: a string, name of the output directory to use to store
49 intermediate and output files. If is None - create a temporary
51 preserve: a Boolean. If outdir above is None and preserve is False, the
52 created temporary directory will be destroyed on exit.
55 OSError: If it cannot create the output directory.
57 global outdir, preserve_outdir
59 preserve_outdir = dirname or preserve
62 if not os.path.isdir(outdir):
65 except OSError as err:
66 raise CmdError("Cannot make output directory '%s': '%s'" %
67 (outdir, err.strerror))
68 tout.Debug("Using output directory '%s'" % outdir)
70 outdir = tempfile.mkdtemp(prefix='binman.')
71 tout.Debug("Using temporary directory '%s'" % outdir)
73 def _RemoveOutputDir():
77 tout.Debug("Deleted temporary directory '%s'" % outdir)
80 def FinaliseOutputDir():
81 global outdir, preserve_outdir
83 """Tidy up: delete output directory if temporary and not preserved."""
84 if outdir and not preserve_outdir:
88 def GetOutputFilename(fname):
89 """Return a filename within the output directory.
92 fname: Filename to use for new file
95 The full path of the filename, within the output directory
97 return os.path.join(outdir, fname)
99 def _FinaliseForTest():
100 """Remove the output directory (for use by tests)"""
107 def SetInputDirs(dirname):
108 """Add a list of input directories, where input files are kept.
111 dirname: a list of paths to input directories to use for obtaining
112 files needed by binman to place in the image.
117 tout.Debug("Using input directories %s" % indir)
119 def GetInputFilename(fname):
120 """Return a filename for use as input.
123 fname: Filename to use for new file
126 The full path of the filename, within the input directory
128 if not indir or fname[:1] == '/':
130 for dirname in indir:
131 pathname = os.path.join(dirname, fname)
132 if os.path.exists(pathname):
135 raise ValueError("Filename '%s' not found in input path (%s) (cwd='%s')" %
136 (fname, ','.join(indir), os.getcwd()))
138 def GetInputFilenameGlob(pattern):
139 """Return a list of filenames for use as input.
142 pattern: Filename pattern to search for
145 A list of matching files in all input directories
148 return glob.glob(fname)
150 for dirname in indir:
151 pathname = os.path.join(dirname, pattern)
152 files += glob.glob(pathname)
155 def Align(pos, align):
158 pos = (pos + mask) & ~mask
161 def NotPowerOfTwo(num):
162 return num and (num & (num - 1))
164 def SetToolPaths(toolpaths):
165 """Set the path to search for tools
168 toolpaths: List of paths to search for tools executed by Run()
170 global tool_search_paths
172 tool_search_paths = toolpaths
174 def PathHasFile(path_spec, fname):
175 """Check if a given filename is in the PATH
178 path_spec: Value of PATH variable to check
179 fname: Filename to check
182 True if found, False if not
184 for dir in path_spec.split(':'):
185 if os.path.exists(os.path.join(dir, fname)):
189 def Run(name, *args):
190 """Run a tool with some arguments
192 This runs a 'tool', which is a program used by binman to process files and
193 perhaps produce some output. Tools can be located on the PATH or in a
197 name: Command name to run
198 args: Arguments to the tool
205 if tool_search_paths:
206 env = dict(os.environ)
207 env['PATH'] = ':'.join(tool_search_paths) + ':' + env['PATH']
208 all_args = (name,) + args
209 result = command.RunPipe([all_args], capture=True, capture_stderr=True,
210 env=env, raise_on_error=False)
211 if result.return_code:
212 raise Exception("Error %d running '%s': %s" %
213 (result.return_code,' '.join(all_args),
217 if env and not PathHasFile(env['PATH'], name):
218 msg = "Please install tool '%s'" % name
219 package = packages.get(name)
221 msg += " (e.g. from package '%s')" % package
222 raise ValueError(msg)
226 """Resolve a file path to an absolute path.
228 If fname starts with ##/ and chroot is available, ##/ gets replaced with
229 the chroot path. If chroot is not available, this file name can not be
230 resolved, `None' is returned.
232 If fname is not prepended with the above prefix, and is not an existing
233 file, the actual file name is retrieved from the passed in string and the
234 search_paths directories (if any) are searched to for the file. If found -
235 the path to the found file is returned, `None' is returned otherwise.
238 fname: a string, the path to resolve.
241 Absolute path to the file or None if not found.
243 if fname.startswith('##/'):
245 fname = os.path.join(chroot_path, fname[3:])
249 # Search for a pathname that exists, and return it if found
250 if fname and not os.path.exists(fname):
251 for path in search_paths:
252 pathname = os.path.join(path, os.path.basename(fname))
253 if os.path.exists(pathname):
256 # If not found, just return the standard, unchanged path
259 def ReadFile(fname, binary=True):
260 """Read and return the contents of a file.
263 fname: path to filename to read, where ## signifiies the chroot.
266 data read from file, as a string.
268 with open(Filename(fname), binary and 'rb' or 'r') as fd:
270 #self._out.Info("Read file '%s' size %d (%#0x)" %
271 #(fname, len(data), len(data)))
274 def WriteFile(fname, data):
275 """Write data into a file.
278 fname: path to filename to write
279 data: data to write to file, as a string
281 #self._out.Info("Write file '%s' size %d (%#0x)" %
282 #(fname, len(data), len(data)))
283 with open(Filename(fname), 'wb') as fd:
286 def GetBytes(byte, size):
287 """Get a string of bytes of a given size
289 This handles the unfortunate different between Python 2 and Python 2.
292 byte: Numeric byte value to use
293 size: Size of bytes/string to return
296 A bytes type with 'byte' repeated 'size' times
298 if sys.version_info[0] >= 3:
299 data = bytes([byte]) * size
301 data = chr(byte) * size
305 """Make sure a value is a unicode string
307 This allows some amount of compatibility between Python 2 and Python3. For
308 the former, it returns a unicode object.
311 val: string or unicode object
314 unicode version of val
316 if sys.version_info[0] >= 3:
318 return val if isinstance(val, unicode) else val.decode('utf-8')
320 def FromUnicode(val):
321 """Make sure a value is a non-unicode string
323 This allows some amount of compatibility between Python 2 and Python3. For
324 the former, it converts a unicode object to a string.
327 val: string or unicode object
330 non-unicode version of val
332 if sys.version_info[0] >= 3:
334 return val if isinstance(val, str) else val.encode('utf-8')
337 """Convert a character to an ASCII value
339 This is useful because in Python 2 bytes is an alias for str, but in
340 Python 3 they are separate types. This function converts the argument to
341 an ASCII value in either case.
344 ch: A string (Python 2) or byte (Python 3) value
347 integer ASCII value for ch
349 return ord(ch) if type(ch) == str else ch
352 """Convert a byte to a character
354 This is useful because in Python 2 bytes is an alias for str, but in
355 Python 3 they are separate types. This function converts an ASCII value to
356 a value with the appropriate type in either case.
359 byte: A byte or str value
361 return chr(byte) if type(byte) != str else byte
363 def ToChars(byte_list):
364 """Convert a list of bytes to a str/bytes type
367 byte_list: List of ASCII values representing the string
370 string made by concatenating all the ASCII values
372 return ''.join([chr(byte) for byte in byte_list])
375 """Convert a str type into a bytes type
378 string: string to convert value
381 Python 3: A bytes type
382 Python 2: A string type
384 if sys.version_info[0] >= 3:
385 return string.encode('utf-8')
388 def Compress(indata, algo, with_header=True):
389 """Compress some data using a given algorithm
391 Note that for lzma this uses an old version of the algorithm, not that
394 This requires 'lz4' and 'lzma_alone' tools. It also requires an output
395 directory to be previously set up, by calling PrepareOutputDir().
398 indata: Input data to compress
399 algo: Algorithm to use ('none', 'gzip', 'lz4' or 'lzma')
406 fname = GetOutputFilename('%s.comp.tmp' % algo)
407 WriteFile(fname, indata)
409 data = Run('lz4', '--no-frame-crc', '-c', fname)
410 # cbfstool uses a very old version of lzma
412 outfname = GetOutputFilename('%s.comp.otmp' % algo)
413 Run('lzma_alone', 'e', fname, outfname, '-lc1', '-lp0', '-pb0', '-d8')
414 data = ReadFile(outfname)
416 data = Run('gzip', '-c', fname)
418 raise ValueError("Unknown algorithm '%s'" % algo)
420 hdr = struct.pack('<I', len(data))
424 def Decompress(indata, algo, with_header=True):
425 """Decompress some data using a given algorithm
427 Note that for lzma this uses an old version of the algorithm, not that
430 This requires 'lz4' and 'lzma_alone' tools. It also requires an output
431 directory to be previously set up, by calling PrepareOutputDir().
434 indata: Input data to decompress
435 algo: Algorithm to use ('none', 'gzip', 'lz4' or 'lzma')
443 data_len = struct.unpack('<I', indata[:4])[0]
444 indata = indata[4:4 + data_len]
445 fname = GetOutputFilename('%s.decomp.tmp' % algo)
446 with open(fname, 'wb') as fd:
449 data = Run('lz4', '-dc', fname)
451 outfname = GetOutputFilename('%s.decomp.otmp' % algo)
452 Run('lzma_alone', 'd', fname, outfname)
453 data = ReadFile(outfname)
455 data = Run('gzip', '-cd', fname)
457 raise ValueError("Unknown algorithm '%s'" % algo)
460 CMD_CREATE, CMD_DELETE, CMD_ADD, CMD_REPLACE, CMD_EXTRACT = range(5)
463 CMD_CREATE: 'create',
464 CMD_DELETE: 'delete',
466 CMD_REPLACE: 'replace',
467 CMD_EXTRACT: 'extract',
470 def RunIfwiTool(ifwi_file, cmd, fname=None, subpart=None, entry_name=None):
471 """Run ifwitool with the given arguments:
474 ifwi_file: IFWI file to operation on
475 cmd: Command to execute (CMD_...)
476 fname: Filename of file to add/replace/extract/create (None for
478 subpart: Name of sub-partition to operation on (None for CMD_CREATE)
479 entry_name: Name of directory entry to operate on, or None if none
481 args = ['ifwitool', ifwi_file]
482 args.append(IFWITOOL_CMDS[cmd])
484 args += ['-f', fname]
486 args += ['-n', subpart]
488 args += ['-d', '-e', entry_name]
492 """Convert an integer value (or None) to a string
495 hex value, or 'None' if the value is None
497 return 'None' if val is None else '%#x' % val
500 """Return the size of an object in hex
503 hex value of size, or 'None' if the value is None
505 return 'None' if val is None else '%#x' % len(val)