Skip to content

WIP: Replace dangerous old string functions with less horrible variants, for -fbounds-safety compatibility - #24

Draft
seanm wants to merge 3 commits into
InsightSoftwareConsortium:masterfrom
seanm:kill-old-str-fns
Draft

seanm wants to merge 3 commits into
InsightSoftwareConsortium:masterfrom
seanm:kill-old-str-fns

Conversation

@seanm

@seanm seanm commented Jan 14, 2026

Copy link
Copy Markdown
Collaborator

@hjmjohnson this one needs careful checking.

Also it's not done yet, I have to do some cmake stuff to compile the new file.

@gdevenyi

gdevenyi commented Aug 15, 2026 •

Copy link
Copy Markdown
Collaborator
Closed PR comment

Heads up that #26 will conflict with this one, and on a couple of details that may be worth folding in whenever this comes off WIP.

The conflicts: #26 rewrites the QSTR macro in both nifti1_io.c and nifti2_io.c (parenthesising sz), rewrites nifti_findhdrname() in both files, and removes nifticdf entirely — so the nifticdf.c hunk here disappears along with the file. Worth noting that this PR's rewrite of nifti_intent_code() drops the malloc NULL check that #23 adds to the same function.

Two things #26 found in code this PR touches:

nifti_findhdrname() under -DFSLSTYLE has a use-after-free — basename is freed, then read by the fprintf reporting the ambiguous-filename error — plus an unchecked calloc whose result goes straight into strcpy/strcat. Both are in the block right above the exit(134).

On string_helper/: the guard is #if defined(__GLIBC__) && ..., so on musl, MSVC, or any non-glibc non-Apple libc __GLIBC__ is undefined, the fallback is not compiled, and strlcpy is missing at link time. Also, defining strlcpy/strlcat at global scope adds symbols with libc-reserved names to the library, which can collide for downstream consumers — a nifti_strlcpy would avoid that. And strlcat(elist[0], extgz, 8) uses a hardcoded 8 rather than sizeof.

Not asking you to rebase across #26 — if it lands first I am happy to do that rebase myself.

@gdevenyi

gdevenyi commented Aug 15, 2026 •

Copy link
Copy Markdown
Collaborator
Closed PR Comment

Followed up on this properly rather than leaving it at "conflicts with #26". I audited every strcpy/strcat call in the tree to work out what the wholesale replacement would actually buy, and the answer surprised me.

Two are genuine defects, and #26 now fixes both.

doPigz()/doPigz2() build a shell command in char command[768]:

strcpy(command, "pigz");
strcat(command, " -n -f > \"");
strcat(command, nim->fname);      /* unbounded */
strcat(command, "\"");

PATH_MAX is 4096, so an ordinary deep path overruns a 768-byte stack array and the result goes to popen(). #11 grows the buffer to 4096, which does not fix it — 4096 is exactly PATH_MAX, and the prefix and quoting push a maximum-length path over. #26 replaces all four calls with one bounded snprintf that refuses to run a truncated command.

znzprintf() had the tree's only unbounded formatted write — vsprintf into a buffer sized strlen(format) + 1000000, with the comment /* overkill I hope */. Now vsnprintf, and the va_list is ended on the allocation-failure path that previously returned without va_end.

The other 145 calls are correct, which is why #26 does not rewrite them:

  • 86 copy into a buffer allocated as strlen(source) + slack a few lines above — the nifti_makehdrname/nifti_makeimgname family and nifti_strdup.
  • 10 write into a fixed array that fits exactly: extcopy[8] receives name + len - 7, the elist[] entries are the char[8] extension buffers whose declaration comment says "(leave space for .gz)", nhdr.magic[4] takes a 3-character literal.
  • The rest are string literals into struct fields many times their length.

Rewriting 145 correct calls is 145 chances to get a length expression wrong, in code whose tests compare output byte for byte. I hit exactly that failure mode earlier in this work: a regex that looked right turned calloc(strlen(basename) + 8, sizeof(char)) into calloc(strlen(basename, sizeof(char)) + 8), and only the binary-comparison test caught it.

So #26 takes a different route to the same goal: _FORTIFY_SOURCE, level chosen by compiling a test rather than checking versions, applied only to optimised builds. The C library then checks the destination size of every one of those calls wherever the compiler can determine it — including the run-time-known strlen(x) + n sizes, which is what level 3 adds and what this codebase needs. I confirmed it catches the doPigz overflow above.

