Skip to content

[-Wunsafe-buffer-usage] Support safe patterns of "%.*s" in printf functions #145862

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 74 additions & 15 deletions clang/lib/Analysis/UnsafeBufferUsage.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
#include "clang/Basic/SourceLocation.h"
#include "clang/Lex/Lexer.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/STLFunctionalExtras.h"
#include "llvm/ADT/SmallSet.h"
Expand Down Expand Up @@ -809,28 +810,86 @@ static bool hasUnsafeFormatOrSArg(const CallExpr *Call, const Expr *&UnsafeArg,
const CallExpr *Call;
unsigned FmtArgIdx;
const Expr *&UnsafeArg;
ASTContext &Ctx;

// Returns an `Expr` representing the precision if specified, null
// otherwise.
// The parameter `Call` is a printf call and the parameter `Precision` is
// the precision of a format specifier of the `Call`.
//
// For example, for the `printf("%d, %.10s", 10, p)` call
// `Precision` can be the precision of either "%d" or "%.10s". The former
// one will have `NotSpecified` kind.
const Expr *
getPrecisionAsExpr(const analyze_printf::OptionalAmount &Precision,
const CallExpr *Call) {
unsigned PArgIdx = -1;

if (Precision.hasDataArgument())
PArgIdx = Precision.getPositionalArgIndex() + FmtArgIdx;
if (0 < PArgIdx && PArgIdx < Call->getNumArgs()) {
const Expr *PArg = Call->getArg(PArgIdx);

// Strip the cast if `PArg` is a cast-to-int expression:
if (auto *CE = dyn_cast<CastExpr>(PArg);
CE && CE->getType()->isSignedIntegerType())
PArg = CE->getSubExpr();
return PArg;
}
if (Precision.getHowSpecified() ==
analyze_printf::OptionalAmount::HowSpecified::Constant) {
auto SizeTy = Ctx.getSizeType();
llvm::APSInt PArgVal = llvm::APSInt(
llvm::APInt(Ctx.getTypeSize(SizeTy), Precision.getConstantAmount()),
true);

return IntegerLiteral::Create(Ctx, PArgVal, Ctx.getSizeType(), {});
}
return nullptr;
}

public:
StringFormatStringHandler(const CallExpr *Call, unsigned FmtArgIdx,
const Expr *&UnsafeArg)
: Call(Call), FmtArgIdx(FmtArgIdx), UnsafeArg(UnsafeArg) {}
const Expr *&UnsafeArg, ASTContext &Ctx)
: Call(Call), FmtArgIdx(FmtArgIdx), UnsafeArg(UnsafeArg), Ctx(Ctx) {}

bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
const char *startSpecifier,
unsigned specifierLen,
const TargetInfo &Target) override {
if (FS.getConversionSpecifier().getKind() ==
analyze_printf::PrintfConversionSpecifier::sArg) {
unsigned ArgIdx = FS.getPositionalArgIndex() + FmtArgIdx;

if (0 < ArgIdx && ArgIdx < Call->getNumArgs())
if (!isNullTermPointer(Call->getArg(ArgIdx))) {
UnsafeArg = Call->getArg(ArgIdx); // output
// returning false stops parsing immediately
return false;
}
}
return true; // continue parsing
if (FS.getConversionSpecifier().getKind() !=
analyze_printf::PrintfConversionSpecifier::sArg)
return true; // continue parsing

unsigned ArgIdx = FS.getPositionalArgIndex() + FmtArgIdx;

if (!(0 < ArgIdx && ArgIdx < Call->getNumArgs()))
// If the `ArgIdx` is invalid, give up.
return true; // continue parsing

const Expr *Arg = Call->getArg(ArgIdx);

if (isNullTermPointer(Arg))
// If Arg is a null-terminated pointer, it is safe anyway.
return true; // continue parsing

// Otherwise, check if the specifier has a precision and if the character
// pointer is safely bound by the precision:
auto LengthModifier = FS.getLengthModifier();
QualType ArgType = Arg->getType();
bool IsArgTypeValid = // Is ArgType a character pointer type?
ArgType->isPointerType() &&
(LengthModifier.getKind() == LengthModifier.AsWideChar
? ArgType->getPointeeType()->isWideCharType()
: ArgType->getPointeeType()->isCharType());

if (auto *Precision = getPrecisionAsExpr(FS.getPrecision(), Call);
Copy link
Contributor

Choose a reason for hiding this comment

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

Nice! Haven't seen the if condition with initializer so far, makes for a cleaner code. Is this coding style allowed in LLVM code base?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I learned this from an upstream reviewer, so I think it conforms to LLVM's coding style.

Precision && IsArgTypeValid)
if (isPtrBufferSafe(Arg, Precision, Ctx))
return true;
// Handle unsafe case:
UnsafeArg = Call->getArg(ArgIdx); // output
return false; // returning false stops parsing immediately
}
};

