[flang] Fix crash from empty -DMACRO= (bug #64837)

Some vector indexing code in the preprocessor fails with empty
tokens or token sequences in predefined macros.

Fixes https://github.com/llvm/llvm-project/issues/64837.

Differential Revision: https://reviews.llvm.org/D158451
This commit is contained in:
Peter Klausler 2023-08-21 13:24:27 -07:00
parent adaf545a50
commit d40e6005db
No known key found for this signature in database
3 changed files with 23 additions and 11 deletions

View File

@ -296,8 +296,9 @@ std::optional<TokenSequence> Preprocessor::MacroReplacement(
if (!def->isFunctionLike()) { if (!def->isFunctionLike()) {
bool isRenaming{false}; bool isRenaming{false};
if (def->isPredefined()) { if (def->isPredefined()) {
std::string name{def->replacement().TokenAt(0).ToString()};
std::string repl; std::string repl;
if (!def->replacement().empty()) {
std::string name{def->replacement().TokenAt(0).ToString()};
if (name == "__FILE__") { if (name == "__FILE__") {
repl = "\""s + repl = "\""s +
allSources_.GetPath(prescanner.GetCurrentProvenance()) + '"'; allSources_.GetPath(prescanner.GetCurrentProvenance()) + '"';
@ -307,6 +308,7 @@ std::optional<TokenSequence> Preprocessor::MacroReplacement(
ss << allSources_.GetLineNumber(prescanner.GetCurrentProvenance()); ss << allSources_.GetLineNumber(prescanner.GetCurrentProvenance());
repl = ss.str(); repl = ss.str();
} }
}
if (!repl.empty()) { if (!repl.empty()) {
ProvenanceRange insert{allSources_.AddCompilerInsertion(repl)}; ProvenanceRange insert{allSources_.AddCompilerInsertion(repl)};
ProvenanceRange call{allSources_.AddMacroCall( ProvenanceRange call{allSources_.AddMacroCall(

View File

@ -61,11 +61,17 @@ public:
std::size_t SizeInTokens() const { return start_.size(); } std::size_t SizeInTokens() const { return start_.size(); }
std::size_t SizeInChars() const { return char_.size(); } std::size_t SizeInChars() const { return char_.size(); }
CharBlock ToCharBlock() const { return {&char_[0], char_.size()}; } CharBlock ToCharBlock() const {
return char_.empty() ? CharBlock{} : CharBlock{&char_[0], char_.size()};
}
std::string ToString() const { return ToCharBlock().ToString(); } std::string ToString() const { return ToCharBlock().ToString(); }
CharBlock TokenAt(std::size_t token) const { CharBlock TokenAt(std::size_t token) const {
return {&char_[start_.at(token)], TokenBytes(token)}; if (auto bytes{TokenBytes(token)}) {
return {&char_[start_.at(token)], bytes};
} else { // char_ could be empty
return {};
}
} }
char CharAt(std::size_t j) const { return char_.at(j); } char CharAt(std::size_t j) const { return char_.at(j); }
CharBlock CurrentOpenToken() const { CharBlock CurrentOpenToken() const {

View File

@ -0,0 +1,4 @@
! RUN: %flang -E -DMACRO= %s 2>&1 | FileCheck %s
!CHECK: integer, parameter :: p = +1
integer, parameter :: p = MACRO +1
end