Skip to content

Commit 8fbe1e7

Browse files
committed
[llvm-objcopy] Fix misaligned access to load command data.
It seems that llvm-objcopy stores data temporarily misaligned with the requirements of the underlaying struct from libBinaryFormat, and UBSan generates a runtime error. Instead of trying to reinterpret the memory as the struct itself, simply access the `char *` pointer that we are interested in, and that do not have alignment restrictions. This problem was pointed out in a comment of D111164. Differential Revision: https://reviews.llvm.org/D112744
1 parent 3a4b605 commit 8fbe1e7

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

llvm/tools/llvm-objcopy/MachO/MachOReader.cpp

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -124,9 +124,12 @@ Error MachOReader::readLoadCommands(Object &O) const {
124124
O.CodeSignatureCommandIndex = O.LoadCommands.size();
125125
break;
126126
case MachO::LC_SEGMENT:
127-
if (StringRef(
128-
reinterpret_cast<MachO::segment_command const *>(LoadCmd.Ptr)
129-
->segname) == TextSegmentName)
127+
// LoadCmd.Ptr might not be aligned temporarily as
128+
// MachO::segment_command requires, but the segname char pointer do not
129+
// have alignment restrictions.
130+
if (StringRef(reinterpret_cast<const char *>(
131+
LoadCmd.Ptr + offsetof(MachO::segment_command, segname))) ==
132+
TextSegmentName)
130133
O.TextSegmentCommandIndex = O.LoadCommands.size();
131134

132135
if (Expected<std::vector<std::unique_ptr<Section>>> Sections =
@@ -137,9 +140,12 @@ Error MachOReader::readLoadCommands(Object &O) const {
137140
return Sections.takeError();
138141
break;
139142
case MachO::LC_SEGMENT_64:
140-
if (StringRef(
141-
reinterpret_cast<MachO::segment_command_64 const *>(LoadCmd.Ptr)
142-
->segname) == TextSegmentName)
143+
// LoadCmd.Ptr might not be aligned temporarily as
144+
// MachO::segment_command_64 requires, but the segname char pointer do
145+
// not have alignment restrictions.
146+
if (StringRef(reinterpret_cast<const char *>(
147+
LoadCmd.Ptr + offsetof(MachO::segment_command_64, segname))) ==
148+
TextSegmentName)
143149
O.TextSegmentCommandIndex = O.LoadCommands.size();
144150

145151
if (Expected<std::vector<std::unique_ptr<Section>>> Sections =

0 commit comments

Comments
 (0)