Skip to content

Commit dcb8d3b

Browse files
committed
[clang-tidy] Fix a crash in bugprone-not-null-terminated-result check when __STDC_WANT_LIB_EXT1__ is not a literal.
If `__STDC_WANT_LIB_EXT1__` is not a literal (e.g. `#define __STDC_WANT_LIB_EXT1__ ((unsigned)1)`) bugprone-not-null-terminated-result check crashes. Stack dump: ``` #0 0x0000000002185e6a llvm::sys::PrintStackTrace(llvm::raw_ostream&) (/llvm-project/build/bin/clang-tidy+0x2185e6a) #1 0x0000000002183e8c llvm::sys::RunSignalHandlers() (/llvm-project/build/bin/clang-tidy+0x2183e8c) rust-lang#2 0x0000000002183ff3 SignalHandler(int) (/llvm-project/build/bin/clang-tidy+0x2183ff3) rust-lang#3 0x00007f08d91b1390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390) rust-lang#4 0x00000000021338bb llvm::StringRef::getAsInteger(unsigned int, llvm::APInt&) const (/llvm-project/build/bin/clang-tidy+0x21338bb) rust-lang#5 0x000000000052051c clang::tidy::bugprone::NotNullTerminatedResultCheck::check(clang::ast_matchers::MatchFinder::MatchResult const&) (/llvm-project/build/bin/clang-tidy+0x52051c) ``` Reviewed By: hokein Differential Revision: https://reviews.llvm.org/D85525
1 parent bebca66 commit dcb8d3b

File tree

2 files changed

+22
-4
lines changed

2 files changed

+22
-4
lines changed

clang-tools-extra/clang-tidy/bugprone/NotNullTerminatedResultCheck.cpp

+6-4
Original file line numberDiff line numberDiff line change
@@ -805,10 +805,12 @@ void NotNullTerminatedResultCheck::check(
805805
// PP->getMacroInfo() returns nullptr if macro has no definition.
806806
if (MI) {
807807
const auto &T = MI->tokens().back();
808-
StringRef ValueStr = StringRef(T.getLiteralData(), T.getLength());
809-
llvm::APInt IntValue;
810-
ValueStr.getAsInteger(10, IntValue);
811-
AreSafeFunctionsWanted = IntValue.getZExtValue();
808+
if (T.isLiteral() && T.getLiteralData()) {
809+
StringRef ValueStr = StringRef(T.getLiteralData(), T.getLength());
810+
llvm::APInt IntValue;
811+
ValueStr.getAsInteger(10, IntValue);
812+
AreSafeFunctionsWanted = IntValue.getZExtValue();
813+
}
812814
}
813815
}
814816

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// RUN: %check_clang_tidy %s bugprone-not-null-terminated-result %t -- \
2+
// RUN: -- -std=c11 -I %S/Inputs/bugprone-not-null-terminated-result
3+
4+
#include "not-null-terminated-result-c.h"
5+
6+
#define __STDC_LIB_EXT1__ 1
7+
#define __STDC_WANT_LIB_EXT1__ ((unsigned)1)
8+
9+
void f(const char *src) {
10+
char dest[13];
11+
memcpy_s(dest, 13, src, strlen(src) - 1);
12+
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: the result from calling 'memcpy_s' is not null-terminated [bugprone-not-null-terminated-result]
13+
// CHECK-FIXES: char dest[14];
14+
// CHECK-FIXES-NEXT: strncpy_s(dest, 14, src, strlen(src) - 1);
15+
}
16+

0 commit comments

Comments
 (0)