Skip to content

Commit 5965fbf

Browse files
committed
[clang-tidy] Fix a crash in bugprone-not-null-terminated-result check when __STDC_WANT_LIB_EXT1__ was undefined after definition.
PP->getMacroInfo() returns nullptr for undefined macro, so we need to check this return value before dereference. 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) #2 0x0000000002183ff3 SignalHandler(int) (/llvm-project/build/bin/clang-tidy+0x2183ff3) #3 0x00007f37df9b1390 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x11390) #4 0x000000000052054e clang::tidy::bugprone::NotNullTerminatedResultCheck::check(clang::ast_matchers::MatchFinder::MatchResult const&) (/llvm-project/build/bin/clang-tidy+0x52054e) ``` Reviewed By: hokein Differential Revision: https://reviews.llvm.org/D85523
1 parent 626d0f5 commit 5965fbf

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed

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

+8-5
Original file line numberDiff line numberDiff line change
@@ -802,11 +802,14 @@ void NotNullTerminatedResultCheck::check(
802802
while (It != PP->macro_end() && !AreSafeFunctionsWanted.hasValue()) {
803803
if (It->first->getName() == "__STDC_WANT_LIB_EXT1__") {
804804
const auto *MI = PP->getMacroInfo(It->first);
805-
const auto &T = MI->tokens().back();
806-
StringRef ValueStr = StringRef(T.getLiteralData(), T.getLength());
807-
llvm::APInt IntValue;
808-
ValueStr.getAsInteger(10, IntValue);
809-
AreSafeFunctionsWanted = IntValue.getZExtValue();
805+
// PP->getMacroInfo() returns nullptr if macro has no definition.
806+
if (MI) {
807+
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();
812+
}
810813
}
811814

812815
++It;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
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__ 1
8+
#undef __STDC_WANT_LIB_EXT1__
9+
10+
void f(const char *src) {
11+
char dest[13];
12+
memcpy_s(dest, 13, src, strlen(src) - 1);
13+
// CHECK-MESSAGES: :[[@LINE-1]]:3: warning: the result from calling 'memcpy_s' is not null-terminated [bugprone-not-null-terminated-result]
14+
// CHECK-FIXES: char dest[14];
15+
// CHECK-FIXES-NEXT: strncpy_s(dest, 14, src, strlen(src) - 1);
16+
}
17+

0 commit comments

Comments
 (0)