[PATCH v4 03/14] pylibfdt: Trim Fdt bytearray to totalsize() in FdtSw.as_fdt()
From: Douglas Anderson
Date: Mon Nov 16 2026 - 15:54:09 EST
`fdt_finish()` relocates the string table directly after the structure
block and updates the FDT header `totalsize` to the packed size, but
`FdtSw.as_fdt()` left the backing Python `bytearray` at the
pre-allocated `FdtSw` buffer size (with trailing zero bytes beyond
`totalsize()`), forcing callers that serialize `fdt.as_bytearray()` to
call `fdt.pack()` just to truncate `_fdt`.
Truncate `fdtsw` to `fdt_totalsize(fdtsw)` in `FdtSw.as_fdt()` (matching
`Fdt.pack()`) so the returned `Fdt`'s `as_bytearray()` length matches
its `totalsize()` immediately.
Assisted-by: Gemini:gemini-pro-prerelease
Signed-off-by: Douglas Anderson <dianders@xxxxxxxxxxxx>
---
Changes in v4:
- New patch trimming the returned Fdt bytearray in FdtSw.as_fdt() so
DeviceTree.flatten() does not need to call fdt.pack() (David Gibson)
pylibfdt/libfdt.i | 1 +
tests/pylibfdt_tests.py | 2 ++
2 files changed, 3 insertions(+)
diff --git a/pylibfdt/libfdt.i b/pylibfdt/libfdt.i
index 8a7dfed85f15..68f22e316ece 100644
--- a/pylibfdt/libfdt.i
+++ b/pylibfdt/libfdt.i
@@ -1026,6 +1026,7 @@ class FdtSw(FdtRo):
fdtsw = bytearray(self._fdt)
while self.check_space(fdt_finish(fdtsw)):
fdtsw = bytearray(self._fdt)
+ del fdtsw[fdt_totalsize(fdtsw):]
return Fdt(fdtsw)
def check_space(self, val):
diff --git a/tests/pylibfdt_tests.py b/tests/pylibfdt_tests.py
index 78d8976c0cf3..26915a015ccb 100644
--- a/tests/pylibfdt_tests.py
+++ b/tests/pylibfdt_tests.py
@@ -684,6 +684,7 @@ class PyLibfdtSwTests(unittest.TestCase):
# Make sure we did at least two resizes
self.assertTrue(len(fdt.as_bytearray()) > FdtSw.INC_SIZE * 2)
+ self.assertEqual(fdt.totalsize(), len(fdt.as_bytearray()))
# Check that as_fdt() resizes when fewer than 4 bytes remain for FDT_END
sw_exact = FdtSw(76)
@@ -692,6 +693,7 @@ class PyLibfdtSwTests(unittest.TestCase):
sw_exact.end_node()
fdt_exact = sw_exact.as_fdt()
self.assertEqual(80, fdt_exact.totalsize())
+ self.assertEqual(80, len(fdt_exact.as_bytearray()))
class PyLibfdtRoTests(unittest.TestCase):
--
2.56.0.679.gc527c65306-goog