Sarthak-Pandey opened a new issue, #22550:
URL: https://github.com/apache/nuttx/issues/22550
### Description / Steps to reproduce the issue
### Summary
`procfs_snprintf()` in `fs/procfs/fs_procfsutil.c` wraps `vsnprintf()` to
return the actual count of bytes formatted and written into `buf`. It contains
a signed/unsigned type comparison flaw and an integer underflow when `size ==
0`:
```c
int procfs_snprintf(FAR char *buf, size_t size,
FAR const IPTR char *format, ...)
{
va_list ap;
int n;
va_start(ap, format);
n = vsnprintf(buf, size, format, ap);
va_end(ap);
return n < size - 1 ? n : size - 1;
}
```
### Root Cause
1. `n` is a signed `int` while `size` is an unsigned `size_t`.
2. When comparing `n < size - 1`, C integer promotion converts signed `int
n` to `size_t`.
3. If `vsnprintf()` fails and returns `-1`, `-1` becomes `(size_t)-1`
(`SIZE_MAX`). The comparison `SIZE_MAX < size - 1` evaluates to `false`,
causing the function to return `size - 1`.
4. If `size == 128` and formatting fails, `procfs_snprintf()` returns `127`
as if 127 bytes were successfully formatted, causing callers to read and
process uninitialized buffer memory.
5. If `size == 0`, `size - 1` underflows to `SIZE_MAX`.
### Steps to Reproduce
1. Call `procfs_snprintf(buf, sizeof(buf), "%invalid_format_specifier")` or
pass an invalid format string that triggers `vsnprintf` to return `-1`.
2. Check the return value: instead of `0` or negative error, it returns
`sizeof(buf) - 1`.
3. Call `procfs_snprintf(buf, 0, "test")`: observe unsigned integer
underflow on `size - 1`.
### Expected Behavior
- If `size == 0` or formatting fails (`n < 0`), the function must return `0`.
- The returned byte count must never exceed the number of
initialized/written bytes.
### Proposed Fix
```diff
--- a/fs/procfs/fs_procfsutil.c
+++ b/fs/procfs/fs_procfsutil.c
@@ -143,8 +143,18 @@ int procfs_snprintf(FAR char *buf, size_t size,
va_list ap;
int n;
+ if (size == 0)
+ {
+ return 0;
+ }
+
va_start(ap, format);
n = vsnprintf(buf, size, format, ap);
va_end(ap);
- return n < size - 1 ? n : size - 1;
+
+ if (n < 0)
+ {
+ return 0;
+ }
+
+ return ((size_t)n < size) ? n : (int)(size - 1);
}
```
### On which OS does this issue occur?
[OS: Windows]
### What is the version of your OS?
Windows 11
### NuttX Version
master
### Issue Architecture
[Arch: all]
### Issue Area
[Area: File System]
### Host information
N/A (Generic architecture-independent C defect in fs/procfs/fs_procfsutil.c)
### Verification
- [x] I have verified before submitting the report.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]