virtiofs_readdir() passed expected_len=-1 to
virtiofs_validate_response(), so the host-controlled out_header.len was
used to compute the return value without a bounds check. A value smaller
than the header underflowed, and a value larger than the dirent and name
buffers was reported as read.
virtiofs_write() validated the reply header but returned the
device-supplied write_out.size without checking it against the request.
A value larger than the requested size makes fs_write() report more
bytes than the caller supplied, and the int accumulator in
virtio_zfs_write() can overflow on 32-bit targets.
Reject both cases with -EIO.
Tested on qemu_x86_64/atom: invalid READDIR lengths and oversized WRITE
replies are rejected with -EIO.
Signed-off-by: Hongquan Li <hongquan.li@processmission.com>
Opening a file is a common way to check whether an optional file exists,
in which case -ENOENT is an expected result, but fs_open() logged it as
an error. Only log the other errors, as fs_stat() already does for
-ENOENT.
Tested with the fat_fs_api and fs_api tests on native_sim.
Assisted-by: Claude:opus-5.5
Signed-off-by: Benjamin Cabé <benjamin@zephyrproject.org>
fs_opendir("/") opens a file system mounted at the root itself when
one exists, instead of unconditionally enumerating mount points via
the virtual root directory.
Co-authored-by: Chris Friedt <chris@fr4.co>
Assisted-by: Claude:claude-opus-5.5
Signed-off-by: Benjamin Cabé <benjamin@zephyrproject.org>
virtiofs_send_receive() ignored the return value of
virtq_add_buffer_chain(). A failed enqueue would never invoke the
receive callback, leaving the caller blocked forever on the completion
semaphore and leaking the bounce buffer.
Check the return value, log the error and release the bounce buffer.
Split the request path into a checked helper that returns the error and
the existing wrapper for callers that validate the response length.
virtiofs_destroy() now uses the checked helper so an enqueue failure is
reported to fs_unmount() instead of being mistaken for a valid empty
FUSE_DESTROY reply.
Fixes#122024
Signed-off-by: Hongquan Li <hongquan.li@processmission.com>
Directory block removal indexed i_block[] by logical block number, which
corrupts indirect directories. Root lookup leaves parent NULL, so renaming
the mount point crashed. Also reject out-of-range inode and group numbers,
cap inode bitmap walks to one block, and compute disk addresses in 64-bit
arithmetic.
Signed-off-by: Dhruv Menon <dhruvmenon1104@gmail.com>
fs_mount() compared mp->fs_data against every mounted entry only after
"if (len != itr->mountp_len) continue;", so two mount points sharing one
private state struct were accepted whenever their mount point strings
differed in length, leaving two mount entries driving one file system
state. Move the comparison ahead of that short circuit, which is only a
precondition for the strncmp() below it, and skip it when the incoming
fs_data is NULL, since ext2 and other file systems that allocate their
state while mounting legitimately arrive here with NULL. Use a plain if
rather than CHECKIF so the guard survives CONFIG_NO_RUNTIME_CHECKS. Also
stop littlefs from clearing fs->backend on its mount failure path, which
corrupted the live instance owning it, and give each mount point in
test_multi_fs its own private data instead of sharing one instance.
Reject a NULL fs_data in littlefs_mount(); littlefs does not allocate that
instance itself.
Signed-off-by: Dhruv Menon <dhruvmenon1104@gmail.com>
New inode allocation remains committed when file or directory creation
fails after allocation. The caller only drops the in-memory reference; the
inode remains allocated on disk.
Keep removal pending until initial creation succeeds. Mark later creation
failures for cleanup through the existing inode-drop path.
Fixes#118139
Signed-off-by: Hongquan Li <hongquan.li@processmission.com>
The close path returns early when inode sync or drop fails, leaving the
file slab object and public file handle allocated. An abandoned handle can
then exhaust the ext2 file and inode pools.
Always attempt inode cleanup and release the file object. Treat a repeated
close of the cleaned handle as a no-op so the public handle can be cleared.
Fixes#118141
Signed-off-by: Hongquan Li <hongquan.li@processmission.com>
Formatting dereferences inode-table block allocations without checking
them, and two directory allocation failures return positive ENOMEM.
Format callers only recognize negative errors, so either case can fault or
report a failed format as successful.
Check allocations before use and return -ENOMEM for allocation failures.
Fixes#118138
Signed-off-by: Hongquan Li <hongquan.li@processmission.com>
ext2_inode_drop() compacts the inode pool after removing an entry, so an
increasing close-loop index skips the entry moved into that slot. The close
path also returns before releasing group blocks when metadata commit fails.
Process compacted entries at the current index and preserve cleanup errors.
Always release group blocks and synchronize the backend.
Fixes#118140
Signed-off-by: Hongquan Li <hongquan.li@processmission.com>
The metadata commit helpers return before releasing the temporary block
when ext2_write_block() fails. This leaks slab allocations on each failed
metadata write.
Drop the block before returning the write error.
Fixes#118137
Signed-off-by: Hongquan Li <hongquan.li@processmission.com>
The inode read and write paths return a later block error after
earlier bytes have completed. The file wrapper therefore leaves its offset
despite completed write data already being persisted.
Return completed byte counts after later block errors and persist the size
reached by completed writes.
Fixes#118142
Signed-off-by: Hongquan Li <hongquan.li@processmission.com>
Add hardening rules for the shell command modules that give raw read
and write access to persistent storage. These are base profile rules:
unlike CONFIG_SHELL itself, which only the strict profile flags, dumping or
rewriting flash, EEPROM, settings and files is not appropriate even for
products that deliberately ship a shell.
- CONFIG_EEPROM_SHELL: n (base)
- CONFIG_FILE_SYSTEM_SHELL: n (base)
- CONFIG_FLASH_SHELL: n (base)
- CONFIG_SETTINGS_SHELL: n (base)
Assisted-by: Claude:fable-5
Signed-off-by: Benjamin Cabé <benjamin@zephyrproject.org>
Utilize a code spell-checking tool to scan for and correct spelling errors
in all files within:
- `subsys/fs/fcb`
Assisted-by: Claude:claude-sonnet-5-5 codespell
Signed-off-by: Pisit Sawangvonganan <pisit@ndrsolution.com>
Every caller that needs a path in canonical form writes its own logic
for it, because the file system subsystem has no such helper.
Requested in #115895, which notes #81888 as an earlier report of the
same gap.
Add fs_normalize_path(path, buf, len): it collapses repeated and
trailing separators and resolves "." and ".." into buf. Zephyr has no
symbolic links, so nothing is resolved through the file system.
The mount table is not consulted, so the result depends on the string
alone. A ".." that would climb above the leading "/" resolves to "/",
as on a POSIX system. Anchoring it at the mount point instead would
depend on what happens to be mounted: mount points may nest and
fs_get_mnt_point() takes the longest prefix, so with /NAND: and
/NAND:/sub both mounted, /NAND:/sub/../x would have been rejected.
path and buf may be the same buffer: the pass never writes ahead of
what it has read. A buf too small for the result, or for a prefix a
later ".." pops, yields -ENAMETOOLONG.
Fixes#115895
Signed-off-by: Arkadiusz Grzelka <devitwise@gmail.com>
Assisted-by: Claude:claude-opus-5
This driver needs the nsi_errno conversion component.
Let's make sure we build it by selecting it.
Signed-off-by: Alberto Escolar Piedras <alberto.escolar.piedras@nordicsemi.no>
FUSE request/response buffers were passed to the virtqueue straight from
the caller's stack. A thread stack is not guaranteed to be physically
addressable via k_mem_phys_addr(), so transfers issued from a non-main
thread could hand the device a bogus physical address and come back with
a zero-length reply (seen as FUSE_INIT returning length 0).
Bounce each FUSE transfer through a heap buffer allocated with k_malloc,
which is DMA-reachable, and tolerate a short FUSE_DESTROY reply.
Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
Use #include <> instead of #include "" to include a header file which path
is not relative to the directory path of the file emitting the #include
directive.
This change was made running scripts/check_quoted_includes.py script
proposed in https://github.com/zephyrproject-rtos/zephyr/pull/112135
with the Linux shell command below and manually selecting the applicable
changes:
$ find subsys/fs/ -type f -exec \
./scripts/check_quoted_includes.py -w {} \;
Signed-off-by: Etienne Carriere <etienne.carriere@st.com>
validate_config() only substitutes ext2_default.block_size when
cfg->block_size is 0; it never enforces a minimum. ext2_format() then
computes:
uint8_t block_log_size = find_msb_set(cfg->block_size) - 11;
find_msb_set() returns an unsigned int, so for any block_size whose
most-significant-bit index is less than 11 (i.e. block_size < 1024,
including the very plausible mistake of passing the sector size, 512),
the subtraction underflows and block_log_size wraps to a large
garbage value (e.g. 512 -> 255, 256 -> 254, 100 -> 252, 1 -> 246).
That truncated value is written straight into the on-disk superblock
field s_log_block_size, so ext2_format() reports success while
silently producing a corrupt, unmountable file system instead of
failing cleanly at format time.
Extend validate_config() to reject any nonzero block_size that is not
a power of two >= 1024, and propagate the error from ext2_format()
before the shift-count calculation is reached. block_size == 0 keeps
resolving to the documented default, and all currently-legal values
(1024/2048/4096/...) are unaffected.
Fixes#84678
Assisted-by: Claude:claude-sonnet-5
Signed-off-by: yi chen <94xhn1@gmail.com>
virtiofs_read() validated only error/used_len but passed expected_len=-1
to virtiofs_validate_response(), skipping the length check. The host-
supplied out_header.len was then used to compute the return value; a
value smaller than sizeof(out_header) underflowed, and a value larger
than the read buffer would misrepresent the bytes read.
Guard against both cases before returning.
Assisted-by: Claude:claude-opus-4-8
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
Use strncpy instead of strcpy when writing the volume name into
the superblock so that an oversized cfg->volume_name cannot overrun
the fixed-size s_volume_name field.
Signed-off-by: Flavio Ceolin <flavio@hubble.com>
Replace nested MIN/MAX macro calls with the min3/max3 APIs which are
safer (evaluate arguments only once) and cleaner.
Assisted-by: Gemini:gemini-3.1-pro
Signed-off-by: Fabio Baltieri <fabiobaltieri@google.com>
Add RPMsgFS fs type to the mount command.
Usage: fs mount rpmsgfs <mount-point> [<remote-path>]
mount-point: Mount point path on local system
remote-path: Path within the exported directory on remote to where the
mount-point is mapped to. [Default: "/"]
Signed-off-by: Andre Heinemans <andre.heinemans@nxp.com>
RPMsgFS allows mounting directories on a remote core using RPMsg. This
protocol is originally made in NuttX but has also implementations in
Linux.
To mount this file system, call fs_mount() with type: "FS_RPMSGFS" and put
the remote path in the .fs_data field as a zero terminated string.
The remote path points to the path on the remote that should be mapped
to the local mount point. The remote path must be an existing path
within the exported path on the remote file system.
Signed-off-by: Andre Heinemans <andre.heinemans@nxp.com>
`FLASH_PAGE_LAYOUT` is a symbol with its own dependencies, it should not
be selected by subsystems that with to use it. The symbol is already
enabled by default when `FLASH_HAS_PAGE_LAYOUT`, so this change won't
silently change any enabled symbols. The `depends on` ensures that the
user is not enabled if the feature is not available.
Signed-off-by: Jordan Yates <jordan@embeint.com>
The block bitmap validation passed
fs_blocks = s_blocks_count - s_first_data_block
directly to ext2_bitmap_count_set() without checking whether it exceeds
the bitmap's capacity of block_size × 8 bits. A crafted image could
trigger a ~512 MB bitmap scan with a heap over-read.
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
Fix problem where fcb_init was failing due to fcb_sector_hdr_init
attempting to write flash without taking write alignment into account.
Fixes#111886
Signed-off-by: Dominik Ermel <dominik.ermel@nordicsemi.no>
ext2_verify_disk_superblock() never validated s_log_block_size. A
crafted image could set it so that 1024 << s_log_block_size overflows
the shift or exceeds CONFIG_EXT2_MAX_BLOCK_SIZE, corrupting the static
block slab and leading to heap overflow on the first block read.
Reject block sizes that overflow the shift or exceed the configured
maximum.
Signed-off-by: Anas Nashif <anas.nashif@intel.com>
ext2_verify_disk_superblock() did not validate that the on-disk fields
s_blocks_per_group and s_inodes_per_group are non-zero. Both are later
used as divisors during mount-time initialization:
- get_ngroups() in subsys/fs/ext2/ext2_diskops.c divides and modulos
s_blocks_count by s_blocks_per_group when ext2_fetch_block_group()
runs from ext2_init_fs().
- get_itable_entry() in the same file divides (ino - 1) by
s_inodes_per_group when fetching the root inode during mount.
Reject both fields up front in the superblock validator so the mount
fails with -EINVAL before any block-group or inode I/O occurs.
Signed-off-by: Flavio Ceolin <flavio@hubblenetwork.com>
Problem:
When fs_open() is called with FS_O_TRUNC, the FS backend
opens the underlying file via mp->fs->open() before the
truncate is attempted. If mp->fs->truncate() then fails,
the previous code cleared zfp->mp and returned right away,
which causes two issues:
- the backend's close hook is never invoked, so the
resources allocated during open (file slab entries,
internal caches, backend-specific structures such as
lfs_file, etc.) stay permanently allocated;
- a follow-up fs_close(zfp) cannot recover them either,
because zfp->mp has already been NULL'd and fs_close()
returns early.
The leak is reproducible on every backend (LittleFS, FAT,
...) and accumulates one slot per failed call until the
file slab is exhausted.
Solution:
Close the backend file explicitly in the truncate failure
path, before clearing zfp->mp, so the FS-specific close
hook can release everything it allocated during open().
If close itself fails, log the secondary error but still
return the original truncate error code, since that is
the root cause callers diagnose against.
Signed-off-by: Shuai Ma <malin719426@gmail.com>
- Fix to_write calculation to account for already written bytes
- Advance offset in loop to fetch correct block on each iteration
Signed-off-by: DEVER Emiel <emiel.dever@psicontrol.com>
ext2_fetch_direntry() trusted the on-disk de_rec_len and de_name_len,
and the lookup and readdir paths advanced traversal by an unvalidated
de_rec_len. A crafted ext2 image could trigger an out-of-bounds read
past the directory block buffer or a zero-progress loop in any path
that walks a directory.
Validate rec_len and name_len in the parser, and reject entries whose
header does not fit in the remaining block or whose rec_len would
cross the block boundary in each caller.
Signed-off-by: Flavio Ceolin <flavio@hubblenetwork.com>
Implement Native Simulator host filesystem mounting under Zephyr. This file
system allows to access host files and directories inside Zephyr running
under Native Simulator.
There is new Native Simulator executable parameter supported '-volume',
which can be used to mount any host directory in Zephyr (following Docker
volume mount syntax):
-volume=/host/dir:/dir
Signed-off-by: Marcin Niestroj <m.niestroj@emb.dev>
Since commit 37717b229f ("sys: util: rename Z_MIN Z_MAX Z_CLAMP to min
max and clamp"), <zephyr/sys/util.h> unconditionally defines function-
like macros named `min`, `max`, and `clamp` in the global namespace (in
C mode). util.h gets pulled in transitively by very broad headers,
including the POSIX layer's <pthread.h>, so any third-party C code that
uses these names as ordinary identifiers (e.g. XNNPACK's static `clamp`
helper and its public `clamp` struct field) fails to build as soon as
<pthread.h> is included.
Following the approach used by Linux, move the lowercase `min`, `max`,
`min3`, `max3`, and `clamp` macros (and their helpers) into a new
<zephyr/sys/minmax.h> header that has to be included explicitly by
source files that want them. util.h keeps the uppercase MIN/MAX/CLAMP,
so most code is unaffected; only the (much smaller) set of files that
actually use the lowercase variants needs to pick up the new include.
Fixes#107853.
Signed-off-by: Nicolas Pitre <npitre@baylibre.com>
ffa_create_top() was opening files with FS_O_CREATE | FS_O_WRITE
only, which caused host applications like 'cat' to fail with
Permission denied when trying to read the file through FUSE. This
is because FAT filesystem explicitly checks the READ flag before
allowing read access.
Fix by replacing FS_O_WRITE with FS_O_RDWR so the file is opened
with both read and write access.
Signed-off-by: Surya Prakash T <suryat@aerlync.com>
Introduces K_MEM_SLAB_DEFINE_TYPE() and K_MEM_SLAB_DEFINE_STATIC_TYPE()
helpers to allow the user to declare slabs for types without having to
manually ensure the alignment is correct.
Manual slab alignment was very error-prone and this change fixes several
instances of misalignment that would be trapped by the undefined
behavior sanitizer when running on 64-bit targets.
Signed-off-by: Egill Sigurdur <egill@egill.xyz>
This commit fixes the bug by ensuring `to_write` is properly bounded.
It is now calculated as the minimum of the remaining requested bytes
(`nbytes - written`) and the remaining space in the current block
(`block_size - block_off`).
Fixes#106276
Signed-off-by: Ashirwad Paswan <ashi06712@gmail.com>
Increase the maximum allowed repeat count for read and write/erase
test commands from 10 to 10000. This allows for more accurate
measurements over longer test durations.
Signed-off-by: Tim Pambor <tim.pambor@codewrights.de>
Replaces usage of these deprecated macros with ones that support
fixed and mapped partition compatibles. Also includes an update to
hal_espressif which also (rightly or wrongly) has zephyr specific
code in it
Signed-off-by: Jamie McCrae <jamie.mccrae@nordicsemi.no>
Add an early check whether FAT fs is already mounted similar to
littlefs mount command. This fixes a null pointer access if the mount
command is used twice.
Fixes#104777
Signed-off-by: Jonas Spinner <jonas.spinner@burkert.com>
Support for using v3 of the FUSE library instead of v2 was added in
b86e52bd6f
As time has been passing more distros are removing v2 support, and at
this point probably all include the v3 in their package repos.
So, let's switch the default to v3.
Signed-off-by: Alberto Escolar Piedras <alberto.escolar.piedras@nordicsemi.no>
Let's avoid using off_t in the interface between the embedded and the
host side of the FUSE driver.
off_t is a C library defined type and as such can have a different sizes
between the host C library and the embedded C library.
While at it, let's do also the same with size_t. Even though size_t is
meant to be defined in stddef.h which is provided by the compiler, it is
possible to override it in the embedded side.
We just replace them with a 64 bit type for each (signed and unsigned
respectively matching the signedness of off_t and size_t).
There was a bug in the queue type which had the read/write second
parameter as off_t while it should have been size_t, which is now fixed
to be uint64_t.
Signed-off-by: Alberto Escolar Piedras <alberto.escolar.piedras@nordicsemi.no>
Use SHELL_HELP macro for help strings to ensure consistency across
various shell modules.
This also documents the usage for each command.
Signed-off-by: Benjamin Cabé <benjamin@zephyrproject.org>