blob: 0a930ba19f8e6cf42e39135fe5a43239b43b1ab1 [file] [log] [blame]
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +00001//===- Object.h - Mach-O object file model ----------------------*- C++ -*-===//
2//
Chandler Carruth127252b2019-02-11 08:25:19 +00003// 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
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +00006//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLVM_OBJCOPY_MACHO_OBJECT_H
10#define LLVM_OBJCOPY_MACHO_OBJECT_H
11
12#include "llvm/ADT/Optional.h"
13#include "llvm/ADT/StringRef.h"
14#include "llvm/BinaryFormat/MachO.h"
Seiya Nutaf923d9b2019-06-21 00:21:50 +000015#include "llvm/MC/StringTableBuilder.h"
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +000016#include "llvm/ObjectYAML/DWARFYAML.h"
Seiya Nuta9e119ad2019-12-16 14:05:06 +090017#include "llvm/Support/StringSaver.h"
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +000018#include "llvm/Support/YAMLTraits.h"
19#include <cstdint>
20#include <string>
21#include <vector>
22
23namespace llvm {
24namespace objcopy {
25namespace macho {
26
27struct MachHeader {
28 uint32_t Magic;
29 uint32_t CPUType;
30 uint32_t CPUSubType;
31 uint32_t FileType;
32 uint32_t NCmds;
33 uint32_t SizeOfCmds;
34 uint32_t Flags;
35 uint32_t Reserved = 0;
36};
37
Seiya Nutaf923d9b2019-06-21 00:21:50 +000038struct RelocationInfo;
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +000039struct Section {
Alexander Shaposhnikovf34fdbc2020-04-22 14:26:28 -070040 uint32_t Index;
Seiya Nutab728e532019-06-08 01:22:54 +000041 std::string Segname;
Seiya Nuta9e119ad2019-12-16 14:05:06 +090042 std::string Sectname;
Seiya Nuta7f19dd12019-10-28 15:40:37 +090043 // CanonicalName is a string formatted as “<Segname>,<Sectname>".
44 std::string CanonicalName;
Seiya Nuta9e119ad2019-12-16 14:05:06 +090045 uint64_t Addr = 0;
46 uint64_t Size = 0;
47 uint32_t Offset = 0;
48 uint32_t Align = 0;
49 uint32_t RelOff = 0;
50 uint32_t NReloc = 0;
51 uint32_t Flags = 0;
52 uint32_t Reserved1 = 0;
53 uint32_t Reserved2 = 0;
54 uint32_t Reserved3 = 0;
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +000055 StringRef Content;
Seiya Nutaf923d9b2019-06-21 00:21:50 +000056 std::vector<RelocationInfo> Relocations;
Seiya Nutab728e532019-06-08 01:22:54 +000057
Seiya Nuta9e119ad2019-12-16 14:05:06 +090058 Section(StringRef SegName, StringRef SectName)
Benjamin Krameradcd0262020-01-28 20:23:46 +010059 : Segname(std::string(SegName)), Sectname(std::string(SectName)),
Seiya Nuta9e119ad2019-12-16 14:05:06 +090060 CanonicalName((Twine(SegName) + Twine(',') + SectName).str()) {}
61
62 Section(StringRef SegName, StringRef SectName, StringRef Content)
Benjamin Krameradcd0262020-01-28 20:23:46 +010063 : Segname(std::string(SegName)), Sectname(std::string(SectName)),
Seiya Nuta9e119ad2019-12-16 14:05:06 +090064 CanonicalName((Twine(SegName) + Twine(',') + SectName).str()),
65 Content(Content) {}
66
Seiya Nutab728e532019-06-08 01:22:54 +000067 MachO::SectionType getType() const {
68 return static_cast<MachO::SectionType>(Flags & MachO::SECTION_TYPE);
69 }
70
71 bool isVirtualSection() const {
72 return (getType() == MachO::S_ZEROFILL ||
73 getType() == MachO::S_GB_ZEROFILL ||
74 getType() == MachO::S_THREAD_LOCAL_ZEROFILL);
75 }
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +000076};
77
78struct LoadCommand {
79 // The type MachO::macho_load_command is defined in llvm/BinaryFormat/MachO.h
80 // and it is a union of all the structs corresponding to various load
81 // commands.
82 MachO::macho_load_command MachOLoadCommand;
83
84 // The raw content of the payload of the load command (located right after the
85 // corresponding struct). In some cases it is either empty or can be
86 // copied-over without digging into its structure.
Alexander Shaposhnikovf34fdbc2020-04-22 14:26:28 -070087 std::vector<uint8_t> Payload;
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +000088
89 // Some load commands can contain (inside the payload) an array of sections,
90 // though the contents of the sections are stored separately. The struct
91 // Section describes only sections' metadata and where to find the
92 // corresponding content inside the binary.
Alexander Shaposhnikovdc046c72020-02-21 13:18:36 -080093 std::vector<std::unique_ptr<Section>> Sections;
Seiya Nuta9e119ad2019-12-16 14:05:06 +090094
95 // Returns the segment name if the load command is a segment command.
96 Optional<StringRef> getSegmentName() const;
Alexander Shaposhnikove60a7602020-09-24 01:48:21 -070097
98 // Returns the segment vm address if the load command is a segment command.
99 Optional<uint64_t> getSegmentVMAddr() const;
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000100};
101
Seiya Nutaf923d9b2019-06-21 00:21:50 +0000102// A symbol information. Fields which starts with "n_" are same as them in the
103// nlist.
104struct SymbolEntry {
105 std::string Name;
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900106 bool Referenced = false;
Seiya Nutaf923d9b2019-06-21 00:21:50 +0000107 uint32_t Index;
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000108 uint8_t n_type;
109 uint8_t n_sect;
110 uint16_t n_desc;
111 uint64_t n_value;
Seiya Nuta552bcb82019-08-19 21:05:31 +0000112
Alexander Shaposhnikov999f04c2020-05-01 18:22:35 -0700113 bool isExternalSymbol() const { return n_type & MachO::N_EXT; }
Seiya Nuta552bcb82019-08-19 21:05:31 +0000114
115 bool isLocalSymbol() const { return !isExternalSymbol(); }
116
117 bool isUndefinedSymbol() const {
118 return (n_type & MachO::N_TYPE) == MachO::N_UNDF;
119 }
Alexander Shaposhnikovf34fdbc2020-04-22 14:26:28 -0700120
Alexander Shaposhnikov842a8cc2020-05-26 16:49:56 -0700121 bool isSwiftSymbol() const {
122 return StringRef(Name).startswith("_$s") ||
123 StringRef(Name).startswith("_$S");
124 }
125
Alexander Shaposhnikovf34fdbc2020-04-22 14:26:28 -0700126 Optional<uint32_t> section() const {
127 return n_sect == MachO::NO_SECT ? None : Optional<uint32_t>(n_sect);
128 }
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000129};
130
131/// The location of the symbol table inside the binary is described by LC_SYMTAB
132/// load command.
133struct SymbolTable {
Seiya Nutaf923d9b2019-06-21 00:21:50 +0000134 std::vector<std::unique_ptr<SymbolEntry>> Symbols;
135
Fangrui Song28a5dc72019-11-13 13:10:15 -0800136 using iterator = pointee_iterator<
137 std::vector<std::unique_ptr<SymbolEntry>>::const_iterator>;
138
139 iterator begin() const { return iterator(Symbols.begin()); }
140 iterator end() const { return iterator(Symbols.end()); }
141
Seiya Nutaf923d9b2019-06-21 00:21:50 +0000142 const SymbolEntry *getSymbolByIndex(uint32_t Index) const;
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900143 SymbolEntry *getSymbolByIndex(uint32_t Index);
144 void removeSymbols(
145 function_ref<bool(const std::unique_ptr<SymbolEntry> &)> ToRemove);
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000146};
147
Seiya Nuta1e589f62019-10-30 15:12:17 +0900148struct IndirectSymbolEntry {
149 // The original value in an indirect symbol table. Higher bits encode extra
150 // information (INDIRECT_SYMBOL_LOCAL and INDIRECT_SYMBOL_ABS).
151 uint32_t OriginalIndex;
152 /// The Symbol referenced by this entry. It's None if the index is
153 /// INDIRECT_SYMBOL_LOCAL or INDIRECT_SYMBOL_ABS.
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900154 Optional<SymbolEntry *> Symbol;
Seiya Nuta1e589f62019-10-30 15:12:17 +0900155
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900156 IndirectSymbolEntry(uint32_t OriginalIndex, Optional<SymbolEntry *> Symbol)
Seiya Nuta1e589f62019-10-30 15:12:17 +0900157 : OriginalIndex(OriginalIndex), Symbol(Symbol) {}
158};
159
Seiya Nuta552bcb82019-08-19 21:05:31 +0000160struct IndirectSymbolTable {
Seiya Nuta1e589f62019-10-30 15:12:17 +0900161 std::vector<IndirectSymbolEntry> Symbols;
Seiya Nuta552bcb82019-08-19 21:05:31 +0000162};
163
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000164/// The location of the string table inside the binary is described by LC_SYMTAB
165/// load command.
166struct StringTable {
167 std::vector<std::string> Strings;
168};
169
Seiya Nutaf923d9b2019-06-21 00:21:50 +0000170struct RelocationInfo {
Alexander Shaposhnikov0db3a5a2020-04-26 22:39:50 -0700171 // The referenced symbol entry. Set if !Scattered && Extern.
172 Optional<const SymbolEntry *> Symbol;
173 // The referenced section. Set if !Scattered && !Extern.
Alexander Shaposhnikov29c6f5c2020-04-27 18:20:01 -0700174 Optional<const Section *> Sec;
Seiya Nutaf923d9b2019-06-21 00:21:50 +0000175 // True if Info is a scattered_relocation_info.
176 bool Scattered;
Alexander Shaposhnikov0db3a5a2020-04-26 22:39:50 -0700177 // True if the r_symbolnum points to a section number (i.e. r_extern=0).
178 bool Extern;
Seiya Nutaf923d9b2019-06-21 00:21:50 +0000179 MachO::any_relocation_info Info;
Lang Hamescc0ec3f2020-04-16 18:21:41 -0700180
181 unsigned getPlainRelocationSymbolNum(bool IsLittleEndian) {
182 if (IsLittleEndian)
183 return Info.r_word1 & 0xffffff;
184 return Info.r_word1 >> 8;
185 }
186
187 void setPlainRelocationSymbolNum(unsigned SymbolNum, bool IsLittleEndian) {
188 assert(SymbolNum < (1 << 24) && "SymbolNum out of range");
189 if (IsLittleEndian)
190 Info.r_word1 = (Info.r_word1 & ~0x00ffffff) | SymbolNum;
191 else
192 Info.r_word1 = (Info.r_word1 & ~0xffffff00) | (SymbolNum << 8);
193 }
Seiya Nutaf923d9b2019-06-21 00:21:50 +0000194};
195
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000196/// The location of the rebase info inside the binary is described by
197/// LC_DYLD_INFO load command. Dyld rebases an image whenever dyld loads it at
198/// an address different from its preferred address. The rebase information is
199/// a stream of byte sized opcodes whose symbolic names start with
200/// REBASE_OPCODE_. Conceptually the rebase information is a table of tuples:
201/// <seg-index, seg-offset, type>
202/// The opcodes are a compressed way to encode the table by only
203/// encoding when a column changes. In addition simple patterns
204/// like "every n'th offset for m times" can be encoded in a few
205/// bytes.
206struct RebaseInfo {
207 // At the moment we do not parse this info (and it is simply copied over),
208 // but the proper support will be added later.
209 ArrayRef<uint8_t> Opcodes;
210};
211
212/// The location of the bind info inside the binary is described by
213/// LC_DYLD_INFO load command. Dyld binds an image during the loading process,
214/// if the image requires any pointers to be initialized to symbols in other
215/// images. The bind information is a stream of byte sized opcodes whose
216/// symbolic names start with BIND_OPCODE_. Conceptually the bind information is
217/// a table of tuples: <seg-index, seg-offset, type, symbol-library-ordinal,
218/// symbol-name, addend> The opcodes are a compressed way to encode the table by
219/// only encoding when a column changes. In addition simple patterns like for
220/// runs of pointers initialized to the same value can be encoded in a few
221/// bytes.
222struct BindInfo {
223 // At the moment we do not parse this info (and it is simply copied over),
224 // but the proper support will be added later.
225 ArrayRef<uint8_t> Opcodes;
226};
227
228/// The location of the weak bind info inside the binary is described by
229/// LC_DYLD_INFO load command. Some C++ programs require dyld to unique symbols
230/// so that all images in the process use the same copy of some code/data. This
231/// step is done after binding. The content of the weak_bind info is an opcode
232/// stream like the bind_info. But it is sorted alphabetically by symbol name.
233/// This enable dyld to walk all images with weak binding information in order
234/// and look for collisions. If there are no collisions, dyld does no updating.
235/// That means that some fixups are also encoded in the bind_info. For
236/// instance, all calls to "operator new" are first bound to libstdc++.dylib
237/// using the information in bind_info. Then if some image overrides operator
238/// new that is detected when the weak_bind information is processed and the
239/// call to operator new is then rebound.
240struct WeakBindInfo {
241 // At the moment we do not parse this info (and it is simply copied over),
242 // but the proper support will be added later.
243 ArrayRef<uint8_t> Opcodes;
244};
245
246/// The location of the lazy bind info inside the binary is described by
247/// LC_DYLD_INFO load command. Some uses of external symbols do not need to be
248/// bound immediately. Instead they can be lazily bound on first use. The
249/// lazy_bind contains a stream of BIND opcodes to bind all lazy symbols. Normal
250/// use is that dyld ignores the lazy_bind section when loading an image.
251/// Instead the static linker arranged for the lazy pointer to initially point
252/// to a helper function which pushes the offset into the lazy_bind area for the
253/// symbol needing to be bound, then jumps to dyld which simply adds the offset
254/// to lazy_bind_off to get the information on what to bind.
255struct LazyBindInfo {
256 ArrayRef<uint8_t> Opcodes;
257};
258
259/// The location of the export info inside the binary is described by
260/// LC_DYLD_INFO load command. The symbols exported by a dylib are encoded in a
261/// trie. This is a compact representation that factors out common prefixes. It
262/// also reduces LINKEDIT pages in RAM because it encodes all information (name,
263/// address, flags) in one small, contiguous range. The export area is a stream
264/// of nodes. The first node sequentially is the start node for the trie. Nodes
265/// for a symbol start with a uleb128 that is the length of the exported symbol
266/// information for the string so far. If there is no exported symbol, the node
267/// starts with a zero byte. If there is exported info, it follows the length.
268/// First is a uleb128 containing flags. Normally, it is followed by
269/// a uleb128 encoded offset which is location of the content named
270/// by the symbol from the mach_header for the image. If the flags
271/// is EXPORT_SYMBOL_FLAGS_REEXPORT, then following the flags is
272/// a uleb128 encoded library ordinal, then a zero terminated
273/// UTF8 string. If the string is zero length, then the symbol
274/// is re-export from the specified dylib with the same name.
275/// If the flags is EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER, then following
276/// the flags is two uleb128s: the stub offset and the resolver offset.
277/// The stub is used by non-lazy pointers. The resolver is used
278/// by lazy pointers and must be called to get the actual address to use.
279/// After the optional exported symbol information is a byte of
280/// how many edges (0-255) that this node has leaving it,
281/// followed by each edge.
282/// Each edge is a zero terminated UTF8 of the addition chars
283/// in the symbol, followed by a uleb128 offset for the node that
284/// edge points to.
285struct ExportInfo {
286 ArrayRef<uint8_t> Trie;
287};
288
Seiya Nuta552bcb82019-08-19 21:05:31 +0000289struct LinkData {
290 ArrayRef<uint8_t> Data;
291};
292
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000293struct Object {
294 MachHeader Header;
295 std::vector<LoadCommand> LoadCommands;
296
297 SymbolTable SymTable;
298 StringTable StrTable;
299
300 RebaseInfo Rebases;
301 BindInfo Binds;
302 WeakBindInfo WeakBinds;
303 LazyBindInfo LazyBinds;
304 ExportInfo Exports;
Seiya Nuta552bcb82019-08-19 21:05:31 +0000305 IndirectSymbolTable IndirectSymTable;
306 LinkData DataInCode;
307 LinkData FunctionStarts;
Alexander Shaposhnikov913bc312020-06-15 18:55:59 -0700308 LinkData CodeSignature;
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000309
Alexander Shaposhnikov842a8cc2020-05-26 16:49:56 -0700310 Optional<uint32_t> SwiftVersion;
311
Alexander Shaposhnikov913bc312020-06-15 18:55:59 -0700312 /// The index of LC_CODE_SIGNATURE load command if present.
313 Optional<size_t> CodeSignatureCommandIndex;
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000314 /// The index of LC_SYMTAB load command if present.
315 Optional<size_t> SymTabCommandIndex;
316 /// The index of LC_DYLD_INFO or LC_DYLD_INFO_ONLY load command if present.
317 Optional<size_t> DyLdInfoCommandIndex;
Seiya Nuta552bcb82019-08-19 21:05:31 +0000318 /// The index LC_DYSYMTAB load comamnd if present.
319 Optional<size_t> DySymTabCommandIndex;
320 /// The index LC_DATA_IN_CODE load comamnd if present.
321 Optional<size_t> DataInCodeCommandIndex;
322 /// The index LC_FUNCTION_STARTS load comamnd if present.
323 Optional<size_t> FunctionStartsCommandIndex;
Seiya Nuta7f19dd12019-10-28 15:40:37 +0900324
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900325 BumpPtrAllocator Alloc;
326 StringSaver NewSectionsContents;
327
328 Object() : NewSectionsContents(Alloc) {}
329
Alexander Shaposhnikovf34fdbc2020-04-22 14:26:28 -0700330 Error
331 removeSections(function_ref<bool(const std::unique_ptr<Section> &)> ToRemove);
Alexander Shaposhnikovd332ec92020-06-22 16:49:14 -0700332
333 Error removeLoadCommands(function_ref<bool(const LoadCommand &)> ToRemove);
334
335 void updateLoadCommandIndexes();
336
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900337 /// Creates a new segment load command in the object and returns a reference
338 /// to the newly created load command. The caller should verify that SegName
339 /// is not too long (SegName.size() should be less than or equal to 16).
340 LoadCommand &addSegment(StringRef SegName);
341
342 bool is64Bit() const {
343 return Header.Magic == MachO::MH_MAGIC_64 ||
344 Header.Magic == MachO::MH_CIGAM_64;
345 }
Alexander Shaposhnikove60a7602020-09-24 01:48:21 -0700346
347 uint64_t nextAvailableSegmentAddress() const;
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000348};
349
350} // end namespace macho
351} // end namespace objcopy
352} // end namespace llvm
353
354#endif // LLVM_OBJCOPY_MACHO_OBJECT_H