[PATCH] D44576: [clangd] Fix undefined behavior due to misaligned type cast

Jan Korous via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Fri Mar 16 12:39:38 PDT 2018


jkorous-apple created this revision.
jkorous-apple added a project: clang-tools-extra.
Herald added subscribers: cfe-commits, ioeric, ilya-biryukov.

The current code is casting pointer to a misaligned type which is undefined behavior.

Found by compiling with Undefined Behavior Sanitizer and running tests (check-clang-tools).

AFAIK clang produces the same code for reinterpret_cast<>() and memcpy().

Follow-up to: https://reviews.llvm.org/D44575


Repository:
  rCTE Clang Tools Extra

https://reviews.llvm.org/D44576

Files:
  clangd/index/Index.h


Index: clangd/index/Index.h
===================================================================
--- clangd/index/Index.h
+++ clangd/index/Index.h
@@ -59,7 +59,9 @@
   friend llvm::hash_code hash_value(const SymbolID &ID) {
     // We already have a good hash, just return the first bytes.
     static_assert(sizeof(size_t) <= HashByteLength, "size_t longer than SHA1!");
-    return *reinterpret_cast<const size_t *>(ID.HashValue.data());
+    size_t Result;
+    memcpy(&Result, ID.HashValue.data(), sizeof(size_t));
+    return llvm::hash_code(Result);
   }
   friend llvm::raw_ostream &operator<<(llvm::raw_ostream &OS,
                                        const SymbolID &ID);


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D44576.138746.patch
Type: text/x-patch
Size: 684 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20180316/018240f1/attachment.bin>


More information about the cfe-commits mailing list