Skip to content

Commit d6315a2

Browse files
authored
[clang][BufferUsage] Fix a StringRef lifetime issue (#159109)
The code before assigned the `std::string` returned from `tryEvaluateString()` to the `StringRef`, but it was possible that the underlying data of that string vanished in the meantime, passing invalid stack memory to `ParsePrintfString`. Fix this by using two different code paths for the `getCharByteWidth() == 1` case and the `tryEvaluateString()` one.
1 parent 1c2d7b3 commit d6315a2

File tree

1 file changed

+13
-13
lines changed

1 file changed

+13
-13
lines changed

clang/lib/Analysis/UnsafeBufferUsage.cpp

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -900,22 +900,22 @@ static bool hasUnsafeFormatOrSArg(const CallExpr *Call, const Expr *&UnsafeArg,
900900
const Expr *Fmt = Call->getArg(FmtArgIdx);
901901

902902
if (auto *SL = dyn_cast<clang::StringLiteral>(Fmt->IgnoreParenImpCasts())) {
903-
StringRef FmtStr;
903+
if (SL->getCharByteWidth() == 1) {
904+
StringRef FmtStr = SL->getString();
905+
StringFormatStringHandler Handler(Call, FmtArgIdx, UnsafeArg, Ctx);
904906

905-
if (SL->getCharByteWidth() == 1)
906-
FmtStr = SL->getString();
907-
else if (auto EvaledFmtStr = SL->tryEvaluateString(Ctx))
908-
FmtStr = *EvaledFmtStr;
909-
else
910-
goto CHECK_UNSAFE_PTR;
911-
912-
StringFormatStringHandler Handler(Call, FmtArgIdx, UnsafeArg, Ctx);
907+
return analyze_format_string::ParsePrintfString(
908+
Handler, FmtStr.begin(), FmtStr.end(), Ctx.getLangOpts(),
909+
Ctx.getTargetInfo(), isKprintf);
910+
}
913911

914-
return analyze_format_string::ParsePrintfString(
915-
Handler, FmtStr.begin(), FmtStr.end(), Ctx.getLangOpts(),
916-
Ctx.getTargetInfo(), isKprintf);
912+
if (auto FmtStr = SL->tryEvaluateString(Ctx)) {
913+
StringFormatStringHandler Handler(Call, FmtArgIdx, UnsafeArg, Ctx);
914+
return analyze_format_string::ParsePrintfString(
915+
Handler, FmtStr->data(), FmtStr->data() + FmtStr->size(),
916+
Ctx.getLangOpts(), Ctx.getTargetInfo(), isKprintf);
917+
}
917918
}
918-
CHECK_UNSAFE_PTR:
919919
// If format is not a string literal, we cannot analyze the format string.
920920
// In this case, this call is considered unsafe if at least one argument
921921
// (including the format argument) is unsafe pointer.

0 commit comments

Comments
 (0)