From: Douglas Gregor Date: Mon, 31 Jan 2011 22:42:36 +0000 (+0000) Subject: Harden Lexer::GetBeginningOfToken() against bogus source locations and X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=3de84241d90f3dd280126fdf2c4651667151c967;p=clang Harden Lexer::GetBeginningOfToken() against bogus source locations and the disappearance/alteration of files. git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@124616 91177308-0d34-0410-b5e6-96231b3b80d8 --- diff --git a/lib/Basic/SourceManager.cpp b/lib/Basic/SourceManager.cpp index 409851f108..e476cb2e29 100644 --- a/lib/Basic/SourceManager.cpp +++ b/lib/Basic/SourceManager.cpp @@ -531,12 +531,21 @@ void SourceManager::overrideFileContents(const FileEntry *SourceFile, llvm::StringRef SourceManager::getBufferData(FileID FID, bool *Invalid) const { bool MyInvalid = false; - const llvm::MemoryBuffer *Buf = getBuffer(FID, &MyInvalid); + const SLocEntry &SLoc = getSLocEntry(FID.ID); + if (!SLoc.isFile()) { + if (Invalid) + *Invalid = true; + return "<<<<>>>>"; + } + + const llvm::MemoryBuffer *Buf + = SLoc.getFile().getContentCache()->getBuffer(Diag, *this, SourceLocation(), + &MyInvalid); if (Invalid) *Invalid = MyInvalid; if (MyInvalid) - return ""; + return "<<<<>>>>"; return Buf->getBuffer(); } diff --git a/lib/Lex/Lexer.cpp b/lib/Lex/Lexer.cpp index 5d9536f40d..7c94528c64 100644 --- a/lib/Lex/Lexer.cpp +++ b/lib/Lex/Lexer.cpp @@ -357,6 +357,9 @@ SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) { std::pair LocInfo = SM.getDecomposedLoc(Loc); + if (LocInfo.first.isInvalid()) + return Loc; + bool Invalid = false; llvm::StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); if (Invalid) @@ -365,6 +368,9 @@ SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc, // Back up from the current location until we hit the beginning of a line // (or the buffer). We'll relex from that point. const char *BufStart = Buffer.data(); + if (LocInfo.second >= Buffer.size()) + return Loc; + const char *StrData = BufStart+LocInfo.second; if (StrData[0] == '\n' || StrData[0] == '\r') return Loc;