This complements what you are doing rather than replacing it. Fortification catches a bad size at run time; strlcpy and -fbounds-safety make the bound explicit at compile time, which is strictly better where you can get it. If this PR lands, the fortification stays useful.

Two things about the current implementation that would need sorting either way, repeating them here so they are not lost:

  • string_helper.h guards the fallback with #if defined(__GLIBC__) && ..., so on musl, MSVC, or any non-glibc non-Apple libc __GLIBC__ is undefined, the fallback is not compiled, and strlcpy is missing at link time.
  • Defining strlcpy/strlcat at global scope claims identifiers reserved to the implementation, which can collide for downstream consumers. A nifti_strlcpy would avoid that, at the cost of not being a drop-in.

Happy to rebase #26 under this if you would rather land yours first — the two touch different lines apart from the doPigz block and the QSTR macro.

@seanm

seanm commented Aug 15, 2026

Copy link
Copy Markdown
Collaborator Author

@gdevenyi your LLM seems to be unaware that with -fbound-safety strncpy() and strcpy() do not compile at all, and that is why I've changed them to strlcpy (as per the commit message "The old functions can easily overflow buffers but also they are not allowed under -fbounds-safety at all.", which I guess the LLM did not parse. It has missed the point entirely.

Instead of making it redo everything I worked hard to do, could you instead use it to review the correctness of this PR? It seems to think 145 calls were correct, does it think they are still correct after the changes here?

@gdevenyi gdevenyi left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review by Claude Fable with effort high

Thanks for tackling this — the call-site conversions all look correct. I checked each fixed buffer against its declaration: extcopy[8] holds the 7-char extensions, extnii[8] + ".gz" fills exactly 8 with the NUL, magic[4] holds "n+1\0", and the strlen(...)+8 allocations cover extension + ".gz" + NUL. The QSTR macro change correctly adds memset to preserve the zero-padding strncpy used to provide.

The blockers are all in the new string_helper fallback (see line comments):

  1. The platform guard only compiles the fallback on glibc < 2.38, so MSVC/MinGW (no __APPLE__, no __GLIBC__, no strlcpy) get no definition at all and every call fails to link. Suggest check_symbol_exists(strlcpy string.h HAVE_STRLCPY) in CMake instead of enumerating platforms.
  2. string_helper.h tests __GLIBC__ before including any libc header, so the prototypes vanish if the header is included first.
  3. The strlcat fallback is unsafe under NDEBUG in a case where BSD's real strlcat is safe.

Also noting (you already flagged the CMake wiring as unfinished): none of the modified .c files #include "string_helper.h" yet, so on pre-2.38 glibc the calls will be implicit declarations even once the file is compiled. Minor: the new files use tabs, // comments, and camelCase parameter names, which don't match the surrounding codebase.

#ifndef __APPLE__

// libc 2.38 and above provides strlcpy and strlcat, so don't redefine them.
#if defined (__GLIBC__) && ((__GLIBC__ < 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ < 38)))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This guard only provides the fallback when __GLIBC__ is defined and < 2.38. On MSVC/MinGW neither __APPLE__ nor __GLIBC__ is defined, so the whole block preprocesses away — and MSVC has no strlcpy, so every call site fails to link. This repo supports MSVC (there are _MSC_VER branches in doPigz).

Rather than enumerating platforms, detect the symbol in CMake:

include(CheckSymbolExists)
check_symbol_exists(strlcpy string.h HAVE_STRLCPY)

and guard on #ifndef HAVE_STRLCPY. That also handles musl, the BSDs, and future libcs without further edits.

#ifndef __APPLE__

// libc 2.38 and above provides strlcpy and strlcat, so don't redefine them.
#if defined (__GLIBC__) && ((__GLIBC__ < 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ < 38)))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

__GLIBC__ is only defined after a libc header has been included. If a .c file includes string_helper.h before <string.h>, this check sees __GLIBC__ undefined and the prototypes vanish even on old glibc. Add #include <string.h> at the top of this header, before the version check (or better, switch to a CMake HAVE_STRLCPY guard as suggested in the .c file).

Comment thread string_helper/string_helper.h Outdated

#include <stddef.h>

size_t strlcpy(char* restrict ioDestination, const char* restrict inSource, size_t inDestinationSize);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

restrict is not a keyword in C++, and there's no extern "C" guard, so any C++ consumer (e.g. ITK) that includes this header will fail to compile. Wrap the declarations in extern "C" and hide restrict behind #ifdef __cplusplus.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just removed restrict

