llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

Can Len - 1 in HeaderMapImpl::getString overflow?

Open shafik opened this issue 1 year ago • 5 comments

A static analysis tool flags Len - 1 for possible overflow if Len has the value 0:

https://github.com/llvm/llvm-project/blob/27c788de759472316169795fa06d592221ac602e/clang/lib/Lex/HeaderMap.cpp#L161

A naive reading of the code does seem to indeed lead one to believe that MaxLen and Len could both be zero. I can't really convince myself this can't happen but maybe there is a constraint I am missing that prevents this.

shafik avatar Mar 06 '25 22:03 shafik

CC @cor3ntin @jansvoboda11 @dexonsmith who may have a better understanding in this area

shafik avatar Mar 06 '25 22:03 shafik

@llvm/issue-subscribers-clang-frontend

Author: Shafik Yaghmour (shafik)

A static analysis tool flags `Len - 1` for possible overflow if `Len` has the value `0`:

https://github.com/llvm/llvm-project/blob/27c788de759472316169795fa06d592221ac602e/clang/lib/Lex/HeaderMap.cpp#L161

A naive reading of the code does seem to indeed lead one to believe that MaxLen and Len could both be zero. I can't really convince myself this can't happen but maybe there is a constraint I am missing that prevents this.

llvmbot avatar Mar 06 '25 22:03 llvmbot

I think it would make sense to add an assert here.

The whole HeaderMap class does not seem to be resilient at all to invalid header map files (but I don't think that's too much of a problem)

cor3ntin avatar Mar 07 '25 06:03 cor3ntin

I think it would make sense to add an assert here.

I think it'd be better to return std::nullopt if MaxLen is 0. Can do this before the strnlen call.

The whole HeaderMap class does not seem to be resilient at all to invalid header map files (but I don't think that's too much of a problem)

Not surprised if it could be more resilient, but this function handles other corruption (such as a missing null terminator) by returning std::nullopt, so IMO we should do the same here.

dexonsmith avatar Mar 07 '25 21:03 dexonsmith

(Seems plausible that you could muck around with a binary header map to create a unit test for this... maybe store an empty string as the first entry, then truncate the file at the start of the string table?)

dexonsmith avatar Mar 07 '25 21:03 dexonsmith