With glibc 2.43, C23's `const`-preserving `strchr` generic selection macro
is enabled when compiling with `-std=c2x`, so `strchr(const char *, int)`
returns `const char *`. Mark `oli` `const` to fix some `-Werror`s.
Tested in ChromeOS' build environment with glibc 2.43 patched in.
Assisted-by: Gemini:argon
Signed-off-by: George Burgess IV <gbiv@google.com>
When calculating the load, reduce active and idle time so it
fits in 32 bits after multiplying active time by 1000. If
measurement window is that big we anyway not lose the precision
because load is given in per mille.
Signed-off-by: Krzysztof Chruściński <krzysztof.chruscinski@nordicsemi.no>
z_vrfy_sys_clock_settime() and z_vrfy_sys_clock_nanosleep() checked
that the user timespec was readable and then passed the user pointer to
the implementation. The implementations validate the struct with
timespec_is_valid() and read it again afterwards, so another thread in
the same memory domain can change tv_nsec between the check and the use.
In settime the second read feeds timespec_add(), whose result is stored
in the global rt_clock_offset. A racing writer can trip the assertion
in timespec_add() from a syscall, or leave an offset with tv_nsec
outside [0, NSEC_PER_SEC) that every SYS_CLOCK_REALTIME reader then
sees. In nanosleep an unvalidated value reaches timespec_to_timeout().
Copy the timespec onto the kernel stack with k_usermode_from_copy() in
both handlers and pass the copy to the implementation, so the validated
value is the one used. The write check on rmtp is unchanged.
Assisted-by: Claude:claude-opus-5.5
Signed-off-by: Flavio Ceolin <flavio@hubble.com>
The remainder's tv_nsec was taken modulo NSEC_PER_MSEC instead of
NSEC_PER_SEC. Introduced in commit a3e934f12c ("sys: clock:
additional sys_clock api calls").
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
sys_bitarray_popcount_region(), sys_bitarray_xor() and
sys_bitarray_find_nth_set() rejected out-of-range regions with
offset + num_bits > bitarray->num_bits. The sum can wrap around
SIZE_MAX, so a call such as num_bits = 1 with offset = SIZE_MAX passed
the check and accessed bundles far outside the array.
Bound num_bits by the array size first and then compare offset with
the remaining space, so no intermediate value can wrap. The other
region functions in this file already bound num_bits and offset
separately before computing the end of the region.
Add test cases with a wrapping offset and a wrapping num_bits for each
of the three functions. Without this change they crash kernel.common
on native_sim and native_sim/native/64. With it, kernel.common and
libraries.mem_blocks pass on both platforms and lorawan.frag_decoder
passes on native_sim.
Assisted-by: Claude:claude-opus-5-5 dawnr
Signed-off-by: Treston Cuzzort <tmcuzzort@gmail.com>
In a hierarchical self-transition, the entry action of the state ran
before the current state was updated and before the transition hook.
The entry action saw the exited state as current, and the hook came
after the entry action, unlike in flat builds and in the hook
documentation.
Run the entry action after the update and the hook, as for any entry.
Signed-off-by: Vladislav Kulikov <vlad_kulikov_c@pm.me>
cobs_encode() pulled the whole source buffer before encoding it, so on
-ENOMEM the source data was consumed and a partial encoding was left
in the destination buffer.
Encode from the source data in place and only pull it on success. On
error, remove the bytes added to the destination buffer. Unlike a check
against cobs_max_encoded_len(), this keeps encodings that fit the
destination exactly working.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
With COBS_FLAG_TRAILING_DELIMITER, cobs_decode() fed the whole source
buffer to the decoder, so multiple frames were merged into the
destination buffer without an error and the frame boundaries were
lost. The frame end was also passed to net_buf_add_mem() as a NULL
pointer, which ends up in memcpy().
Stop the decoder at the first frame end and only pull the used bytes
from the source buffer, so a buffer holding several frames can be
decoded by calling cobs_decode() repeatedly.
A source buffer without a complete frame, such as a frame still being
received, returns -EAGAIN instead of -EINVAL so the caller can wait for
more data. On any error the decoded bytes are removed from the
destination buffer and the source buffer is left untouched.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
cobs_decoder_write() always used the whole input, so a caller that
receives several frames in one buffer could not handle a frame before
the next one was decoded into the same destination.
When the callback returns a positive value for a frame end, stop after
the delimiter and return the number of bytes used. The caller can then
handle the frame and write the remaining data. Callbacks returning 0
behave as before.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
cobs_decoder_close() only failed when a group was incomplete. An empty
stream, which holds no code byte and is not a valid COBS encoding, was
accepted, and with COBS_FLAG_TRAILING_DELIMITER a frame that was never
terminated was accepted as well. Before commit f344ab6b98 ("cobs:
Introduce streaming") cobs_decode() rejected input that did not end
with the delimiter.
Without the flag, require exactly one complete frame. With the flag,
require the stream to end with a delimiter.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
With COBS_FLAG_TRAILING_DELIMITER set, the streaming decoder reported a
frame end for every delimiter, including consecutive delimiters and a
delimiter at the start of the stream. Those produced callbacks that a
consumer cannot distinguish from a valid empty frame (0x01 followed by
a delimiter).
Track whether a code byte was received since the last frame end and
ignore delimiters until one is, which also lets a receiver resync on
idle delimiters.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
cobs_decoder_write() read dec->flags in the declaration of the
sentinel, before asserting that dec is not NULL, so the assertion could
never catch a NULL decoder. Read the flags after the assertion.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Pieter De Gendt <pieter.degendt@basalte.be>
calling `cbprintf(out, "%s", "<UTF-8 string>")` invokes
implementation-defined behaviour (casting a non-ASCII char to an int).
avoid implementation-defined behaviour by casting to `unsigned char`
first.
Signed-off-by: Eden Frosst <eden.frosst@rbr-global.com>
Fix potential overflows when converting timespec and timeval values
by ensuring tv_sec is promoted to 64-bit before scaling in ts_to_ns()
and ts_to_ms(). Additionally, replace manual select() timeout
calculations with timespec_to_timeout().
This avoids 32-bit intermediate overflows on toolchains where time_t
is 32-bit, preventing incorrect POSIX timeout and select() behavior.
Signed-off-by: Mohamed Moawad <melhosar@gfoundries.com>
With CONFIG_NET_BUF_POOL_USAGE, net_buf_alloc_len() updates
pool->max_used with a plain read-modify-write. An allocation that
preempts another one, or runs on another CPU, can have its higher
value overwritten by the lower one, and net_buf_get_max_used() then
reports less than the real peak.
Update max_used under the pool lock, and compute the usage from the
value the decrement returns instead of reading avail_count again,
which could miss a peak when a buffer is freed in between.
Tested with tests/lib/net_buf on native_sim. There is no reproducer
for the race.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
In the flat build, smf_run_state() returned 0 when run() called
smf_set_terminate(), and the value only came back on the next call.
Check the terminate flag once after the run actions, for both builds.
smf_execute_ancestor_run_actions() now returns void, as its return
value only mirrored the flag.
Signed-off-by: Vladislav Kulikov <vlad_kulikov_c@pm.me>
The help of NET_BUF_WARN_ALLOC_INTERVAL says that 0 prints a warning
only once per allocation, but the time the allocation was blocked is
also printed when it gets a buffer. The help of NET_BUF_POOL_USAGE does
not mention the maximum number of buffers in use, which is what
net_buf_get_max_used() returns, and the help of NET_BUF_HARDENING
mentions only the operations that return NULL when they are rejected.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
Provide the packet socket address header so that applications and
modules can include <netpacket/packet.h> as they do on other systems.
The Zephyr header pulls in the native packet socket definitions from
<zephyr/net/net_ip.h>, and the newlib and picolibc shims forward to it
since neither C library ships this header.
Signed-off-by: Chris Friedt <chris@fr4.co>
Since commit 9bb2878319 ("net_buf: make reference counts atomic"),
net_buf_unref() decrements ref_word before its double free check. At a
zero reference count the decrement borrows from the other bytes of
ref_word: from flags, and from pool_id if flags is zero, so a buffer
that has already been freed can end up with the wrong pool id. With
assertions disabled, this undoes commit 9d0d3ef076 ("net_buf: buf:
return on double free").
Decrement with a compare-and-swap that leaves a zero count alone, also
when a double free races with the last unref. On Cortex-M33 and
Cortex-M4F this costs 2 to 16 cycles per unref.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Johan Hedberg <johan.hedberg@silabs.com>
Give ump_stream_responder.h C linkage so C++ code can link against it.
Tested by building a C++ app using it on native_sim.
Assisted-by: Claude:claude-opus-5-5
Signed-off-by: Benjamin Cabé <benjamin@zephyrproject.org>
Up until now offloaded sockets bind their local port inside the
offload engine, outside the net_context list, so
net_context_port_in_use() cannot see them.
This commit adds recording of each offloaded socket's local
binding in the socket layer and adds net_socket_port_in_use()
which consults both the socket and the context layer for
in use ports.
Signed-off-by: Carlo Kirchmeier <carlo.kirchmeier.ext@siemens.com>
When the malloc arena uses the RAM left after the image, a
nearly full image can leave less space than a heap needs. With
assertions disabled, the heap was still set up on that space
and allocations corrupted the memory past it.
Treat such an arena as empty, including when its size wraps or
its mapping fails, so allocations fail with ENOMEM, and log a
warning. Since the malloc partition is then empty, ztest no
longer adds it to the default memory domain.
Assisted-by: Claude:opus-5
Signed-off-by: Sylvio Alves <sylvio.alves@espressif.com>
Statically defined sys_mem_blocks allocators and the socket object table
are permanent storage, so they are enumerated in place as the permanent
range of their object type instead of each taking a registry entry. The
section of allocator pointers is registered as an indirect range. Socket
objects that were never initialized do not carry the type tag and are
not reported.
Assisted-by: Claude:claude-fable-5-1
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
A kernel object embedded in a k_malloc()ed or slab-allocated structure
ends its life with the block that holds it, and nothing calls the object
core API when that block is released. Its registry entry then stays
until the storage is reused by an object of another type.
Add a hidden SYS_HEAP_RELEASE_HOOK that the heap calls with the released
memory while it is still valid, from sys_heap_free() and from the tail an
in-place shrink gives up, and have k_mem_slab_free() report the released
block the same way. Object cores provide the hook under
OBJ_CORE_EVICT_ON_FREE, default on, and drop every entry located in the
released range. User mode frees are ignored: the registry is kernel
data and user mode never holds registered objects.
Assisted-by: Claude:claude-fable-5-1
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
Replace scripts/kconfig/hardened.csv with a distributed YAML database.
The CSV format could not carry any explanation for its recommendations,
had no validation (a malformed line was silently dropped), no notion of
profiles, no ownership story, and no way to extend it out of tree.
The database now lives where the code lives: the central
scripts/kconfig/hardening.yaml defines the hardening profiles (plus
rules for top-level Kconfig symbols), and per-subsystem hardening.yaml
fragments next to the relevant Kconfig files carry the rules, so each
rule is reviewed by the maintainers of the code it hardens. Every rule
has a required rationale and optional references, supports exact-value
and integer min/max recommendations (STACK_POINTER_RANDOM is now
'>=100' instead of '==100'), and belongs to a profile: 'base' (memory
protection and inherently insecure features) or 'strict' (extends base
with debug/observability feature removal). The default profile is
'strict', matching the rule set the CSV checked.
hardenconfig is restructured around a serializable HardeningReport
model so results can be consumed programmatically, and gains:
- a Rationale column in the report
- profile selection:
west build -t hardenconfig -- -DHARDENCONFIG_PROFILE=base
- HARDENCONFIG_SHOW_ALL to also list PASS/NA results
- HARDENCONFIG_STRICT to exit non-zero on failures, for CI use
- HARDENCONFIG_JSON to write machine-readable results, including which
database file each rule came from
- HARDENCONFIG_EXTRA_SOURCES to layer out-of-tree database files that
may add profiles/rules and override in-tree ones
The EXPERIMENTAL/DEPRECATED/NOT_SECURE marker symbol detection is
preserved unchanged.
Three CSV entries are intentionally not carried over because they were
redundant: BT_CONN_DISABLE_SECURITY and BT_OOB_DATA_FIXED can only be
enabled together with BT_TESTING, and TIMER_RANDOM_GENERATOR together
with TEST_RANDOM_GENERATOR, all of which the database already
recommends disabling for the same profiles.
Behavioral fix: the CSV's DEBUG_COREDUMP line used '=' instead of ','
and was silently ignored, so CONFIG_DEBUG_COREDUMP was never actually
checked; it now is.
Also add tabulate to requirements-base.txt: hardenconfig has always
imported it, but it was only pulled in via other requirements files.
Assisted-by: Claude:fable-5
Signed-off-by: Benjamin Cabé <benjamin@zephyrproject.org>
Add sys_heap_get_largest_free_block() to report the size of the
largest contiguous free block currently available in a sys_heap.
The value is computed on demand from the current heap state by
scanning the highest-indexed non-empty bucket. This avoids adding
overhead to the allocation and free paths while preserving the
public API behavior.
Signed-off-by: Deepak Mokili <dmokili@qti.qualcomm.com>
The shared multi-heap is a single global pool, but none of its
operations were locked and sys_heap is not internally
synchronized. Callers in different threads, such as the
Espressif Wi-Fi driver with its heap in PSRAM, corrupted the
heap on concurrent alloc and free.
Protect the allocation functions and the publication of a new
region with a spinlock, as mem_attr_heap and k_heap already do.
The region itself is initialized outside the lock, like
k_heap_init() does, and the interface documentation now states
which functions are safe to call from any thread and from ISRs.
shared_multi_heap_alloc() now reuses the aligned variant with no
alignment requirement, which is what sys_multi_heap_alloc()
does.
Assisted-by: Claude:opus-5
Signed-off-by: Sylvio Alves <sylvio.alves@espressif.com>
Introduce ZASSERT, a self-contained assertion facility configured per
source file through a named module rather than the single global
CONFIG_ASSERT switch.
A file selects its module with ZASSERT_MODULE(); the level is resolved
from CONFIG_ASSERT_MODULE_<MODULE>_LEVEL and may be overridden per file.
Modules are defined with the Kconfig.template.assert template, which takes
module/module-str inputs following the logging template convention.
The four levels are:
- Off (compiled out)
- Terse (check only)
- On (check + location only)
- Verbose (Check, location, condition and message)
Since the level is known at compile time, disabled assertions are folded
away by the compiler, and below Verbose the optional message and its
arguments are as well.
zassert provides a set of __weak overridable hooks:
- zassert_fail() - called when an assertion fails
- zassert_vprint() - called to print the assertion failure message
- zassert_post_action() - the terminal action after an assertion failure
CONFIG_ASSERT remains the master switch. The assert Kconfig moves from
subsys/debug to lib/os/zassert, the legacy CONFIG_ASSERT_* symbols are kept
but deprecated (mapped onto the DEFAULT module), and lib/os/assert.c is
removed. The __ASSERT() family is preserved as a thin compatibility shim
over the DEFAULT module, so existing call sites keep working unchanged.
Signed-off-by: Måns Ansgariusson <mansgariusson@gmail.com>
As part of the transition from C99 to C17 as the minimum supported C
standard version, remove the workarounds in the formatted output
subsystem to maintain compatibility with toolchains that do not support
the _Generic keyword.
Signed-off-by: Carles Cufi <carles.cufi@nordicsemi.no>
Fixes various issues with Kconfigs, including:
- Redundent `default n` on bools
- Not select deprecated on supposed deprecated symbols
- Using the wrong indentation
- Not having [DEPRECATED] in the prompt, or not having it at the
end
Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
Add a small OS helper for validating and copying a boot firmware device
tree blob into caller-owned storage.
The helper checks the FDT magic and total-size fields, verifies that
the caller-provided destination is large enough, copies the blob, and
returns 0 or a negative errno value. It does not own the destination
buffer or make policy decisions about which firmware argument contains
an FDT.
Add optional Xen support for preserving the boot device tree blob from
the first firmware argument when running on xenvm. The Xen driver code
owns the storage and policy, then exposes the copied data through
xen_fdt_get().
Signed-off-by: Vladyslav Goncharuk <vladyslav_goncharuk@epam.com>
Assisted-by: Codex:gpt-5
Add TriCore architecture port supporting TC1.6P and TC1.8P core
variants used in Infineon AURIX TC3x and TC4x SoC families.
Includes context switching using TriCore upper/lower context save
areas (CSA), interrupt management, trap and exception handling,
syscall interface, reset vector and linker script.
Supports cooperative and preemptive threading, nested interrupt
handling with priority-based preemption.
Signed-off-by: Christoph Seitz <christoph.seitz@infineon.com>
Signed-off-by: Parthiban Nallathambi <parthiban@linumiz.com>
The new implementation provides a full SPSC ring buffer API, reducing the
size of the ring_buffer struct to 12 bytes(on a 32-bit arch), and increases
the throughput of the ring buffers hot path by ~30% (measured on nRF5340).
The default variant drops the claim/finish and item APIs functionality to
reduce the struct size. During the deprecation period, the old APIs are
still reachable through the CONFIG_RING_BUFFER Kconfig option.
Signed-off-by: Måns Ansgariusson <mansgariusson@gmail.com>
I can't find any trace of support for these outside of the Kconfig
file; they "can't" have ever worked.
Signed-off-by: Keith Packard <keithp@keithp.com>
sys_heap_aligned_alloc() called heap_sanitizer_on_alloc() twice for
the same allocation, unpoisoning the region redundantly. Remove the
duplicate call, which was unintended change.
Signed-off-by: Deepak Mokili <dmokili@qti.qualcomm.com>
Drop unrelated formatting changes in Kconfig and heap.h, fix tags
list syntax and drop the redundant filter expression already
guaranteed true by prj.conf in tests.yaml.
Signed-off-by: Deepak Mokili <dmokili@qti.qualcomm.com>
heap_constants.c includes heap.h
directly without including zephyr/sys/sys_heap.h first, so the
z_heap_stats_on_*() prototypes taking struct sys_heap * left the
type undeclared in that translation unit, triggering error
Signed-off-by: Deepak Mokili <dmokili@qti.qualcomm.com>
Key the stats pool by struct sys_heap * identity in a parallel
registration table (z_heap_stats_heaps) instead of reading h->stats
from the caller's buffer. h->stats is now always assigned explicitly
by on_init and never read before being set.
Signed-off-by: Deepak Mokili <dmokili@qti.qualcomm.com>
- Decouple chunk trailer from SYS_HEAP_CANARIES; gate on
CANARIES || THREAD_STATS || CALLER_POINTER independently
- Move all stats logic to heap_stats.c; call via thin hooks
using IF_ENABLED() following the sanitizer hook pattern
- Remove atomics; model is caller-serialised matching sys_heap
contract; document in Kconfig
- Reuse pool slot on re-init instead of consuming a new one
- Serialise threads in overflow test; no concurrent raw sys_heap
Signed-off-by: Deepak Mokili <dmokili@qti.qualcomm.com>
Add CONFIG_SYS_HEAP_STATS_LOGGING to enable a heap statistics
framework. CONFIG_SYS_HEAP_THREAD_STATS tracks outstanding allocation
bytes per thread per heap, with ISR/boot/overflow aggregate counters
and sys_heap_stats_log() to print them. CONFIG_SYS_HEAP_CALLER_POINTER
stores the allocation call-site address in the chunk trailer, readable
via sys_heap_get_caller(). Both features store metadata in the
per-chunk trailer and auto-select SYS_HEAP_CANARIES.
Includes a ztest suite under tests/lib/heap_stats_log.
Signed-off-by: Deepak Mokili <dmokili@qti.qualcomm.com>
MISRA C:2012 Rule 8.2 requires every parameter in a function type to be
named, including the parameters of function pointer parameters.
The stdout hook install helper is defined once per C library and only the
minimal and picolibc versions named the hook's character argument. The
minimal stdlib.h and the newlib string.h overrides also declared their
parameters with bare types.
Name them after the arguments the documentation or the
definitions already use. No functional change.
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
net_buf_append_bytes() links every newly allocated fragment with
net_buf_frag_add(), which walks the whole chain from the head to find
the tail. That tail is already known: it is the fragment the loop has
just filled. A single append spanning n fragments therefore costs
O(n^2) fragment traversals, and a caller that appends one segment at a
time onto a growing chain walks that chain twice per call instead of
once.
The second shape is the common one in tree. The Bluetooth host appends
one received segment per call when reassembling LE L2CAP SDUs in
l2cap_chan_le_recv_seg() and BR/EDR segments in bt_l2cap_br_recv_seg(),
and the hl7800 and wncm14a2a modem receive paths append one UART read
per call. The GATT call sites build a single outgoing ATT PDU and pass
no allocator, so they normally stay within one buffer.
Keep the tail in a local variable and link the new fragment behind it
with net_buf_frag_insert(). For a non-NULL head net_buf_frag_add() does
exactly that on the tail, and the function already requires a non-NULL
buffer, so the fragment reference is still consumed and the resulting
chain order is unchanged. The tail is re-derived from the returned
fragment so an allocator handing back a chain keeps its old behaviour.
The allocation-failure path still returns before any linking.
Measured on native_sim/native/64 with an instrumented
net_buf_frag_last(). Appending 4096 bytes over 32 128-byte fragments in
one call drops from 465 to 0 traversal steps. Building the same
32-fragment chain one fragment per call, which is the reassembly shape
above, drops from 930 to 465; the remainder is the entry walk that the
head-pointer argument requires and that this change does not address.
Add a regression test that builds a ten-fragment chain over two calls
and checks the fragment count, that every fragment is filled, the
payload order across the join, and that a failed allocation leaves the
chain untouched.
Signed-off-by: Magnus Strømme <magnus.henrik@hotmail.com>
Assisted-by: Claude:claude-opus-5
The %s conversion computed the string length with strlen() and clamped
it to the precision afterwards. A precision is meant to let callers pass
a buffer that is not NUL-terminated, but strlen() still scans for the
terminator and reads past the end of such a buffer.
Bound the length scan by the precision with strnlen() when a precision
is given, as cbprintf_complete.c already does, and keep strlen() when
there is none. Define _POSIX_C_SOURCE for the strnlen() declaration,
matching cbprintf_complete.c.
The out-of-bounds read was reproduced and the fix verified with
AddressSanitizer on the host, and with twister on qemu_cortex_m3
(tests/lib/sprintf and tests/lib/cbprintf_package, including the
CONFIG_CBPRINTF_NANO and MINIMAL_LIBC variants), all passing.
Fixes: #117791
Signed-off-by: Rithwik Reddy Eedula <rithwikreddy.eedula@sjsu.edu>
MISRA C:2012 Rule 8.2 requires every parameter in a function type to be
named, including the parameters of function pointer parameters.
The C++ ABI __cxa_atexit() stub, its local prototype in the ARM
__aeabi_atexit() wrapper and that wrapper itself left the destructor's
parameter unnamed.
Name them after the arguments the documentation or the
definitions already use. No functional change.
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
Remove remaining uses of the internal __ASSERT_ON macro. Let __ASSERT()
handle disabled assertions, mark assert-only values as unused where needed,
and use CONFIG_ASSERT for assertion-only state.
Signed-off-by: Måns Ansgariusson <mansgariusson@gmail.com>