fdtfactor: Introduce fdtfactor to auto-factor overlays
Subsystems (2)
v2 cover fdtfactor: Introduce fdtfactor to auto-factor overlays
Devicetree overlays exist at both the source level (via /include/ and .dtsi files) and the binary level (where a compiled .dtbo overlay is applied to a "base" .dtb at runtime to add or modify nodes).
Binary .dtbo overlays were created by transcribing source-level overlay semantics to .dtb blobs to serve two main use cases:
1. Supporting add-on boards (like "hats" on a dev board), where a base board's .dtb is combined with an add-on board's .dtbo at boot or runtime (a use case that Hervé Codina's upcoming "addons" work aims to model more cleanly).
2. Allowing constrained bootloaders or firmware images to support a "family" of similar boards in a space-efficient way without shipping a full .dtb for every variant. In upstream Linux, for example, there are 47 distinct sc7180-trogdor boards supported. At the source level these boards share common .dtsi files, but we still compile (and ship) 47 separate full .dtb blobs. Binary devicetree overlays can make this much more efficient by factoring the common bits into a single base .dtb and representing each of the 47 boards as a small .dtbo overlay.
Even though .dtbo overlay semantics are a natural fit for case #2 (since they derive from source-level .dts overlays, which were designed for board/SoC families), upstream Linux has mostly reserved compiled .dtso -> .dtbo overlays for case #1. Many Android phones attempt to use .dtso overlays for case #2 by describing the SoC as the base devicetree and describing boards in .dtso overlays, but forcing the binary base/overlay split into the source files has drawbacks: there is still lots of duplication between board overlays, and upstream reception towards structuring board source files this way has been lukewarm [1].
This patch series introduces a tool to decouple binary .dtbo generation from .dts source structure. The idea (suggested by Konrad Dybcio at LPC) is to continue to represent all the boards in a family as normal standalone device trees in source code (using .dtsi includes as makes sense for human readability). Then, after building the full .dtb blobs, fdtfactor automatically factors them into a common base .dtb and a set of per-board .dtbo overlays.
This tool has quite a few advantages over other solutions:
1. No change to the way device trees are stored / arranged upstream.
2. No need to deal with some of the awkwardness / limitations of overlays.
3. Better savings than just a simple partitioning, like between SoC and boards.
I've used this tool to reduce sc7180-trogdor device tree files (which are stored lz4 compressed) from 1.71 MB to 213 KB, an 87.5% savings.
To compare against the manual SoC-base + board-overlay split used by downstream Android kernels, I also tested fdtfactor -S on the downstream Pixel 10 family device trees (29 physical hardware board
variants: 27 phone variants across Pixel 10, Pixel 10 Pro, and Pixel 10 Pro XL plus 2 socketed dev board variants) by combining the downstream base + overlays into full board DTBs and re-factoring them with fdtfactor -S:
* Just B0 silicon (29 boards):
- Full unfactored DTBs (29 .dtbs): 26.30 MB uncompressed (5.28 MB
lz4)
- Downstream manual SoC base (`lga-b0.dtb`) + 29 board `.dtbo`s:
8.06 MB uncompressed (1.66 MB lz4) - Auto-factored with fdtfactor -S (1 base.dtb + 29 .dtbos):
3.27 MB uncompressed (668 KB lz4) -- 2.48x smaller than the manual SoC split (and 3.68x smaller across the 27 phone boards alone, where average overlay size drops from 252 KB to 44 KB uncompressed, or 52 KB to 9.1 KB lz4).
* Both A0 and B0 SoC steppings:
In practice, phone Proto boards (8 variants) only ever use A0 silicon, phone EVT1.1+ boards (15 variants) only ever use B0 silicon, and only phone EVT1 boards (4 variants) and the socketed dev boards (2 variants) can have either A0 or B0 silicon -- giving 35 realistic (board, stepping) combinations (14 A0 + 21 B0), compared to 58 for a naive 29 x 2 cross-product:
- Full unfactored DTBs (35 .dtbs): 31.71 MB uncompressed (6.37 MB
lz4)
- Downstream manual split (2 SoC bases `lga-a0.dtb` + `lga-b0.dtb` +
29 board `.dtbo`s): 8.78 MB uncompressed (1.79 MB lz4) - Auto-factored with fdtfactor -S (1 shared base.dtb + 35 .dtbos): 4.00 MB uncompressed (855 KB lz4). This could likely be improved more with multiple levels of overlays, but we're already 2x smaller than what downstream is doing today.
NOTE: on Chromebooks like sc7180-trogdor, using overlays like this is an optimization. On Android phones like Pixel 10, the bootloader logic bakes in the need for overlays. Specifically, if we want to be able to build a single image that supports multiple boards and have the bootloader auto-construct the right devicetree, we need the boards to be represented by overlays. This fdtfactor tool can make that a reality.
The fdtfactor tool can either work directly on a set of compiled devicetree files or it can work on a FIT (flattened image tree) file. The idea is that you'd create the FIT file containing all of the duplicated devicetree files and then fdtfactor would "optimize" them.
Before introducing fdtfactor itself, the series starts with a few preparatory patches: adding Python iterators and a NodeTree live-tree abstraction to pylibfdt, and teaching libfdt's fdt_overlay_apply() to update /__local_fixups__ on the base tree so overlays can be applied in multiple stages.
I'll freely admit that the patches in this series were pretty heavily vibe coded. I'll not pretend that I have a deep understanding of the intricacies of how overlays are implemented. That being said:
* I've spent quite a bit of time reviewing the code from a high-level
perspective: confirming that functions are well documented, well structured, and make sense.
* I believe that what the tool is doing and how the tool is used make sense.
* I have had quite a number of internal "the AI reviews the AI" rounds to the point of diminishing returns.
At this point, I'm not embarrassed to put my name behind this. While I won't promise that there are zero cases of the AI doing something really stupid, I'd be willing to bet that the end result is better (and cleaner / better structured) than what I would have coded up if I had spent a few weeks doing this on my own.
[1] https://lore.kernel.org/all/20251114-elite-refined-yak-bf9e64@kuoka/
v1: https://lore.kernel.org/r/[email protected]
Changes in v2:
- New patch fixing FdtSw.as_fdt() buffer resize when < 4 bytes remain
- New patch adding FdtRo.subnodes(), FdtRo.properties(), and FdtRo.get_mem_rsv_list()
- Split NodeTree live tree representation out of fdtfactor into pylibfdt (David Gibson)
- New patch factoring out overlay_parse_fixup_entry() and overlay_split_fragment_path() helpers in libfdt/fdt_overlay.c
- New patch tightening fixup offset parsing and generalizing overlay_split_fragment_path() for non-NUL-terminated paths in libfdt/fdt_overlay.c
- New patch updating base /__local_fixups__ in libfdt fdt_overlay_apply() instead of stripping /__local_fixups__ by default (David Gibson)
- Preserve /__local_fixups__ on base.dtb by default (David Gibson)
- Store parsed trees directly in NodeTree with node.phandle and node.fixups attributes instead of parallel dicts (David Gibson)
- Extract phandles in a separate pass after unflattening and reject legacy linux,phandle properties (David Gibson)
- Exclude non-root common phandle nodes lacking a common symbol from base.dtb instead of synthesizing __fdtfactor_ph_* symbols (David Gibson)
- Drop -q/--quiet, rename -v/--verbose to -s/--stats, and move tests to a dedicated fdtfactor test suite (David Gibson)
- Split -S/--strip-local-fixups into a separate opt-in patch (David Gibson)
- Add --base-compression to explicitly control base.dtb compression while documenting auto-detection from --base-dtb's filename suffix (David Gibson)
- Support legacy LZ4 frames (lz4 -l) and use CRC32 check for XZ outputs (Simon Glass)
- Drop "tests: Fix Python test environment setup in meson.build" (applied upstream by David Gibson)
- Clarify source-level (.dts/.dtsi) vs. binary-level (.dtb/.dtbo) overlay history in cover letter (David Gibson)
- Add Pixel 10 (Tensor G5) base + overlay comparison numbers to cover letter (Simon Glass)
- Rename -f/--fit and -F/--fit-out to -F/--fit and --outfile and clarify FIT mode in the --help description (David Gibson, Simon Glass)
- Reject signed FIT images with signature* subnodes (Simon Glass)
- Use '<base-node-name>.dtb' for FIT base FDT descriptions instead of common-prefix heuristics (Simon Glass)
- Compare FIT group node overlap against the group's common node set instead of only the first entry (Simon Glass)
- Document in README.md that U-Boot's boot_get_fdt_fit() currently requires FIT overlays to be uncompressed (Simon Glass)
Douglas Anderson (10):
pylibfdt: Fix FdtSw.as_fdt() when buffer is nearly full
pylibfdt: Add subnode/property iterators and get_mem_rsv_list()
pylibfdt: Add NodeTree live tree representation
libfdt: overlay: Factor out fixup and fragment path parsing helpers
libfdt: overlay: Prepare fixup and fragment path helpers for reuse
libfdt: overlay: Update base /__local_fixups__ on apply
fdtfactor: Add tool to split DTBs into a base DTB and overlays
fdtfactor: Add -S/--strip-local-fixups option
fdtfactor: Support compressed DTB inputs and outputs
fdtfactor: Add compiled FIT image factoring support
Makefile | 2 +- README.md | 74 ++ fdtfactor | 1626 ++++++++++++++++++++++++++++ libfdt/fdt_overlay.c | 847 +++++++++++++-- meson.build | 1 + pylibfdt/libfdt.i | 310 +++++- tests/Makefile.tests | 7 +- tests/fdtfactor_board1.dts | 38 + tests/fdtfactor_board2.dts | 36 + tests/fdtfactor_board3.dts | 34 + tests/fdtfactor_board3_shifted.dts | 34 + tests/fdtfactor_lz4.its | 109 ++ tests/fdtfactor_other1.dts | 33 + tests/fdtfactor_other2.dts | 33 + tests/fdtfactor_test.its | 109 ++ tests/meson.build | 2 +- tests/pylibfdt_tests.py | 80 ++ tests/run_tests.sh | 337 +++++- tests/testutils.sh | 1 + 19 files changed, 3629 insertions(+), 84 deletions(-) create mode 100755 fdtfactor create mode 100644 tests/fdtfactor_board1.dts create mode 100644 tests/fdtfactor_board2.dts create mode 100644 tests/fdtfactor_board3.dts create mode 100644 tests/fdtfactor_board3_shifted.dts create mode 100644 tests/fdtfactor_lz4.its create mode 100644 tests/fdtfactor_other1.dts create mode 100644 tests/fdtfactor_other2.dts create mode 100644 tests/fdtfactor_test.its
Signature · 1 line
2.56.0.313.g2479322e68-goog
PATCH v2 1/10 pylibfdt: Fix FdtSw.as_fdt() when buffer is nearly full
FdtSw.as_fdt() calls fdt_finish() on a copy of self._fdt without using self.check_space(). Because fdt_finish() appends the 4-byte FDT_END token, as_fdt() raises FdtException(FDT_ERR_NOSPACE) if fewer than 4 bytes of free space remain in self._fdt after the final end_node().
Wrap fdt_finish() in a while self.check_space(fdt_finish(fdtsw)): loop so FdtSw.as_fdt() automatically resizes the buffer when needed, matching the rest of FdtSw's methods.
---
Changes in v2:
- New patch fixing FdtSw.as_fdt() buffer resize when < 4 bytes remain
pylibfdt/libfdt.i | 3 ++- tests/pylibfdt_tests.py | 8 ++++++++ 2 files changed, 10 insertions(+), 1 deletion(-)
pylibfdt/libfdt.i +2 -1
@@ -959,7 +959,8 @@ class FdtSw(FdtRo): Fdt object allowing access to the newly created device tree """ fdtsw = bytearray(self._fdt) - check_err(fdt_finish(fdtsw)) + while self.check_space(fdt_finish(fdtsw)): + fdtsw = bytearray(self._fdt) return Fdt(fdtsw) def check_space(self, val):
tests/pylibfdt_tests.py +8 -0
@@ -646,6 +646,14 @@ class PyLibfdtSwTests(unittest.TestCase): # Make sure we did at least two resizes self.assertTrue(len(fdt.as_bytearray()) > FdtSw.INC_SIZE * 2) + # Check that as_fdt() resizes when fewer than 4 bytes remain for FDT_END + sw_exact = FdtSw(76) + sw_exact.finish_reservemap() + sw_exact.begin_node('') + sw_exact.end_node() + fdt_exact = sw_exact.as_fdt() + self.assertEqual(80, fdt_exact.totalsize()) + class PyLibfdtRoTests(unittest.TestCase): """Test class for read-only pylibfdt access functions
Signature · 1 line
2.56.0.313.g2479322e68-goog
PATCH v2 2/10 pylibfdt: Add subnode/property iterators and get_mem_rsv_list()
In reply to Douglas AndersonAdd Pythonic iterator helpers on FdtRo to simplify walking nodes, properties, and memory reservation entries without manual offset loops or -FDT_ERR_NOTFOUND sentinel handling:
- subnodes(nodeoffset): yields the offset of each direct child subnode of nodeoffset.
- properties(nodeoffset): yields a Property object for each property of nodeoffset.
- get_mem_rsv_list(): returns a list of (address, size) tuples for all entries in the memory reservation block.
---
Changes in v2:
- New patch adding FdtRo.subnodes(), FdtRo.properties(), and FdtRo.get_mem_rsv_list()
pylibfdt/libfdt.i | 45 +++++++++++++++++++++++++++++++++++++++++ tests/pylibfdt_tests.py | 18 +++++++++++++++++ 2 files changed, 63 insertions(+)
pylibfdt/libfdt.i +45 -0
@@ -201,6 +201,23 @@ class FdtRo(object): """ return check_err(fdt_next_subnode(self._fdt, nodeoffset), quiet) + def subnodes(self, nodeoffset): + """Iterate over the subnodes of a node + + Args: + nodeoffset: Offset of parent node to check + + Yields: + Node offset of each direct subnode in order + + Raises: + FdtException on error (e.g. invalid nodeoffset) + """ + soff = self.first_subnode(nodeoffset, quiet=QUIET_NOTFOUND) + while soff >= 0: + yield soff + soff = self.next_subnode(soff, quiet=QUIET_NOTFOUND) + def magic(self): """Return the magic word from the header
@@ -302,6 +319,17 @@ class FdtRo(object): check_err(val[0], quiet) return val[1:] + def get_mem_rsv_list(self): + """Return a list of all memory reserve-map records + + Returns: + List of (address, size) tuples for each memory reserve-map record + """ + return [ + tuple(self.get_mem_rsv(i)) + for i in range(self.num_mem_rsv()) + ] + def address_cells(self, nodeoffset, quiet=()): """Return the number of address cells used by a node's children
@@ -434,6 +462,23 @@ class FdtRo(object): return pdata[1] return Property(pdata[0], pdata[1]) + def properties(self, nodeoffset): + """Iterate over the properties of a node + + Args: + nodeoffset: Offset of node to check + + Yields: + Property object for each property on @nodeoffset in order + + Raises: + FdtException on error (e.g. invalid nodeoffset) + """ + poff = self.first_property_offset(nodeoffset, quiet=QUIET_NOTFOUND) + while poff >= 0: + yield self.get_property_by_offset(poff) + poff = self.next_property_offset(poff, quiet=QUIET_NOTFOUND) + def getprop(self, nodeoffset, prop_name, quiet=()): """Get a property from a node
tests/pylibfdt_tests.py +18 -0
@@ -243,6 +243,22 @@ class PyLibfdtBasicTests(unittest.TestCase): node_list.append(self.fdt.get_name(node)) node = self.fdt.next_subnode(node, QUIET_NOTFOUND) self.assertEqual(node_list, ['subnode@1', 'subnode@2']) + self.assertEqual( + [self.fdt.get_name(n) for n in self.fdt.subnodes(0)], + ['subnode@1', 'subnode@2'], + ) + leaf = self.fdt.path_offset('/subnode@1/ss1') + self.assertEqual(list(self.fdt.subnodes(leaf)), []) + + def testPropertiesIterator(self): + """Check that we can iterate through properties of a node""" + node = self.fdt.path_offset('/subnode@1') + props = list(self.fdt.properties(node)) + self.assertEqual([p.name for p in props], + ['compatible', 'reg', 'prop-int']) + self.assertEqual(props[0], b'subnode1\0') + leaf = self.fdt.path_offset('/subnode@1/ss1') + self.assertEqual(list(self.fdt.properties(leaf)), []) def testFirstNextSubnodeOffsetExceptions(self): """Check except handling for first/next subnode functions"""
@@ -410,6 +426,8 @@ class PyLibfdtBasicTests(unittest.TestCase): self.assertEqual([ 0xdeadbeef00000000, 0x100000], self.fdt.get_mem_rsv(0)) self.assertEqual([123456789, 0o10000], self.fdt.get_mem_rsv(1)) + self.assertEqual([(0xdeadbeef00000000, 0x100000), (123456789, 0o10000)], + self.fdt.get_mem_rsv_list()) def testAddDelReserveMap(self): """Test that we can add to and remove from the memory reserve map"""
Signature · 1 line
2.56.0.313.g2479322e68-goog
PATCH v2 3/10 pylibfdt: Add NodeTree live tree representation
In reply to Douglas AndersonAdd NodeTree, an in-memory live tree representation of a devicetree node and its subtree, to pylibfdt:
- NodeTree.unflatten(fdt, offset=0) builds a NodeTree hierarchy from an FdtRo instance.
- NodeTree.flatten(mem_rsv=(), boot_cpuid_phys=0) serializes a root NodeTree back into a packed FDT blob via FdtSw.
- get_node(), create_path(), and walk() provide path lookup, intermediate node creation, and pre-order traversal.
- get_str(), set_str(), get_stringlist(), set_stringlist(), get_u32(), set_u32(), get_u32_list(), and set_u32_list() provide typed property access and mutation (updating Property.as_str() and Property.as_stringlist() so empty b'' properties raise ValueError or return [] rather than IndexError).
Add unit tests in tests/pylibfdt_tests.py covering NodeTree unflatten/flatten round-tripping and helper methods.
---
Changes in v2:
- Split NodeTree live tree representation out of fdtfactor into pylibfdt (David Gibson)
pylibfdt/libfdt.i | 262 +++++++++++++++++++++++++++++++++++++++- tests/pylibfdt_tests.py | 54 +++++++++ 2 files changed, 315 insertions(+), 1 deletion(-)
pylibfdt/libfdt.i +261 -1
@@ -929,7 +929,7 @@ class Property(bytearray): def as_str(self): """Unicode is supported by decoding from UTF-8""" - if self[-1] != 0: + if not self or self[-1] != 0: raise ValueError('Property lacks nul termination') if 0 in self[:-1]: raise ValueError('Property contains embedded nul characters')
@@ -937,6 +937,8 @@ class Property(bytearray): def as_stringlist(self): """Unicode is supported by decoding from UTF-8""" + if not self: + return [] if self[-1] != 0: raise ValueError('Property lacks nul termination') parts = self[:-1].split(b'\x00')
@@ -1210,6 +1212,264 @@ class NodeAdder(): def __exit__(self, type, value, traceback): self._fdt.end_node() + + +class NodeTree: + """In-memory live tree representation of a devicetree node and its subtree. + + Attributes: + props: Dict mapping property name (str) to raw property value (bytes). + children: Dict mapping child node name (str) to child NodeTree. + """ + + def __init__(self): + self.props = {} + self.children = {} + + @classmethod + def unflatten(cls, fdt, offset=0): + """Unflatten an FdtRo subtree starting at `offset` into a NodeTree. + + Args: + fdt: An `FdtRo` (or `Fdt`) instance. + offset: Starting node offset (default 0 for the root node). + + Returns: + A `NodeTree` representing the node at `offset` and its descendants. + """ + node = cls() + for prop in fdt.properties(offset): + node.props[prop.name] = bytes(prop) + for suboff in fdt.subnodes(offset): + node.children[fdt.get_name(suboff)] = cls.unflatten(fdt, suboff) + return node + + def _flatten_subtree(self, sw, name): + """Recursively write this NodeTree and its children into an FdtSw. + + Args: + sw: An `FdtSw` sequential-write instance. + name: Node name for this subtree (empty string `''` for root). + """ + with sw.add_node(name): + for prop_name, val in self.props.items(): + sw.property(prop_name, bytes(val)) + for child_name, child_node in self.children.items(): + child_node._flatten_subtree(sw, child_name) + + def flatten(self, mem_rsv=(), boot_cpuid_phys=0): + """Serialize this root NodeTree into a packed FDT byte string. + + Args: + mem_rsv: Iterable of (address, size) tuples for the FDT memory + reservation block. + boot_cpuid_phys: Physical boot CPU ID for the FDT header. + + Returns: + Serialized FDT blob as `bytes`. + """ + sw = FdtSw() + for addr, size in mem_rsv: + sw.add_reservemap_entry(addr, size) + sw.finish_reservemap() + self._flatten_subtree(sw, '') + fdt = sw.as_fdt() + fdt_set_boot_cpuid_phys(fdt._fdt, boot_cpuid_phys) + fdt.pack() + return bytes(fdt.as_bytearray()) + + def get_node(self, path): + """Look up a descendant NodeTree by path without modifying the tree. + + Follows the slash-separated node names in `path` starting from `self` + (leading, trailing, and repeated `'/'` characters are ignored, so + `'/soc/i2c@4000'` and `'soc/i2c@4000'` behave identically, and `''` or + `'/'` returns `self`). If any component along `path` is not present in + `children`, returns `None`. + + Args: + path: Slash-separated node path starting from `self` (e.g. + `'/soc/i2c@4000'` or `'soc/i2c@4000'`). + + Returns: + The `NodeTree` at `path`, or `None` if not found. + """ + node = self + for part in path.split('/'): + if not part: + continue + node = node.children.get(part) + if node is None: + return None + return node + + def create_path(self, path): + """Return the descendant NodeTree at `path`, creating missing nodes. + + Looks up a child or deeper descendant `NodeTree` by following the + slash-separated node names in `path` starting from `self` (leading, + trailing, and repeated `'/'` characters are ignored, so + `'/soc/i2c@4000'` and `'soc/i2c@4000'` behave identically). If any + node along `path` does not exist yet in `children`, a new empty + `NodeTree` is created for it automatically (similar to `mkdir -p`). + Passing `''` or `'/'` returns `self`. + + Example: + root = NodeTree() + # Automatically creates root.children['soc'] and + # root.children['soc'].children['i2c@4000'], and returns the + # 'i2c@4000' NodeTree. + i2c = root.create_path('/soc/i2c@4000') + i2c.set_str('status', 'okay') + + Args: + path: Slash-separated node path starting from `self` (e.g. + `'/soc/i2c@4000'` or `'soc/i2c@4000'`). + + Returns: + The `NodeTree` instance at `path`. + """ + node = self + for part in path.split('/'): + if not part: + continue + if part not in node.children: + node.children[part] = type(self)() + node = node.children[part] + return node + + def walk(self, path=''): + """Yield `(path, node)` pairs for this subtree in pre-order. + + Args: + path: Path prefix for `self` (defaults to `''` for the root node, + producing paths like `''`, `'/soc'`, `'/soc/i2c@4000'`). + + Yields: + Tuple of `(path, node)` for `self` followed recursively by each + descendant `NodeTree`. + """ + prefix = path.rstrip('/') + yield path, self + for name, child in self.children.items(): + yield from child.walk(f'{prefix}/{name}') + + def get_str(self, name): + """Return property `name` decoded as a NUL-terminated UTF-8 string. + + Args: + name: Property name to look up in `self.props`. + + Returns: + Decoded string value (without the trailing NUL byte). + + Raises: + KeyError: If `name` is not in `self.props`. + ValueError: If the property value is not a single NUL-terminated + UTF-8 string. + """ + return Property(name, self.props[name]).as_str() + + def set_str(self, name, val): + """Set property `name` to a NUL-terminated UTF-8 string. + + Args: + name: Property name to set in `self.props`. + val: String value to encode as UTF-8 with a trailing NUL byte. + + Raises: + ValueError: If `val` contains embedded NUL characters. + """ + if '\x00' in val: + raise ValueError('String value contains embedded nul characters') + self.props[name] = val.encode('utf-8') + b'\x00' + + def get_stringlist(self, name): + """Return property `name` decoded as a list of NUL-separated strings. + + Args: + name: Property name to look up in `self.props`. + + Returns: + List of decoded UTF-8 strings (`[]` if the property is empty). + + Raises: + KeyError: If `name` is not in `self.props`. + ValueError: If a non-empty property lacks NUL termination. + """ + return Property(name, self.props[name]).as_stringlist() + + def set_stringlist(self, name, vals): + """Set property `name` to a NUL-separated list of UTF-8 strings. + + Args: + name: Property name to set in `self.props`. + vals: Iterable of strings to encode as NUL-terminated UTF-8. + + Raises: + ValueError: If any string in `vals` contains embedded NUL + characters. + """ + vals = list(vals) + if any('\x00' in v for v in vals): + raise ValueError('String value contains embedded nul characters') + self.props[name] = b''.join(v.encode('utf-8') + b'\x00' for v in vals) + + def get_u32(self, name): + """Return property `name` decoded as a single big-endian uint32 cell. + + Args: + name: Property name to look up in `self.props`. + + Returns: + Integer value of the 32-bit cell. + + Raises: + KeyError: If `name` is not in `self.props`. + ValueError: If the property length is not 4 bytes. + """ + raw = self.props[name] + if len(raw) != 4: + raise ValueError(f'Property {name!r} length {len(raw)} != 4') + return Property(name, raw).as_uint32() + + def set_u32(self, name, val): + """Set property `name` to a single big-endian uint32 cell. + + Args: + name: Property name to set in `self.props`. + val: Unsigned 32-bit integer value. + """ + self.props[name] = struct.pack('>I', val) + + def get_u32_list(self, name): + """Return property `name` decoded as a list of big-endian uint32 cells. + + Args: + name: Property name to look up in `self.props`. + + Returns: + List of 32-bit unsigned integers. + + Raises: + KeyError: If `name` is not in `self.props`. + ValueError: If the property length is not a multiple of 4 bytes. + """ + raw = self.props[name] + if len(raw) % 4 != 0: + raise ValueError( + f'Property {name!r} length {len(raw)} is not a multiple of 4' + ) + return Property(name, raw).as_uint32_list() + + def set_u32_list(self, name, vals): + """Set property `name` to a sequence of big-endian uint32 cells. + + Args: + name: Property name to set in `self.props`. + vals: Sequence of unsigned 32-bit integer values. + """ + self.props[name] = struct.pack(f'>{len(vals)}I', *vals) %} %rename(fdt_property) fdt_property_func;
tests/pylibfdt_tests.py +54 -0
60 lines not on this page · raw message
Signature · 1 line
2.56.0.313.g2479322e68-goog
PATCH v2 4/10 libfdt: overlay: Factor out fixup and fragment path parsing helpers
In reply to Douglas AndersonIn preparation for updating the base device tree's /__local_fixups__ node during fdt_overlay_apply(), factor out two helper functions in libfdt/fdt_overlay.c:
- Factor out overlay_parse_fixup_entry() from overlay_fixup_phandle() to parse "path:name:offset" entries in /__fixups__ properties.
- Factor out overlay_split_fragment_path() from overlay_symbol_update() to validate and split "/<fragment>/__overlay__[/<rel>]" paths into the fragment name and relative subnode path.
This commit is pure code movement with no functional change.
---
Changes in v2:
- New patch factoring out overlay_parse_fixup_entry() and overlay_split_fragment_path() helpers in libfdt/fdt_overlay.c
libfdt/fdt_overlay.c | 226 +++++++++++++++++++++++++++++-------------- 1 file changed, 154 insertions(+), 72 deletions(-)
libfdt/fdt_overlay.c +154 -72
@@ -351,6 +351,72 @@ static int overlay_fixup_one_phandle(void *fdto, int symbols_off, sizeof(phandle_prop)); } +/** +* overlay_parse_fixup_entry - Parse one "path:name:offset" entry from /__fixups__ +* @valuep: In/out pointer to the current NUL-terminated fixup string +* @lenp: In/out remaining length of the /__fixups__ property value +* @pathp: Output pointer to the target node path +* @path_lenp: Output length of @pathp in bytes +* @namep: Output pointer to the target property name +* @name_lenp: Output length of @namep in bytes +* @poffsetp: Output byte offset within the target property +* +* returns: +* 0 on success +* -FDT_ERR_BADOVERLAY if the fixup entry is malformed +*/ +static int overlay_parse_fixup_entry (const char **valuep,int *lenp, +const char **pathp,uint32_t *path_lenp, +const char **namep,uint32_t *name_lenp, +int *poffsetp) +{ +const char *path, *name, *fixup_end; +const char *fixup_str = *valuep; +uint32_t path_len, name_len; +uint32_t fixup_len; +const char *sep; +char *endptr; +int poffset; + + fixup_end =memchr (*valuep,'\0' , *lenp); +if (!fixup_end) +return -FDT_ERR_BADOVERLAY ; + fixup_len = fixup_end - fixup_str; + + *lenp -= fixup_len +1 ; + *valuep += fixup_len +1 ; + + path = fixup_str; + sep =memchr (fixup_str,':' , fixup_len); +if (!sep || *sep !=':' ) +return -FDT_ERR_BADOVERLAY ; + + path_len = sep - path; +if (path_len == (fixup_len -1 )) +return -FDT_ERR_BADOVERLAY ; + + fixup_len -= path_len +1 ; + name = sep +1 ; + sep =memchr (name,':' , fixup_len); +if (!sep || *sep !=':' ) +return -FDT_ERR_BADOVERLAY ; + + name_len = sep - name; +if (!name_len) +return -FDT_ERR_BADOVERLAY ; + + poffset =strtoul (sep +1 , &endptr,10 ); +if ((*endptr !='\0' ) || (endptr <= (sep +1 ))) +return -FDT_ERR_BADOVERLAY ; + + *pathp = path; + *path_lenp = path_len; + *namep = name; + *name_lenp = name_len; + *poffsetp = poffset; +return 0 ; +} +/** * overlay_fixup_phandle - Set an overlay phandle to the base one * @fdt: Base Device Tree blob
@@ -403,44 +469,14 @@ static int overlay_fixup_phandle(void *fdt, void *fdto, int symbols_off,return -FDT_ERR_NOTFOUND ; do { - const char *path, *name, *fixup_end; - const char *fixup_str = value; + const char *path, *name; uint32_t path_len, name_len; - uint32_t fixup_len; - const char *sep; - char *endptr; int poffset, ret; - fixup_end = memchr(value, '\0', len); - if (!fixup_end) - return -FDT_ERR_BADOVERLAY; - fixup_len = fixup_end - fixup_str; - - len -= fixup_len + 1; - value += fixup_len + 1; - - path = fixup_str; - sep = memchr(fixup_str, ':', fixup_len); - if (!sep || *sep != ':') - return -FDT_ERR_BADOVERLAY; - - path_len = sep - path; - if (path_len == (fixup_len - 1)) - return -FDT_ERR_BADOVERLAY; - - fixup_len -= path_len + 1; - name = sep + 1; - sep = memchr(name, ':', fixup_len); - if (!sep || *sep != ':') - return -FDT_ERR_BADOVERLAY; - - name_len = sep - name; - if (!name_len) - return -FDT_ERR_BADOVERLAY; - - poffset = strtoul(sep + 1, &endptr, 10); - if ((*endptr != '\0') || (endptr <= (sep + 1))) - return -FDT_ERR_BADOVERLAY; + ret = overlay_parse_fixup_entry(&value, &len, &path, &path_len, + &name, &name_len, &poffset); + if (ret) + return ret; ret = overlay_fixup_one_phandle(fdto, symbols_off, path, path_len, name, name_len,
@@ -887,6 +923,80 @@ static int get_path_len(const void *fdt, int nodeoffset)return len; } +/** +* overlay_split_fragment_path - Split "/<frag>/__overlay__[/<rel>]" into parts +* @path: Input NUL-terminated path property string +* @path_len: Length of @path in bytes (including trailing NUL) +* @frag_namep: Output pointer to the fragment name +* @frag_name_lenp: Output length of @frag_namep in bytes +* @rel_pathp: Output pointer to the relative subnode path after __overlay__ +* @rel_path_lenp: Output length of @rel_pathp in bytes +* @is_overlayp: Set to true if @path is under an __overlay__ subnode +* +* returns: +* 0 on success +* -FDT_ERR_BADVALUE if @path is not a valid NUL-terminated '/' path +*/ +static int overlay_split_fragment_path (const char *path,int path_len, +const char **frag_namep, +int *frag_name_lenp, +const char **rel_pathp, +int *rel_path_lenp, +bool *is_overlayp) +{ +int len, frag_name_len, rel_path_len; +const char *s, *e; +const char *frag_name; +const char *rel_path; + + *is_overlayp = false; + +/* verify it's a string property (terminated by a single \0) */ +if (path_len <1 ||memchr (path,'\0' , path_len) != &path[path_len -1 ]) +return -FDT_ERR_BADVALUE ; + +/* keep end marker to avoid strlen() */ + e = path + path_len; + +if (*path !='/' ) +return -FDT_ERR_BADVALUE ; + +/* get fragment name first */ + s =strchr (path +1 ,'/' ); +if (!s) { +/* Symbol refers to something that won't end +* up in the target tree */ +return 0 ; + } + + frag_name = path +1 ; + frag_name_len = s - path -1 ; + +/* verify format; safe since "s" lies in \0 terminated prop */ + len =sizeof ("/__overlay__/" ) -1 ; +if ((e - s) > len && (memcmp (s,"/__overlay__/" , len) ==0 )) { +/* /<fragment-name>/__overlay__/<relative-subnode-path> */ + rel_path = s + len; + rel_path_len = e - rel_path -1 ; + }else if ((e - s) == len + && (memcmp (s,"/__overlay__" , len -1 ) ==0 )) { +/* /<fragment-name>/__overlay__ */ + rel_path ="" ; + rel_path_len =0 ; + }else { +/* Symbol refers to something that won't end +* up in the target tree */ +return 0 ; + } + + *frag_namep = frag_name; + *frag_name_lenp = frag_name_len; + *rel_pathp = rel_path; + *rel_path_lenp = rel_path_len; + *is_overlayp = true; +return 0 ; +} +/** * overlay_symbol_update - Update the symbols of base tree after a merge * @fdt: Base Device Tree blob
@@ -907,7 +1017,6 @@ static int overlay_symbol_update(void *fdt, void *fdto) {int root_sym, ov_sym, prop, path_len, fragment, target;int len, frag_name_len, ret, rel_path_len; -const char *s, *e;const char *path;const char *name;const char *frag_name;
@@ -934,47 +1043,20 @@ static int overlay_symbol_update(void *fdt, void *fdto)/* iterate over each overlay symbol */ fdt_for_each_property_offset (prop, fdto, ov_sym) { +bool is_overlay; + path =fdt_getprop_by_offset (fdto, prop, &name, &path_len);if (!path)return path_len; -/* verify it's a string property (terminated by a single \0) */ -if (path_len <1 ||memchr (path,'\0' , path_len) != &path[path_len -1 ]) -return -FDT_ERR_BADVALUE ; - -/* keep end marker to avoid strlen() */ - e = path + path_len; - -if (*path !='/' ) -return -FDT_ERR_BADVALUE ; - -/* get fragment name first */ - s =strchr (path +1 ,'/' ); -if (!s) { -/* Symbol refers to something that won't end -* up in the target tree */ -continue ; - } - - frag_name = path +1 ; - frag_name_len = s - path -1 ; - -/* verify format; safe since "s" lies in \0 terminated prop */ - len =sizeof ("/__overlay__/" ) -1 ; -if ((e - s) > len && (memcmp (s,"/__overlay__/" , len) ==0 )) { -/* /<fragment-name>/__overlay__/<relative-subnode-path> */ - rel_path = s + len; - rel_path_len = e - rel_path -1 ; - }else if ((e - s) == len - && (memcmp (s,"/__overlay__" , len -1 ) ==0 )) { -/* /<fragment-name>/__overlay__ */ - rel_path ="" ; - rel_path_len =0 ; - }else { -/* Symbol refers to something that won't end -* up in the target tree */ + ret =overlay_split_fragment_path (path, path_len, + &frag_name, &frag_name_len, + &rel_path, &rel_path_len, + &is_overlay); +if (ret) +return ret; +if (!is_overlay)continue ; - }/* find the fragment index in which the symbol lies */ ret = fdt_subnode_offset_namelen(fdto, 0, frag_name,
Signature · 1 line
2.56.0.313.g2479322e68-goog
PATCH v2 5/10 libfdt: overlay: Prepare fixup and fragment path helpers for reuse
In reply to Douglas AndersonClean up overlay_parse_fixup_entry() and generalize overlay_split_fragment_path() in libfdt/fdt_overlay.c so both can be reused when updating /__local_fixups__:
- Change poffset from int to uint32_t in overlay_fixup_one_phandle(), overlay_parse_fixup_entry(), and overlay_fixup_phandle(), and parse into unsigned long before validating the range.
- Require *(sep + 1) to be an ASCII digit ('0'..'9') and bound poffset to INT32_MAX - sizeof(uint32_t) so negative strings (such as "-4"), leading whitespace, or large values cannot silently truncate or wrap around in fdt_setprop_inplace_namelen_partial().
- Drop the redundant *sep != ':' checks after memchr(..., ':', ...).
- Generalize overlay_split_fragment_path() to accept a length-bounded path slice that is not necessarily NUL-terminated (using memchr() instead of strchr(), and keeping the NUL-terminated property check in overlay_symbol_update()) so it can also split :-delimited paths from /__fixups__.
---
Changes in v2:
- New patch tightening fixup offset parsing and generalizing overlay_split_fragment_path() for non-NUL-terminated paths in libfdt/fdt_overlay.c
libfdt/fdt_overlay.c | 46 +++++++++++++++++++++++--------------------- 1 file changed, 24 insertions(+), 22 deletions(-)
libfdt/fdt_overlay.c +24 -22
@@ -330,7 +330,7 @@ static int overlay_update_local_references(void *fdto, uint32_t delta)static int overlay_fixup_one_phandle (void *fdto,int symbols_off,const char *path,uint32_t path_len,const char *name,uint32_t name_len, -int poffset,uint32_t phandle) +uint32_t poffset,uint32_t phandle) {fdt32_t phandle_prop;int fixup_off;
@@ -368,7 +368,7 @@ static int overlay_fixup_one_phandle(void *fdto, int symbols_off,static int overlay_parse_fixup_entry (const char **valuep,int *lenp,const char **pathp,uint32_t *path_lenp,const char **namep,uint32_t *name_lenp, -int *poffsetp) +uint32_t *poffsetp) {const char *path, *name, *fixup_end;const char *fixup_str = *valuep;
@@ -376,7 +376,7 @@ static int overlay_parse_fixup_entry(const char **valuep, int *lenp,uint32_t fixup_len;const char *sep;char *endptr; -int poffset; +unsigned long poffset; fixup_end =memchr (*valuep,'\0' , *lenp);if (!fixup_end)
@@ -388,7 +388,7 @@ static int overlay_parse_fixup_entry(const char **valuep, int *lenp, path = fixup_str; sep =memchr (fixup_str,':' , fixup_len); -if (!sep || *sep !=':' ) +if (!sep)return -FDT_ERR_BADOVERLAY ; path_len = sep - path;
@@ -398,15 +398,17 @@ static int overlay_parse_fixup_entry(const char **valuep, int *lenp, fixup_len -= path_len +1 ; name = sep +1 ; sep =memchr (name,':' , fixup_len); -if (!sep || *sep !=':' ) +if (!sep)return -FDT_ERR_BADOVERLAY ; name_len = sep - name;if (!name_len)return -FDT_ERR_BADOVERLAY ; +if ((*(sep +1 ) <'0' ) || (*(sep +1 ) >'9' )) +return -FDT_ERR_BADOVERLAY ; poffset =strtoul (sep +1 , &endptr,10 ); -if ((*endptr !='\0' ) || (endptr <= (sep +1 ))) +if ((*endptr !='\0' ) || (poffset > (INT32_MAX -sizeof (uint32_t ))))return -FDT_ERR_BADOVERLAY ; *pathp = path;
@@ -470,8 +472,8 @@ static int overlay_fixup_phandle(void *fdt, void *fdto, int symbols_off, do { const char *path, *name; - uint32_t path_len, name_len; - int poffset, ret; + uint32_t path_len, name_len, poffset; + int ret; ret = overlay_parse_fixup_entry(&value, &len, &path, &path_len, &name, &name_len, &poffset);
@@ -925,8 +927,8 @@ static int get_path_len(const void *fdt, int nodeoffset)/** * overlay_split_fragment_path - Split "/<frag>/__overlay__[/<rel>]" into parts -* @path: Input NUL-terminated path property string -* @path_len: Length of @path in bytes (including trailing NUL) +* @path: Input path string (need not be NUL-terminated) +* @path_len: Length of @path in bytes (excluding any terminator) * @frag_namep: Output pointer to the fragment name * @frag_name_lenp: Output length of @frag_namep in bytes * @rel_pathp: Output pointer to the relative subnode path after __overlay__
@@ -935,7 +937,7 @@ static int get_path_len(const void *fdt, int nodeoffset)* * returns: * 0 on success -* -FDT_ERR_BADVALUE if @path is not a valid NUL-terminated '/' path +* -FDT_ERR_BADVALUE if @path does not start with '/' */ static int overlay_split_fragment_path(const char *path, int path_len, const char **frag_namep,
@@ -951,18 +953,14 @@ static int overlay_split_fragment_path(const char *path, int path_len, *is_overlayp = false; -/* verify it's a string property (terminated by a single \0) */ -if (path_len <1 ||memchr (path,'\0' , path_len) != &path[path_len -1 ]) -return -FDT_ERR_BADVALUE ; -/* keep end marker to avoid strlen() */ e = path + path_len; -if (*path !='/' ) +if (path_len <1 || *path !='/' )return -FDT_ERR_BADVALUE ;/* get fragment name first */ - s =strchr (path +1 ,'/' ); + s =memchr (path +1 ,'/' , path_len -1 );if (!s) {/* Symbol refers to something that won't end * up in the target tree */
@@ -972,13 +970,13 @@ static int overlay_split_fragment_path(const char *path, int path_len, frag_name = path +1 ; frag_name_len = s - path -1 ; -/* verify format; safe since "s" lies in \0 terminated prop */ +/* verify format */ len =sizeof ("/__overlay__/" ) -1 ; -if ((e - s) > len && (memcmp (s,"/__overlay__/" , len) ==0 )) { +if ((e - s) >= len && (memcmp (s,"/__overlay__/" , len) ==0 )) {/* /<fragment-name>/__overlay__/<relative-subnode-path> */ rel_path = s + len; - rel_path_len = e - rel_path -1 ; - }else if ((e - s) == len + rel_path_len = e - rel_path; + }else if ((e - s) == (len -1 ) && (memcmp (s,"/__overlay__" , len -1 ) ==0 )) {/* /<fragment-name>/__overlay__ */ rel_path ="" ;
@@ -1049,7 +1047,11 @@ static int overlay_symbol_update(void *fdt, void *fdto)if (!path)return path_len; - ret =overlay_split_fragment_path (path, path_len, +/* verify it's a string property (terminated by a single \0) */ +if (path_len <1 ||memchr (path,'\0' , path_len) != &path[path_len -1 ]) +return -FDT_ERR_BADVALUE ; + + ret =overlay_split_fragment_path (path, path_len -1 , &frag_name, &frag_name_len, &rel_path, &rel_path_len, &is_overlay);
Signature · 1 line
2.56.0.313.g2479322e68-goog
PATCH v2 6/10 libfdt: overlay: Update base /__local_fixups__ on apply
In reply to Douglas AndersonWhen a base device tree is compiled with dtc -L (--local-fixups), it contains a root /__local_fixups__ node recording the byte offsets of all phandle references in its properties.
Previously, fdt_overlay_apply() updated the base tree's /__symbols__ via overlay_symbol_update(), but left the base tree's /__local_fixups__ untouched. As a result, applying an overlay to a base tree with /__local_fixups__ left /__local_fixups__ missing the phandle references introduced by the overlay (both from the overlay's /__local_fixups__ and from its resolved /__fixups__), and left stale offsets if the overlay overwrote a base property that previously had phandle references.
Add overlay_local_fixups_update() to update the base tree's /__local_fixups__ whenever /__local_fixups__ is present in the base tree:
- Remove pre-existing /__local_fixups__ properties for any base properties overwritten by overlay fragments.
- Merge the overlay's /__local_fixups__ and /__fixups__ offsets into the base tree's /__local_fixups__ in sorted ascending order.
- Prune any subnodes under /__local_fixups__ that become empty after overwriting properties.
When the base tree does not have a /__local_fixups__ node, overlay_local_fixups_update() is a no-op.
---
Changes in v2:
- New patch updating base /__local_fixups__ in libfdt fdt_overlay_apply() instead of stripping /__local_fixups__ by default (David Gibson)
libfdt/fdt_overlay.c | 621 ++++++++++++++++++++++++++++++++++++++++++- tests/run_tests.sh | 19 ++ 2 files changed, 636 insertions(+), 4 deletions(-)
libfdt/fdt_overlay.c +617 -4
@@ -804,7 +804,7 @@ static int overlay_prevent_phandle_overwrite(void *fdt, void *fdto)* Negative error code on failure */ static int overlay_apply_node (void *fdt,int target, -void *fdto,int node) +const void *fdto,int node) {int property;int subnode;
@@ -1003,9 +1003,8 @@ static int overlay_split_fragment_path(const char *path, int path_len,* overlay_symbol_update() updates the symbols of the base tree with the * symbols of the applied overlay * -* This is the last step in the device tree overlay application -* process, allowing the reference of overlay symbols by subsequent -* overlay operations. +* This step in the device tree overlay application process allows +* the reference of overlay symbols by subsequent overlay operations. * * returns: * 0 on success
@@ -1122,6 +1121,616 @@ static int overlay_symbol_update(void *fdt, void *fdto)return 0 ; } +/** +* overlay_create_path - Create a relative path under a parent node +* @fdt: Base Device Tree blob +* @parent: Node offset of the starting parent node +* @path: Relative or slash-prefixed path to traverse +* @path_len: Length of @path in bytes +* +* overlay_create_path() walks the slash-separated path components in @path +* starting at @parent, creating any missing intermediate subnodes along the +* way. +* +* returns: +* Node offset of the resolved or created subnode on success +* Negative error code on failure +*/ +static int overlay_create_path (void *fdt,int parent,const char *path, +int path_len) +{ +const char *sep; +int node = parent; + +while (path_len >0 && *path =='/' ) { + path++; + path_len--; + } + +while (path_len >0 ) { +int comp_len; +int next; + + sep =memchr (path,'/' , path_len); + comp_len = sep ? (sep - path) : path_len; + +if (comp_len >0 ) { + next =fdt_subnode_offset_namelen (fdt, node, path, + comp_len); +if (next == -FDT_ERR_NOTFOUND ) + next =fdt_add_subnode_namelen (fdt, node, path, + comp_len); +if (next <0 ) +return next; + node = next; + } + + path += comp_len; + path_len -= comp_len; +while (path_len >0 && *path =='/' ) { + path++; + path_len--; + } + } + +return node; +} + +/** +* overlay_fragment_local_fixups - Find or create a fragment's target under /__local_fixups__ +* @fdt: Base Device Tree blob +* @fdto: Device tree overlay blob +* @fragment: Node offset of the fragment in @fdto +* @create: Whether to create missing subnodes under /__local_fixups__ +* +* overlay_fragment_local_fixups() resolves the target of @fragment in @fdt and +* locates (or creates, when @create is true) the corresponding node at the +* same path under @fdt's /__local_fixups__ subtree. +* +* returns: +* Node offset of the corresponding /__local_fixups__ node on success +* Negative error code on failure +*/ +static int overlay_fragment_local_fixups (void *fdt,const void *fdto, +int fragment,bool create) +{ +int root_lf, target, cur_fdt, node; + + root_lf =fdt_subnode_offset (fdt,0 ,"__local_fixups__" ); +if (root_lf <0 ) +return root_lf; + + target =fdt_overlay_target_offset (fdt, fdto, fragment,NULL ); +if (target <0 ) +return target; + + cur_fdt =0 ; + node = root_lf; +while (cur_fdt != target) { +int subnode, ancestor = -FDT_ERR_INTERNAL ; +const char *name; +int namelen, next_lf; + +fdt_for_each_subnode (subnode, fdt, cur_fdt) { +if (subnode <= target) + ancestor = subnode; +else +break ; + } +if (ancestor <0 ) +return ancestor; + + name =fdt_get_name (fdt, ancestor, &namelen); +if (!name) +return namelen; + + next_lf =fdt_subnode_offset_namelen (fdt, node, name, namelen); +if (next_lf == -FDT_ERR_NOTFOUND && create) { +char namebuf[256 ]; +int old_struct_size =fdt_size_dt_struct (fdt); + +if ((size_t )namelen >=sizeof (namebuf)) +return -FDT_ERR_INTERNAL ; +memcpy (namebuf, name, namelen); + next_lf =fdt_add_subnode_namelen (fdt, node, namebuf, + namelen); +if (next_lf <0 ) +return next_lf; +if (next_lf <= ancestor) { +int delta =fdt_size_dt_struct (fdt) - + old_struct_size; + target += delta; + ancestor += delta; + } + }else if (next_lf <0 ) { +return next_lf; + } + + cur_fdt = ancestor; + node = next_lf; + } + +return node; +} + +/** +* overlay_clear_overwritten_local_fixups - Remove local fixups for overwritten properties +* @fdt: Base Device Tree blob +* @target_lf: Node offset in @fdt's /__local_fixups__ subtree +* @fdto: Device tree overlay blob +* @overlay: Node offset in @fdto's __overlay__ subtree +* +* overlay_clear_overwritten_local_fixups() recursively deletes properties under +* @target_lf that correspond to properties overwritten by @overlay in @fdto. +* +* returns: +* 0 on success +* Negative error code on failure +*/ +static int overlay_clear_overwritten_local_fixups (void *fdt,int target_lf, +const void *fdto,int overlay) +{ +int prop, subnode; + +fdt_for_each_property_offset (prop, fdto, overlay) { +const char *name; +const void *val; +int len, ret; + + val =fdt_getprop_by_offset (fdto, prop, &name, &len); +if (!val) +return len; + + ret =fdt_delprop (fdt, target_lf, name); +if (ret && ret != -FDT_ERR_NOTFOUND ) +return ret; + } + +fdt_for_each_subnode (subnode, fdto, overlay) { +const char *name; +int namelen, sub_lf, ret; + + name =fdt_get_name (fdto, subnode, &namelen); +if (!name) +return namelen; + + sub_lf =fdt_subnode_offset_namelen (fdt, target_lf, name, + namelen); +if (sub_lf == -FDT_ERR_NOTFOUND ) +continue ; +if (sub_lf <0 ) +return sub_lf; + + ret =overlay_clear_overwritten_local_fixups (fdt, sub_lf, + fdto, subnode); +if (ret) +return ret; + } + +return 0 ; +} + +/** +* overlay_add_local_fixup_offset - Insert a sorted u32 offset into a local fixup property +* @fdt: Base Device Tree blob +* @lf_node: Node offset in @fdt's /__local_fixups__ subtree +* @name: Property name to update +* @name_len: Length of @name in bytes +* @poffset: Byte offset of the phandle reference within the target property +* +* overlay_add_local_fixup_offset() inserts @poffset in ascending sorted order +* (ignoring duplicates) into the u32 array property @name on @lf_node. +* +* returns: +* 0 on success +* Negative error code on failure +*/ +static int overlay_add_local_fixup_offset (void *fdt,int lf_node, +const char *name,int name_len, +uint32_t poffset) +{ +const fdt32_t *old_val; +fdt32_t *vals; +void *prop_data; +int old_len, count, i, idx, ret; + + old_val =fdt_getprop_namelen (fdt, lf_node, name, name_len, &old_len); +if (!old_val && old_len != -FDT_ERR_NOTFOUND ) +return old_len; + +if (!old_val) { + old_len =0 ; + count =0 ; + idx =0 ; + }else { +if (old_len %sizeof (uint32_t )) +return -FDT_ERR_BADSTRUCTURE ; + count = old_len /sizeof (uint32_t ); + idx = count; +for (i =0 ; i < count; i++) { +uint32_t cur =fdt32_ld (old_val + i); + +if (cur == poffset) +return 0 ; +if (cur > poffset) { + idx = i; +break ; + } + } + } + + ret =fdt_setprop_placeholder_namelen (fdt, lf_node, name, name_len, + old_len +sizeof (uint32_t ), + &prop_data); +if (ret) +return ret; + + vals = prop_data; +if (idx < count) +memmove (vals + idx +1 , vals + idx, + (count - idx) *sizeof (uint32_t )); +fdt32_st (vals + idx, poffset); + +return 0 ; +} + +/** +* overlay_merge_fixup_into_local_fixups - Record one /__fixups__ property for a fragment +* @fdt: Base Device Tree blob +* @fdto: Device tree overlay blob +* @property: Property offset in @fdto's /__fixups__ node +* @fragment: Node offset of the current fragment in @fdto +* @target_frag_name: Name of @fragment +* @target_frag_len: Length of @target_frag_name in bytes +* @target_lfp: In/out cached node offset of @fragment under @fdt's /__local_fixups__ +* +* overlay_merge_fixup_into_local_fixups() parses all "path:prop:offset" entries +* in a single /__fixups__ property of @fdto and adds the resolved property +* byte offsets belonging to @fragment into @fdt's /__local_fixups__ subtree. +* +* returns: +* 0 on success +* Negative error code on failure +*/ +static int overlay_merge_fixup_into_local_fixups (void *fdt,const void *fdto, +int property,int fragment, +const char *target_frag_name, +int target_frag_len, +int *target_lfp) +{ +const char *value, *label; +int len; + + value =fdt_getprop_by_offset (fdto, property, &label, &len); +if (!value) +return len; + +do { +const char *path, *name, *frag_name, *rel_path; +uint32_t path_len, name_len, poffset; +int frag_name_len, rel_path_len, lf_node, ret; +bool is_overlay; + + ret =overlay_parse_fixup_entry (&value, &len, &path, &path_len, + &name, &name_len, &poffset); +if (ret) +return ret; + + ret =overlay_split_fragment_path (path, path_len, + &frag_name, &frag_name_len, + &rel_path, &rel_path_len, + &is_overlay); +if (ret) +return ret; +if (!is_overlay) +continue ; + +if (frag_name_len != target_frag_len || +memcmp (frag_name, target_frag_name, frag_name_len) !=0 ) +continue ; + +if (*target_lfp <0 ) { + *target_lfp =overlay_fragment_local_fixups ( + fdt, fdto, fragment, true); +if (*target_lfp <0 ) +return *target_lfp; + } + + lf_node =overlay_create_path (fdt, *target_lfp, rel_path, + rel_path_len); +if (lf_node <0 ) +return lf_node; + + ret =overlay_add_local_fixup_offset (fdt, lf_node, name, + name_len, poffset); +if (ret) +return ret; + }while (len >0 ); + +return 0 ; +} + +/** +* overlay_merge_fixups_into_local_fixups - Record resolved /__fixups__ for a fragment +* @fdt: Base Device Tree blob +* @fdto: Device tree overlay blob +* @fragment: Node offset of the current fragment in @fdto +* @frag_name: Name of @fragment +* @frag_name_len: Length of @frag_name in bytes +* @target_lfp: In/out cached node offset of @fragment under @fdt's /__local_fixups__ +* +* overlay_merge_fixups_into_local_fixups() parses external phandle references +* belonging to @fragment in @fdto's /__fixups__ node and records their resolved +* property byte offsets in @fdt's /__local_fixups__ subtree. +* +* returns: +* 0 on success +* Negative error code on failure +*/ +static int overlay_merge_fixups_into_local_fixups (void *fdt,const void *fdto, +int fragment, +const char *frag_name, +int frag_name_len, +int *target_lfp) +{ +int fixups_off, prop; + + fixups_off =fdt_subnode_offset (fdto,0 ,"__fixups__" ); +if (fixups_off == -FDT_ERR_NOTFOUND ) +return 0 ; +if (fixups_off <0 ) +return fixups_off; + +fdt_for_each_property_offset (prop, fdto, fixups_off) { +int ret; + + ret =overlay_merge_fixup_into_local_fixups ( + fdt, fdto, prop, fragment, frag_name, frag_name_len, + target_lfp); +if (ret) +return ret; + } + +return 0 ; +} + +/** +* overlay_prune_empty_local_fixups - Remove empty subnodes from /__local_fixups__ +* @fdt: Base Device Tree blob +* @lf_node: Node offset in @fdt's /__local_fixups__ subtree +* +* overlay_prune_empty_local_fixups() recursively deletes any child subnodes +* under @lf_node that have neither properties nor subnodes remaining. +* +* returns: +* 0 on success +* Negative error code on failure +*/ +static int overlay_prune_empty_local_fixups (void *fdt,int lf_node) +{ +int subnode =fdt_first_subnode (fdt, lf_node); + +while (subnode >=0 ) { +int next, ret; + + ret =overlay_prune_empty_local_fixups (fdt, subnode); +if (ret <0 ) +return ret; + + next =fdt_next_subnode (fdt, subnode); +if (fdt_first_property_offset (fdt, subnode) == -FDT_ERR_NOTFOUND && +fdt_first_subnode (fdt, subnode) == -FDT_ERR_NOTFOUND ) { +int old_struct_size =fdt_size_dt_struct (fdt); + + ret =fdt_del_node (fdt, subnode); +if (ret <0 ) +return ret; +if (next >=0 ) + next +=fdt_size_dt_struct (fdt) - + old_struct_size; + } + subnode = next; + } + +return 0 ; +} + +/** +* overlay_validate_local_fixups - Validate /__local_fixups__ fragment nodes in overlay +* @fdto: Device tree overlay blob +* @ov_lf_root: Node offset of /__local_fixups__ in @fdto +* +* overlay_validate_local_fixups() verifies that every fragment subnode under +* @ov_lf_root that contains an __overlay__ subnode corresponds to a valid +* fragment node at the root of @fdto. +* +* returns: +* 0 on success +* Negative error code on failure +*/ +static int overlay_validate_local_fixups (const void *fdto,int ov_lf_root) +{ +int lf_frag; + +fdt_for_each_subnode (lf_frag, fdto, ov_lf_root) { +const char *frag_name; +int frag_name_len, lf_overlay, fragment; + + frag_name =fdt_get_name (fdto, lf_frag, &frag_name_len); +if (!frag_name) +return frag_name_len; + + lf_overlay =fdt_subnode_offset (fdto, lf_frag,"__overlay__" ); +if (lf_overlay == -FDT_ERR_NOTFOUND ) +continue ; +if (lf_overlay <0 ) +return lf_overlay; + + fragment =fdt_subnode_offset_namelen (fdto,0 , frag_name, + frag_name_len); +if (fragment <0 ) +return -FDT_ERR_BADOVERLAY ; + +if (fdt_subnode_offset (fdto, fragment,"__overlay__" ) <0 ) +return -FDT_ERR_BADOVERLAY ; + } + +return 0 ; +} + +/** +* overlay_fragment_local_fixups_src - Find a fragment's __overlay__ in overlay /__local_fixups__ +* @fdto: Device tree overlay blob +* @ov_lf_root: Node offset of /__local_fixups__ in @fdto (or -FDT_ERR_NOTFOUND) +* @frag_name: Name of the fragment node +* @frag_name_len: Length of @frag_name in bytes +* +* overlay_fragment_local_fixups_src() locates the __overlay__ subnode for +* @frag_name under @ov_lf_root in @fdto. +* +* returns: +* Node offset of /__local_fixups__/<frag_name>/__overlay__ on success +* -FDT_ERR_NOTFOUND if @ov_lf_root, <frag_name>, or __overlay__ is absent +* Negative error code on other failures +*/ +static int overlay_fragment_local_fixups_src (const void *fdto,int ov_lf_root, +const char *frag_name, +int frag_name_len) +{ +int lf_frag; + +if (ov_lf_root <0 ) +return -FDT_ERR_NOTFOUND ; + + lf_frag =fdt_subnode_offset_namelen (fdto, ov_lf_root, frag_name, + frag_name_len); +if (lf_frag <0 ) +return lf_frag; + +return fdt_subnode_offset (fdto, lf_frag,"__overlay__" ); +} + +/** +* overlay_fragment_update_local_fixups - Update base /__local_fixups__ for one fragment +* @fdt: Base Device Tree blob +* @fdto: Device tree overlay blob +* @fragment: Node offset of the fragment in @fdto +* @ov_lf_root: Node offset of /__local_fixups__ in @fdto (or -FDT_ERR_NOTFOUND) +* +* overlay_fragment_update_local_fixups() clears any base /__local_fixups__ +* entries overwritten by @fragment, then merges phandle offsets for @fragment +* from @fdto's /__local_fixups__ and /__fixups__ subtrees. +* +* returns: +* 0 on success +* Negative error code on failure +*/ +static int overlay_fragment_update_local_fixups (void *fdt,const void *fdto, +int fragment,int ov_lf_root) +{ +const char *frag_name; +int frag_name_len, overlay, target_lf, lf_overlay, ret; + + overlay =fdt_subnode_offset (fdto, fragment,"__overlay__" ); +if (overlay == -FDT_ERR_NOTFOUND ) +return 0 ; +if (overlay <0 ) +return overlay; + + frag_name =fdt_get_name (fdto, fragment, &frag_name_len); +if (!frag_name) +return frag_name_len; + + target_lf =overlay_fragment_local_fixups (fdt, fdto, fragment, false); +if (target_lf <0 && target_lf != -FDT_ERR_NOTFOUND ) +return target_lf; + +if (target_lf >=0 ) { + ret =overlay_clear_overwritten_local_fixups (fdt, target_lf, + fdto, overlay); +if (ret) +return ret; + } + + lf_overlay =overlay_fragment_local_fixups_src (fdto, ov_lf_root, + frag_name, + frag_name_len); +if (lf_overlay <0 && lf_overlay != -FDT_ERR_NOTFOUND ) +return lf_overlay; + +if (lf_overlay >=0 ) { +if (target_lf <0 ) + target_lf =overlay_fragment_local_fixups (fdt, fdto, + fragment, + true); +if (target_lf <0 ) +return target_lf; + + ret =overlay_apply_node (fdt, target_lf, fdto, lf_overlay); +if (ret) +return ret; + } + +return overlay_merge_fixups_into_local_fixups ( + fdt, fdto, fragment, frag_name, frag_name_len, &target_lf); +} + +/** +* overlay_local_fixups_update - Update base /__local_fixups__ with overlay fixups +* @fdt: Base Device Tree blob +* @fdto: Device tree overlay blob +* +* overlay_local_fixups_update() updates the base device tree's +* /__local_fixups__ subtree (when present) by walking each overlay fragment in +* application order, clearing entries for properties overwritten by that +* fragment, and merging phandle reference offsets from @fdto's +* /__local_fixups__ and /__fixups__ subtrees. +* +* This is part of the device tree overlay application process, when you want +* the merged device tree to retain complete local phandle fixup metadata. +* +* returns: +* 0 on success +* Negative error code on failure +*/ +static int overlay_local_fixups_update (void *fdt,const void *fdto) +{ +int root_lf, ov_lf_root, fragment, ret; + + root_lf =fdt_subnode_offset (fdt,0 ,"__local_fixups__" ); +if (root_lf == -FDT_ERR_NOTFOUND ) +return 0 ; +if (root_lf <0 ) +return root_lf; + + ov_lf_root =fdt_subnode_offset (fdto,0 ,"__local_fixups__" ); +if (ov_lf_root >=0 ) { + ret =overlay_validate_local_fixups (fdto, ov_lf_root); +if (ret) +return ret; + }else if (ov_lf_root != -FDT_ERR_NOTFOUND ) { +return ov_lf_root; + } + +/* +* Process fragments in application order so that if a later fragment in +* fdto overwrites a property modified by an earlier fragment, the +* earlier fragment's local fixups for that property are cleared first. +*/ +fdt_for_each_subnode (fragment, fdto,0 ) { + ret =overlay_fragment_update_local_fixups (fdt, fdto, fragment, + ov_lf_root); +if (ret) +return ret; + } + + root_lf =fdt_subnode_offset (fdt,0 ,"__local_fixups__" ); +if (root_lf <0 ) +return root_lf; + +return overlay_prune_empty_local_fixups (fdt, root_lf); +} +int fdt_overlay_apply (void *fdt,void *fdto) {uint32_t delta;
@@ -1162,6 +1771,10 @@ int fdt_overlay_apply(void *fdt, void *fdto)if (ret) goto err; + ret =overlay_local_fixups_update (fdt, fdto); +if (ret) + goto err; +/* * The overlay has been damaged, erase its magic. */
tests/run_tests.sh +19 -0
@@ -1089,6 +1089,25 @@ fdtoverlay_tests() { shorten_echo "check phandle to noda d wasn't overwritten: " run_wrap_test test "$bd" = "$pd" + + # verify that /__local_fixups__ in a -L base blob is updated when applying an overlay + run_dtc_test -@ -L -I dts -O dtb -o overlay_base_phandle_lf.test.dtb "$SRCDIR/overlay_base_phandle.dts" + run_wrap_test $FDTOVERLAY -i overlay_base_phandle_lf.test.dtb -o overlay_base_phandle_lfO.test.dtb overlay_overlay_phandle.test.dtb + run_fdtget_test 0 overlay_base_phandle_lfO.test.dtb /__local_fixups__/b a + run_fdtget_test 0 overlay_base_phandle_lfO.test.dtb /__local_fixups__/b d + run_fdtget_test 0 overlay_base_phandle_lfO.test.dtb /__local_fixups__/c b + run_fdtget_test 0 overlay_base_phandle_lfO.test.dtb /__local_fixups__/d a + run_fdtget_test 0 overlay_base_phandle_lfO.test.dtb /__local_fixups__/d b + run_fdtget_test 0 overlay_base_phandle_lfO.test.dtb /__local_fixups__/d c + + run_dtc_test -@ -L -I dts -O dtb -o overlay_base_lf.test.dtb "$SRCDIR/overlay_base.dts" + run_wrap_test $DTPUT overlay_base_lf.test.dtb -cp /__local_fixups__/test-node/sub-test-node + run_wrap_test $DTPUT overlay_base_lf.test.dtb /__local_fixups__/test-node/sub-test-node new-sub-test-property -tu 0 + run_dtc_test -@ -I dts -O dtb -o overlay_overlay.fdtoverlay.test.dtb "$SRCDIR/overlay_overlay.dts" + run_wrap_test $FDTOVERLAY -i overlay_base_lf.test.dtb -o overlay_base_lfO.test.dtb overlay_overlay.fdtoverlay.test.dtb + run_fdtget_test "0 4" overlay_base_lfO.test.dtb /__local_fixups__/test-node test-phandle + run_fdtget_test "0 4" overlay_base_lfO.test.dtb /__local_fixups__/test-node test-several-phandle + run_test check_path overlay_base_lfO.test.dtb not-exists "/__local_fixups__/test-node/sub-test-node" } pylibfdt_tests () {
Signature · 1 line
2.56.0.313.g2479322e68-goog
PATCH v2 7/10 fdtfactor: Add tool to split DTBs into a base DTB and overlays
In reply to Douglas AndersonWhen shipping a single firmware or kernel image that supports many closely related board variants or SKUs, bundling a full compiled .dtb for every variant results in substantial duplication.
Add fdtfactor, a Python tool built on pylibfdt that takes a set of compiled device tree blobs (.dtb) compiled with -@ -L (/__symbols__ and /__local_fixups__) and splits them into a single common base.dtb and per-board .dtbo overlays:
- Common nodes present across all input DTBs are placed in base.dtb, with each common property assigned the value shared by at least two boards that maximizes byte savings across overlays.
- Using /__local_fixups__, phandle references inside property values are normalized to target node paths so common properties referencing common nodes match even when numeric phandles differ across input DTBs.
- Any common node that carries a phandle in any input DTB receives its phandle in base.dtb so overlays only emit phandle properties on newly added subnodes, matching the requirements of libfdt, Linux's drivers/of/overlay.c, and coreboot's dt_apply_overlay().
Add a fdtfactor test suite in tests/run_tests.sh verifying that applying each generated .dtbo to base.dtb with fdtoverlay reconstructs the original DTB (verified via dtbs_equal_unordered, including across input DTBs with shifted phandle numbers).
---
Changes in v2:
- Preserve /__local_fixups__ on base.dtb by default (David Gibson)
- Store parsed trees directly in NodeTree with node.phandle and node.fixups attributes instead of parallel dicts (David Gibson)
- Extract phandles in a separate pass after unflattening and reject legacy linux,phandle properties (David Gibson)
- Exclude non-root common phandle nodes lacking a common symbol from base.dtb instead of synthesizing __fdtfactor_ph_* symbols (David Gibson)
- Drop -q/--quiet, rename -v/--verbose to -s/--stats, and move tests to a dedicated fdtfactor test suite (David Gibson)
Makefile | 2 +- README.md | 43 ++ fdtfactor | 814 +++++++++++++++++++++++++++++ meson.build | 1 + tests/Makefile.tests | 4 +- tests/fdtfactor_board1.dts | 38 ++ tests/fdtfactor_board2.dts | 36 ++ tests/fdtfactor_board3.dts | 34 ++ tests/fdtfactor_board3_shifted.dts | 34 ++ tests/meson.build | 2 +- tests/run_tests.sh | 65 ++- tests/testutils.sh | 1 + 12 files changed, 1067 insertions(+), 7 deletions(-) create mode 100755 fdtfactor create mode 100644 tests/fdtfactor_board1.dts create mode 100644 tests/fdtfactor_board2.dts create mode 100644 tests/fdtfactor_board3.dts create mode 100644 tests/fdtfactor_board3_shifted.dts
Makefile +1 -1
@@ -165,7 +165,7 @@ BIN += fdtget BIN += fdtput BIN += fdtoverlay -SCRIPTS = dtdiff +SCRIPTS = dtdiff fdtfactor all: $(BIN) libfdt
README.md +43 -0
49 lines not on this page · raw message
fdtfactor new file +814 -0
814 lines not on this page · raw message
meson.build +1 -0
@@ -114,6 +114,7 @@ if get_option('tools') and not wheel_only install_data( 'dtdiff', + 'fdtfactor', install_dir: get_option('bindir'), install_mode: 'rwxr-xr-x', )
tests/Makefile.tests +2 -2
@@ -53,10 +53,10 @@ TESTS_DEPFILES = $(TESTS:%=%.d) \ $(addprefix $(TESTS_PREFIX),testutils.d) TESTS_CLEANFILES_L = $(STD_CLEANFILES) \ - *.dtb *.test.dts *.test.dt.yaml *.dtsv1 tmp.* *.bak \ + *.dtb *.test.dtbo *.test.dts *.test.dt.yaml *.dtsv1 tmp.* *.bak \ treegen TESTS_CLEANFILES = $(TESTS) $(TESTS_CLEANFILES_L:%=$(TESTS_PREFIX)%) -TESTS_CLEANDIRS_L = fs +TESTS_CLEANDIRS_L = fs *.test.dir TESTS_CLEANDIRS = $(TESTS_CLEANDIRS_L:%=$(TESTS_PREFIX)%) .PHONY: tests
tests/fdtfactor_board1.dts new file +38 -0
@@ -0,0 +1,38 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/dts-v1/; + +/memreserve/ 0xdeadbeef00000000 0x100000; + +/ { + compatible = "test_fdtfactor"; + model = "board1"; + prop-int = <0xdeadbeef>; + #address-cells = <1>; + #size-cells = <0>; + + sn1: subnode@1 { + compatible = "subnode1"; + reg = <1>; + prop-ref = <&sn1 0x10 &ssn1 0x20>; + + ssn1: subsubnode { + compatible = "subsubnode1", "subsubnode"; + prop-phandle = <&sn1>; + }; + }; + + sn2: subnode@2 { + reg = <2>; + prop-maybe-phandle = <&sn2>; + }; + + b1_node: board1-node { + prop-str = "board1"; + ref-base = <&sn1>; + ref-local = <&b1_node &b1_child>; + + b1_child: child { + reg = <1>; + }; + }; +};
tests/fdtfactor_board2.dts new file +36 -0
@@ -0,0 +1,36 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/dts-v1/; + +/memreserve/ 0xdeadbeef00000000 0x100000; + +/ { + compatible = "test_fdtfactor"; + model = "board2"; + prop-int = <0xdeadbeef>; + #address-cells = <1>; + #size-cells = <0>; + + sn1: subnode@1 { + compatible = "subnode1"; + reg = <1>; + prop-ref = <&sn1 0x10 &ssn1 0x20>; + + ssn1: subsubnode { + compatible = "subsubnode1", "subsubnode"; + prop-phandle = <&sn1>; + }; + }; + + sn2: subnode@2 { + reg = <2>; + prop-maybe-phandle = <&sn2>; + board2-only-prop = "only-on-board2"; + board2-ref = <&b2_node>; + }; + + b2_node: board2-node { + prop-str = "board2"; + ref-base = <&ssn1>; + ref-self = <&b2_node>; + }; +};
tests/fdtfactor_board3.dts new file +34 -0
@@ -0,0 +1,34 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/dts-v1/; + +/memreserve/ 0xdeadbeef00000000 0x100000; + +/ { + compatible = "test_fdtfactor"; + model = "board3"; + prop-int = <0x12345678>; + #address-cells = <1>; + #size-cells = <0>; + + sn1: subnode@1 { + compatible = "subnode1"; + reg = <1>; + prop-ref = <&sn1 0x10 &ssn1 0x20>; + + ssn1: subsubnode { + compatible = "subsubnode1", "subsubnode"; + prop-phandle = <&sn2>; + }; + }; + + sn2: subnode@2 { + reg = <2>; + prop-maybe-phandle = <0>; + }; + + b3_node: board3-node { + prop-str = "board3"; + ref-base = <&sn2>; + ref-self = <&b3_node>; + }; +};
tests/fdtfactor_board3_shifted.dts new file +34 -0
@@ -0,0 +1,34 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/dts-v1/; + +/memreserve/ 0xdeadbeef00000000 0x100000; + +/ { + compatible = "test_fdtfactor"; + model = "board3"; + prop-int = <0x12345678>; + #address-cells = <1>; + #size-cells = <0>; + + b3_node: board3-node { + prop-str = "board3"; + ref-self = <&b3_node>; + ref-base = <&sn2>; + }; + + sn1: subnode@1 { + compatible = "subnode1"; + reg = <1>; + prop-ref = <&sn1 0x10 &ssn1 0x20>; + + ssn1: subsubnode { + compatible = "subsubnode1", "subsubnode"; + prop-phandle = <&sn2>; + }; + }; + + sn2: subnode@2 { + reg = <2>; + prop-maybe-phandle = <0>; + }; +};
tests/meson.build +1 -1
@@ -143,7 +143,7 @@ run_test_deps = [ dtc_tools, treegen_dtb, tests_exe, ] if pylibfdt_enabled - run_test_types += 'pylibfdt' + run_test_types += ['pylibfdt', 'fdtfactor'] run_test_deps += pylibfdt endif foreach test_type : run_test_types
tests/run_tests.sh +62 -3
88 lines not on this page · raw message
tests/testutils.sh +1 -0
@@ -27,6 +27,7 @@ DTGET=${TEST_BINDIR}/fdtget DTPUT=${TEST_BINDIR}/fdtput FDTDUMP=${TEST_BINDIR}/fdtdump FDTOVERLAY=${TEST_BINDIR}/fdtoverlay +FDTFACTOR=${SRCDIR}/../fdtfactor verbose_run () { if [ -z "$QUIET_TEST" ]; then
Signature · 1 line
2.56.0.313.g2479322e68-goog
PATCH v2 8/10 fdtfactor: Add -S/--strip-local-fixups option
In reply to Douglas AndersonBy default, fdtfactor preserves /__local_fixups__ on base.dtb so that when fdt_overlay_apply() merges a .dtbo overlay, the reconstructed device tree retains full /__local_fixups__ information (for instance, if an OS kernel wants to know which property cells contain phandles at runtime).
When -L was passed to dtc solely to help fdtfactor locate phandle cells at build time and /__local_fixups__ is not needed at runtime, retaining /__local_fixups__ in base.dtb wastes space.
Add -S / --strip-local-fixups to omit /__local_fixups__ from base.dtb (and therefore from the merged device trees produced by fdt_overlay_apply()). On a set of 47 Qualcomm SC7180 Trogdor Chromebook board DTBs, fdtfactor -S reduces total uncompressed size from 7.69 MB to 634 KB (91.8% savings).
Add a test case in tests/run_tests.sh verifying that fdtfactor -S followed by fdtoverlay reproduces DTBs compiled with -@ (without -L) via dtbs_equal_unordered.
---
Changes in v2:
- Split -S/--strip-local-fixups into a separate opt-in patch (David Gibson)
README.md | 9 +++++++++ fdtfactor | 34 ++++++++++++++++++++++++++-------- tests/run_tests.sh | 22 ++++++++++++++++++++++ 3 files changed, 57 insertions(+), 8 deletions(-)
README.md +9 -0
@@ -118,6 +118,15 @@ Options: * `-o`, `--outdir`: Output directory for generated `.dtbo` files and `--base-dtb` (default: alongside each input `.dtb` for `.dtbo` files, current directory for `--base-dtb`). +* `-S`, `--strip-local-fixups`: Omit `/__local_fixups__` from the generated + `base.dtb` and final reconstructed device trees. By default, `fdtfactor` + preserves `/__local_fixups__` on `base.dtb` so that when `fdt_overlay_apply()` + merges a `.dtbo` overlay, the reconstructed device tree retains full + `/__local_fixups__` information (e.g., for an OS kernel that wants to + know which property cells contain phandles at runtime). When `-L` was + passed to `dtc` solely to help `fdtfactor` locate phandles at build time + and `/__local_fixups__` is not needed at runtime, passing `-S` strips it + from `base.dtb` to save space. * `-s`, `--stats`: Print size savings summary. ### TODO
fdtfactor +26 -8
@@ -424,7 +424,8 @@ def _build_base_tree(dtbs): return base_root -def _serialize_base_dtb(base_root, base_dtb_symbols, rsvmap, boot_cpuid_phys): +def _serialize_base_dtb(base_root, base_dtb_symbols, rsvmap, boot_cpuid_phys, + strip_local_fixups=False): """Materialize phandles, `/__symbols__`, and `/__local_fixups__` and flatten. Args:
@@ -433,6 +434,8 @@ def _serialize_base_dtb(base_root, base_dtb_symbols, rsvmap, boot_cpuid_phys): base_dtb_symbols: Dict mapping common symbol labels to target paths. rsvmap: Sequence of `(address, size)` memory reservation tuples. boot_cpuid_phys: Physical boot CPU ID for the FDT header. + strip_local_fixups: If True, omit `/__local_fixups__` from the + generated `base.dtb`. Returns: Serialized `.dtb` `bytes` for the common base DTB.
@@ -462,11 +465,12 @@ def _serialize_base_dtb(base_root, base_dtb_symbols, rsvmap, boot_cpuid_phys): for label, target_path in base_dtb_symbols.items(): sym_node.set_str(label, target_path or '/') - # Always create `/__local_fixups__` on the base DTB so `fdt_overlay_apply()` - # updates it with the overlay's phandle fixups when merging. - lf_root = out_root.create_path('/__local_fixups__') - for path, prop_name, offs in lf_entries: - lf_root.create_path(path).set_u32_list(prop_name, offs) + if not strip_local_fixups: + # Create `/__local_fixups__` on the base DTB so `fdt_overlay_apply()` + # updates it with the overlay's phandle fixups when merging. + lf_root = out_root.create_path('/__local_fixups__') + for path, prop_name, offs in lf_entries: + lf_root.create_path(path).set_u32_list(prop_name, offs) return out_root.flatten(mem_rsv=rsvmap, boot_cpuid_phys=boot_cpuid_phys)
@@ -610,11 +614,13 @@ def _build_board_dtbo(dtb, base_root, base_dtb_symbols, return dtbo_root.flatten() -def create_base_dtb_and_overlays(dtbs): +def create_base_dtb_and_overlays(dtbs, strip_local_fixups=False): """Compute the base DTB and per-board DTBO blobs from parsed DTBs. Args: dtbs: Sequence of `ParsedDtb` instances (at least two). + strip_local_fixups: If True, omit `/__local_fixups__` from the + generated `base.dtb`. Returns: Tuple of `(base_dtb_blob, dtbo_blobs)` where `base_dtb_blob` is the
@@ -629,6 +635,7 @@ def create_base_dtb_and_overlays(dtbs): base_dtb_blob = _serialize_base_dtb( base_root, base_dtb_symbols, dtbs[0].mem_rsv, dtbs[0].boot_cpuid_phys, + strip_local_fixups=strip_local_fixups, ) dtbo_blobs = [ _build_board_dtbo(
@@ -691,6 +698,14 @@ def parse_args(argv=None): 'for --base-dtb)' ), ) + parser.add_argument( + '-S', '--strip-local-fixups', + action='store_true', + help=( + 'Omit /__local_fixups__ from the generated base .dtb and ' + 'reconstructed device trees' + ), + ) parser.add_argument( '-s', '--stats', action='store_true',
@@ -775,7 +790,10 @@ def factor_dtb_files(args): seen_paths.add(abs_out) dtbo_paths.append(out_path) - base_dtb_blob, dtbo_blobs = create_base_dtb_and_overlays(dtbs) + base_dtb_blob, dtbo_blobs = create_base_dtb_and_overlays( + dtbs, + strip_local_fixups=args.strip_local_fixups, + ) if args.outdir: os.makedirs(args.outdir, exist_ok=True)
tests/run_tests.sh +22 -0
@@ -1184,6 +1184,28 @@ fdtfactor_tests () { run_wrap_error_test $PYTHON $FDTFACTOR -o fdtfactor_legacy.test.dir \ fdtfactor_out.test.dir/fdtfactor_board1.test.dtbo \ fdtfactor_board2.test.dtb + + # Strip local fixups (-S): verify that merged DTBs match DTBs compiled + # with -@ (without -L), and that inputs lacking /__local_fixups__ are + # rejected. + for i in 1 2 3; do + run_dtc_test -b 2 -@ -I dts -O dtb -o fdtfactor_board${i}.nolf.test.dtb \ + "$SRCDIR/fdtfactor_board${i}.dts" + done + run_wrap_error_test $PYTHON $FDTFACTOR -o fdtfactor_strip.test.dir \ + fdtfactor_board1.nolf.test.dtb fdtfactor_board2.test.dtb + rm -rf fdtfactor_strip.test.dir + run_wrap_test $PYTHON $FDTFACTOR -S -b base_strip.test.dtb \ + -o fdtfactor_strip.test.dir \ + fdtfactor_board1.test.dtb fdtfactor_board2.test.dtb \ + fdtfactor_board3.test.dtb + for i in 1 2 3; do + run_wrap_test $FDTOVERLAY -i fdtfactor_strip.test.dir/base_strip.test.dtb \ + -o fdtfactor_strip.test.dir/merged${i}.test.dtb \ + fdtfactor_strip.test.dir/fdtfactor_board${i}.test.dtbo + run_test dtbs_equal_unordered fdtfactor_board${i}.nolf.test.dtb \ + fdtfactor_strip.test.dir/merged${i}.test.dtb + done } while getopts "vt:me" ARG ; do
Signature · 1 line
2.56.0.313.g2479322e68-goog
PATCH v2 9/10 fdtfactor: Support compressed DTB inputs and outputs
In reply to Douglas AndersonFirmware and FIT image build pipelines frequently store device tree blobs compressed with LZ4, LZMA/XZ, or gzip (e.g., .dtb.lz4).
Extend fdtfactor to detect compressed input blobs by magic bytes or file extension, transparently decompress them before factoring, and compress the resulting .dtbo and base.dtb outputs when appropriate:
- Support .lz4 (including legacy -l frames via the lz4 CLI), .lzma/.xz (via Python's lzma module, using CHECK_CRC32 for XZ compatibility with kernel/bootloader decompressors), and .gz (via Python's gzip module).
- Preserve the input compression format on generated .dtbo files and compress base.dtb according to --base-compression (which defaults to auto, auto-detecting from --base-dtb's filename extension such as -b base.dtb.lz4).
- Report compressed size savings alongside uncompressed savings when -s/--stats is specified.
On the 47 Qualcomm SC7180 Trogdor Chromebook .dtb.lz4 files, fdtfactor -S reduces total LZ4-compressed size from 1.71 MB to 213 KB (87.5% savings).
---
Changes in v2:
- Add --base-compression to explicitly control base.dtb compression while documenting auto-detection from --base-dtb's filename suffix (David Gibson)
- Support legacy LZ4 frames (lz4 -l) and use CRC32 check for XZ outputs (Simon Glass)
README.md | 17 ++- fdtfactor | 312 +++++++++++++++++++++++++++++++++++++++---- tests/Makefile.tests | 5 +- tests/run_tests.sh | 77 ++++++++++- 4 files changed, 379 insertions(+), 32 deletions(-)
README.md +11 -6
@@ -94,10 +94,10 @@ values. ## fdtfactor `fdtfactor` is a Python tool built on `pylibfdt` that takes a set of -compiled device tree blobs (`.dtb`) and splits them into a single common -`base.dtb` and per-board `.dtbo` overlays so that applying a board's -`.dtbo` to `base.dtb` recreates the original board device tree while -reducing total storage size. +compiled device tree blobs (`.dtb`, or compressed `.dtb.lz4`, `.dtb.xz`, +`.dtb.lzma`, `.dtb.gz`) and splits them into a single common `base.dtb` and +per-board `.dtbo` overlays so that applying a board's `.dtbo` to `base.dtb` +recreates the original board device tree while reducing total storage size. Input `.dtb` files must be compiled with `dtc -@ -L` so that both `/__symbols__` (used to resolve overlay `/__fixups__` against `base.dtb`)
@@ -114,7 +114,12 @@ Options: * `-b`, `--base-dtb`: Output filename for the common base `.dtb` (default: `base.dtb`; placed in `--outdir` if specified, or the current - directory otherwise). + directory otherwise). By default (`--base-compression=auto`), `base.dtb` + is compressed if its filename carries a `.lz4`, `.xz`, `.lzma`, or `.gz` + suffix, whereas each `.dtbo` preserves its input `.dtb`'s compression. +* `--base-compression`: Compression format for `--base-dtb`: `auto`, + `none`, `lz4`, `lz4_legacy`, `lzma`, `xz`, or `gzip` (default: `auto`, + which auto-detects from the `--base-dtb` filename suffix). * `-o`, `--outdir`: Output directory for generated `.dtbo` files and `--base-dtb` (default: alongside each input `.dtb` for `.dtbo` files, current directory for `--base-dtb`).
@@ -127,7 +132,7 @@ Options: passed to `dtc` solely to help `fdtfactor` locate phandles at build time and `/__local_fixups__` is not needed at runtime, passing `-S` strips it from `base.dtb` to save space. -* `-s`, `--stats`: Print size savings summary. +* `-s`, `--stats`: Print uncompressed and compressed size savings. ### TODO
fdtfactor +288 -24
418 lines not on this page · raw message
tests/Makefile.tests +4 -1
@@ -53,7 +53,10 @@ TESTS_DEPFILES = $(TESTS:%=%.d) \ $(addprefix $(TESTS_PREFIX),testutils.d) TESTS_CLEANFILES_L = $(STD_CLEANFILES) \ - *.dtb *.test.dtbo *.test.dts *.test.dt.yaml *.dtsv1 tmp.* *.bak \ + *.dtb *.test.dtbo *.test.dts *.test.dt.yaml *.dtsv1 \ + *.test.dtb.gz *.test.dtbo.gz *.test.dtb.xz *.test.dtbo.xz \ + *.test.dtb.lzma *.test.dtbo.lzma *.test.dtb.lz4 *.test.dtbo.lz4 \ + tmp.* *.bak \ treegen TESTS_CLEANFILES = $(TESTS) $(TESTS_CLEANFILES_L:%=$(TESTS_PREFIX)%) TESTS_CLEANDIRS_L = fs *.test.dir
tests/run_tests.sh +76 -1
89 lines not on this page · raw message
Signature · 1 line
2.56.0.313.g2479322e68-goog
PATCH v2 10/10 fdtfactor: Add compiled FIT image factoring support
In reply to Douglas AndersonBootloaders such as depthcharge on Chromebooks and U-Boot use Flattened Image Tree (FIT) images to bundle a kernel image with multiple board FDT blobs (fdt-1, fdt-2, ...) and per-board configuration nodes.
Add -F/--fit, --outfile, and --single-base-dtb options to fdtfactor to factor a compiled FIT image directly:
- Parse non-overlay type = "flat_dt" nodes under /images, decompressing their data blobs according to their compression property (none, lz4, lzma, xz, gzip).
- Reject FIT images containing signature* subnodes under /images/* or /configurations/*, as modifying FDT blobs and configurations would invalidate cryptographic signatures.
- Partition the flat_dt blobs into compatible factor groups (by compression, architecture, FDT header fields, and node-path overlap) so a single FIT image containing multiple board/SoC families produces a separate fdt-base-1, fdt-base-2, etc. for each family.
- Support --single-base-dtb to force all flat_dt blobs into a single base DTB regardless of node-path overlap, failing only if their FDT headers, architecture, or compression differ.
- Insert each fdt-base-N node into /images, replace each factored fdt-* node's data with its compressed .dtbo overlay, recompute any hash* subnode digests, and prepend fdt-base-N to each matching configuration's fdt string list while preserving all other configuration properties (description, compatible, etc., populating compatible from the board DTB's root node when omitted) and any pre-existing overlay entries.
Add uncompressed, LZ4-compressed multi-family, signed-FIT rejection, and --single-base-dtb FIT image test cases to the fdtfactor test suite.
---
Changes in v2:
- Rename -f/--fit and -F/--fit-out to -F/--fit and --outfile and clarify FIT mode in the --help description (David Gibson, Simon Glass)
- Reject signed FIT images with signature* subnodes (Simon Glass)
- Use '<base-node-name>.dtb' for FIT base FDT descriptions instead of common-prefix heuristics (Simon Glass)
- Compare FIT group node overlap against the group's common node set instead of only the first entry (Simon Glass)
- Document in README.md that U-Boot's boot_get_fdt_fit() currently requires FIT overlays to be uncompressed (Simon Glass)
README.md | 17 ++ fdtfactor | 588 +++++++++++++++++++++++++++++++++++-- tests/Makefile.tests | 2 +- tests/fdtfactor_lz4.its | 109 +++++++ tests/fdtfactor_other1.dts | 33 +++ tests/fdtfactor_other2.dts | 33 +++ tests/fdtfactor_test.its | 109 +++++++ tests/run_tests.sh | 158 +++++++++- 8 files changed, 1018 insertions(+), 31 deletions(-) create mode 100644 tests/fdtfactor_lz4.its create mode 100644 tests/fdtfactor_other1.dts create mode 100644 tests/fdtfactor_other2.dts create mode 100644 tests/fdtfactor_test.its
README.md +17 -0
@@ -108,6 +108,7 @@ Basic usage: ``` $ fdtfactor -o out_dir board1.dtb board2.dtb board3.dtb +$ fdtfactor -F image.fit --outfile image.factored.fit ``` Options:
@@ -123,6 +124,22 @@ Options: * `-o`, `--outdir`: Output directory for generated `.dtbo` files and `--base-dtb` (default: alongside each input `.dtb` for `.dtbo` files, current directory for `--base-dtb`). +* `-F`, `--fit`: Factor `/images/fdt-*` blobs inside a compiled FIT image + (creating `/images/fdt-base-1`, `/images/fdt-base-2`, ... per compatible + board/SoC family grouped by FDT headers and `>= 50%` node-path overlap, + converting each `/images/fdt-N` node into a `.dtbo` overlay, updating + `/configurations/conf-*` `fdt` and `compatible` properties, and + recalculating `/images/*/hash-*` digests). Each factored base DTB and + `.dtbo` overlay preserves the `compression` setting of its `/images/fdt-*` + node (note: while bootloaders such as depthcharge decompress compressed + FIT overlays, U-Boot's `boot_get_fdt_fit()` currently only decompresses + the base DTB and requires FIT overlays to be uncompressed). Signed FIT + images with `signature*` subnodes are rejected because modifying FDT blobs + and configurations would invalidate cryptographic signatures. +* `--outfile`: Output FIT image path when `--fit` is used (default: + overwrite `--fit` in place). +* `--single-base-dtb`: Force a single `/images/fdt-base-1` across all FDTs + in `--fit` mode rather than grouping by node-path overlap. * `-S`, `--strip-local-fixups`: Omit `/__local_fixups__` from the generated `base.dtb` and final reconstructed device trees. By default, `fdtfactor` preserves `/__local_fixups__` on `base.dtb` so that when `fdt_overlay_apply()`
fdtfactor +559 -29
708 lines not on this page · raw message
tests/Makefile.tests +1 -1
@@ -53,7 +53,7 @@ TESTS_DEPFILES = $(TESTS:%=%.d) \ $(addprefix $(TESTS_PREFIX),testutils.d) TESTS_CLEANFILES_L = $(STD_CLEANFILES) \ - *.dtb *.test.dtbo *.test.dts *.test.dt.yaml *.dtsv1 \ + *.dtb *.test.dtbo *.test.dts *.test.dt.yaml *.dtsv1 *.test.fit \ *.test.dtb.gz *.test.dtbo.gz *.test.dtb.xz *.test.dtbo.xz \ *.test.dtb.lzma *.test.dtbo.lzma *.test.dtb.lz4 *.test.dtbo.lz4 \ tmp.* *.bak \
tests/fdtfactor_lz4.its new file +109 -0
109 lines not on this page · raw message
tests/fdtfactor_other1.dts new file +33 -0
@@ -0,0 +1,33 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/dts-v1/; + +/memreserve/ 0xdeadbeef00000000 0x100000; + +/ { + compatible = "vendor,other1", "vendor,other"; + model = "other1"; + #address-cells = <1>; + #size-cells = <0>; + + osn1: other-subnode@1 { + compatible = "other-subnode1"; + reg = <1>; + prop-ref = <&osn1 0x10 &ossn1 0x20>; + + ossn1: other-subsubnode { + compatible = "other-subsubnode"; + prop-int = <0x1111>; + }; + }; + + osn2: other-subnode@2 { + reg = <2>; + prop-phandle = <&osn2>; + }; + + o1_node: other1-node { + prop-str = "other1"; + ref-base = <&osn1>; + ref-self = <&o1_node>; + }; +};
tests/fdtfactor_other2.dts new file +33 -0
@@ -0,0 +1,33 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/dts-v1/; + +/memreserve/ 0xdeadbeef00000000 0x100000; + +/ { + compatible = "vendor,other2", "vendor,other"; + model = "other2"; + #address-cells = <1>; + #size-cells = <0>; + + osn1: other-subnode@1 { + compatible = "other-subnode1"; + reg = <1>; + prop-ref = <&osn1 0x10 &ossn1 0x20>; + + ossn1: other-subsubnode { + compatible = "other-subsubnode"; + prop-int = <0x2222>; + }; + }; + + osn2: other-subnode@2 { + reg = <2>; + prop-phandle = <&osn2>; + }; + + o2_node: other2-node { + prop-str = "other2"; + ref-base = <&ossn1>; + ref-self = <&o2_node>; + }; +};
tests/fdtfactor_test.its new file +109 -0
109 lines not on this page · raw message
tests/run_tests.sh +157 -1
170 lines not on this page · raw message
Signature · 1 line
2.56.0.313.g2479322e68-goog
Re: [PATCH v2 02/10] pylibfdt: Add subnode/property iterators and get_mem_rsv_list()
In reply to Douglas AndersonQuoted 11 lines · Douglas Anderson
Add Pythonic iterator helpers on
FdtRoto simplify walking nodes, properties, and memory reservation entries without manual offset loops or-FDT_ERR_NOTFOUNDsentinel handling:-
subnodes(nodeoffset): yields the offset of each direct child subnode ofnodeoffset.
-properties(nodeoffset): yields aPropertyobject for each property ofnodeoffset.
-get_mem_rsv_list(): returns a list of(address, size)tuples for all entries in the memory reservation block.
Quoted 2 lines
Assisted-by Gemini:gemini-pro-prereleaseSigned-off-by Douglas Anderson <[email protected]>
Patches 1 & 2 are useful independent of the rest of the series. Applied, thanks.
Quoted 120 lines
---
Changes in v2:
- New patch addingFdtRo.subnodes(),FdtRo.properties(), andFdtRo.get_mem_rsv_list()pylibfdt/libfdt.i | 45 +++++++++++++++++++++++++++++++++++++++++ tests/pylibfdt_tests.py | 18 +++++++++++++++++ 2 files changed, 63 insertions(+)pylibfdt/libfdt.i +45
-0@@ -201,6 +201,23 @@ class FdtRo(object): """ return check_err(fdt_next_subnode(self._fdt, nodeoffset), quiet) + def subnodes(self, nodeoffset): + """Iterate over the subnodes of a node + + Args: + nodeoffset: Offset of parent node to check + + Yields: + Node offset of each direct subnode in order + + Raises: + FdtException on error (e.g. invalid nodeoffset) + """ + soff = self.first_subnode(nodeoffset, quiet=QUIET_NOTFOUND) + while soff >= 0: + yield soff + soff = self.next_subnode(soff, quiet=QUIET_NOTFOUND) + def magic(self): """Return the magic word from the header@@ -302,6 +319,17 @@ class FdtRo(object): check_err(val[0], quiet) return val[1:] + def get_mem_rsv_list(self): + """Return a list of all memory reserve-map records + + Returns: + List of (address, size) tuples for each memory reserve-map record + """ + return [ + tuple(self.get_mem_rsv(i)) + for i in range(self.num_mem_rsv()) + ] + def address_cells(self, nodeoffset, quiet=()): """Return the number of address cells used by a node's children@@ -434,6 +462,23 @@ class FdtRo(object): return pdata[1] return Property(pdata[0], pdata[1]) + def properties(self, nodeoffset): + """Iterate over the properties of a node + + Args: + nodeoffset: Offset of node to check + + Yields: + Property object for each property on @nodeoffset in order + + Raises: + FdtException on error (e.g. invalid nodeoffset) + """ + poff = self.first_property_offset(nodeoffset, quiet=QUIET_NOTFOUND) + while poff >= 0: + yield self.get_property_by_offset(poff) + poff = self.next_property_offset(poff, quiet=QUIET_NOTFOUND) + def getprop(self, nodeoffset, prop_name, quiet=()): """Get a property from a nodetests/pylibfdt_tests.py +18
-0@@ -243,6 +243,22 @@ class PyLibfdtBasicTests(unittest.TestCase): node_list.append(self.fdt.get_name(node)) node = self.fdt.next_subnode(node, QUIET_NOTFOUND) self.assertEqual(node_list, ['subnode@1', 'subnode@2']) + self.assertEqual( + [self.fdt.get_name(n) for n in self.fdt.subnodes(0)], + ['subnode@1', 'subnode@2'], + ) + leaf = self.fdt.path_offset('/subnode@1/ss1') + self.assertEqual(list(self.fdt.subnodes(leaf)), []) + + def testPropertiesIterator(self): + """Check that we can iterate through properties of a node""" + node = self.fdt.path_offset('/subnode@1') + props = list(self.fdt.properties(node)) + self.assertEqual([p.name for p in props], + ['compatible', 'reg', 'prop-int']) + self.assertEqual(props[0], b'subnode1\0') + leaf = self.fdt.path_offset('/subnode@1/ss1') + self.assertEqual(list(self.fdt.properties(leaf)), []) def testFirstNextSubnodeOffsetExceptions(self): """Check except handling for first/next subnode functions"""@@ -410,6 +426,8 @@ class PyLibfdtBasicTests(unittest.TestCase): self.assertEqual([ 0xdeadbeef00000000, 0x100000], self.fdt.get_mem_rsv(0)) self.assertEqual([123456789, 0o10000], self.fdt.get_mem_rsv(1)) + self.assertEqual([(0xdeadbeef00000000, 0x100000), (123456789, 0o10000)], + self.fdt.get_mem_rsv_list()) def testAddDelReserveMap(self): """Test that we can add to and remove from the memory reserve map"""Signature · 1 line
2.56.0.313.g2479322e68-goog
Signature · 4 lines
David Gibson (he or they) | I'll have my music baroque, and my code david AT gibson.dropbear.id.au | minimalist, thank you, not the other way | around. http://www.ozlabs.org/~dgibson
Re: [PATCH v2 03/10] pylibfdt: Add NodeTree live tree representation
In reply to Douglas AndersonQuoted 16 lines · Douglas Anderson
Add
NodeTree, an in-memory live tree representation of a devicetree node and its subtree, topylibfdt:-
NodeTree.unflatten(fdt, offset=0)builds aNodeTreehierarchy from anFdtRoinstance.
-NodeTree.flatten(mem_rsv=(), boot_cpuid_phys=0)serializes a rootNodeTreeback into a packed FDT blob viaFdtSw.
-get_node(),create_path(), andwalk()provide path lookup, intermediate node creation, and pre-order traversal.
-get_str(),set_str(),get_stringlist(),set_stringlist(),get_u32(),set_u32(),get_u32_list(), andset_u32_list()provide typed property access and mutation (updatingProperty.as_str()andProperty.as_stringlist()so emptyb''properties raiseValueErroror return[]rather thanIndexError).
Quoted 2 lines
Add unit tests in
tests/pylibfdt_tests.pycoveringNodeTreeunflatten/flatten round-tripping and helper methods.
Thanks for splitting this out as suggested. However, on consideration, I don't think it really belongs in pylibfdt: the "f" in there refers to "flattened" and this is, explicitly, a non-flattened data structure.
I have sometimes thought about adding a library for handling non-flattened trees, although I wasn't thinking something Python specific.
I think for now let's move this to its own Python file / module.
Quoted 26 lines
Assisted-by Gemini:gemini-pro-prereleaseSigned-off-by Douglas Anderson <[email protected]>---
Changes in v2:
- Split NodeTree live tree representation out of fdtfactor into pylibfdt (David Gibson)pylibfdt/libfdt.i | 262 +++++++++++++++++++++++++++++++++++++++- tests/pylibfdt_tests.py | 54 +++++++++ 2 files changed, 315 insertions(+), 1 deletion(-)pylibfdt/libfdt.i +1
-1@@ -929,7 +929,7 @@ class Property(bytearray): def as_str(self): """Unicode is supported by decoding from UTF-8""" - if self[-1] != 0: + if not self or self[-1] != 0: raise ValueError('Property lacks nul termination') if 0 in self[:-1]: raise ValueError('Property contains embedded nul characters')
pylibfdt/libfdt.i class Property(bytearray): · line 941
Quoted 5 lines
pylibfdt/libfdt.i +2
-0@@ -937,6 +937,8 @@ class Property(bytearray): def as_stringlist(self): """Unicode is supported by decoding from UTF-8""" + if not self: + return []
The two hunks above are good fixes, but unrelated to the bulk of the patch.
pylibfdt/libfdt.i class NodeAdder(): · line 1217
Quoted 10 lines
pylibfdt/libfdt.i +3
-0if self[-1] != 0: raise ValueError('Property lacks nul termination') parts = self[:-1].split(b'\x00')@@ -1210,6 +1212,264 @@ class NodeAdder(): def __exit__(self, type, value, traceback): self._fdt.end_node() + + +class NodeTree:
Maybe class DeviceTree? The "node" doesn't really add any useful information.
Quoted 15 lines
pylibfdt/libfdt.i +15
-0+ """In-memory live tree representation of a devicetree node and its subtree. + + Attributes: + props: Dict mapping property name (str) to raw property value (bytes). + children: Dict mapping child node name (str) to child NodeTree. + """ + + def __init__(self): + self.props = {} + self.children = {} + + @classmethod + def unflatten(cls, fdt, offset=0): + """Unflatten an FdtRo subtree starting at `offset` into a NodeTree. +
pylibfdt/libfdt.i class NodeAdder(): · line 1242
Quoted 10 lines
pylibfdt/libfdt.i +10
-0+ Args: + fdt: An `FdtRo` (or `Fdt`) instance. + offset: Starting node offset (default 0 for the root node). + + Returns: + A `NodeTree` representing the node at `offset` and its descendants. + """ + node = cls() + for prop in fdt.properties(offset): + node.props[prop.name] = bytes(prop)
Since we already rely on class Property from libfdt.i, it seems like it would be a little more natural to have the dictionary values be class Property instances. Yes, that technically has some redundant storage of the property names, but we're not particularly concerned about optimisation for this Python library. Plus, Python's assign-by-reference should mean it's generally just a duplicated pointer, not a whole duplicated string.
Quoted 26 lines
pylibfdt/libfdt.i +26
-0+ for suboff in fdt.subnodes(offset): + node.children[fdt.get_name(suboff)] = cls.unflatten(fdt, suboff) + return node + + def _flatten_subtree(self, sw, name): + """Recursively write this NodeTree and its children into an FdtSw. + + Args: + sw: An `FdtSw` sequential-write instance. + name: Node name for this subtree (empty string `''` for root). + """ + with sw.add_node(name): + for prop_name, val in self.props.items(): + sw.property(prop_name, bytes(val)) + for child_name, child_node in self.children.items(): + child_node._flatten_subtree(sw, child_name) + + def flatten(self, mem_rsv=(), boot_cpuid_phys=0): + """Serialize this root NodeTree into a packed FDT byte string. + + Args: + mem_rsv: Iterable of (address, size) tuples for the FDT memory + reservation block. + boot_cpuid_phys: Physical boot CPU ID for the FDT header. + + Returns:
pylibfdt/libfdt.i class NodeAdder(): · line 1278
Quoted 10 lines
pylibfdt/libfdt.i +10
-0+ Serialized FDT blob as `bytes`. + """ + sw = FdtSw() + for addr, size in mem_rsv: + sw.add_reservemap_entry(addr, size) + sw.finish_reservemap() + self._flatten_subtree(sw, '') + fdt = sw.as_fdt() + fdt_set_boot_cpuid_phys(fdt._fdt, boot_cpuid_phys) + fdt.pack()
For better symmetry with unflatten(), I'd suggest returning the Fdt object here, leaving the conversion to a bytearray to the caller.
Quoted 27 lines
pylibfdt/libfdt.i +27
-0+ return bytes(fdt.as_bytearray()) + + def get_node(self, path): + """Look up a descendant NodeTree by path without modifying the tree. + + Follows the slash-separated node names in `path` starting from `self` + (leading, trailing, and repeated `'/'` characters are ignored, so + `'/soc/i2c@4000'` and `'soc/i2c@4000'` behave identically, and `''` or + `'/'` returns `self`). If any component along `path` is not present in + `children`, returns `None`. + + Args: + path: Slash-separated node path starting from `self` (e.g. + `'/soc/i2c@4000'` or `'soc/i2c@4000'`). + + Returns: + The `NodeTree` at `path`, or `None` if not found. + """ + node = self + for part in path.split('/'): + if not part: + continue + node = node.children.get(part) + if node is None: + return None + return node +
pylibfdt/libfdt.i class NodeAdder(): · line 1315
Quoted 10 lines
pylibfdt/libfdt.i +10
-0+ def create_path(self, path): + """Return the descendant NodeTree at `path`, creating missing nodes. + + Looks up a child or deeper descendant `NodeTree` by following the + slash-separated node names in `path` starting from `self` (leading, + trailing, and repeated `'/'` characters are ignored, so + `'/soc/i2c@4000'` and `'soc/i2c@4000'` behave identically). If any + node along `path` does not exist yet in `children`, a new empty + `NodeTree` is created for it automatically (similar to `mkdir -p`). + Passing `''` or `'/'` returns `self`.
Reference get_path() rather than repeating this useful, but wordy, description.
Quoted 229 lines
pylibfdt/libfdt.i +157
-0+ + Example: + root = NodeTree() + # Automatically creates root.children['soc'] and + # root.children['soc'].children['i2c@4000'], and returns the + # 'i2c@4000' NodeTree. + i2c = root.create_path('/soc/i2c@4000') + i2c.set_str('status', 'okay') + + Args: + path: Slash-separated node path starting from `self` (e.g. + `'/soc/i2c@4000'` or `'soc/i2c@4000'`). + + Returns: + The `NodeTree` instance at `path`. + """ + node = self + for part in path.split('/'): + if not part: + continue + if part not in node.children: + node.children[part] = type(self)() + node = node.children[part] + return node + + def walk(self, path=''): + """Yield `(path, node)` pairs for this subtree in pre-order. + + Args: + path: Path prefix for `self` (defaults to `''` for the root node, + producing paths like `''`, `'/soc'`, `'/soc/i2c@4000'`). + + Yields: + Tuple of `(path, node)` for `self` followed recursively by each + descendant `NodeTree`. + """ + prefix = path.rstrip('/') + yield path, self + for name, child in self.children.items(): + yield from child.walk(f'{prefix}/{name}') + + def get_str(self, name): + """Return property `name` decoded as a NUL-terminated UTF-8 string. + + Args: + name: Property name to look up in `self.props`. + + Returns: + Decoded string value (without the trailing NUL byte). + + Raises: + KeyError: If `name` is not in `self.props`. + ValueError: If the property value is not a single NUL-terminated + UTF-8 string. + """ + return Property(name, self.props[name]).as_str() + + def set_str(self, name, val): + """Set property `name` to a NUL-terminated UTF-8 string. + + Args: + name: Property name to set in `self.props`. + val: String value to encode as UTF-8 with a trailing NUL byte. + + Raises: + ValueError: If `val` contains embedded NUL characters. + """ + if '\x00' in val: + raise ValueError('String value contains embedded nul characters') + self.props[name] = val.encode('utf-8') + b'\x00' + + def get_stringlist(self, name): + """Return property `name` decoded as a list of NUL-separated strings. + + Args: + name: Property name to look up in `self.props`. + + Returns: + List of decoded UTF-8 strings (`[]` if the property is empty). + + Raises: + KeyError: If `name` is not in `self.props`. + ValueError: If a non-empty property lacks NUL termination. + """ + return Property(name, self.props[name]).as_stringlist() + + def set_stringlist(self, name, vals): + """Set property `name` to a NUL-separated list of UTF-8 strings. + + Args: + name: Property name to set in `self.props`. + vals: Iterable of strings to encode as NUL-terminated UTF-8. + + Raises: + ValueError: If any string in `vals` contains embedded NUL + characters. + """ + vals = list(vals) + if any('\x00' in v for v in vals): + raise ValueError('String value contains embedded nul characters') + self.props[name] = b''.join(v.encode('utf-8') + b'\x00' for v in vals) + + def get_u32(self, name): + """Return property `name` decoded as a single big-endian uint32 cell. + + Args: + name: Property name to look up in `self.props`. + + Returns: + Integer value of the 32-bit cell. + + Raises: + KeyError: If `name` is not in `self.props`. + ValueError: If the property length is not 4 bytes. + """ + raw = self.props[name] + if len(raw) != 4: + raise ValueError(f'Property {name!r} length {len(raw)} != 4') + return Property(name, raw).as_uint32() + + def set_u32(self, name, val): + """Set property `name` to a single big-endian uint32 cell. + + Args: + name: Property name to set in `self.props`. + val: Unsigned 32-bit integer value. + """ + self.props[name] = struct.pack('>I', val) + + def get_u32_list(self, name): + """Return property `name` decoded as a list of big-endian uint32 cells. + + Args: + name: Property name to look up in `self.props`. + + Returns: + List of 32-bit unsigned integers. + + Raises: + KeyError: If `name` is not in `self.props`. + ValueError: If the property length is not a multiple of 4 bytes. + """ + raw = self.props[name] + if len(raw) % 4 != 0: + raise ValueError( + f'Property {name!r} length {len(raw)} is not a multiple of 4' + ) + return Property(name, raw).as_uint32_list() + + def set_u32_list(self, name, vals): + """Set property `name` to a sequence of big-endian uint32 cells. + + Args: + name: Property name to set in `self.props`. + vals: Sequence of unsigned 32-bit integer values. + """ + self.props[name] = struct.pack(f'>{len(vals)}I', *vals) %} %rename(fdt_property) fdt_property_func;tests/pylibfdt_tests.py +54
-0@@ -697,6 +697,60 @@ class PyLibfdtRoTests(unittest.TestCase): self.assertEqual(b'this is a placeholder string\0string2\0', self.fdt.getprop(node, 'placeholder')) + def testNodeTreeRoundTrip(self): + """Test unflattening and flattening a tree via NodeTree""" + tree = libfdt.NodeTree.unflatten(self.fdt) + rsvmap = self.fdt.get_mem_rsv_list() + cpuid = self.fdt.boot_cpuid_phys() + blob = tree.flatten(rsvmap, cpuid) + + fdt2 = libfdt.FdtRo(blob) + self.assertEqual(rsvmap, fdt2.get_mem_rsv_list()) + self.assertEqual(cpuid, fdt2.boot_cpuid_phys()) + + tree2 = libfdt.NodeTree.unflatten(fdt2) + nodes1 = [(path, n.props, list(n.children.keys())) + for path, n in tree.walk()] + nodes2 = [(path, n.props, list(n.children.keys())) + for path, n in tree2.walk()] + self.assertEqual(nodes1, nodes2) + + def testNodeTreeHelpers(self): + """Test NodeTree navigation and typed property helpers""" + root = libfdt.NodeTree() + self.assertIs(root, root.get_node('')) + self.assertIs(root, root.get_node('/')) + self.assertIsNone(root.get_node('/soc/i2c@4000')) + + i2c = root.create_path('/soc/i2c@4000') + self.assertIs(i2c, root.get_node('/soc/i2c@4000')) + self.assertIs(i2c, root.get_node('soc/i2c@4000')) + self.assertEqual(['', '/soc', '/soc/i2c@4000'], + [path for path, _ in root.walk()]) + self.assertEqual(['/', '/soc', '/soc/i2c@4000'], + [path for path, _ in root.walk('/')]) + + i2c.set_str('status', 'okay') + self.assertEqual('okay', i2c.get_str('status')) + with self.assertRaises(ValueError): + i2c.set_str('status', 'ok\x00ay') + + i2c.set_stringlist('compatible', ['vendor,i2c', 'generic,i2c']) + self.assertEqual(['vendor,i2c', 'generic,i2c'], + i2c.get_stringlist('compatible')) + with self.assertRaises(ValueError): + i2c.set_stringlist('compatible', ['vendor\x00,i2c']) + i2c.set_stringlist('empty-list', []) + self.assertEqual([], i2c.get_stringlist('empty-list')) + with self.assertRaises(ValueError): + i2c.get_str('empty-list') + + i2c.set_u32('#address-cells', 1) + self.assertEqual(1, i2c.get_u32('#address-cells')) + + i2c.set_u32_list('reg', [0x4000, 0x100]) + self.assertEqual([0x4000, 0x100], i2c.get_u32_list('reg')) + if __name__ == "__main__": unittest.main()Signature · 1 line
2.56.0.313.g2479322e68-goog
Signature · 4 lines
David Gibson (he or they) | I'll have my music baroque, and my code david AT gibson.dropbear.id.au | minimalist, thank you, not the other way | around. http://www.ozlabs.org/~dgibson
Re: [PATCH v2 04/10] libfdt: overlay: Factor out fixup and fragment path parsing helpers
In reply to Douglas AndersonQuoted 12 lines · Douglas Anderson
In preparation for updating the base device tree's
/__local_fixups__node duringfdt_overlay_apply(), factor out two helper functions inlibfdt/fdt_overlay.c:- Factor out
overlay_parse_fixup_entry()fromoverlay_fixup_phandle()to parse"path:name:offset"entries in/__fixups__properties.
- Factor outoverlay_split_fragment_path()fromoverlay_symbol_update()to validate and split"/<fragment>/__overlay__[/<rel>]"paths into the fragment name and relative subnode path.
Quoted 1 line
This commit is pure code movement with no functional change.
Conceptually good, but has a couple of warts.
Quoted 17 lines
Assisted-by Gemini:gemini-pro-prereleaseSigned-off-by Douglas Anderson <[email protected]>---
Changes in v2:
- New patch factoring outoverlay_parse_fixup_entry()andoverlay_split_fragment_path()helpers inlibfdt/fdt_overlay.clibfdt/fdt_overlay.c | 226 +++++++++++++++++++++++++++++-------------- 1 file changed, 154 insertions(+), 72 deletions(-)libfdt/fdt_overlay.c +0
-0
libfdt/fdt_overlay.c static int overlay_fixup_one_phandle(void *fdto, int symbols_off, · line 357
Quoted 7 lines
libfdt/fdt_overlay.c +4
-0@@ -351,6 +351,72 @@ static int overlay_fixup_one_phandle(void *fdto, int symbols_off, sizeof(phandle_prop)); } +/** +* overlay_parse_fixup_entry - Parse one "path:name:offset" entry from /__fixups__ +* @valuep: In/out pointer to the current NUL-terminated fixup string +* @lenp: In/out remaining length of the /__fixups__ property value
It would be good to describe how the in/out values are updated.
Quoted 5 lines
libfdt/fdt_overlay.c +5
-0+* @pathp: Output pointer to the target node path +* @path_lenp: Output length of @pathp in bytes +* @namep: Output pointer to the target property name +* @name_lenp: Output length of @namep in bytes +* @poffsetp: Output byte offset within the target property
[snip]
Quoted 9 lines
+/**
+ *overlay_split_fragment_path- Split "/<frag>/__overlay__[/<rel>]" into parts
+ * @path: Input NUL-terminated path property string
+ * @path_len: Length of @path in bytes (including trailing NUL)
+ * @frag_namep: Output pointer to the fragment name
+ * @frag_name_lenp: Output length of @frag_namep in bytes
+ * @rel_pathp: Output pointer to the relative subnode path after__overlay__
+ * @rel_path_lenp: Output length of @rel_pathp in bytes
+ * @is_overlayp: Set to true if @path is under an__overlay__subnode
Returning the bool this way is clunky. Better to use the return value.
Quoted 136 lines
+ * returns:
+ * 0 on success
+ * -FDT_ERR_BADVALUE if @path is not a valid NUL-terminated '/' path
+ */libfdt/fdt_overlay.c +69
-37+static int overlay_split_fragment_path (const char *path,int path_len, +const char **frag_namep, +int *frag_name_lenp, +const char **rel_pathp, +int *rel_path_lenp, +bool *is_overlayp) +{ +int len, frag_name_len, rel_path_len; +const char *s, *e; +const char *frag_name; +const char *rel_path; + + *is_overlayp = false; + +/* verify it's a string property (terminated by a single \0) */ +if (path_len <1 ||memchr (path,'\0' , path_len) != &path[path_len -1 ]) +return -FDT_ERR_BADVALUE ; + +/* keep end marker to avoid strlen() */ + e = path + path_len; + +if (*path !='/' ) +return -FDT_ERR_BADVALUE ; + +/* get fragment name first */ + s =strchr (path +1 ,'/' ); +if (!s) { +/* Symbol refers to something that won't end +* up in the target tree */ +return 0 ; + } + + frag_name = path +1 ; + frag_name_len = s - path -1 ; + +/* verify format; safe since "s" lies in \0 terminated prop */ + len =sizeof ("/__overlay__/" ) -1 ; +if ((e - s) > len && (memcmp (s,"/__overlay__/" , len) ==0 )) { +/* /<fragment-name>/__overlay__/<relative-subnode-path> */ + rel_path = s + len; + rel_path_len = e - rel_path -1 ; + }else if ((e - s) == len + && (memcmp (s,"/__overlay__" , len -1 ) ==0 )) { +/* /<fragment-name>/__overlay__ */ + rel_path ="" ; + rel_path_len =0 ; + }else { +/* Symbol refers to something that won't end +* up in the target tree */ +return 0 ; + } + + *frag_namep = frag_name; + *frag_name_lenp = frag_name_len; + *rel_pathp = rel_path; + *rel_path_lenp = rel_path_len; + *is_overlayp = true; +return 0 ; +} +/** * overlay_symbol_update - Update the symbols of base tree after a merge * @fdt: Base Device Tree blob @@ -907,7 +1017,6 @@ static int overlay_symbol_update(void *fdt, void *fdto) {int root_sym, ov_sym, prop, path_len, fragment, target;int len, frag_name_len, ret, rel_path_len; -const char *s, *e;const char *path;const char *name;const char *frag_name;@@ -934,47 +1043,20 @@ static int overlay_symbol_update(void *fdt, void *fdto)/* iterate over each overlay symbol */ fdt_for_each_property_offset (prop, fdto, ov_sym) { +bool is_overlay; + path =fdt_getprop_by_offset (fdto, prop, &name, &path_len);if (!path)return path_len; -/* verify it's a string property (terminated by a single \0) */ -if (path_len <1 ||memchr (path,'\0' , path_len) != &path[path_len -1 ]) -return -FDT_ERR_BADVALUE ; - -/* keep end marker to avoid strlen() */ - e = path + path_len; - -if (*path !='/' ) -return -FDT_ERR_BADVALUE ; - -/* get fragment name first */ - s =strchr (path +1 ,'/' ); -if (!s) { -/* Symbol refers to something that won't end -* up in the target tree */ -continue ; - } - - frag_name = path +1 ; - frag_name_len = s - path -1 ; - -/* verify format; safe since "s" lies in \0 terminated prop */ - len =sizeof ("/__overlay__/" ) -1 ; -if ((e - s) > len && (memcmp (s,"/__overlay__/" , len) ==0 )) { -/* /<fragment-name>/__overlay__/<relative-subnode-path> */ - rel_path = s + len; - rel_path_len = e - rel_path -1 ; - }else if ((e - s) == len - && (memcmp (s,"/__overlay__" , len -1 ) ==0 )) { -/* /<fragment-name>/__overlay__ */ - rel_path ="" ; - rel_path_len =0 ; - }else { -/* Symbol refers to something that won't end -* up in the target tree */ + ret =overlay_split_fragment_path (path, path_len, + &frag_name, &frag_name_len, + &rel_path, &rel_path_len, + &is_overlay); +if (ret) +return ret; +if (!is_overlay)continue ; - }/* find the fragment index in which the symbol lies */ ret = fdt_subnode_offset_namelen(fdto, 0, frag_name,Signature · 1 line
2.56.0.313.g2479322e68-goog
Signature · 4 lines
David Gibson (he or they) | I'll have my music baroque, and my code david AT gibson.dropbear.id.au | minimalist, thank you, not the other way | around. http://www.ozlabs.org/~dgibson
Re: [PATCH v2 05/10] libfdt: overlay: Prepare fixup and fragment path helpers for reuse
In reply to Douglas AndersonQuoted 11 lines · Douglas Anderson
Clean up
overlay_parse_fixup_entry()and generalizeoverlay_split_fragment_path()inlibfdt/fdt_overlay.cso both can be reused when updating/__local_fixups__:- Change
poffsetfrominttouint32_tinoverlay_fixup_one_phandle(),overlay_parse_fixup_entry(), andoverlay_fixup_phandle(), and parse intounsigned longbefore validating the range.
- Require*(sep + 1)to be an ASCII digit ('0'..'9') and boundpoffsettoINT32_MAX - sizeof(uint32_t)so negative strings (such as"-4"), leading whitespace, or large values cannot silently
Huh, I'd assumed that strtoul() wouldn't accept negative strings, but according to BUGS in strtoul(1) that might not be the case (at least for Linux+glibc). Good catch.
Quoted 7 lines
truncate or wrap around in
fdt_setprop_inplace_namelen_partial().
- Drop the redundant*sep != ':'checks aftermemchr(..., ':', ...).
- Generalizeoverlay_split_fragment_path()to accept a length-boundedpathslice that is not necessarily NUL-terminated (usingmemchr()instead ofstrchr(), and keeping the NUL-terminated property check inoverlay_symbol_update()) so it can also split:-delimited paths from/__fixups__.
This may need some minor rebasing for the suggestions on the previous patch, plus some additional minor refinements suggested below.
Quoted 57 lines
Assisted-by Gemini:gemini-pro-prereleaseSigned-off-by Douglas Anderson <[email protected]>---
Changes in v2:
- New patch tightening fixup offset parsing and generalizingoverlay_split_fragment_path()for non-NUL-terminated paths inlibfdt/fdt_overlay.clibfdt/fdt_overlay.c | 46 +++++++++++++++++++++++--------------------- 1 file changed, 24 insertions(+), 22 deletions(-)libfdt/fdt_overlay.c +4
-4@@ -330,7 +330,7 @@ static int overlay_update_local_references(void *fdto, uint32_t delta)static int overlay_fixup_one_phandle (void *fdto,int symbols_off,const char *path,uint32_t path_len,const char *name,uint32_t name_len, -int poffset,uint32_t phandle) +uint32_t poffset,uint32_t phandle) {fdt32_t phandle_prop;int fixup_off;@@ -368,7 +368,7 @@ static int overlay_fixup_one_phandle(void *fdto, int symbols_off,static int overlay_parse_fixup_entry (const char **valuep,int *lenp,const char **pathp,uint32_t *path_lenp,const char **namep,uint32_t *name_lenp, -int *poffsetp) +uint32_t *poffsetp) {const char *path, *name, *fixup_end;const char *fixup_str = *valuep;@@ -376,7 +376,7 @@ static int overlay_parse_fixup_entry(const char **valuep, int *lenp,uint32_t fixup_len;const char *sep;char *endptr; -int poffset; +unsigned long poffset; fixup_end =memchr (*valuep,'\0' , *lenp);if (!fixup_end)@@ -388,7 +388,7 @@ static int overlay_parse_fixup_entry(const char **valuep, int *lenp, path = fixup_str; sep =memchr (fixup_str,':' , fixup_len); -if (!sep || *sep !=':' ) +if (!sep)return -FDT_ERR_BADOVERLAY ; path_len = sep - path;@@ -398,15 +398,17 @@ static int overlay_parse_fixup_entry(const char **valuep, int *lenp, fixup_len -= path_len +1 ; name = sep +1 ; sep =memchr (name,':' , fixup_len);
libfdt/fdt_overlay.c static int overlay_parse_fixup_entry(const char **valuep, int *lenp, · line 409
Quoted 10 lines
libfdt/fdt_overlay.c +3
-1-if (!sep || *sep !=':' ) +if (!sep)return -FDT_ERR_BADOVERLAY ; name_len = sep - name;if (!name_len)return -FDT_ERR_BADOVERLAY ; +if ((*(sep +1 ) <'0' ) || (*(sep +1 ) >'9' )) +return -FDT_ERR_BADOVERLAY ;
Putting the rationale for this in a comment here would be more useful than just in the commit message.
Quoted 93 lines
libfdt/fdt_overlay.c +17
-17poffset =strtoul (sep +1 , &endptr,10 ); -if ((*endptr !='\0' ) || (endptr <= (sep +1 ))) +if ((*endptr !='\0' ) || (poffset > (INT32_MAX -sizeof (uint32_t ))))return -FDT_ERR_BADOVERLAY ; *pathp = path;@@ -470,8 +472,8 @@ static int overlay_fixup_phandle(void *fdt, void *fdto, int symbols_off, do { const char *path, *name; - uint32_t path_len, name_len; - int poffset, ret; + uint32_t path_len, name_len, poffset; + int ret; ret = overlay_parse_fixup_entry(&value, &len, &path, &path_len, &name, &name_len, &poffset);@@ -925,8 +927,8 @@ static int get_path_len(const void *fdt, int nodeoffset)/** * overlay_split_fragment_path - Split "/<frag>/__overlay__[/<rel>]" into parts -* @path: Input NUL-terminated path property string -* @path_len: Length of @path in bytes (including trailing NUL) +* @path: Input path string (need not be NUL-terminated) +* @path_len: Length of @path in bytes (excluding any terminator) * @frag_namep: Output pointer to the fragment name * @frag_name_lenp: Output length of @frag_namep in bytes * @rel_pathp: Output pointer to the relative subnode path after __overlay__ @@ -935,7 +937,7 @@ static int get_path_len(const void *fdt, int nodeoffset)* * returns: * 0 on success -* -FDT_ERR_BADVALUE if @path is not a valid NUL-terminated '/' path +* -FDT_ERR_BADVALUE if @path does not start with '/' */ static int overlay_split_fragment_path(const char *path, int path_len, const char **frag_namep,@@ -951,18 +953,14 @@ static int overlay_split_fragment_path(const char *path, int path_len, *is_overlayp = false; -/* verify it's a string property (terminated by a single \0) */ -if (path_len <1 ||memchr (path,'\0' , path_len) != &path[path_len -1 ]) -return -FDT_ERR_BADVALUE ; -/* keep end marker to avoid strlen() */ e = path + path_len; -if (*path !='/' ) +if (path_len <1 || *path !='/' )return -FDT_ERR_BADVALUE ;/* get fragment name first */ - s =strchr (path +1 ,'/' ); + s =memchr (path +1 ,'/' , path_len -1 );if (!s) {/* Symbol refers to something that won't end * up in the target tree */ @@ -972,13 +970,13 @@ static int overlay_split_fragment_path(const char *path, int path_len, frag_name = path +1 ; frag_name_len = s - path -1 ; -/* verify format; safe since "s" lies in \0 terminated prop */ +/* verify format */ len =sizeof ("/__overlay__/" ) -1 ; -if ((e - s) > len && (memcmp (s,"/__overlay__/" , len) ==0 )) { +if ((e - s) >= len && (memcmp (s,"/__overlay__/" , len) ==0 )) {/* /<fragment-name>/__overlay__/<relative-subnode-path> */ rel_path = s + len; - rel_path_len = e - rel_path -1 ; - }else if ((e - s) == len + rel_path_len = e - rel_path; + }else if ((e - s) == (len -1 ) && (memcmp (s,"/__overlay__" , len -1 ) ==0 )) {/* /<fragment-name>/__overlay__ */ rel_path ="" ;@@ -1049,7 +1047,11 @@ static int overlay_symbol_update(void *fdt, void *fdto)if (!path)return path_len; - ret =overlay_split_fragment_path (path, path_len, +/* verify it's a string property (terminated by a single \0) */ +if (path_len <1 ||memchr (path,'\0' , path_len) != &path[path_len -1 ]) +return -FDT_ERR_BADVALUE ; + + ret =overlay_split_fragment_path (path, path_len -1 , &frag_name, &frag_name_len, &rel_path, &rel_path_len, &is_overlay);Signature · 1 line
2.56.0.313.g2479322e68-goog
Signature · 4 lines
David Gibson (he or they) | I'll have my music baroque, and my code david AT gibson.dropbear.id.au | minimalist, thank you, not the other way | around. http://www.ozlabs.org/~dgibson
Re: [PATCH v2 06/10] libfdt: overlay: Update base /__local_fixups__ on apply
In reply to Douglas AndersonQuoted 24 lines · Douglas Anderson
When a base device tree is compiled with
dtc -L(--local-fixups), it contains a root/__local_fixups__node recording the byte offsets of all phandle references in its properties.Previously,
fdt_overlay_apply()updated the base tree's/__symbols__viaoverlay_symbol_update(), but left the base tree's/__local_fixups__untouched. As a result, applying an overlay to a base tree with/__local_fixups__left/__local_fixups__missing the phandle references introduced by the overlay (both from the overlay's/__local_fixups__and from its resolved/__fixups__), and left stale offsets if the overlay overwrote a base property that previously had phandle references.Add
overlay_local_fixups_update()to update the base tree's/__local_fixups__whenever/__local_fixups__is present in the base tree:- Remove pre-existing
/__local_fixups__properties for any base properties overwritten by overlay fragments.
- Merge the overlay's/__local_fixups__and/__fixups__offsets into the base tree's/__local_fixups__in sorted ascending order.
- Prune any subnodes under/__local_fixups__that become empty after overwriting properties.
Quoted 2 lines
When the base tree does not have a
/__local_fixups__node,overlay_local_fixups_update()is a no-op.
So, this turned out to be substantially more involved than I realised. I wonder if it might be better to make --strip-locals the default, and only add support for preserving the local fixups as a later extension.
Quoted 18 lines
Assisted-by Gemini:gemini-pro-prereleaseSigned-off-by Douglas Anderson <[email protected]>---
Changes in v2:
- New patch updating base /__local_fixups__ in libfdtfdt_overlay_apply()instead of stripping /__local_fixups__ by default (David Gibson)libfdt/fdt_overlay.c | 621 ++++++++++++++++++++++++++++++++++++++++++- tests/run_tests.sh | 19 ++ 2 files changed, 636 insertions(+), 4 deletions(-)libfdt/fdt_overlay.c +0
-0
libfdt/fdt_overlay.c static int overlay_prevent_phandle_overwrite(void *fdt, void *fdto) · line 807
Quoted 5 lines
libfdt/fdt_overlay.c +1
-1@@ -804,7 +804,7 @@ static int overlay_prevent_phandle_overwrite(void *fdt, void *fdto)* Negative error code on failure */ static int overlay_apply_node (void *fdt,int target, -void *fdto,int node) +const void *fdto,int node)
This change is unrelated to the rest of the patch.
Quoted 34 lines
libfdt/fdt_overlay.c +17
-3{int property;int subnode;@@ -1003,9 +1003,8 @@ static int overlay_split_fragment_path(const char *path, int path_len,* overlay_symbol_update() updates the symbols of the base tree with the * symbols of the applied overlay * -* This is the last step in the device tree overlay application -* process, allowing the reference of overlay symbols by subsequent -* overlay operations. +* This step in the device tree overlay application process allows +* the reference of overlay symbols by subsequent overlay operations. * * returns: * 0 on success @@ -1122,6 +1121,616 @@ static int overlay_symbol_update(void *fdt, void *fdto)return 0 ; } +/** +* overlay_create_path - Create a relative path under a parent node +* @fdt: Base Device Tree blob +* @parent: Node offset of the starting parent node +* @path: Relative or slash-prefixed path to traverse +* @path_len: Length of @path in bytes +* +* overlay_create_path() walks the slash-separated path components in @path +* starting at @parent, creating any missing intermediate subnodes along the +* way. +* +* returns: +* Node offset of the resolved or created subnode on success +* Negative error code on failure +*/
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1148
Quoted 10 lines
libfdt/fdt_overlay.c +10
-0+static int overlay_create_path (void *fdt,int parent,const char *path, +int path_len) +{ +const char *sep; +int node = parent; + +while (path_len >0 && *path =='/' ) { + path++; + path_len--; + }
In Python, I'm pretty happy to have the code to optionally allow extra slashes to make the functions more widely useful. In C - especially since this is code that may be run in limited environments - I'd prefer to pin down exactly what the expected format is and require that. So, I'd suggest this function only take a relative path, and make sure that's the case from the callers.
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1157
Quoted 9 lines
libfdt/fdt_overlay.c +9
-0+ +while (path_len >0 ) { +int comp_len; +int next; + + sep =memchr (path,'/' , path_len); + comp_len = sep ? (sep - path) : path_len; + +if (comp_len >0 ) {
Similarly, in C I'd treat comp_len == 0 as an error condition, rather than trying to handle it.
Quoted 6 lines
libfdt/fdt_overlay.c +6
-0+ next =fdt_subnode_offset_namelen (fdt, node, path, + comp_len); +if (next == -FDT_ERR_NOTFOUND ) + next =fdt_add_subnode_namelen (fdt, node, path, + comp_len); +if (next <0 )
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1173
Quoted 10 lines
libfdt/fdt_overlay.c +10
-0+return next; + node = next; + } + + path += comp_len; + path_len -= comp_len; +while (path_len >0 && *path =='/' ) { + path++; + path_len--; + }
Same thoughts here.
Quoted 27 lines
libfdt/fdt_overlay.c +27
-0+ } + +return node; +} + +/** +* overlay_fragment_local_fixups - Find or create a fragment's target under /__local_fixups__ +* @fdt: Base Device Tree blob +* @fdto: Device tree overlay blob +* @fragment: Node offset of the fragment in @fdto +* @create: Whether to create missing subnodes under /__local_fixups__ +* +* overlay_fragment_local_fixups() resolves the target of @fragment in @fdt and +* locates (or creates, when @create is true) the corresponding node at the +* same path under @fdt's /__local_fixups__ subtree. +* +* returns: +* Node offset of the corresponding /__local_fixups__ node on success +* Negative error code on failure +*/ +static int overlay_fragment_local_fixups (void *fdt,const void *fdto, +int fragment,bool create) +{ +int root_lf, target, cur_fdt, node; + + root_lf =fdt_subnode_offset (fdt,0 ,"__local_fixups__" ); +if (root_lf <0 )
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1207
Quoted 10 lines
libfdt/fdt_overlay.c +7
-0+return root_lf; + + target =fdt_overlay_target_offset (fdt, fdto, fragment,NULL ); +if (target <0 ) +return target; + + cur_fdt =0 ;
"cur_fdt" isn't a great name, it's not really suggesting to me what it's tracking.
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1208
Quoted 1 line
libfdt/fdt_overlay.c +1
-0+ node = root_lf;
Might be better to call this node_lf as a reminder that it's tracking a subnode of __local_fixups__.
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1218
Quoted 10 lines
libfdt/fdt_overlay.c +10
-0+while (cur_fdt != target) { +int subnode, ancestor = -FDT_ERR_INTERNAL ; +const char *name; +int namelen, next_lf; + +fdt_for_each_subnode (subnode, fdt, cur_fdt) { +if (subnode <= target) + ancestor = subnode; +else +break ;
I think
if (subnode > target) break; ancestor = subnode;
would be clearer.
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1229
Quoted 11 lines
libfdt/fdt_overlay.c +11
-0+ } +if (ancestor <0 ) +return ancestor; + + name =fdt_get_name (fdt, ancestor, &namelen); +if (!name) +return namelen; + + next_lf =fdt_subnode_offset_namelen (fdt, node, name, namelen); +if (next_lf == -FDT_ERR_NOTFOUND && create) { +char namebuf[256 ];
Arbitrary buffer size.
Quoted 4 lines
libfdt/fdt_overlay.c +4
-0+int old_struct_size =fdt_size_dt_struct (fdt); + +if ((size_t )namelen >=sizeof (namebuf)) +return -FDT_ERR_INTERNAL ;
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1243
Quoted 10 lines
libfdt/fdt_overlay.c +10
-0+memcpy (namebuf, name, namelen); + next_lf =fdt_add_subnode_namelen (fdt, node, namebuf, + namelen); +if (next_lf <0 ) +return next_lf; +if (next_lf <= ancestor) { +int delta =fdt_size_dt_struct (fdt) - + old_struct_size; + target += delta; + ancestor += delta;
Subtle, but necessary :/. Probably worth a comment that this - as well as the memcpy() above is because the fdt_add_subnode_namelen() might move 'target', and therefore also its name within the fdt.
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1251
Quoted 8 lines
libfdt/fdt_overlay.c +8
-0+ } + }else if (next_lf <0 ) { +return next_lf; + } + + cur_fdt = ancestor; + node = next_lf; + }
What this function is doing is pretty similar to fdt_supernode_atdepth_offset(). I wonder if it there's a reasonable way to make a common helper.
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1261
Quoted 10 lines
libfdt/fdt_overlay.c +10
-0+ +return node; +} + +/** +* overlay_clear_overwritten_local_fixups - Remove local fixups for overwritten properties +* @fdt: Base Device Tree blob +* @target_lf: Node offset in @fdt's /__local_fixups__ subtree +* @fdto: Device tree overlay blob +* @overlay: Node offset in @fdto's __overlay__ subtree
I'd probably suggest s/overlay/node/ and s/target_lf/node_lf/.
Quoted 15 lines
libfdt/fdt_overlay.c +15
-0+* +* overlay_clear_overwritten_local_fixups() recursively deletes properties under +* @target_lf that correspond to properties overwritten by @overlay in @fdto. +* +* returns: +* 0 on success +* Negative error code on failure +*/ +static int overlay_clear_overwritten_local_fixups (void *fdt,int target_lf, +const void *fdto,int overlay) +{ +int prop, subnode; + +fdt_for_each_property_offset (prop, fdto, overlay) { +const char *name;
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1286
Quoted 10 lines
libfdt/fdt_overlay.c +10
-0+const void *val; +int len, ret; + + val =fdt_getprop_by_offset (fdto, prop, &name, &len); +if (!val) +return len; + + ret =fdt_delprop (fdt, target_lf, name); +if (ret && ret != -FDT_ERR_NOTFOUND ) +return ret;
Doing this as a post-processing step, reconsulting the properties fromt the overlay seems a bit odd to me, rather than zapping the __local_fixups__ entry from within overlay_apply_node(). Is there a reason for it?
Quoted 26 lines
libfdt/fdt_overlay.c +26
-0+ } + +fdt_for_each_subnode (subnode, fdto, overlay) { +const char *name; +int namelen, sub_lf, ret; + + name =fdt_get_name (fdto, subnode, &namelen); +if (!name) +return namelen; + + sub_lf =fdt_subnode_offset_namelen (fdt, target_lf, name, + namelen); +if (sub_lf == -FDT_ERR_NOTFOUND ) +continue ; +if (sub_lf <0 ) +return sub_lf; + + ret =overlay_clear_overwritten_local_fixups (fdt, sub_lf, + fdto, subnode); +if (ret) +return ret; + } + +return 0 ; +} +
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1322
Quoted 10 lines
libfdt/fdt_overlay.c +10
-0+/** +* overlay_add_local_fixup_offset - Insert a sorted u32 offset into a local fixup property +* @fdt: Base Device Tree blob +* @lf_node: Node offset in @fdt's /__local_fixups__ subtree +* @name: Property name to update +* @name_len: Length of @name in bytes +* @poffset: Byte offset of the phandle reference within the target property +* +* overlay_add_local_fixup_offset() inserts @poffset in ascending sorted order +* (ignoring duplicates) into the u32 array property @name on @lf_node.
Does the spec actually require that these offsets be sorted? A reference to that requirement might be useful here.
Quoted 15 lines
libfdt/fdt_overlay.c +15
-0+* +* returns: +* 0 on success +* Negative error code on failure +*/ +static int overlay_add_local_fixup_offset (void *fdt,int lf_node, +const char *name,int name_len, +uint32_t poffset) +{ +const fdt32_t *old_val; +fdt32_t *vals; +void *prop_data; +int old_len, count, i, idx, ret; + + old_val =fdt_getprop_namelen (fdt, lf_node, name, name_len, &old_len);
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1347
Quoted 10 lines
libfdt/fdt_overlay.c +10
-0+if (!old_val && old_len != -FDT_ERR_NOTFOUND ) +return old_len; + +if (!old_val) { + old_len =0 ; + count =0 ; + idx =0 ; + }else { +if (old_len %sizeof (uint32_t )) +return -FDT_ERR_BADSTRUCTURE ;
This should probably be BADVALUE rather than BADSTRUCTURE.
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1354
Quoted 7 lines
libfdt/fdt_overlay.c +7
-0+ count = old_len /sizeof (uint32_t ); + idx = count; +for (i =0 ; i < count; i++) { +uint32_t cur =fdt32_ld (old_val + i); + +if (cur == poffset) +return 0 ;
I'm trying to think under what circumstances this would occur. Does it indicate a bad overlay if we're attempting to add a fixup that already exists?
Quoted 20 lines
libfdt/fdt_overlay.c +20
-0+if (cur > poffset) { + idx = i; +break ; + } + } + } + + ret =fdt_setprop_placeholder_namelen (fdt, lf_node, name, name_len, + old_len +sizeof (uint32_t ), + &prop_data); +if (ret) +return ret; + + vals = prop_data; +if (idx < count) +memmove (vals + idx +1 , vals + idx, + (count - idx) *sizeof (uint32_t )); +fdt32_st (vals + idx, poffset); + +return 0 ;
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1384
Quoted 10 lines
libfdt/fdt_overlay.c +10
-0+} + +/** +* overlay_merge_fixup_into_local_fixups - Record one /__fixups__ property for a fragment +* @fdt: Base Device Tree blob +* @fdto: Device tree overlay blob +* @property: Property offset in @fdto's /__fixups__ node +* @fragment: Node offset of the current fragment in @fdto +* @target_frag_name: Name of @fragment +* @target_frag_len: Length of @target_frag_name in bytes
fdt_get_name() is a pretty cheap operation. Might be simpler to allow this function to derive the @target_frag_* values from @fragment.
Quoted 36 lines
libfdt/fdt_overlay.c +36
-0+* @target_lfp: In/out cached node offset of @fragment under @fdt's /__local_fixups__ +* +* overlay_merge_fixup_into_local_fixups() parses all "path:prop:offset" entries +* in a single /__fixups__ property of @fdto and adds the resolved property +* byte offsets belonging to @fragment into @fdt's /__local_fixups__ subtree. +* +* returns: +* 0 on success +* Negative error code on failure +*/ +static int overlay_merge_fixup_into_local_fixups(void *fdt, const void *fdto, + int property, int fragment, + const char *target_frag_name, + int target_frag_len, + int *target_lfp) +{ + const char *value, *label; + int len; + + value = fdt_getprop_by_offset(fdto, property, &label, &len); + if (!value) + return len; + + do { + const char *path, *name, *frag_name, *rel_path; + uint32_t path_len, name_len, poffset; + int frag_name_len, rel_path_len, lf_node, ret; + bool is_overlay; + + ret = overlay_parse_fixup_entry(&value, &len, &path, &path_len, + &name, &name_len, &poffset); + if (ret) + return ret; + + ret = overlay_split_fragment_path(path, path_len, + &frag_name, &frag_name_len,
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1430
Quoted 10 lines
libfdt/fdt_overlay.c +10
-0+ &rel_path, &rel_path_len, + &is_overlay); +if (ret) +return ret; +if (!is_overlay) +continue ; + +if (frag_name_len != target_frag_len || +memcmp (frag_name, target_frag_name, frag_name_len) !=0 ) +continue ;
Why filter by target fragment? Neither the __fixups__ node you're working from, nor the __local_fixups__ node you're updating is naturally divided by fragment.
Quoted 51 lines
libfdt/fdt_overlay.c +51
-0+if (*target_lfp <0 ) { + *target_lfp =overlay_fragment_local_fixups ( + fdt, fdto, fragment, true); +if (*target_lfp <0 ) +return *target_lfp; + } + + lf_node =overlay_create_path (fdt, *target_lfp, rel_path, + rel_path_len); +if (lf_node <0 ) +return lf_node; + + ret =overlay_add_local_fixup_offset (fdt, lf_node, name, + name_len, poffset); +if (ret) +return ret; + }while (len >0 ); + +return 0 ; +} + +/** +* overlay_merge_fixups_into_local_fixups - Record resolved /__fixups__ for a fragment +* @fdt: Base Device Tree blob +* @fdto: Device tree overlay blob +* @fragment: Node offset of the current fragment in @fdto +* @frag_name: Name of @fragment +* @frag_name_len: Length of @frag_name in bytes +* @target_lfp: In/out cached node offset of @fragment under @fdt's /__local_fixups__ +* +* overlay_merge_fixups_into_local_fixups() parses external phandle references +* belonging to @fragment in @fdto's /__fixups__ node and records their resolved +* property byte offsets in @fdt's /__local_fixups__ subtree. +* +* returns: +* 0 on success +* Negative error code on failure +*/ +static int overlay_merge_fixups_into_local_fixups (void *fdt,const void *fdto, +int fragment, +const char *frag_name, +int frag_name_len, +int *target_lfp) +{ +int fixups_off, prop; + + fixups_off =fdt_subnode_offset (fdto,0 ,"__fixups__" ); +if (fixups_off == -FDT_ERR_NOTFOUND ) +return 0 ; +if (fixups_off <0 ) +return fixups_off;
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1492
Quoted 10 lines
libfdt/fdt_overlay.c +10
-0+ +fdt_for_each_property_offset (prop, fdto, fixups_off) { +int ret; + + ret =overlay_merge_fixup_into_local_fixups ( + fdt, fdto, prop, fragment, frag_name, frag_name_len, + target_lfp); +if (ret) +return ret; + }
Is there a reason to do this as a post-processing pass, rather than making the __local_fixups__ adjustment at the same time we already process the fixup in overlay_fixup_phandle()?
Quoted 10 lines
libfdt/fdt_overlay.c +10
-0+return 0 ; +} + +/** +* overlay_prune_empty_local_fixups - Remove empty subnodes from /__local_fixups__ +* @fdt: Base Device Tree blob +* @lf_node: Node offset in @fdt's /__local_fixups__ subtree +* +* overlay_prune_empty_local_fixups() recursively deletes any child subnodes +* under @lf_node that have neither properties nor subnodes remaining.
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1513
Quoted 10 lines
libfdt/fdt_overlay.c +10
-0+* +* returns: +* 0 on success +* Negative error code on failure +*/ +static int overlay_prune_empty_local_fixups (void *fdt,int lf_node) +{ +int subnode =fdt_first_subnode (fdt, lf_node); + +while (subnode >=0 ) {
We should propagate the error if subnode < 0 but is not -FDT_ERR_NOTFOUND.
Quoted 22 lines
libfdt/fdt_overlay.c +22
-0+int next, ret; + + ret =overlay_prune_empty_local_fixups (fdt, subnode); +if (ret <0 ) +return ret; + + next =fdt_next_subnode (fdt, subnode); +if (fdt_first_property_offset (fdt, subnode) == -FDT_ERR_NOTFOUND && +fdt_first_subnode (fdt, subnode) == -FDT_ERR_NOTFOUND ) { +int old_struct_size =fdt_size_dt_struct (fdt); + + ret =fdt_del_node (fdt, subnode); +if (ret <0 ) +return ret; +if (next >=0 ) + next +=fdt_size_dt_struct (fdt) - + old_struct_size; + } + subnode = next; + } + +return 0 ;
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1545
Quoted 10 lines
libfdt/fdt_overlay.c +10
-0+} + +/** +* overlay_validate_local_fixups - Validate /__local_fixups__ fragment nodes in overlay +* @fdto: Device tree overlay blob +* @ov_lf_root: Node offset of /__local_fixups__ in @fdto +* +* overlay_validate_local_fixups() verifies that every fragment subnode under +* @ov_lf_root that contains an __overlay__ subnode corresponds to a valid +* fragment node at the root of @fdto.
What's the reason for doing this as a pre-validation pass, rather than checking this as we go to process each individual local_fixups entry?
Quoted 236 lines
libfdt/fdt_overlay.c +192
-0+* +* returns: +* 0 on success +* Negative error code on failure +*/ +static int overlay_validate_local_fixups (const void *fdto,int ov_lf_root) +{ +int lf_frag; + +fdt_for_each_subnode (lf_frag, fdto, ov_lf_root) { +const char *frag_name; +int frag_name_len, lf_overlay, fragment; + + frag_name =fdt_get_name (fdto, lf_frag, &frag_name_len); +if (!frag_name) +return frag_name_len; + + lf_overlay =fdt_subnode_offset (fdto, lf_frag,"__overlay__" ); +if (lf_overlay == -FDT_ERR_NOTFOUND ) +continue ; +if (lf_overlay <0 ) +return lf_overlay; + + fragment =fdt_subnode_offset_namelen (fdto,0 , frag_name, + frag_name_len); +if (fragment <0 ) +return -FDT_ERR_BADOVERLAY ; + +if (fdt_subnode_offset (fdto, fragment,"__overlay__" ) <0 ) +return -FDT_ERR_BADOVERLAY ; + } + +return 0 ; +} + +/** +* overlay_fragment_local_fixups_src - Find a fragment's __overlay__ in overlay /__local_fixups__ +* @fdto: Device tree overlay blob +* @ov_lf_root: Node offset of /__local_fixups__ in @fdto (or -FDT_ERR_NOTFOUND) +* @frag_name: Name of the fragment node +* @frag_name_len: Length of @frag_name in bytes +* +* overlay_fragment_local_fixups_src() locates the __overlay__ subnode for +* @frag_name under @ov_lf_root in @fdto. +* +* returns: +* Node offset of /__local_fixups__/<frag_name>/__overlay__ on success +* -FDT_ERR_NOTFOUND if @ov_lf_root, <frag_name>, or __overlay__ is absent +* Negative error code on other failures +*/ +static int overlay_fragment_local_fixups_src (const void *fdto,int ov_lf_root, +const char *frag_name, +int frag_name_len) +{ +int lf_frag; + +if (ov_lf_root <0 ) +return -FDT_ERR_NOTFOUND ; + + lf_frag =fdt_subnode_offset_namelen (fdto, ov_lf_root, frag_name, + frag_name_len); +if (lf_frag <0 ) +return lf_frag; + +return fdt_subnode_offset (fdto, lf_frag,"__overlay__" ); +} + +/** +* overlay_fragment_update_local_fixups - Update base /__local_fixups__ for one fragment +* @fdt: Base Device Tree blob +* @fdto: Device tree overlay blob +* @fragment: Node offset of the fragment in @fdto +* @ov_lf_root: Node offset of /__local_fixups__ in @fdto (or -FDT_ERR_NOTFOUND) +* +* overlay_fragment_update_local_fixups() clears any base /__local_fixups__ +* entries overwritten by @fragment, then merges phandle offsets for @fragment +* from @fdto's /__local_fixups__ and /__fixups__ subtrees. +* +* returns: +* 0 on success +* Negative error code on failure +*/ +static int overlay_fragment_update_local_fixups (void *fdt,const void *fdto, +int fragment,int ov_lf_root) +{ +const char *frag_name; +int frag_name_len, overlay, target_lf, lf_overlay, ret; + + overlay =fdt_subnode_offset (fdto, fragment,"__overlay__" ); +if (overlay == -FDT_ERR_NOTFOUND ) +return 0 ; +if (overlay <0 ) +return overlay; + + frag_name =fdt_get_name (fdto, fragment, &frag_name_len); +if (!frag_name) +return frag_name_len; + + target_lf =overlay_fragment_local_fixups (fdt, fdto, fragment, false); +if (target_lf <0 && target_lf != -FDT_ERR_NOTFOUND ) +return target_lf; + +if (target_lf >=0 ) { + ret =overlay_clear_overwritten_local_fixups (fdt, target_lf, + fdto, overlay); +if (ret) +return ret; + } + + lf_overlay =overlay_fragment_local_fixups_src (fdto, ov_lf_root, + frag_name, + frag_name_len); +if (lf_overlay <0 && lf_overlay != -FDT_ERR_NOTFOUND ) +return lf_overlay; + +if (lf_overlay >=0 ) { +if (target_lf <0 ) + target_lf =overlay_fragment_local_fixups (fdt, fdto, + fragment, + true); +if (target_lf <0 ) +return target_lf; + + ret =overlay_apply_node (fdt, target_lf, fdto, lf_overlay); +if (ret) +return ret; + } + +return overlay_merge_fixups_into_local_fixups ( + fdt, fdto, fragment, frag_name, frag_name_len, &target_lf); +} + +/** +* overlay_local_fixups_update - Update base /__local_fixups__ with overlay fixups +* @fdt: Base Device Tree blob +* @fdto: Device tree overlay blob +* +* overlay_local_fixups_update() updates the base device tree's +* /__local_fixups__ subtree (when present) by walking each overlay fragment in +* application order, clearing entries for properties overwritten by that +* fragment, and merging phandle reference offsets from @fdto's +* /__local_fixups__ and /__fixups__ subtrees. +* +* This is part of the device tree overlay application process, when you want +* the merged device tree to retain complete local phandle fixup metadata. +* +* returns: +* 0 on success +* Negative error code on failure +*/ +static int overlay_local_fixups_update (void *fdt,const void *fdto) +{ +int root_lf, ov_lf_root, fragment, ret; + + root_lf =fdt_subnode_offset (fdt,0 ,"__local_fixups__" ); +if (root_lf == -FDT_ERR_NOTFOUND ) +return 0 ; +if (root_lf <0 ) +return root_lf; + + ov_lf_root =fdt_subnode_offset (fdto,0 ,"__local_fixups__" ); +if (ov_lf_root >=0 ) { + ret =overlay_validate_local_fixups (fdto, ov_lf_root); +if (ret) +return ret; + }else if (ov_lf_root != -FDT_ERR_NOTFOUND ) { +return ov_lf_root; + } + +/* +* Process fragments in application order so that if a later fragment in +* fdto overwrites a property modified by an earlier fragment, the +* earlier fragment's local fixups for that property are cleared first. +*/ +fdt_for_each_subnode (fragment, fdto,0 ) { + ret =overlay_fragment_update_local_fixups (fdt, fdto, fragment, + ov_lf_root); +if (ret) +return ret; + } + + root_lf =fdt_subnode_offset (fdt,0 ,"__local_fixups__" ); +if (root_lf <0 ) +return root_lf; + +return overlay_prune_empty_local_fixups (fdt, root_lf); +} +int fdt_overlay_apply (void *fdt,void *fdto) {uint32_t delta;@@ -1162,6 +1771,10 @@ int fdt_overlay_apply(void *fdt, void *fdto)if (ret) goto err; + ret =overlay_local_fixups_update (fdt, fdto); +if (ret) + goto err; +/* * The overlay has been damaged, erase its magic. */ tests/run_tests.sh +19
-0@@ -1089,6 +1089,25 @@ fdtoverlay_tests() { shorten_echo "check phandle to noda d wasn't overwritten: " run_wrap_test test "$bd" = "$pd" + + # verify that /__local_fixups__ in a -L base blob is updated when applying an overlay + run_dtc_test -@ -L -I dts -O dtb -o overlay_base_phandle_lf.test.dtb "$SRCDIR/overlay_base_phandle.dts" + run_wrap_test $FDTOVERLAY -i overlay_base_phandle_lf.test.dtb -o overlay_base_phandle_lfO.test.dtb overlay_overlay_phandle.test.dtb + run_fdtget_test 0 overlay_base_phandle_lfO.test.dtb /__local_fixups__/b a + run_fdtget_test 0 overlay_base_phandle_lfO.test.dtb /__local_fixups__/b d + run_fdtget_test 0 overlay_base_phandle_lfO.test.dtb /__local_fixups__/c b + run_fdtget_test 0 overlay_base_phandle_lfO.test.dtb /__local_fixups__/d a + run_fdtget_test 0 overlay_base_phandle_lfO.test.dtb /__local_fixups__/d b + run_fdtget_test 0 overlay_base_phandle_lfO.test.dtb /__local_fixups__/d c + + run_dtc_test -@ -L -I dts -O dtb -o overlay_base_lf.test.dtb "$SRCDIR/overlay_base.dts" + run_wrap_test $DTPUT overlay_base_lf.test.dtb -cp /__local_fixups__/test-node/sub-test-node + run_wrap_test $DTPUT overlay_base_lf.test.dtb /__local_fixups__/test-node/sub-test-node new-sub-test-property -tu 0 + run_dtc_test -@ -I dts -O dtb -o overlay_overlay.fdtoverlay.test.dtb "$SRCDIR/overlay_overlay.dts" + run_wrap_test $FDTOVERLAY -i overlay_base_lf.test.dtb -o overlay_base_lfO.test.dtb overlay_overlay.fdtoverlay.test.dtb + run_fdtget_test "0 4" overlay_base_lfO.test.dtb /__local_fixups__/test-node test-phandle + run_fdtget_test "0 4" overlay_base_lfO.test.dtb /__local_fixups__/test-node test-several-phandle + run_test check_path overlay_base_lfO.test.dtb not-exists "/__local_fixups__/test-node/sub-test-node" } pylibfdt_tests () {Signature · 1 line
2.56.0.313.g2479322e68-goog
Signature · 4 lines
David Gibson (he or they) | I'll have my music baroque, and my code david AT gibson.dropbear.id.au | minimalist, thank you, not the other way | around. http://www.ozlabs.org/~dgibson
Re: [PATCH v2 01/10] pylibfdt: Fix FdtSw.as_fdt() when buffer is nearly full
In reply to Douglas AndersonQuoted 12 lines · Douglas Anderson
pylibfdt: Fix
FdtSw.as_fdt()when buffer is nearly full
FdtSw.as_fdt()callsfdt_finish()on a copy ofself._fdtwithout usingself.check_space(). Becausefdt_finish()appends the 4-byteFDT_ENDtoken,as_fdt()raisesFdtException(FDT_ERR_NOSPACE)if fewer than 4 bytes of free space remain inself._fdtafter the finalend_node().Wrap
fdt_finish()in awhile self.check_space(fdt_finish(fdtsw)):loop soFdtSw.as_fdt()automatically resizes the buffer when needed, matching the rest ofFdtSw's methods.
Quoted 6 lines
Assisted-by Gemini:gemini-pro-prereleaseSigned-off-by Douglas Anderson <[email protected]>pylibfdt/libfdt.i | 3 ++- tests/pylibfdt_tests.py | 8 ++++++++ 2 files changed, 10 insertions(+), 1 deletion(-)
Re: [PATCH v2 02/10] pylibfdt: Add subnode/property iterators and get_mem_rsv_list()
In reply to Douglas AndersonHi Doug,
Quoted 22 lines · Douglas Anderson
pylibfdt: Add subnode/property iterators and
get_mem_rsv_list()Add Pythonic iterator helpers on
FdtRoto simplify walking nodes, properties, and memory reservation entries without manual offset loops or-FDT_ERR_NOTFOUNDsentinel handling:-
subnodes(nodeoffset): yields the offset of each direct child subnode ofnodeoffset.
-properties(nodeoffset): yields aPropertyobject for each property ofnodeoffset.
-get_mem_rsv_list(): returns a list of(address, size)tuples for all entries in the memory reservation block.Assisted-by Gemini:gemini-pro-prereleaseSigned-off-by Douglas Anderson <[email protected]>pylibfdt/libfdt.i | 45 +++++++++++++++++++++++++++++++++++++++++++++ tests/pylibfdt_tests.py | 18 ++++++++++++++++++ 2 files changed, 63 insertions(+)
pylibfdt/libfdt.i class FdtRo(object): · line 204
Quoted 4 lines
pylibfdt/libfdt.i +4
-0@@ -201,6 +201,23 @@ class FdtRo(object): + soff = self.first_subnode(nodeoffset, quiet=QUIET_NOTFOUND) + while soff >= 0: + yield soff + soff = self.next_subnode(soff, quiet=QUIET_NOTFOUND)
Since Fdt inherits this generator, a caller can easily write 'for off in fdt.subnodes(0): fdt.del_node(off)' and get garbage, because the offsets move under it. Since David has applied this, please can you send a follow-up noting in the docstring (here and in properties()) that the tree must not be modified while iterating, as with fdt_for_each_subnode() in C?
tests/pylibfdt_tests.py class PyLibfdtBasicTests(unittest.TestCase): · line 244
Quoted 4 lines
tests/pylibfdt_tests.py +2
-0@@ -243,6 +243,22 @@ class PyLibfdtBasicTests(unittest.TestCase): + leaf = self.fdt.path_offset('/subnode@1/ss1') + self.assertEqual(list(self.fdt.subnodes(leaf)), [])
The docstrings say both iterators raise FdtException for a bad offset, but nothing tests that. A test that list(self.fdt.subnodes(-1)) and list(self.fdt.properties(-1)) raise, perhaps alongside testFirstNextSubnodeOffsetExceptions, would be good, perhaps in the same follow-up. Since these are generators, the exception only appears on the first next(), not when the method is called.
Re: [PATCH v2 03/10] pylibfdt: Add NodeTree live tree representation
In reply to Douglas AndersonHi Doug,
Quoted 22 lines · Douglas Anderson
pylibfdt: Add NodeTree live tree representation
Add
NodeTree, an in-memory live tree representation of a devicetree node and its subtree, topylibfdt:-
NodeTree.unflatten(fdt, offset=0)builds aNodeTreehierarchy from anFdtRoinstance.
-NodeTree.flatten(mem_rsv=(), boot_cpuid_phys=0)serializes a rootNodeTreeback into a packed FDT blob viaFdtSw.
-get_node(),create_path(), andwalk()provide path lookup, intermediate node creation, and pre-order traversal.
-get_str(),set_str(),get_stringlist(),set_stringlist(),get_u32(),set_u32(),get_u32_list(), andset_u32_list()provide typed property access and mutation (updatingProperty.as_str()andProperty.as_stringlist()so emptyb''properties raiseValueErroror return[]rather thanIndexError).Add unit tests in
tests/pylibfdt_tests.pycoveringNodeTreeunflatten/flatten round-tripping and helper methods. [...]
Quoted 8 lines
pylibfdt/libfdt.i | 262 +++++++++++++++++++++++++++++++++++++++++++++++- tests/pylibfdt_tests.py | 54 ++++++++++ 2 files changed, 315 insertions(+), 1 deletion(-)provide typed property access and mutation (updating
Property.as_str()andProperty.as_stringlist()so emptyb''properties raiseValueErroror return[]rather thanIndexError).
When you split this out (as David suggests), please can you add tests that call Property directly rather than only going through NodeTree?
pylibfdt/libfdt.i class NodeAdder(): · line 1217
Quoted 8 lines
pylibfdt/libfdt.i +6
-0@@ -1210,6 +1212,264 @@ class NodeAdder(): + node = cls() + for prop in fdt.properties(offset): + node.props[prop.name] = bytes(prop) + for suboff in fdt.subnodes(offset): + node.children[fdt.get_name(suboff)] = cls.unflatten(fdt, suboff) + return node
If a blob has two sibling nodes (or two properties) with the same name, one is silently dropped. I checked with FdtSw: with two 'a' subnodes under the root, only the second survives. libfdt does not reject such blobs and fdtfactor reads input it does not control, so I think it is better to raise ValueError here than to quietly throw data away.
pylibfdt/libfdt.i class NodeAdder(): · line 1215
Quoted 6 lines
pylibfdt/libfdt.i +4
-0@@ -1210,6 +1212,264 @@ class NodeAdder(): + self._flatten_subtree(sw, '') + fdt = sw.as_fdt() + fdt_set_boot_cpuid_phys(fdt._fdt, boot_cpuid_phys) + fdt.pack()
This reaches into fdt._fdt and calls the raw SWIG function. It would be worth adding Fdt.set_boot_cpuid_phys() to go with the existing FdtRo.boot_cpuid_phys(), and calling that instead.
pylibfdt/libfdt.i class NodeAdder(): · line 1218
Quoted 9 lines
pylibfdt/libfdt.i +7
-0@@ -1210,6 +1212,264 @@ class NodeAdder(): +class NodeTree: + """In-memory live tree representation of a devicetree node and its subtree. + + Attributes: + props: Dict mapping property name (str) to raw property value (bytes). + children: Dict mapping child node name (str) to child NodeTree. + """
BTW in patch 7, fdtfactor adds 'phandle' and 'fixups' attributes to NodeTree objects on the fly, so they carry attributes the class does not declare. Since unflatten() uses cls and create_path() uses type(self), subclassing already works, so a small subclass in fdtfactor declaring these two attributes would be cleaner. What do you think?
Regards,
Simon
Re: [PATCH v2 04/10] libfdt: overlay: Factor out fixup and fragment path parsing helpers
In reply to Douglas AndersonQuoted 14 lines · Douglas Anderson
libfdt: overlay: Factor out fixup and fragment path parsing helpers
In preparation for updating the base device tree's
/__local_fixups__node duringfdt_overlay_apply(), factor out two helper functions inlibfdt/fdt_overlay.c:- Factor out
overlay_parse_fixup_entry()fromoverlay_fixup_phandle()to parse"path:name:offset"entries in/__fixups__properties.
- Factor outoverlay_split_fragment_path()fromoverlay_symbol_update()to validate and split"/<fragment>/__overlay__[/<rel>]"paths into the fragment name and relative subnode path.
Quoted 7 lines
This commit is pure code movement with no functional change.
Assisted-by Gemini:gemini-pro-prereleaseSigned-off-by Douglas Anderson <[email protected]>libfdt/fdt_overlay.c | 226 +++++++++++++++++++++++++++++++++++---------------- 1 file changed, 154 insertions(+), 72 deletions(-)
Re: [PATCH v2 05/10] libfdt: overlay: Prepare fixup and fragment path helpers for reuse
In reply to Douglas AndersonHi Doug,
Quoted 6 lines · Douglas Anderson
libfdt: overlay: Prepare fixup and fragment path helpers for reuse
Clean up
overlay_parse_fixup_entry()and generalizeoverlay_split_fragment_path()inlibfdt/fdt_overlay.cso both can be reused when updating/__local_fixups__:
Quoted 8 lines
- Change
poffsetfrominttouint32_tinoverlay_fixup_one_phandle(),overlay_parse_fixup_entry(), andoverlay_fixup_phandle(), and parse intounsigned longbefore validating the range.
- Require*(sep + 1)to be an ASCII digit ('0'..'9') and boundpoffsettoINT32_MAX - sizeof(uint32_t)so negative strings (such as"-4"), leading whitespace, or large values cannot silently truncate or wrap around infdt_setprop_inplace_namelen_partial().
This is more than a clean-up: it fixes an existing out-of-bounds write in fdt_overlay_apply(). With a /__fixups__ entry like '/fragment@0/__overlay__/node:prop:-4', strtoul() gives -4 as an int, which reaches fdt_setprop_inplace_namelen_partial() as idx = 0xfffffffc. Then 'len + idx' wraps to 0, the 'proplen < len + idx' check passes and memcpy() writes 4 bytes before the property value. On 64-bit, '4294967292' does the same. Overlays may well be untrusted, so please can you split this into its own patch at the start of the series, with a commit message that starts with the problem so it doesn't get lost under 'Prepare ... for reuse'?
libfdt/fdt_overlay.c static int overlay_parse_fixup_entry(const char **valuep, int *lenp, · line 402
Quoted 8 lines
libfdt/fdt_overlay.c +3
-1@@ -398,15 +398,17 @@ static int overlay_parse_fixup_entry(const char **valuep, int *lenp, +if ((*(sep +1 ) <'0' ) || (*(sep +1 ) >'9' )) +return -FDT_ERR_BADOVERLAY ; poffset =strtoul (sep +1 , &endptr,10 ); -if ((*endptr !='\0' ) || (endptr <= (sep +1 ))) +if ((*endptr !='\0' ) || (poffset > (INT32_MAX -sizeof (uint32_t ))))return -FDT_ERR_BADOVERLAY ;
The real cause is the wrapping check in fdt_setprop_inplace_namelen_partial(). That function is public, so any caller passing a large idx hits the same overflow. I suggest fixing it there with something like:
if (idx > (unsigned)proplen || (unsigned)len > (unsigned)proplen - idx)
return -FDT_ERR_NOSPACE;and keeping the digit check here so that '+4' and ' 4' are still rejected. The INT32_MAX bound then becomes an early rejection rather than what keeps memory safe. What do you think?
A test in tests/ checking that fdt_overlay_apply() returns -FDT_ERR_BADOVERLAY for an overlay with a negative or oversized fixup offset would also be good.
libfdt/fdt_overlay.c static int overlay_parse_fixup_entry(const char **valuep, int *lenp,
Quoted 10 lines
libfdt/fdt_overlay.c +0
-2- Drop the redundant `*sep != ':'` checks after `memchr(..., ':', ...)`. - Generalize `overlay_split_fragment_path()` to accept a length-bounded `path` slice that is not necessarily NUL-terminated (using `memchr()` instead of `strchr()`, and keeping the NUL-terminated property check in `overlay_symbol_update()`) so it can also split `:`-delimited paths from `/__fixups__`. libfdt/fdt_overlay.c | 46 ++++++++++++++++++++++---------------------- 1 file changed, 24 insertions(+), 22 deletions(-)
Regards,
Simon
Re: [PATCH v2 06/10] libfdt: overlay: Update base /__local_fixups__ on apply
In reply to Douglas AndersonHi Doug,
Quoted 9 lines · Douglas Anderson
libfdt: overlay: Update base /__local_fixups__ on apply
When a base device tree is compiled with
dtc -L(--local-fixups), it contains a root/__local_fixups__node recording the byte offsets of all phandle references in its properties.Previously,
fdt_overlay_apply()updated the base tree's/__symbols__viaoverlay_symbol_update(), but left the base tree's/__local_fixups__untouched. As a result, applying an overlay to a
Please can you put the motivation first and use the present tense ('fdt_overlay_apply() updates /__symbols__ but leaves /__local_fixups__ untouched...')? It would also help to say why anyone needs an accurate /__local_fixups__ in the merged tree. Patch 8 gives the reason (an OS that wants to know which cells hold phandles, and the merged tree matching what 'dtc -L' produces), and that belongs here, since this patch changes behaviour for every libfdt user.
Quoted 19 lines
base tree with
/__local_fixups__left/__local_fixups__missing the phandle references introduced by the overlay (both from the overlay's/__local_fixups__and from its resolved/__fixups__), and left stale offsets if the overlay overwrote a base property that previously had phandle references.Add
overlay_local_fixups_update()to update the base tree's/__local_fixups__whenever/__local_fixups__is present in the base tree:- Remove pre-existing
/__local_fixups__properties for any base [...]libfdt/fdt_overlay.c | 621 ++++++++++++++++++++++++++++++++++++++++++++++++++- tests/run_tests.sh | 19 ++ 2 files changed, 636 insertions(+), 4 deletions(-)
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1127
Quoted 7 lines
libfdt/fdt_overlay.c +7
-0@@ -1122,6 +1121,616 @@ static int overlay_symbol_update(void *fdt, void *fdto) + next_lf =fdt_subnode_offset_namelen (fdt, node, name, namelen); +if (next_lf == -FDT_ERR_NOTFOUND && create) { +char namebuf[256 ]; +int old_struct_size =fdt_size_dt_struct (fdt); + +if ((size_t )namelen >=sizeof (namebuf)) +return -FDT_ERR_INTERNAL ;
I can see why the copy is needed, since the name is in the same blob and fdt_add_subnode_namelen() may move it. But libfdt has no limit on node-name length, so a valid tree with a long name makes fdt_overlay_apply() fail with -FDT_ERR_INTERNAL, which is meant for libfdt bugs. It also puts 256 bytes on the stack in code that runs in bootloaders. Please can you either avoid the copy (e.g. by re-reading the name after the splice, adjusted by the delta) or at least return a proper error code and document the limit?
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1122
Quoted 4 lines
libfdt/fdt_overlay.c +2
-0@@ -1122,6 +1121,616 @@ static int overlay_symbol_update(void *fdt, void *fdto) +if (old_len %sizeof (uint32_t )) +return -FDT_ERR_BADSTRUCTURE ;
-FDT_ERR_BADSTRUCTURE means the structure block is corrupt. Elsewhere in this file (e.g. overlay_symbol_update()) a badly sized property value gives -FDT_ERR_BADVALUE, and if the property came from the overlay's /__local_fixups__, -FDT_ERR_BADOVERLAY fits better.
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1123
Quoted 5 lines
libfdt/fdt_overlay.c +3
-0@@ -1122,6 +1121,616 @@ static int overlay_symbol_update(void *fdt, void *fdto) +static int overlay_validate_local_fixups (const void *fdto,int ov_lf_root) +{ +int lf_frag;
Just to check, is this needed? overlay_update_local_references() already walks the overlay's /__local_fixups__ against the overlay tree from the root, returning -FDT_ERR_BADOVERLAY if a node is missing. So by this point each /__local_fixups__/<frag>/__overlay__ is known to have a matching /<frag>/__overlay__ in fdto. If I have that right, this function and its call can go, which also helps with the size issue below.
libfdt/fdt_overlay.c int fdt_overlay_apply(void *fdt, void *fdto) · line 1773
Quoted 5 lines
libfdt/fdt_overlay.c +3
-0@@ -1162,6 +1771,10 @@ int fdt_overlay_apply(void *fdt, void *fdto) + ret =overlay_local_fixups_update (fdt, fdto); +if (ret) + goto err;
One thing I'd like to check before this goes in.. this changes what an exported function does. A base with /__local_fixups__ now needs more free space (so it can hit -FDT_ERR_NOSPACE where it did not before), and unrelated empty nodes under /__local_fixups__ get pruned. Please can you update the fdt_overlay_apply() comment in libfdt.h to describe the new behaviour?
Code size is also worth a look. With -Os, the fdt_overlay.c text grows from 3040 to 4904 bytes on Thumb-2 and from 4770 to 7983 on x86_64, about 60%. That code goes into things like U-Boot SPL, mostly for boards whose base has no /__local_fixups__ at all. Could this be made optional for size-sensitive users, or at least slimmed down? What do you think?
Regards,
Simon
Re: [PATCH v2 07/10] fdtfactor: Add tool to split DTBs into a base DTB and overlays
In reply to Douglas AndersonQuoted 31 lines · Douglas Anderson
fdtfactor: Add tool to split DTBs into a base DTB and overlays
When shipping a single firmware or kernel image that supports many closely related board variants or SKUs, bundling a full compiled .dtb for every variant results in substantial duplication.
Add
fdtfactor, a Python tool built onpylibfdtthat takes a set of compiled device tree blobs (.dtb) compiled with-@ -L(/__symbols__and/__local_fixups__) and splits them into a single commonbase.dtband per-board.dtbooverlays:- Common nodes present across all input DTBs are placed in
base.dtb, with each common property assigned the value shared by at least two boards that maximizes byte savings across overlays.
- Using/__local_fixups__, phandle references inside property values are normalized to target node paths so common properties referencing common nodes match even when numeric phandles differ across input DTBs.
- Any common node that carries a phandle in any input DTB receives its phandle inbase.dtbso overlays only emitphandleproperties on newly added subnodes, matching the requirements oflibfdt, Linux'sdrivers/of/overlay.c, and coreboot'sdt_apply_overlay().Add a
fdtfactortest suite intests/run_tests.shverifying that applying each generated.dtbotobase.dtbwithfdtoverlayreconstructs the original DTB (verified viadtbs_equal_unordered, including across input DTBs with shifted phandle numbers).Assisted-by Gemini:gemini-pro-prereleaseSigned-off-by Douglas Anderson <[email protected]>
Quoted 13 lines
Makefile | 2 +- README.md | 43 ++ fdtfactor | 814 +++++++++++++++++++++++++++++++++++++ meson.build | 1 + tests/Makefile.tests | 4 +- tests/fdtfactor_board1.dts | 38 ++ tests/fdtfactor_board2.dts | 36 ++ tests/fdtfactor_board3.dts | 34 ++ tests/fdtfactor_board3_shifted.dts | 34 ++ tests/meson.build | 2 +- tests/run_tests.sh | 65 ++- tests/testutils.sh | 1 + 12 files changed, 1067 insertions(+), 7 deletions(-)
Re: [PATCH v2 08/10] fdtfactor: Add -S/--strip-local-fixups option
In reply to Douglas AndersonHi Doug,
Quoted 12 lines · Douglas Anderson
fdtfactor: Add -S/--strip-local-fixups option
By default,
fdtfactorpreserves/__local_fixups__onbase.dtbso that whenfdt_overlay_apply()merges a.dtbooverlay, the reconstructed device tree retains full/__local_fixups__information (for instance, if an OS kernel wants to know which property cells contain phandles at runtime).When
-Lwas passed todtcsolely to helpfdtfactorlocate phandle cells at build time and/__local_fixups__is not needed at runtime, retaining/__local_fixups__inbase.dtbwastes space.
Quoted 5 lines
Add
-S/--strip-local-fixupsto omit/__local_fixups__frombase.dtb(and therefore from the merged device trees produced byfdt_overlay_apply()). On a set of 47 Qualcomm SC7180 Trogdor Chromebook board DTBs,fdtfactor -Sreduces total uncompressed size from 7.69 MB to 634 KB (91.8% savings).
This compares against the unfactored DTBs, so it doesn't show what -S itself saves. Please can you also give the size without -S, so it is clear what the /__local_fixups__ in base.dtb costs?
Quoted 12 lines
Add a test case in
tests/run_tests.shverifying thatfdtfactor -Sfollowed byfdtoverlayreproduces DTBs compiled with-@(without [...]README.md | 9 +++++++++ fdtfactor | 34 ++++++++++++++++++++++++++-------- tests/run_tests.sh | 22 ++++++++++++++++++++++ 3 files changed, 57 insertions(+), 8 deletions(-)
tests/run_tests.sh fdtfactor_tests () { · line 1242
Quoted 9 lines
tests/run_tests.sh +9
-0@@ -1234,6 +1234,28 @@ fdtfactor_tests () { + # Strip local fixups (-S): verify that merged DTBs match DTBs compiled + # with -@ (without -L), and that inputs lacking /__local_fixups__ are + # rejected. + for i in 1 2 3; do + run_dtc_test -b 2 -@ -I dts -O dtb -o fdtfactor_board${i}.nolf.test.dtb \ + "$SRCDIR/fdtfactor_board${i}.dts" + done + run_wrap_error_test $PYTHON $FDTFACTOR -o fdtfactor_strip.test.dir \ + fdtfactor_board1.nolf.test.dtb fdtfactor_board2.test.dtb
This rejection test has no -S, so it checks the -L requirement from the previous patch rather than anything added here. Since -S could easily be read as 'my inputs don't need -L', I think it is more useful to pass -S here, to show that it does not relax that requirement. The plain no-S case could then go into the previous patch with the other rejection tests.
Regards,
Simon
Re: [PATCH v2 09/10] fdtfactor: Support compressed DTB inputs and outputs
In reply to Douglas AndersonQuoted 24 lines · Douglas Anderson
fdtfactor: Support compressed DTB inputs and outputs
Firmware and FIT image build pipelines frequently store device tree blobs compressed with LZ4, LZMA/XZ, or gzip (e.g.,
.dtb.lz4).Extend
fdtfactorto detect compressed input blobs by magic bytes or file extension, transparently decompress them before factoring, and compress the resulting.dtboandbase.dtboutputs when appropriate:- Support
.lz4(including legacy-lframes via thelz4CLI),.lzma/.xz(via Python'slzmamodule, usingCHECK_CRC32for XZ compatibility with kernel/bootloader decompressors), and.gz(via Python'sgzipmodule).
- Preserve the input compression format on generated.dtbofiles and compressbase.dtbaccording to--base-compression(which defaults toauto, auto-detecting from--base-dtb's filename extension such as-b base.dtb.lz4).
- Report compressed size savings alongside uncompressed savings when-s/--statsis specified.On the 47 Qualcomm SC7180 Trogdor Chromebook
.dtb.lz4files,fdtfactor -Sreduces total LZ4-compressed size from 1.71 MB to 213 KB (87.5% savings).
Quoted 8 lines
Assisted-by Gemini:gemini-pro-prereleaseSigned-off-by Douglas Anderson <[email protected]>README.md | 17 ++- fdtfactor | 312 +++++++++++++++++++++++++++++++++++++++++++++++---- tests/Makefile.tests | 5 +- tests/run_tests.sh | 77 ++++++++++++- 4 files changed, 379 insertions(+), 32 deletions(-)
Re: [PATCH v2 10/10] fdtfactor: Add compiled FIT image factoring support
In reply to Douglas AndersonQuoted 36 lines · Douglas Anderson
fdtfactor: Add compiled FIT image factoring support
Bootloaders such as depthcharge on Chromebooks and U-Boot use Flattened Image Tree (FIT) images to bundle a kernel image with multiple board FDT blobs (
fdt-1,fdt-2, ...) and per-board configuration nodes.Add
-F/--fit,--outfile, and--single-base-dtboptions tofdtfactorto factor a compiled FIT image directly:- Parse non-overlay
type = "flat_dt"nodes under/images, decompressing theirdatablobs according to theircompressionproperty (none,lz4,lzma,xz,gzip).
- Reject FIT images containingsignature*subnodes under/images/*or/configurations/*, as modifying FDT blobs and configurations would invalidate cryptographic signatures.
- Partition theflat_dtblobs into compatible factor groups (by compression, architecture, FDT header fields, and node-path overlap) so a single FIT image containing multiple board/SoC families produces a separatefdt-base-1,fdt-base-2, etc. for each family.
- Support--single-base-dtbto force allflat_dtblobs into a single base DTB regardless of node-path overlap, failing only if their FDT headers, architecture, or compression differ.
- Insert eachfdt-base-Nnode into/images, replace each factoredfdt-*node'sdatawith its compressed.dtbooverlay, recompute anyhash*subnode digests, and prependfdt-base-Nto each matching configuration'sfdtstring list while preserving all other configuration properties (description,compatible, etc., populatingcompatiblefrom the board DTB's root node when omitted) and any pre-existing overlay entries.Add uncompressed, LZ4-compressed multi-family, signed-FIT rejection, and
--single-base-dtbFIT image test cases to thefdtfactortest suite.Assisted-by Gemini:gemini-pro-prereleaseSigned-off-by Douglas Anderson <[email protected]>
Quoted 9 lines
README.md | 17 ++ fdtfactor | 588 ++++++++++++++++++++++++++++++++++++++++++--- tests/Makefile.tests | 2 +- tests/fdtfactor_lz4.its | 109 +++++++++ tests/fdtfactor_other1.dts | 33 +++ tests/fdtfactor_other2.dts | 33 +++ tests/fdtfactor_test.its | 109 +++++++++ tests/run_tests.sh | 158 +++++++++++- 8 files changed, 1018 insertions(+), 31 deletions(-)
BTW, 'FIT image' actually means an image in a FIT, so I think you should try to call the whole thing a 'FIT' instead.
Re: [PATCH v2 02/10] pylibfdt: Add subnode/property iterators and get_mem_rsv_list()
In reply to Simon GlassHi Simon,
Quoted 18 lines · Simon Glass
Quoted 18 lines
pylibfdt/libfdt.i +15
-0@@ -204,6 +204,23 @@ class FdtRo(object): + def subnodes(self, nodeoffset): + """Iterate over the subnodes of a node + + Args: + nodeoffset: Offset of parent node to check + + Yields: + Node offset of each direct subnode in order + + Raises: + FdtException on error (e.g. invalid nodeoffset) + """ + soff = self.first_subnode(nodeoffset, quiet=QUIET_NOTFOUND) + while soff >= 0: + yield soff
Quoted 8 lines
pylibfdt/libfdt.i class FdtRo(object): · line 219
Quoted 1 line
pylibfdt/libfdt.i +1
-0+ soff = self.next_subnode(soff, quiet=QUIET_NOTFOUND)Since Fdt inherits this generator, a caller can easily write 'for off in
fdt.subnodes(0):fdt.del_node(off)' and get garbage, because the offsets move under it. Since David has applied this, please can you send a follow-up noting in the docstring (here and inproperties()) that the tree must not be modified while iterating, as withfdt_for_each_subnode()in C?
Done. Added a patch in v3 ("pylibfdt: Clarify iterator docstrings and test negative offsets") noting in both subnodes() and properties() that the tree must not be modified while iterating.
Quoted 7 lines
Quoted 7 lines
tests/pylibfdt_tests.py +5
-0@@ -243,6 +243,21 @@ class PyLibfdtBasicTests(unittest.TestCase): + self.assertEqual( + [self.fdt.get_name(n) for n in self.fdt.subnodes(0)], + ['subnode@1', 'subnode@2'], + ) + leaf = self.fdt.path_offset('/subnode@1/ss1')
Quoted 8 lines
tests/pylibfdt_tests.py class PyLibfdtBasicTests(unittest.TestCase): · line 251
Quoted 1 line
tests/pylibfdt_tests.py +1
-0+ self.assertEqual(list(self.fdt.subnodes(leaf)), [])The docstrings say both iterators raise FdtException for a bad offset, but nothing tests that. A test that list(self.fdt.subnodes(-1)) and list(self.fdt.properties(-1)) raise, perhaps alongside testFirstNextSubnodeOffsetExceptions, would be good, perhaps in the same follow-up. Since these are generators, the exception only appears on the first
next(), not when the method is called.
Added the test for list(self.fdt.properties(-1)) raising FdtException (-libfdt.BADOFFSET) in testPropertyOffsetExceptions.
For subnodes(), it turns out fdt_first_subnode() and fdt_next_subnode() in libfdt/fdt.c map all negative returns from fdt_next_node() to -FDT_ERR_NOTFOUND (if (offset < 0 || depth != 1) return -FDT_ERR_NOTFOUND;, and fdt_next_node() treats offset < 0 as starting before the root node), so subnodes() never raises FdtException on a bad offset. I removed the inaccurate Raises: section from subnodes()'s docstring in the same follow-up patch.
-Doug
Re: [PATCH v2 03/10] pylibfdt: Add NodeTree live tree representation
In reply to David GibsonHi David,
Quoted 23 lines · David Gibson
Quoted 17 lines · Douglas Anderson
Add a
NodeTreeclass topylibfdtto provide an in-memory live tree representation of a devicetree node and its subtree.While
FdtRo/Fdt/FdtSwoperate on flat binary blobs by node and property offsets, tools that inspect, compare, or transform whole device trees are much simpler when manipulating a Python tree of nodes and properties.
NodeTreeprovides:
-NodeTree.unflatten(fdt, offset=0)andtree.flatten(...)to convert betweenFdtRoblobs andNodeTreehierarchies.
-get_node(path),create_path(path), andwalk(path='')for path navigation and pre-order traversal.
- Typed property getters and setters (get_str(),set_str(),get_stringlist(),set_stringlist(),get_u32(),set_u32(),get_u32_list(),set_u32_list()).Quoted 3 lines
Also fix
Property.as_str()andProperty.as_stringlist()when called on an emptyb''property soas_str()raisesValueErrorinstead ofIndexErrorandas_stringlist()returns[].
Quoted 7 lines
Thanks for splitting this out as suggested. However, on consideration, I don't think it really belongs in pylibfdt: the "f" in there refers to "flattened" and this is, explicitly, a non-flattened data structure. I have sometimes thought about adding a library for handling non-flattened trees, although I wasn't thinking something Python specific. I think for now let's move this to its own Python file / module.
Done. I've moved it out of pylibfdt/libfdt.i into its own devicetree.py module.
Quoted 15 lines
Quoted 15 lines
pylibfdt/libfdt.i +1
-1@@ -929,14 +929,16 @@ class Property(bytearray): def as_str(self): """Unicode is supported by decoding from UTF-8""" - if self[-1] != 0: + if not self or self[-1] != 0: raise ValueError('Property lacks nul termination') if 0 in self[:-1]: raise ValueError('Property contains embedded nul characters') return self[:-1].decode('utf-8')
Quoted 10 lines
pylibfdt/libfdt.i class Property(bytearray): · line 944
Quoted 7 lines
pylibfdt/libfdt.i +2
-0def as_stringlist(self): """Unicode is supported by decoding from UTF-8""" + if not self: + return [] if self[-1] != 0: raise ValueError('Property lacks nul termination') parts = self[:-1].split(b'\x00')The two hunks above are good fixes, but unrelated to the bulk of the patch.
Split out into a separate patch ("pylibfdt: Handle empty properties in as_str() and as_stringlist()") with direct unit tests for Property.
Quoted 8 lines
pylibfdt/libfdt.i class NodeAdder(): · line 1219
Quoted 5 lines
pylibfdt/libfdt.i +1
-0@@ -1214,6 +1216,261 @@ class NodeAdder(): self._fdt.end_node() +class NodeTree:Maybe class DeviceTree? The "node" doesn't really add any useful information.
Done. Renamed to DeviceTree (in devicetree.py).
Quoted 15 lines
Quoted 4 lines
pylibfdt/libfdt.i +4
-0+ @classmethod + def unflatten(cls, fdt, offset=0): + """Unflatten an FdtRo subtree starting at `offset` into a NodeTree. +pylibfdt/libfdt.i class NodeAdder(): · line 1242
Quoted 10 lines
pylibfdt/libfdt.i +10
-0+ Args: + fdt: An `FdtRo` (or `Fdt`) instance. + offset: Starting node offset (default 0 for the root node). + + Returns: + A `NodeTree` representing the node at `offset` and its descendants. + """ + node = cls() + for prop in fdt.properties(offset): + node.props[prop.name] = bytes(prop)
Quoted 7 lines
Since we already rely on class Property from libfdt.i, it seems like it would be a little more natural to have the dictionary values be class Property instances. Yes, that technically has some redundant storage of the property names, but we're not particularly concerned about optimisation for this Python library. Plus, Python's assign-by-reference should mean it's generally just a duplicated pointer, not a whole duplicated string.
Done. node.props now maps property names to libfdt.Property instances, which also simplifies get_str(), get_stringlist(), get_u32(), and get_u32_list().
Quoted 6 lines
pylibfdt/libfdt.i class NodeAdder(): · line 1279
Quoted 4 lines
pylibfdt/libfdt.i +4
-0+ fdt = sw.as_fdt() + fdt_set_boot_cpuid_phys(fdt._fdt, boot_cpuid_phys) + fdt.pack() + return bytes(fdt.as_bytearray())For better symmetry with
unflatten(), I'd suggest returning the Fdt
Done. flatten() now returns the packed libfdt.Fdt instance.
-Doug
Re: [PATCH v2 03/10] pylibfdt: Add NodeTree live tree representation
In reply to Simon GlassHi Simon,
Quoted 13 lines · Simon Glass
Quoted 13 lines
pylibfdt/libfdt.i +1
-1@@ -929,14 +929,16 @@ class Property(bytearray): def as_str(self): """Unicode is supported by decoding from UTF-8""" - if self[-1] != 0: + if not self or self[-1] != 0: raise ValueError('Property lacks nul termination') if 0 in self[:-1]: raise ValueError('Property contains embedded nul characters') return self[:-1].decode('utf-8')
Quoted 10 lines
pylibfdt/libfdt.i class Property(bytearray): · line 944
Quoted 7 lines
pylibfdt/libfdt.i +2
-0def as_stringlist(self): """Unicode is supported by decoding from UTF-8""" + if not self: + return [] if self[-1] != 0: raise ValueError('Property lacks nul termination') parts = self[:-1].split(b'\x00')When you split this out (as David suggests), please can you add tests that call Property directly rather than only going through NodeTree?
Done. Split into its own patch ("pylibfdt: Handle empty properties in as_str() and as_stringlist()") with direct tests on libfdt.Property('empty', b'').
Quoted 10 lines
pylibfdt/libfdt.i class NodeAdder(): · line 1216
Quoted 3 lines
pylibfdt/libfdt.i +1
-0@@ -1214,6 +1216,261 @@ class NodeAdder(): +class NodeTree:BTW in patch 7, fdtfactor adds 'phandle' and 'fixups' attributes to NodeTree objects on the fly, so they carry attributes the class does not declare. Since
unflatten()uses cls andcreate_path()uses type(self), subclassing already works, so a small subclass in fdtfactor declaring these two attributes would be cleaner. What do you think?
Good idea! In v3 fdtfactor defines a FactoredTree(devicetree.DeviceTree) subclass that initializes self.phandle = None and self.fixups = {} in __init__().
Quoted 7 lines
pylibfdt/libfdt.i class NodeAdder(): · line 1245
Quoted 6 lines
pylibfdt/libfdt.i +6
-0+ node = cls() + for prop in fdt.properties(offset): + node.props[prop.name] = bytes(prop) + for suboff in fdt.subnodes(offset): + node.children[fdt.get_name(suboff)] = cls.unflatten(fdt, suboff) + return node
Quoted 6 lines
If a blob has two sibling nodes (or two properties) with the same name, one is silently dropped. I checked with FdtSw: with two 'a' subnodes under the root, only the second survives. libfdt does not reject such blobs and fdtfactor reads input it does not control, so I think it is better to raise ValueError here than to quietly throw data away.
Done. DeviceTree.unflatten() now raises ValueError if a node has duplicate property names or duplicate sibling subnode names, with unit tests in tests/pylibfdt_tests.py.
Quoted 8 lines
pylibfdt/libfdt.i class NodeAdder(): · line 1279
Quoted 4 lines
pylibfdt/libfdt.i +4
-0+ fdt = sw.as_fdt() + fdt_set_boot_cpuid_phys(fdt._fdt, boot_cpuid_phys) + fdt.pack() + return bytes(fdt.as_bytearray())This reaches into fdt._fdt and calls the raw SWIG function. It would be worth adding
Fdt.set_boot_cpuid_phys()to go with the existingFdtRo.boot_cpuid_phys(), and calling that instead.
Done. Added Fdt.set_boot_cpuid_phys() in a preparatory patch and updated DeviceTree.flatten() to call it.
-Doug
Re: [PATCH v2 04/10] libfdt: overlay: Factor out fixup and fragment path parsing helpers
In reply to David GibsonHi David,
Quoted 12 lines · David Gibson
Quoted 9 lines · Douglas Anderson
Extract
overlay_parse_fixup_entry()fromoverlay_fixup_phandle()andoverlay_split_fragment_path()fromoverlay_symbol_update().A subsequent patch updating the base tree's
/__local_fixups__node duringfdt_overlay_apply()needs to parse the same"path:name:offset"entries in/__fixups__and split/<fragment>/__overlay__/<subpath>paths in the same way.No functional change intended.
Quoted 8 lines
Conceptually good, but has a couple of warts.
Quoted 4 lines
+/**
+ *overlay_parse_fixup_entry- Parse one "path:name:offset" entry from /__fixups__
+ * @valuep: In/out pointer to the current NUL-terminated fixup string
+ * @lenp: In/out remaining length of the /__fixups__ property valueIt would be good to describe how the in/out values are updated.
Done. Updated the doc comment to specify that @valuep is advanced past the terminating NUL byte to the next entry and @lenp is decremented by the consumed entry length (including its NUL terminator).
Quoted 8 lines
libfdt/fdt_overlay.c static int get_path_len(const void *fdt, int nodeoffset) · line 945
Quoted 6 lines
libfdt/fdt_overlay.c +6
-0+static int overlay_split_fragment_path (const char *path,int path_len, +const char **frag_namep, +int *frag_name_lenp, +const char **rel_pathp, +int *rel_path_lenp, +bool *is_overlayp)Returning the bool this way is clunky. Better to use the return value.
Done. Dropped bool *is_overlayp and updated overlay_split_fragment_path() to return 1 if @path is under an __overlay__ subnode, 0 if it is a valid path not under __overlay__, or -FDT_ERR_BADVALUE on error.
-Doug
Re: [PATCH v2 05/10] libfdt: overlay: Prepare fixup and fragment path helpers for reuse
In reply to David GibsonHi David,
Quoted 22 lines · David Gibson
Quoted 8 lines · Douglas Anderson
Tighten
overlay_parse_fixup_entry()andoverlay_split_fragment_path()before reusing them to update the base tree's/__local_fixups__:- In
overlay_parse_fixup_entry(), store thestrtoul()result in anunsigned longbefore range-checking againstINT32_MAX - sizeof(uint32_t), and require the offset field to begin with an ASCII digit ('0'..'9') sincestrtoul()accepts leading whitespace and+/-signs (wrapping negative values tounsigned long).Huh, I'd assumed that
strtoul()wouldn't accept negative strings, but according to BUGS in strtoul(1) that might not be the case (at least for Linux+glibc). Good catch.This may need some minor rebasing for the suggestions on the previous patch, plus some additional minor refinements suggested below.
Quoted 4 lines
libfdt/fdt_overlay.c +0
-0@@ -404,9 +405,10 @@ static int overlay_parse_fixup_entry(const char **valuep, int *lenp,if (!name_len)return -FDT_ERR_BADOVERLAY ;
Quoted 5 lines
libfdt/fdt_overlay.c static int overlay_parse_fixup_entry(const char **valuep, int *lenp, · line 409
Quoted 2 lines
libfdt/fdt_overlay.c +2
-0+if ((*(sep +1 ) <'0' ) || (*(sep +1 ) >'9' )) +return -FDT_ERR_BADOVERLAY ;Putting the rationale for this in a comment here would be more useful than just in the commit message.
Done. Added a comment right above this check explaining why we require an ASCII digit before calling strtoul(). Also, as Simon suggested, I split this out-of-bounds write fix (along with fixing the unsigned overflow check in fdt_setprop_inplace_namelen_partial()) into a standalone bugfix patch at the start of the series.
-Doug
Re: [PATCH v2 05/10] libfdt: overlay: Prepare fixup and fragment path helpers for reuse
In reply to Simon GlassHi Simon,
Quoted 63 lines · Simon Glass
Quoted 35 lines · Douglas Anderson
Tighten
overlay_parse_fixup_entry()andoverlay_split_fragment_path()before reusing them to update the base tree's/__local_fixups__:- In
overlay_parse_fixup_entry(), store thestrtoul()result in anunsigned longbefore range-checking againstINT32_MAX - sizeof(uint32_t), and require the offset field to begin with an ASCII digit ('0'..'9') sincestrtoul()accepts leading whitespace and+/-signs (wrapping negative values tounsigned long).
- Inoverlay_split_fragment_path(), reject paths with a trailing slash after/__overlay__/(rel_path_len == 0) with-FDT_ERR_BADVALUE.Assisted-by Gemini:gemini-3-pro [edid_decode] [gerrit_and_build_artifacts] [gsheets_gdocs_cli]Signed-off-by Douglas Anderson <[email protected]>---
(no changes since v1)
libfdt/fdt_overlay.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-)libfdt/fdt_overlay.c +1
-1@@ -376,7 +376,8 @@ static int overlay_parse_fixup_entry(const char **valuep, int *lenp,uint32_t fixup_len;const char *sep;char *endptr; -uint32_t poffset; +unsigned long poffset; fixup_end =memchr (*valuep,'\0' , *lenp);if (!fixup_end)libfdt/fdt_overlay.c static int overlay_parse_fixup_entry(const char **valuep, int *lenp, · line 412
Quoted 9 lines
libfdt/fdt_overlay.c +3
-1@@ -404,9 +405,10 @@ static int overlay_parse_fixup_entry(const char **valuep, int *lenp,if (!name_len)return -FDT_ERR_BADOVERLAY ; +if ((*(sep +1 ) <'0' ) || (*(sep +1 ) >'9' )) +return -FDT_ERR_BADOVERLAY ; poffset =strtoul (sep +1 , &endptr,10 ); -if ((*endptr !='\0' ) || (poffset <0 )) +if ((*endptr !='\0' ) || (poffset > (INT32_MAX -sizeof (uint32_t ))))return -FDT_ERR_BADOVERLAY ;This is more than a clean-up: it fixes an existing out-of-bounds write in
fdt_overlay_apply(). With a /__fixups__ entry like '/fragment@0/__overlay__/node:prop:-4',strtoul()gives -4 as an int, which reachesfdt_setprop_inplace_namelen_partial()as idx =0xfffffffc. Then 'len + idx' wraps to 0, the 'proplen < len + idx' check passes andmemcpy()writes 4 bytes before the property value. On 64-bit, '4294967292' does the same. Overlays may well be untrusted, so please can you split this into its own patch at the start of the series, with a commit message that starts with the problem so it doesn't get lost under 'Prepare ... for reuse'?The real cause is the wrapping check in
fdt_setprop_inplace_namelen_partial(). That function is public, so any caller passing a large idx hits the same overflow. I suggest fixing it there with something like:
Quoted 8 lines
if (idx > (unsigned)proplen || (unsigned)len > (unsigned)proplen - idx) return -FDT_ERR_NOSPACE;and keeping the digit check here so that '+4' and ' 4' are still rejected. The
INT32_MAXbound then becomes an early rejection rather than what keeps memory safe. What do you think? A test in tests/ checking thatfdt_overlay_apply()returns -FDT_ERR_BADOVERLAY for an overlay with a negative or oversized fixup offset would also be good.
Great catch on fdt_setprop_inplace_namelen_partial()! In v3 I've:
1. Split this into its own patch at the very start of the series ("libfdt:
overlay: Fix out-of-bounds write on bad fixup offset").
2. Fixed the overflow check in fdt_setprop_inplace_namelen_partial() in libfdt/fdt_wip.c as you suggested.
3. Kept the digit check and a poffset > UINT32_MAX bound in libfdt/fdt_overlay.c (mapping -FDT_ERR_NOSPACE from fdt_setprop_inplace_namelen_partial() to -FDT_ERR_BADOVERLAY in overlay_fixup_one_phandle()).
4. Added tests in tests/setprop_inplace.c and tests/run_tests.sh (overlay_bad_fixup_negative_index.dts and overlay_bad_fixup_overflow_index.dts).
-Doug
Re: [PATCH v2 06/10] libfdt: overlay: Update base /__local_fixups__ on apply
In reply to Simon GlassHi Simon,
Quoted 5 lines · Simon Glass
Quoted 4 lines
When
fdt_overlay_apply()merges an overlay into a base device tree, it updates/__symbols__in the base tree if present, but previously left the base tree's/__local_fixups__node untouched.
Quoted 7 lines
Please can you put the motivation first and use the present tense ('
fdt_overlay_apply()updates /__symbols__ but leaves /__local_fixups__ untouched...')? It would also help to say why anyone needs an accurate /__local_fixups__ in the merged tree. Patch 8 gives the reason (an OS that wants to know which cells hold phandles, and the merged tree matching what 'dtc -L' produces), and that belongs here, since this patch changes behaviour for every libfdt user.
Done. Rewrote the commit message in the present tense with the motivation up front.
Quoted 19 lines
Quoted 8 lines
libfdt/fdt_overlay.c +8
-0+ next_lf =fdt_subnode_offset_namelen (fdt, node, name, namelen); +if (next_lf == -FDT_ERR_NOTFOUND && create) { +char namebuf[256 ]; +int old_struct_size =fdt_size_dt_struct (fdt); + +if ((size_t )namelen >=sizeof (namebuf)) +return -FDT_ERR_INTERNAL ; +memcpy (namebuf, name, namelen);libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1244
Quoted 10 lines
libfdt/fdt_overlay.c +10
-0+ next_lf =fdt_add_subnode_namelen (fdt, node, namebuf, + namelen); +if (next_lf <0 ) +return next_lf; +if (next_lf <= ancestor) { +int delta =fdt_size_dt_struct (fdt) - + old_struct_size; + target += delta; + ancestor += delta; + }
Quoted 8 lines
I can see why the copy is needed, since the name is in the same blob and
fdt_add_subnode_namelen()may move it. But libfdt has no limit on node-name length, so a valid tree with a long name makesfdt_overlay_apply()fail with -FDT_ERR_INTERNAL, which is meant for libfdt bugs. It also puts 256 bytes on the stack in code that runs in bootloaders. Please can you either avoid the copy (e.g. by re-reading the name after the splice, adjusted by the delta) or at least return a proper error code and document the limit?
Done! Removed namebuf[256] completely and instead re-read name from ancestor (adjusted by delta) after fdt_add_subnode_namelen() when next_lf <= ancestor.
Quoted 5 lines
Quoted 4 lines
libfdt/fdt_overlay.c +4
-0+static int overlay_add_local_fixup_offset (void *fdt,int lf_node, +const char *name,int name_len, +uint32_t poffset) +{...
Quoted 8 lines
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1347
Quoted 3 lines
libfdt/fdt_overlay.c +3
-0+ }else { +if (old_len %sizeof (uint32_t )) +return -FDT_ERR_BADSTRUCTURE ;-FDT_ERR_BADSTRUCTURE means the structure block is corrupt. Elsewhere in this file (e.g.
overlay_symbol_update()) a badly sized property value gives -FDT_ERR_BADVALUE, and if the property came from the overlay's /__local_fixups__, -FDT_ERR_BADOVERLAY fits better.
Done. Changed this to return -FDT_ERR_BADVALUE.
Quoted 30 lines
Quoted 19 lines
libfdt/fdt_overlay.c +19
-0+static int overlay_validate_local_fixups (const void *fdto,int ov_lf_root) +{ +int lf_frag; + +fdt_for_each_subnode (lf_frag, fdto, ov_lf_root) { +const char *frag_name; +int frag_name_len, lf_overlay, fragment; + + frag_name =fdt_get_name (fdto, lf_frag, &frag_name_len); +if (!frag_name) +return frag_name_len; + + lf_overlay =fdt_subnode_offset (fdto, lf_frag,"__overlay__" ); +if (lf_overlay == -FDT_ERR_NOTFOUND ) +continue ; +if (lf_overlay <0 ) +return lf_overlay; + + fragment = fdt_subnode_offset_namelen(fdto, 0, frag_name,libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1579
Quoted 10 lines
libfdt/fdt_overlay.c +10
-0+ frag_name_len); +if (fragment <0 ) +return -FDT_ERR_BADOVERLAY ; + +if (fdt_subnode_offset (fdto, fragment,"__overlay__" ) <0 ) +return -FDT_ERR_BADOVERLAY ; + } + +return 0 ; +}
Quoted 7 lines
Just to check, is this needed?
overlay_update_local_references()already walks the overlay's /__local_fixups__ against the overlay tree from the root, returning -FDT_ERR_BADOVERLAY if a node is missing. So by this point each /__local_fixups__/<frag>/__overlay__ is known to have a matching /<frag>/__overlay__ in fdto. If I have that right, this function and its call can go, which also helps with the size issue below.
You're right, overlay_update_local_references() has already walked and validated /__local_fixups__ against fdto before overlay_local_fixups_update()
is called. I've dropped overlay_validate_local_fixups() (and also inlined the single-caller overlay_fragment_local_fixups_src() and overlay_merge_fixup_into_local_fixups() helpers).
Quoted 17 lines
libfdt/fdt_overlay.c int fdt_overlay_apply(void *fdt, void *fdto) · line 1778
Quoted 9 lines
libfdt/fdt_overlay.c +4
-0@@ -1771,6 +1771,10 @@ int fdt_overlay_apply(void *fdt, void *fdto) ret =overlay_symbol_update (fdt, fdto);if (ret) goto err; + ret =overlay_local_fixups_update (fdt, fdto); +if (ret) + goto err; +One thing I'd like to check before this goes in.. this changes what an exported function does. A base with /__local_fixups__ now needs more free space (so it can hit -FDT_ERR_NOSPACE where it did not before), and unrelated empty nodes under /__local_fixups__ get pruned. Please can you update the
fdt_overlay_apply()comment inlibfdt.hto describe the new behaviour?
Quoted 6 lines
Code size is also worth a look. With -Os, the
fdt_overlay.ctext grows from 3040 to 4904 bytes on Thumb-2 and from 4770 to 7983 onx86_64, about 60%. That code goes into things like U-Boot SPL, mostly for boards whose base has no /__local_fixups__ at all. Could this be made optional for size-sensitive users, or at least slimmed down? What do you think?
I've updated the fdt_overlay_apply() doc comment in libfdt/libfdt.h, slimmed down the implementation as noted above, and gated /__local_fixups__ handling in fdt_overlay_apply() behind a 3-state compile-time FDT_OVERLAY_LOCAL_FIXUPS option in libfdt/libfdt_internal.h:
- 0 (FDT_OVERLAY_LOCAL_FIXUPS_IGNORE): Leave /__local_fixups__ untouched. I made this the #ifndef fallback in libfdt_internal.h so that embedded projects (like U-Boot SPL) that compile libfdt/*.c directly get zero code-size increase and zero behavior change unless they opt in.
- 1 (FDT_OVERLAY_LOCAL_FIXUPS_STRIP): Delete /__local_fixups__ from the base DTB if present (~50 bytes of code), avoiding leaving a stale or incomplete /__local_fixups__ node in the merged DTB.
- 2 (FDT_OVERLAY_LOCAL_FIXUPS_UPDATE): Fully update /__local_fixups__ in the base DTB. This is enabled by default in dtc's Meson (-Doverlay-local-fixups=2) and Make (OVERLAY_LOCAL_FIXUPS=2) builds for desktop tools and tests.
Let me know if that works well for you or if you'd prefer a different default!
-Doug
Re: [PATCH v2 06/10] libfdt: overlay: Update base /__local_fixups__ on apply
In reply to David GibsonHi David,
Quoted 23 lines · David Gibson
Quoted 21 lines · Douglas Anderson
When
fdt_overlay_apply()merges an overlay into a base device tree, it updates/__symbols__in the base tree if present, but previously left the base tree's/__local_fixups__node untouched.Add
overlay_local_fixups_update()so that when the base tree contains a/__local_fixups__node,fdt_overlay_apply()updates it to reflect the applied overlay:
- For each fragment in application order, any local fixup properties in the base tree's/__local_fixups__that correspond to properties overwritten by that fragment are cleared first.
- Local phandle references from that fragment's subtree under the overlay's/__local_fixups__/<fragment>/__overlay__are merged into the corresponding target path under the base tree's/__local_fixups__.
- External phandle references for that fragment from the overlay's/__fixups__(which are now resolved to local phandles in the merged base tree) are added in sorted order to the base tree's/__local_fixups__.
- Any subnodes under the base tree's/__local_fixups__that become empty after clearing overwritten properties are pruned.
Quoted 6 lines
Quoted 2 lines
If the base tree does not have a
/__local_fixups__node, nothing is added.So, this turned out to be substantially more involved than I realised. I wonder if it might be better to make --strip-locals the default, and only add support for preserving the local fixups as a later extension.
In v3 I went ahead and addressed all of your and Simon's review comments on this patch (which also trimmed ~80 lines of C from fdt_overlay.c).
To address Simon's point about code size in constrained environments like U-Boot SPL, I also gated /__local_fixups__ handling in fdt_overlay_apply() behind a 3-state compile-time FDT_OVERLAY_LOCAL_FIXUPS option in libfdt/libfdt_internal.h:
- 0 (FDT_OVERLAY_LOCAL_FIXUPS_IGNORE): Leave /__local_fixups__ untouched. I made this the #ifndef fallback in libfdt_internal.h so that embedded projects that vendor libfdt directly get zero code-size increase and zero behavior change unless they opt in.
- 1 (FDT_OVERLAY_LOCAL_FIXUPS_STRIP): Delete /__local_fixups__ from the base DTB if present (~50 bytes of code), so a stale/half-working /__local_fixups__ node isn't left behind in the merged tree.
- 2 (FDT_OVERLAY_LOCAL_FIXUPS_UPDATE): Fully update /__local_fixups__ in the base DTB. This is enabled by default in dtc's Meson (-Doverlay-local-fixups=2) and Make (OVERLAY_LOCAL_FIXUPS=2) builds for desktop tools and tests.
Even when fdtfactor -S is used, we actually do need fdtoverlay to update /__local_fixups__ for two reasons:
1. **Kernel composite DTBs (foo-dtbs := base.dtb bar.dtbo)**: In the Linux kernel build (scripts/Makefile.dtbs), many upstream boards are built as composite DTBs using cmd_fdtoverlay (fdtoverlay -i base.dtb -o foo.dtb bar.dtbo) *before* fdtfactor runs on them. As Simon pointed out on the kernel series [1], if fdtoverlay left /__local_fixups__ untouched (IGNORE), foo.dtb would still have base.dtb's /__local_fixups__ node (missing all phandle references from bar.dtbo and retaining stale offsets for any overwritten properties), causing fdtfactor to silently miss or corrupt phandle references when factoring foo.dtb. And if fdtoverlay stripped /__local_fixups__, foo.dtb wouldn't have /__local_fixups__ at all and fdtfactor wouldn't be able to factor any composite DTB.
2. **fdtfactor self-tests**: Since fdtfactor inputs are compiled with dtc -@ -L, having fdtoverlay update /__local_fixups__ lets the test suite directly verify with dtbs_equal_unordered that recombining base.dtb + board.dtbo produces an exact match for the original input .dtb (including all phandle fixup metadata).
Let me know if you're happy with this approach (or if you'd prefer a different FDT_OVERLAY_LOCAL_FIXUPS default)!
[1] https://lore.kernel.org/all/CAFLszTiVvuaMUsRHjhRTFxFf8Q2hbN1a1K-G=QFv4DyXNpWY6w@mail.gmail.com/
Quoted 7 lines
Quoted 7 lines
libfdt/fdt_overlay.c +0
-0@@ -804,7 +804,7 @@ static int overlay_prevent_phandle_overwrite(void *fdt, void *fdto)* Negative error code on failure */
Quoted 8 lines
libfdt/fdt_overlay.c static int overlay_prevent_phandle_overwrite(void *fdt, void *fdto) · line 810
Quoted 6 lines
libfdt/fdt_overlay.c +1
-1static int overlay_apply_node (void *fdt,int target, -void *fdto,int node) +const void *fdto,int node) {int property;int subnode;This change is unrelated to the rest of the patch.
Split into its own standalone preparatory patch ("libfdt: overlay: Make fdto const in overlay_apply_node()").
Quoted 44 lines
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1148
Quoted 10 lines
libfdt/fdt_overlay.c +10
-0+static int overlay_create_path (void *fdt,int parent,const char *path, +int path_len) +{ +const char *sep; +int node = parent; + +while (path_len >0 && *path =='/' ) { + path++; + path_len--; + }In Python, I'm pretty happy to have the code to optionally allow extra slashes to make the functions more widely useful. In C - especially since this is code that may be run in limited environments - I'd prefer to pin down exactly what the expected format is and require that. So, I'd suggest this function only take a relative path, and make sure that's the case from the callers.
libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1157
Quoted 8 lines
libfdt/fdt_overlay.c +8
-0+while (path_len >0 ) { +int comp_len; +int next; + + sep =memchr (path,'/' , path_len); + comp_len = sep ? (sep - path) : path_len; + +if (comp_len >0 ) {Similarly, in C I'd treat
comp_len== 0 as an error condition, rather than trying to handle it.libfdt/fdt_overlay.c static int overlay_symbol_update(void *fdt, void *fdto) · line 1170
Quoted 13 lines
libfdt/fdt_overlay.c +13
-0+ next =fdt_subnode_offset_namelen (fdt, node, path, + comp_len); +if (next == -FDT_ERR_NOTFOUND ) + next =fdt_add_subnode_namelen (fdt, node, path, + comp_len); +if (next <0 ) +return next; + node = next; + } + + path += comp_len; + path_len -= comp_len; +while (path_len >0 && *path =='/' ) {
Quoted 1 line
Same thoughts here.
Done. overlay_create_path() now requires a strict relative path and returns -FDT_ERR_BADOVERLAY if comp_len == 0 (leading /, repeated //) or if @path has a trailing /.
-Doug
Re: [PATCH v2 08/10] fdtfactor: Add -S/--strip-local-fixups option
In reply to Simon GlassHi Simon,
Quoted 8 lines · Simon Glass
Quoted 4 lines
On a set of 47 Qualcomm SC7180 Trogdor Chromebook board DTBs,
fdtfactor -Sreduces total uncompressed size from 7.69 MB to 634 KB (91.8% savings).This compares against the unfactored DTBs, so it doesn't show what -S itself saves. Please can you also give the size without -S, so it is clear what the /__local_fixups__ in base.dtb costs?
Done. Updated the commit message to show both numbers: without -S the 47 Trogdor DTBs factor down from 7.69 MB to 932 KB (88.2% savings), and with -S they factor down to 634 KB (91.8% savings, saving an additional 298 KB by omitting /__local_fixups__ from base.dtb).
Quoted 10 lines
Quoted 10 lines
tests/run_tests.sh +8
-0@@ -1238,6 +1238,28 @@ fdtfactor_tests () { + # Strip local fixups (-S): verify that merged DTBs match DTBs compiled + # with -@ (without -L), and that inputs lacking /__local_fixups__ are + # rejected. + for i in 1 2 3; do + run_dtc_test -b 2 -@ -I dts -O dtb -o fdtfactor_board${i}.nolf.test.dtb \ + "$SRCDIR/fdtfactor_board${i}.dts" + done + run_wrap_error_test $PYTHON $FDTFACTOR -o fdtfactor_strip.test.dir \
Quoted 8 lines
tests/run_tests.sh fdtfactor_tests () { · line 1196
Quoted 1 line
tests/run_tests.sh +1
-0+ fdtfactor_board1.nolf.test.dtb fdtfactor_board2.test.dtbThis rejection test has no -S, so it checks the -L requirement from the previous patch rather than anything added here. Since -S could easily be read as 'my inputs don't need -L', I think it is more useful to pass -S here, to show that it does not relax that requirement. The plain no-S case could then go into the previous patch with the other rejection tests.
Done. Moved the no--S .nolf.test.dtb rejection test into the main fdtfactor patch and updated this test to pass -S.
-Doug
Re: [PATCH v2 10/10] fdtfactor: Add compiled FIT image factoring support
In reply to Simon GlassHi Simon,
Quoted 33 lines · Simon Glass
Quoted 4 lines · Douglas Anderson
Add
-F/--fit,--outfile, and--single-base-dtbtofdtfactorso it can directly factor/images/fdt-*blobs inside a compiled U-Boot / ChromeOS Flattened Image Tree (FIT) image....
Quoted 13 lines
Assisted-by Gemini:gemini-3-pro [edid_decode] [gerrit_and_build_artifacts] [gsheets_gdocs_cli]Signed-off-by Douglas Anderson <[email protected]>---
Changes in v2:
- Moved FIT image factoring into its own patch.
- Replaced externalfdtget/fdtputsubprocess calls withNodeTree.
- Added FIThash*recalculation (crc32,sha1,sha256, etc.) and rejected signed FIT images (signature*subnodes) and external-data FIT images (data-offset/data-position).
- Preserved per-group compression (lz4,lzma,xz,gzip) on factored FITfdt-base-*andfdt-*nodes.Quoted 12 lines
README.md | 19 +++ fdtfactor | 408 +++++++++++++++++++++++++++++++++++++- tests/fdtfactor_lz4.its | 83 ++++++++ tests/fdtfactor_other1.dts| 21 ++ tests/fdtfactor_other2.dts| 21 ++ tests/fdtfactor_test.its | 83 ++++++++ tests/run_tests.sh | 156 +++++++++++++++ 7 files changed, 789 insertions(+), 2 deletions(-) create mode 100644 tests/fdtfactor_lz4.its create mode 100644 tests/fdtfactor_other1.dts create mode 100644 tests/fdtfactor_other2.dts create mode 100644 tests/fdtfactor_test.its
Quoted 4 lines
Reviewed-by Simon Glass <[email protected]>BTW, 'FIT image' actually means an image in a FIT, so I think you should try to call the whole thing a 'FIT' instead.
Done. Updated the commit message, README.md, fdtfactor, and tests to refer to the container as a "FIT" rather than a "FIT image".
-Doug
Re: [PATCH v2 02/10] pylibfdt: Add subnode/property iterators and get_mem_rsv_list()
In reply to Simon GlassQuoted 23 lines · Simon Glass
Hi Doug,
Quoted 19 lines · Douglas Anderson
pylibfdt: Add subnode/property iterators and
get_mem_rsv_list()Add Pythonic iterator helpers on
FdtRoto simplify walking nodes, properties, and memory reservation entries without manual offset loops or-FDT_ERR_NOTFOUNDsentinel handling:-
subnodes(nodeoffset): yields the offset of each direct child subnode ofnodeoffset.
-properties(nodeoffset): yields aPropertyobject for each property ofnodeoffset.
-get_mem_rsv_list(): returns a list of(address, size)tuples for all entries in the memory reservation block.Assisted-by Gemini:gemini-pro-prereleaseSigned-off-by Douglas Anderson <[email protected]>pylibfdt/libfdt.i | 45 +++++++++++++++++++++++++++++++++++++++++++++ tests/pylibfdt_tests.py | 18 ++++++++++++++++++ 2 files changed, 63 insertions(+)
Quoted 10 lines
pylibfdt/libfdt.i class FdtRo(object): · line 204
Quoted 6 lines
pylibfdt/libfdt.i +4
-0@@ -201,6 +201,23 @@ class FdtRo(object): + soff = self.first_subnode(nodeoffset, quiet=QUIET_NOTFOUND) + while soff >= 0: + yield soff + soff = self.next_subnode(soff, quiet=QUIET_NOTFOUND)Since Fdt inherits this generator, a caller can easily write 'for off in
fdt.subnodes(0):fdt.del_node(off)' and get garbage, because the offsets move under it.
Right. I noticed that, but merged anyway, since you can basically do the same thing with the existing interfaces. By abstracting it further, this interface does arguably make the problem worse. This is kind of a perennial problem with the Python bindings. The libfdt interface is shaped by what is and isn't possible with the flattened format - the reason we insistently name "offsets" everywhere, rather than just "nodes" or "properties" is an attempt to inculcate the right mental model. By abstracting things more, the Python bindings make it easier to miss that.
[Aside: one of the many projects I'll probably never find time for is
to write a Rust-native libfdt, where the ownership model could be harnessed to enforce many of the required invariants]
Quoted 4 lines
Since David has applied this, please can you
send a follow-up noting in the docstring (here and inproperties()) that the tree must not be modified while iterating, as withfdt_for_each_subnode()in C?
Right, adding a comment is probably a good idea.
Quoted 14 lines
tests/pylibfdt_tests.py class PyLibfdtBasicTests(unittest.TestCase): · line 244
Quoted 4 lines
tests/pylibfdt_tests.py +2
-0@@ -243,6 +243,22 @@ class PyLibfdtBasicTests(unittest.TestCase): + leaf = self.fdt.path_offset('/subnode@1/ss1') + self.assertEqual(list(self.fdt.subnodes(leaf)), [])The docstrings say both iterators raise FdtException for a bad offset, but nothing tests that. A test that list(self.fdt.subnodes(-1)) and list(self.fdt.properties(-1)) raise, perhaps alongside testFirstNextSubnodeOffsetExceptions, would be good, perhaps in the same follow-up. Since these are generators, the exception only appears on the first
next(), not when the method is called.Reviewed-by Simon Glass <[email protected]>
Signature · 4 lines
David Gibson (he or they) | I'll have my music baroque, and my code david AT gibson.dropbear.id.au | minimalist, thank you, not the other way | around. http://www.ozlabs.org/~dgibson
Re: [PATCH v2 06/10] libfdt: overlay: Update base /__local_fixups__ on apply
In reply to Doug AndersonQuoted 30 lines · Doug Anderson
Hi David,
Quoted 26 lines · David Gibson
Quoted 23 lines · Douglas Anderson
When
fdt_overlay_apply()merges an overlay into a base device tree, it updates/__symbols__in the base tree if present, but previously left the base tree's/__local_fixups__node untouched.Add
overlay_local_fixups_update()so that when the base tree contains a/__local_fixups__node,fdt_overlay_apply()updates it to reflect the applied overlay:
- For each fragment in application order, any local fixup properties in the base tree's/__local_fixups__that correspond to properties overwritten by that fragment are cleared first.
- Local phandle references from that fragment's subtree under the overlay's/__local_fixups__/<fragment>/__overlay__are merged into the corresponding target path under the base tree's/__local_fixups__.
- External phandle references for that fragment from the overlay's/__fixups__(which are now resolved to local phandles in the merged base tree) are added in sorted order to the base tree's/__local_fixups__.
- Any subnodes under the base tree's/__local_fixups__that become empty after clearing overwritten properties are pruned.If the base tree does not have a
/__local_fixups__node, nothing is added.
Quoted 6 lines
Quoted 3 lines
So, this turned out to be substantially more involved than I realised. I wonder if it might be better to make --strip-locals the default, and only add support for preserving the local fixups as a later extension.
In v3 I went ahead and addressed all of your and Simon's review comments on this patch (which also trimmed ~80 lines of C from
fdt_overlay.c).
Oh good :).
Quoted 20 lines
To address Simon's point about code size in constrained environments like U-Boot SPL, I also gated
/__local_fixups__handling infdt_overlay_apply()behind a 3-state compile-timeFDT_OVERLAY_LOCAL_FIXUPSoption inlibfdt/libfdt_internal.h:-
0(FDT_OVERLAY_LOCAL_FIXUPS_IGNORE): Leave/__local_fixups__untouched. I made this the#ifndeffallback inlibfdt_internal.hso that embedded projects that vendorlibfdtdirectly get zero code-size increase and zero behavior change unless they opt in.
-1(FDT_OVERLAY_LOCAL_FIXUPS_STRIP): Delete/__local_fixups__from the base DTB if present (~50 bytes of code), so a stale/half-working/__local_fixups__node isn't left behind in the merged tree.
-2(FDT_OVERLAY_LOCAL_FIXUPS_UPDATE): Fully update/__local_fixups__in the base DTB. This is enabled by default indtc's Meson (-Doverlay-local-fixups=2) and Make (OVERLAY_LOCAL_FIXUPS=2) builds for desktop tools and tests.Even when
fdtfactor -Sis used, we actually do needfdtoverlayto update/__local_fixups__for two reasons:
Quoted 12 lines
1. **Kernel composite DTBs (
foo-dtbs := base.dtb bar.dtbo)**: In the Linux kernel build (scripts/Makefile.dtbs), many upstream boards are built as composite DTBs usingcmd_fdtoverlay(fdtoverlay -i base.dtb -o foo.dtb bar.dtbo) *before*fdtfactorruns on them. As Simon pointed out on the kernel series [1], iffdtoverlayleft/__local_fixups__untouched (IGNORE),foo.dtbwould still havebase.dtb's/__local_fixups__node (missing all phandle references frombar.dtboand retaining stale offsets for any overwritten properties), causingfdtfactorto silently miss or corrupt phandle references when factoringfoo.dtb. And iffdtoverlaystripped/__local_fixups__,foo.dtbwouldn't have/__local_fixups__at all andfdtfactorwouldn't be able to factor any composite DTB.
Ah, right.
Quoted 8 lines
2. **
fdtfactorself-tests**: Sincefdtfactorinputs are compiled withdtc -@ -L, havingfdtoverlayupdate/__local_fixups__lets the test suite directly verify withdtbs_equal_unorderedthat recombiningbase.dtb+board.dtboproduces an exact match for the original input.dtb(including all phandle fixup metadata).Let me know if you're happy with this approach (or if you'd prefer a different
FDT_OVERLAY_LOCAL_FIXUPSdefault)!
I'll bear this in mind when I look at v3 and see what I think.
Signature · 4 lines
David Gibson (he or they) | I'll have my music baroque, and my code david AT gibson.dropbear.id.au | minimalist, thank you, not the other way | around. http://www.ozlabs.org/~dgibson
Re: [PATCH v2 02/10] pylibfdt: Add subnode/property iterators and get_mem_rsv_list()
In reply to David GibsonHi David,
Quoted 36 lines · David Gibson
Quoted 23 lines · Simon Glass
Hi Doug,
Quoted 19 lines · Douglas Anderson
pylibfdt: Add subnode/property iterators and
get_mem_rsv_list()Add Pythonic iterator helpers on
FdtRoto simplify walking nodes, properties, and memory reservation entries without manual offset loops or-FDT_ERR_NOTFOUNDsentinel handling:-
subnodes(nodeoffset): yields the offset of each direct child subnode ofnodeoffset.
-properties(nodeoffset): yields aPropertyobject for each property ofnodeoffset.
-get_mem_rsv_list(): returns a list of(address, size)tuples for all entries in the memory reservation block.Assisted-by Gemini:gemini-pro-prereleaseSigned-off-by Douglas Anderson <[email protected]>pylibfdt/libfdt.i | 45 +++++++++++++++++++++++++++++++++++++++++++++ tests/pylibfdt_tests.py | 18 ++++++++++++++++++ 2 files changed, 63 insertions(+)Quoted 10 lines
pylibfdt/libfdt.i class FdtRo(object): · line 204
Quoted 6 lines
pylibfdt/libfdt.i +4
-0@@ -201,6 +201,23 @@ class FdtRo(object): + soff = self.first_subnode(nodeoffset, quiet=QUIET_NOTFOUND) + while soff >= 0: + yield soff + soff = self.next_subnode(soff, quiet=QUIET_NOTFOUND)Since Fdt inherits this generator, a caller can easily write 'for off in
fdt.subnodes(0):fdt.del_node(off)' and get garbage, because the offsets move under it.
Quoted 9 lines
Right. I noticed that, but merged anyway, since you can basically do the same thing with the existing interfaces. By abstracting it further, this interface does arguably make the problem worse. This is kind of a perennial problem with the Python bindings. The libfdt interface is shaped by what is and isn't possible with the flattened format - the reason we insistently name "offsets" everywhere, rather than just "nodes" or "properties" is an attempt to inculcate the right mental model. By abstracting things more, the Python bindings make it easier to miss that.
Yes that makes sense, and noted.
Quoted 4 lines
[Aside: one of the many projects I'll probably never find time for is
to write a Rust-native libfdt, where the ownership model could be harnessed to enforce many of the required invariants]
Yes we talked about that briefly last year I think. I haven't seriously looked at it though, apart from some experiments with ownership of an offset. I have dug into Rust quite a bit but I'm sure there are other people who would do a better job of this.
Quoted 22 lines
Quoted 5 lines
Since David has applied this, please can you
send a follow-up noting in the docstring (here and inproperties()) that the tree must not be modified while iterating, as withfdt_for_each_subnode()in C?Right, adding a comment is probably a good idea.
Quoted 14 lines
tests/pylibfdt_tests.py class PyLibfdtBasicTests(unittest.TestCase): · line 244
Quoted 4 lines
tests/pylibfdt_tests.py +2
-0@@ -243,6 +243,22 @@ class PyLibfdtBasicTests(unittest.TestCase): + leaf = self.fdt.path_offset('/subnode@1/ss1') + self.assertEqual(list(self.fdt.subnodes(leaf)), [])The docstrings say both iterators raise FdtException for a bad offset, but nothing tests that. A test that list(self.fdt.subnodes(-1)) and list(self.fdt.properties(-1)) raise, perhaps alongside testFirstNextSubnodeOffsetExceptions, would be good, perhaps in the same follow-up. Since these are generators, the exception only appears on the first
next(), not when the method is called.Reviewed-by Simon Glass <[email protected]>
Regards,
Simon