assert(destinationLength < inDestinationSize);

ioDestination += destinationLength;
inDestinationSize -= destinationLength;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the destination is not NUL-terminated within inDestinationSize, the assert on line 41 is compiled out under NDEBUG, and this subtraction underflows to a huge value. The truncation branch below is then skipped and the memcpy writes past the buffer. OpenBSD's strlcat handles this case safely by returning size + strlen(src) without writing:

if (destinationLength >= inDestinationSize)
    return inDestinationSize + sourceLength;

All call sites in this PR are fine today, but a safety shim that can overflow where the real strlcat cannot defeats the purpose.

Comment thread niftilib/nifti1_io.c Outdated
strcat(command, "\"");
strlcpy(command, "pigz", sizeof(command));
strlcat(command, " -n -f > \"", sizeof(command));
strlcat(command, nim->fname, sizeof(command));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Behavior change worth handling: the old strcat overflowed on a very long fname (~750+ chars); strlcat now silently truncates instead, which drops the closing quote and hands pigz a mangled command. Since strlcat returns the total length it tried to create, check it against sizeof(command) and fail (return -1) on truncation. Applies to all four copies (doPigz/doPigz2 in both nifti1_io.c and nifti2_io.c).

Comment thread niftilib/nifti1_io.c Outdated
strcat(elist[0], extgz); strcat(elist[1], extgz); strcat(elist[2], extgz);
strlcat(elist[0], extgz, 8);
strlcat(elist[1], extgz, 8);
strlcat(elist[2], extgz, 8);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The hardcoded 8 is correct today (extnii[8] + ".gz" fills it exactly), but sizeof(extnii) / sizeof(exthdr) / sizeof(extimg) would stay correct if the buffers ever change. Same in the nifti2_io.c copy.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

This was referenced Aug 15, 2026
@hjmjohnson

Copy link
Copy Markdown
Member

Rebased onto current master. The conflict was semantic rather than mechanical, and two structural issues turned up while resolving it — neither is a rebase artifact, both predate it.

Blocking: string_helper/ is never compiled. No CMakeLists.txt references it and no source #includes it, so on any platform lacking a native strlcpy the seven files that now call it have neither a declaration nor a definition.

1. The conflict: this branch reintroduced a use-after-free that #54 fixed

nifti_findhdrname's FSLSTYLE block was rewritten by #54 (merged) to fix a read-after-free: basename is read by the ambiguous-name fprintf, so it cannot be freed before it. This branch's version frees it first.

Resolved by combining both sides — this branch's strlcpy/strlcat with the gznamelength variable, on top of #54's memory semantics: basename freed only after the fprintf, gzname's allocation checked, every exit path releasing what it holds, and return NULL rather than exit(134).

2. string_helper is dead code, and its guards exclude the platforms that need it
$ grep -rn string_helper --include=CMakeLists.txt --include='*.cmake' .   # -> nothing
$ grep -rn 'include.*string_helper' --include='*.c' --include='*.h' .     # -> nothing

The build confirms it: a full ninja run never compiles string_helper.c.

It currently builds green everywhere CI runs only because every one of those platforms already has strlcpy in libc — Apple and BSD natively, and Ubuntu 24.04 at glibc 2.39, which is past the 2.38 cutoff the header tests for. The fallback has never been exercised.

The guards are also inverted relative to the commit message. Both files wrap their contents in:

#ifndef __APPLE__
#if defined (__GLIBC__) && ((__GLIBC__ < 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ < 38)))

The inner test requires __GLIBC__ to be defined, so on the platforms with no strlcpy at all (musl / MSVC / MinGW / Solaris) both the declaration and the definition compile away to nothing:

$ cc -E -U__APPLE__ -I string_helper probe.c | grep -E 'strlcpy|strlcat'
(nothing)

Result on those targets is an implicit declaration, which is an error under C99 and later with current compilers, or a link failure.

3. Defining strlcpy/strlcat at global scope in a vendored library

Worth a decision before this lands rather than after. This library is vendored into ITK, AFNI, FSL, dcm2niix, and Slicer. Defining strlcpy and strlcat as ordinary external symbols means a consumer that also carries its own fallback gets a duplicate-symbol link error, and one that compiles against a glibc newer than the one it runs on gets two different definitions of the same name.

A file-local name such as nifti_strlcpy, or static definitions in a header, avoids both and costs nothing at the call sites.

