Skip to content

Commit

Permalink
Fix unchecked optional access in compile subcommand (#4756)
Browse files Browse the repository at this point in the history
Hi,

I fixed a small issue that I found inside the "compile subcommand"
component:
The program can be crashed by running ```bazel run -- toolchain:carbon
compile --dump-mem-usage "non-existing-file.carbon"``` - i.e. by
activating the memory usage dump flag and passing a non-existing file.

Best regards,
oz
  • Loading branch information
ottmar-zittlau authored Jan 8, 2025
1 parent 13c121c commit 7ed3b98
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
11 changes: 7 additions & 4 deletions toolchain/driver/compile_subcommand.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -369,14 +369,17 @@ class CompilationUnit {
source_ = SourceBuffer::MakeFromFileOrStdin(*driver_env_->fs,
input_filename_, *consumer_);
});
if (mem_usage_) {
mem_usage_->Add("source_", source_->text().size(),
source_->text().size());
}

if (!source_) {
success_ = false;
return;
}

if (mem_usage_) {
mem_usage_->Add("source_", source_->text().size(),
source_->text().size());
}

CARBON_VLOG("*** SourceBuffer ***\n```\n{0}\n```\n", source_->text());

LogCall("Lex::Lex", "lex",
Expand Down
11 changes: 11 additions & 0 deletions toolchain/driver/driver_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,17 @@ TEST_F(DriverTest, CompileCommandErrors) {
StrEq("error: not all required positional arguments were provided; first "
"missing and required positional argument: `FILE`\n"));

// Pass non-existing file
EXPECT_FALSE(driver_
.RunCommand({"compile", "--dump-mem-usage",
"non-existing-file.carbon"})
.success);
EXPECT_THAT(
test_error_stream_.TakeStr(),
ContainsRegex("No such file or directory[\\n]*non-existing-file.carbon"));
// Flush output stream, because it's ok that it's not empty here.
test_output_stream_.TakeStr();

// Invalid output filename. No reliably error message here.
// TODO: Likely want a different filename on Windows.
auto empty_file = MakeTestFile("");
Expand Down

0 comments on commit 7ed3b98

Please sign in to comment.