The grammar action for a top-level &{/path} { ... } holds its merge
logic, including making an overlay fragment in a plugin.
Move it into merge_ref(), which can tell a path from a label by looking
at the reference, and use a single rule for both kinds of reference.
The output does not change.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Simon Glass <sjg@chromium.org>
Reviewed-by: David Gibson <david@gibson.dropbear.id.au>
Message-ID: <20261126184126.1472738-9-sjg@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
In a plugin, &label { ... } is merged into the labelled node if the
label is in the plugin, as of commit 0fcffda15e ("Merge nodes with
local target label references"). But &{label} { ... } always becomes a
separate fragment@N node, since anything in braces is lexed as a path
reference. This adds an overlay fragment which is not needed, which that
commit aims to avoid, and fails with FDT_ERR_NOTFOUND if the label is
not within an overlay fragment.
Treat a reference as a path only if it starts with '/', so that both
forms are merged into the node. This changes the output for such a file.
Applying an overlay which already works gives the same result, apart
from the order of the properties and that a later &label { ... } now
overrides an earlier &{label} { ... }, as the source order suggests.
Other references are not affected. An absolute path still becomes a
fragment@N node, as does a label which is not in the plugin, since it
may be in the base tree.
This also means that dtc does not need to record whether a reference is
written in braces. The merge code, which is about to move out of the
grammar, can tell a path from a label by looking at the reference.
Add the merge-label-braces.dts and merge-label-order.dts tests to check
this.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Simon Glass <sjg@chromium.org>
Reviewed-by: David Gibson <david@gibson.dropbear.id.au>
Message-ID: <20261126184126.1472738-8-sjg@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
The grammar action for a top-level &label { ... } holds its merge logic,
including making an overlay fragment in a plugin when the label is not
found.
Move it into a new merge_ref(), passing it a struct source_layer for the
reference and node.
The output does not change.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Simon Glass <sjg@chromium.org>
Reviewed-by: David Gibson <david@gibson.dropbear.id.au>
Message-ID: <20261126184126.1472738-7-sjg@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
The grammar action for a top-level /omit-if-no-ref/ still holds its
merge logic.
Move it into a new merge_omit_if_no_ref(), passing it a struct
source_layer for the reference.
The output does not change.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Simon Glass <sjg@chromium.org>
Reviewed-by: David Gibson <david@gibson.dropbear.id.au>
Message-ID: <20261126184126.1472738-6-sjg@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
The grammar actions merge each source layer of a dts file into the tree
as it is parsed, so the merge logic is spread over the rules for each
kind of source layer. This makes it hard to follow and to change.
As a first step towards moving this logic into livetree.c, move the
action for a top-level /delete-node/ into a new merge_delete_node(),
passing it a struct source_layer for the reference.
The output does not change.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Simon Glass <sjg@chromium.org>
Reviewed-by: David Gibson <david@gibson.dropbear.id.au>
Message-ID: <20261126184126.1472738-5-sjg@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
A dts file is made up of source layers: the root node, later definitions
of a node by label or path, and /delete-node/ or /omit-if-no-ref/ with a
reference. We would like to deal with each source layer on its own
before it is merged, for example to apply deletes consistently or to run
some checks on each one, but that requires keeping the source layers
apart. At present the parser merges each one into the tree as soon as it
is parsed.
Add a struct source_layer to hold one which refers to a node, with a
function to build each kind and one to free it.
These are not used yet.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Simon Glass <sjg@chromium.org>
Reviewed-by: David Gibson <david@gibson.dropbear.id.au>
Message-ID: <20261126184126.1472738-4-sjg@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
In a plugin, label: &ref { ... } cannot become an overlay fragment,
since dtc cannot put a label on the target of one. So dtc reports an
error if the node is not in the plugin, whether ref is a label or a
path, but there is no test for this.
Add merge-labelled-missing.dts to check both errors.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Simon Glass <sjg@chromium.org>
Message-ID: <20261126184126.1472738-3-sjg@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
In a plugin, &{/} { ... } becomes an overlay fragment for the root node
of the base tree, unlike / { ... }. The merge-root-plugin.dts test checks
this, but this is existing behaviour rather than a deliberate choice,
and it is not clear that the two should differ.
Add a comment to the test to say so.
Suggested-by: David Gibson <david@gibson.dropbear.id.au>
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Simon Glass <sjg@chromium.org>
Message-ID: <20261126184126.1472738-2-sjg@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
When the parser merges the top-level fragments of a dts file, it can
report that a label or path is not found, or that a label-relative
reference is not supported in a plugin. Most of these errors are not
covered by any test, and the two tests which do reach them only check
that dtc fails, not the message or where it is reported. The merge
logic is about to move out of the grammar, so this needs better tests.
Add a test file for each error which is not covered, and check the
message and its position for all of them, including the two existing
ones. Also check that merging carries on after an error, so that later
errors are reported too, that a labelled reference within a plugin adds
the label, that / { ... } and &{/} { ... } differ in a plugin, and that
a label in a plugin becomes an overlay fragment if it is not found,
since nothing covers these either.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Simon Glass <sjg@chromium.org>
Message-ID: <20261116235813.935070-2-sjg@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
For make builds we enable the -Wcast-qual warning, but we overlooked this
for meson builds. Add it in, although this does require some workarounds
for MacOS, because it trips some warnings in the flex template code.
Note that make is also missing some warnings which we enable for meson,
however this is intentional: the warnings aren't available on all of the
platforms / compiler versions we support and unlike meson we don't have an
easy way to test for unsupported options in make.
While we're there sort the options alphabetically in both Makefile and
meson.build for easier maintenance.
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
Some recent patches fixed bugs where we didn't correctly zero padding bytes
inserted to correctly align out structures. However, the way it was done
potentially calls memset() with a zero length, which may not be safe on all
platforms. Correct it.
Correcting that exposes some careless mixing of signed and unsigned values,
so fix that as well.
Fixes: 5036c259132f ("libfdt: Zero padding in sequential write")
Fixes: cb9570afe7a4 ("libfdt: Zero name padding in fdt_set_name")
Fixes: ce51dcbd84 ("libfdt: Zero the padding after a property value")
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
fdt_begin_node() and fdt_property_placeholder() don't clear their
padding. fdt_create() zeroes the buffer but fdt_resize() doesn't, so
the padding can hold garbage. Zero it where the space is grabbed.
Signed-off-by: Tharaka Jayasena <9dmpires2k17.tuj@gmail.com>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
fdt_set_name copies newlen + 1 bytes into FDT_TAGALIGN(newlen + 1),
so a shorter name leaves the old name's tail in the padding. Clear it.
Signed-off-by: Tharaka Jayasena <9dmpires2k17.tuj@gmail.com>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
clangd creates many files in .cache/clangd for temporary state, and is
automatically started by the Zed editor. Ignore for git purposes.
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
`fdt_find_string_len_()` currently calls `memcmp()` at every byte offset
across the string table (`for (p = strtab; p <= last; p++)`). When
building or modifying trees with large string tables (such as DTBs and
overlays with hundreds of `/__symbols__` or `/__fixups__` labels via
`fdt_sw` or `fdt_rw`), scanning multi-kilobyte string tables byte by
byte dominates serialization time.
Advance `p` between candidate first-byte matches using `memchr()` (with
an explicit `slen == 0` check for empty property names and a `tabsize <
slen + 1` bounds check before computing `last`), preserving identical
suffix-sharing behavior.
On one stress test (running the fdtfactor tool across 438 arm64 Qualcomm
DTBs) this reduced `fdt_property()` time by ~5.6x.
Assisted-by: Gemini:gemini-pro-prerelease
Signed-off-by: Douglas Anderson <dianders@chromium.org>
Message-ID: <20261116205320.1621386-9-dianders@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
`Property.as_list()` currently decodes multi-cell properties via
`list(map(lambda x: x[0], struct.iter_unpack('>' + fmt, self)))`, which
constructs an iterator and `map` wrapper and invokes a Python `lambda`
for every cell.
Compute the element size via `struct.calcsize('>' + fmt)` and unpack all
elements in a single C `struct.unpack()` call instead.
On one stress test (decoding ~301k `/__local_fixups__` cell lists across
438 arm64 Qualcomm DTBs) this reduced `Property.as_list()` time by
~2.1x.
Assisted-by: Gemini:gemini-pro-prerelease
Signed-off-by: Douglas Anderson <dianders@chromium.org>
Message-ID: <20261116205320.1621386-6-dianders@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
`libfdt.Property` provides `as_*()` methods (`as_cell`, `as_uint32`,
`as_int32`, `as_uint64`, `as_int64`, `as_list`, `as_uint32_list`,
`as_int32_list`, `as_uint64_list`, `as_int64_list`, `as_str`, and
`as_stringlist`) to decode typed values from a `Property`, but lacks the
corresponding creation methods to construct a `Property` from typed
values.
Add `from_*()` classmethods mirroring each `as_*()` method so callers
(such as `DeviceTree` users) can construct typed `Property` instances
directly without duplicating encoding helpers on `DeviceTree`.
Assisted-by: Gemini:gemini-pro-prerelease
Signed-off-by: Douglas Anderson <dianders@chromium.org>
Message-ID: <20261116205320.1621386-5-dianders@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
`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@chromium.org>
Message-ID: <20261116205320.1621386-4-dianders@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
`Property` represents a snapshot of a property's name and value read
from a flattened device tree. Making `Property` a subclass of the
immutable `bytes` type instead of mutable `bytearray` prevents callers
from accidentally mutating a `Property` instance in place when sharing
it across data structures (such as `DeviceTree`), makes `Property`
hashable, and allows `Property` instances to be passed directly to
`Fdt.setprop()` without converting to `bytes` first.
Also return `bytes` instead of `bytearray` from the
`fdt_get_property_by_offset()` SWIG typemap and drop the redundant
`bytearray()` conversion in `FdtRo.getprop()`.
Assisted-by: Gemini:gemini-pro-prerelease
Signed-off-by: Douglas Anderson <dianders@chromium.org>
Message-ID: <20261116205320.1621386-3-dianders@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
`README.md` currently jumps directly from building `dtc` and `pylibfdt`
to mailing list information without mentioning `dtc` itself or the
ancillary utilities built and installed alongside it.
Add brief overview sections with basic usage examples for `dtc`,
`dtdiff`, `fdtget`, `fdtput`, `fdtdump`, `convert-dtsv0`, and
`fdtoverlay` (along with a pointer to `Documentation/manual.txt` for
full command-line details).
Assisted-by: Gemini:gemini-pro-prerelease
Signed-off-by: Douglas Anderson <dianders@chromium.org>
Message-ID: <20261116205320.1621386-2-dianders@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
An unchecked /__local_fixups__ offset lets an overlay make
fdt_overlay_apply() do a four byte read-modify-write up to 4 GiB past
the property it names, outside the caller's overlay buffer.
overlay_update_local_node_references() never compares the offset
against the length of the property it is patching.
Fix this by rejecting an offset that does not name a whole cell inside
the target property, there and in the identical pattern in
overlay_update_node_conflicting_references(), and add a test case.
Assisted-by: Aristotle (Harmonic) <aristotle-harmonic@harmonic.fun>
Signed-off-by: Gabe Dijkstra <gabe.dijkstra@harmonic.fun>
Message-ID: <20261116210119.1562863-1-gabe.dijkstra@harmonic.fun>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
fdt_setprop() and fdt_appendprop() size the value to FDT_TAGALIGN(len)
but copy only len bytes, so the padding keeps stale data: the old
value's tail when a property shrinks, or bytes of the following tags
when space is inserted. The devicetree specification requires the
padding to be zeroed, so clear it.
Signed-off-by: Tharaka Jayasena <9dmpires2k17.tuj@gmail.com>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
The remaining grammar actions which merge a fragment use
is_ref_relative() to reject a label-relative reference in a plugin.
Move it to livetree.c, so that it is available when these actions move
there too, and add a comment.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Simon Glass <sjg@chromium.org>
Reviewed-by: David Gibson <david@gibson.dropbear.id.au>
Message-ID: <20261106195159.2623314-7-sjg@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
To avoid clang-tidy (via Zed editor) warnings, and possible fragility from
relying on indirect includes.
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
clang-tidy (as invoked by Zed editor) complains about various not-directly
used #includes. Clean those up, though it does mean changing style a bit
(no longer using dtc.h to #include anything that any .c file might need).
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
Because fdtdump is a crappy debug tool, we don't do much checking of our
position as we scan through the dtb. But, we keep getting reports from
LLMs who think the sky is falling because there are memory handling errors
in there. So be more careful about our read offset and bounds check it as
we go.
Reported-by: 胡景浩 <jinghaohu33@163.com>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
Validate name offset values from FDT_PROP tags before attempting to print
the associated string.
Reported-by: 胡景浩 <jinghaohu33@163.com>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
If a dtb gives a memory reserve offset that's out of bounds, we'll access
bad memory. Bounds check to prevent it.
Reported-by: 胡景浩 <jinghaohu33@163.com>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
A position is not always available: a node read from a dtb has none, and
top-level fragments may eventually come from a dtbo as well as from
source. At present srcpos_string() crashes if it has no position, so
each caller which might not have one needs to check, as those in
checks.c do.
Return a placeholder in this case, using the same text as
srcpos_string_comment() does, so that srcpos_error() can be used whether
or not there is a position.
No caller passes NULL at present, so this has no test yet.
Suggested-by: David Gibson <david@gibson.dropbear.id.au>
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Simon Glass <sjg@chromium.org>
Message-ID: <20261106195159.2623314-3-sjg@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
MSYS2 appears to have removed the mingw-w64-i686-libyaml package, meaning
the Github CI fails during system setup. Disable yaml for the mingw32
builds to avoid the error.
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
Asking fdt_get_path() for an offset past the root node's FDT_END_NODE
tag makes it read before the start of the caller's buffer. Such an
offset is not a node offset, so fdt_get_path() should return
-FDT_ERR_BADOFFSET.
fdt_get_path() trims a component off the buffer for each level the walk
comes back up, comparing the components it has against the depth from
fdt_next_node(). On leaving the root node, fdt_next_node() takes the
depth negative and returns the offset just past that tag rather than an
error, as commit ce4d9c0f ("libfdt: Rework fdt_next_node()") intended so
that fdt_node_end_offset_() can find where a node ends. The loop only
tests the offset, so it runs once more and tries to trim a component
that is not there, scanning back past the start of the buffer.
Stop the walk once the depth goes negative, as
fdt_subnode_offset_namelen() and fdt_node_end_offset_() already do, and
reject the offset up front with fdt_check_node_offset_() where input is
not assumed valid. Add a bad-offset case to tests/get_path.c; run it
under valgrind (tests/run_tests.sh -m) to catch the read.
Signed-off-by: Ayan Kumar Halder <ayan.kumar.halder@amd.com>
Message-ID: <20261105180439.955822-1-ayan.kumar.halder@amd.com>
Reviewed-by: Simon Glass <sjg@chromium.org>
Reviewed-by: Herve Codina <herve.codina@bootlin.com>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
Reading a negative amount of data is nonsensical, so flat_read_data()
should take an unsigned integer length, matching the length field within
struct data itself.
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
flat_read_property() reads proplen as uint32_t but passes it to
flat_read_data() which casts it to int. A crafted DTB with proplen
0x80000000 or larger wraps negative, bypassing the flat_read_data()
bounds check, causing an out-of-bounds read.
Check that proplen does not exceed the remaining blob size before
using it.
Signed-off-by: Tristan Madani <tristan@talencesecurity.com>
Link: https://github.com/dgibson/dtc/pull/200
[dwg: Added new test file to treegen_dtb output in tests/meson.build]
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
`overlay_apply_node()` only reads from the overlay blob `@fdto` while
merging properties and subnodes into `@fdt`. Mark `@fdto` as
`const void *` so callers holding a `const void *fdto` pointer (such as
the upcoming `/__local_fixups__` update logic) can call
`overlay_apply_node()` without casting away `const`.
Assisted-by: Gemini:gemini-pro-prerelease
Signed-off-by: Douglas Anderson <dianders@chromium.org>
Message-ID: <20261101220224.1436242-11-dianders@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
Generalize `overlay_split_fragment_path()` in `libfdt/fdt_overlay.c` to
accept a length-bounded `path` slice that is not necessarily
NUL-terminated (using `memchr()` instead of `strchr()`, moving the
NUL-terminated property check back into `overlay_symbol_update()`, and
rejecting a trailing `'/'` after `"/__overlay__/"`) so it can also split
`:`-delimited paths from `/__fixups__` when updating
`/__local_fixups__`.
Assisted-by: Gemini:gemini-pro-prerelease
Signed-off-by: Douglas Anderson <dianders@chromium.org>
Message-ID: <20261101220224.1436242-10-dianders@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
In preparation for updating the base device tree's `/__local_fixups__`
node during `fdt_overlay_apply()`, factor out two helper functions in
`libfdt/fdt_overlay.c`:
- Factor out `overlay_parse_fixup_entry()` from
`overlay_fixup_phandle()` to parse `"path:name:offset"` entries in
`/__fixups__` properties.
- Factor out `overlay_split_fragment_path()` from
`overlay_symbol_update()` to validate and split
`"/<fragment>/__overlay__[/<rel>]"` paths into the fragment name and
relative subnode path.
This commit is pure code movement with no functional change.
Reviewed-by: Simon Glass <sjg@chromium.org>
Assisted-by: Gemini:gemini-pro-prerelease
Signed-off-by: Douglas Anderson <dianders@chromium.org>
Message-ID: <20261101220224.1436242-9-dianders@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
dtc-fatal.sh only checks that dtc exits with status 1, so a test which
expects a particular error passes just as well if dtc fails for some
other reason, such as a mistake in the test's dts file.
Add a -m option which also checks that dtc's output contains a given
message, and use it in each test which runs dtc-fatal.sh. Unlike
run_wrap_error_msg_test, this runs dtc under valgrind when that is
enabled.
Suggested-by: David Gibson <david@gibson.dropbear.id.au>
Link: https://lore.kernel.org/devicetree-compiler/20261029093115.3647778-2-sjg@chromium.org/
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Simon Glass <sjg@chromium.org>
Reviewed-by: David Gibson <david@gibson.dropbear.id.au>
Message-ID: <20261101170842.2802301-1-sjg@chromium.org>
fdt_next_tag() skips the name of a node by calling fdt_offset_ptr()
for each byte. Unless FDT_ASSUME_MASK includes ASSUME_VALID_INPUT,
each call reads totalsize, off_dt_struct, version and size_dt_struct
from the header again and checks the access against them. Every walk
over the structure block skips the name of every node it passes, and
also calls fdt_offset_ptr() two or three more times per tag, so this
dominates lookups such as fdt_path_offset() in large trees.
The structure block offset maps linearly to a pointer, so work out
where the range that fdt_offset_ptr() accepts ends in
fdt_struct_limit_(), rewrite fdt_offset_ptr() in terms of it, and
compute that limit once per fdt_next_tag() call. Check each access
against it with plain comparisons, and find the end of the name with
one memchr() over the rest of the range. The checks themselves don't
change: a name that isn't terminated before the end of the structure
block still makes fdt_next_tag() return FDT_END. The range is also
capped at INT_MAX, since offsets are ints, so a header that claims
more than 2 GiB now ends the walk instead of producing a negative
next offset.
With a 612 KiB tree (3,012 nodes, 17,899 properties) on x86-64, built
with gcc -O2 and the default FDT_ASSUME_MASK, a full walk with
fdt_next_tag() takes 131 us instead of 291 us (227 us if only
FDT_BEGIN_NODE uses the precomputed limit, as the other three checks
run 65,745 times during the walk), and fdt_path_offset() of /chosen,
which is near the end, takes 142 us instead of 382 us. In Android's
Generic Bootloader on an AArch64 device at 600 MHz, also with the
default FDT_ASSUME_MASK, the fixups made to that tree after applying
overlays take 23.3 ms instead of 33.1 ms.
Signed-off-by: Kelvin Zhang <zhangkelvin@google.com>
Message-ID: <CAOSmRziU5g9WO2R86d3w0mBgNmtwpdHfKu9EXTSD9d5cw-pNcw@mail.gmail.com>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
Unless FDT_ASSUME_MASK includes ASSUME_VALID_INPUT, fdt_get_string()
finds the end of the string with memchr(), bounded by the end of the
string block, which also checks that the string is terminated. A
string block normally ends with a NUL, and then every string in it is
terminated. When the caller does not ask for the string's length,
check that byte instead, so that fdt_string() doesn't scan the string
at all.
This helps callers that look up many property names. With a 612 KiB
tree on x86-64, built with gcc -O2 and the default FDT_ASSUME_MASK,
calling fdt_string() for the name of each of its 17,899 properties
takes 108 us instead of 160 us, not counting the walk that finds
them. libufdt, which Android bootloaders use to apply overlays, calls
fdt_string() at least once for every property it reads: tens of
thousands of times to apply one overlay to a 445 KiB tree.
Reviewed-by: David Gibson <david@gibson.dropbear.id.au>
Signed-off-by: Kelvin Zhang <zhangkelvin@google.com>
Message-ID: <CAOSmRzixCf479QyhmGuwBBZrRLTYqoaSUw88HKZnkPyEh6=gcw@mail.gmail.com>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
`libfdt.Property` subclasses `bytearray` and has a two-argument
`__init__(self, name, value)` constructor. Because `bytearray`'s default
copy/reduce protocol passes only the raw byte buffer to the constructor
(and does not copy instance attributes), calling `copy.copy()` or
`copy.deepcopy()` on a `Property` fails with `TypeError:
Property.__init__() missing 1 required positional argument: 'value'`.
Implement `__copy__()` and `__deepcopy__()` on `Property` so shallow and
deep copies preserve both `name` and the byte contents, and add a unit
test in `tests/pylibfdt_tests.py`.
Assisted-by: Gemini:gemini-pro-prerelease
Signed-off-by: Douglas Anderson <dianders@chromium.org>
Message-ID: <20261101220224.1436242-7-dianders@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
`FdtRo` exposes `boot_cpuid_phys()` to read the physical boot CPU ID
from the FDT header, and SWIG already wraps the underlying C function
`fdt_set_boot_cpuid_phys()`, but `class Fdt` lacked a corresponding
`set_boot_cpuid_phys()` method.
Add `Fdt.set_boot_cpuid_phys()` and test it in
`tests/pylibfdt_tests.py`.
Assisted-by: Gemini:gemini-pro-prerelease
Signed-off-by: Douglas Anderson <dianders@chromium.org>
Message-ID: <20261101220224.1436242-6-dianders@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
Currently, calling `Property.as_str()` or `Property.as_stringlist()` on
an empty `Property` (`b''`) raises `IndexError: bytearray index out of
range` when indexing `self[-1]`.
Update `Property.as_str()` to raise `ValueError('Property lacks nul
termination')` on an empty property, and update
`Property.as_stringlist()` to return `[]` on an empty property. Add unit
tests in `tests/pylibfdt_tests.py`.
Assisted-by: Gemini:gemini-pro-prerelease
Signed-off-by: Douglas Anderson <dianders@chromium.org>
Message-ID: <20261101220224.1436242-5-dianders@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
Follow-up improvements to commit 6b0371afc5 ("pylibfdt: Add
subnode/property iterators and get_mem_rsv_list()"):
- Document in `FdtRo.subnodes()` and `FdtRo.properties()` that the
device tree must not be modified while iterating, as node or property
offsets may shift.
- Remove the inaccurate `Raises:` section from `FdtRo.subnodes()`, as
`fdt_first_subnode()` and `fdt_next_subnode()` map all negative
returns from `fdt_next_node()` to `-FDT_ERR_NOTFOUND` (which
`subnodes()` quiets).
- Add a test case in `tests/pylibfdt_tests.py` verifying that passing a
negative offset (`-1`) to `properties()` raises `FdtException` with
`-libfdt.BADOFFSET`.
Assisted-by: Gemini:gemini-pro-prerelease
Signed-off-by: Douglas Anderson <dianders@chromium.org>
Message-ID: <20261101220224.1436242-4-dianders@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
In `overlay_fixup_phandle()`, `sep` is obtained via `memchr(..., ':',
...)`. When `sep` is non-NULL, `*sep` is guaranteed to be `':'`, so the
`|| *sep != ':'` checks are redundant. Drop them.
Assisted-by: Gemini:gemini-pro-prerelease
Signed-off-by: Douglas Anderson <dianders@chromium.org>
Message-ID: <20261101220224.1436242-3-dianders@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
A malformed overlay with a negative or very large fixup offset in
/__fixups__ (such as "/fragment@0:target:-4" or
"/fragment@0:target:4294967292") can cause an out-of-bounds write during
overlay application:
1. overlay_fixup_phandle() parses the offset with strtoul(), which
accepts negative numbers and values larger than UINT32_MAX, and
truncates the result into a 32-bit integer.
2. fdt_setprop_inplace_namelen_partial() checks bounds with
`(unsigned)proplen < (len + idx)`, where `len + idx` wraps around to
a small number when `idx` is near UINT32_MAX, bypassing the check and
passing the huge offset to memcpy().
Tighten the fixup offset parsing in overlay_fixup_phandle(), fix the
bounds check in fdt_setprop_inplace_namelen_partial() to avoid unsigned
wrap-around, and add test cases covering both negative and overflowing
offsets.
Assisted-by: Gemini:gemini-pro-prerelease
Signed-off-by: Douglas Anderson <dianders@chromium.org>
Message-ID: <20261101220224.1436242-2-dianders@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
The Python section of README.md assumes a make build. It installs with
'make install', disables the library with NO_PYTHON, and runs its
examples from the source tree, where make puts the built module. With
meson the module is in the build directory instead, so the help example
quietly imports whatever libfdt is installed, and the coverage example
fails.
Use meson to install and to disable the Python library, and run the
examples from the build directory.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Simon Glass <sjg@chromium.org>
Reviewed-by: David Gibson <david@gibson.dropbear.id.au>
Reviewed-by: Herve Codina <herve.codina@bootlin.com>
Message-ID: <20261028112007.3980089-2-sjg@chromium.org>
Building with make is deprecated in favour of meson, but README.md only
gives instructions for make, in its Python section, and CONTRIBUTING.md
says to use 'make check'. The meson commands only appear in the warning
which the Makefile prints.
Add a short Building section to README.md with the meson commands for
building, testing and installing, pointing to the Meson quick guide and
to scripts/install-deps.sh. Use meson for running the tests in
CONTRIBUTING.md too.
Closes: https://github.com/dgibson/dtc/issues/83
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Simon Glass <sjg@chromium.org>
Reviewed-by: David Gibson <david@gibson.dropbear.id.au>
Reviewed-by: Herve Codina <herve.codina@bootlin.com>
Message-ID: <20261028112007.3980089-1-sjg@chromium.org>
Add Pythonic iterator helpers on `FdtRo` to simplify walking nodes,
properties, and memory reservation entries without manual offset loops
or `-FDT_ERR_NOTFOUND` sentinel handling:
- `subnodes(nodeoffset)`: yields the offset of each direct child subnode
of `nodeoffset`.
- `properties(nodeoffset)`: yields a `Property` object for each property
of `nodeoffset`.
- `get_mem_rsv_list()`: returns a list of `(address, size)` tuples for
all entries in the memory reservation block.
Assisted-by: Gemini:gemini-pro-prerelease
Signed-off-by: Douglas Anderson <dianders@chromium.org>
Message-ID: <20261028215600.1713475-3-dianders@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
`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@chromium.org>
Message-ID: <20261028215600.1713475-2-dianders@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
When 'fdtput -d' fails to delete a property, for example because it does
not exist, the error names the node rather than the property:
$ fdtput -d test.dtb /chosen missing
Error at '/chosen': FDT_ERR_NOTFOUND
This suggests that the node is missing, when it is the property that
is.
Report the property name as well as the node:
$ fdtput -d test.dtb /chosen missing
Error at '/chosen', property 'missing': FDT_ERR_NOTFOUND
Check the message in the existing test for this.
Fixes: aa719618a8 ("fdtput: add delete node and property function")
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Simon Glass <sjg@chromium.org>
Reviewed-by: Herve Codina <herve.codina@bootlin.com>
Message-ID: <20261028073440.3327687-5-sjg@chromium.org>
Signed-off-by: David Gibson <david@gibson.dropbear.id.au>