Skip to content

[analyzer] Fix StreamChecker crash in fread modeling #108393

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

Merged
merged 2 commits into from
Sep 12, 2024
Merged
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
2 changes: 1 addition & 1 deletion clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1129,7 +1129,7 @@ tryToInvalidateFReadBufferByElements(ProgramStateRef State, CheckerContext &C,
if (!ElemTy.isNull() && CountVal && Size && StartIndexVal) {
int64_t NumBytesRead = Size.value() * CountVal.value();
int64_t ElemSizeInChars = Ctx.getTypeSizeInChars(ElemTy).getQuantity();
if (ElemSizeInChars == 0)
if (ElemSizeInChars == 0 || NumBytesRead < 0)
return nullptr;

bool IncompleteLastElement = (NumBytesRead % ElemSizeInChars) != 0;
Expand Down
30 changes: 30 additions & 0 deletions clang/test/Analysis/fread.c
Original file line number Diff line number Diff line change
Expand Up @@ -443,3 +443,33 @@ void test_unaligned_start_read(void) {
fclose(fp);
}
}

void no_crash_if_count_is_negative(long l, long r, unsigned char *buffer) {
FILE *fp = fopen("path", "r");
if (fp) {
if (l * r == -1) {
fread(buffer, 1, l * r, fp); // no-crash
}
fclose(fp);
}
}

void no_crash_if_size_is_negative(long l, long r, unsigned char *buffer) {
FILE *fp = fopen("path", "r");
if (fp) {
if (l * r == -1) {
fread(buffer, l * r, 1, fp); // no-crash
}
fclose(fp);
}
}

void no_crash_if_size_and_count_are_negative(long l, long r, unsigned char *buffer) {
FILE *fp = fopen("path", "r");
if (fp) {
if (l * r == -1) {
fread(buffer, l * r, l * r, fp); // no-crash
}
fclose(fp);
}
}
Loading