[llvm] [Support] Fix UB in decodeULEB128 and decodeSLEB128 (NFC) (PR #114986)
Krzysztof Pszeniczny via llvm-commits
llvm-commits at lists.llvm.org
Tue Nov 5 05:49:37 PST 2024
https://github.com/amharc created https://github.com/llvm/llvm-project/pull/114986
It currently might try to shift `Slice << Shift` for `Slice == 0` and `Shift > 63`. The behaviour is undefined in this case per [[expr.shift]/1](https://eel.is/c++draft/expr.shift#1).
>From 00769208fdae2f97177a6d2a2e68f88fc1693e97 Mon Sep 17 00:00:00 2001
From: Krzysztof Pszeniczny <kpszeniczny at google.com>
Date: Tue, 5 Nov 2024 14:43:07 +0100
Subject: [PATCH] [Support] Fix UB in decodeULEB128 and decodeSLEB128 (NFC)
It currently might try to shift `Slice << Shift` for `Slice == 0` and
`Shift > 63`. The behaviour is undefined in this case per
[expr.shift]/1.
---
llvm/include/llvm/Support/LEB128.h | 10 ++++++++--
1 file changed, 8 insertions(+), 2 deletions(-)
diff --git a/llvm/include/llvm/Support/LEB128.h b/llvm/include/llvm/Support/LEB128.h
index a15b73bc14dcde..19d113fec05d7d 100644
--- a/llvm/include/llvm/Support/LEB128.h
+++ b/llvm/include/llvm/Support/LEB128.h
@@ -150,7 +150,10 @@ inline uint64_t decodeULEB128(const uint8_t *p, unsigned *n = nullptr,
Value = 0;
break;
}
- Value += Slice << Shift;
+ // We might still have Shift > 63 && Slice == 0 here, so we need to protect
+ // against UB in <<.
+ if (LLVM_LIKELY(Shift <= 63))
+ Value += Slice << Shift;
Shift += 7;
} while (*p++ >= 128);
if (n)
@@ -188,7 +191,10 @@ inline int64_t decodeSLEB128(const uint8_t *p, unsigned *n = nullptr,
*n = (unsigned)(p - orig_p);
return 0;
}
- Value |= Slice << Shift;
+ // We might still have Shift > 63 here, so we need to protect against UB
+ // in <<.
+ if (LLVM_LIKELY(Shift <= 63))
+ Value |= Slice << Shift;
Shift += 7;
++p;
} while (Byte >= 128);
More information about the llvm-commits
mailing list