1 //===- Object.h - Mach-O object file model ----------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #ifndef LLVM_OBJCOPY_MACHO_OBJECT_H
10 #define LLVM_OBJCOPY_MACHO_OBJECT_H
12 #include "llvm/ADT/Optional.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/BinaryFormat/MachO.h"
15 #include "llvm/MC/StringTableBuilder.h"
16 #include "llvm/ObjectYAML/DWARFYAML.h"
17 #include "llvm/Support/StringSaver.h"
18 #include "llvm/Support/YAMLTraits.h"
35 uint32_t Reserved
= 0;
38 struct RelocationInfo
;
43 // CanonicalName is a string formatted as “<Segname>,<Sectname>".
44 std::string CanonicalName
;
47 // Offset in the input file.
48 Optional
<uint32_t> OriginalOffset
;
54 uint32_t Reserved1
= 0;
55 uint32_t Reserved2
= 0;
56 uint32_t Reserved3
= 0;
58 std::vector
<RelocationInfo
> Relocations
;
60 Section(StringRef SegName
, StringRef SectName
)
61 : Segname(std::string(SegName
)), Sectname(std::string(SectName
)),
62 CanonicalName((Twine(SegName
) + Twine(',') + SectName
).str()) {}
64 Section(StringRef SegName
, StringRef SectName
, StringRef Content
)
65 : Segname(std::string(SegName
)), Sectname(std::string(SectName
)),
66 CanonicalName((Twine(SegName
) + Twine(',') + SectName
).str()),
69 MachO::SectionType
getType() const {
70 return static_cast<MachO::SectionType
>(Flags
& MachO::SECTION_TYPE
);
73 bool isVirtualSection() const {
74 return (getType() == MachO::S_ZEROFILL
||
75 getType() == MachO::S_GB_ZEROFILL
||
76 getType() == MachO::S_THREAD_LOCAL_ZEROFILL
);
79 bool hasValidOffset() const {
80 return !(isVirtualSection() || (OriginalOffset
&& *OriginalOffset
== 0));
85 // The type MachO::macho_load_command is defined in llvm/BinaryFormat/MachO.h
86 // and it is a union of all the structs corresponding to various load
88 MachO::macho_load_command MachOLoadCommand
;
90 // The raw content of the payload of the load command (located right after the
91 // corresponding struct). In some cases it is either empty or can be
92 // copied-over without digging into its structure.
93 std::vector
<uint8_t> Payload
;
95 // Some load commands can contain (inside the payload) an array of sections,
96 // though the contents of the sections are stored separately. The struct
97 // Section describes only sections' metadata and where to find the
98 // corresponding content inside the binary.
99 std::vector
<std::unique_ptr
<Section
>> Sections
;
101 // Returns the segment name if the load command is a segment command.
102 Optional
<StringRef
> getSegmentName() const;
104 // Returns the segment vm address if the load command is a segment command.
105 Optional
<uint64_t> getSegmentVMAddr() const;
108 // A symbol information. Fields which starts with "n_" are same as them in the
112 bool Referenced
= false;
119 bool isExternalSymbol() const { return n_type
& MachO::N_EXT
; }
121 bool isLocalSymbol() const { return !isExternalSymbol(); }
123 bool isUndefinedSymbol() const {
124 return (n_type
& MachO::N_TYPE
) == MachO::N_UNDF
;
127 bool isSwiftSymbol() const {
128 return StringRef(Name
).startswith("_$s") ||
129 StringRef(Name
).startswith("_$S");
132 Optional
<uint32_t> section() const {
133 return n_sect
== MachO::NO_SECT
? None
: Optional
<uint32_t>(n_sect
);
137 /// The location of the symbol table inside the binary is described by LC_SYMTAB
140 std::vector
<std::unique_ptr
<SymbolEntry
>> Symbols
;
142 using iterator
= pointee_iterator
<
143 std::vector
<std::unique_ptr
<SymbolEntry
>>::const_iterator
>;
145 iterator
begin() const { return iterator(Symbols
.begin()); }
146 iterator
end() const { return iterator(Symbols
.end()); }
148 const SymbolEntry
*getSymbolByIndex(uint32_t Index
) const;
149 SymbolEntry
*getSymbolByIndex(uint32_t Index
);
151 function_ref
<bool(const std::unique_ptr
<SymbolEntry
> &)> ToRemove
);
154 struct IndirectSymbolEntry
{
155 // The original value in an indirect symbol table. Higher bits encode extra
156 // information (INDIRECT_SYMBOL_LOCAL and INDIRECT_SYMBOL_ABS).
157 uint32_t OriginalIndex
;
158 /// The Symbol referenced by this entry. It's None if the index is
159 /// INDIRECT_SYMBOL_LOCAL or INDIRECT_SYMBOL_ABS.
160 Optional
<SymbolEntry
*> Symbol
;
162 IndirectSymbolEntry(uint32_t OriginalIndex
, Optional
<SymbolEntry
*> Symbol
)
163 : OriginalIndex(OriginalIndex
), Symbol(Symbol
) {}
166 struct IndirectSymbolTable
{
167 std::vector
<IndirectSymbolEntry
> Symbols
;
170 /// The location of the string table inside the binary is described by LC_SYMTAB
173 std::vector
<std::string
> Strings
;
176 struct RelocationInfo
{
177 // The referenced symbol entry. Set if !Scattered && Extern.
178 Optional
<const SymbolEntry
*> Symbol
;
179 // The referenced section. Set if !Scattered && !Extern.
180 Optional
<const Section
*> Sec
;
181 // True if Info is a scattered_relocation_info.
183 // True if the type is an ADDEND. r_symbolnum holds the addend instead of a
186 // True if the r_symbolnum points to a section number (i.e. r_extern=0).
188 MachO::any_relocation_info Info
;
190 unsigned getPlainRelocationSymbolNum(bool IsLittleEndian
) {
192 return Info
.r_word1
& 0xffffff;
193 return Info
.r_word1
>> 8;
196 void setPlainRelocationSymbolNum(unsigned SymbolNum
, bool IsLittleEndian
) {
197 assert(SymbolNum
< (1 << 24) && "SymbolNum out of range");
199 Info
.r_word1
= (Info
.r_word1
& ~0x00ffffff) | SymbolNum
;
201 Info
.r_word1
= (Info
.r_word1
& ~0xffffff00) | (SymbolNum
<< 8);
205 /// The location of the rebase info inside the binary is described by
206 /// LC_DYLD_INFO load command. Dyld rebases an image whenever dyld loads it at
207 /// an address different from its preferred address. The rebase information is
208 /// a stream of byte sized opcodes whose symbolic names start with
209 /// REBASE_OPCODE_. Conceptually the rebase information is a table of tuples:
210 /// <seg-index, seg-offset, type>
211 /// The opcodes are a compressed way to encode the table by only
212 /// encoding when a column changes. In addition simple patterns
213 /// like "every n'th offset for m times" can be encoded in a few
216 // At the moment we do not parse this info (and it is simply copied over),
217 // but the proper support will be added later.
218 ArrayRef
<uint8_t> Opcodes
;
221 /// The location of the bind info inside the binary is described by
222 /// LC_DYLD_INFO load command. Dyld binds an image during the loading process,
223 /// if the image requires any pointers to be initialized to symbols in other
224 /// images. The bind information is a stream of byte sized opcodes whose
225 /// symbolic names start with BIND_OPCODE_. Conceptually the bind information is
226 /// a table of tuples: <seg-index, seg-offset, type, symbol-library-ordinal,
227 /// symbol-name, addend> The opcodes are a compressed way to encode the table by
228 /// only encoding when a column changes. In addition simple patterns like for
229 /// runs of pointers initialized to the same value can be encoded in a few
232 // At the moment we do not parse this info (and it is simply copied over),
233 // but the proper support will be added later.
234 ArrayRef
<uint8_t> Opcodes
;
237 /// The location of the weak bind info inside the binary is described by
238 /// LC_DYLD_INFO load command. Some C++ programs require dyld to unique symbols
239 /// so that all images in the process use the same copy of some code/data. This
240 /// step is done after binding. The content of the weak_bind info is an opcode
241 /// stream like the bind_info. But it is sorted alphabetically by symbol name.
242 /// This enable dyld to walk all images with weak binding information in order
243 /// and look for collisions. If there are no collisions, dyld does no updating.
244 /// That means that some fixups are also encoded in the bind_info. For
245 /// instance, all calls to "operator new" are first bound to libstdc++.dylib
246 /// using the information in bind_info. Then if some image overrides operator
247 /// new that is detected when the weak_bind information is processed and the
248 /// call to operator new is then rebound.
249 struct WeakBindInfo
{
250 // At the moment we do not parse this info (and it is simply copied over),
251 // but the proper support will be added later.
252 ArrayRef
<uint8_t> Opcodes
;
255 /// The location of the lazy bind info inside the binary is described by
256 /// LC_DYLD_INFO load command. Some uses of external symbols do not need to be
257 /// bound immediately. Instead they can be lazily bound on first use. The
258 /// lazy_bind contains a stream of BIND opcodes to bind all lazy symbols. Normal
259 /// use is that dyld ignores the lazy_bind section when loading an image.
260 /// Instead the static linker arranged for the lazy pointer to initially point
261 /// to a helper function which pushes the offset into the lazy_bind area for the
262 /// symbol needing to be bound, then jumps to dyld which simply adds the offset
263 /// to lazy_bind_off to get the information on what to bind.
264 struct LazyBindInfo
{
265 ArrayRef
<uint8_t> Opcodes
;
268 /// The location of the export info inside the binary is described by
269 /// LC_DYLD_INFO load command. The symbols exported by a dylib are encoded in a
270 /// trie. This is a compact representation that factors out common prefixes. It
271 /// also reduces LINKEDIT pages in RAM because it encodes all information (name,
272 /// address, flags) in one small, contiguous range. The export area is a stream
273 /// of nodes. The first node sequentially is the start node for the trie. Nodes
274 /// for a symbol start with a uleb128 that is the length of the exported symbol
275 /// information for the string so far. If there is no exported symbol, the node
276 /// starts with a zero byte. If there is exported info, it follows the length.
277 /// First is a uleb128 containing flags. Normally, it is followed by
278 /// a uleb128 encoded offset which is location of the content named
279 /// by the symbol from the mach_header for the image. If the flags
280 /// is EXPORT_SYMBOL_FLAGS_REEXPORT, then following the flags is
281 /// a uleb128 encoded library ordinal, then a zero terminated
282 /// UTF8 string. If the string is zero length, then the symbol
283 /// is re-export from the specified dylib with the same name.
284 /// If the flags is EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER, then following
285 /// the flags is two uleb128s: the stub offset and the resolver offset.
286 /// The stub is used by non-lazy pointers. The resolver is used
287 /// by lazy pointers and must be called to get the actual address to use.
288 /// After the optional exported symbol information is a byte of
289 /// how many edges (0-255) that this node has leaving it,
290 /// followed by each edge.
291 /// Each edge is a zero terminated UTF8 of the addition chars
292 /// in the symbol, followed by a uleb128 offset for the node that
295 ArrayRef
<uint8_t> Trie
;
299 ArrayRef
<uint8_t> Data
;
304 std::vector
<LoadCommand
> LoadCommands
;
306 SymbolTable SymTable
;
307 StringTable StrTable
;
311 WeakBindInfo WeakBinds
;
312 LazyBindInfo LazyBinds
;
314 IndirectSymbolTable IndirectSymTable
;
316 LinkData LinkerOptimizationHint
;
317 LinkData FunctionStarts
;
318 LinkData ExportsTrie
;
319 LinkData ChainedFixups
;
321 Optional
<uint32_t> SwiftVersion
;
323 /// The index of LC_CODE_SIGNATURE load command if present.
324 Optional
<size_t> CodeSignatureCommandIndex
;
325 /// The index of LC_SYMTAB load command if present.
326 Optional
<size_t> SymTabCommandIndex
;
327 /// The index of LC_DYLD_INFO or LC_DYLD_INFO_ONLY load command if present.
328 Optional
<size_t> DyLdInfoCommandIndex
;
329 /// The index LC_DYSYMTAB load command if present.
330 Optional
<size_t> DySymTabCommandIndex
;
331 /// The index LC_DATA_IN_CODE load command if present.
332 Optional
<size_t> DataInCodeCommandIndex
;
333 /// The index of LC_LINKER_OPTIMIZATIN_HINT load command if present.
334 Optional
<size_t> LinkerOptimizationHintCommandIndex
;
335 /// The index LC_FUNCTION_STARTS load command if present.
336 Optional
<size_t> FunctionStartsCommandIndex
;
337 /// The index LC_DYLD_CHAINED_FIXUPS load command if present.
338 Optional
<size_t> ChainedFixupsCommandIndex
;
339 /// The index LC_DYLD_EXPORTS_TRIE load command if present.
340 Optional
<size_t> ExportsTrieCommandIndex
;
341 /// The index of the LC_SEGMENT or LC_SEGMENT_64 load command
342 /// corresponding to the __TEXT segment.
343 Optional
<size_t> TextSegmentCommandIndex
;
345 BumpPtrAllocator Alloc
;
346 StringSaver NewSectionsContents
;
348 Object() : NewSectionsContents(Alloc
) {}
351 removeSections(function_ref
<bool(const std::unique_ptr
<Section
> &)> ToRemove
);
353 Error
removeLoadCommands(function_ref
<bool(const LoadCommand
&)> ToRemove
);
355 void updateLoadCommandIndexes();
357 /// Creates a new segment load command in the object and returns a reference
358 /// to the newly created load command. The caller should verify that SegName
359 /// is not too long (SegName.size() should be less than or equal to 16).
360 LoadCommand
&addSegment(StringRef SegName
, uint64_t SegVMSize
);
362 bool is64Bit() const {
363 return Header
.Magic
== MachO::MH_MAGIC_64
||
364 Header
.Magic
== MachO::MH_CIGAM_64
;
367 uint64_t nextAvailableSegmentAddress() const;
370 } // end namespace macho
371 } // end namespace objcopy
372 } // end namespace llvm
374 #endif // LLVM_OBJCOPY_MACHO_OBJECT_H