Skip to contentSkip to conversation

fdtfactor: Introduce fdtfactor to auto-factor overlays

PATCH New Douglas Anderson 1 participant 9 messages Dec 4

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

v5 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 fdtfactor -S to reduce sc7180-trogdor device tree files (which are stored lz4 compressed) from 1.08 MB (built without -@ -L) to 214 KB, an 80.2% 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.

To test multi-SoC FIT factoring, I also built an upstream Linux arch/arm64 image.fit containing all 438 Qualcomm device trees (367 standalone .dtbs plus 71 composite .dtbs built from 30 add-on .dtbos; gzip-compressed). Comparing the embedded FDT blob totals (with non-factored cases built without -@ -L, and factored cases using fdtfactor -S):

* Plain FIT (438 full .dtbs): 49.13 MB uncompressed (9.27 MB gzip)
* FIT_DECOMPOSE_DTBS=1 alone (deduplicating the 71 composite .dtbs into 367 .dtbs + 30 add-on .dtbos): 36.23 MB uncompressed (6.94 MB gzip)
* fdtfactor alone (41 fdt-base-* groups, 426 board .dtbos, 12 single-board SoCs): 18.26 MB uncompressed (3.59 MB gzip -- 61.3% compressed savings vs. plain)
* FIT_DECOMPOSE_DTBS=1 + fdtfactor (41 fdt-base-* groups, 355 board .dtbos, 30 add-on .dtbos, 12 single-board SoCs): 15.28 MB uncompressed (3.03 MB gzip -- 67.3% compressed savings vs. plain, 56.3% vs. FIT_DECOMPOSE_DTBS=1 alone)

Before introducing fdtfactor itself, the series starts with a few preparatory patches: checking the NUL terminator before memcmp() in libfdt's fdt_find_string_len_(), adding a DeviceTree live-tree abstraction in pylibfdt/libpydt.py, and teaching libfdt's fdt_overlay_apply() to update /__local_fixups__ on the base tree so merged trees retain complete and accurate phandle location metadata (for runtime consumers, composite .dtbs built by fdtoverlay that are later fed into fdtfactor, and round-trip verification against dtc -L).

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]
v2: https://lore.kernel.org/r/[email protected]
v3: https://lore.kernel.org/r/[email protected]
v4: https://lore.kernel.org/r/[email protected]

Changes in v5:
- New follow-up patch checking p[slen] == '\0' before memcmp() in fdt_find_string_len_() (David Laight)
- Make fdt_add_empty_subnode_() static via VISIBLE_IF_LOCAL_FIXUPS_UPDATE when FDT_OVERLAY_LOCAL_FIXUPS != FDT_OVERLAY_LOCAL_FIXUPS_UPDATE so non-UPDATE builds inline it back into fdt_add_subnode_namelen(), and temper the code-size wording in libfdt_internal.h and the commit message (Simon Glass)
- Drop patches 1-5 and 8 from v4 (applied upstream by David Gibson)
- Drop patch 6 ("pylibfdt: Speed up FdtRo.properties() with a C helper") from v4 for now (David Gibson)
- Add follow-up libfdt patch checking p[slen] == '\0' before memcmp() in fdt_find_string_len_() (David Laight)
- Address v4 review feedback on fdt_add_empty_subnode_() and parallel blob compression (Simon Glass)
- Always create the ThreadPoolExecutor inside _map_blobs() instead of threading a shared pool argument through factor_fit() and its helpers (Simon Glass)
- Drop the dead 'if fdt is None' path in ParsedDtb.__init__(), make 'fdt' a required argument, and update its docstring (Simon Glass)

Changes in v4:
- Start the commit message with the motivation for a live tree and condense the summary (Simon Glass)
- Rename devicetree.py to libpydt.py (under pylibfdt/) to avoid colliding with PyPI's python-devicetree package, and move its unit tests into a separate tests/libpydt_tests.py file (Simon Glass, David Gibson)
- Unflatten the tree in a single O(n) pass using fdt.next_node() instead of recursive O(d * n) fdt.subnodes() traversal, raising FdtException on corrupt/truncated trees, and add a unit test (David Gibson, Simon Glass)
- Implement DeviceTree.walk() iteratively with an explicit stack instead of recursive yield from, and populate node.props directly in unflatten()
- Drop redundant fdt.pack() call from DeviceTree.flatten() (David Gibson)
- Drop get_*/set_* typed wrapper methods from DeviceTree in favor of Property.as_*() and Property.from_*() plus DeviceTree.set_prop() (David Gibson)
- Drop unnecessary copy.deepcopy() and compare unordered node/child sets instead of ordered lists in round-trip test (David Gibson)
- Split out internal helper fdt_add_empty_subnode_() so overlay_fragment_local_fixups() avoids passing an in-blob pointer to fdt_add_subnode_namelen() or casting fdt_get_name() (Simon Glass)
- Add test cases in tests/overlay.c where the overlay target has no existing subnode under /__local_fixups__, with /__local_fixups__ both before and after the target in the blob (Simon Glass)
- Pass OVERLAY_LOCAL_FIXUPS to tests/run_tests.sh, adjust fdtoverlay_tests for all three modes, and use 4-space indentation (Simon Glass, David Gibson)
- Rename -o/--outdir to -o/--output so standalone DTB mode and FIT mode share the same output option, and use 4-space indentation in tests/run_tests.sh (David Gibson)
- Update for libpydt rename, use Property.as_*(), Property.from_*(), and DeviceTree.set_prop() instead of DeviceTree get_*/set_* wrapper methods, and drop redundant bytes() copies on Property instances (David Gibson, Simon Glass)
- Replace ParsedDtb.raw_bytes with uncompressed_size, use early continue to reduce loop nesting, drop redundant set() before sorted() on local fixup offsets, and clarify pre-order walk and phandle comments (David Gibson)
- Allow dtc -@ -L inputs with no phandles (where dtc omits /__symbols__ and /__local_fixups__)
- Check _is_dtbo_overlay() on the unflattened DeviceTree, index ParsedDtb.nodes and base_nodes by path, and skip unchanged base nodes in _build_board_dtbo() to avoid repeated O(depth) traversals and per-property comparisons
- Handle OVERLAY_LOCAL_FIXUPS != 2 in fdtfactor_tests (Simon Glass)
- Use 4-space indentation instead of mixed tabs and spaces in tests/run_tests.sh, and update context for -o/--output (David Gibson)
- Replace magic-byte/extension auto-detection and --base-compression with a single explicit -C/--compression option controlling both input and output compression (David Gibson)
- Drop unnecessary --stats documentation/help changes and use 4-space indentation in tests/run_tests.sh (David Gibson)
- Use check_factored_dtb in fdtfactor_tests so tests pass when OVERLAY_LOCAL_FIXUPS != 2 (Simon Glass)
- Unify --outfile into -o/--output, and split standalone DTB vs. FIT options into separate README.md subsections and --help groups (David Gibson)
- Check _is_dtbo_overlay() directly in _extract_fit_fdt_entries() instead of adding OverlayBlobError to ParsedDtb (David Gibson)
- Map standard FIT hash algorithm names explicitly via FIT_HASH_ALGOS instead of passing raw names to hashlib.new() (David Gibson)
- Remove compression and entry from FIT grouping, document load, expose --min-overlap, and compute FIT group overlap using normalized property byte costs via _prop_byte_cost() instead of unweighted node paths (David Gibson)
- Strip /__local_fixups__ from unfactored single-board FIT flat_dt entries when -S/--strip-local-fixups is passed, and pick the next unused fdt-base-N node name instead of rejecting FITs that already contain fdt-base-* nodes
- Pass already-unflattened FactoredTree into ParsedDtb and intern normalized properties to integer IDs in group_fit_dtbs() to speed up multi-SoC FIT factoring
- Preserve whether input FIT FDT descriptions include a compression extension instead of unconditionally appending one
- Update for libpydt rename, use Property.as_*(), Property.from_*(), and DeviceTree.set_prop() instead of DeviceTree get_*/set_* wrapper methods, and drop redundant bytes() copies on Property instances (David Gibson, Simon Glass)
- Use check_factored_dtb and 4-space indentation in tests/run_tests.sh (Simon Glass, David Gibson)
- Drop patches 1-6 and 8-10 from v3 (applied upstream by David Gibson)
- Add preparatory README.md patch documenting dtc and ancillary tools (David Gibson)
- Add pylibfdt preparatory patches making Property a subclass of bytes, trimming FdtSw.as_fdt() to totalsize(), adding Property.from_*() creation helpers (David Gibson), and speeding up Property.as_list() and FdtRo.properties()
- Rename devicetree.py to pylibfdt/libpydt.py and address v3 review feedback on DeviceTree (Simon Glass, David Gibson)
- Add preparatory libfdt patch speeding up fdt_find_string_len_() with memchr()
- Update cover letter motivation for fdt_overlay_apply() /__local_fixups__ handling (Simon Glass)
- Replace compression auto-detection with explicit -C/--compression, unify -o/--output across DTB and FIT modes, and group FIT FDTs by configurable --min-overlap shared normalized property byte cost instead of a hardcoded 50% node-path heuristic (David Gibson)
- Speed up multi-SoC FIT factoring, parallelize blob compression/decompression, and add Qualcomm FIT space-savings numbers (and non--@ -L sc7180-trogdor baseline) to cover letter
- New patch parallelizing blob compression and decompression across worker threads

