Commit graph

2410 commits

Author SHA1 Message Date
Abhishek Mishra
db6ab892a2 fs/binfmt: close symlink TOCTOU and harden setuid/setgid exec hygiene
Some checks are pending
Build Documentation / build-html (push) Waiting to run
MemBrowse Memory Report / changes-filter (push) Waiting to run
MemBrowse Memory Report / load-targets (push) Waiting to run
MemBrowse Memory Report / identical (push) Blocked by required conditions
MemBrowse Memory Report / analyze (push) Blocked by required conditions
Perform pseudo-filesystem permission checks inside inode_reserve() and
inode_remove() while the inode tree lock is held, and hold that lock across
pseudorename mutations so symlink swaps cannot bypass directory checks.
Hold a read lock around pseudo-fs open permission checks.

On setuid/setgid exec, update saved set-IDs, mark the task group secure,
sanitize dangerous environment variables, clear debug/dumpable flags, and
add issetugid(), secure_getenv(), and PR_SET/GET_DUMPABLE support.

Signed-off-by: Abhishek Mishra <mishra.abhishek2808@gmail.com>
2026-08-01 15:32:03 -03:00
hanzhijian
ddf350f1a3 libs/libc: support explicit bases up to 36
Some checks are pending
MemBrowse Memory Report / changes-filter (push) Waiting to run
MemBrowse Memory Report / load-targets (push) Waiting to run
MemBrowse Memory Report / identical (push) Blocked by required conditions
MemBrowse Memory Report / analyze (push) Blocked by required conditions
The strto* interfaces document explicit bases in the range 2 through 36, and lib_isbasedigit() already supports alphabetic digits through base 36.  However, lib_checkbase() rejects every explicit base above 26 with EINVAL.

Raise the validation limit to 36 so the conversion interfaces accept the full documented range while continuing to reject base 37 and above.

