[lld] r264202 - Use a memcpy to avoid unaligned store UB.

Pete Cooper via llvm-commits llvm-commits at lists.llvm.org
Wed Mar 23 15:00:09 PDT 2016


Author: pete
Date: Wed Mar 23 17:00:09 2016
New Revision: 264202

URL: http://llvm.org/viewvc/llvm-project?rev=264202&view=rev
Log:
Use a memcpy to avoid unaligned store UB.

On a 32-bit output, we may write LC_SOURCE_VERSION (which contains a uint64_t) to
an unaligned address.  This changes it to use a memcpy instead which is UB safe.

Modified:
    lld/trunk/lib/ReaderWriter/MachO/MachONormalizedFileBinaryWriter.cpp

Modified: lld/trunk/lib/ReaderWriter/MachO/MachONormalizedFileBinaryWriter.cpp
URL: http://llvm.org/viewvc/llvm-project/lld/trunk/lib/ReaderWriter/MachO/MachONormalizedFileBinaryWriter.cpp?rev=264202&r1=264201&r2=264202&view=diff
==============================================================================
--- lld/trunk/lib/ReaderWriter/MachO/MachONormalizedFileBinaryWriter.cpp (original)
+++ lld/trunk/lib/ReaderWriter/MachO/MachONormalizedFileBinaryWriter.cpp Wed Mar 23 17:00:09 2016
@@ -928,12 +928,15 @@ std::error_code MachOFileLayout::writeLo
 
     // Add LC_SOURCE_VERSION
     {
-      source_version_command* sv = reinterpret_cast<source_version_command*>(lc);
-      sv->cmd       = LC_SOURCE_VERSION;
-      sv->cmdsize   = sizeof(source_version_command);
-      sv->version   = _file.sourceVersion;
+      // Note, using a temporary here to appease UB as we may not be aligned
+      // enough for a struct containing a uint64_t when emitting a 32-bit binary
+      source_version_command sv;
+      sv.cmd       = LC_SOURCE_VERSION;
+      sv.cmdsize   = sizeof(source_version_command);
+      sv.version   = _file.sourceVersion;
       if (_swap)
-        swapStruct(*sv);
+        swapStruct(sv);
+      memcpy(lc, &sv, sizeof(source_version_command));
       lc += sizeof(source_version_command);
     }
 




More information about the llvm-commits mailing list