restrict in the signatures is also C99, so it needs checking against the oldest-standard CI leg.

Verification
Build Result
Apple, Release, Ninja 0 warnings, 344/344 tests

Confirms only that the conflict resolution is sound on a platform with native strlcpy. It does not exercise the fallback, which nothing currently does.

@hjmjohnson

Copy link
Copy Markdown
Member

Re-rebased onto current master (b4876bf) and both commit messages reworded. No code changed.

Still blocking, unchanged since the previous review: string_helper/ is never compiled — no CMakeLists.txt references it and no source #includes it — so on any platform lacking a native strlcpy the call sites have neither a declaration nor a definition. I re-verified all of it against today's tree rather than trusting the earlier note.

Rebase

master's last 44 commits were rewritten on 2026-09-22 (messages only, trees byte-identical), so this branch's base no longer existed and GitHub reported it CONFLICTING again. Rebased with git rebase --onto master ce0af45^; both commits applied without conflict this time — the nifti_findhdrname use-after-free resolution from the previous round is already in the branch and survived intact (basename is still freed only after the ambiguous-name fprintf, gzname's allocation is still checked, every exit path still releases what it holds, and it still returns NULL rather than terminating).

diff <(git diff master HEAD) <(git diff ce0af45^ 460ba38) differs only in blob hashes and in context lines that moved because doPigz/doPigz2 gained static on master. The content delta is unchanged.

Commit messages

Both subjects were bare sentences; they now carry ENH: and are wrapped to 78/72, with the strncpy zero-fill caveat kept because it is the one thing a reader has to know. Author and author date preserved. Nothing was stripped — neither commit carried a tool trailer or a transient URL. British behaviour in the original body is now US spelling.

Blocker 1 — string_helper is still dead code (re-verified today)
$ grep -rn string_helper --include=CMakeLists.txt --include='*.cmake' .   # 0 hits
$ grep -rn string_helper --include='*.c' --include='*.h' . | grep -v ^./string_helper/   # 0 hits

A full ninja run still never compiles string_helper.c. It builds green everywhere CI runs only because every one of those platforms already has strlcpy in libc — Apple and the BSDs natively, Ubuntu 24.04 at glibc 2.39, past the 2.38 cutoff the header tests for. The fallback has never been exercised on any machine.

Blocker 2 — the guards exclude exactly the platforms that need the fallback

Both files wrap their contents in:

#ifndef __APPLE__
#if defined (__GLIBC__) && ((__GLIBC__ < 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ < 38)))

The inner test requires __GLIBC__ to be defined, so on the targets with no strlcpy at all — musl, MSVC, MinGW, Solaris — both the declaration and the definition compile away to nothing. Reproduced on this tree:

$ printf '#include "string_helper.h"\n' > probe.c
$ cc -E -U__APPLE__ -I string_helper probe.c | grep -cE 'strlcpy|strlcat'
0

The result on those targets is an implicit declaration — an error with current compilers at C99 and later — or a link failure.

string_helper.h also has no include guard and no #pragma once.

Blocker 3 — defining strlcpy/strlcat at global scope in a vendored library

Unresolved, and it wants a decision rather than a patch from me. This library is vendored into ITK, AFNI, FSL, dcm2niix, and Slicer. Defining strlcpy and strlcat as ordinary external symbols means a consumer that carries its own fallback gets a duplicate-symbol link error, and one compiled against a newer glibc than it runs on gets two different definitions of one name.

A file-local name such as nifti_strlcpy, or static inline definitions in the header, avoids both and costs nothing at the call sites. restrict in the signatures is C99 and needs checking against the oldest-standard CI leg. The sources are also tab-indented where the rest of the tree uses spaces.

I have deliberately not redesigned this — the choice of spelling is the author's and the maintainer's.

Test coverage — and why I added none

The conversion itself is BEHAVIORAL in principle: strncpy zero-fills the destination and strlcpy does not, and strncpy may leave the destination unterminated where strlcpy always terminates. But the whole point of the change is that every converted call site is one where the old and new forms agree on well-formed input, so a test over the existing fixtures passes identically before and after — worthless as a red-green proof. Making one differ means constructing an input that overflows a fixed header field, which is the MEMORY class and belongs under a sanitizer build against a hand-built malformed header, not against the current fixtures. NOT-DEMONSTRABLE as the branch stands.

The string_helper implementations themselves are the one genuinely testable piece here — a unit test over strlcpy/strlcat truncation and return values would be worth having — but writing it is blocked on blockers 1 and 2, since there is currently no build in which that code is compiled at all.

Build and test

macOS/arm64, Ninja, Release, -DNIFTI_BUILD_APPLICATIONS=ON -DUSE_NIFTI2_CODE=ON -DUSE_CIFTI_CODE=ON -DUSE_FSL_CODE=ON: builds clean, 100% tests passed, 0 tests failed out of 362. This exercises the Apple path, i.e. the system strlcpy, and says nothing about the fallback.

@gdevenyi gdevenyi left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review by Google Carbon

Verdict: Request Changes (WIP Draft)

Reviewed the branch history and the bounds-safety / warning-cleanup changes in detail:

  1. Branch topology (75 orphaned commits): Only the top 2 commits (7569506 and 129a637) belong to this PR; the 75 commits beneath them come from pre-reset master history overlapping #90, #92, #101, #106, #108, #111, #127, etc. Please cherry-pick only the 2 strlcpy/strlcat commits onto current master.
  2. Critical buffer overread & SIZE_MAX heap/stack overflow in string_helper/string_helper.c (strlcat):
    • strlen(ioDestination) reads past inDestinationSize if ioDestination is not NUL-terminated within the bound (standard strlcat uses strnlen(ioDestination, inDestinationSize)).
    • Worse, in Release builds (-DNDEBUG), assert(destinationLength < inDestinationSize) compiles out: when destinationLength >= inDestinationSize (including valid strlcat(dst, src, 0) size queries!), inDestinationSize - 1 underflows unsigned size_t to SIZE_MAX and executes memcpy(ioDestination, inSource, SIZE_MAX)!
  3. Broken platform/C11 feature guards, missing CMake wiring, and C11 reserved-identifier / symbol collisions:
    • #if defined(__GLIBC__) excludes Windows/MSVC (causing the LNK2019 CI failures), MinGW, musl, Solaris, etc. Furthermore, under master's -std=c11 (CMAKE_C_EXTENSIONS OFF) and nifti1_io.c's #define _POSIX_C_SOURCE 200809L, <string.h> hides strlcpy/strlcat on both glibc >= 2.38 and macOS (_DARWIN_C_SOURCE is suppressed by _POSIX_C_SOURCE)!
    • string_helper.c is not added to any CMakeLists.txt, "string_helper.h" is never #included, and exporting global strlcpy/strlcat violates C11 §7.31.13 (identifiers starting with str + lowercase letter are reserved for <string.h>) and causes duplicate-symbol errors when statically linking libniftiio + libnifti2 + libnifticdf.
    • Recommended design: Replace string_helper.c with a private header-only static inline size_t nifti_strlcpy(...) / nifti_strlcat(...) helper — zero symbol collisions, zero CMake target plumbing, and identical behavior on every platform/libc.
  4. Call-site bugs: Silent command truncation before popen() in doPigz, unchecked nifti_makebasename / calloc before strlen / strlcpy, signed char UB in toupper(*upt), and dropped zero-padding in fill_field (fp->name).

inDestinationSize -= destinationLength;
if (sourceLength >= inDestinationSize)
{
sourceLength = inDestinationSize - 1;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Google Carbon] Critical SIZE_MAX buffer overflow in Release (-DNDEBUG) builds:

  1. Line 37 calls strlen(ioDestination) instead of strnlen(ioDestination, inDestinationSize), overreading un-terminated buffers.
  2. When -DNDEBUG disables line 41's assert(destinationLength < inDestinationSize) — e.g. on strlcat(dst, src, 0) or an already-full buffer where destinationLength == inDestinationSize — inDestinationSize becomes 0 at line 44, so inDestinationSize - 1 wraps to SIZE_MAX and line 49 runs memcpy(ioDestination, inSource, SIZE_MAX)!

If destinationLength == inDestinationSize (using strnlen), strlcat must immediately return inDestinationSize + sourceLength; without writing a NUL byte.

#ifndef __APPLE__

// libc 2.38 and above provides strlcpy and strlcat, so don't redefine them.
#if defined (__GLIBC__) && ((__GLIBC__ < 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ < 38)))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Google Carbon] Platform & standard-library visibility issues:

  • #if defined(__GLIBC__) leaves Windows MSVC (LNK2019), MinGW, and musl Linux without declarations or definitions.
  • Under master's strict C11 mode (-std=c11, CMAKE_C_EXTENSIONS=OFF) plus #define _POSIX_C_SOURCE 200809L in nifti1_io.c/nifti2_io.c, system <string.h> hides strlcpy/strlcat on both glibc >= 2.38 (_DEFAULT_SOURCE required) and Apple (_POSIX_C_SOURCE disables _DARWIN_C_SOURCE).
  • Defining external strlcpy/strlcat violates C11 §7.31.13 reserved str[a-z]* identifiers and will collide at link time across libniftiio, libnifti2, and libnifticdf.

Defining static inline size_t nifti_strlcpy(...) and static inline size_t nifti_strlcat(...) in an internal header avoids all libc feature-test macro pitfalls and symbol collisions.

Comment thread niftilib/nifti1_io.c
basename = nifti_makebasename(fname);
imgname = (char *)calloc(sizeof(char),strlen(basename)+8);
basename = nifti_makebasename(fname);
size_t imgnamelength = strlen(basename)+8;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Google Carbon] nifti_makebasename(fname) returns NULL on allocation failure, so strlen(basename) dereferences NULL; likewise imgname = calloc(...) on line 2909 is unchecked before strlcpy(imgname, ...) (assert(ioDestination) / memcpy NULL deref). Also note calloc(sizeof(char), imgnamelength) has transposed arguments (-Wcalloc-transposed-args on GCC >= 14; should be calloc(imgnamelength, sizeof(char))).