Signed-off-by: hanzhijian <hanzhijian@zepp.com>
2026-08-01 20:08:32 +08:00
Udit Jain
6f0da60bd7 libs/libbuiltin/compiler-rt: skip unsupported Arm VFP builtins asm
Some checks are pending
Build Documentation / build-html (push) Waiting to run
MemBrowse Memory Report / changes-filter (push) Waiting to run
MemBrowse Memory Report / load-targets (push) Waiting to run
MemBrowse Memory Report / identical (push) Blocked by required conditions
MemBrowse Memory Report / analyze (push) Blocked by required conditions
The compiler-rt builtins build globs every arm/*.S source, but several of
those hand-written assembly files require FPU features the target may not
have.  Upstream compiler-rt selects them conditionally; NuttX did not, so
BUILTIN_COMPILER_RT builds for single-precision-FPU Arm targets (e.g.
Cortex-M33, -mfpu=fpv5-sp-d16) failed to assemble with errors such as
"selected FPU does not support instruction -- vadd.f64".

Filter the source list to match the configured FPU, in both the Makefile
and CMake builds:
  - chkstk.S / chkstk2.S are Windows/MinGW-only stack probes, always dropped;
  - with no hardware FPU (!CONFIG_ARCH_FPU) all arm/*vfp.S are dropped;
  - with a single-precision FPU (!CONFIG_ARCH_DPFPU) the double-precision
    *df*vfp.S routines are dropped.

Reproduced against compiler-rt 17.0.1 with arm-none-eabi-gcc 14.2 using the
Cortex-M33 single-precision flags: 18 of 86 arm/*.S files failed to assemble
(17 double-precision *df*vfp.S plus chkstk.S); after the filter all remaining
68 files assemble cleanly.

Fixes: https://github.com/apache/nuttx/issues/17386
Generated-by: Claude (Anthropic)
Signed-off-by: Udit Jain <uditjainstjis@gmail.com>
2026-07-31 15:37:33 -03:00
Abhishek Mishra
5c9c236954 libc/pwd: default ostest multiuser passwd path to /tmp/ostest_passwd
When CONFIG_TESTING_OSTEST_MULTIUSER is enabled, default
CONFIG_LIBC_PASSWD_FILEPATH to a writable tmpfs path used by the
ostest multiuser passwd sub-test.

Signed-off-by: Abhishek Mishra <mishra.abhishek2808@gmail.com>
2026-07-30 09:48:10 +08:00
Abhishek Mishra
282d4cb0e9 libc/pwd: parse NuttX 5-field passwd records
Accept user#️⃣uid:gid:home lines produced by mkpasswd in addition
to the six-field gecos form, and raise the default line buffer to 256.

Signed-off-by: Abhishek Mishra <mishra.abhishek2808@gmail.com>
2026-07-30 09:48:10 +08:00
Abhishek Mishra
4c62271654 sched/group: add getresuid, getresgid, setreuid, and setregid
Implement POSIX real/effective/saved credential getters and paired
setters in the task group layer, with libc stubs and syscalls.

Signed-off-by: Abhishek Mishra <mishra.abhishek2808@gmail.com>
2026-07-30 09:48:10 +08:00
Alan Carvalho de Assis
c027e7c3e4 tools: fix stale archive members surviving a Kconfig-driven CSRCS change
During the Toybox port to NuttX, Claude noticed that changes in the
menuconfig weren't taking affect. This issue exists for a long time on
NuttX, in fact BayLibre's presentation from 2017 make jokes about our
building system not been reliable:
https://www.youtube.com/watch?v=XUJK2htXxKw&t=320s

Stale archive members from $(AR)'s additive-only behavior can linger
after Kconfig toggles change which files provide a symbol, causing dead
weight or "multiple definition" link errors on incremental builds.
Fixed by splitting ARCHIVE into two macros: ARCHIVE keeps the original
additive behavior for apps/libapps.a, which many independent
subdirectories contribute to across a build, while the new
ARCHIVE_REBUILD deletes then archives for the far more common case
of a single Makefile building its own self-contained $(OBJS)
- all 39 such call sites now use it.

Assisted-By: Claude Sonnet 5
Signed-off-by: Alan C. Assis <acassis@gmail.com>
2026-07-28 21:26:03 -03:00
hanzhijian
5f0c1c8d10 libc/time: Fix POSIX timezone string parsing.
When loading a zoneinfo file fails, parse a non-colon-prefixed TZ value
as a POSIX timezone string. Treat a successful tzparse() result as
success while preserving the leading-colon file-only behavior.

Assisted-by: Codex:gpt-5.6 Sol
Signed-off-by: hanzhijian <hanzhijian@zepp.com>
2026-07-25 19:54:18 +08:00
Lingao Meng
b5d3d30378 netdb: Add http and https service entries
getaddrinfo() and getservbyname() use the built-in service table when
resolving service names. The table only contained ntp, so common
service names such as http and https could not be resolved without a
numeric port.

Add http and https entries for both TCP and UDP to match the existing
service table style.

Testing:

  - Host: Ubuntu 22.04 x86_64.

  - Board/config: sim:nsh with CONFIG_LIBC_NETDB=y and
    CONFIG_EXAMPLES_HELLO=y.

  - make clean && make -j16.

  - Ran a temporary hello example that called getservbyname("http",
    "tcp") and getservbyname("https", "tcp"). The app verified ports
    80 and 443 and printed "getservbyname http/https test passed".

Assisted-by: Claude:Claude-Fable-5
Signed-off-by: Lingao Meng <menglingao@xiaomi.com>
2026-07-23 15:34:02 +08:00
anjiahao
745a6e53a4 spawn: allow zero stacksize/priority to use binary loader defaults
posix_spawnattr_init() no longer pre-fills attr->stacksize and
attr->priority (it leaves them zero, as memset already does).  When a
caller does not set them, the binary loader supplies them from the
loaded ELF (binp->stacksize / binp->priority, parsed from the nx_*
symbols), and nxtask_spawn_exec() falls back to the parent priority and
CONFIG_POSIX_SPAWN_DEFAULT_STACKSIZE for the posix_spawn() function-task
path.

This lets an application's stack size and priority embedded as ELF
symbols actually drive the spawned task, instead of being overridden by
the spawnattr defaults.

Signed-off-by: anjiahao <anjiahao@xiaomi.com>
2026-07-15 12:24:44 -03:00
anjiahao
c8b71df614 libelf:support find symbol by symbol name
Add libelf_findsymbol() to locate a symbol in the ELF symbol table by
name, reusing the existing libelf_findsymtab/libelf_readsym/libelf_symname
helpers, and expose its prototype in include/nuttx/lib/elf.h.

Signed-off-by: anjiahao <anjiahao@xiaomi.com>
2026-07-15 12:24:44 -03:00
liang.huang
170a989ccb libc/builtin: support per-application priority/stacksize under KERNEL build.
nsh_fileapp() could not apply an application's Kconfig-configured
priority/stacksize via posix_spawn() under CONFIG_BUILD_KERNEL, because
the registry table (struct builtin_s / g_builtins[]) was gated on
CONFIG_BUILTIN, which depends on !BUILD_KERNEL. Those settings were
silently ignored in KERNEL builds.

CONFIG_BUILTIN conflates the table with main_t-based dispatch, which is
meaningless under CONFIG_BUILD_KERNEL. Add a hidden derived symbol,
APP_REGISTRY, that tracks table availability independently of dispatch:

  config APP_REGISTRY
          bool
          default y if BUILTIN || BUILD_KERNEL

Switch the guards on the table itself (Make.defs, builtin.h) from
CONFIG_BUILTIN to CONFIG_APP_REGISTRY. Call sites that dereference
builtin->main stay gated on CONFIG_BUILTIN and remain unreachable
under CONFIG_BUILD_KERNEL.

Signed-off-by: liang.huang <liang.huang@houmo.ai>
2026-07-13 15:23:39 -03:00
Alan Carvalho de Assis
d8d77c249c libs/libdsp: Add Matrix operations
This commit adds support for matrix operation on libdsp. The code
came from: https://github.com/DjVul/Extended-Kalman-Filter---STM32/blob/main/Core/Src/matrix_utils.c

Signed-off-by: Alan C. Assis <acassis@gmail.com>
2026-07-11 14:55:59 -03:00
Old-Ding
8ff9dfdea3 libs: netdb: Advance stream buffers by transfer count
Update the DNS stream send and receive helpers to advance their buffers
by the number of bytes actually transferred. Advancing by the original
remaining length skips data when send() or recv() completes partially.

Signed-off-by: Old-Ding <ai.neo.ae86@gmail.com>
2026-07-09 08:45:42 +08:00
Old-Ding
bab2b4a5f2 libc/stream: Check lowout bounds before access
Check the provided length before reading the current lowoutstream byte. This avoids reading past zero-length or fully consumed buffers before the loop condition stops.

Generated-by: OpenAI Codex
Signed-off-by: Old-Ding <35417409+Old-Ding@users.noreply.github.com>
2026-07-06 09:02:22 +02:00
hanzhijian
9e467388de stdlib/rand: replace weak LCG with xorshift32 PRNG
The existing first-order LCG (seed = 470001 * seed % 999563) has several
quality problems:
- Output range limited to [1, 999562] (~20 bits) instead of full 32-bit
- Lower bits have very short periods (8-bit period = 1, 16-bit = 105)
- Overall period only ~1M, far too short for many applications
- Causes mbedtls_rsa_gen_key to loop forever when rand() consumption
  aligns with the cycle length (issue #16760)

Replace the entire order-based LCG implementation (CONFIG_LIBC_RAND_ORDER
0-3) with Marsaglia's xorshift32:
- Full 32-bit output range
- Period 2^32 - 1 (~4.29 billion)
- Fast: just three XOR/shift operations
- No floating-point math needed
- No CONFIG_LIBC_RAND_ORDER configuration required

Remove the CONFIG_LIBC_RAND_ORDER Kconfig option and clean up all
defconfig references (12 boards) and related comments.

Signed-off-by: hanzhijian <hanzhijian@zepp.com>
2026-07-03 15:08:12 +08:00
hanzhijian
87d84e437a libc/crc32: add IEEE-compatible crc32_ieee for Linux/zlib interop
Add crc32_ieee() and crc32_ieeepart() that produce CRC32 values
compatible with Linux/zlib. The difference from the existing crc32():

  crc32():        init=0, no final XOR (NuttX native)
  crc32_ieee():   init=0xFFFFFFFF, final XOR 0xFFFFFFFF (Linux/zlib)

The existing crc32() and crc32part() are unchanged to avoid breaking
existing callers (bbsram, sbram, etc.).

New functions:
  crc32_ieee(src, len)              - full CRC, Linux-compatible
  crc32_ieeepart(src, len, crcval)  - incremental CRC, Linux-compatible

Verified on sim:nsh against known Linux zlib test vectors:
  crc32_ieee("hello")     = 0x3610a686 (Linux: 0x3610a686) PASS
  crc32_ieee("123456789") = 0xcbf43926 (Linux: 0xcbf43926) PASS
  crc32_ieee("")           = 0x00000000 (Linux: 0x00000000) PASS
  crc32_ieeepart incremental  = 0xcbf43926               PASS
  crc32("hello")          = 0xf032519b (unchanged)       PASS

Signed-off-by: hanzhijian <hanzhijian@zepp.com>
2026-07-03 10:18:28 +08:00
Karel Kočí
d61242c319 libs/libm: correct implementation of truncl if long double is double
This reuses implementation of trunc in case long double has same size as
double.

The previous implementation is used only in case x87 80-bit float point
is the long double. In other cases the logic is intentionally replaced
with panic to not provide a wrong result.

Signed-off-by: Karel Kočí <kkoci@elektroline.cz>
2026-07-02 09:02:21 -03:00
Karel Kočí
9f4b4faf47 libs/libc: add limits checks
NuttX defines constants for the sizes of types just as constants
directly in the code. The real values depend on compiler and target
platform. It is possible that value declared by NuttX header is wrong
compared to the compiler configuration. This is more likely in case of
floating points.

Not all compilers supported by NuttX provide required info through
defines and thus it is more generic to specify limits as constants, but
in case compiler provides them then it is a good idea to compare. This
commit adds such set of comparisons for limits.h and float.h constants.

The comparisons were tested with GCC and Clang. They will be ignored in
case compiler doesn't provide them.

Signed-off-by: Karel Kočí <kkoci@elektroline.cz>
2026-07-02 09:02:21 -03:00
Xiang Xiao
9e141acab3 !include/fcntl.h: align open flags with Linux values
Align the NuttX open(2) flag constants with the Linux asm-generic
values so that the FUSE wire protocol and other cross-platform
interfaces work without conversion.

All code that used '(flags & O_RDONLY)' as a bitmask check (always 0
now that O_RDONLY=0) has been updated to use '(flags & O_ACCMODE)'
comparisons.

The NUTTX_O_* constants in include/nuttx/fs/hostfs.h are updated to
match, and the sim hostfs open flag mapping is fixed.

Signed-off-by: Xiang Xiao <xiaoxiang@xiaomi.com>
2026-06-30 13:43:44 +08:00
Xiang Xiao
6161c73639 include/fcntl.h: remove O_RDOK/O_WROK aliases
O_RDOK and O_WROK are non-standard aliases for O_RDONLY and O_WRONLY
respectively.  Having two names for the same flag creates confusion,
especially when aligning the flag values with Linux.  Remove the
aliases and replace all uses with the standard O_RDONLY/O_WRONLY.

No functional change — O_RDOK was defined as O_RDONLY and O_WROK as
O_WRONLY, so the replacement is a pure text substitution.

Signed-off-by: Xiang Xiao <xiaoxiang@xiaomi.com>
2026-06-28 09:10:11 -03:00
Xiang Xiao
9704481224 libc/unistd: add getgroups()
Add getgroups() to the C library.  NuttX has no supplementary group
IDs, so it reports a single group, the effective group ID, and follows
POSIX for the gidsetsize == 0 and short-buffer (EINVAL) cases.

Signed-off-by: Xiang Xiao <xiaoxiang@xiaomi.com>
2026-06-24 14:55:11 -03:00
Xiang Xiao
95063bde15 drivers/serial: add job-control TTY ioctls and libc wrappers
NuttX has no real session/process-group abstraction, so the TTY layer
collapses the foreground process group onto the single dev->pid field
(pgrp == pid, one member per group).  Extend the controlling-terminal
support so portable software (e.g. dropbear, socat) that relies on
job-control primitives works without losing the existing NuttX-specific
behaviour.

Driver (serial.c, pty.c):
- TIOCSCTTY now accepts a flag: arg > 0 keeps the historical "target
  PID in arg" semantics (NSH registers the foreground command it just
  spawned), while arg == 0 selects the calling task via
  nxsched_getpid(), matching the POSIX flag convention used by
  dropbear/socat/apue.  This preserves all existing callers and makes
  the previously-dead arg==0 path deliver SIGINT correctly.
- Add TIOCGPGRP/TIOCGSID (return dev->pid) and TIOCSPGRP (set it).
- pty.c gains the same handlers against pd_pid and includes
  nuttx/sched.h for nxsched_getpid().

ioctl numbers (tioctl.h): TIOCGPGRP/TIOCSPGRP/TIOCGSID at 0x37-0x39.

libc wrappers:
- termios: tcgetpgrp(), tcsetpgrp(), tcgetsid() over the new ioctls.
- unistd: setsid()/getsid()/setpgid() stubs consistent with the
  existing getpgrp()/getpgid() single-session model (sid == pgid ==
  pid; setpgid only succeeds for pgid == pid).

Declare the new prototypes in unistd.h (tcgetsid was already in
termios.h) and register all sources in the Make.defs/CMakeLists.

Group-broadcast signalling (kill(-pgrp)) remains unsupported, so
tty signals still target the single dev->pid; a real session/process
group model is left as a follow-up.

Signed-off-by: Xiang Xiao <xiaoxiang@xiaomi.com>
2026-06-23 16:26:53 -03:00
Xiang Xiao
a9b72ed796 libc/grp: add getgrouplist()
Add getgrouplist() to the C library.  It scans the group database for
a user's supplementary groups and always reports the primary group
first.  Without CONFIG_LIBC_GROUP_FILE only the primary group is
returned, since no membership information is available.

The group file is read through lib_get_tempbuffer()/lib_put_tempbuffer()
to avoid a heap allocation on every lookup.

Signed-off-by: Xiang Xiao <xiaoxiang@xiaomi.com>
2026-06-23 23:09:22 +08:00
Michal Lenc
1685e8ff7b syslog: avoid an infinite loop if one channel fails
The current implementation exits syslog_write_foreach function
if write to one channel fails, causing other channels not being written
and returning negated errno. libc syslog functions then stay in
an infinite loop, because error is returned and the same bytes
are still passed to syslograwstream_flush and syslog_write_foreach.

The channel write may fail for many reasons - disconnected USB if
CDC ACM syslog is enabled, lost networking if telnet syslog is enabled,
error on NOR flash etc. This shouldn't lead to an ininite loop in the
code though.

The solution ensures all channels in syslog_write_foreach are tried,
therefore the user get the output to the working channels even if
the first one is broken. It also updates syslograwstream_addchar and
syslograwstream_addstring to skip the bytes if all channels fails. This
ensures syslog call won't result in an infinite loop, but the user may
lost the debugging output.

Co-authored-by: Martin Krasula <mkrasula@elektroline.cz>
Signed-off-by: Michal Lenc <michallenc@seznam.cz>
2026-06-23 22:45:01 +08:00
Jukka Laitinen
7f8f800e63 arch, sched/signal: Fix compilation with ENABLE_PARTIAL_SIGNALS=y
Correct build errors when CONFIG_ENABLE_ALL_SIGNALS is not defined

- sched makefiles: Move pending-signal helpers from the ENABLE_ALL_SIGNALS-only
  list to the !DISABLE_ALL_SIGNALS list so signal dispatch is available in
  PARTIAL builds sched: make SIG_PREALLOC_ACTIONS, SIG_ALLOC_ACTIONS and
  SIG_DEFAULT depend on ENABLE_ALL_SIGNALS
- sched: fix ifdefs around pending-signal queue access and signal-mask for
  PARTIAL/DISABLE modes
- arch: gate SYS_signal_handler / _return calls and SYSCALL_LOOKUP(signal)
  with ENABLE_ALL_SIGNALS

Signed-off-by: Jukka Laitinen <jukka.laitinen@tii.ae>
2026-06-16 17:07:32 +08:00
Jukka Laitinen
f442c6b05e libs/libc/pthread/pthread_mutex: Fix robust mutex initialization
This fixes an issue where ostest robust mutex test gets stuck.

In CONFIG_PTHREAD_MUTEX_ROBUST mode, every NORMAL mutex is robust by
definition, so the robust flag must be set to allow the mutex to be tracked
in the holder's mutex list.

Otherwise, pthread_mutex_add() will not record the mutex and
pthread_mutex_inconsistent() will not be able to mark it as inconsistent or
wake waiters when the holder thread terminates.

Signed-off-by: Jukka Laitinen <jukka.laitinen@tii.ae>
2026-06-12 08:04:09 +08:00
Jukka Laitinen
116a325763 libs/libc/time: Add configuration options for the strftime
This adds 3 configuration options for the lib_strftime, which can be
used to save flash memory when all the formatters are not needed by an
embedded application.

There is always a minimal set of formatters supported:
"%a, %b/%h, %d, %H, %m, %M, %S, %Y, %%". To add on top of that one can
specify:

- LIBC_STRFTIME_C_STANDARD_FORMATS  : All ISO-C conversion specifiers
- LIBC_STRFTIME_POSIX_FORMATS       : Additional posix formats
- LIBC_STRFTIME_NONSTANDARD_FORMATS : Additional GNU nonstandard formats

All of these are enabled by default unless building for CONFIG_DEFAULT_SMALL.
Disabling these options can save over 3KB of flash on an 32-bit
ARM system, when all the format specifiers are not needed.

Signed-off-by: Jukka Laitinen <jukka.laitinen@tii.ae>
2026-06-04 14:29:33 +08:00
yushuailong
7e67d2d906 libs/libc/dirent: preserve errno on readdir() end-of-directory
readdir() returned NULL at end-of-directory without ensuring errno was
clean.  POSIX requires errno to be unchanged at EOF, but the underlying
read() path may leave a stale errno value.  Callers that follow the
POSIX idiom (set errno to 0 before the call, test it after a NULL
return), such as readdir_r() and scandir(), then misread this as a
readdir() failure.

Save errno on entry and restore it on the end-of-directory return so
that EOF no longer reports a spurious error, while genuine errors
(read() returning a negative value) still propagate.

Signed-off-by: yushuailong <yyyusl@qq.com>
2026-06-02 23:34:25 +08:00
zhangyu117
02833038fd arch/tricore: Full implementation of setjmp and longjmp.
1. The original method of restoring the register context relies on
   the ret instruction, which does not conform to the semantics of
   longjmp not returning.
2. There are csa leak during longjmp and need recycle.

Signed-off-by: zhangyu117 <zhangyu117@xiaomi.com>
2026-05-22 00:38:02 +08:00
zhangyuan29
e087d0f79d arch/tricore: Support setjmp and longjmp.
Add setjmp/longjmp support for TriCore architecture using iLLD
intrinsics to save and restore the CSA (Context Save Area) chain.

This implementation saves upper/lower context registers and walks
the CSA linked list to restore the full call context on longjmp.

Signed-off-by: zhangyuan29 <zhangyuan29@xiaomi.com>
2026-05-22 00:38:02 +08:00
Xiang Xiao
754dfd980b arch/sim: replace macOS C++ constructor runtime hack with post-link patch
The sim architecture needs to defer C++ global constructors until after
NuttX kernel initialization completes. On macOS this was previously done
via a runtime hack (sim_macho_init.c): a __attribute__((constructor))
function intercepted constructors, saved them, and replayed them later.
That approach was fragile because it depended on constructor ordering
and required mprotect() to patch the read-only __mod_init_func section
at runtime.

This commit replaces the runtime hack with a post-link patching scheme:

  1. Link with -Wl,-ld_classic,-no_fixup_chains to keep the classic
     __mod_init_func pointer format (prevents ld64 from converting it
     to __init_offsets).
  2. Post-link, run patch_macho_initsection.py (python3 + lief) to
     patch Mach-O section type flags from
     MOD_INIT_FUNC_POINTERS/INIT_FUNC_OFFSETS to REGULAR, so dyld
     skips them entirely.
  3. Use the Mach-O auto-generated boundary symbols
     section$start$__DATA_CONST$__mod_init_func /
     section$end$__DATA_CONST$__mod_init_func, mapped via __asm()
     labels in arch/sim/include/arch.h to the common _sinit[]/_einit[]
     names used by lib_cxx_initialize().

Linux behavior is unchanged.

Changes:
  - arch/sim/include/arch.h: add macOS __asm() declarations for
    _sinit/_einit
  - arch/sim/src/Makefile: drop sim_macho_init.c HEADSRC handling,
    always pass -ld_classic,-no_fixup_chains on macOS, run
    patch_macho_initsection.py after link when CONFIG_HAVE_CXXINITIALIZE
  - arch/sim/src/sim/CMakeLists.txt: same for the CMake build
  - arch/sim/src/patch_macho_initsection.py: new lief-based patcher
  - arch/sim/src/sim/posix/sim_macho_init.c: deleted (135-line hack)
  - libs/libc/misc/lib_cxx_initialize.c: remove
    macho_call_saved_init_funcs special case; single unified loop

Testing:
  - macOS (Ventura VM): verified lief patching with standalone test
    (test_sinit7) confirming the constructor is deferred past main()
    and only invoked when explicitly called via the _sinit/_einit loop.

Signed-off-by: Xiang Xiao <xiaoxiang@xiaomi.com>
2026-05-19 07:08:55 -03:00
Xiang Xiao
9ff99c6d0f !nuttx: drop redundant casts on tv_sec/tv_nsec and fix printf formats
Now that time_t is unconditionally 64-bit (signed int64_t) and the
struct timespec fields tv_sec / tv_nsec are wide enough on their own,
the explicit (uint64_t)/(int64_t)/(int) casts that used to guard the
multiplications and subtractions in *_us / *_ms / *_ns helpers are no
longer needed.  Drop them to keep the timekeeping math readable and
consistent with the previous sclock_t/time_t cleanup.

In the same spirit, this commit also:

* Normalises the printf-style format specifiers and casts used to
  print tv_sec / tv_nsec / tv_usec values across arch/, drivers/,
  fs/, sched/ and libs/.  The prior code was a mix of
  "%d"/"%u"/"%ld"/"%lu"/"%lld"/PRIu32/PRIu64 with matching
  (int)/(unsigned long)/(long long)/PRIu* casts; some formats
  truncated time_t on 32-bit hosts, others mismatched signedness or
  width.  Replace all such cases with the portable POSIX-recommended
  forms:

    - tv_sec  (time_t,       signed, impl-defined width) -> %jd  + (intmax_t)
    - tv_nsec (long,         signed)                     -> %ld  (no cast)
    - tv_usec (suseconds_t / long)                       -> %ld  (no cast)

  Add #include <stdint.h> where required.

* Drops a few stale `(FAR const time_t *)&ts.tv_sec` casts and
  related `(FAR struct tm *)` / `(const time_t *)` casts in
  gmtime_r() / localtime_r() / gmtime() callers; ts.tv_sec is plain
  time_t now and the casts only obscured the type.

* Fixes one overflow in fs/procfs/fs_procfscritmon.c where
  all_time.tv_sec * 1000000 could overflow on 32-bit time_t before
  being multiplied again; cast to uint64_t at the start.

No behavioural change.

Signed-off-by: Xiang Xiao <xiaoxiang@xiaomi.com>
2026-05-19 16:21:28 +08:00
Xiang Xiao
c47b1e2c5b !sys/types.h: change time_t and clock_t to int64_t to align with other OSes
POSIX leaves the signedness of time_t and clock_t unspecified, but
mainstream implementations (Linux glibc/musl, the BSDs, macOS, RTEMS,
Zephyr's POSIX layer, Windows _time64) expose time_t as signed 64-bit.
NuttX has historically used uint64_t only because it was tied to the
CONFIG_SYSTEM_TIME64 knob; with that gone, switch:

  time_t   : uint64_t  -> int64_t
  clock_t  : uint64_t  -> int64_t
  CLOCK_MAX: UINT64_MAX -> INT64_MAX

This lets (time_t)-1 sentinels, negative tick deltas, and host-side
headers behave as on every other POSIX system without source churn.

Headers updated:
  - include/sys/types.h, include/limits.h, include/nuttx/clock.h
  - include/nuttx/fs/hostfs.h (nuttx_time_t alias)
  - include/nuttx/{mqueue.h,wdog.h,wqueue.h,timers/clkcnt.h}

Because clock_t is now signed 64-bit, the NuttX-internal sclock_t
alias becomes redundant: every sclock_t/SCLOCK_MAX use is folded
back to clock_t/CLOCK_MAX (notably in sched/wdog, sched/mqueue,
sched/sched, sched/clock, sched/timer, libs/libc/time, fs/vfs and
the drivers/arch consumers below).

Tick/period constants (NSEC_PER_SEC, USEC_PER_SEC, MSEC_PER_SEC,
SEC_PER_MIN, ...) in include/nuttx/clock.h are retyped from "long"
literals to INT64_C(...) so that 64-bit arithmetic no longer
depends on the host's long width.

Strip now-redundant (time_t)/(clock_t)/(unsigned long) casts and
unsigned-only branches across the tree:
  - arch RTC / oneshot / tickless lowerhalfs:
      arm: cxd56xx, efm32, imxrt, lc823450, max326xx, sam34, sama5,
           samd5e5, samv7, stm32, stm32f7, stm32h7, stm32l4, stm32wb,
           xmc4
      mips: pic32mz       sparc: bm3803       x86_64: intel64
      risc-v/xtensa: espressif (esp_i2c[_slave], esp_rtc,
           esp32c3{_i2c,_rtc,_wifi_adapter}, esp32{,s2,s3}_*),
           mpfs_perf
  - drivers: audio/tone, input/aw86225, power/pm/{activity,
           stability}_governor, rpmsg/rpmsg_ping,
           timers/{ds3231,mcp794xx,pcf85263,rx8010},
           wireless/ieee80211/bcm43xxx, wireless/spirit/spirit_spi
  - core: fs/vfs/{fs_poll,fs_timerfd}, mm/iob/iob_alloc,
          libs/libc/{netdb/lib_dnscache,time/{lib_calendar2utc,
          lib_time}}, net/icmp/icmp_pmtu, net/icmpv6/icmpv6_pmtu,
          net/ipfrag, net/tcp/{tcp.h,tcp_timer},
          net/utils/net_snoop, net/mld/mld_query (drop the now-dead
          mld_mrc2mrd helper since signed math handles it directly),
          sched/clock/{clock,clock_initialize},
          sched/sched/{sched_profil,sched_setparam,sched_setscheduler},
          sched/pthread/pthread_create,
          sched/wdog/{wd_gettime,wd_start,wdog.h},
          sched/timer/timer_gettime, sched/mqueue/*

Flip the few in-tree printf format strings that assumed an
unsigned 64-bit tv_sec:
  * drivers/rpmsg/rpmsg_ping.c                       PRIu64 -> PRId64
  * arch/xtensa/src/esp32{,s2,s3}/esp32*_oneshot_lowerhalf.c
                                          PRIu32 (already wrong) -> PRId64

Signed-off-by: Xiang Xiao <xiaoxiang@xiaomi.com>
2026-05-19 16:21:28 +08:00
Xiang Xiao
c6654b1106 !sched/clock: remove CONFIG_SYSTEM_TIME64 and always use 64-bit time
The 32-bit system clock has a limited range (~497 days) and the
configuration knob is no longer worth the complexity given that
practically every modern target already enables it.  Make 64-bit
time_t/clock_t/sclock_t/nuttx_time_t the only supported flavor.

Specifically:
  - Drop the SYSTEM_TIME64 Kconfig option and its dependent
    PERF_OVERFLOW_CORRECTION/HRTIMER guards in sched/Kconfig.
  - Remove every #ifdef CONFIG_SYSTEM_TIME64 branch in headers
    (include/{sys/types.h,limits.h,inttypes.h,nuttx/clock.h,
    nuttx/fs/hostfs.h}) and core code paths
    (sched/clock/clock.h, drivers/power/pm/pm_procfs.c,
    drivers/rpmsg/rpmsg_ping.c, fs/procfs/fs_procfsuptime.c,
    libs/libc/wqueue/work_usrthread.c,
    arch/avr/src/avrdx/avrdx_timerisr_tickless_alarm.c).
  - Strip CONFIG_SYSTEM_TIME64=y from every board defconfig.
  - Update Documentation/guides/rust.rst accordingly.

Signed-off-by: Xiang Xiao <xiaoxiang@xiaomi.com>
2026-05-19 16:21:28 +08:00
Xiang Xiao
1b3af76bf3 !libc/stream: remove CONFIG_LIBC_LONG_LONG and always support long long
Long long support is now unconditional in printf/scanf and related
helpers. Remove the Kconfig option, the conditional compilation in
libvsprintf/libvscanf/ultoa_invert, the build-time #error in the
rn2xx3 driver, and clean up CONFIG_LIBC_LONG_LONG entries from all
board defconfigs.

Signed-off-by: Xiang Xiao <xiaoxiang@xiaomi.com>
2026-05-19 16:21:28 +08:00
Xiang Xiao
c32b683085 !compiler: drop CONFIG_HAVE_LONG_LONG and require long long support
Every compiler supported by NuttX provides the "long long" types,
so the CONFIG_HAVE_LONG_LONG indirection is no longer useful.
Remove the option from include/nuttx/compiler.h and treat
"long long" as unconditionally available across the OS.

In addition to deleting the guard itself, this commit unconditionally
enables the long-long flavored helpers that used to be gated behind
it:

  - libs/libc/fixedmath: drop the soft-emulated b32/ub32 routines
    in lib_fixedmath.c (-261 lines) and trim the matching
    prototypes, Make.defs and CMakeLists.txt entries; keep only
    the long-long backed implementations.
  - include/sys/endian.h, include/strings.h, libs/libc/string
    /lib_ffsll.c, lib_flsll.c: always expose the 64-bit byte-swap
    and ffsll/flsll variants.
  - libs/libm/libm/lib_llround{,f,l}.c: drop the empty stubs.
  - libs/libc/stdlib (atoll, llabs, lldiv, strtoll/ull, rand48,
    strtold), libs/libc/stream (libvsprintf, libvscanf,
    libbsprintf, ultoa_invert), libs/libc/misc (crc64, crc64emac),
    libs/libc/inttypes/strtoimax, libs/libc/lzf, libs/libc/libc.csv,
    libs/libc/string (memset, vikmemcpy): remove the
    #ifdef CONFIG_HAVE_LONG_LONG branches.
  - include/{stddef.h,stdlib.h,fixedmath.h,sys/epoll.h,cxx/cstdlib,
    nuttx/audio/audio.h,nuttx/crc64.h,nuttx/lib/math.h,
    nuttx/lib/math32.h,nuttx/lib/stdbit.h}: same guard cleanup.
  - drivers/note/note_driver.c, fs/spiffs/src/spiffs.h,
    sched/irq/irq_procfs.c: drop their local guards as well.
  - Documentation/applications/netutils/ntpclient/index.rst:
    refresh the documentation snippet.

Signed-off-by: Xiang Xiao <xiaoxiang@xiaomi.com>
2026-05-19 16:21:28 +08:00
Liam Hickey
13ba91a33f arch/*/src/Makefile: Avoid uncessary relinking of the nuttx binary.
The goal is to only execute recipes when there is an actual change in
the prerequisites.

