[clang] [clang-format] Fix an off-by-1 bug with -length option (PR #143302)

Owen Pan via cfe-commits cfe-commits at lists.llvm.org
Wed Jun 25 22:13:35 PDT 2025


================
@@ -296,12 +296,16 @@ static bool fillRanges(MemoryBuffer *Code,
     }
     if (!EmptyLengths)
       Length = Lengths[I];
+    if (Length == 0) {
+      errs() << "error: length should be at least 1\n";
+      return true;
+    }
     if (Offset + Length > CodeSize) {
       errs() << "error: invalid length " << Length << ", offset + length ("
-             << Offset + Length << ") is outside the file.\n";
+             << Offset + Length << ") is outside the file\n";
       return true;
     }
-    Ranges.push_back(tooling::Range(Offset, Length));
+    Ranges.push_back(tooling::Range(Offset, Length - 1));
----------------
owenca wrote:

> I do agree that there's an off by one somewhere, but I think it's more likely to be in https://github.com/llvm/llvm-project/blob/main/clang/lib/Format/AffectedRangeManager.cpp#L61-L71. Logic in there accepts two ranges `[B1, E1)` and `[B2, E2)` as intersecting when `E1==B2`, but those ranges are half open (as they're constructed from `offset + length` pairs).

I didn't fix it there because we would have to change all unit tests that passes `0` as the length argument.

https://github.com/llvm/llvm-project/pull/143302


More information about the cfe-commits mailing list