Changes in v3:
- Move NodeTree out of pylibfdt/libfdt.i into a new devicetree.py module and rename it to DeviceTree (David Gibson)
- Store libfdt.Property objects in self.props instead of raw bytes (David Gibson)
- Return a packed libfdt.Fdt object from flatten() instead of raw bytes and use fdt.set_boot_cpuid_phys() (David Gibson, Simon Glass)
- Raise ValueError in unflatten() on duplicate property or sibling subnode names (Simon Glass)
- Move constifying fdto in overlay_apply_node() into a standalone preparatory patch (David Gibson)
- Gate /__local_fixups__ handling behind a 3-state compile-time FDT_OVERLAY_LOCAL_FIXUPS flag (0=ignore, 1=strip, 2=update), defaulting to 0 (IGNORE) in libfdt_internal.h for embedded builds and 2 (UPDATE) in Meson/Make desktop builds (Simon Glass, David Gibson)
- Rewrite commit message in the present tense with motivation up front, and update fdt_overlay_apply() documentation in libfdt/libfdt.h (Simon Glass)
- Require a strict relative path in overlay_create_path() and return -FDT_ERR_BADOVERLAY on empty path components or trailing '/' (David Gibson)
- Eliminate the 256-byte namebuf limit in overlay_fragment_local_fixups() by re-reading the node name from the shifted ancestor offset after fdt_add_subnode_namelen() (David Gibson, Simon Glass)
- Return -FDT_ERR_BADVALUE instead of -FDT_ERR_BADSTRUCTURE in overlay_add_local_fixup_offset() when an existing /__local_fixups__ property length is not a multiple of 4 (David Gibson, Simon Glass)
- Drop redundant overlay_validate_local_fixups() pre-pass and inline single-use helpers (Simon Glass)
- Update fdtfactor to use devicetree.DeviceTree and a FactoredTree subclass initializing self.phandle and self.fixups in __init__() (David Gibson, Simon Glass)
- Rename -b/--base-dtb to --output-base-dtb to avoid confusion with an input base DTB (David Gibson)
- Move the test rejecting input DTBs lacking /__local_fixups__ from the -S patch into this base patch (Simon Glass)
- Include both non--S (932 KB) and -S (634 KB) Trogdor size numbers in the commit message to show the savings of -S itself (Simon Glass)
- Pass -S to the negative test verifying that inputs lacking /__local_fixups__ are still rejected when -S is used, and move the non--S rejection test to the base fdtfactor patch (Simon Glass)
- Update for -b/--base-dtb rename to --output-base-dtb (David Gibson)
- Use "FIT" instead of "FIT image" in documentation, comments, and commit messages (Simon Glass)
- Update for DeviceTree and --output-base-dtb (Simon Glass, David Gibson)
- Drop "pylibfdt: Fix FdtSw.as_fdt() when buffer is nearly full" and "pylibfdt: Add subnode/property iterators and get_mem_rsv_list()" (applied upstream by David Gibson)
- Split fixup offset overflow fix, redundant memchr() check cleanup, iterator docstring/test follow-up, Property.as_str()/as_stringlist() empty-property handling, Fdt.set_boot_cpuid_phys(), Property.__copy__()/__deepcopy__(), and overlay_apply_node() const fdto into standalone patches (David Gibson, Simon Glass)
- Move NodeTree into a new devicetree.py module as DeviceTree (David Gibson)
- Gate fdt_overlay_apply() /__local_fixups__ handling behind a 3-state compile-time FDT_OVERLAY_LOCAL_FIXUPS option (Simon Glass, David Gibson)

Changes in v2:
- Split live tree representation out of fdtfactor (David Gibson)
- 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)
- 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)
- 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)

Douglas Anderson (8):
libfdt: Check NUL byte before memcmp() in fdt_find_string_len_()
libpydt: Add DeviceTree live tree representation
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 factoring support
fdtfactor: Parallelize blob compression and decompression

 Makefile                           |    8 +-
 README.md                          |  100 ++
 fdtfactor                          | 1831 ++++++++++++++++++++++++++++
 libfdt/fdt.c                       |    2 +-
 libfdt/fdt_overlay.c               |  525 +++++++-
 libfdt/fdt_rw.c                    |   38 +-
 libfdt/libfdt.h                    |    7 +
 libfdt/libfdt_internal.h           |   29 +
 meson.build                        |    6 +
 meson_options.txt                  |    2 +
 pylibfdt/libpydt.py                |  184 +++
 pylibfdt/meson.build               |    2 +
 tests/Makefile.tests               |   13 +-
 tests/fdtfactor_board1.dts         |   72 ++
 tests/fdtfactor_board2.dts         |   70 ++
 tests/fdtfactor_board3.dts         |   68 ++
 tests/fdtfactor_board3_shifted.dts |   68 ++
 tests/fdtfactor_lz4.its            |  109 ++
 tests/fdtfactor_other1.dts         |   67 +
 tests/fdtfactor_other2.dts         |   67 +
 tests/fdtfactor_test.its           |  109 ++
 tests/libpydt_tests.py             |  106 ++
 tests/meson.build                  |    5 +-
 tests/overlay.c                    |  154 +++
 tests/run_tests.sh                 |  446 ++++++-
 tests/testutils.sh                 |    1 +
 26 files changed, 4058 insertions(+), 31 deletions(-)
 create mode 100755 fdtfactor
 create mode 100644 pylibfdt/libpydt.py
 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
 create mode 100644 tests/libpydt_tests.py
Signature · 1 line
2.56.1.987.g2ec0ab4260-goog
#1 lore raw

PATCH v5 1/8 libfdt: Check NUL byte before memcmp() in fdt_find_string_len_()

In fdt_find_string_len_(), commit c954f9dd8357 ("libfdt: Speed up fdt_find_string_len_() with memchr()") bounds p by last = strtab + tabsize - (slen + 1), so p[slen] is always within strtab.

Check p[slen] == '\0' before memcmp(p, s, slen) == 0 so that candidate s[0] matches whose remaining length to '\0' is not slen skip calling memcmp(). On a real 855-string (11,259-byte) Qualcomm DTB dt_strings block, this cuts memcmp() calls during table construction from ~187k to ~14k (~20% faster overall at -O2).

Assisted-by Gemini:gemini-pro-prerelease

---

Changes in v5:
- New follow-up patch checking p[slen] == '\0' before memcmp() in fdt_find_string_len_() (David Laight)

 libfdt/fdt.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
