From 1844181ab710a7a263487b574a4568aacf0b3dae Mon Sep 17 00:00:00 2001 From: David Majnemer Date: Wed, 17 Feb 2016 22:37:45 +0000 Subject: [PATCH] Don't crash w/ a diagnostic range containing a null byte We prematurely ended the line at the null byte which caused us to crash down stream because we tried to reason about columns beyond the end of the line. git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@261171 91177308-0d34-0410-b5e6-96231b3b80d8 --- lib/Frontend/TextDiagnostic.cpp | 14 +++++++++++--- test/Misc/diag-null-bytes-in-line.cpp | Bin 0 -> 398 bytes 2 files changed, 11 insertions(+), 3 deletions(-) create mode 100644 test/Misc/diag-null-bytes-in-line.cpp diff --git a/lib/Frontend/TextDiagnostic.cpp b/lib/Frontend/TextDiagnostic.cpp index d4e156d445..5dda151d55 100644 --- a/lib/Frontend/TextDiagnostic.cpp +++ b/lib/Frontend/TextDiagnostic.cpp @@ -1082,10 +1082,13 @@ void TextDiagnostic::emitSnippetAndCaret( // Get information about the buffer it points into. bool Invalid = false; - const char *BufStart = SM.getBufferData(FID, &Invalid).data(); + StringRef BufData = SM.getBufferData(FID, &Invalid); if (Invalid) return; + const char *BufStart = BufData.data(); + const char *BufEnd = BufStart + BufData.size(); + unsigned LineNo = SM.getLineNumber(FID, FileOffset); unsigned ColNo = SM.getColumnNumber(FID, FileOffset); @@ -1101,15 +1104,20 @@ void TextDiagnostic::emitSnippetAndCaret( // Compute the line end. Scan forward from the error position to the end of // the line. const char *LineEnd = TokPtr; - while (*LineEnd != '\n' && *LineEnd != '\r' && *LineEnd != '\0') + while (*LineEnd != '\n' && *LineEnd != '\r' && LineEnd != BufEnd) ++LineEnd; // Arbitrarily stop showing snippets when the line is too long. if (size_t(LineEnd - LineStart) > MaxLineLengthToPrint) return; + // Trim trailing null-bytes. + StringRef Line(LineStart, LineEnd - LineStart); + while (Line.size() > ColNo && Line.back() == '\0') + Line = Line.drop_back(); + // Copy the line of code into an std::string for ease of manipulation. - std::string SourceLine(LineStart, LineEnd); + std::string SourceLine(Line.begin(), Line.end()); // Build the byte to column map. const SourceColumnMap sourceColMap(SourceLine, DiagOpts->TabStop); diff --git a/test/Misc/diag-null-bytes-in-line.cpp b/test/Misc/diag-null-bytes-in-line.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1eba91f6b23925ef3eae323eef81751bd1238d2b GIT binary patch literal 398 zcmbu5K}!QM5QRPGSG-G$B4JyPtMsx|ghCI+f*>j(JKYV&$uddluK44PsA~mp&Se<* z_}*iR0-No+1c!u)^@f`#Yv<6rIB+t(4(ta^A}$uwIo@#XJXI~(XXu#3*`yDxOB6d} zDPu}GPU!EWd!?{D$;ZQ`DhgCL%W75PV1ykvIc@JfY-_~WL;}}v5UNK~ua|eXC5~NJ z+w)nT#c$;oh@*K_qoxFj1j(!KC;M1& literal 0 HcmV?d00001 -- 2.40.0