Comment thread niftilib/nifti1_io.c
strlcpy(command, "pigz", sizeof(command));
strlcat(command, " -n -f > \"", sizeof(command));
strlcat(command, nim->fname, sizeof(command));
strlcat(command, "\"", sizeof(command));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Google Carbon] Replacing strcpy/strcat with unchecked strlcat on a shell command passed to popen(command, "w") turns long nim->fname (>= 754 bytes) into silent path truncation with a missing closing quote ", invoking /bin/sh -c on a broken or unintended filename! Use int n = snprintf(command, sizeof(command), "pigz -n -f > \"%s\"", nim->fname); if (n < 0 || (size_t)n >= sizeof(command)) return -1; instead (and same in nifti2/nifti2_io.c).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

Comment thread niftilib/nifti1_test.c
tmpstr = nifti_makebasename(argv[iarg]);
nim->fname = (char *)calloc(1,ll+8) ; strcpy(nim->fname,tmpstr) ;
nim->iname = (char *)calloc(1,ll+8) ; strcpy(nim->iname,tmpstr) ;
nim->fname = (char *)calloc(1,ll) ; strlcpy(nim->fname, tmpstr, ll) ;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Google Carbon] Neither tmpstr (from nifti_makebasename) nor nim->fname / nim->iname (from calloc) is checked for NULL before strlcpy.