libfdt/fdt.c +1 -1
index c7cedfba7815..403063787873 100644
@@ -358,7 +358,7 @@ const char *fdt_find_string_len_(const char *strtab, int tabsize, const char *s,
 
 	last = strtab + tabsize - (slen + 1);
 	while (p <= last && (p = memchr(p, s[0], last - p + 1)) != NULL) {
-		if (memcmp(p, s, slen) == 0 && p[slen] == '\0')
+		if (p[slen] == '\0' && memcmp(p, s, slen) == 0)
 			return p;
 		p++;
 	}
Signature · 1 line
2.56.1.987.g2ec0ab4260-goog
#2 lore raw

PATCH v5 2/8 libpydt: Add DeviceTree live tree representation

In reply to Douglas Anderson

pylibfdt's Fdt and FdtRo classes operate directly on flattened device tree blobs, where inserting or deleting nodes and properties shifts subsequent node offsets. That works well for in-place queries and localized edits, but makes multi-tree comparison, structural diffing, and bottom-up tree construction (as needed by the upcoming fdtfactor tool) awkward and error-prone.

Add pylibfdt/libpydt.py providing DeviceTree, an in-memory live tree representation where each node holds props (a dict mapping property name to libfdt.Property) and children (a dict mapping child node name to child DeviceTree), along with unflatten() and flatten() to convert between FdtRo/Fdt blobs and live trees, and helpers for path lookup, node creation, and pre-order traversal.

Add unit tests in tests/libpydt_tests.py covering DeviceTree round-tripping, subtree unflattening, duplicate-name and corrupt-tree rejection, and navigation helpers.

Assisted-by Gemini:gemini-pro-prerelease

---

(no changes since v4)

Changes in v4:
- Start the commit message with the motivation for a live tree and condense the summary (Simon Glass)
- Rename devicetree.py to libpydt.py (under pylibfdt/) to avoid colliding with PyPI's python-devicetree package, and move its unit tests into a separate tests/libpydt_tests.py file (Simon Glass, David Gibson)
- Unflatten the tree in a single O(n) pass using fdt.next_node() instead of recursive O(d * n) fdt.subnodes() traversal, raising FdtException on corrupt/truncated trees, and add a unit test (David Gibson, Simon Glass)
- Implement DeviceTree.walk() iteratively with an explicit stack instead of recursive yield from, and populate node.props directly in unflatten()
- Drop redundant fdt.pack() call from DeviceTree.flatten() (David Gibson)
- Drop get_*/set_* typed wrapper methods from DeviceTree in favor of Property.as_*() and Property.from_*() plus DeviceTree.set_prop() (David Gibson)
- Drop unnecessary copy.deepcopy() and compare unordered node/child sets instead of ordered lists in round-trip test (David Gibson)

Changes in v3:
- Move NodeTree out of pylibfdt/libfdt.i into a new devicetree.py module and rename it to DeviceTree (David Gibson)
- Store libfdt.Property objects in self.props instead of raw bytes (David Gibson)
- Return a packed libfdt.Fdt object from flatten() instead of raw bytes and use fdt.set_boot_cpuid_phys() (David Gibson, Simon Glass)
- Raise ValueError in unflatten() on duplicate property or sibling subnode names (Simon Glass)

Changes in v2:
- Split live tree representation out of fdtfactor (David Gibson)

 pylibfdt/libpydt.py    | 184 +++++++++++++++++++++++++++++++++++++++++
 pylibfdt/meson.build   |   2 +
 tests/libpydt_tests.py | 106 ++++++++++++++++++++++++
 tests/meson.build      |   2 +-
 tests/run_tests.sh     |  13 ++-
 5 files changed, 302 insertions(+), 5 deletions(-)
 create mode 100644 pylibfdt/libpydt.py
 create mode 100644 tests/libpydt_tests.py
pylibfdt/libpydt.py new file +184 -0
new file mode 100644
index 000000000000..6d8501f432ca
@@ -0,0 +1,184 @@
+# SPDX-License-Identifier: (GPL-2.0-or-later OR BSD-2-Clause)
+"""libpydt - Non-flattened in-memory device tree representation in Python."""
+
+import libfdt
+
+
+class DeviceTree:
+    """In-memory live tree representation of a devicetree node and its subtree.
+
+    `props` and `children` are public dictionaries intended to be accessed and
+    manipulated directly by callers (e.g. `node.props['status'].as_str()`,
+    `node.props.get('reg')`, `node.children.get('soc')`), with `set_prop()`
+    provided as a convenience for inserting a `libfdt.Property` under its own
+    `prop.name`.
+
+    Attributes:
+        props: Dict mapping property name (str) to `libfdt.Property`.
+        children: Dict mapping child node name (str) to child `DeviceTree`.
+    """
+
+    def __init__(self):
+        self.props = {}
+        self.children = {}
+
+    @classmethod
+    def unflatten(cls, fdt, offset=0):
+        """Unflatten an FdtRo subtree starting at `offset` into a DeviceTree.
+
+        Args:
+            fdt: An `FdtRo` (or `Fdt`) instance.
+            offset: Starting node offset (default 0 for the root node).
+
+        Returns:
+            A `DeviceTree` representing the node at `offset` and its
+            descendants.
+
+        Raises:
+            ValueError: If a node contains duplicate property names or
+                duplicate sibling subnode names.
+        """
+        stack = []
+        depth = 0
+        while depth >= 0:
+            node = cls()
+            props = node.props
+            for prop in fdt.properties(offset):
+                name = prop.name
+                if name in props:
+                    raise ValueError(f'Duplicate property {name!r}')
+                props[name] = prop
+            if depth == 0:
+                stack = [node]
+            else:
+                parent = stack[depth - 1]
+                subname = fdt.get_name(offset)
+                if subname in parent.children:
+                    raise ValueError(f'Duplicate subnode {subname!r}')
+                parent.children[subname] = node
+                del stack[depth:]
+                stack.append(node)
+            offset, depth = fdt.next_node(offset, depth)
+            if offset < 0:
+                libfdt.check_err(offset)
+        return stack[0]
+
+    def _flatten_subtree(self, sw, name):
+        """Recursively write this DeviceTree 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, 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 DeviceTree into a packed `libfdt.Fdt` object.
+
+        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:
+            Packed `libfdt.Fdt` instance.
+        """
+        sw = libfdt.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(boot_cpuid_phys)
+        return fdt
+
+    def set_prop(self, prop):
+        """Insert or replace a `libfdt.Property` in `self.props` under `prop.name`.
+
+        Args:
+            prop: `libfdt.Property` instance to store at `self.props[prop.name]`.
+        """
+        self.props[prop.name] = prop
+
+    def get_node(self, path):
+        """Look up a descendant DeviceTree 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 `DeviceTree` 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 DeviceTree at `path`, creating missing nodes.
+
+        Looks up a child or deeper descendant `DeviceTree` 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
+        `DeviceTree` is created for it automatically (similar to `mkdir -p`).
+        Passing `''` or `'/'` returns `self`.
+
+        Example:
+            root = DeviceTree()
+            # Automatically creates root.children['soc'] and
+            # root.children['soc'].children['i2c@4000'], and returns the
+            # 'i2c@4000' DeviceTree.
+            i2c = root.create_path('/soc/i2c@4000')
+            i2c.set_prop(libfdt.Property.from_str('status', 'okay'))
+
+        Args:
+            path: Slash-separated node path starting from `self` (e.g.
+                `'/soc/i2c@4000'` or `'soc/i2c@4000'`).
+
+        Returns:
+            The `DeviceTree` 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 in pre-order by each
+            descendant `DeviceTree`.
+        """
+        stack = [(path, self)]
+        while stack:
+            cur_path, node = stack.pop()
+            yield cur_path, node
+            prefix = cur_path.rstrip('/')
+            for name, child in reversed(node.children.items()):
+                stack.append((f'{prefix}/{name}', child))
pylibfdt/meson.build +2 -0
index b13d8021497f..ccf6c1bf78a6 100644
@@ -19,3 +19,5 @@ pylibfdt = py.extension_module(
   dependencies: [libfdt_dep, py.dependency()],
   install: true,
 )
+
+py.install_sources('libpydt.py', pure: false)
tests/libpydt_tests.py new file +106 -0

106 lines not on this page · raw message

tests/meson.build +1 -1
index 97fb15a64ea8..662213788196 100644
@@ -120,7 +120,7 @@ if not pylibfdt_enabled
 else
   env += [
     'PYTHON=' + py.full_path(),
-    'PYTHONPATH=' + meson.project_build_root() / 'pylibfdt',
+    'PYTHONPATH=' + meson.project_build_root() / 'pylibfdt' + ':' + meson.project_source_root() / 'pylibfdt',
     'NO_PYTHON=0',
   ]
 endif
tests/run_tests.sh +9 -4
index 467a9dc3520d..8053de9953d6 100755
@@ -1216,17 +1216,16 @@ fdtoverlay_tests() {
     run_wrap_test test "$bd" = "$pd"
 }
 
-pylibfdt_tests () {
-    run_dtc_test -I dts -O dtb -o test_props.dtb "$SRCDIR/test_props.dts"
+run_python_tests () {
     TMP=/tmp/tests.stderr.$$
-    $PYTHON "$SRCDIR/pylibfdt_tests.py" -v 2> $TMP
+    $PYTHON "$1" -v 2> $TMP
 
     # Use the 'ok' message meaning the test passed, 'ERROR' meaning it failed
     # and the summary line for total tests (e.g. 'Ran 17 tests in 0.002s').
     # We could add pass + fail to get total tests, but this provides a useful
     # sanity check.
     pass_count=$(grep "ok$" $TMP | wc -l)
-    fail_count=$(grep "^ERROR: " $TMP | wc -l)
+    fail_count=$(grep "^ERROR: \|^FAIL: " $TMP | wc -l)
     total_tests=$(sed -n 's/^Ran \([0-9]*\) tests.*$/\1/p' $TMP)
     cat $TMP
     rm $TMP
@@ -1237,6 +1236,12 @@ pylibfdt_tests () {
     tot_tests=$((tot_tests + $total_tests))
 }
 
+pylibfdt_tests () {
+    run_dtc_test -I dts -O dtb -o test_props.dtb "$SRCDIR/test_props.dts"
+    run_python_tests "$SRCDIR/pylibfdt_tests.py"
+    run_python_tests "$SRCDIR/libpydt_tests.py"
+}
+
 while getopts "vt:me" ARG ; do
     case $ARG in
 	"v")
Signature · 1 line
2.56.1.987.g2ec0ab4260-goog
#3 lore raw

PATCH v5 3/8 libfdt: overlay: Update base /__local_fixups__ on apply

In reply to 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 (for example, so an OS kernel can identify phandle cells at runtime, so a composite .dtb built by fdtoverlay such as Linux's foo-dtbs := base.dtb bar.dtbo retains complete phandle metadata for tools like fdtfactor, or so a merged tree matches what dtc -L produces).

fdt_overlay_apply() updates the base tree's /__symbols__ via overlay_symbol_update(), but leaves the base tree's /__local_fixups__ untouched. As a result, applying an overlay to a base tree with /__local_fixups__ leaves /__local_fixups__ missing the phandle references introduced by the overlay (both from the overlay's /__local_fixups__ and from its resolved /__fixups__), and leaves stale offsets if the overlay overwrites a base property that previously had phandle references.

Add overlay_local_fixups_update(), controlled by a 3-state compile-time FDT_OVERLAY_LOCAL_FIXUPS setting in libfdt/libfdt_internal.h:

- 0 (FDT_OVERLAY_LOCAL_FIXUPS_IGNORE): Leave /__local_fixups__ untouched. This is the #ifndef fallback in libfdt_internal.h so that size-sensitive embedded environments (such as U-Boot SPL) that vendor libfdt directly get negligible code-size impact and no behavior change unless they opt in.
- 1 (FDT_OVERLAY_LOCAL_FIXUPS_STRIP): Delete /__local_fixups__ from the base tree if present (~50 bytes of code), avoiding leaving a stale/incomplete /__local_fixups__ node in the merged tree.
- 2 (FDT_OVERLAY_LOCAL_FIXUPS_UPDATE): Fully update the base tree's /__local_fixups__ node when present (clearing entries for overwritten properties, merging offsets from the overlay's /__local_fixups__ and /__fixups__ in sorted ascending order, and pruning any subnodes that become empty). 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.

Assisted-by Gemini:gemini-pro-prerelease

---

Changes in v5:
- Make fdt_add_empty_subnode_() static via VISIBLE_IF_LOCAL_FIXUPS_UPDATE when FDT_OVERLAY_LOCAL_FIXUPS != FDT_OVERLAY_LOCAL_FIXUPS_UPDATE so non-UPDATE builds inline it back into fdt_add_subnode_namelen(), and temper the code-size wording in libfdt_internal.h and the commit message (Simon Glass)

Changes in v4:
- Split out internal helper fdt_add_empty_subnode_() so overlay_fragment_local_fixups() avoids passing an in-blob pointer to fdt_add_subnode_namelen() or casting fdt_get_name() (Simon Glass)
- Add test cases in tests/overlay.c where the overlay target has no existing subnode under /__local_fixups__, with /__local_fixups__ both before and after the target in the blob (Simon Glass)
- Pass OVERLAY_LOCAL_FIXUPS to tests/run_tests.sh, adjust fdtoverlay_tests for all three modes, and use 4-space indentation (Simon Glass, David Gibson)

Changes in v3:
- Move constifying fdto in overlay_apply_node() into a standalone preparatory patch (David Gibson)
- Gate /__local_fixups__ handling behind a 3-state compile-time FDT_OVERLAY_LOCAL_FIXUPS flag (0=ignore, 1=strip, 2=update), defaulting to 0 (IGNORE) in libfdt_internal.h for embedded builds and 2 (UPDATE) in Meson/Make desktop builds (Simon Glass, David Gibson)
- Rewrite commit message in the present tense with motivation up front, and update fdt_overlay_apply() documentation in libfdt/libfdt.h (Simon Glass)
- Require a strict relative path in overlay_create_path() and return -FDT_ERR_BADOVERLAY on empty path components or trailing '/' (David Gibson)
- Eliminate the 256-byte namebuf limit in overlay_fragment_local_fixups() by re-reading the node name from the shifted ancestor offset after fdt_add_subnode_namelen() (David Gibson, Simon Glass)
- Return -FDT_ERR_BADVALUE instead of -FDT_ERR_BADSTRUCTURE in overlay_add_local_fixup_offset() when an existing /__local_fixups__ property length is not a multiple of 4 (David Gibson, Simon Glass)
- Drop redundant overlay_validate_local_fixups() pre-pass and inline single-use helpers (Simon Glass)

Changes in v2:
- New patch updating base /__local_fixups__ in libfdt fdt_overlay_apply() instead of stripping /__local_fixups__ by default (David Gibson)

 Makefile                 |   6 +-
 libfdt/fdt_overlay.c     | 525 ++++++++++++++++++++++++++++++++++++++-
 libfdt/fdt_rw.c          |  38 ++-
 libfdt/libfdt.h          |   7 +
 libfdt/libfdt_internal.h |  29 +++
 meson.build              |   5 +
 meson_options.txt        |   2 +
 tests/Makefile.tests     |   6 +-
 tests/meson.build        |   1 +
 tests/overlay.c          | 154 ++++++++++++
 tests/run_tests.sh       |  32 +++
 11 files changed, 787 insertions(+), 18 deletions(-)
Makefile +5 -1
index a5dd1ee0c662..0e105081dcbd 100644
@@ -21,7 +21,11 @@ CONFIG_LOCALVERSION =
 # See libfdt_internal.h for details
 ASSUME_MASK ?= 0
 
-CPPFLAGS = -I libfdt -I . -DFDT_ASSUME_MASK=$(ASSUME_MASK)
+# Control how fdt_overlay_apply() handles base /__local_fixups__ (0=ignore, 1=strip, 2=update)
+# See libfdt_internal.h for details
+OVERLAY_LOCAL_FIXUPS ?= 2
+
+CPPFLAGS = -I libfdt -I . -DFDT_ASSUME_MASK=$(ASSUME_MASK) -DFDT_OVERLAY_LOCAL_FIXUPS=$(OVERLAY_LOCAL_FIXUPS)
 WARNINGS = -Wall -Wcast-qual -Wmissing-prototypes -Wnested-externs \
 	-Wpointer-arith -Wredundant-decls -Wshadow -Wsign-compare \
 	-Wstrict-prototypes -Wwrite-strings
libfdt/fdt_overlay.c +522 -3

543 lines not on this page · raw message

libfdt/fdt_rw.c +27 -11
index 1f2c56f400a7..9a292d5a2589 100644
@@ -378,8 +378,9 @@ int fdt_delprop(void *fdt, int nodeoffset, const char *name)
 	return fdt_splice_struct_(fdt, prop, proplen, 0);
 }
 
-int fdt_add_subnode_namelen(void *fdt, int parentoffset,
-			    const char *name, int namelen)
+VISIBLE_IF_LOCAL_FIXUPS_UPDATE
+int fdt_add_empty_subnode_(void *fdt, int parentoffset, int namelen,
+			   char **namep)
 {
 	struct fdt_node_header *nh;
 	int offset, nextoffset;
@@ -388,14 +389,6 @@ int fdt_add_subnode_namelen(void *fdt, int parentoffset,
 	uint32_t tag;
 	fdt32_t *endtag;
 
-	FDT_RW_PROBE(fdt);
-
-	offset = fdt_subnode_offset_namelen(fdt, parentoffset, name, namelen);
-	if (offset >= 0)
-		return -FDT_ERR_EXISTS;
-	else if (offset != -FDT_ERR_NOTFOUND)
-		return offset;
-
 	/* Try to place the new node after the parent's properties */
 	tag = fdt_next_tag(fdt, parentoffset, &nextoffset);
 	/* the fdt_subnode_offset_namelen() should ensure this never hits */
@@ -415,9 +408,32 @@ int fdt_add_subnode_namelen(void *fdt, int parentoffset,
 
 	nh->tag = cpu_to_fdt32(FDT_BEGIN_NODE);
 	memset(nh->name, 0, FDT_TAGALIGN(namelen+1));
-	memcpy(nh->name, name, namelen);
 	endtag = (fdt32_t *)((char *)nh + nodelen - FDT_TAGSIZE);
 	*endtag = cpu_to_fdt32(FDT_END_NODE);
+	*namep = nh->name;
+
+	return offset;
+}
+
+int fdt_add_subnode_namelen(void *fdt, int parentoffset,
+			    const char *name, int namelen)
+{
+	char *namep;
+	int offset;
+
+	FDT_RW_PROBE(fdt);
+
+	offset = fdt_subnode_offset_namelen(fdt, parentoffset, name, namelen);
+	if (offset >= 0)
+		return -FDT_ERR_EXISTS;
+	else if (offset != -FDT_ERR_NOTFOUND)
+		return offset;
+
+	offset = fdt_add_empty_subnode_(fdt, parentoffset, namelen, &namep);
+	if (offset < 0)
+		return offset;
+
+	memcpy(namep, name, namelen);
 
 	return offset;
 }
libfdt/libfdt.h +7 -0
index c69a18edf09f..c2f47a7d3e87 100644
@@ -2472,6 +2472,13 @@ int fdt_del_node(void *fdt, int nodeoffset);
  * fdt_overlay_apply() will apply the given device tree overlay on the
  * given base device tree.
  *
+ * If the base device tree contains a /__symbols__ node, it is updated with
+ * any symbols from the overlay. If the base device tree contains a
+ * /__local_fixups__ node, how it is handled depends on the build-time
+ * FDT_OVERLAY_LOCAL_FIXUPS setting (see libfdt_internal.h): left untouched
+ * (IGNORE), deleted (STRIP), or updated to reflect phandle references in the
+ * merged tree (UPDATE, the default when built via dtc's build system).
+ *
  * Expect the base device tree to be modified, even if the function
  * returns an error.
  *
libfdt/libfdt_internal.h +29 -0
index eefea2a3ccf3..3da52f565603 100644
@@ -99,6 +99,35 @@ static inline uint64_t fdt64_ld_(const fdt64_t *p)
 #define FDT_PARENT_MAX_DEPTH 32
 #endif
 
+/*
+ * Controls how fdt_overlay_apply() handles a /__local_fixups__ node in the
+ * base device tree:
+ *   0 (FDT_OVERLAY_LOCAL_FIXUPS_IGNORE): Leave /__local_fixups__ untouched
+ *     (negligible code-size impact and preserves historical behavior; default
+ *     when building libfdt standalone without dtc's build system).
+ *   1 (FDT_OVERLAY_LOCAL_FIXUPS_STRIP): Delete /__local_fixups__ from the
+ *     base device tree so a stale/incomplete /__local_fixups__ node is not
+ *     left behind (~50 bytes of code).
+ *   2 (FDT_OVERLAY_LOCAL_FIXUPS_UPDATE): Fully update /__local_fixups__ in
+ *     the base device tree with the overlay's local and resolved external
+ *     phandle fixups (default when building via dtc's Meson/Make build).
+ */
+#define FDT_OVERLAY_LOCAL_FIXUPS_IGNORE	0
+#define FDT_OVERLAY_LOCAL_FIXUPS_STRIP	1
+#define FDT_OVERLAY_LOCAL_FIXUPS_UPDATE	2
+
+#ifndef FDT_OVERLAY_LOCAL_FIXUPS
+#define FDT_OVERLAY_LOCAL_FIXUPS	FDT_OVERLAY_LOCAL_FIXUPS_IGNORE
+#endif
+
+#if FDT_OVERLAY_LOCAL_FIXUPS == FDT_OVERLAY_LOCAL_FIXUPS_UPDATE
+#define VISIBLE_IF_LOCAL_FIXUPS_UPDATE
+int fdt_add_empty_subnode_(void *fdt, int parentoffset, int namelen,
+			   char **namep);
+#else
+#define VISIBLE_IF_LOCAL_FIXUPS_UPDATE	static
+#endif
+
 /*
  * Defines assumptions which can be enabled. Each of these can be enabled
  * individually. For maximum safety, don't enable any assumptions!
meson.build +5 -0
index 2a8af7546f6b..ed6a31a1d6c1 100644
@@ -29,6 +29,11 @@ add_project_arguments(
   language: 'c'
 )
 
+add_project_arguments(
+  '-DFDT_OVERLAY_LOCAL_FIXUPS=' + get_option('overlay-local-fixups').to_string(),
+  language: 'c'
+)
+
 yamltree = 'yamltree.c'
 yaml = dependency('yaml-0.1', version: '>=0.2.3', required: get_option('yaml'))
 if not yaml.found()
meson_options.txt +2 -0
index a866b172e802..ac8ea4aa2a9f 100644
@@ -2,6 +2,8 @@ option('tools', type: 'boolean', value: true,
        description: 'Build tools')
 option('assume-mask', type: 'integer', value: 0,
        description: 'Control the assumptions made (e.g. risking security issues) in the code.')
+option('overlay-local-fixups', type: 'integer', value: 2,
+       description: 'Control how fdt_overlay_apply() handles base /__local_fixups__ (0=ignore, 1=strip, 2=update)')
 option('yaml', type: 'feature', value: 'auto',
        description: 'YAML support')
 option('valgrind', type: 'feature', value: 'auto',
tests/Makefile.tests +3 -3
index dfb2fe529590..af3b19eed827 100644
@@ -81,18 +81,18 @@ tests_clean:
 	rm -rf $(TESTS_CLEANDIRS)
 
 check:	tests ${TESTS_BIN} $(TESTS_PYLIBFDT)
-	cd $(TESTS_PREFIX); ./run_tests.sh
+	cd $(TESTS_PREFIX); OVERLAY_LOCAL_FIXUPS=$(OVERLAY_LOCAL_FIXUPS) ./run_tests.sh
 
 ifeq ($(NO_VALGRIND),1)
 checkm:
 	@echo "make checkm requires valgrind, but NO_VALGRIND=1"
 else
 checkm: tests ${TESTS_BIN} $(TESTS_PYLIBFDT)
-	cd $(TESTS_PREFIX); ./run_tests.sh -m
+	cd $(TESTS_PREFIX); OVERLAY_LOCAL_FIXUPS=$(OVERLAY_LOCAL_FIXUPS) ./run_tests.sh -m
 endif
 
 checkv:	tests ${TESTS_BIN} $(TESTS_PYLIBFDT)
-	cd $(TESTS_PREFIX); ./run_tests.sh -v
+	cd $(TESTS_PREFIX); OVERLAY_LOCAL_FIXUPS=$(OVERLAY_LOCAL_FIXUPS) ./run_tests.sh -v
 
 ifneq ($(DEPTARGETS),)
 -include $(TESTS_DEPFILES)
tests/meson.build +1 -0
index 662213788196..42cb0c32716a 100644
@@ -129,6 +129,7 @@ if not yaml.found()
 else
   env += 'NO_YAML=0'
 endif
+env += 'OVERLAY_LOCAL_FIXUPS=' + get_option('overlay-local-fixups').to_string()
 
 run_test_types = [
   'libfdt',
tests/overlay.c +154 -0

172 lines not on this page · raw message

tests/run_tests.sh +32 -0
index 8053de9953d6..75f06e38b58b 100755
@@ -11,6 +11,10 @@ if [ -z "$PYTHON" ]; then
     PYTHON=python3
 fi
 
+if [ -z "$OVERLAY_LOCAL_FIXUPS" ]; then
+    OVERLAY_LOCAL_FIXUPS=2
+fi
+
 if [ -n "$NO_PYTHON" ]; then
     if [ "$NO_PYTHON" != "0" ]; then
         no_python=true
@@ -1214,6 +1218,34 @@ fdtoverlay_tests() {
 
     shorten_echo "check phandle to noda d wasn't overwritten:	"
     run_wrap_test test "$bd" = "$pd"
+
+    # verify how /__local_fixups__ in a -L base blob is handled 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_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
+    if [ "$OVERLAY_LOCAL_FIXUPS" -eq 2 ]; then
+        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_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"
+    elif [ "$OVERLAY_LOCAL_FIXUPS" -eq 1 ]; then
+        run_test check_path overlay_base_phandle_lfO.test.dtb not-exists "/__local_fixups__"
+        run_test check_path overlay_base_lfO.test.dtb not-exists "/__local_fixups__"
+    else
+        run_fdtget_test 0 overlay_base_phandle_lfO.test.dtb /__local_fixups__/b a
+        run_wrap_error_test $DTGET overlay_base_phandle_lfO.test.dtb /__local_fixups__/b d
+        run_fdtget_test 0 overlay_base_lfO.test.dtb /__local_fixups__/test-node/sub-test-node new-sub-test-property
+    fi
 }
 
 run_python_tests () {
Signature · 1 line
2.56.1.987.g2ec0ab4260-goog
#4 lore raw

PATCH v5 4/8 fdtfactor: Add tool to split DTBs into a base DTB and overlays

In reply to Douglas Anderson

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 on pylibfdt and libpydt 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).

Assisted-by Gemini:gemini-pro-prerelease

---

(no changes since v4)

Changes in v4:
- Rename -o/--outdir to -o/--output so standalone DTB mode and FIT mode share the same output option, and use 4-space indentation in tests/run_tests.sh (David Gibson)
- Update for libpydt rename, use Property.as_*(), Property.from_*(), and DeviceTree.set_prop() instead of DeviceTree get_*/set_* wrapper methods, and drop redundant bytes() copies on Property instances (David Gibson, Simon Glass)
- Replace ParsedDtb.raw_bytes with uncompressed_size, use early continue to reduce loop nesting, drop redundant set() before sorted() on local fixup offsets, and clarify pre-order walk and phandle comments (David Gibson)
- Allow dtc -@ -L inputs with no phandles (where dtc omits /__symbols__ and /__local_fixups__)
- Check _is_dtbo_overlay() on the unflattened DeviceTree, index ParsedDtb.nodes and base_nodes by path, and skip unchanged base nodes in _build_board_dtbo() to avoid repeated O(depth) traversals and per-property comparisons
- Handle OVERLAY_LOCAL_FIXUPS != 2 in fdtfactor_tests (Simon Glass)

Changes in v3:
- Update fdtfactor to use devicetree.DeviceTree and a FactoredTree subclass initializing self.phandle and self.fixups in __init__() (David Gibson, Simon Glass)
- Rename -b/--base-dtb to --output-base-dtb to avoid confusion with an input base DTB (David Gibson)
- Move the test rejecting input DTBs lacking /__local_fixups__ from the -S patch into this base patch (Simon Glass)

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                          | 881 +++++++++++++++++++++++++++++
 meson.build                        |   1 +
 tests/Makefile.tests               |   4 +-
 tests/fdtfactor_board1.dts         |  72 +++
 tests/fdtfactor_board2.dts         |  70 +++
 tests/fdtfactor_board3.dts         |  68 +++
 tests/fdtfactor_board3_shifted.dts |  68 +++
 tests/meson.build                  |   2 +-
 tests/run_tests.sh                 | 110 +++-
 tests/testutils.sh                 |   1 +
 12 files changed, 1315 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
index 0e105081dcbd..38bbcea16236 100644
@@ -169,7 +169,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 +881 -0

881 lines not on this page · raw message

meson.build +1 -0
index ed6a31a1d6c1..82365d48b158 100644
@@ -120,6 +120,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
index af3b19eed827..6c03a26e11bd 100644
@@ -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 +72 -0

72 lines not on this page · raw message

tests/fdtfactor_board2.dts new file +70 -0

70 lines not on this page · raw message

tests/fdtfactor_board3.dts new file +68 -0

68 lines not on this page · raw message

tests/fdtfactor_board3_shifted.dts new file +68 -0

68 lines not on this page · raw message

tests/meson.build +1 -1
index 42cb0c32716a..4d5cef19e5af 100644
@@ -145,7 +145,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 +107 -3

133 lines not on this page · raw message

tests/testutils.sh +1 -0
index 6b2f0d14e3e5..7f35ba8e4158 100644
@@ -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.1.987.g2ec0ab4260-goog
#5 lore raw

PATCH v5 5/8 fdtfactor: Add -S/--strip-local-fixups option

In reply to Douglas Anderson

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 (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 without -S reduces total uncompressed size from 7.69 MB to 932 KB (88.2% savings), while fdtfactor -S reduces it to 634 KB (91.8% savings, saving an additional 298 KB by omitting /__local_fixups__ from base.dtb).

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.

Assisted-by Gemini:gemini-pro-prerelease

---

(no changes since v4)

Changes in v4:
- Use 4-space indentation instead of mixed tabs and spaces in tests/run_tests.sh, and update context for -o/--output (David Gibson)

Changes in v3:
- Include both non--S (932 KB) and -S (634 KB) Trogdor size numbers in the commit message to show the savings of -S itself (Simon Glass)
- Pass -S to the negative test verifying that inputs lacking /__local_fixups__ are still rejected when -S is used, and move the non--S rejection test to the base fdtfactor patch (Simon Glass)

Changes in v2:
- Split -S/--strip-local-fixups into a separate opt-in patch (David Gibson)

 README.md          |  9 +++++++++
 fdtfactor          | 21 ++++++++++++++++++---
 tests/run_tests.sh | 19 +++++++++++++++++++
 3 files changed, 46 insertions(+), 3 deletions(-)
README.md +9 -0
index 9a8be74d47fe..198384cd8456 100644
@@ -228,6 +228,15 @@ Options:
 * `-o`, `--output`: Output directory for generated `.dtbo` files and
   `--output-base-dtb` (default: alongside each input `.dtb` for `.dtbo` files,
   current directory for `--output-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 +18 -3
index dfbee0aea2d6..a083a8c380a0 100755
@@ -675,11 +675,13 @@ def _build_board_dtbo(dtb, base_nodes, base_dtb_symbols,
     return bytes(dtbo_root.flatten().as_bytearray())
 
 
-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
@@ -694,7 +696,9 @@ def create_base_dtb_and_overlays(dtbs):
     base_dtb_blob = _serialize_base_dtb(
         base_nodes, base_dtb_symbols,
         dtbs[0].mem_rsv, dtbs[0].boot_cpuid_phys,
-        emit_local_fixups=any(d.has_local_fixups for d in dtbs),
+        emit_local_fixups=(
+            not strip_local_fixups and any(d.has_local_fixups for d in dtbs)
+        ),
     )
     dtbo_blobs = [
         _build_board_dtbo(
@@ -757,6 +761,14 @@ def parse_args(argv=None):
             'current directory for --output-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',
@@ -841,7 +853,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.output:
         os.makedirs(args.output, exist_ok=True)
tests/run_tests.sh +19 -0
index 6e36ff1719f8..646a0ed7095f 100755
@@ -1372,6 +1372,25 @@ fdtfactor_tests () {
     done
     run_wrap_error_test $PYTHON $FDTFACTOR -o fdtfactor_legacy.test.dir \
         fdtfactor_board1.nolf.test.dtb 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
+    # still rejected even when -S is passed.
+    run_wrap_error_test $PYTHON $FDTFACTOR -S -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 --output-base-dtb 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.1.987.g2ec0ab4260-goog
#6 lore raw

PATCH v5 6/8 fdtfactor: Support compressed DTB inputs and outputs

In reply to Douglas Anderson

Firmware and FIT build pipelines frequently store device tree blobs compressed with LZ4, LZMA/XZ, or gzip (e.g., .dtb.lz4).

Add -C / --compression (none, lz4, lz4_legacy, lzma, xz, gzip; default none) to fdtfactor to decompress compressed input DTBs before factoring and compress the resulting base.dtb and .dtbo outputs with the same algorithm:

- Support lz4 and lz4_legacy (via the lz4 CLI), lzma and xz (via Python's lzma module, using CHECK_CRC32 for XZ compatibility with kernel/bootloader decompressors), and gzip (via Python's gzip module).
- Default --output-base-dtb to base.dtb.<ext> matching -C / --compression (e.g., base.dtb.lz4 when -C lz4 is passed), and emit .dtbo.<ext> overlays.
- Report compressed size savings alongside uncompressed savings when -s / --stats is specified with compression enabled.

On the 47 Qualcomm SC7180 Trogdor Chromebook .dtb.lz4 files, fdtfactor -S -C lz4 reduces total LZ4-compressed size from 1.08 MB (built without -@ -L) to 214 KB (80.2% savings).

Assisted-by Gemini:gemini-pro-prerelease

---

(no changes since v4)

Changes in v4:
- Replace magic-byte/extension auto-detection and --base-compression with a single explicit -C/--compression option controlling both input and output compression (David Gibson)
- Drop unnecessary --stats documentation/help changes and use 4-space indentation in tests/run_tests.sh (David Gibson)
- Use check_factored_dtb in fdtfactor_tests so tests pass when OVERLAY_LOCAL_FIXUPS != 2 (Simon Glass)

Changes in v3:
- Update for -b/--base-dtb rename to --output-base-dtb (David Gibson)

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            |  11 ++-
 fdtfactor            | 208 ++++++++++++++++++++++++++++++++++++++-----
 tests/Makefile.tests |   5 +-
 tests/run_tests.sh   |  51 ++++++++++-
 4 files changed, 248 insertions(+), 27 deletions(-)
README.md +8 -3
index 198384cd8456..ac571384d421 100644
@@ -204,7 +204,8 @@ $ fdtoverlay -i base.dtb -o merged.dtb overlay1.dtbo overlay2.dtbo
 ## 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
+compiled device tree blobs (`.dtb`, or compressed `.dtb.lz4`, `.dtb.xz`,
+`.dtb.lzma`, `.dtb.gz` with `-C`) 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.
@@ -223,8 +224,12 @@ $ fdtfactor -o out_dir board1.dtb board2.dtb board3.dtb
 Options:
 
 * `--output-base-dtb`: Output filename for the common base `.dtb`
-  (default: `base.dtb`; placed in `--output` if specified, or the current
-  directory otherwise).
+  (default: `base.dtb`, or `base.dtb.<ext>` when `-C` / `--compression` is
+  used; placed in `--output` if specified, or the current directory
+  otherwise).
+* `-C`, `--compression`: Compression format for both input `.dtb` files and
+  generated `base.dtb` / `.dtbo` outputs: `none`, `lz4`, `lz4_legacy`, `lzma`,
+  `xz`, or `gzip` (default: `none`).
 * `-o`, `--output`: Output directory for generated `.dtbo` files and
   `--output-base-dtb` (default: alongside each input `.dtb` for `.dtbo` files,
   current directory for `--output-base-dtb`).
fdtfactor +186 -22

323 lines not on this page · raw message

tests/Makefile.tests +4 -1
index 6c03a26e11bd..5c7279f5cdf2 100644
@@ -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 +50 -1

63 lines not on this page · raw message

Signature · 1 line
2.56.1.987.g2ec0ab4260-goog
#7 lore raw

PATCH v5 7/8 fdtfactor: Add compiled FIT factoring support

In reply to Douglas Anderson

Bootloaders such as depthcharge on Chromebooks and U-Boot use Flattened Image Trees (FITs) to bundle a kernel image with multiple board FDT blobs (fdt-1, fdt-2, ...) and per-board configuration nodes.

Add -F/--fit, --min-overlap, and --single-base-dtb options to fdtfactor (writing the factored FIT to -o/--output, or updating --fit in place by default):

- Parse non-overlay type = "flat_dt" nodes under /images, decompressing their data blobs according to their compression property (none, lz4, lzma, xz, gzip).
- Reject FITs containing signature* subnodes under /images/* or /configurations/*, as modifying FDT blobs and configurations would invalidate cryptographic signatures.
- Partition the flat_dt blobs into factor groups by compatible FDT headers / FIT arch and load properties and shared normalized property byte overlap (>= --min-overlap%, default 50%, reusing select_best_candidate()'s _prop_byte_cost() model) so a single FIT 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 property overlap, failing only if their FDT headers, arch, or load properties differ.
- Insert each fdt-base-N node into /images (picking the next unused fdt-base-N name), replace each factored fdt-* node's data with its .dtbo overlay (preserving each node's compression setting, and stripping /__local_fixups__ from any unfactored single-board flat_dt nodes too when -S is passed), 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, --min-overlap, unfactored-singleton -S, pre-existing fdt-base-* / multi-pass, signed-FIT rejection, and --single-base-dtb FIT test cases to the fdtfactor test suite.

Assisted-by Gemini:gemini-pro-prerelease

---

(no changes since v4)

Changes in v4:
- Unify --outfile into -o/--output, and split standalone DTB vs. FIT options into separate README.md subsections and --help groups (David Gibson)
- Check _is_dtbo_overlay() directly in _extract_fit_fdt_entries() instead of adding OverlayBlobError to ParsedDtb (David Gibson)
- Map standard FIT hash algorithm names explicitly via FIT_HASH_ALGOS instead of passing raw names to hashlib.new() (David Gibson)
- Remove compression and entry from FIT grouping, document load, expose --min-overlap, and compute FIT group overlap using normalized property byte costs via _prop_byte_cost() instead of unweighted node paths (David Gibson)
- Strip /__local_fixups__ from unfactored single-board FIT flat_dt entries when -S/--strip-local-fixups is passed, and pick the next unused fdt-base-N node name instead of rejecting FITs that already contain fdt-base-* nodes
- Pass already-unflattened FactoredTree into ParsedDtb and intern normalized properties to integer IDs in group_fit_dtbs() to speed up multi-SoC FIT factoring
- Preserve whether input FIT FDT descriptions include a compression extension instead of unconditionally appending one
- Update for libpydt rename, use Property.as_*(), Property.from_*(), and DeviceTree.set_prop() instead of DeviceTree get_*/set_* wrapper methods, and drop redundant bytes() copies on Property instances (David Gibson, Simon Glass)
- Use check_factored_dtb and 4-space indentation in tests/run_tests.sh (Simon Glass, David Gibson)

Changes in v3:
- Use "FIT" instead of "FIT image" in documentation, comments, and commit messages (Simon Glass)
- Update for DeviceTree and --output-base-dtb (Simon Glass, David Gibson)

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                  |  89 +++-
 fdtfactor                  | 850 +++++++++++++++++++++++++++++++++----
 tests/Makefile.tests       |   2 +-
 tests/fdtfactor_lz4.its    | 109 +++++
 tests/fdtfactor_other1.dts |  67 +++
 tests/fdtfactor_other2.dts |  67 +++
 tests/fdtfactor_test.its   | 109 +++++
 tests/run_tests.sh         | 225 +++++++++-
 8 files changed, 1421 insertions(+), 97 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 +66 -23
index ac571384d421..304611eb763b 100644
@@ -203,14 +203,14 @@ $ fdtoverlay -i base.dtb -o merged.dtb overlay1.dtbo overlay2.dtbo
 
 ## fdtfactor
 
-`fdtfactor` is a Python tool built on `pylibfdt` that takes a set of
-compiled device tree blobs (`.dtb`, or compressed `.dtb.lz4`, `.dtb.xz`,
-`.dtb.lzma`, `.dtb.gz` with `-C`) 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
+`fdtfactor` is a Python tool built on `pylibfdt` that factors a set of
+compiled device tree blobs — either standalone `.dtb` files or
+`/images/fdt-*` nodes inside a compiled FIT — into a common base `.dtb`
+and per-board `.dtbo` overlays so that applying a board's `.dtbo` to the
+base `.dtb` recreates the original board device tree while reducing
+total storage size.
+
+Input `.dtb` blobs must be compiled with `dtc -@ -L` so that both
 `/__symbols__` (used to resolve overlay `/__fixups__` against `base.dtb`)
 and `/__local_fixups__` (used to identify phandle references inside
 property values) are present.
@@ -219,30 +219,73 @@ Basic usage:
 
 ```
 $ fdtfactor -o out_dir board1.dtb board2.dtb board3.dtb
+$ fdtfactor -F image.fit -o image.factored.fit
 ```
 
-Options:
+Common options:
 
+* `-S`, `--strip-local-fixups`: Omit `/__local_fixups__` from the generated
+  base `.dtb` and final reconstructed device trees. By default, `fdtfactor`
+  preserves `/__local_fixups__` on the 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 the base `.dtb` (and any unfactored FIT FDTs) to save space.
+* `-s`, `--stats`: Print size savings summary.
+
+### Standalone DTB Factoring
+
+When `-F` / `--fit` is not passed, `fdtfactor` takes two or more positional
+`.dtb` files (or compressed `.dtb.lz4`, `.dtb.xz`, `.dtb.lzma`, `.dtb.gz`
+files with `-C`) and writes a common base `.dtb` plus one `.dtbo` overlay per
+input file:
+
+* `-o`, `--output`: Output directory for generated `.dtbo` files and
+  `--output-base-dtb` (default: alongside each input `.dtb` for `.dtbo`
+  files, current directory for `--output-base-dtb`).
 * `--output-base-dtb`: Output filename for the common base `.dtb`
   (default: `base.dtb`, or `base.dtb.<ext>` when `-C` / `--compression` is
-  used; placed in `--output` if specified, or the current directory
+  used; placed in `-o` / `--output` if specified, or the current directory
   otherwise).
 * `-C`, `--compression`: Compression format for both input `.dtb` files and
   generated `base.dtb` / `.dtbo` outputs: `none`, `lz4`, `lz4_legacy`, `lzma`,
   `xz`, or `gzip` (default: `none`).
-* `-o`, `--output`: Output directory for generated `.dtbo` files and
-  `--output-base-dtb` (default: alongside each input `.dtb` for `.dtbo` files,
-  current directory for `--output-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.
+
+### FIT Factoring
+
+When `-F` / `--fit` is passed, `fdtfactor` updates a compiled Flattened Image
+Tree:
+
+* `-F`, `--fit`: Input compiled FIT (`.fit` / `.itb`) to factor.
+* `-o`, `--output`: Output FIT path (default: overwrite `--fit` in place).
+* `--min-overlap`: Minimum percentage (`0`–`100`, default: `50`) of normalized
+  property bytes shared with a group's common properties required to place a
+  `flat_dt` node into that group.
+* `--single-base-dtb`: Force a single `/images/fdt-base-1` across all FDTs in
+  the FIT regardless of property overlap.
+
+FIT behavior and constraints:
+
+* Non-overlay `type = "flat_dt"` subnodes under `/images` are decompressed
+  according to their FIT `compression` property (`none`, `lz4`, `lzma`, `xz`,
+  `gzip`) and partitioned into factor groups that share compatible FDT headers,
+  `arch`, and `load` properties and at least `--min-overlap`% of normalized
+  property bytes (or forced into a single group when `--single-base-dtb` is
+  passed).
+* For each group, `fdtfactor` inserts `/images/fdt-base-N`, converts each
+  member `/images/fdt-*` node into a `.dtbo` overlay (preserving each node's
+  `compression` setting and stripping any `load` address), prepends
+  `fdt-base-N` to matching `/configurations/conf-*` `fdt` string lists
+  (populating `compatible` from the board DTB's root node when omitted), and
+  recomputes `/images/*/hash*` digests.
+* Note that 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 FITs containing `signature*` subnodes are rejected because modifying
+  FDT blobs and configurations would invalidate cryptographic signatures; sign
+  the FIT after factoring.
 
 ### TODO
 
fdtfactor +778 -72

996 lines not on this page · raw message

tests/Makefile.tests +1 -1
index 5c7279f5cdf2..64b43a729729 100644
@@ -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 +67 -0

67 lines not on this page · raw message

tests/fdtfactor_other2.dts new file +67 -0

67 lines not on this page · raw message

tests/fdtfactor_test.its new file +109 -0

109 lines not on this page · raw message

tests/run_tests.sh +224 -1

237 lines not on this page · raw message

Signature · 1 line
2.56.1.987.g2ec0ab4260-goog
#8 lore raw

PATCH v5 8/8 fdtfactor: Parallelize blob compression and decompression

In reply to Douglas Anderson

When factoring dozens or hundreds of compressed DTBs (either standalone with -C or inside a compiled FIT with -F), running gzip, lzma, xz, or external lz4 processes sequentially spends several seconds compressing and decompressing blobs one at a time.

Because Python's zlib and _lzma C extensions and subprocess.run() for lz4 all release the GIL, add a small _map_blobs() helper using concurrent.futures.ThreadPoolExecutor to decompress input blobs and compress output base/overlay blobs across worker threads in deterministic input order whenever multiple compressed blobs are processed. Now that factor_dtb_files() also reads and decompresses input blobs up front, drop the unused fdt is None path from ParsedDtb.__init__() and make fdt a required argument.

Assisted-by Gemini:gemini-pro-prerelease

---
Found this speedup while benchmarking fdtfactor. It's not critical to functionality, but seems like a nice win.

Changes in v5:
- Always create the ThreadPoolExecutor inside _map_blobs() instead of threading a shared pool argument through factor_fit() and its helpers (Simon Glass)
- Drop the dead 'if fdt is None' path in ParsedDtb.__init__(), make 'fdt' a required argument, and update its docstring (Simon Glass)

Changes in v4:
- New patch parallelizing blob compression and decompression across worker threads

 fdtfactor | 149 +++++++++++++++++++++++++++++++++++++++---------------
 1 file changed, 107 insertions(+), 42 deletions(-)
fdtfactor +107 -42
index ebf40cdeaf92..74b376b9731a 100755
@@ -18,6 +18,7 @@ its embedded `/images/fdt-*` blobs into base DTBs (`fdt-base-1`, `fdt-base-2`,
 
 import argparse
 from collections import Counter
+import concurrent.futures
 import copy
 import gzip
 import hashlib
@@ -140,6 +141,29 @@ def compress_blob(raw_bytes, comp, filename=''):
     raise ValueError(f'{prefix}Unsupported compression type: {comp}')
 
 
+def _map_blobs(func, tasks):
+    """Apply `func(blob, comp, filename)` across `tasks`, parallelizing if compressed.
+
+    Python's `zlib` and `_lzma` C extensions and external `lz4` subprocesses
+    release the GIL, so running multiple compressed tasks across a
+    `ThreadPoolExecutor` overlaps compression and decompression across CPU
+    cores while preserving deterministic input order.
+
+    Args:
+        func: `decompress_blob` or `compress_blob`.
+        tasks: Sequence of `(blob_bytes, comp, filename)` tuples.
+
+    Returns:
+        List of processed `bytes` in the same order as `tasks`.
+    """
+    if len(tasks) < 2 or not any(
+        comp not in ('none', '', None) for _, comp, _ in tasks
+    ):
+        return [func(*t) for t in tasks]
+    with concurrent.futures.ThreadPoolExecutor() as pool:
+        return list(pool.map(lambda t: func(*t), tasks))
+
+
 def _is_dtbo_overlay(root):
     """Return True if `root` is a `.dtbo` overlay tree rather than a base DTB.
 
@@ -213,37 +237,29 @@ class ParsedDtb:
       independent of numeric phandle numbering.
     """
 
-    def __init__(self, filename, comp='none', fdt=None, root=None,
+    def __init__(self, filename, fdt, comp='none', root=None,
                  uncompressed_size=None, compressed_size=None):
-        """Parse an input FDT file or opened `FdtRo` into a `FactoredTree`.
+        """Parse an opened `FdtRo` into a normalized `FactoredTree`.
 
         Args:
-            filename: File path (or display name when `fdt` is provided).
+            filename: File path or display name for error reporting and stats.
+            fdt: Already-validated `libfdt.FdtRo` instance.
             comp: Compression format string (default: `'none'`).
-            fdt: Optional already-validated `libfdt.FdtRo` instance; if None,
-                read and decompressed from `filename`.
             root: Optional already-unflattened `FactoredTree` for `fdt`.
-            uncompressed_size: Uncompressed byte length when `fdt` is provided.
-            compressed_size: Raw/compressed byte length when `fdt` is provided.
+            uncompressed_size: Uncompressed byte length (defaults to
+                `fdt.totalsize()`).
+            compressed_size: Raw/compressed byte length (defaults to
+                `self.uncompressed_size`).
         """
         self.filename = filename
         self.compression = comp
-        if fdt is None:
-            with open(filename, 'rb') as f:
-                file_bytes = f.read()
-            self.compressed_size = len(file_bytes)
-            raw_bytes = decompress_blob(file_bytes, comp, filename=filename)
-            self.uncompressed_size = len(raw_bytes)
-            fdt = _open_fdt(raw_bytes, filename)
-        else:
-            self.uncompressed_size = (
-                fdt.totalsize() if uncompressed_size is None
-                else uncompressed_size
-            )
-            self.compressed_size = (
-                self.uncompressed_size if compressed_size is None
-                else compressed_size
-            )
+        self.uncompressed_size = (
+            fdt.totalsize() if uncompressed_size is None else uncompressed_size
+        )
+        self.compressed_size = (
+            self.uncompressed_size if compressed_size is None
+            else compressed_size
+        )
 
         self.boot_cpuid_phys = fdt.boot_cpuid_phys()
         self.mem_rsv = tuple(fdt.get_mem_rsv_list())
@@ -1081,7 +1097,7 @@ def _extract_fit_fdt_entries(fit_in_path, images_node, configs_node):
                     f'is not supported; sign the FIT after factoring'
                 )
 
-    fdt_entries = []
+    candidates = []
     for img_name, img_node in images_node.children.items():
         if ('data-offset' in img_node.props or
                 'data-position' in img_node.props):
@@ -1112,7 +1128,18 @@ def _extract_fit_fdt_entries(fit_in_path, images_node, configs_node):
             )
         if comp == 'lz4' and raw_data.startswith(LZ4_LEGACY_MAGIC):
             comp = 'lz4_legacy'
-        raw_bytes = decompress_blob(raw_data, comp, filename=node_label)
+        candidates.append((img_name, img_node, node_label, comp, raw_data))
+
+    raw_blobs = _map_blobs(
+        decompress_blob,
+        [(raw_data, comp, node_label)
+         for _, _, node_label, comp, raw_data in candidates],
+    )
+
+    fdt_entries = []
+    for (img_name, img_node, node_label, comp, raw_data), raw_bytes in zip(
+        candidates, raw_blobs
+    ):
         fdt = _open_fdt(raw_bytes, node_label)
         root = FactoredTree.unflatten(fdt)
         if _is_dtbo_overlay(root):
@@ -1120,8 +1147,8 @@ def _extract_fit_fdt_entries(fit_in_path, images_node, configs_node):
 
         parsed_dtb = ParsedDtb(
             node_label,
+            fdt,
             comp=comp,
-            fdt=fdt,
             root=root,
             uncompressed_size=len(raw_bytes),
             compressed_size=len(raw_data),
@@ -1201,6 +1228,7 @@ def _strip_fit_unfactored_local_fixups(unfactored_entries):
         unfactored_entries: List of single-board FIT `flat_dt` entry dicts left
             unfactored by `_partition_fit_fdt_entries()`.
     """
+    to_recompress = []
     for entry in unfactored_entries:
         fdt = entry.pop('fdt')
         tree = libpydt.DeviceTree.unflatten(fdt)
@@ -1210,12 +1238,19 @@ def _strip_fit_unfactored_local_fixups(unfactored_entries):
             mem_rsv=entry['dtb'].mem_rsv,
             boot_cpuid_phys=entry['dtb'].boot_cpuid_phys,
         )
-        comp_bytes = compress_blob(
-            bytes(stripped_fdt.as_bytearray()),
+        stripped_bytes = bytes(stripped_fdt.as_bytearray())
+        to_recompress.append((
+            entry['node'],
+            stripped_bytes,
             entry['dtb'].compression,
-            filename=f'/images/{entry["name"]}',
-        )
-        img_node = entry['node']
+            f'/images/{entry["name"]}',
+        ))
+
+    comp_blobs = _map_blobs(
+        compress_blob,
+        [(blob, comp, label) for _, blob, comp, label in to_recompress],
+    )
+    for (img_node, _, _, _), comp_bytes in zip(to_recompress, comp_blobs):
         img_node.set_prop(libfdt.Property('data', comp_bytes))
         _update_fit_hashes(img_node)
 
@@ -1241,9 +1276,19 @@ def _factor_fit_group(entries, base_dtb_node_name, strip_local_fixups):
     )
     base_comp = group_dtbs[0].compression
 
-    base_dtb_comp_bytes = compress_blob(
-        base_dtb_blob, base_comp, filename=f'/images/{base_dtb_node_name}'
+    comp_blobs = _map_blobs(
+        compress_blob,
+        [
+            (base_dtb_blob, base_comp, f'/images/{base_dtb_node_name}'),
+            *(
+                (dtbo_blob, entry['dtb'].compression, f'/images/{entry["name"]}')
+                for entry, dtbo_blob in zip(entries, dtbo_blobs)
+            ),
+        ],
     )
+    base_dtb_comp_bytes = comp_blobs[0]
+    dtbo_comp_blobs = comp_blobs[1:]
+
     base_dtb_node = copy.deepcopy(entries[0]['node'])
     for prop in ('phandle', 'compatible'):
         base_dtb_node.props.pop(prop, None)
@@ -1272,12 +1317,9 @@ def _factor_fit_group(entries, base_dtb_node_name, strip_local_fixups):
     _update_fit_hashes(base_dtb_node)
 
     dtbo_comp_sizes = []
-    for entry, dtbo_blob in zip(entries, dtbo_blobs):
+    for entry, dtbo_comp_bytes in zip(entries, dtbo_comp_blobs):
         img_node = entry['node']
         entry_comp = entry['dtb'].compression
-        dtbo_comp_bytes = compress_blob(
-            dtbo_blob, entry_comp, filename=f'/images/{entry["name"]}'
-        )
         dtbo_comp_sizes.append(len(dtbo_comp_bytes))
 
         if 'description' in img_node.props:
@@ -1668,7 +1710,24 @@ def factor_dtb_files(args):
     """
     comp = args.compression
     input_dtb_paths = args.dtbs
-    dtbs = [ParsedDtb(p, comp=comp) for p in input_dtb_paths]
+    file_blobs = []
+    for p in input_dtb_paths:
+        with open(p, 'rb') as f:
+            file_blobs.append(f.read())
+    raw_blobs = _map_blobs(
+        decompress_blob,
+        [(b, comp, p) for p, b in zip(input_dtb_paths, file_blobs)],
+    )
+    dtbs = [
+        ParsedDtb(
+            p,
+            _open_fdt(raw, p),
+            comp=comp,
+            uncompressed_size=len(raw),
+            compressed_size=len(fblob),
+        )
+        for p, fblob, raw in zip(input_dtb_paths, file_blobs, raw_blobs)
+    ]
 
     base_dtb_path = (
         os.path.join(args.output, args.output_base_dtb)
@@ -1706,20 +1765,26 @@ def factor_dtb_files(args):
         strip_local_fixups=args.strip_local_fixups,
     )
 
-    base_dtb_file_bytes = compress_blob(
-        base_dtb_blob, comp, filename=base_dtb_path
+    comp_blobs = _map_blobs(
+        compress_blob,
+        [
+            (base_dtb_blob, comp, base_dtb_path),
+            *((b, comp, p) for p, b in zip(dtbo_paths, dtbo_blobs)),
+        ],
     )
+    base_dtb_file_bytes = comp_blobs[0]
+    dtbo_comp_blobs = comp_blobs[1:]
+
     if args.output:
         os.makedirs(args.output, exist_ok=True)
     with open(base_dtb_path, 'wb') as f:
         f.write(base_dtb_file_bytes)
 
     dtbo_file_sizes = []
-    for out_path, dtbo_blob in zip(dtbo_paths, dtbo_blobs):
+    for out_path, out_bytes in zip(dtbo_paths, dtbo_comp_blobs):
         out_dir = os.path.dirname(out_path)
         if out_dir:
             os.makedirs(out_dir, exist_ok=True)
-        out_bytes = compress_blob(dtbo_blob, comp, filename=out_path)
         dtbo_file_sizes.append(len(out_bytes))
         with open(out_path, 'wb') as f:
             f.write(out_bytes)
Signature · 1 line
2.56.1.987.g2ec0ab4260-goog