[PATCH v2 01/10] pylibfdt: Fix FdtSw.as_fdt() when buffer is nearly full

From: Douglas Anderson

Date: Wed Oct 28 2026 - 17:57:03 EST


`FdtSw.as_fdt()` calls `fdt_finish()` on a copy of `self._fdt` without
using `self.check_space()`. Because `fdt_finish()` appends the 4-byte
`FDT_END` token, `as_fdt()` raises `FdtException(FDT_ERR_NOSPACE)` if
fewer than 4 bytes of free space remain in `self._fdt` after the final
`end_node()`.

Wrap `fdt_finish()` in a `while self.check_space(fdt_finish(fdtsw)):`
loop so `FdtSw.as_fdt()` automatically resizes the buffer when needed,
matching the rest of `FdtSw`'s methods.

Assisted-by: Gemini:gemini-pro-prerelease
Signed-off-by: Douglas Anderson <dianders@xxxxxxxxxxxx>
---

Changes in v2:
- New patch fixing FdtSw.as_fdt() buffer resize when < 4 bytes remain

pylibfdt/libfdt.i | 3 ++-
tests/pylibfdt_tests.py | 8 ++++++++
2 files changed, 10 insertions(+), 1 deletion(-)

diff --git a/pylibfdt/libfdt.i b/pylibfdt/libfdt.i
index b41c03f4932a..46f28f67290d 100644
--- a/pylibfdt/libfdt.i
+++ b/pylibfdt/libfdt.i
@@ -959,7 +959,8 @@ class FdtSw(FdtRo):
Fdt object allowing access to the newly created device tree
"""
fdtsw = bytearray(self._fdt)
- check_err(fdt_finish(fdtsw))
+ while self.check_space(fdt_finish(fdtsw)):
+ fdtsw = bytearray(self._fdt)
return Fdt(fdtsw)

def check_space(self, val):
diff --git a/tests/pylibfdt_tests.py b/tests/pylibfdt_tests.py
index 0e1660753477..1b65961491bf 100644
--- a/tests/pylibfdt_tests.py
+++ b/tests/pylibfdt_tests.py
@@ -646,6 +646,14 @@ class PyLibfdtSwTests(unittest.TestCase):
# Make sure we did at least two resizes
self.assertTrue(len(fdt.as_bytearray()) > FdtSw.INC_SIZE * 2)

+ # Check that as_fdt() resizes when fewer than 4 bytes remain for FDT_END
+ sw_exact = FdtSw(76)
+ sw_exact.finish_reservemap()
+ sw_exact.begin_node('')
+ sw_exact.end_node()
+ fdt_exact = sw_exact.as_fdt()
+ self.assertEqual(80, fdt_exact.totalsize())
+

class PyLibfdtRoTests(unittest.TestCase):
"""Test class for read-only pylibfdt access functions
--
2.56.0.313.g2479322e68-goog