Comment thread nifticdf/nifticdf.c Outdated
return -1 ;
strlcpy(unam,name,size);
for( char *upt=unam ; *upt != '\0' ; upt++ )
*upt = (char)toupper(*upt) ;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Google Carbon] Passing a plain char (*upt) directly to toupper() is undefined behavior in C11 (§7.4) when char is signed and *upt < 0 (non-ASCII bytes). Cast to unsigned char first: *upt = (char)toupper((unsigned char)*upt);.

Comment thread niftilib/nifti1_tool.c

strncpy(fp->name, name, sizeof(fp->name));
fp->name[sizeof(fp->name) - 1] = 0;
strlcpy(fp->name, name, sizeof(fp->name));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Google Carbon] Note subtle behavioral change: strncpy(fp->name, name, NT_FIELD_NAME_LEN - 1) previously zero-padded the entire fp->name array, whereas strlcpy only writes a single NUL terminator, leaving trailing bytes of fp->name uninitialized if an external caller passes an unzeroed field_s struct (and nifti2/nifti_tool.c's fill_field should stay synchronized).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

On macOS at least, this makes strlcpy() unavailable since it's not part of POSIX.
The old functions can easily overflow buffers but also they are not allowed under -fbounds-safety at all.

Most cases were trivial.

strncpy() notably zeros the whole buffer, while strlcpy() does not. I examined each case carefully and in most cases calloc() was used previously meaning the buffer was already zeroed. In one case, added a memset(0) to preserve the behaviour, those I'm not sure it really is necessary.

In a few cases, too the opportunity to better move variable declaration to first usage or otherwise refactor a little bit.
strlcpy and strlcat came from OpenBSD and have since been added to other BSDs, macOS (and variants), and glibc (though only since 2.38). Add implementations for other platforms.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants