Use a memcpy to avoid unaligned store UB.
authorPete Cooper <peter_cooper@apple.com>
Wed, 23 Mar 2016 22:00:09 +0000 (22:00 +0000)
committerPete Cooper <peter_cooper@apple.com>
Wed, 23 Mar 2016 22:00:09 +0000 (22:00 +0000)
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.

llvm-svn: 264202

lld/lib/ReaderWriter/MachO/MachONormalizedFileBinaryWriter.cpp

index 03e081a..a0a3df4 100644 (file)
@@ -928,12 +928,15 @@ std::error_code MachOFileLayout::writeLoadCommands() {
 
     // 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);
     }