There are several issues which cause the nuttx binary target to be
re-made every time the top level make is run.

1. Previously the target nuttx$(EXEEXT), was used, but make resolved
this in the relative directory make -C $(ARCH_SRC), and couldn’t find
it (need an absolute path: `$(TOPDIR)/..).

2. The .tmp prerequisite for nuttx was always deleted

3. libboard's recipe had a sub-make which may or may not update that
target. This was a phony target, and was therefore always considered out
of date.

These issues were causing the nuttx recipe to be run every make, which
was hiding some missing prerequisites:

1. the .config is a prerequisite for the .tmp target
2. libapps.a (and other linklibs) are pre-requisites for nuttx

Changes:

The changes are only in the build system, and only for arm.

Track nuttx$(EXEEXT) via vpath so Make knows when it's already up to
date without an explicit path. Add $(TOPDIR)/.config as a dependency
to the linker script preprocessing so config changes trigger
re-preprocessing.

Keep the .tmp linker script on disk (clean already removes it) so
timestamp-based dependency checking works across builds. These .tmp
files need to be added to the gitignore or the CI will complain.

Use FORCE pattern for board/libboard to ensure it's always checked
but use the actual library file as the link dependency so nuttx is
only re-linked when library content changes. Add staging libs as
dependency to nuttx link rule so changed app libs trigger re-link.

Signed-off-by: Liam Hickey <williamhickey@geotab.com>
2026-05-18 09:33:58 +02:00
bijunda
1076cb933d fix(compiler-rt): avoid duplicate builtins dir on sim
compiler-rt/Make.defs:45: target `bin/compiler-rt/compiler-rt/lib/builtins' given more than once in the same rule.
compiler-rt/Make.defs:45: target `kbin/compiler-rt/compiler-rt/lib/builtins' given more than once in the same rule.

Signed-off-by: bijunda <bijunda@bytedance.com>
2026-05-13 10:01:26 -03:00
bijunda
31c7409d80 fix(sim): fix compiler-rt build on macOS
Added the missing __APPLE__ which was undefined by sim globally.
Added missing linker flags.

Signed-off-by: bijunda <bijunda@bytedance.com>
2026-05-13 10:01:26 -03:00
yaojiaqi
131f7f75ed arm: memcpy: add NEON paths for aligned copies
Add dedicated NEON implementations for mutually aligned medium and long memcpy copies when building with __ARM_NEON__. These paths use NEON multi-register loads and stores while preserving the existing VFP implementation for non-NEON VFP configurations.

NEON builds also define USE_VFP, so select the NEON implementation explicitly before falling back to VFP. Apply the same aligned-copy optimization to the armv7-a, armv7-r, and armv8-r implementations.

Signed-off-by: yaojiaqi <yaojiaqi@lixiang.com>
2026-05-09 09:46:43 +08:00
Alan Carvalho de Assis
805169cebd libs/netdb: Fix dns_recv_response() to dns_answer_s size
This commit avoid that dns_recv_response() accepts fewer tha 10 bytes
that could end up with an OOB read.

Signed-off-by: Alan C. Assis <acassis@gmail.com>
2026-05-04 12:16:50 -03:00
Piyush Patle
0dccc8ba21 include/debug.h: Move to include/nuttx/debug.h
debug.h is a NuttX-specific, non-POSIX header. Placing it in the
top-level include/ directory creates naming conflicts with external
projects that define their own debug.h.
This commit moves the canonical header to include/nuttx/debug.h,
following the NuttX convention for non-POSIX/non-standard headers,
and updates all in-tree references.

A backward-compatibility shim is left at include/debug.h that
emits a deprecation #warning and re-includes <nuttx/debug.h>,
allowing out-of-tree code to continue building while migrating.

Signed-off-by: Piyush Patle <piyushpatle228@gmail.com>
2026-04-07 07:50:06 -03:00
shichunma
900998fe20 netdb/dns: validate nameserver input in dns_add_nameserver
It can't be zero or broadcast addr for a valid dns server.

Signed-off-by: shichunma <masc2008@gmail.com>
2026-04-07 16:43:14 +08:00
Huang Qi
e09048cc88 style: Fix "is is" typo across the codebase.
Correct duplicate "is is" word found in 181 files throughout the
codebase.
In most cases "is is" was changed to "is", but in contexts like
"MCU is is sleep mode" it was corrected to "MCU in sleep mode".

Also fixes a "the the" typo in net/inet/inet_sockif.c.

This is a pure style/documentation fix that improves code readability.

Signed-off-by: Huang Qi <huangqi3@xiaomi.com>
2026-03-24 09:39:26 +08:00
simbit18
c324fc1cc2 libs\libxx: Fix Make style
- Remove spaces from make file

Signed-off-by: simbit18 <simbit18@gmail.com>
2026-03-23 18:16:46 -04:00
Huang Qi
e3eeaefd6d style: Fix "the the" typo across the codebase.
Fix 269 occurrences of duplicate "the" word typo found in 209 files
across source code, header files, and configuration.

Signed-off-by: Huang Qi <huangqi3@xiaomi.com>
2026-03-23 11:07:49 +01:00
Huang Qi
228eae22a0 libs/libbuiltin: Fix spacing style in gcov.c
Add space after 'else if' keyword to follow NuttX coding style
guidelines.

Signed-off-by: Huang Qi <huangqi3@xiaomi.com>
2026-03-21 19:44:54 -04:00
chenzhaoxiang
3fb1a40a4b libs/libc: add configurable skip count for mutex backtrace addresses
This commit introduces a new Kconfig option LIBC_MUTEX_BACKTRACE_SKIP tocontrol the
number of initial addresses skipped when generating mutex backtraces.

Key changes:
1. Add LIBC_MUTEX_BACKTRACE_SKIP Kconfig entry (depends on
LIBC_MUTEX_BACKTRACE > 0), defaulting to 2. This option lets users configure
how many leading addresses are omitted from the mutex backtrace output.

2. Modify the nxmutex_add_backtrace() function to pass the new config value
as the skip parameter to sched_backtrace(), replacing the hardcoded 0.

This enhancement improves the usability of mutex backtraces by allowing removalof uninformative
initial stack frames (e.g., backtrace helper functions ormutex acquisition wrappers), making the
relevant call stack entries more visiblefor debugging lock-related issues.

The default value (2) maintains sensibleout-of-the-box behavior while enabling customization for specific use cases.

Signed-off-by: chao an <anchao.archer@bytedance.com>
2026-02-27 19:54:37 +08:00
wangchengdong
5060ee80d1 libs/pthread: disable pthread_kill when no signals
pthread_kill depends on signasl, so when all signals are disabled
 disable pthread_kill too

Signed-off-by: Chengdong Wang <wangchengdong@lixiang.com>
2026-02-26 20:03:05 +08:00