blob: b0123732f80ae1e70c65f2ea5d81c7d570c44892 [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 Shaposhnikovd911ed12019-02-02 00:38:07 +000097};
98
Seiya Nutaf923d9b2019-06-21 00:21:50 +000099// A symbol information. Fields which starts with "n_" are same as them in the
100// nlist.
101struct SymbolEntry {
102 std::string Name;
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900103 bool Referenced = false;
Seiya Nutaf923d9b2019-06-21 00:21:50 +0000104 uint32_t Index;
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000105 uint8_t n_type;
106 uint8_t n_sect;
107 uint16_t n_desc;
108 uint64_t n_value;
Seiya Nuta552bcb82019-08-19 21:05:31 +0000109
Alexander Shaposhnikov999f04c2020-05-01 18:22:35 -0700110 bool isExternalSymbol() const { return n_type & MachO::N_EXT; }
Seiya Nuta552bcb82019-08-19 21:05:31 +0000111
112 bool isLocalSymbol() const { return !isExternalSymbol(); }
113
114 bool isUndefinedSymbol() const {
115 return (n_type & MachO::N_TYPE) == MachO::N_UNDF;
116 }
Alexander Shaposhnikovf34fdbc2020-04-22 14:26:28 -0700117
118 Optional<uint32_t> section() const {
119 return n_sect == MachO::NO_SECT ? None : Optional<uint32_t>(n_sect);
120 }
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000121};
122
123/// The location of the symbol table inside the binary is described by LC_SYMTAB
124/// load command.
125struct SymbolTable {
Seiya Nutaf923d9b2019-06-21 00:21:50 +0000126 std::vector<std::unique_ptr<SymbolEntry>> Symbols;
127
Fangrui Song28a5dc72019-11-13 13:10:15 -0800128 using iterator = pointee_iterator<
129 std::vector<std::unique_ptr<SymbolEntry>>::const_iterator>;
130
131 iterator begin() const { return iterator(Symbols.begin()); }
132 iterator end() const { return iterator(Symbols.end()); }
133
Seiya Nutaf923d9b2019-06-21 00:21:50 +0000134 const SymbolEntry *getSymbolByIndex(uint32_t Index) const;
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900135 SymbolEntry *getSymbolByIndex(uint32_t Index);
136 void removeSymbols(
137 function_ref<bool(const std::unique_ptr<SymbolEntry> &)> ToRemove);
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000138};
139
Seiya Nuta1e589f62019-10-30 15:12:17 +0900140struct IndirectSymbolEntry {
141 // The original value in an indirect symbol table. Higher bits encode extra
142 // information (INDIRECT_SYMBOL_LOCAL and INDIRECT_SYMBOL_ABS).
143 uint32_t OriginalIndex;
144 /// The Symbol referenced by this entry. It's None if the index is
145 /// INDIRECT_SYMBOL_LOCAL or INDIRECT_SYMBOL_ABS.
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900146 Optional<SymbolEntry *> Symbol;
Seiya Nuta1e589f62019-10-30 15:12:17 +0900147
Seiya Nuta9bbf2a12019-10-31 13:51:11 +0900148 IndirectSymbolEntry(uint32_t OriginalIndex, Optional<SymbolEntry *> Symbol)
Seiya Nuta1e589f62019-10-30 15:12:17 +0900149 : OriginalIndex(OriginalIndex), Symbol(Symbol) {}
150};
151
Seiya Nuta552bcb82019-08-19 21:05:31 +0000152struct IndirectSymbolTable {
Seiya Nuta1e589f62019-10-30 15:12:17 +0900153 std::vector<IndirectSymbolEntry> Symbols;
Seiya Nuta552bcb82019-08-19 21:05:31 +0000154};
155
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000156/// The location of the string table inside the binary is described by LC_SYMTAB
157/// load command.
158struct StringTable {
159 std::vector<std::string> Strings;
160};
161
Seiya Nutaf923d9b2019-06-21 00:21:50 +0000162struct RelocationInfo {
Alexander Shaposhnikov0db3a5a2020-04-26 22:39:50 -0700163 // The referenced symbol entry. Set if !Scattered && Extern.
164 Optional<const SymbolEntry *> Symbol;
165 // The referenced section. Set if !Scattered && !Extern.
Alexander Shaposhnikov29c6f5c2020-04-27 18:20:01 -0700166 Optional<const Section *> Sec;
Seiya Nutaf923d9b2019-06-21 00:21:50 +0000167 // True if Info is a scattered_relocation_info.
168 bool Scattered;
Alexander Shaposhnikov0db3a5a2020-04-26 22:39:50 -0700169 // True if the r_symbolnum points to a section number (i.e. r_extern=0).
170 bool Extern;
Seiya Nutaf923d9b2019-06-21 00:21:50 +0000171 MachO::any_relocation_info Info;
Lang Hamescc0ec3f2020-04-16 18:21:41 -0700172
173 unsigned getPlainRelocationSymbolNum(bool IsLittleEndian) {
174 if (IsLittleEndian)
175 return Info.r_word1 & 0xffffff;
176 return Info.r_word1 >> 8;
177 }
178
179 void setPlainRelocationSymbolNum(unsigned SymbolNum, bool IsLittleEndian) {
180 assert(SymbolNum < (1 << 24) && "SymbolNum out of range");
181 if (IsLittleEndian)
182 Info.r_word1 = (Info.r_word1 & ~0x00ffffff) | SymbolNum;
183 else
184 Info.r_word1 = (Info.r_word1 & ~0xffffff00) | (SymbolNum << 8);
185 }
Seiya Nutaf923d9b2019-06-21 00:21:50 +0000186};
187
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000188/// The location of the rebase info inside the binary is described by
189/// LC_DYLD_INFO load command. Dyld rebases an image whenever dyld loads it at
190/// an address different from its preferred address. The rebase information is
191/// a stream of byte sized opcodes whose symbolic names start with
192/// REBASE_OPCODE_. Conceptually the rebase information is a table of tuples:
193/// <seg-index, seg-offset, type>
194/// The opcodes are a compressed way to encode the table by only
195/// encoding when a column changes. In addition simple patterns
196/// like "every n'th offset for m times" can be encoded in a few
197/// bytes.
198struct RebaseInfo {
199 // At the moment we do not parse this info (and it is simply copied over),
200 // but the proper support will be added later.
201 ArrayRef<uint8_t> Opcodes;
202};
203
204/// The location of the bind info inside the binary is described by
205/// LC_DYLD_INFO load command. Dyld binds an image during the loading process,
206/// if the image requires any pointers to be initialized to symbols in other
207/// images. The bind information is a stream of byte sized opcodes whose
208/// symbolic names start with BIND_OPCODE_. Conceptually the bind information is
209/// a table of tuples: <seg-index, seg-offset, type, symbol-library-ordinal,
210/// symbol-name, addend> The opcodes are a compressed way to encode the table by
211/// only encoding when a column changes. In addition simple patterns like for
212/// runs of pointers initialized to the same value can be encoded in a few
213/// bytes.
214struct BindInfo {
215 // At the moment we do not parse this info (and it is simply copied over),
216 // but the proper support will be added later.
217 ArrayRef<uint8_t> Opcodes;
218};
219
220/// The location of the weak bind info inside the binary is described by
221/// LC_DYLD_INFO load command. Some C++ programs require dyld to unique symbols
222/// so that all images in the process use the same copy of some code/data. This
223/// step is done after binding. The content of the weak_bind info is an opcode
224/// stream like the bind_info. But it is sorted alphabetically by symbol name.
225/// This enable dyld to walk all images with weak binding information in order
226/// and look for collisions. If there are no collisions, dyld does no updating.
227/// That means that some fixups are also encoded in the bind_info. For
228/// instance, all calls to "operator new" are first bound to libstdc++.dylib
229/// using the information in bind_info. Then if some image overrides operator
230/// new that is detected when the weak_bind information is processed and the
231/// call to operator new is then rebound.
232struct WeakBindInfo {
233 // At the moment we do not parse this info (and it is simply copied over),
234 // but the proper support will be added later.
235 ArrayRef<uint8_t> Opcodes;
236};
237
238/// The location of the lazy bind info inside the binary is described by
239/// LC_DYLD_INFO load command. Some uses of external symbols do not need to be
240/// bound immediately. Instead they can be lazily bound on first use. The
241/// lazy_bind contains a stream of BIND opcodes to bind all lazy symbols. Normal
242/// use is that dyld ignores the lazy_bind section when loading an image.
243/// Instead the static linker arranged for the lazy pointer to initially point
244/// to a helper function which pushes the offset into the lazy_bind area for the
245/// symbol needing to be bound, then jumps to dyld which simply adds the offset
246/// to lazy_bind_off to get the information on what to bind.
247struct LazyBindInfo {
248 ArrayRef<uint8_t> Opcodes;
249};
250
251/// The location of the export info inside the binary is described by
252/// LC_DYLD_INFO load command. The symbols exported by a dylib are encoded in a
253/// trie. This is a compact representation that factors out common prefixes. It
254/// also reduces LINKEDIT pages in RAM because it encodes all information (name,
255/// address, flags) in one small, contiguous range. The export area is a stream
256/// of nodes. The first node sequentially is the start node for the trie. Nodes
257/// for a symbol start with a uleb128 that is the length of the exported symbol
258/// information for the string so far. If there is no exported symbol, the node
259/// starts with a zero byte. If there is exported info, it follows the length.
260/// First is a uleb128 containing flags. Normally, it is followed by
261/// a uleb128 encoded offset which is location of the content named
262/// by the symbol from the mach_header for the image. If the flags
263/// is EXPORT_SYMBOL_FLAGS_REEXPORT, then following the flags is
264/// a uleb128 encoded library ordinal, then a zero terminated
265/// UTF8 string. If the string is zero length, then the symbol
266/// is re-export from the specified dylib with the same name.
267/// If the flags is EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER, then following
268/// the flags is two uleb128s: the stub offset and the resolver offset.
269/// The stub is used by non-lazy pointers. The resolver is used
270/// by lazy pointers and must be called to get the actual address to use.
271/// After the optional exported symbol information is a byte of
272/// how many edges (0-255) that this node has leaving it,
273/// followed by each edge.
274/// Each edge is a zero terminated UTF8 of the addition chars
275/// in the symbol, followed by a uleb128 offset for the node that
276/// edge points to.
277struct ExportInfo {
278 ArrayRef<uint8_t> Trie;
279};
280
Seiya Nuta552bcb82019-08-19 21:05:31 +0000281struct LinkData {
282 ArrayRef<uint8_t> Data;
283};
284
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000285struct Object {
286 MachHeader Header;
287 std::vector<LoadCommand> LoadCommands;
288
289 SymbolTable SymTable;
290 StringTable StrTable;
291
292 RebaseInfo Rebases;
293 BindInfo Binds;
294 WeakBindInfo WeakBinds;
295 LazyBindInfo LazyBinds;
296 ExportInfo Exports;
Seiya Nuta552bcb82019-08-19 21:05:31 +0000297 IndirectSymbolTable IndirectSymTable;
298 LinkData DataInCode;
299 LinkData FunctionStarts;
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000300
301 /// The index of LC_SYMTAB load command if present.
302 Optional<size_t> SymTabCommandIndex;
303 /// The index of LC_DYLD_INFO or LC_DYLD_INFO_ONLY load command if present.
304 Optional<size_t> DyLdInfoCommandIndex;
Seiya Nuta552bcb82019-08-19 21:05:31 +0000305 /// The index LC_DYSYMTAB load comamnd if present.
306 Optional<size_t> DySymTabCommandIndex;
307 /// The index LC_DATA_IN_CODE load comamnd if present.
308 Optional<size_t> DataInCodeCommandIndex;
309 /// The index LC_FUNCTION_STARTS load comamnd if present.
310 Optional<size_t> FunctionStartsCommandIndex;
Seiya Nuta7f19dd12019-10-28 15:40:37 +0900311
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900312 BumpPtrAllocator Alloc;
313 StringSaver NewSectionsContents;
314
315 Object() : NewSectionsContents(Alloc) {}
316
Alexander Shaposhnikovf34fdbc2020-04-22 14:26:28 -0700317 Error
318 removeSections(function_ref<bool(const std::unique_ptr<Section> &)> ToRemove);
Alexander Shaposhnikovc54959c2019-11-19 23:30:52 -0800319 void addLoadCommand(LoadCommand LC);
Seiya Nuta9e119ad2019-12-16 14:05:06 +0900320
321 /// Creates a new segment load command in the object and returns a reference
322 /// to the newly created load command. The caller should verify that SegName
323 /// is not too long (SegName.size() should be less than or equal to 16).
324 LoadCommand &addSegment(StringRef SegName);
325
326 bool is64Bit() const {
327 return Header.Magic == MachO::MH_MAGIC_64 ||
328 Header.Magic == MachO::MH_CIGAM_64;
329 }
Alexander Shaposhnikovd911ed12019-02-02 00:38:07 +0000330};
331
332} // end namespace macho
333} // end namespace objcopy
334} // end namespace llvm
335
336#endif // LLVM_OBJCOPY_MACHO_OBJECT_H