[PATCH] D65940: [clang-format] fix crash involving invalid preprocessor line

Krasimir Georgiev via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Thu Aug 8 04:44:51 PDT 2019


krasimir created this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

This (invalid) fragment is crashing clang-format:

  #if 1
  int x;
  #elif
  int y;
  #endif

The reason being that the parser expects a token after `#elif`, and the
subsequent parsing of the next line does not check if `CurrentToken` is null.


Repository:
  rC Clang

https://reviews.llvm.org/D65940

Files:
  lib/Format/TokenAnnotator.cpp
  unittests/Format/FormatTest.cpp


Index: unittests/Format/FormatTest.cpp
===================================================================
--- unittests/Format/FormatTest.cpp
+++ unittests/Format/FormatTest.cpp
@@ -3087,6 +3087,15 @@
                "#endif\n"
                "#endif\n",
                Style);
+  // Don't crash if there is nothing following #elif.
+  verifyFormat("#if 1\n"
+               "int x;\n"
+               "#elif\n"
+               "int y;\n"
+               "#else\n"
+               "int z;\n"
+               "#endif",
+               Style);
   // FIXME: This doesn't handle the case where there's code between the
   // #ifndef and #define but all other conditions hold. This is because when
   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
Index: lib/Format/TokenAnnotator.cpp
===================================================================
--- lib/Format/TokenAnnotator.cpp
+++ lib/Format/TokenAnnotator.cpp
@@ -1099,6 +1099,8 @@
 
 public:
   LineType parseLine() {
+    if (!CurrentToken)
+      return LT_Invalid;
     NonTemplateLess.clear();
     if (CurrentToken->is(tok::hash))
       return parsePreprocessorDirective();


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D65940.214113.patch
Type: text/x-patch
Size: 1168 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20190808/423e7d60/attachment.bin>


More information about the cfe-commits mailing list