Expand All @@ -846,7 +905,7 @@ static bool hasUnsafeFormatOrSArg(const CallExpr *Call, const Expr *&UnsafeArg,
else
goto CHECK_UNSAFE_PTR;

StringFormatStringHandler Handler(Call, FmtArgIdx, UnsafeArg);
StringFormatStringHandler Handler(Call, FmtArgIdx, UnsafeArg, Ctx);

return analyze_format_string::ParsePrintfString(
Handler, FmtStr.begin(), FmtStr.end(), Ctx.getLangOpts(),
Expand Down
36 changes: 36 additions & 0 deletions clang/test/SemaCXX/warn-unsafe-buffer-usage-libc-functions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,24 @@ namespace std {
T *c_str();
T *data();
unsigned size_bytes();
unsigned size();
};

typedef basic_string<char> string;
typedef basic_string<wchar_t> wstring;

template<typename T>
struct basic_string_view {
T *c_str() const noexcept;
T *data() const noexcept;
unsigned size();
const T* begin() const noexcept;
const T* end() const noexcept;
};

typedef basic_string_view<char> string_view;
typedef basic_string_view<wchar_t> wstring_view;

// C function under std:
void memcpy();
void strcpy();
Expand Down Expand Up @@ -134,6 +147,29 @@ void safe_examples(std::string s1, int *p) {
snprintf(nullptr, 0, "%s%d%s%p%s", __PRETTY_FUNCTION__, *p, "hello", s1.c_str()); // no warn
}

void test_sarg_precision(std::string Str, std::string_view Sv, std::wstring_view WSv,
std::span<char> SpC, std::span<int> SpI) {
printf("%.*s");
printf("%.*s", (int)Str.size(), Str.data());
printf("%.*s", (int)Str.size_bytes(), Str.data());
printf("%.*s", (int)Sv.size(), Sv.data());
printf("%.*s", (int)SpC.size(), SpC.data());
printf("%.*s", SpC.size(), SpC.data());
printf("%.*ls", WSv.size(), WSv.data());
printf("%.*s", SpC.data()); // no warn because `SpC.data()` is passed to the precision while the actually string pointer is not given

printf("%.*s", SpI.size(), SpI.data()); // expected-warning {{function 'printf' is unsafe}} expected-note{{string argument is not guaranteed to be null-terminated}}
printf("%.*s", SpI.size(), SpC.data()); // expected-warning {{function 'printf' is unsafe}} expected-note{{string argument is not guaranteed to be null-terminated}}
printf("%.*s", WSv.size(), WSv.data()); // expected-warning {{function 'printf' is unsafe}} expected-note{{string argument is not guaranteed to be null-terminated}}

char a[10];
int b[10];

printf("%.10s", a);
printf("%.11s", a); // expected-warning {{function 'printf' is unsafe}} expected-note{{string argument is not guaranteed to be null-terminated}}
printf("%.10s", b); // expected-warning {{function 'printf' is unsafe}} expected-note{{string argument is not guaranteed to be null-terminated}}
}


void g(char *begin, char *end, char *p, std::span<char> s) {
std::copy(begin, end, p); // no warn
Expand Down
Loading