binman: Allow reading of images to list contents
v2 cover binman: Allow reading of images to list contents
This series adds features to allow binman to read its own images. Using an 'FDT map' inside the image (basically a cut-down copy of the input config with some pieces added) it can reverse-engineer the image and figure out what is where.
Uses of this feature are
- a new 'ls' command, which allows listing the entries in an image
- a new 'extract' command, which allows entry contents to be extracted and written to one or more files
Other improvements along the way include:
- Support for FDT map
- Support for an image header, which points to the FDT map
- Ability to deal with entries which change size after packing
- Additional error checking and FDT features for CBFS
- Convert from OptionParser to ArgumentParser
- Refactor to reduce code differences between entries and sections
Future work will allow reading files from the image, but I've decided to put that in the next series.
Changes in v2:
- Add patches to enhance the 'ls' command to filter which entries are shown
- Add patches to implement the 'extract' command
- Add the Entry object to EntryInfo as well
- Adjust LocateFdtmap() to return the position of the header
- Adjust the test to not rely on lz4 compression version
- Allow listing subsets of the image
- Avoid dual assignment in ResetForPack()
- Change Image.ListEntries() to BuildEntryList() since signature differs
- Change list command from 'list' to 'ls'
- Deal with travis's old lz4 version by skipping tests as necessary
- Don't allow global arguments after the command
- Fix up arguments in main Makefile
- Move 129_list_fdtmap.dts into the next commit
- Move patch 'Add a comment about CBFS test structure' to earlier series
- Move patch 'Allow cbfstool to be optional with tests' to earlier series
- Pass verbosity to tests via the setup_test_args() method
- Put --toolpath in the right place in functional tests
- Rename 128_decode_image_no_hdr.dts to 129_decode_image_nohdr.dts
- Show a message when a section's size changes
- Update Image for LocateFdtmap() returning the position of the header
- Update commit subject to more accurately describe this patch
- Update output from 'list' command
- Update test to use _DoReadFileRealDtb() helper
- Use 3 packing passes instead of two, and add a comment
- Use bytearray for Python 3
Simon Glass (31):
binman: Simplify the entry test
binman: Update future features
binman: Update help for new features
binman: Add a convenience functions for real-DTB tests
binman: Add an FDT map
binman: Add an image header
binman: Convert to use ArgumentParser
binman: Move compression into the Entry base class
binman: Drop an unused arg in Entry.Lookup()
binman: Allow easy importing of entry modules
binman: Fix up ProcessUpdateContents error and comments
binman: Call ProcessUpdateContents() consistently
binman: Add a return value to ProcessContentsUpdate()
binman: Add a control for post-pack entry expansion
binman: Allow entries to expand after packing
binman: Allow device-tree entries to be compressed
binman: Provide the actual data address for cbfs files
binman: Use the cbfs memlen field only for uncompressed length
binman: Support FDT update for CBFS
binman: Detect bad CBFS file types
binman: Allow listing the entries in an image
binman: Support locating an FDT map
binman: Support locating an image header
binman: Support reading an image into an Image object
binman: Convert Image to a subclass of Entry
binman: Support listing an image
binman: Allow for logging information to be displayed
binman: Allow reading an entry from an image
binman: Support reading from CBFS entries
binman: Add an 'extract' command
binman: Add a test for nested and aligned sections
.travis.yml | 2 +- Makefile | 4 +- test/run | 4 +- tools/binman/README | 129 ++- tools/binman/README.entries | 78 +- tools/binman/binman.py | 47 +- tools/binman/bsection.py | 496 ----------- tools/binman/cbfs_util.py | 56 +- tools/binman/cmdline.py | 101 ++- tools/binman/control.py | 213 ++++- tools/binman/entry.py | 149 +++- tools/binman/entry_test.py | 32 +- tools/binman/etype/__init__.py | 0 tools/binman/etype/_testing.py | 14 +- tools/binman/etype/blob.py | 51 +- tools/binman/etype/blob_dtb.py | 10 +- tools/binman/etype/cbfs.py | 64 +- tools/binman/etype/fdtmap.py | 130 +++ tools/binman/etype/files.py | 3 +- tools/binman/etype/fmap.py | 4 +- tools/binman/etype/image_header.py | 99 +++ tools/binman/etype/section.py | 439 +++++++++- tools/binman/etype/u_boot_with_ucode_ptr.py | 8 +- tools/binman/ftest.py | 811 ++++++++++++++++-- tools/binman/image.py | 315 +++++-- tools/binman/image_test.py | 18 +- tools/binman/state.py | 26 +- tools/binman/test/115_fdtmap.dts | 13 + tools/binman/test/116_fdtmap_hdr.dts | 17 + tools/binman/test/117_fdtmap_hdr_start.dts | 19 + tools/binman/test/118_fdtmap_hdr_pos.dts | 19 + tools/binman/test/119_fdtmap_hdr_missing.dts | 16 + tools/binman/test/120_hdr_no_location.dts | 16 + tools/binman/test/121_entry_expand.dts | 20 + tools/binman/test/122_entry_expand_twice.dts | 21 + .../binman/test/123_entry_expand_section.dts | 22 + tools/binman/test/124_compress_dtb.dts | 14 + tools/binman/test/125_cbfs_update.dts | 21 + tools/binman/test/126_cbfs_bad_type.dts | 17 + tools/binman/test/127_list.dts | 33 + tools/binman/test/128_decode_image.dts | 36 + tools/binman/test/129_decode_image_nohdr.dts | 33 + tools/binman/test/130_list_fdtmap.dts | 36 + tools/binman/test/131_pack_align_section.dts | 28 + tools/patman/test_util.py | 6 +- tools/patman/tout.py | 10 +- 46 files changed, 2787 insertions(+), 913 deletions(-) delete mode 100644 tools/binman/bsection.py create mode 100644 tools/binman/etype/__init__.py create mode 100644 tools/binman/etype/fdtmap.py create mode 100644 tools/binman/etype/image_header.py create mode 100644 tools/binman/test/115_fdtmap.dts create mode 100644 tools/binman/test/116_fdtmap_hdr.dts create mode 100644 tools/binman/test/117_fdtmap_hdr_start.dts create mode 100644 tools/binman/test/118_fdtmap_hdr_pos.dts create mode 100644 tools/binman/test/119_fdtmap_hdr_missing.dts create mode 100644 tools/binman/test/120_hdr_no_location.dts create mode 100644 tools/binman/test/121_entry_expand.dts create mode 100644 tools/binman/test/122_entry_expand_twice.dts create mode 100644 tools/binman/test/123_entry_expand_section.dts create mode 100644 tools/binman/test/124_compress_dtb.dts create mode 100644 tools/binman/test/125_cbfs_update.dts create mode 100644 tools/binman/test/126_cbfs_bad_type.dts create mode 100644 tools/binman/test/127_list.dts create mode 100644 tools/binman/test/128_decode_image.dts create mode 100644 tools/binman/test/129_decode_image_nohdr.dts create mode 100644 tools/binman/test/130_list_fdtmap.dts create mode 100644 tools/binman/test/131_pack_align_section.dts
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 1/31 binman: Simplify the entry test
The current test for the 'entry' module is a bit convoluted since it has to import the module multiple times. It also relies on ordering, in that test1EntryNoImportLib() must run before test2EntryImportLib() if they are running in the same Python process.
This is unreliable since neither the ordering of tests nor the process that they run in is defined.
Fix this by always reloading the entry in these two tests. Also add a check that the expected value of have_importlib is obtained.
This corrects a code-coverage problem in the 'entry' module on some systems.
---
Changes in v2: None
tools/binman/entry_test.py | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-)
tools/binman/entry_test.py +16 -16
@@ -9,12 +9,11 @@ import os import sys import unittest +import entry import fdt import fdt_util import tools -entry = None - class TestEntry(unittest.TestCase): def setUp(self): tools.PrepareOutputDir(None)
@@ -29,16 +28,7 @@ class TestEntry(unittest.TestCase): dtb = fdt.FdtScan(fname) return dtb.GetNode('/binman/u-boot') - def test1EntryNoImportLib(self): - """Test that we can import Entry subclassess successfully""" - - sys.modules['importlib'] = None - global entry - import entry - entry.Entry.Create(None, self.GetNode(), 'u-boot') - - def test2EntryImportLib(self): - del sys.modules['importlib'] + def _ReloadEntry(self): global entry if entry: if sys.version_info[0] >= 3:
@@ -48,8 +38,21 @@ class TestEntry(unittest.TestCase): reload(entry) else: import entry + + def test1EntryNoImportLib(self): + """Test that we can import Entry subclassess successfully""" + sys.modules['importlib'] = None + global entry + self._ReloadEntry() + entry.Entry.Create(None, self.GetNode(), 'u-boot') + self.assertFalse(entry.have_importlib) + + def test2EntryImportLib(self): + del sys.modules['importlib'] + global entry + self._ReloadEntry() entry.Entry.Create(None, self.GetNode(), 'u-boot-spl') - del entry + self.assertTrue(entry.have_importlib) def testEntryContents(self): """Test the Entry bass class"""
@@ -59,7 +62,6 @@ class TestEntry(unittest.TestCase): def testUnknownEntry(self): """Test that unknown entry types are detected""" - import entry Node = collections.namedtuple('Node', ['name', 'path']) node = Node('invalid-name', 'invalid-path') with self.assertRaises(ValueError) as e:
@@ -69,7 +71,6 @@ class TestEntry(unittest.TestCase): def testUniqueName(self): """Test Entry.GetUniqueName""" - import entry Node = collections.namedtuple('Node', ['name', 'parent']) base_node = Node('root', None) base_entry = entry.Entry(None, None, base_node, read_node=False)
@@ -80,7 +81,6 @@ class TestEntry(unittest.TestCase): def testGetDefaultFilename(self): """Trivial test for this base class function""" - import entry base_entry = entry.Entry(None, None, None, read_node=False) self.assertIsNone(base_entry.GetDefaultFilename())
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 1/31 binman: Simplify the entry test
The current test for the 'entry' module is a bit convoluted since it has to import the module multiple times. It also relies on ordering, in that test1EntryNoImportLib() must run before test2EntryImportLib() if they are running in the same Python process.
This is unreliable since neither the ordering of tests nor the process that they run in is defined.
Fix this by always reloading the entry in these two tests. Also add a check that the expected value of have_importlib is obtained.
This corrects a code-coverage problem in the 'entry' module on some systems.
---
Changes in v2: None
tools/binman/entry_test.py | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-)
Applied to u-boot-dm, thanks!
PATCH v2 2/31 binman: Update future features
In reply to Simon GlassA few features have been completed and a few items are added.
---
Changes in v2: None
tools/binman/README | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
tools/binman/README +8 -4
@@ -811,13 +811,17 @@ Some ideas: - Use of-platdata to make the information available to code that is unable to use device tree (such as a very small SPL image) - Allow easy building of images by specifying just the board name -- Produce a full Python binding for libfdt (for upstream). This is nearing - completion but some work remains - Add an option to decode an image into the constituent binaries - Support building an image for a board (-b) more completely, with a configurable build directory -- Consider making binman work with buildman, although if it is used in the - Makefile, this will be automatic +- Support putting the FDT in an image with a suitable magic number +- Support adding a pointer to the FDT map +- Support listing files in images +- Support logging of binman's operations, with different levels of verbosity +- Support updating binaries in an image (with no size change / repacking) +- Support updating binaries in an image (with repacking) +- Support adding FITs to an image +- Support for ARM Trusted Firmware (ATF) -- Simon Glass <[email protected]>
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 2/31 binman: Update future features
A few features have been completed and a few items are added.
---
Changes in v2: None
tools/binman/README | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-)
Applied to u-boot-dm, thanks!
PATCH v2 3/31 binman: Update help for new features
In reply to Simon GlassA few new features have been added. This has rendered part of the README obsolete. Update it.
---
Changes in v2: None
tools/binman/README | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-)
tools/binman/README +3 -4
@@ -36,10 +36,9 @@ suitable padding and alignment. It provides a way to process binaries before they are included, by adding a Python plug-in. The device tree is available to U-Boot at run-time so that the images can be interpreted. -Binman does not yet update the device tree with the final location of -everything when it is done. A simple C structure could be generated for -constrained environments like SPL (using dtoc) but this is also not -implemented. +Binman can update the device tree with the final location of everything when it +is done. Entry positions can be provided to U-Boot SPL as run-time symbols, +avoiding device-tree code overhead. Binman can also support incorporating filesystems in the image if required. For example x86 platforms may use CBFS in some cases.
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 3/31 binman: Update help for new features
A few new features have been added. This has rendered part of the README obsolete. Update it.
---
Changes in v2: None
tools/binman/README | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-)
Applied to u-boot-dm, thanks!
PATCH v2 4/31 binman: Add a convenience functions for real-DTB tests
In reply to Simon GlassQuite a few tests will use a real device tree and need it updated with the binman metadata. Add a helper function for this.
---
Changes in v2: None
tools/binman/ftest.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-)
tools/binman/ftest.py +12 -2
@@ -380,6 +380,17 @@ class TestFunctional(unittest.TestCase): if reset_dtbs and use_real_dtb: self._ResetDtbs() + def _DoReadFileRealDtb(self, fname): + """Run binman with a real .dtb file and return the resulting data + + Args: + fname: DT source filename to use (e.g. 082_fdt_update_all.dts) + + Returns: + Resulting image contents + """ + return self._DoReadFileDtb(fname, use_real_dtb=True, update_dtb=True)[0] + def _DoReadFile(self, fname, use_real_dtb=False): """Helper function which discards the device-tree binary
@@ -1547,8 +1558,7 @@ class TestFunctional(unittest.TestCase): def testUpdateFdtAll(self): """Test that all device trees are updated with offset/size info""" - data, _, _, _ = self._DoReadFileDtb('082_fdt_update_all.dts', - use_real_dtb=True, update_dtb=True) + data = self._DoReadFileRealDtb('082_fdt_update_all.dts') base_expected = { 'section:image-pos': 0,
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 4/31 binman: Add a convenience functions for real-DTB tests
Quite a few tests will use a real device tree and need it updated with the binman metadata. Add a helper function for this.
---
Changes in v2: None
tools/binman/ftest.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-)
Applied to u-boot-dm, thanks!
PATCH v2 5/31 binman: Add an FDT map
In reply to Simon GlassAn FDT map is an entry which holds a full description of the image entries, in FDT format. It can be discovered using the magic string at its start. Tools can locate and read this entry to find out what entries are in the image and where each entry is located.
---
Changes in v2: None
tools/binman/README | 5 +- tools/binman/README.entries | 38 +++++++++++ tools/binman/etype/fdtmap.py | 109 +++++++++++++++++++++++++++++++ tools/binman/ftest.py | 52 +++++++++++++-- tools/binman/state.py | 2 +- tools/binman/test/115_fdtmap.dts | 13 ++++ 6 files changed, 211 insertions(+), 8 deletions(-) create mode 100644 tools/binman/etype/fdtmap.py create mode 100644 tools/binman/test/115_fdtmap.dts
tools/binman/README +4 -1
@@ -638,6 +638,10 @@ the image definition, binman calculates the final values and writes these to the device tree. These can be used by U-Boot at run-time to find the location of each entry. +Alternatively, an FDT map entry can be used to add a special FDT containing +just the information about the image. This is preceded by a magic string so can +be located anywhere in the image. + Compression -----------
@@ -814,7 +818,6 @@ Some ideas: - Support building an image for a board (-b) more completely, with a configurable build directory - Support putting the FDT in an image with a suitable magic number -- Support adding a pointer to the FDT map - Support listing files in images - Support logging of binman's operations, with different levels of verbosity - Support updating binaries in an image (with no size change / repacking)
tools/binman/README.entries +38 -0
@@ -223,6 +223,44 @@ updating the EC on startup via software sync. +Entry: fdtmap: An entry which contains an FDT map +------------------------------------------------- + +Properties / Entry arguments: + None + +An FDT map is just a header followed by an FDT containing a list of all the +entries in the image. + +The header is the string _FDTMAP_ followed by 8 unused bytes. + +When used, this entry will be populated with an FDT map which reflects the +entries in the current image. Hierarchy is preserved, and all offsets and +sizes are included. + +Note that the -u option must be provided to ensure that binman updates the +FDT with the position of each entry. + +Example output for a simple image with U-Boot and an FDT map: + +/ { + size = <0x00000112>; + image-pos = <0x00000000>; + offset = <0x00000000>; + u-boot { + size = <0x00000004>; + image-pos = <0x00000000>; + offset = <0x00000000>; + }; + fdtmap { + size = <0x0000010e>; + image-pos = <0x00000004>; + offset = <0x00000004>; + }; +}; + + + Entry: files: Entry containing a set of files ---------------------------------------------
tools/binman/etype/fdtmap.py new file +109 -0
109 lines not on this page · raw message
tools/binman/ftest.py +46 -6
68 lines not on this page · raw message
tools/binman/state.py +1 -1
@@ -59,7 +59,7 @@ def GetFdtPath(fname): """ return fdt_files[fname]._fname -def GetFdtContents(fname): +def GetFdtContents(fname='u-boot.dtb'): """Looks up the FDT pathname and contents This is used to obtain the Fdt pathname and contents when needed by an
tools/binman/test/115_fdtmap.dts new file +13 -0
@@ -0,0 +1,13 @@ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + binman { + u-boot { + }; + fdtmap { + }; + }; +};
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 5/31 binman: Add an FDT map
An FDT map is an entry which holds a full description of the image entries, in FDT format. It can be discovered using the magic string at its start. Tools can locate and read this entry to find out what entries are in the image and where each entry is located.
---
Changes in v2: None
tools/binman/README | 5 +- tools/binman/README.entries | 38 +++++++++++ tools/binman/etype/fdtmap.py | 109 +++++++++++++++++++++++++++++++ tools/binman/ftest.py | 52 +++++++++++++-- tools/binman/state.py | 2 +- tools/binman/test/115_fdtmap.dts | 13 ++++ 6 files changed, 211 insertions(+), 8 deletions(-) create mode 100644 tools/binman/etype/fdtmap.py create mode 100644 tools/binman/test/115_fdtmap.dts
Applied to u-boot-dm, thanks!
PATCH v2 6/31 binman: Add an image header
In reply to Simon GlassIt is useful to be able to quickly locate the FDT map in the image. An easy way to do this is with a pointer at the start or end of the image.
Add an 'image header' entry, which places a magic number followed by a pointer to the FDT map. This can be located at the start or end of the image, or at a chosen location.
As part of this, update GetSiblingImagePos() to detect missing siblings.
---
Changes in v2:
- Update test to use _DoReadFileRealDtb() helper
tools/binman/README | 5 +- tools/binman/README.entries | 19 +++++ tools/binman/entry.py | 11 +++ tools/binman/etype/image_header.py | 76 ++++++++++++++++++++ tools/binman/ftest.py | 47 +++++++++++- tools/binman/test/116_fdtmap_hdr.dts | 17 +++++ tools/binman/test/117_fdtmap_hdr_start.dts | 19 +++++ tools/binman/test/118_fdtmap_hdr_pos.dts | 19 +++++ tools/binman/test/119_fdtmap_hdr_missing.dts | 16 +++++ tools/binman/test/120_hdr_no_location.dts | 16 +++++ 10 files changed, 242 insertions(+), 3 deletions(-) create mode 100644 tools/binman/etype/image_header.py create mode 100644 tools/binman/test/116_fdtmap_hdr.dts create mode 100644 tools/binman/test/117_fdtmap_hdr_start.dts create mode 100644 tools/binman/test/118_fdtmap_hdr_pos.dts create mode 100644 tools/binman/test/119_fdtmap_hdr_missing.dts create mode 100644 tools/binman/test/120_hdr_no_location.dts
tools/binman/README +3 -2
@@ -640,7 +640,9 @@ of each entry. Alternatively, an FDT map entry can be used to add a special FDT containing just the information about the image. This is preceded by a magic string so can -be located anywhere in the image. +be located anywhere in the image. An image header (typically at the start or end +of the image) can be used to point to the FDT map. See fdtmap and image-header +entries for more information. Compression
@@ -817,7 +819,6 @@ Some ideas: - Add an option to decode an image into the constituent binaries - Support building an image for a board (-b) more completely, with a configurable build directory -- Support putting the FDT in an image with a suitable magic number - Support listing files in images - Support logging of binman's operations, with different levels of verbosity - Support updating binaries in an image (with no size change / repacking)
tools/binman/README.entries +19 -0
@@ -331,6 +331,25 @@ README.chromium for how to obtain the required keys and tools. +Entry: image-header: An entry which contains a pointer to the FDT map +--------------------------------------------------------------------- + +Properties / Entry arguments: + location: Location of header ("start" or "end" of image). This is + optional. If omitted then the entry must have an offset property. + +This adds an 8-byte entry to the start or end of the image, pointing to the +location of the FDT map. The format is a magic number followed by an offset +from the start or end of the image, in twos-compliment format. + +This entry must be in the top-level part of the image. + +NOTE: If the location is at the start/end, you will probably need to specify +sort-by-offset for the image, unless you actually put the image header +first/last in the entry list. + + + Entry: intel-cmc: Entry containing an Intel Chipset Micro Code (CMC) file -------------------------------------------------------------------------
tools/binman/entry.py +11 -0
@@ -561,3 +561,14 @@ features to produce new behaviours. else False """ return name in self.section.GetEntries() + + def GetSiblingImagePos(self, name): + """Return the image position of the given sibling + + Returns: + Image position of sibling, or None if the sibling has no position, + or False if there is no such sibling + """ + if not self.HasSibling(name): + return False + return self.section.GetEntries()[name].image_pos
tools/binman/etype/image_header.py new file +76 -0
76 lines not on this page · raw message
tools/binman/ftest.py +46 -1
59 lines not on this page · raw message
tools/binman/test/116_fdtmap_hdr.dts new file +17 -0
@@ -0,0 +1,17 @@ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + binman { + size = <0x400>; + u-boot { + }; + fdtmap { + }; + image-header { + location = "end"; + }; + }; +};
tools/binman/test/117_fdtmap_hdr_start.dts new file +19 -0
@@ -0,0 +1,19 @@ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + binman { + size = <0x400>; + sort-by-offset; + u-boot { + offset = <0x100>; + }; + fdtmap { + }; + image-header { + location = "start"; + }; + }; +};
tools/binman/test/118_fdtmap_hdr_pos.dts new file +19 -0
@@ -0,0 +1,19 @@ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + binman { + size = <0x400>; + sort-by-offset; + u-boot { + offset = <0x100>; + }; + fdtmap { + }; + image-header { + offset = <0x80>; + }; + }; +};
tools/binman/test/119_fdtmap_hdr_missing.dts new file +16 -0
@@ -0,0 +1,16 @@ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + binman { + sort-by-offset; + u-boot { + }; + image-header { + offset = <0x80>; + location = "start"; + }; + }; +};
tools/binman/test/120_hdr_no_location.dts new file +16 -0
@@ -0,0 +1,16 @@ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + binman { + sort-by-offset; + u-boot { + }; + fdtmap { + }; + image-header { + }; + }; +};
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 6/31 binman: Add an image header
It is useful to be able to quickly locate the FDT map in the image. An easy way to do this is with a pointer at the start or end of the image.
Add an 'image header' entry, which places a magic number followed by a pointer to the FDT map. This can be located at the start or end of the image, or at a chosen location.
As part of this, update GetSiblingImagePos() to detect missing siblings.
---
Changes in v2:
- Update test to use _DoReadFileRealDtb() helper
tools/binman/README | 5 +- tools/binman/README.entries | 19 +++++ tools/binman/entry.py | 11 +++ tools/binman/etype/image_header.py | 76 ++++++++++++++++++++ tools/binman/ftest.py | 47 +++++++++++- tools/binman/test/116_fdtmap_hdr.dts | 17 +++++ tools/binman/test/117_fdtmap_hdr_start.dts | 19 +++++ tools/binman/test/118_fdtmap_hdr_pos.dts | 19 +++++ tools/binman/test/119_fdtmap_hdr_missing.dts | 16 +++++ tools/binman/test/120_hdr_no_location.dts | 16 +++++ 10 files changed, 242 insertions(+), 3 deletions(-) create mode 100644 tools/binman/etype/image_header.py create mode 100644 tools/binman/test/116_fdtmap_hdr.dts create mode 100644 tools/binman/test/117_fdtmap_hdr_start.dts create mode 100644 tools/binman/test/118_fdtmap_hdr_pos.dts create mode 100644 tools/binman/test/119_fdtmap_hdr_missing.dts create mode 100644 tools/binman/test/120_hdr_no_location.dts
Applied to u-boot-dm, thanks!
PATCH v2 7/31 binman: Convert to use ArgumentParser
In reply to Simon GlassThis class is the new way to handle arguments in Python. Convert binman over to use it. At the same time, introduce commands so that we can separate out the different parts of binman functionality.
---
Changes in v2:
- Don't allow global arguments after the command
- Fix up arguments in main Makefile
- Pass verbosity to tests via the setup_test_args() method
- Put --toolpath in the right place in functional tests
.travis.yml | 2 +- Makefile | 4 +- test/run | 4 +- tools/binman/README | 8 ++-- tools/binman/binman.py | 47 +++++++++++----------- tools/binman/cmdline.py | 82 +++++++++++++++++++++------------------ tools/binman/control.py | 51 ++++++++++++------------ tools/binman/ftest.py | 66 +++++++++++++------------------ tools/patman/test_util.py | 5 ++- 9 files changed, 133 insertions(+), 136 deletions(-)
.travis.yml +1 -1
@@ -147,7 +147,7 @@ script: if [[ -n "${TEST_PY_TOOLS}" ]]; then PYTHONPATH="${UBOOT_TRAVIS_BUILD_DIR}/scripts/dtc/pylibfdt" PATH="${UBOOT_TRAVIS_BUILD_DIR}/scripts/dtc:${PATH}" - ./tools/binman/binman --toolpath ${UBOOT_TRAVIS_BUILD_DIR}/tools -t && + ./tools/binman/binman --toolpath ${UBOOT_TRAVIS_BUILD_DIR}/tools test && ./tools/patman/patman --test && ./tools/buildman/buildman -t && PYTHONPATH="${UBOOT_TRAVIS_BUILD_DIR}/scripts/dtc/pylibfdt"
Makefile +2 -2
@@ -1196,9 +1196,9 @@ u-boot.ldr: u-boot # --------------------------------------------------------------------------- # Use 'make BINMAN_DEBUG=1' to enable debugging quiet_cmd_binman = BINMAN $@ -cmd_binman = $(srctree)/tools/binman/binman -u -d u-boot.dtb -O . -m \ +cmd_binman = $(srctree)/tools/binman/binman build -u -d u-boot.dtb -O . -m \ -I . -I $(srctree) -I $(srctree)/board/$(BOARDDIR) \ - $(if $(BINMAN_DEBUG),-D) $(BINMAN_$(@F)) $< + $(if $(BINMAN_DEBUG),-D) $(BINMAN_$(@F)) OBJCOPYFLAGS_u-boot.ldr.hex := -I binary -O ihex
test/run +2 -2
@@ -40,7 +40,7 @@ export PYTHONPATH=${DTC_DIR}/pylibfdt export DTC=${DTC_DIR}/dtc TOOLS_DIR=build-sandbox_spl/tools -run_test "binman" ./tools/binman/binman -t --toolpath ${TOOLS_DIR} +run_test "binman" ./tools/binman/binman --toolpath ${TOOLS_DIR} test run_test "patman" ./tools/patman/patman --test [ "$1" == "quick" ] && skip=--skip-net-tests
@@ -52,7 +52,7 @@ run_test "dtoc" ./tools/dtoc/dtoc -t # To enable Python test coverage on Debian-type distributions (e.g. Ubuntu): # $ sudo apt-get install python-pytest python-coverage export PATH=$PATH:${TOOLS_DIR} -run_test "binman code coverage" ./tools/binman/binman -T --toolpath ${TOOLS_DIR} +run_test "binman code coverage" ./tools/binman/binman test -T run_test "dtoc code coverage" ./tools/dtoc/dtoc -T run_test "fdt code coverage" ./tools/dtoc/test_fdt -T
tools/binman/README +4 -4
@@ -187,7 +187,7 @@ First install prerequisites, e.g. Type: - binman -b <board_name> + binman build -b <board_name> to build an image for a board. The board name is the same name used when configuring U-Boot (e.g. for sandbox_defconfig the board name is 'sandbox').
@@ -195,7 +195,7 @@ Binman assumes that the input files for the build are in ../b/<board_name>. Or you can specify this explicitly: - binman -I <build_path> + binman build -I <build_path> where <build_path> is the build directory containing the output of the U-Boot build.
@@ -483,7 +483,7 @@ Entry Documentation For details on the various entry types supported by binman and how to use them, see README.entries. This is generated from the source code using: - binman -E >tools/binman/README.entries + binman entry-docs >tools/binman/README.entries Hashing Entries
@@ -715,7 +715,7 @@ Code coverage ------------- Binman is a critical tool and is designed to be very testable. Entry -implementations target 100% test coverage. Run 'binman -T' to check this. +implementations target 100% test coverage. Run 'binman test -T' to check this. To enable Python test coverage on Debian-type distributions (e.g. Ubuntu):
tools/binman/binman.py +24 -23
95 lines not on this page · raw message
tools/binman/cmdline.py +45 -37
108 lines not on this page · raw message
tools/binman/control.py +25 -26
118 lines not on this page · raw message
tools/binman/ftest.py +27 -39
163 lines not on this page · raw message
tools/patman/test_util.py +3 -2
@@ -46,9 +46,10 @@ def RunTestCoverage(prog, filter_fname, exclude_list, build_dir, required=None): glob_list = [] glob_list += exclude_list glob_list += ['*libfdt.py', '*site-packages*', '*dist-packages*'] + test_cmd = 'test' if 'binman.py' in prog else '-t' cmd = ('PYTHONPATH=$PYTHONPATH:%s/sandbox_spl/tools %s-coverage run ' - '--omit "%s" %s -P1 -t' % (build_dir, PYTHON, ','.join(glob_list), - prog)) + '--omit "%s" %s %s -P1' % (build_dir, PYTHON, ','.join(glob_list), + prog, test_cmd)) os.system(cmd) stdout = command.Output('%s-coverage' % PYTHON, 'report') lines = stdout.splitlines()
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 7/31 binman: Convert to use ArgumentParser
This class is the new way to handle arguments in Python. Convert binman over to use it. At the same time, introduce commands so that we can separate out the different parts of binman functionality.
---
Changes in v2:
- Don't allow global arguments after the command
- Fix up arguments in main Makefile
- Pass verbosity to tests via the setup_test_args() method
- Put --toolpath in the right place in functional tests
.travis.yml | 2 +- Makefile | 4 +- test/run | 4 +- tools/binman/README | 8 ++-- tools/binman/binman.py | 47 +++++++++++----------- tools/binman/cmdline.py | 82 +++++++++++++++++++++------------------ tools/binman/control.py | 51 ++++++++++++------------ tools/binman/ftest.py | 66 +++++++++++++------------------ tools/patman/test_util.py | 5 ++- 9 files changed, 133 insertions(+), 136 deletions(-)
Applied to u-boot-dm, thanks!
PATCH v2 8/31 binman: Move compression into the Entry base class
In reply to Simon GlassCompression is currently available only with blobs. However we want to report the compression algorithm and uncompressed size for all entries, so that other entry types can support compression. This will help with the forthcoming 'list' feature which lists entries in the image.
Move the compression properties into the base class. Also fix up the docs which had the wrong property name.
---
Changes in v2: None
tools/binman/README | 11 ++++++++--- tools/binman/entry.py | 9 +++++++++ tools/binman/etype/blob.py | 19 ++++--------------- 3 files changed, 21 insertions(+), 18 deletions(-)
tools/binman/README +8 -3
@@ -339,6 +339,10 @@ expand-size: limited by the size of the image/section and the position of the next entry. +compress: + Sets the compression algortihm to use (for blobs only). See the entry + documentation for details. + The attributes supported for images and sections are described below. Several are similar to those for entries.
@@ -649,15 +653,16 @@ Compression ----------- Binman support compression for 'blob' entries (those of type 'blob' and -derivatives). To enable this for an entry, add a 'compression' property: +derivatives). To enable this for an entry, add a 'compress' property: blob { filename = "datafile"; - compression = "lz4"; + compress = "lz4"; }; The entry will then contain the compressed data, using the 'lz4' compression -algorithm. Currently this is the only one that is supported. +algorithm. Currently this is the only one that is supported. The uncompressed +size is written to the node in an 'uncomp-size' property, if -u is used.
tools/binman/entry.py +9 -0
@@ -51,6 +51,8 @@ class Entry(object): offset: Offset of entry within the section, None if not known yet (in which case it will be calculated by Pack()) size: Entry size in bytes, None if not known + uncomp_size: Size of uncompressed data in bytes, if the entry is + compressed, else None contents_size: Size of contents in bytes, 0 by default align: Entry start offset alignment, or None align_size: Entry size alignment, or None
@@ -58,6 +60,7 @@ class Entry(object): pad_before: Number of pad bytes before the contents, 0 if none pad_after: Number of pad bytes after the contents, 0 if none data: Contents of entry (string of bytes) + compress: Compression algoithm used (e.g. 'lz4'), 'none' if none """ def __init__(self, section, etype, node, read_node=True, name_prefix=''): self.section = section
@@ -66,6 +69,7 @@ class Entry(object): self.name = node and (name_prefix + node.name) or 'none' self.offset = None self.size = None + self.uncomp_size = None self.data = None self.contents_size = 0 self.align = None
@@ -76,6 +80,7 @@ class Entry(object): self.offset_unset = False self.image_pos = None self._expand_size = False + self.compress = 'none' if read_node: self.ReadNode()
@@ -188,6 +193,8 @@ class Entry(object): for prop in ['offset', 'size', 'image-pos']: if not prop in self._node.props: state.AddZeroProp(self._node, prop) + if self.compress != 'none': + state.AddZeroProp(self._node, 'uncomp-size') err = state.CheckAddHashProp(self._node) if err: self.Raise(err)
@@ -198,6 +205,8 @@ class Entry(object): state.SetInt(self._node, 'size', self.size) state.SetInt(self._node, 'image-pos', self.image_pos - self.section.GetRootSkipAtStart()) + if self.uncomp_size is not None: + state.SetInt(self._node, 'uncomp-size', self.uncomp_size) state.CheckSetHashValue(self._node, self.GetData) def ProcessFdt(self, fdt):
tools/binman/etype/blob.py +4 -15
@@ -33,8 +33,7 @@ class Entry_blob(Entry): def __init__(self, section, etype, node): Entry.__init__(self, section, etype, node) self._filename = fdt_util.GetString(self._node, 'filename', self.etype) - self._compress = fdt_util.GetString(self._node, 'compress', 'none') - self._uncompressed_size = None + self.compress = fdt_util.GetString(self._node, 'compress', 'none') def ObtainContents(self): self._filename = self.GetDefaultFilename()
@@ -50,21 +49,11 @@ class Entry_blob(Entry): # the data in chunks and avoid reading it all at once. For now # this seems like an unnecessary complication. indata = tools.ReadFile(self._pathname) - if self._compress != 'none': - self._uncompressed_size = len(indata) - data = tools.Compress(indata, self._compress) + if self.compress != 'none': + self.uncomp_size = len(indata) + data = tools.Compress(indata, self.compress) self.SetContents(data) return True def GetDefaultFilename(self): return self._filename - - def AddMissingProperties(self): - Entry.AddMissingProperties(self) - if self._compress != 'none': - state.AddZeroProp(self._node, 'uncomp-size') - - def SetCalculatedProperties(self): - Entry.SetCalculatedProperties(self) - if self._uncompressed_size is not None: - state.SetInt(self._node, 'uncomp-size', self._uncompressed_size)
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 8/31 binman: Move compression into the Entry base class
Compression is currently available only with blobs. However we want to report the compression algorithm and uncompressed size for all entries, so that other entry types can support compression. This will help with the forthcoming 'list' feature which lists entries in the image.
Move the compression properties into the base class. Also fix up the docs which had the wrong property name.
---
Changes in v2: None
tools/binman/README | 11 ++++++++--- tools/binman/entry.py | 9 +++++++++ tools/binman/etype/blob.py | 19 ++++--------------- 3 files changed, 21 insertions(+), 18 deletions(-)
Applied to u-boot-dm, thanks!
PATCH v2 9/31 binman: Drop an unused arg in Entry.Lookup()
In reply to Simon GlassThe first argument is not used. Remove it.
---
Changes in v2: None
tools/binman/entry.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-)
tools/binman/entry.py +3 -4
@@ -85,11 +85,10 @@ class Entry(object): self.ReadNode() @staticmethod - def Lookup(section, node_path, etype): + def Lookup(node_path, etype): """Look up the entry class for a node. Args: - section: Section object containing this node node_node: Path name of Node object containing information about the entry to create (used for errors) etype: Entry type to use
@@ -140,7 +139,7 @@ class Entry(object): """ if not etype: etype = fdt_util.GetString(node, 'type', node.name) - obj = Entry.Lookup(section, node.path, etype) + obj = Entry.Lookup(node.path, etype) # Call its constructor to get the object we want. return obj(section, etype, node)
@@ -514,7 +513,7 @@ features to produce new behaviours. modules.remove('_testing') missing = [] for name in modules: - module = Entry.Lookup(name, name, name) + module = Entry.Lookup(name, name) docs = getattr(module, '__doc__') if test_missing == name: docs = None
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 9/31 binman: Drop an unused arg in Entry.Lookup()
The first argument is not used. Remove it.
---
Changes in v2: None
tools/binman/entry.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-)
Applied to u-boot-dm, thanks!
PATCH v2 10/31 binman: Allow easy importing of entry modules
In reply to Simon GlassAt present entry modules can only be accessed using Entry.Lookup() or Entry.Create(). Most of the time this is fine, but sometimes a module needs to provide constants or helper functions useful to other modules. It is easier in this case to use 'import'.
Add an __init__ file to permit this.
---
Changes in v2: None
tools/binman/entry.py | 2 ++ tools/binman/etype/__init__.py | 0 tools/patman/test_util.py | 1 + 3 files changed, 3 insertions(+) create mode 100644 tools/binman/etype/__init__.py
tools/binman/entry.py +2 -0
@@ -513,6 +513,8 @@ features to produce new behaviours. modules.remove('_testing') missing = [] for name in modules: + if name.startswith('__'): + continue module = Entry.Lookup(name, name) docs = getattr(module, '__doc__') if test_missing == name:
tools/binman/etype/__init__.py new file +0 -0
tools/patman/test_util.py +1 -0
@@ -58,6 +58,7 @@ def RunTestCoverage(prog, filter_fname, exclude_list, build_dir, required=None): test_set = set([os.path.splitext(os.path.basename(line.split()[0]))[0] for line in lines if '/etype/' in line]) missing_list = required + missing_list.discard('__init__') missing_list.difference_update(test_set) if missing_list: print('Missing tests for %s' % (', '.join(missing_list)))
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 10/31 binman: Allow easy importing of entry modules
At present entry modules can only be accessed using Entry.Lookup() or Entry.Create(). Most of the time this is fine, but sometimes a module needs to provide constants or helper functions useful to other modules. It is easier in this case to use 'import'.
Add an __init__ file to permit this.
---
Changes in v2: None
tools/binman/entry.py | 2 ++ tools/binman/etype/__init__.py | 0 tools/patman/test_util.py | 1 + 3 files changed, 3 insertions(+) create mode 100644 tools/binman/etype/__init__.py
Applied to u-boot-dm, thanks!
PATCH v2 11/31 binman: Fix up ProcessUpdateContents error and comments
In reply to Simon GlassThis function raises an exception with its arguments around the wrong way so the message is incorrect. Fix this as well as a few minor comment problems.
---
Changes in v2: None
tools/binman/entry.py | 8 ++++---- tools/binman/ftest.py | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-)
tools/binman/entry.py +4 -4
@@ -237,25 +237,25 @@ class Entry(object): This sets both the data and content_size properties Args: - data: Data to set to the contents (string) + data: Data to set to the contents (bytes) """ self.data = data self.contents_size = len(self.data) def ProcessContentsUpdate(self, data): - """Update the contens of an entry, after the size is fixed + """Update the contents of an entry, after the size is fixed This checks that the new data is the same size as the old. Args: - data: Data to set to the contents (string) + data: Data to set to the contents (bytes) Raises: ValueError if the new data size is not the same as the old """ if len(data) != self.contents_size: self.Raise('Cannot update entry size from %d to %d' % - (len(data), self.contents_size)) + (self.contents_size, len(data))) self.SetContents(data) def ObtainContents(self):
tools/binman/ftest.py +1 -1
@@ -1223,7 +1223,7 @@ class TestFunctional(unittest.TestCase): with self.assertRaises(ValueError) as e: self._DoReadFile('059_change_size.dts', True) self.assertIn("Node '/binman/_testing': Cannot update entry size from " - '2 to 1', str(e.exception)) + '1 to 2', str(e.exception)) def testUpdateFdt(self): """Test that we can update the device tree with offset/size info"""
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 11/31 binman: Fix up ProcessUpdateContents error and comments
This function raises an exception with its arguments around the wrong way so the message is incorrect. Fix this as well as a few minor comment problems.
---
Changes in v2: None
tools/binman/entry.py | 8 ++++---- tools/binman/ftest.py | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-)
Applied to u-boot-dm, thanks!
PATCH v2 12/31 binman: Call ProcessUpdateContents() consistently
In reply to Simon GlassSetContents() should only be called to set the contents of an entry from within the ObtainContents() call, since it has no guard against increasing the size of the contents, thus triggering incorrect operation.
Change all such calls to use ProcessUpdateContents() instead.
---
Changes in v2: None
tools/binman/etype/blob_dtb.py | 2 +- tools/binman/etype/fdtmap.py | 2 +- tools/binman/etype/fmap.py | 2 +- tools/binman/etype/image_header.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-)
tools/binman/etype/blob_dtb.py +1 -1
@@ -30,4 +30,4 @@ class Entry_blob_dtb(Entry_blob): def ProcessContents(self): """Re-read the DTB contents so that we get any calculated properties""" _, data = state.GetFdtContents(self._filename) - self.SetContents(data) + self.ProcessContentsUpdate(data)
tools/binman/etype/fdtmap.py +1 -1
@@ -106,4 +106,4 @@ class Entry_fdtmap(Entry): This is necessary since new data may have been written back to it during processing, e.g. the image-pos properties. """ - self.SetContents(self._GetFdtmap()) + self.ProcessContentsUpdate(self._GetFdtmap())
tools/binman/etype/fmap.py +1 -1
@@ -62,4 +62,4 @@ class Entry_fmap(Entry): return True def ProcessContents(self): - self.SetContents(self._GetFmap()) + self.ProcessContentsUpdate(self._GetFmap())
tools/binman/etype/image_header.py +1 -1
@@ -73,4 +73,4 @@ class Entry_image_header(Entry): This is necessary since image_pos is not available when ObtainContents() is called, since by then the entries have not been packed in the image. """ - self.SetContents(self._GetHeader()) + self.ProcessContentsUpdate(self._GetHeader())
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 12/31 binman: Call ProcessUpdateContents() consistently
SetContents() should only be called to set the contents of an entry from within the ObtainContents() call, since it has no guard against increasing the size of the contents, thus triggering incorrect operation.
Change all such calls to use ProcessUpdateContents() instead.
---
Changes in v2: None
tools/binman/etype/blob_dtb.py | 2 +- tools/binman/etype/fdtmap.py | 2 +- tools/binman/etype/fmap.py | 2 +- tools/binman/etype/image_header.py | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-)
Applied to u-boot-dm, thanks!
PATCH v2 13/31 binman: Add a return value to ProcessContentsUpdate()
In reply to Simon GlassAt present if this function tries to update the contents such that the size changes, it raises an error. We plan to add the ability to change the size of entries after packing is completed, since in some cases it is not possible to determine the size in advance.
An example of this is with a compressed device tree, where the values of the device tree change in SetCalculatedProperties() or ProcessEntryContents(). While the device tree itself does not change size, since placeholders for any new properties have already bee added by AddMissingProperties(), we cannot predict the size of the device tree after compression. If a value changes from 0 to 0x1234 (say), then the compressed device tree may expand.
As a first step towards supporting this, make ProcessContentsUpdate() return a value indicating whether the content size is OK. For now this is always True (since otherwise binman raises an error), but later patches will adjust this.
---
Changes in v2: None
tools/binman/bsection.py | 8 +++++++- tools/binman/entry.py | 22 +++++++++++++++++++-- tools/binman/etype/_testing.py | 5 +++-- tools/binman/etype/blob_dtb.py | 2 +- tools/binman/etype/fdtmap.py | 2 +- tools/binman/etype/fmap.py | 2 +- tools/binman/etype/image_header.py | 2 +- tools/binman/etype/section.py | 5 +++-- tools/binman/etype/u_boot_with_ucode_ptr.py | 6 +++--- tools/binman/image.py | 5 ++++- 10 files changed, 44 insertions(+), 15 deletions(-)
tools/binman/bsection.py +7 -1
@@ -317,9 +317,15 @@ class Section(object): """Call the ProcessContents() method for each entry This is intended to adjust the contents as needed by the entry type. + + Returns: + True if no entries needed to change their size """ + sizes_ok = True for entry in self._entries.values(): - entry.ProcessContents() + if not entry.ProcessContents(): + sizes_ok = False + return sizes_ok def WriteSymbols(self): """Write symbol values into binary files for access at run time"""
tools/binman/entry.py +20 -2
@@ -245,7 +245,8 @@ class Entry(object): def ProcessContentsUpdate(self, data): """Update the contents of an entry, after the size is fixed - This checks that the new data is the same size as the old. + This checks that the new data is the same size as the old. If the size + has changed, this triggers a re-run of the packing algorithm. Args: data: Data to set to the contents (bytes)
@@ -253,10 +254,12 @@ class Entry(object): Raises: ValueError if the new data size is not the same as the old """ + size_ok = True if len(data) != self.contents_size: self.Raise('Cannot update entry size from %d to %d' % (self.contents_size, len(data))) self.SetContents(data) + return size_ok def ObtainContents(self): """Figure out the contents of an entry.
@@ -401,7 +404,22 @@ class Entry(object): self.image_pos = image_pos + self.offset def ProcessContents(self): - pass + """Do any post-packing updates of entry contents + + This function should call ProcessContentsUpdate() to update the entry + contents, if necessary, returning its return value here. + + Args: + data: Data to set to the contents (bytes) + + Returns: + True if the new data size is OK, False if expansion is needed + + Raises: + ValueError if the new data size is not the same as the old and + state.AllowEntryExpansion() is False + """ + return True def WriteSymbols(self, section): """Write symbol values into binary files for access at run time
tools/binman/etype/_testing.py +3 -2
@@ -88,9 +88,10 @@ class Entry__testing(Entry): def ProcessContents(self): if self.bad_update_contents: - # Request to update the conents with something larger, to cause a + # Request to update the contents with something larger, to cause a # failure. - self.ProcessContentsUpdate('aa') + return self.ProcessContentsUpdate('aa') + return True def ProcessFdt(self, fdt): """Force reprocessing the first time"""
tools/binman/etype/blob_dtb.py +1 -1
@@ -30,4 +30,4 @@ class Entry_blob_dtb(Entry_blob): def ProcessContents(self): """Re-read the DTB contents so that we get any calculated properties""" _, data = state.GetFdtContents(self._filename) - self.ProcessContentsUpdate(data) + return self.ProcessContentsUpdate(data)
tools/binman/etype/fdtmap.py +1 -1
@@ -106,4 +106,4 @@ class Entry_fdtmap(Entry): This is necessary since new data may have been written back to it during processing, e.g. the image-pos properties. """ - self.ProcessContentsUpdate(self._GetFdtmap()) + return self.ProcessContentsUpdate(self._GetFdtmap())
tools/binman/etype/fmap.py +1 -1
@@ -62,4 +62,4 @@ class Entry_fmap(Entry): return True def ProcessContents(self): - self.ProcessContentsUpdate(self._GetFmap()) + return self.ProcessContentsUpdate(self._GetFmap())
tools/binman/etype/image_header.py +1 -1
@@ -73,4 +73,4 @@ class Entry_image_header(Entry): This is necessary since image_pos is not available when ObtainContents() is called, since by then the entries have not been packed in the image. """ - self.ProcessContentsUpdate(self._GetHeader()) + return self.ProcessContentsUpdate(self._GetHeader())
tools/binman/etype/section.py +3 -2
@@ -85,8 +85,9 @@ class Entry_section(Entry): self._section.SetCalculatedProperties() def ProcessContents(self): - self._section.ProcessEntryContents() - super(Entry_section, self).ProcessContents() + sizes_ok = self._section.ProcessEntryContents() + sizes_ok_base = super(Entry_section, self).ProcessContents() + return sizes_ok and sizes_ok_base def CheckOffset(self): self._section.CheckEntries()
tools/binman/etype/u_boot_with_ucode_ptr.py +3 -3
@@ -91,6 +91,6 @@ class Entry_u_boot_with_ucode_ptr(Entry_blob): # Write the microcode offset and size into the entry offset_and_size = struct.pack('<2L', offset, size) self.target_offset -= self.image_pos - self.ProcessContentsUpdate(self.data[:self.target_offset] + - offset_and_size + - self.data[self.target_offset + 8:]) + return self.ProcessContentsUpdate(self.data[:self.target_offset] + + offset_and_size + + self.data[self.target_offset + 8:])
tools/binman/image.py +4 -1
@@ -122,8 +122,11 @@ class Image: """Call the ProcessContents() method for each entry This is intended to adjust the contents as needed by the entry type. + + Returns: + True if the new data size is OK, False if expansion is needed """ - self._section.ProcessEntryContents() + return self._section.ProcessEntryContents() def WriteSymbols(self): """Write symbol values into binary files for access@run time"""
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 13/31 binman: Add a return value to ProcessContentsUpdate()
At present if this function tries to update the contents such that the size changes, it raises an error. We plan to add the ability to change the size of entries after packing is completed, since in some cases it is not possible to determine the size in advance.
An example of this is with a compressed device tree, where the values of the device tree change in SetCalculatedProperties() or ProcessEntryContents(). While the device tree itself does not change size, since placeholders for any new properties have already bee added by AddMissingProperties(), we cannot predict the size of the device tree after compression. If a value changes from 0 to 0x1234 (say), then the compressed device tree may expand.
As a first step towards supporting this, make ProcessContentsUpdate() return a value indicating whether the content size is OK. For now this is always True (since otherwise binman raises an error), but later patches will adjust this.
---
Changes in v2: None
tools/binman/bsection.py | 8 +++++++- tools/binman/entry.py | 22 +++++++++++++++++++-- tools/binman/etype/_testing.py | 5 +++-- tools/binman/etype/blob_dtb.py | 2 +- tools/binman/etype/fdtmap.py | 2 +- tools/binman/etype/fmap.py | 2 +- tools/binman/etype/image_header.py | 2 +- tools/binman/etype/section.py | 5 +++-- tools/binman/etype/u_boot_with_ucode_ptr.py | 6 +++--- tools/binman/image.py | 5 ++++- 10 files changed, 44 insertions(+), 15 deletions(-)
Applied to u-boot-dm, thanks!
PATCH v2 14/31 binman: Add a control for post-pack entry expansion
In reply to Simon GlassWe plan to support changing the size of entries after they have been packed. For now it will always be enabled. But to aid testing of both cases (in the event that we want to add a command-line flag, for example), add a setting to control it.
---
Changes in v2: None
tools/binman/state.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+)
tools/binman/state.py +24 -0
@@ -31,6 +31,11 @@ fdt_subset = set() # The DTB which contains the full image information main_dtb = None +# Allow entries to expand after they have been packed. This is detected and +# forces a re-pack. If not allowed, any attempted expansion causes an error in +# Entry.ProcessContentsUpdate() +allow_entry_expansion = True + def GetFdt(fname): """Get the Fdt object for a particular device-tree filename
@@ -250,3 +255,22 @@ def CheckSetHashValue(node, get_data_func): data = m.digest() for n in GetUpdateNodes(hash_node): n.SetData('value', data) + +def SetAllowEntryExpansion(allow): + """Set whether post-pack expansion of entries is allowed + + Args: + allow: True to allow expansion, False to raise an exception + """ + global allow_entry_expansion + + allow_entry_expansion = allow + +def AllowEntryExpansion(): + """Check whether post-pack expansion of entries is allowed + + Returns: + True if expansion should be allowed, False if an exception should be + raised + """ + return allow_entry_expansion
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 14/31 binman: Add a control for post-pack entry expansion
We plan to support changing the size of entries after they have been packed. For now it will always be enabled. But to aid testing of both cases (in the event that we want to add a command-line flag, for example), add a setting to control it.
---
Changes in v2: None
tools/binman/state.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+)
Applied to u-boot-dm, thanks!
PATCH v2 15/31 binman: Allow entries to expand after packing
In reply to Simon GlassAdd support for detecting entries that change size after they have already been packed, and re-running packing when it happens.
This removes the limitation that entry size cannot change after PackEntries() is called.
---
Changes in v2:
- Avoid dual assignment in ResetForPack()
- Show a message when a section's size changes
- Use 3 packing passes instead of two, and add a comment
- Use bytearray for Python 3
tools/binman/README | 3 +- tools/binman/bsection.py | 12 +++++ tools/binman/control.py | 51 +++++++++++++------ tools/binman/entry.py | 21 +++++++- tools/binman/etype/_testing.py | 11 +++- tools/binman/etype/section.py | 5 ++ tools/binman/etype/u_boot_with_ucode_ptr.py | 2 +- tools/binman/ftest.py | 33 ++++++++++-- tools/binman/image.py | 8 +++ tools/binman/test/121_entry_expand.dts | 20 ++++++++ tools/binman/test/122_entry_expand_twice.dts | 21 ++++++++ .../binman/test/123_entry_expand_section.dts | 22 ++++++++ 12 files changed, 184 insertions(+), 25 deletions(-) create mode 100644 tools/binman/test/121_entry_expand.dts create mode 100644 tools/binman/test/122_entry_expand_twice.dts create mode 100644 tools/binman/test/123_entry_expand_section.dts
tools/binman/README +2 -1
@@ -566,7 +566,8 @@ tree. This sets the correct 'offset' and 'size' vaues, for example. The default implementatoin does nothing. This can be overriden to adjust the contents of an entry in some way. For example, it would be possible to create an entry containing a hash of the contents of some other entries. At this -stage the offset and size of entries should not be adjusted. +stage the offset and size of entries should not be adjusted unless absolutely +necessary, since it requires a repack (going back to PackEntries()). 10. WriteSymbols() - write the value of symbols into the U-Boot SPL binary. See 'Access to binman entry offsets at run time' below for a description of
tools/binman/bsection.py +12 -0
@@ -45,6 +45,8 @@ class Section(object): _name_prefix: Prefix to add to the name of all entries within this section _entries: OrderedDict() of entries + _orig_offset: Original offset value read from node + _orig_size: Original size value read from node """ def __init__(self, name, parent_section, node, image, test=False): global entry
@@ -76,6 +78,8 @@ class Section(object): """Read properties from the section node""" self._offset = fdt_util.GetInt(self._node, 'offset') self._size = fdt_util.GetInt(self._node, 'size') + self._orig_offset = self._offset + self._orig_size = self._size self._align_size = fdt_util.GetInt(self._node, 'align-size') if tools.NotPowerOfTwo(self._align_size): self._Raise("Alignment size %s must be a power of two" %
@@ -257,6 +261,13 @@ class Section(object): for name, info in offset_dict.items(): self._SetEntryOffsetSize(name, *info) + def ResetForPack(self): + """Reset offset/size fields so that packing can be done again""" + self._offset = self._orig_offset + self._size = self._orig_size + for entry in self._entries.values(): + entry.ResetForPack() + def PackEntries(self): """Pack all entries into the section""" offset = self._skip_at_start
@@ -325,6 +336,7 @@ class Section(object): for entry in self._entries.values(): if not entry.ProcessContents(): sizes_ok = False + print("Entry '%s' size change" % self._node.path) return sizes_ok def WriteSymbols(self):
tools/binman/control.py +36 -15
57 lines not on this page · raw message
tools/binman/entry.py +19 -2
@@ -61,6 +61,8 @@ class Entry(object): pad_after: Number of pad bytes after the contents, 0 if none data: Contents of entry (string of bytes) compress: Compression algoithm used (e.g. 'lz4'), 'none' if none + orig_offset: Original offset value read from node + orig_size: Original size value read from node """ def __init__(self, section, etype, node, read_node=True, name_prefix=''): self.section = section
@@ -153,6 +155,9 @@ class Entry(object): self.Raise("Please use 'offset' instead of 'pos'") self.offset = fdt_util.GetInt(self._node, 'offset') self.size = fdt_util.GetInt(self._node, 'size') + self.orig_offset = self.offset + self.orig_size = self.size + self.align = fdt_util.GetInt(self._node, 'align') if tools.NotPowerOfTwo(self.align): raise ValueError("Node '%s': Alignment %s must be a power of two" %
@@ -255,9 +260,16 @@ class Entry(object): ValueError if the new data size is not the same as the old """ size_ok = True - if len(data) != self.contents_size: + new_size = len(data) + if state.AllowEntryExpansion(): + if new_size > self.contents_size: + print("Entry '%s' size change from %#x to %#x" % ( + self._node.path, self.contents_size, new_size)) + # self.data will indicate the new size needed + size_ok = False + elif new_size != self.contents_size: self.Raise('Cannot update entry size from %d to %d' % - (self.contents_size, len(data))) + (self.contents_size, new_size)) self.SetContents(data) return size_ok
@@ -271,6 +283,11 @@ class Entry(object): # No contents by default: subclasses can implement this return True + def ResetForPack(self): + """Reset offset/size fields so that packing can be done again""" + self.offset = self.orig_offset + self.size = self.orig_size + def Pack(self, offset): """Figure out how to pack the entry into the section
tools/binman/etype/_testing.py +9 -2
@@ -50,6 +50,8 @@ class Entry__testing(Entry): 'bad-update-contents') self.return_contents_once = fdt_util.GetBool(self._node, 'return-contents-once') + self.bad_update_contents_twice = fdt_util.GetBool(self._node, + 'bad-update-contents-twice') # Set to True when the entry is ready to process the FDT. self.process_fdt_ready = False
@@ -71,11 +73,12 @@ class Entry__testing(Entry): if self.force_bad_datatype: self.GetEntryArgsOrProps([EntryArg('test-bad-datatype-arg', bool)]) self.return_contents = True + self.contents = b'a' def ObtainContents(self): if self.return_unknown_contents or not self.return_contents: return False - self.data = b'a' + self.data = self.contents self.contents_size = len(self.data) if self.return_contents_once: self.return_contents = False
@@ -90,7 +93,11 @@ class Entry__testing(Entry): if self.bad_update_contents: # Request to update the contents with something larger, to cause a # failure. - return self.ProcessContentsUpdate('aa') + if self.bad_update_contents_twice: + self.contents += b'a' + else: + self.contents = b'aa' + return self.ProcessContentsUpdate(self.contents) return True def ProcessFdt(self, fdt):
tools/binman/etype/section.py +5 -0
@@ -64,6 +64,11 @@ class Entry_section(Entry): self._section.GetEntryOffsets() return {} + def ResetForPack(self): + """Reset offset/size fields so that packing can be done again""" + self._section.ResetForPack() + Entry.ResetForPack(self) + def Pack(self, offset): """Pack all entries into the section""" self._section.PackEntries()
tools/binman/etype/u_boot_with_ucode_ptr.py +1 -1
@@ -49,7 +49,7 @@ class Entry_u_boot_with_ucode_ptr(Entry_blob): def ProcessContents(self): # If the image does not need microcode, there is nothing to do if not self.target_offset: - return + return True # Get the offset of the microcode ucode_entry = self.section.FindEntryType('u-boot-ucode')
tools/binman/ftest.py +29 -4
@@ -1220,10 +1220,14 @@ class TestFunctional(unittest.TestCase): def testBadChangeSize(self): """Test that trying to change the size of an entry fails""" - with self.assertRaises(ValueError) as e: - self._DoReadFile('059_change_size.dts', True) - self.assertIn("Node '/binman/_testing': Cannot update entry size from " - '1 to 2', str(e.exception)) + try: + state.SetAllowEntryExpansion(False) + with self.assertRaises(ValueError) as e: + self._DoReadFile('059_change_size.dts', True) + self.assertIn("Node '/binman/_testing': Cannot update entry size from 1 to 2", + str(e.exception)) + finally: + state.SetAllowEntryExpansion(True) def testUpdateFdt(self): """Test that we can update the device tree with offset/size info"""
@@ -2117,6 +2121,27 @@ class TestFunctional(unittest.TestCase): self.assertIn("Invalid location 'None', expected 'start' or 'end'", str(e.exception)) + def testEntryExpand(self): + """Test expanding an entry after it is packed""" + data = self._DoReadFile('121_entry_expand.dts') + self.assertEqual(b'aa', data[:2]) + self.assertEqual(U_BOOT_DATA, data[2:2 + len(U_BOOT_DATA)]) + self.assertEqual(b'aa', data[-2:]) + + def testEntryExpandBad(self): + """Test expanding an entry after it is packed, twice""" + with self.assertRaises(ValueError) as e: + self._DoReadFile('122_entry_expand_twice.dts') + self.assertIn("Image '/binman': Entries expanded after packing", + str(e.exception)) + + def testEntryExpandSection(self): + """Test expanding an entry within a section after it is packed""" + data = self._DoReadFile('123_entry_expand_section.dts') + self.assertEqual(b'aa', data[:2]) + self.assertEqual(U_BOOT_DATA, data[2:2 + len(U_BOOT_DATA)]) + self.assertEqual(b'aa', data[-2:]) + if __name__ == "__main__": unittest.main()
tools/binman/image.py +8 -0
@@ -55,6 +55,10 @@ class Image: self._filename = filename self._section = bsection.Section('main-section', None, self._node, self) + def Raise(self, msg): + """Convenience function to raise an error referencing an image""" + raise ValueError("Image '%s': %s" % (self._node.path, msg)) + def GetFdtSet(self): """Get the set of device tree files used by this image""" return self._section.GetFdtSet()
@@ -100,6 +104,10 @@ class Image: """ self._section.GetEntryOffsets() + def ResetForPack(self): + """Reset offset/size fields so that packing can be done again""" + self._section.ResetForPack() + def PackEntries(self): """Pack all entries into the image""" self._section.PackEntries()
tools/binman/test/121_entry_expand.dts new file +20 -0
@@ -0,0 +1,20 @@ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + binman { + _testing { + bad-update-contents; + }; + + u-boot { + }; + + _testing2 { + type = "_testing"; + bad-update-contents; + }; + }; +};
tools/binman/test/122_entry_expand_twice.dts new file +21 -0
@@ -0,0 +1,21 @@ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + binman { + _testing { + bad-update-contents; + bad-update-contents-twice; + }; + + u-boot { + }; + + _testing2 { + type = "_testing"; + bad-update-contents; + }; + }; +};
tools/binman/test/123_entry_expand_section.dts new file +22 -0
@@ -0,0 +1,22 @@ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + binman { + _testing { + bad-update-contents; + }; + + u-boot { + }; + + section { + _testing2 { + type = "_testing"; + bad-update-contents; + }; + }; + }; +};
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 15/31 binman: Allow entries to expand after packing
Add support for detecting entries that change size after they have already been packed, and re-running packing when it happens.
This removes the limitation that entry size cannot change after PackEntries() is called.
---
Changes in v2:
- Avoid dual assignment in ResetForPack()
- Show a message when a section's size changes
- Use 3 packing passes instead of two, and add a comment
- Use bytearray for Python 3
tools/binman/README | 3 +- tools/binman/bsection.py | 12 +++++ tools/binman/control.py | 51 +++++++++++++------ tools/binman/entry.py | 21 +++++++- tools/binman/etype/_testing.py | 11 +++- tools/binman/etype/section.py | 5 ++ tools/binman/etype/u_boot_with_ucode_ptr.py | 2 +- tools/binman/ftest.py | 33 ++++++++++-- tools/binman/image.py | 8 +++ tools/binman/test/121_entry_expand.dts | 20 ++++++++ tools/binman/test/122_entry_expand_twice.dts | 21 ++++++++ .../binman/test/123_entry_expand_section.dts | 22 ++++++++ 12 files changed, 184 insertions(+), 25 deletions(-) create mode 100644 tools/binman/test/121_entry_expand.dts create mode 100644 tools/binman/test/122_entry_expand_twice.dts create mode 100644 tools/binman/test/123_entry_expand_section.dts
Applied to u-boot-dm, thanks!
PATCH v2 16/31 binman: Allow device-tree entries to be compressed
In reply to Simon GlassAt present the logic skips the blob class' handling of compression, so this is not supported with device tree entries. Fix this.
---
Changes in v2:
- Update test to use _DoReadFileRealDtb() helper
tools/binman/etype/blob.py | 25 +++++++++++++++++-------- tools/binman/etype/blob_dtb.py | 8 ++++---- tools/binman/ftest.py | 18 ++++++++++++++++++ tools/binman/test/124_compress_dtb.dts | 14 ++++++++++++++ 4 files changed, 53 insertions(+), 12 deletions(-) create mode 100644 tools/binman/test/124_compress_dtb.dts
tools/binman/etype/blob.py +17 -8
@@ -41,17 +41,26 @@ class Entry_blob(Entry): self.ReadBlobContents() return True - def ReadBlobContents(self): - # We assume the data is small enough to fit into memory. If this - # is used for large filesystem image that might not be true. - # In that case, Image.BuildImage() could be adjusted to use a - # new Entry method which can read in chunks. Then we could copy - # the data in chunks and avoid reading it all at once. For now - # this seems like an unnecessary complication. - indata = tools.ReadFile(self._pathname) + def CompressData(self, indata): if self.compress != 'none': self.uncomp_size = len(indata) data = tools.Compress(indata, self.compress) + return data + + def ReadBlobContents(self): + """Read blob contents into memory + + This function compresses the data before storing if needed. + + We assume the data is small enough to fit into memory. If this + is used for large filesystem image that might not be true. + In that case, Image.BuildImage() could be adjusted to use a + new Entry method which can read in chunks. Then we could copy + the data in chunks and avoid reading it all at once. For now + this seems like an unnecessary complication. + """ + indata = tools.ReadFile(self._pathname) + data = self.CompressData(indata) self.SetContents(data) return True
tools/binman/etype/blob_dtb.py +4 -4
@@ -23,11 +23,11 @@ class Entry_blob_dtb(Entry_blob): def ObtainContents(self): """Get the device-tree from the list held by the 'state' module""" self._filename = self.GetDefaultFilename() - self._pathname, data = state.GetFdtContents(self._filename) - self.SetContents(data) - return True + self._pathname, _ = state.GetFdtContents(self._filename) + return Entry_blob.ReadBlobContents(self) def ProcessContents(self): """Re-read the DTB contents so that we get any calculated properties""" - _, data = state.GetFdtContents(self._filename) + _, indata = state.GetFdtContents(self._filename) + data = self.CompressData(indata) return self.ProcessContentsUpdate(data)
tools/binman/ftest.py +18 -0
@@ -2142,6 +2142,24 @@ class TestFunctional(unittest.TestCase): self.assertEqual(U_BOOT_DATA, data[2:2 + len(U_BOOT_DATA)]) self.assertEqual(b'aa', data[-2:]) + def testCompressDtb(self): + """Test that compress of device-tree files is supported""" + self._CheckLz4() + data = self.data = self._DoReadFileRealDtb('124_compress_dtb.dts') + self.assertEqual(U_BOOT_DATA, data[:len(U_BOOT_DATA)]) + comp_data = data[len(U_BOOT_DATA):] + orig = self._decompress(comp_data) + dtb = fdt.Fdt.FromData(orig) + dtb.Scan() + props = self._GetPropTree(dtb, ['size', 'uncomp-size']) + expected = { + 'u-boot:size': len(U_BOOT_DATA), + 'u-boot-dtb:uncomp-size': len(orig), + 'u-boot-dtb:size': len(comp_data), + 'size': len(data), + } + self.assertEqual(expected, props) + if __name__ == "__main__": unittest.main()
tools/binman/test/124_compress_dtb.dts new file +14 -0
@@ -0,0 +1,14 @@ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + binman { + u-boot { + }; + u-boot-dtb { + compress = "lz4"; + }; + }; +};
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 16/31 binman: Allow device-tree entries to be compressed
At present the logic skips the blob class' handling of compression, so this is not supported with device tree entries. Fix this.
---
Changes in v2:
- Update test to use _DoReadFileRealDtb() helper
tools/binman/etype/blob.py | 25 +++++++++++++++++-------- tools/binman/etype/blob_dtb.py | 8 ++++---- tools/binman/ftest.py | 18 ++++++++++++++++++ tools/binman/test/124_compress_dtb.dts | 14 ++++++++++++++ 4 files changed, 53 insertions(+), 12 deletions(-) create mode 100644 tools/binman/test/124_compress_dtb.dts
Applied to u-boot-dm, thanks!
PATCH v2 17/31 binman: Provide the actual data address for cbfs files
In reply to Simon GlassAt present a file with no explicit CBFS offset is placed in the next available location but there is no way to find out where it ended up. Update and rename the get_data() function to provide this information.
---
Changes in v2: None
tools/binman/cbfs_util.py | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-)
tools/binman/cbfs_util.py +20 -11
@@ -185,7 +185,8 @@ class CbfsFile(object): """Class to represent a single CBFS file This is used to hold the information about a file, including its contents. - Use the get_data() method to obtain the raw output for writing to CBFS. + Use the get_data_and_offset() method to obtain the raw output for writing to + CBFS. Properties: name: Name of file
@@ -319,12 +320,15 @@ class CbfsFile(object): raise ValueError('Unknown file type %#x\n' % self.ftype) return hdr_len - def get_data(self, offset=None, pad_byte=None): - """Obtain the contents of the file, in CBFS format + def get_data_and_offset(self, offset=None, pad_byte=None): + """Obtain the contents of the file, in CBFS format and the offset of + the data within the file Returns: - bytes representing the contents of this file, packed and aligned - for directly inserting into the final CBFS output + tuple: + bytes representing the contents of this file, packed and aligned + for directly inserting into the final CBFS output + offset to the file data from the start of the returned data. """ name = _pack_string(self.name) hdr_len = len(name) + FILE_HEADER_LEN
@@ -368,8 +372,10 @@ class CbfsFile(object): (self.name, self.cbfs_offset, offset)) pad = tools.GetBytes(pad_byte, pad_len) hdr_len += pad_len - self.offset = len(content) + len(data) - hdr = struct.pack(FILE_HEADER_FORMAT, FILE_MAGIC, self.offset, + + # This is the offset of the start of the file's data, + size = len(content) + len(data) + hdr = struct.pack(FILE_HEADER_FORMAT, FILE_MAGIC, size, self.ftype, attr_pos, hdr_len) # Do a sanity check of the get_header_len() function, to ensure that it
@@ -381,7 +387,7 @@ class CbfsFile(object): # happen. It probably indicates that get_header_len() is broken. raise ValueError("Internal error: CBFS file '%s': Expected headers of %#x bytes, got %#d" % (self.name, expected_len, actual_len)) - return hdr + name + attr + pad + content + data + return hdr + name + attr + pad + content + data, hdr_len class CbfsWriter(object):
@@ -392,7 +398,7 @@ class CbfsWriter(object): cbw = CbfsWriter(size) cbw.add_file_raw('u-boot', tools.ReadFile('u-boot.bin')) ... - data = cbw.get_data() + data, cbfs_offset = cbw.get_data_and_offset() Attributes: _master_name: Name of the file containing the master header
@@ -475,7 +481,7 @@ class CbfsWriter(object): todo = align_int_down(offset - upto, self._align) if todo: cbf = CbfsFile.empty(todo, self._erase_byte) - fd.write(cbf.get_data()) + fd.write(cbf.get_data_and_offset()[0]) self._skip_to(fd, offset) def _align_to(self, fd, align):
@@ -579,8 +585,11 @@ class CbfsWriter(object): offset = cbf.calc_start_offset() if offset is not None: self._pad_to(fd, align_int_down(offset, self._align)) - fd.write(cbf.get_data(fd.tell(), self._erase_byte)) + pos = fd.tell() + data, data_offset = cbf.get_data_and_offset(pos, self._erase_byte) + fd.write(data) self._align_to(fd, self._align) + cbf.calced_cbfs_offset = pos + data_offset if not self._hdr_at_start: self._write_header(fd, add_fileheader=self._add_fileheader)
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 17/31 binman: Provide the actual data address for cbfs files
At present a file with no explicit CBFS offset is placed in the next available location but there is no way to find out where it ended up. Update and rename the get_data() function to provide this information.
---
Changes in v2: None
tools/binman/cbfs_util.py | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-)
Applied to u-boot-dm, thanks!
PATCH v2 18/31 binman: Use the cbfs memlen field only for uncompressed length
In reply to Simon GlassThe purpose of this badly named field is a bit ambiguous. Adjust the code to use it only to store the uncompressed length of a file, leaving it set to None if there is no compression used. This makes it easy to see if the value in this field is relevant / useful.
Also set data_len for compressed fields, since it should be the length of the compressed data, not the uncompressed data.
---
Changes in v2: None
tools/binman/cbfs_util.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-)
tools/binman/cbfs_util.py +7 -4
@@ -197,7 +197,8 @@ class CbfsFile(object): data_len: Length of (possibly compressed) data in bytes ftype: File type (TYPE_...) compression: Compression type (COMPRESS_...) - memlen: Length of data in memory (typically the uncompressed length) + memlen: Length of data in memory, i.e. the uncompressed length, None if + no compression algortihm is selected load: Load address in memory if known, else None entry: Entry address in memory if known, else None. This is where execution starts after the file is loaded
@@ -213,11 +214,11 @@ class CbfsFile(object): self.data = data self.ftype = ftype self.compress = compress - self.memlen = len(data) + self.memlen = None self.load = None self.entry = None self.base_address = None - self.data_len = 0 + self.data_len = len(data) self.erase_byte = None self.size = None
@@ -349,9 +350,11 @@ class CbfsFile(object): data = tools.Compress(orig_data, 'lz4') elif self.compress == COMPRESS_LZMA: data = tools.Compress(orig_data, 'lzma') + self.memlen = len(orig_data) + self.data_len = len(data) attr = struct.pack(ATTR_COMPRESSION_FORMAT, FILE_ATTR_TAG_COMPRESSION, ATTR_COMPRESSION_LEN, - self.compress, len(orig_data)) + self.compress, self.memlen) elif self.ftype == TYPE_EMPTY: data = tools.GetBytes(self.erase_byte, self.size) else:
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 18/31 binman: Use the cbfs memlen field only for uncompressed length
The purpose of this badly named field is a bit ambiguous. Adjust the code to use it only to store the uncompressed length of a file, leaving it set to None if there is no compression used. This makes it easy to see if the value in this field is relevant / useful.
Also set data_len for compressed fields, since it should be the length of the compressed data, not the uncompressed data.
---
Changes in v2: None
tools/binman/cbfs_util.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-)
Applied to u-boot-dm, thanks!
PATCH v2 19/31 binman: Support FDT update for CBFS
In reply to Simon GlassIt is useful to add the CBFS file information (offset, size, etc.) into the FDT so that the layout is complete. Add support for this.
---
Changes in v2: None
tools/binman/etype/cbfs.py | 49 +++++++++++++++++++++++++-- tools/binman/ftest.py | 25 ++++++++++++++ tools/binman/test/125_cbfs_update.dts | 21 ++++++++++++ 3 files changed, 92 insertions(+), 3 deletions(-) create mode 100644 tools/binman/test/125_cbfs_update.dts
tools/binman/etype/cbfs.py +46 -3
@@ -11,6 +11,7 @@ import cbfs_util from cbfs_util import CbfsWriter from entry import Entry import fdt_util +import state class Entry_cbfs(Entry): """Entry containing a Coreboot Filesystem (CBFS)
@@ -181,11 +182,17 @@ class Entry_cbfs(Entry): if not entry.ObtainContents(): return False data = entry.GetData() + cfile = None if entry._type == 'raw': - cbfs.add_file_raw(entry._cbfs_name, data, entry._cbfs_offset, - entry._cbfs_compress) + cfile = cbfs.add_file_raw(entry._cbfs_name, data, + entry._cbfs_offset, + entry._cbfs_compress) elif entry._type == 'stage': - cbfs.add_file_stage(entry._cbfs_name, data, entry._cbfs_offset) + cfile = cbfs.add_file_stage(entry._cbfs_name, data, + entry._cbfs_offset) + if cfile: + entry._cbfs_file = cfile + entry.size = cfile.data_len data = cbfs.get_data() self.SetContents(data) return True
@@ -203,3 +210,39 @@ class Entry_cbfs(Entry): self.Raise("Invalid compression in '%s': '%s'" % (node.name, compress)) self._cbfs_entries[entry._cbfs_name] = entry + + def SetImagePos(self, image_pos): + """Override this function to set all the entry properties from CBFS + + We can only do this once image_pos is known + + Args: + image_pos: Position of this entry in the image + """ + Entry.SetImagePos(self, image_pos) + + # Now update the entries with info from the CBFS entries + for entry in self._cbfs_entries.values(): + cfile = entry._cbfs_file + entry.size = cfile.data_len + entry.offset = cfile.calced_cbfs_offset + entry.image_pos = self.image_pos + entry.offset + if entry._cbfs_compress: + entry.uncomp_size = cfile.memlen + + def AddMissingProperties(self): + Entry.AddMissingProperties(self) + for entry in self._cbfs_entries.values(): + entry.AddMissingProperties() + if entry._cbfs_compress: + state.AddZeroProp(entry._node, 'uncomp-size') + + def SetCalculatedProperties(self): + """Set the value of device-tree properties calculated by binman""" + Entry.SetCalculatedProperties(self) + for entry in self._cbfs_entries.values(): + state.SetInt(entry._node, 'offset', entry.offset) + state.SetInt(entry._node, 'size', entry.size) + state.SetInt(entry._node, 'image-pos', entry.image_pos) + if entry.uncomp_size is not None: + state.SetInt(entry._node, 'uncomp-size', entry.uncomp_size)
tools/binman/ftest.py +25 -0
@@ -2160,6 +2160,31 @@ class TestFunctional(unittest.TestCase): } self.assertEqual(expected, props) + def testCbfsUpdateFdt(self): + """Test that we can update the device tree with CBFS offset/size info""" + self._CheckLz4() + data, _, _, out_dtb_fname = self._DoReadFileDtb('125_cbfs_update.dts', + update_dtb=True) + dtb = fdt.Fdt(out_dtb_fname) + dtb.Scan() + props = self._GetPropTree(dtb, ['offset', 'size', 'image-pos', + 'uncomp-size']) + del props['cbfs/u-boot:size'] + self.assertEqual({ + 'offset': 0, + 'size': len(data), + 'image-pos': 0, + 'cbfs:offset': 0, + 'cbfs:size': len(data), + 'cbfs:image-pos': 0, + 'cbfs/u-boot:offset': 0x38, + 'cbfs/u-boot:uncomp-size': len(U_BOOT_DATA), + 'cbfs/u-boot:image-pos': 0x38, + 'cbfs/u-boot-dtb:offset': 0xb8, + 'cbfs/u-boot-dtb:size': len(U_BOOT_DATA), + 'cbfs/u-boot-dtb:image-pos': 0xb8, + }, props) + if __name__ == "__main__": unittest.main()
tools/binman/test/125_cbfs_update.dts new file +21 -0
@@ -0,0 +1,21 @@ +// SPDX-License-Identifier: GPL-2.0+ + +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + binman { + cbfs { + size = <0x100>; + u-boot { + cbfs-type = "raw"; + cbfs-compress = "lz4"; + }; + u-boot-dtb { + cbfs-type = "raw"; + }; + }; + }; +};
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 19/31 binman: Support FDT update for CBFS
It is useful to add the CBFS file information (offset, size, etc.) into the FDT so that the layout is complete. Add support for this.
---
Changes in v2: None
tools/binman/etype/cbfs.py | 49 +++++++++++++++++++++++++-- tools/binman/ftest.py | 25 ++++++++++++++ tools/binman/test/125_cbfs_update.dts | 21 ++++++++++++ 3 files changed, 92 insertions(+), 3 deletions(-) create mode 100644 tools/binman/test/125_cbfs_update.dts
Applied to u-boot-dm, thanks!
PATCH v2 20/31 binman: Detect bad CBFS file types
In reply to Simon GlassDetect when an unknown or unsupported file type is specified and report an error.
---
Changes in v2: None
tools/binman/etype/cbfs.py | 3 +++ tools/binman/ftest.py | 6 ++++++ tools/binman/test/126_cbfs_bad_type.dts | 17 +++++++++++++++++ 3 files changed, 26 insertions(+) create mode 100644 tools/binman/test/126_cbfs_bad_type.dts
tools/binman/etype/cbfs.py +3 -0
@@ -190,6 +190,9 @@ class Entry_cbfs(Entry): elif entry._type == 'stage': cfile = cbfs.add_file_stage(entry._cbfs_name, data, entry._cbfs_offset) + else: + entry.Raise("Unknown cbfs-type '%s' (use 'raw', 'stage')" % + entry._type) if cfile: entry._cbfs_file = cfile entry.size = cfile.data_len
tools/binman/ftest.py +6 -0
@@ -2185,6 +2185,12 @@ class TestFunctional(unittest.TestCase): 'cbfs/u-boot-dtb:image-pos': 0xb8, }, props) + def testCbfsBadType(self): + """Test an image header with a no specified location is detected""" + with self.assertRaises(ValueError) as e: + self._DoReadFile('126_cbfs_bad_type.dts') + self.assertIn("Unknown cbfs-type 'badtype'", str(e.exception)) + if __name__ == "__main__": unittest.main()
tools/binman/test/126_cbfs_bad_type.dts new file +17 -0
@@ -0,0 +1,17 @@ +// SPDX-License-Identifier: GPL-2.0+ + +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + binman { + cbfs { + size = <0x100>; + u-boot { + cbfs-type = "badtype"; + }; + }; + }; +};
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 20/31 binman: Detect bad CBFS file types
Detect when an unknown or unsupported file type is specified and report an error.
---
Changes in v2: None
tools/binman/etype/cbfs.py | 3 +++ tools/binman/ftest.py | 6 ++++++ tools/binman/test/126_cbfs_bad_type.dts | 17 +++++++++++++++++ 3 files changed, 26 insertions(+) create mode 100644 tools/binman/test/126_cbfs_bad_type.dts
Applied to u-boot-dm, thanks!
PATCH v2 21/31 binman: Allow listing the entries in an image
In reply to Simon GlassIt is useful to be able to summarise all the entries in an image, e.g. to display this to this user. Add a new ListEntries() method to Entry, and set up a way to call it through the Image class.
---
Changes in v2:
- Add the Entry object to EntryInfo as well
- Change Image.ListEntries() to BuildEntryList() since signature differs
tools/binman/bsection.py | 9 ++++ tools/binman/entry.py | 36 ++++++++++++++++ tools/binman/etype/cbfs.py | 7 +++- tools/binman/etype/section.py | 4 ++ tools/binman/ftest.py | 76 ++++++++++++++++++++++++++++++++++ tools/binman/image.py | 10 +++++ tools/binman/test/127_list.dts | 33 +++++++++++++++ 7 files changed, 174 insertions(+), 1 deletion(-) create mode 100644 tools/binman/test/127_list.dts
tools/binman/bsection.py +9 -0
@@ -10,6 +10,7 @@ from __future__ import print_function from collections import OrderedDict import sys +from entry import Entry import fdt_util import re import state
@@ -512,3 +513,11 @@ class Section(object): image size is dynamic and its sections have not yet been packed """ return self._image._size + + def ListEntries(self, entries, indent): + """Override this method to list all files in the section""" + Entry.AddEntryInfo(entries, indent, self._name, 'section', self._size, + self._image_pos, None, self._offset, + self._parent_section) + for entry in self._entries.values(): + entry.ListEntries(entries, indent + 1)
tools/binman/entry.py +36 -0
@@ -33,6 +33,10 @@ our_path = os.path.dirname(os.path.realpath(__file__)) # device-tree properties. EntryArg = namedtuple('EntryArg', ['name', 'datatype']) +# Information about an entry for use when displaying summaries +EntryInfo = namedtuple('EntryInfo', ['indent', 'name', 'etype', 'size', + 'image_pos', 'uncomp_size', 'offset', + 'entry']) class Entry(object): """An Entry in the section
@@ -617,3 +621,35 @@ features to produce new behaviours. if not self.HasSibling(name): return False return self.section.GetEntries()[name].image_pos + + @staticmethod + def AddEntryInfo(entries, indent, name, etype, size, image_pos, + uncomp_size, offset, entry): + """Add a new entry to the entries list + + Args: + entries: List (of EntryInfo objects) to add to + indent: Current indent level to add to list + name: Entry name (string) + etype: Entry type (string) + size: Entry size in bytes (int) + image_pos: Position within image in bytes (int) + uncomp_size: Uncompressed size if the entry uses compression, else + None + offset: Entry offset within parent in bytes (int) + entry: Entry object + """ + entries.append(EntryInfo(indent, name, etype, size, image_pos, + uncomp_size, offset, entry)) + + def ListEntries(self, entries, indent): + """Add files in this entry to the list of entries + + This can be overridden by subclasses which need different behaviour. + + Args: + entries: List (of EntryInfo objects) to add to + indent: Current indent level to add to list + """ + self.AddEntryInfo(entries, indent, self.name, self.etype, self.size, + self.image_pos, self.uncomp_size, self.offset, self)
tools/binman/etype/cbfs.py +6 -1
@@ -195,7 +195,6 @@ class Entry_cbfs(Entry): entry._type) if cfile: entry._cbfs_file = cfile - entry.size = cfile.data_len data = cbfs.get_data() self.SetContents(data) return True
@@ -249,3 +248,9 @@ class Entry_cbfs(Entry): state.SetInt(entry._node, 'image-pos', entry.image_pos) if entry.uncomp_size is not None: state.SetInt(entry._node, 'uncomp-size', entry.uncomp_size) + + def ListEntries(self, entries, indent): + """Override this method to list all files in the section""" + Entry.ListEntries(self, entries, indent) + for entry in self._cbfs_entries.values(): + entry.ListEntries(entries, indent + 1)
tools/binman/etype/section.py +4 -0
@@ -111,3 +111,7 @@ class Entry_section(Entry): def ExpandToLimit(self, limit): super(Entry_section, self).ExpandToLimit(limit) self._section.ExpandSize(self.size) + + def ListEntries(self, entries, indent): + """List the files in the section""" + self._section.ListEntries(entries, indent)
tools/binman/ftest.py +76 -0
82 lines not on this page · raw message
tools/binman/image.py +10 -0
@@ -162,3 +162,13 @@ class Image: file=fd) self._section.WriteMap(fd, 0) return fname + + def BuildEntryList(self): + """List the files in an image + + Returns: + List of entry.EntryInfo objects describing all entries in the image + """ + entries = [] + self._section.ListEntries(entries, 0) + return entries
tools/binman/test/127_list.dts new file +33 -0
@@ -0,0 +1,33 @@ +// SPDX-License-Identifier: GPL-2.0+ + +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + binman { + u-boot { + }; + section { + align = <0x100>; + cbfs { + size = <0x400>; + u-boot { + cbfs-type = "raw"; + cbfs-offset = <0x38>; + }; + u-boot-dtb { + type = "text"; + text = "compress xxxxxxxxxxxxxxxxxxxxxx data"; + cbfs-type = "raw"; + cbfs-compress = "lzma"; + cbfs-offset = <0x78>; + }; + }; + u-boot-dtb { + compress = "lz4"; + }; + }; + }; +};
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 21/31 binman: Allow listing the entries in an image
It is useful to be able to summarise all the entries in an image, e.g. to display this to this user. Add a new ListEntries() method to Entry, and set up a way to call it through the Image class.
---
Changes in v2:
- Add the Entry object to EntryInfo as well
- Change Image.ListEntries() to BuildEntryList() since signature differs
tools/binman/bsection.py | 9 ++++ tools/binman/entry.py | 36 ++++++++++++++++ tools/binman/etype/cbfs.py | 7 +++- tools/binman/etype/section.py | 4 ++ tools/binman/ftest.py | 76 ++++++++++++++++++++++++++++++++++ tools/binman/image.py | 10 +++++ tools/binman/test/127_list.dts | 33 +++++++++++++++ 7 files changed, 174 insertions(+), 1 deletion(-) create mode 100644 tools/binman/test/127_list.dts
Applied to u-boot-dm, thanks!
PATCH v2 22/31 binman: Support locating an FDT map
In reply to Simon GlassAdd support for locating an image's Fdt map which is used to determine the contents and structure of the image.
---
Changes in v2:
- Adjust LocateFdtmap() to return the position of the header
- Update commit subject to more accurately describe this patch
- Update test to use _DoReadFileRealDtb() helper
tools/binman/etype/fdtmap.py | 25 ++++++++++++++++-- tools/binman/ftest.py | 15 +++++++++++ tools/binman/test/128_decode_image.dts | 36 ++++++++++++++++++++++++++ 3 files changed, 74 insertions(+), 2 deletions(-) create mode 100644 tools/binman/test/128_decode_image.dts
tools/binman/etype/fdtmap.py +23 -2
@@ -15,7 +15,26 @@ from fdt import Fdt import state import tools -FDTMAP_MAGIC = b'_FDTMAP_' +FDTMAP_MAGIC = b'_FDTMAP_' +FDTMAP_HDR_LEN = 16 + +def LocateFdtmap(data): + """Search an image for an fdt map + + Args: + data: Data to search + + Returns: + Position of fdt map in data, or None if not found. Note that the + position returned is of the FDT header, i.e. before the FDT data + """ + hdr_pos = data.find(FDTMAP_MAGIC) + size = len(data) + if hdr_pos: + hdr = data[hdr_pos:hdr_pos + FDTMAP_HDR_LEN] + if len(hdr) == FDTMAP_HDR_LEN: + return hdr_pos + return None class Entry_fdtmap(Entry): """An entry which contains an FDT map
@@ -24,7 +43,9 @@ class Entry_fdtmap(Entry): None An FDT map is just a header followed by an FDT containing a list of all the - entries in the image. + entries in the image. The root node corresponds to the image node in the + original FDT, and an image-name property indicates the image name in that + original tree. The header is the string _FDTMAP_ followed by 8 unused bytes.
tools/binman/ftest.py +15 -0
@@ -24,6 +24,7 @@ import command import control import elf import fdt +from etype import fdtmap import fdt_util import fmap_util import test_util
@@ -2267,6 +2268,20 @@ class TestFunctional(unittest.TestCase): self.assertEqual(len(data), 0x100 + section_size) self.assertEqual(section_size, 0x400 + dtb_size) + def testFindFdtmap(self): + """Test locating an FDT map in an image""" + self._CheckLz4() + data = self.data = self._DoReadFileRealDtb('128_decode_image.dts') + image = control.images['image'] + entries = image.GetEntries() + entry = entries['fdtmap'] + self.assertEqual(entry.image_pos, fdtmap.LocateFdtmap(data)) + + def testFindFdtmapMissing(self): + """Test failing to locate an FDP map""" + data = self._DoReadFile('005_simple.dts') + self.assertEqual(None, fdtmap.LocateFdtmap(data)) + if __name__ == "__main__": unittest.main()
tools/binman/test/128_decode_image.dts new file +36 -0
@@ -0,0 +1,36 @@ +// SPDX-License-Identifier: GPL-2.0+ + +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + binman { + size = <0xc00>; + u-boot { + }; + section { + align = <0x100>; + cbfs { + size = <0x400>; + u-boot { + cbfs-type = "raw"; + }; + u-boot-dtb { + cbfs-type = "raw"; + cbfs-compress = "lzma"; + cbfs-offset = <0x80>; + }; + }; + u-boot-dtb { + compress = "lz4"; + }; + }; + fdtmap { + }; + image-header { + location = "end"; + }; + }; +};
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 22/31 binman: Support locating an FDT map
Add support for locating an image's Fdt map which is used to determine the contents and structure of the image.
---
Changes in v2:
- Adjust LocateFdtmap() to return the position of the header
- Update commit subject to more accurately describe this patch
- Update test to use _DoReadFileRealDtb() helper
tools/binman/etype/fdtmap.py | 25 ++++++++++++++++-- tools/binman/ftest.py | 15 +++++++++++ tools/binman/test/128_decode_image.dts | 36 ++++++++++++++++++++++++++ 3 files changed, 74 insertions(+), 2 deletions(-) create mode 100644 tools/binman/test/128_decode_image.dts
Applied to u-boot-dm, thanks!
PATCH v2 23/31 binman: Support locating an image header
In reply to Simon GlassAdd support for locating an image header in an image.
---
Changes in v2: None
tools/binman/etype/image_header.py | 23 +++++++++++++++++++++++ tools/binman/ftest.py | 27 +++++++++++++++++++++++++++ 2 files changed, 50 insertions(+)
tools/binman/etype/image_header.py +23 -0
@@ -15,6 +15,29 @@ from entry import Entry import fdt_util IMAGE_HEADER_MAGIC = b'BinM' +IMAGE_HEADER_LEN = 8 + +def LocateHeaderOffset(data): + """Search an image for an image header + + Args: + data: Data to search + + Returns: + Offset of image header in the image, or None if not found + """ + hdr_pos = data.find(IMAGE_HEADER_MAGIC) + if hdr_pos != -1: + size = len(data) + hdr = data[hdr_pos:hdr_pos + IMAGE_HEADER_LEN] + if len(hdr) == IMAGE_HEADER_LEN: + offset = struct.unpack('<I', hdr[4:])[0] + if hdr_pos == len(data) - IMAGE_HEADER_LEN: + pos = size + offset - (1 << 32) + else: + pos = offset + return pos + return None class Entry_image_header(Entry): """An entry which contains a pointer to the FDT map
tools/binman/ftest.py +27 -0
@@ -25,6 +25,7 @@ import control import elf import fdt from etype import fdtmap +from etype import image_header import fdt_util import fmap_util import test_util
@@ -2282,6 +2283,32 @@ class TestFunctional(unittest.TestCase): data = self._DoReadFile('005_simple.dts') self.assertEqual(None, fdtmap.LocateFdtmap(data)) + def testFindImageHeader(self): + """Test locating a image header""" + self._CheckLz4() + data = self._DoReadFileDtb('128_decode_image.dts', use_real_dtb=True, + update_dtb=True)[0] + image = control.images['image'] + entries = image.GetEntries() + entry = entries['fdtmap'] + # The header should point to the FDT map + self.assertEqual(entry.image_pos, image_header.LocateHeaderOffset(data)) + + def testFindImageHeaderStart(self): + """Test locating a image header located@the start of an image""" + data = self._DoReadFileDtb('117_fdtmap_hdr_start.dts', + use_real_dtb=True, update_dtb=True)[0] + image = control.images['image'] + entries = image.GetEntries() + entry = entries['fdtmap'] + # The header should point to the FDT map + self.assertEqual(entry.image_pos, image_header.LocateHeaderOffset(data)) + + def testFindImageHeaderMissing(self): + """Test failing to locate an image header""" + data = self._DoReadFile('005_simple.dts') + self.assertEqual(None, image_header.LocateHeaderOffset(data)) + if __name__ == "__main__": unittest.main()
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 23/31 binman: Support locating an image header
Add support for locating an image header in an image.
---
Changes in v2: None
tools/binman/etype/image_header.py | 23 +++++++++++++++++++++++ tools/binman/ftest.py | 27 +++++++++++++++++++++++++++ 2 files changed, 50 insertions(+)
Applied to u-boot-dm, thanks!
PATCH v2 24/31 binman: Support reading an image into an Image object
In reply to Simon GlassIt is possible to read an Image, locate its FDT map and then read it into the binman data structures. This allows full access to the entries that were written to the image. Add support for this.
---
Changes in v2:
- Deal with travis's old lz4 version by skipping tests as necessary
- Move 129_list_fdtmap.dts into the next commit
- Rename 128_decode_image_no_hdr.dts to 129_decode_image_nohdr.dts
- Update Image for LocateFdtmap() returning the position of the header
- Update test to use _DoReadFileRealDtb() helper
tools/binman/entry.py | 5 +++ tools/binman/ftest.py | 39 ++++++++++++++++++-- tools/binman/image.py | 38 +++++++++++++++++++ tools/binman/test/129_decode_image_nohdr.dts | 33 +++++++++++++++++ 4 files changed, 111 insertions(+), 4 deletions(-) create mode 100644 tools/binman/test/129_decode_image_nohdr.dts
tools/binman/entry.py +5 -0
@@ -162,6 +162,11 @@ class Entry(object): self.orig_offset = self.offset self.orig_size = self.size + # These should not be set in input files, but are set in an FDT map, + # which is also read by this code. + self.image_pos = fdt_util.GetInt(self._node, 'image-pos') + self.uncomp_size = fdt_util.GetInt(self._node, 'uncomp-size') + self.align = fdt_util.GetInt(self._node, 'align') if tools.NotPowerOfTwo(self.align): raise ValueError("Node '%s': Alignment %s must be a power of two" %
tools/binman/ftest.py +35 -4
@@ -30,6 +30,7 @@ import fdt_util import fmap_util import test_util import gzip +from image import Image import state import tools import tout
@@ -2286,8 +2287,7 @@ class TestFunctional(unittest.TestCase): def testFindImageHeader(self): """Test locating a image header""" self._CheckLz4() - data = self._DoReadFileDtb('128_decode_image.dts', use_real_dtb=True, - update_dtb=True)[0] + data = self.data = self._DoReadFileRealDtb('128_decode_image.dts') image = control.images['image'] entries = image.GetEntries() entry = entries['fdtmap']
@@ -2296,8 +2296,7 @@ class TestFunctional(unittest.TestCase): def testFindImageHeaderStart(self): """Test locating a image header located at the start of an image""" - data = self._DoReadFileDtb('117_fdtmap_hdr_start.dts', - use_real_dtb=True, update_dtb=True)[0] + data = self.data = self._DoReadFileRealDtb('117_fdtmap_hdr_start.dts') image = control.images['image'] entries = image.GetEntries() entry = entries['fdtmap']
@@ -2309,6 +2308,38 @@ class TestFunctional(unittest.TestCase): data = self._DoReadFile('005_simple.dts') self.assertEqual(None, image_header.LocateHeaderOffset(data)) + def testReadImage(self): + """Test reading an image and accessing its FDT map""" + self._CheckLz4() + data = self.data = self._DoReadFileRealDtb('128_decode_image.dts') + image_fname = tools.GetOutputFilename('image.bin') + orig_image = control.images['image'] + image = Image.FromFile(image_fname) + self.assertEqual(orig_image.GetEntries().keys(), + image.GetEntries().keys()) + + orig_entry = orig_image.GetEntries()['fdtmap'] + entry = image.GetEntries()['fdtmap'] + self.assertEquals(orig_entry.offset, entry.offset) + self.assertEquals(orig_entry.size, entry.size) + self.assertEquals(orig_entry.image_pos, entry.image_pos) + + def testReadImageNoHeader(self): + """Test accessing an image's FDT map without an image header""" + self._CheckLz4() + data = self._DoReadFileRealDtb('129_decode_image_nohdr.dts') + image_fname = tools.GetOutputFilename('image.bin') + image = Image.FromFile(image_fname) + self.assertTrue(isinstance(image, Image)) + self.assertEqual('image', image._name) + + def testReadImageFail(self): + """Test failing to read an image image's FDT map""" + self._DoReadFile('005_simple.dts') + image_fname = tools.GetOutputFilename('image.bin') + with self.assertRaises(ValueError) as e: + image = Image.FromFile(image_fname) + self.assertIn("Cannot find FDT map in image", str(e.exception)) if __name__ == "__main__": unittest.main()
tools/binman/image.py +38 -0
@@ -12,6 +12,9 @@ from operator import attrgetter import re import sys +from etype import fdtmap +from etype import image_header +import fdt import fdt_util import bsection import tools
@@ -47,6 +50,41 @@ class Image: else: self._ReadNode() + @classmethod + def FromFile(cls, fname): + """Convert an image file into an Image for use in binman + + Args: + fname: Filename of image file to read + + Returns: + Image object on success + + Raises: + ValueError if something goes wrong + """ + data = tools.ReadFile(fname) + size = len(data) + + # First look for an image header + pos = image_header.LocateHeaderOffset(data) + if pos is None: + # Look for the FDT map + pos = fdtmap.LocateFdtmap(data) + if pos is None: + raise ValueError('Cannot find FDT map in image') + + # We don't know the FDT size, so check its header first + probe_dtb = fdt.Fdt.FromData( + data[pos + fdtmap.FDTMAP_HDR_LEN:pos + 256]) + dtb_size = probe_dtb.GetFdtObj().totalsize() + fdtmap_data = data[pos:pos + dtb_size + fdtmap.FDTMAP_HDR_LEN] + dtb = fdt.Fdt.FromData(fdtmap_data[fdtmap.FDTMAP_HDR_LEN:]) + dtb.Scan() + + # Return an Image with the associated nodes + return Image('image', dtb.GetRoot()) + def _ReadNode(self): """Read properties from the image node""" self._size = fdt_util.GetInt(self._node, 'size')
tools/binman/test/129_decode_image_nohdr.dts new file +33 -0
@@ -0,0 +1,33 @@ +// SPDX-License-Identifier: GPL-2.0+ + +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + binman { + size = <0xc00>; + u-boot { + }; + section { + align = <0x100>; + cbfs { + size = <0x400>; + u-boot { + cbfs-type = "raw"; + }; + u-boot-dtb { + cbfs-type = "raw"; + cbfs-compress = "lzma"; + cbfs-offset = <0x80>; + }; + }; + u-boot-dtb { + compress = "lz4"; + }; + }; + fdtmap { + }; + }; +};
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 24/31 binman: Support reading an image into an Image object
It is possible to read an Image, locate its FDT map and then read it into the binman data structures. This allows full access to the entries that were written to the image. Add support for this.
---
Changes in v2:
- Deal with travis's old lz4 version by skipping tests as necessary
- Move 129_list_fdtmap.dts into the next commit
- Rename 128_decode_image_no_hdr.dts to 129_decode_image_nohdr.dts
- Update Image for LocateFdtmap() returning the position of the header
- Update test to use _DoReadFileRealDtb() helper
tools/binman/entry.py | 5 +++ tools/binman/ftest.py | 39 ++++++++++++++++++-- tools/binman/image.py | 38 +++++++++++++++++++ tools/binman/test/129_decode_image_nohdr.dts | 33 +++++++++++++++++ 4 files changed, 111 insertions(+), 4 deletions(-) create mode 100644 tools/binman/test/129_decode_image_nohdr.dts
Applied to u-boot-dm, thanks!
PATCH v2 25/31 binman: Convert Image to a subclass of Entry
In reply to Simon GlassWhen support for sections (and thus hierarchical images) was added to binman, the decision was made to create a new Section class which could be used by both Image and an Entry_section class. The decision between using inheritance and composition was tricky to make, but in the end it was decided that Image was different enough from Entry that it made sense to put the implementation of sections in an entirely separate class. It also has the advantage that core Image code does have to rely on an entry class in the etype directory.
This work was mostly completed in commit:
8f1da50ccc "binman: Refactor much of the image code into 'section'
As a result of this, the Section class has its own version of things like offset and size and these must be kept in sync with the parent Entry_section class in some cases.
In the last year it has become apparent that the cost of keeping things in sync is larger than expected, since more and more code wants to access these properties.
An alternative approach, previously considered and rejected, now seems better.
Adjust Image to be a subclass of Entry_section. Move the code from Section (in bsection.py) to Entry_section and delete Section. Update all tests accordingly.
This requires substantial changes to Image. Overall the changes reduce code size by about 240 lines. While much of that is just boilerplate from Section, there are quite a few functions in Entry_section which now do not need to be overiden from Entry. This suggests the change is beneficial even without further functionality being added.
A side benefit is that the properties of sections are now consistent with other entries. This fixes a problem in testListCmd() where some properties are missing for sections.
Unfortunately this is a very large commit since it is not feasible to do the migration piecemeal. Given the substantial tests available and the 100% code coverage of binman, we should be able to do this safely.
---
Changes in v2: None
tools/binman/README.entries | 21 +- tools/binman/bsection.py | 523 ---------------------------------- tools/binman/entry.py | 8 +- tools/binman/etype/files.py | 3 +- tools/binman/etype/fmap.py | 2 +- tools/binman/etype/section.py | 431 +++++++++++++++++++++++++--- tools/binman/ftest.py | 29 +- tools/binman/image.py | 129 +++------ tools/binman/image_test.py | 18 +- 9 files changed, 462 insertions(+), 702 deletions(-) delete mode 100644 tools/binman/bsection.py
tools/binman/README.entries +13 -8
@@ -521,16 +521,21 @@ Entry: section: Entry that contains other entries ------------------------------------------------- Properties / Entry arguments: (see binman README for more information) - - size: Size of section in bytes - - align-size: Align size to a particular power of two - - pad-before: Add padding before the entry - - pad-after: Add padding after the entry - - pad-byte: Pad byte to use when padding - - sort-by-offset: Reorder the entries by offset - - end-at-4gb: Used to build an x86 ROM which ends at 4GB (2^32) - - name-prefix: Adds a prefix to the name of every entry in the section + pad-byte: Pad byte to use when padding + sort-by-offset: True if entries should be sorted by offset, False if + they must be in-order in the device tree description + end-at-4gb: Used to build an x86 ROM which ends at 4GB (2^32) + skip-at-start: Number of bytes before the first entry starts. These + effectively adjust the starting offset of entries. For example, + if this is 16, then the first entry would start at 16. An entry + with offset = 20 would in fact be written at offset 4 in the image + file, since the first 16 bytes are skipped when writing. + name-prefix: Adds a prefix to the name of every entry in the section when writing out the map +Since a section is also an entry, it inherits all the properies of entries +too. + A section is an entry which can contain other entries, thus allowing hierarchical images to be created. See 'Sections and hierarchical images' in the binman README for more information.
tools/binman/bsection.py deleted +0 -523
523 lines not on this page · raw message
tools/binman/entry.py +4 -4
@@ -175,8 +175,8 @@ class Entry(object): self.pad_after = fdt_util.GetInt(self._node, 'pad-after', 0) self.align_size = fdt_util.GetInt(self._node, 'align-size') if tools.NotPowerOfTwo(self.align_size): - raise ValueError("Node '%s': Alignment size %s must be a power " - "of two" % (self._node.path, self.align_size)) + self.Raise("Alignment size %s must be a power of two" % + self.align_size) self.align_end = fdt_util.GetInt(self._node, 'align-end') self.offset_unset = fdt_util.GetBool(self._node, 'offset-unset') self.expand_size = fdt_util.GetBool(self._node, 'expand-size')
@@ -216,8 +216,8 @@ class Entry(object): """Set the value of device-tree properties calculated by binman""" state.SetInt(self._node, 'offset', self.offset) state.SetInt(self._node, 'size', self.size) - state.SetInt(self._node, 'image-pos', - self.image_pos - self.section.GetRootSkipAtStart()) + base = self.section.GetRootSkipAtStart() if self.section else 0 + state.SetInt(self._node, 'image-pos', self.image_pos - base) if self.uncomp_size is not None: state.SetInt(self._node, 'uncomp-size', self.uncomp_size) state.CheckSetHashValue(self._node, self.GetData)
tools/binman/etype/files.py +1 -2
@@ -14,7 +14,6 @@ import fdt_util import state import tools -import bsection class Entry_files(Entry_section): """Entry containing a set of files
@@ -54,4 +53,4 @@ class Entry_files(Entry_section): state.AddString(subnode, 'compress', self._compress) # Read entries again, now that we have some - self._section._ReadEntries() + self._ReadEntries()
tools/binman/etype/fmap.py +1 -1
@@ -49,7 +49,7 @@ class Entry_fmap(Entry): areas.append(fmap_util.FmapArea(pos or 0, entry.size or 0, tools.FromUnicode(entry.name), 0)) - entries = self.section._image.GetEntries() + entries = self.section.image.GetEntries() areas = [] for entry in entries.values(): _AddEntries(areas, entry)
tools/binman/etype/section.py +388 -43
503 lines not on this page · raw message
tools/binman/ftest.py +15 -14
@@ -595,7 +595,7 @@ class TestFunctional(unittest.TestCase): self.assertEqual(0, retcode) image = control.images['image1'] - self.assertEqual(len(U_BOOT_DATA), image._size) + self.assertEqual(len(U_BOOT_DATA), image.size) fname = tools.GetOutputFilename('image1.bin') self.assertTrue(os.path.exists(fname)) with open(fname, 'rb') as fd:
@@ -603,7 +603,7 @@ class TestFunctional(unittest.TestCase): self.assertEqual(U_BOOT_DATA, data) image = control.images['image2'] - self.assertEqual(3 + len(U_BOOT_DATA) + 5, image._size) + self.assertEqual(3 + len(U_BOOT_DATA) + 5, image.size) fname = tools.GetOutputFilename('image2.bin') self.assertTrue(os.path.exists(fname)) with open(fname, 'rb') as fd:
@@ -659,7 +659,7 @@ class TestFunctional(unittest.TestCase): self.assertEqual(61, entry.offset) self.assertEqual(len(U_BOOT_DATA), entry.size) - self.assertEqual(65, image._size) + self.assertEqual(65, image.size) def testPackExtra(self): """Test that extra packing feature works as expected"""
@@ -703,7 +703,7 @@ class TestFunctional(unittest.TestCase): self.assertEqual(64, entry.size) self.CheckNoGaps(entries) - self.assertEqual(128, image._size) + self.assertEqual(128, image.size) def testPackAlignPowerOf2(self): """Test that invalid entry alignment is detected"""
@@ -761,7 +761,7 @@ class TestFunctional(unittest.TestCase): self.assertEqual(0, retcode) self.assertIn('image', control.images) image = control.images['image'] - self.assertEqual(7, image._size) + self.assertEqual(7, image.size) def testPackImageSizeAlign(self): """Test that image size alignemnt works as expected"""
@@ -769,7 +769,7 @@ class TestFunctional(unittest.TestCase): self.assertEqual(0, retcode) self.assertIn('image', control.images) image = control.images['image'] - self.assertEqual(16, image._size) + self.assertEqual(16, image.size) def testPackInvalidImageAlign(self): """Test that invalid image alignment is detected"""
@@ -782,7 +782,7 @@ class TestFunctional(unittest.TestCase): """Test that invalid image alignment is detected""" with self.assertRaises(ValueError) as e: self._DoTestFile('020_pack_inv_image_align_power2.dts') - self.assertIn("Section '/binman': Alignment size 131 must be a power of " + self.assertIn("Image '/binman': Alignment size 131 must be a power of " "two", str(e.exception)) def testImagePadByte(self):
@@ -833,7 +833,7 @@ class TestFunctional(unittest.TestCase): """Test that the end-at-4gb property requires a size property""" with self.assertRaises(ValueError) as e: self._DoTestFile('027_pack_4gb_no_size.dts') - self.assertIn("Section '/binman': Section size must be provided when " + self.assertIn("Image '/binman': Section size must be provided when " "using end-at-4gb", str(e.exception)) def test4gbAndSkipAtStartTogether(self):
@@ -841,7 +841,7 @@ class TestFunctional(unittest.TestCase): together""" with self.assertRaises(ValueError) as e: self._DoTestFile('80_4gb_and_skip_at_start_together.dts') - self.assertIn("Section '/binman': Provide either 'end-at-4gb' or " + self.assertIn("Image '/binman': Provide either 'end-at-4gb' or " "'skip-at-start'", str(e.exception)) def testPackX86RomOutside(self):
@@ -1217,7 +1217,7 @@ class TestFunctional(unittest.TestCase): """Test that obtaining the contents works as expected""" with self.assertRaises(ValueError) as e: self._DoReadFile('057_unknown_contents.dts', True) - self.assertIn("Section '/binman': Internal error: Could not complete " + self.assertIn("Image '/binman': Internal error: Could not complete " "processing of contents: remaining [<_testing.Entry__testing ", str(e.exception))
@@ -1657,7 +1657,7 @@ class TestFunctional(unittest.TestCase): image = control.images['image'] entries = image.GetEntries() files = entries['files'] - entries = files._section._entries + entries = files._entries orig = b'' for i in range(1, 3):
@@ -2209,7 +2209,7 @@ class TestFunctional(unittest.TestCase): self.assertEqual(len(data), ent.size) self.assertEqual(0, ent.image_pos) self.assertEqual(None, ent.uncomp_size) - self.assertEqual(None, ent.offset) + self.assertEqual(0, ent.offset) ent = entries[1] self.assertEqual(1, ent.indent)
@@ -2227,7 +2227,7 @@ class TestFunctional(unittest.TestCase): section_size = ent.size self.assertEqual(0x100, ent.image_pos) self.assertEqual(None, ent.uncomp_size) - self.assertEqual(len(U_BOOT_DATA), ent.offset) + self.assertEqual(0x100, ent.offset) ent = entries[3] self.assertEqual(2, ent.indent)
@@ -2331,7 +2331,7 @@ class TestFunctional(unittest.TestCase): image_fname = tools.GetOutputFilename('image.bin') image = Image.FromFile(image_fname) self.assertTrue(isinstance(image, Image)) - self.assertEqual('image', image._name) + self.assertEqual('image', image.image_name) def testReadImageFail(self): """Test failing to read an image image's FDT map"""
@@ -2341,5 +2341,6 @@ class TestFunctional(unittest.TestCase): image = Image.FromFile(image_fname) self.assertIn("Cannot find FDT map in image", str(e.exception)) + if __name__ == "__main__": unittest.main()
tools/binman/image.py +33 -96
195 lines not on this page · raw message
tools/binman/image_test.py +7 -11
@@ -12,28 +12,25 @@ from test_util import capture_sys_output class TestImage(unittest.TestCase): def testInvalidFormat(self): image = Image('name', 'node', test=True) - section = image._section with self.assertRaises(ValueError) as e: - section.LookupSymbol('_binman_something_prop_', False, 'msg') + image.LookupSymbol('_binman_something_prop_', False, 'msg') self.assertIn( "msg: Symbol '_binman_something_prop_' has invalid format", str(e.exception)) def testMissingSymbol(self): image = Image('name', 'node', test=True) - section = image._section - section._entries = {} + image._entries = {} with self.assertRaises(ValueError) as e: - section.LookupSymbol('_binman_type_prop_pname', False, 'msg') + image.LookupSymbol('_binman_type_prop_pname', False, 'msg') self.assertIn("msg: Entry 'type' not found in list ()", str(e.exception)) def testMissingSymbolOptional(self): image = Image('name', 'node', test=True) - section = image._section - section._entries = {} + image._entries = {} with capture_sys_output() as (stdout, stderr): - val = section.LookupSymbol('_binman_type_prop_pname', True, 'msg') + val = image.LookupSymbol('_binman_type_prop_pname', True, 'msg') self.assertEqual(val, None) self.assertEqual("Warning: msg: Entry 'type' not found in list ()\n", stderr.getvalue())
@@ -41,8 +38,7 @@ class TestImage(unittest.TestCase): def testBadProperty(self): image = Image('name', 'node', test=True) - section = image._section - section._entries = {'u-boot': 1} + image._entries = {'u-boot': 1} with self.assertRaises(ValueError) as e: - section.LookupSymbol('_binman_u_boot_prop_bad', False, 'msg') + image.LookupSymbol('_binman_u_boot_prop_bad', False, 'msg') self.assertIn("msg: No such property 'bad", str(e.exception))
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 25/31 binman: Convert Image to a subclass of Entry
When support for sections (and thus hierarchical images) was added to binman, the decision was made to create a new Section class which could be used by both Image and an Entry_section class. The decision between using inheritance and composition was tricky to make, but in the end it was decided that Image was different enough from Entry that it made sense to put the implementation of sections in an entirely separate class. It also has the advantage that core Image code does have to rely on an entry class in the etype directory.
This work was mostly completed in commit:
8f1da50ccc "binman: Refactor much of the image code into 'section'
As a result of this, the Section class has its own version of things like offset and size and these must be kept in sync with the parent Entry_section class in some cases.
In the last year it has become apparent that the cost of keeping things in sync is larger than expected, since more and more code wants to access these properties.
An alternative approach, previously considered and rejected, now seems better.
Adjust Image to be a subclass of Entry_section. Move the code from Section (in bsection.py) to Entry_section and delete Section. Update all tests accordingly.
This requires substantial changes to Image. Overall the changes reduce code size by about 240 lines. While much of that is just boilerplate from Section, there are quite a few functions in Entry_section which now do not need to be overiden from Entry. This suggests the change is beneficial even without further functionality being added.
A side benefit is that the properties of sections are now consistent with other entries. This fixes a problem in testListCmd() where some properties are missing for sections.
Unfortunately this is a very large commit since it is not feasible to do the migration piecemeal. Given the substantial tests available and the 100% code coverage of binman, we should be able to do this safely.
---
Changes in v2: None
tools/binman/README.entries | 21 +- tools/binman/bsection.py | 523 ---------------------------------- tools/binman/entry.py | 8 +- tools/binman/etype/files.py | 3 +- tools/binman/etype/fmap.py | 2 +- tools/binman/etype/section.py | 431 +++++++++++++++++++++++++--- tools/binman/ftest.py | 29 +- tools/binman/image.py | 129 +++------ tools/binman/image_test.py | 18 +- 9 files changed, 462 insertions(+), 702 deletions(-) delete mode 100644 tools/binman/bsection.py
Applied to u-boot-dm, thanks!
PATCH v2 26/31 binman: Support listing an image
In reply to Simon GlassAdd support for listing the entries in an image. This relies on the image having an FDT map.
---
Changes in v2:
- Adjust the test to not rely on lz4 compression version
- Allow listing subsets of the image
- Change list command from 'list' to 'ls'
- Deal with travis's old lz4 version by skipping tests as necessary
- Move patch 'Add a comment about CBFS test structure' to earlier series
- Move patch 'Allow cbfstool to be optional with tests' to earlier series
- Update output from 'list' command
- Update test to use _DoReadFileRealDtb() helper
tools/binman/README | 44 +++++++- tools/binman/cmdline.py | 6 ++ tools/binman/control.py | 35 ++++++ tools/binman/ftest.py | 82 ++++++++++++++ tools/binman/image.py | 150 ++++++++++++++++++++++++++ tools/binman/test/130_list_fdtmap.dts | 36 +++++++ 6 files changed, 352 insertions(+), 1 deletion(-) create mode 100644 tools/binman/test/130_list_fdtmap.dts
tools/binman/README +43 -1
@@ -490,6 +490,49 @@ see README.entries. This is generated from the source code using: binman entry-docs >tools/binman/README.entries +Listing images +-------------- + +It is possible to list the entries in an existing firmware image created by +binman, provided that there is an 'fdtmap' entry in the image. For example: + + $ binman ls -i image.bin + Name Image-pos Size Entry-type Offset Uncomp-size + ---------------------------------------------------------------------- + main-section c00 section 0 + u-boot 0 4 u-boot 0 + section 5fc section 4 + cbfs 100 400 cbfs 0 + u-boot 138 4 u-boot 38 + u-boot-dtb 180 108 u-boot-dtb 80 3b5 + u-boot-dtb 500 1ff u-boot-dtb 400 3b5 + fdtmap 6fc 381 fdtmap 6fc + image-header bf8 8 image-header bf8 + +This shows the hierarchy of the image, the position, size and type of each +entry, the offset of each entry within its parent and the uncompressed size if +the entry is compressed. + +It is also possible to list just some files in an image, e.g. + + $ binman ls -i image.bin section/cbfs + Name Image-pos Size Entry-type Offset Uncomp-size + -------------------------------------------------------------------- + cbfs 100 400 cbfs 0 + u-boot 138 4 u-boot 38 + u-boot-dtb 180 108 u-boot-dtb 80 3b5 + +or with wildcards: + + $ binman ls -i image.bin "*cb*" "*head*" + Name Image-pos Size Entry-type Offset Uncomp-size + ---------------------------------------------------------------------- + cbfs 100 400 cbfs 0 + u-boot 138 4 u-boot 38 + u-boot-dtb 180 108 u-boot-dtb 80 3b5 + image-header bf8 8 image-header bf8 + + Hashing Entries ---------------
@@ -825,7 +868,6 @@ Some ideas: - Add an option to decode an image into the constituent binaries - Support building an image for a board (-b) more completely, with a configurable build directory -- Support listing files in images - Support logging of binman's operations, with different levels of verbosity - Support updating binaries in an image (with no size change / repacking) - Support updating binaries in an image (with repacking)
tools/binman/cmdline.py +6 -0
@@ -65,6 +65,12 @@ controlled by a description in the board device tree.''' entry_parser = subparsers.add_parser('entry-docs', help='Write out entry documentation (see README.entries)') + list_parser = subparsers.add_parser('ls', help='List files in an image') + list_parser.add_argument('-i', '--image', type=str, required=True, + help='Image filename to list') + list_parser.add_argument('paths', type=str, nargs='*', + help='Paths within file to list (wildcard)') + test_parser = subparsers.add_parser('test', help='Run tests') test_parser.add_argument('-P', '--processes', type=int, help='set number of processes to use for running tests')
tools/binman/control.py +35 -0
@@ -67,6 +67,37 @@ def WriteEntryDocs(modules, test_missing=None): from entry import Entry Entry.WriteDocs(modules, test_missing) + +def ListEntries(image_fname, entry_paths): + """List the entries in an image + + This decodes the supplied image and displays a table of entries from that + image, preceded by a header. + + Args: + image_fname: Image filename to process + entry_paths: List of wildcarded paths (e.g. ['*dtb*', 'u-boot*', + 'section/u-boot']) + """ + image = Image.FromFile(image_fname) + + entries, lines, widths = image.GetListEntries(entry_paths) + + num_columns = len(widths) + for linenum, line in enumerate(lines): + if linenum == 1: + # Print header line + print('-' * (sum(widths) + num_columns * 2)) + out = '' + for i, item in enumerate(line): + width = -widths[i] + if item.startswith('>'): + width = -width + item = item[1:] + txt = '%*s ' % (width, item) + out += txt + print(out.rstrip()) + def Binman(args): """The main control code for binman
@@ -87,6 +118,10 @@ def Binman(args): command.Run(pager, fname) return 0 + if args.cmd == 'ls': + ListEntries(args.image, args.paths) + return 0 + # Try to figure out which device tree contains our image description if args.dt: dtb_fname = args.dt
tools/binman/ftest.py +82 -0
88 lines not on this page · raw message
tools/binman/image.py +150 -0
159 lines not on this page · raw message
tools/binman/test/130_list_fdtmap.dts new file +36 -0
@@ -0,0 +1,36 @@ +// SPDX-License-Identifier: GPL-2.0+ + +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + binman { + size = <0xc00>; + u-boot { + }; + section { + align = <0x100>; + cbfs { + size = <0x400>; + u-boot { + cbfs-type = "raw"; + }; + u-boot-dtb { + cbfs-type = "raw"; + cbfs-compress = "lzma"; + cbfs-offset = <0x80>; + }; + }; + u-boot-dtb { + compress = "lz4"; + }; + }; + fdtmap { + }; + image-header { + location = "end"; + }; + }; +};
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 26/31 binman: Support listing an image
Add support for listing the entries in an image. This relies on the image having an FDT map.
---
Changes in v2:
- Adjust the test to not rely on lz4 compression version
- Allow listing subsets of the image
- Change list command from 'list' to 'ls'
- Deal with travis's old lz4 version by skipping tests as necessary
- Move patch 'Add a comment about CBFS test structure' to earlier series
- Move patch 'Allow cbfstool to be optional with tests' to earlier series
- Update output from 'list' command
- Update test to use _DoReadFileRealDtb() helper
tools/binman/README | 44 +++++++- tools/binman/cmdline.py | 6 ++ tools/binman/control.py | 35 ++++++ tools/binman/ftest.py | 82 ++++++++++++++ tools/binman/image.py | 150 ++++++++++++++++++++++++++ tools/binman/test/130_list_fdtmap.dts | 36 +++++++ 6 files changed, 352 insertions(+), 1 deletion(-) create mode 100644 tools/binman/test/130_list_fdtmap.dts
Applied to u-boot-dm, thanks!
PATCH v2 27/31 binman: Allow for logging information to be displayed
In reply to Simon GlassBinman generally operates silently but in some cases it is useful to see what Binman is actually doing at each step. Enable some logging output with different logging levels selectable via the -v flag.
---
Changes in v2: None
tools/binman/README | 19 ++++++++++++++++++- tools/binman/entry.py | 3 ++- tools/binman/image.py | 3 ++- tools/patman/tout.py | 10 +++++++++- 4 files changed, 31 insertions(+), 4 deletions(-)
tools/binman/README +18 -1
@@ -533,6 +533,24 @@ or with wildcards: image-header bf8 8 image-header bf8 +Logging +------- + +Binman normally operates silently unless there is an error, in which case it +just displays the error. The -D/--debug option can be used to create a full +backtrace when errors occur. + +Internally binman logs some output while it is running. This can be displayed +by increasing the -v/--verbosity from the default of 1: + + 0: silent + 1: warnings only + 2: notices (important messages) + 3: info about major operations + 4: detailed information about each operation + 5: debug (all output) + + Hashing Entries ---------------
@@ -868,7 +886,6 @@ Some ideas: - Add an option to decode an image into the constituent binaries - Support building an image for a board (-b) more completely, with a configurable build directory -- Support logging of binman's operations, with different levels of verbosity - Support updating binaries in an image (with no size change / repacking) - Support updating binaries in an image (with repacking) - Support adding FITs to an image
tools/binman/entry.py +2 -1
@@ -23,6 +23,7 @@ import sys import fdt_util import state import tools +import tout modules = {}
@@ -272,7 +273,7 @@ class Entry(object): new_size = len(data) if state.AllowEntryExpansion(): if new_size > self.contents_size: - print("Entry '%s' size change from %#x to %#x" % ( + tout.Debug("Entry '%s' size change from %#x to %#x" % ( self._node.path, self.contents_size, new_size)) # self.data will indicate the new size needed size_ok = False
tools/binman/image.py +2 -1
@@ -20,6 +20,7 @@ from etype import section import fdt import fdt_util import tools +import tout class Image(section.Entry_section): """A Image, representing an output from binman
@@ -107,7 +108,7 @@ class Image(section.Entry_section): for entry in self._entries.values(): if not entry.ProcessContents(): sizes_ok = False - print("Entry '%s' size change" % self._node.path) + tout.Debug("Entry '%s' size change" % self._node.path) return sizes_ok def WriteSymbols(self):
tools/patman/tout.py +9 -1
@@ -131,13 +131,21 @@ def Info(msg): """ _Output(3, msg) +def Detail(msg): + """Display a detailed message + + Args: + msg; Message to display. + """ + _Output(4, msg) + def Debug(msg): """Display a debug message Args: msg; Message to display. """ - _Output(4, msg) + _Output(5, msg) def UserOutput(msg): """Display a message regardless of the current output level.
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 27/31 binman: Allow for logging information to be displayed
Binman generally operates silently but in some cases it is useful to see what Binman is actually doing at each step. Enable some logging output with different logging levels selectable via the -v flag.
---
Changes in v2: None
tools/binman/README | 19 ++++++++++++++++++- tools/binman/entry.py | 3 ++- tools/binman/image.py | 3 ++- tools/patman/tout.py | 10 +++++++++- 4 files changed, 31 insertions(+), 4 deletions(-)
Applied to u-boot-dm, thanks!
PATCH v2 28/31 binman: Allow reading an entry from an image
In reply to Simon GlassIt is useful to be able to extract entry contents from an image to see what is inside. Add a simple function to read the contents of an entry, decompressing it by default.
---
Changes in v2: None
tools/binman/control.py | 20 ++++++++++++++++++ tools/binman/entry.py | 21 +++++++++++++++++++ tools/binman/etype/blob.py | 13 ++++++++++++ tools/binman/ftest.py | 42 ++++++++++++++++++++++++++++++++++++++ tools/binman/image.py | 4 +++- 5 files changed, 99 insertions(+), 1 deletion(-)
tools/binman/control.py +20 -0
@@ -98,6 +98,26 @@ def ListEntries(image_fname, entry_paths): out += txt print(out.rstrip()) + +def ReadEntry(image_fname, entry_path, decomp=True): + """Extract an entry from an image + + This extracts the data from a particular entry in an image + + Args: + image_fname: Image filename to process + entry_path: Path to entry to extract + decomp: True to return uncompressed data, if the data is compress + False to return the raw data + + Returns: + data extracted from the entry + """ + image = Image.FromFile(image_fname) + entry = image.FindEntryPath(entry_path) + return entry.ReadData(decomp) + + def Binman(args): """The main control code for binman
tools/binman/entry.py +21 -0
@@ -659,3 +659,24 @@ features to produce new behaviours. """ self.AddEntryInfo(entries, indent, self.name, self.etype, self.size, self.image_pos, self.uncomp_size, self.offset, self) + + def ReadData(self, decomp=True): + """Read the data for an entry from the image + + This is used when the image has been read in and we want to extract the + data for a particular entry from that image. + + Args: + decomp: True to decompress any compressed data before returning it; + False to return the raw, uncompressed data + + Returns: + Entry data (bytes) + """ + # Use True here so that we get an uncompressed section to work from, + # although compressed sections are currently not supported + data = self.section.ReadData(True) + tout.Info('%s: Reading data from offset %#x-%#x, size %#x (avail %#x)' % + (self.GetPath(), self.offset, self.offset + self.size, + self.size, len(data))) + return data[self.offset:self.offset + self.size]
tools/binman/etype/blob.py +13 -0
@@ -9,6 +9,7 @@ from entry import Entry import fdt_util import state import tools +import tout class Entry_blob(Entry): """Entry containing an arbitrary binary blob
@@ -66,3 +67,15 @@ class Entry_blob(Entry): def GetDefaultFilename(self): return self._filename + + def ReadData(self, decomp=True): + indata = Entry.ReadData(self, decomp) + if decomp: + data = tools.Decompress(indata, self.compress) + if self.uncomp_size: + tout.Info("%s: Decompressing data size %#x with algo '%s' to data size %#x" % + (self.GetPath(), len(indata), self.compress, + len(data))) + else: + data = indata + return data
tools/binman/ftest.py +42 -0
54 lines not on this page · raw message
tools/binman/image.py +3 -1
@@ -82,7 +82,9 @@ class Image(section.Entry_section): dtb.Scan() # Return an Image with the associated nodes - return Image('image', dtb.GetRoot()) + image = Image('image', dtb.GetRoot()) + image._data = data + return image def Raise(self, msg): """Convenience function to raise an error referencing an image"""
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 28/31 binman: Allow reading an entry from an image
It is useful to be able to extract entry contents from an image to see what is inside. Add a simple function to read the contents of an entry, decompressing it by default.
---
Changes in v2: None
tools/binman/control.py | 20 ++++++++++++++++++ tools/binman/entry.py | 21 +++++++++++++++++++ tools/binman/etype/blob.py | 13 ++++++++++++ tools/binman/ftest.py | 42 ++++++++++++++++++++++++++++++++++++++ tools/binman/image.py | 4 +++- 5 files changed, 99 insertions(+), 1 deletion(-)
Applied to u-boot-dm, thanks!
PATCH v2 29/31 binman: Support reading from CBFS entries
In reply to Simon GlassCBFS is a bit like a section but with a custom format. Provide the list of entries and the compression type to binman so that it can extract the data from the CBFS, just like any other part of the image.
---
Changes in v2: None
tools/binman/cbfs_util.py | 14 ++++++++++++++ tools/binman/etype/cbfs.py | 7 +++++++ 2 files changed, 21 insertions(+)
tools/binman/cbfs_util.py +14 -0
@@ -142,6 +142,20 @@ def find_compress(find_name): return compress return None +def compress_name(compress): + """Look up the name of a compression algorithm + + Args: + compress: Compression algorithm number to find (COMPRESS_...) + + Returns: + Compression algorithm name (string) + + Raises: + KeyError if the algorithm number is invalid + """ + return COMPRESS_NAMES[compress] + def align_int(val, align): """Align a value up to the given alignment
tools/binman/etype/cbfs.py +7 -0
@@ -238,6 +238,10 @@ class Entry_cbfs(Entry): entry.AddMissingProperties() if entry._cbfs_compress: state.AddZeroProp(entry._node, 'uncomp-size') + # Store the 'compress' property, since we don't look at + # 'cbfs-compress' in Entry.ReadData() + state.AddString(entry._node, 'compress', + cbfs_util.compress_name(entry._cbfs_compress)) def SetCalculatedProperties(self): """Set the value of device-tree properties calculated by binman"""
@@ -254,3 +258,6 @@ class Entry_cbfs(Entry): Entry.ListEntries(self, entries, indent) for entry in self._cbfs_entries.values(): entry.ListEntries(entries, indent + 1) + + def GetEntries(self): + return self._cbfs_entries
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 29/31 binman: Support reading from CBFS entries
CBFS is a bit like a section but with a custom format. Provide the list of entries and the compression type to binman so that it can extract the data from the CBFS, just like any other part of the image.
---
Changes in v2: None
tools/binman/cbfs_util.py | 14 ++++++++++++++ tools/binman/etype/cbfs.py | 7 +++++++ 2 files changed, 21 insertions(+)
Applied to u-boot-dm, thanks!
PATCH v2 30/31 binman: Add an 'extract' command
In reply to Simon GlassIt is useful to be able to extract all binaries from the image, or a subset of them. Add a new 'extract' command to handle this.
---
Changes in v2: None
tools/binman/README | 25 +++++- tools/binman/cmdline.py | 13 +++ tools/binman/control.py | 60 +++++++++++++ tools/binman/ftest.py | 189 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 286 insertions(+), 1 deletion(-)
tools/binman/README +24 -1
@@ -533,6 +533,30 @@ or with wildcards: image-header bf8 8 image-header bf8 +Extracting files from images +---------------------------- + +You can extract files from an existing firmware image created by binman, +provided that there is an 'fdtmap' entry in the image. For example: + + $ binman extract -i image.bin section/cbfs/u-boot + +which will write the uncompressed contents of that entry to the file 'u-boot' in +the current directory. You can also extract to a particular file, in this case +u-boot.bin: + + $ binman extract -i image.bin section/cbfs/u-boot -f u-boot.bin + +It is possible to extract all files into a destination directory, which will +put files in subdirectories matching the entry hierarchy: + + $ binman extract -i image.bin -O outdir + +or just a selection: + + $ binman extract -i image.bin "*u-boot*" -O outdir + + Logging -------
@@ -883,7 +907,6 @@ Some ideas: - Use of-platdata to make the information available to code that is unable to use device tree (such as a very small SPL image) - Allow easy building of images by specifying just the board name -- Add an option to decode an image into the constituent binaries - Support building an image for a board (-b) more completely, with a configurable build directory - Support updating binaries in an image (with no size change / repacking)
tools/binman/cmdline.py +13 -0
@@ -71,6 +71,19 @@ controlled by a description in the board device tree.''' list_parser.add_argument('paths', type=str, nargs='*', help='Paths within file to list (wildcard)') + extract_parser = subparsers.add_parser('extract', + help='Extract files from an image') + extract_parser.add_argument('-i', '--image', type=str, required=True, + help='Image filename to extract') + extract_parser.add_argument('-f', '--filename', type=str, + help='Output filename to write to') + extract_parser.add_argument('-O', '--outdir', type=str, default='', + help='Path to directory to use for output files') + extract_parser.add_argument('paths', type=str, nargs='*', + help='Paths within file to extract (wildcard)') + extract_parser.add_argument('-U', '--uncompressed', action='store_true', + help='Output raw uncompressed data for compressed entries') + test_parser = subparsers.add_parser('test', help='Run tests') test_parser.add_argument('-P', '--processes', type=int, help='set number of processes to use for running tests')
tools/binman/control.py +60 -0
72 lines not on this page · raw message
tools/binman/ftest.py +189 -0
201 lines not on this page · raw message
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 30/31 binman: Add an 'extract' command
It is useful to be able to extract all binaries from the image, or a subset of them. Add a new 'extract' command to handle this.
---
Changes in v2: None
tools/binman/README | 25 +++++- tools/binman/cmdline.py | 13 +++ tools/binman/control.py | 60 +++++++++++++ tools/binman/ftest.py | 189 ++++++++++++++++++++++++++++++++++++++++ 4 files changed, 286 insertions(+), 1 deletion(-)
Applied to u-boot-dm, thanks!
PATCH v2 31/31 binman: Add a test for nested and aligned sections
In reply to Simon GlassCurrent test coverage is likely sufficient for the logic used to place sections in the image. However it seems useful to add a test specifically for nested sections, since these could have some unusual interactions.
Add a new test for this and aligned sections. This test failed before the refactor to drop the bsection.py file (Section class), but passes now.
---
Changes in v2:
- Add patches to enhance the 'ls' command to filter which entries are shown
- Add patches to implement the 'extract' command
tools/binman/ftest.py | 67 +++++++++++++++++++- tools/binman/test/131_pack_align_section.dts | 28 ++++++++ 2 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 tools/binman/test/131_pack_align_section.dts
tools/binman/ftest.py +66 -1
@@ -586,7 +586,7 @@ class TestFunctional(unittest.TestCase): def testSimpleDebug(self): """Test a simple binman run with debugging enabled""" - data = self._DoTestFile('005_simple.dts', debug=True) + self._DoTestFile('005_simple.dts', debug=True) def testDual(self): """Test that we can handle creating two images
@@ -2654,6 +2654,71 @@ class TestFunctional(unittest.TestCase): self.assertIn('Must specify exactly one entry path to write with -o', str(e.exception)) + def testPackAlignSection(self): + """Test that sections can have alignment""" + self._DoReadFile('131_pack_align_section.dts') + + self.assertIn('image', control.images) + image = control.images['image'] + entries = image.GetEntries() + self.assertEqual(3, len(entries)) + + # First u-boot + self.assertIn('u-boot', entries) + entry = entries['u-boot'] + self.assertEqual(0, entry.offset) + self.assertEqual(0, entry.image_pos) + self.assertEqual(len(U_BOOT_DATA), entry.contents_size) + self.assertEqual(len(U_BOOT_DATA), entry.size) + + # Section0 + self.assertIn('section0', entries) + section0 = entries['section0'] + self.assertEqual(0x10, section0.offset) + self.assertEqual(0x10, section0.image_pos) + self.assertEqual(len(U_BOOT_DATA), section0.size) + + # Second u-boot + section_entries = section0.GetEntries() + self.assertIn('u-boot', section_entries) + entry = section_entries['u-boot'] + self.assertEqual(0, entry.offset) + self.assertEqual(0x10, entry.image_pos) + self.assertEqual(len(U_BOOT_DATA), entry.contents_size) + self.assertEqual(len(U_BOOT_DATA), entry.size) + + # Section1 + self.assertIn('section1', entries) + section1 = entries['section1'] + self.assertEqual(0x14, section1.offset) + self.assertEqual(0x14, section1.image_pos) + self.assertEqual(0x20, section1.size) + + # Second u-boot + section_entries = section1.GetEntries() + self.assertIn('u-boot', section_entries) + entry = section_entries['u-boot'] + self.assertEqual(0, entry.offset) + self.assertEqual(0x14, entry.image_pos) + self.assertEqual(len(U_BOOT_DATA), entry.contents_size) + self.assertEqual(len(U_BOOT_DATA), entry.size) + + # Section2 + self.assertIn('section2', section_entries) + section2 = section_entries['section2'] + self.assertEqual(0x4, section2.offset) + self.assertEqual(0x18, section2.image_pos) + self.assertEqual(4, section2.size) + + # Third u-boot + section_entries = section2.GetEntries() + self.assertIn('u-boot', section_entries) + entry = section_entries['u-boot'] + self.assertEqual(0, entry.offset) + self.assertEqual(0x18, entry.image_pos) + self.assertEqual(len(U_BOOT_DATA), entry.contents_size) + self.assertEqual(len(U_BOOT_DATA), entry.size) + if __name__ == "__main__": unittest.main()
tools/binman/test/131_pack_align_section.dts new file +28 -0
@@ -0,0 +1,28 @@ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + binman { + u-boot { + }; + section0 { + type = "section"; + align = <0x10>; + u-boot { + }; + }; + section1 { + type = "section"; + align-size = <0x20>; + u-boot { + }; + section2 { + type = "section"; + u-boot { + }; + }; + }; + }; +};
Signature · 1 line
2.22.0.410.gd8fdbe21b5-goog
PATCH v2 31/31 binman: Add a test for nested and aligned sections
Current test coverage is likely sufficient for the logic used to place sections in the image. However it seems useful to add a test specifically for nested sections, since these could have some unusual interactions.
Add a new test for this and aligned sections. This test failed before the refactor to drop the bsection.py file (Section class), but passes now.
---
Changes in v2:
- Add patches to enhance the 'ls' command to filter which entries are shown
- Add patches to implement the 'extract' command
tools/binman/ftest.py | 67 +++++++++++++++++++- tools/binman/test/131_pack_align_section.dts | 28 ++++++++ 2 files changed, 94 insertions(+), 1 deletion(-) create mode 100644 tools/binman/test/131_pack_align_section.dts
Applied to u-boot-dm, thanks!