Merging r259381:
[oota-llvm.git] / include / llvm / MC / MCMachObjectWriter.h
1 //===-- llvm/MC/MCMachObjectWriter.h - Mach Object Writer -------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #ifndef LLVM_MC_MCMACHOBJECTWRITER_H
11 #define LLVM_MC_MCMACHOBJECTWRITER_H
12
13 #include "llvm/ADT/DenseMap.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/MC/MCExpr.h"
16 #include "llvm/MC/MCSection.h"
17 #include "llvm/MC/MCObjectWriter.h"
18 #include "llvm/MC/StringTableBuilder.h"
19 #include "llvm/Support/DataTypes.h"
20 #include "llvm/Support/MachO.h"
21 #include <vector>
22
23 namespace llvm {
24
25 class MachObjectWriter;
26
27 class MCMachObjectTargetWriter {
28   const unsigned Is64Bit : 1;
29   const uint32_t CPUType;
30   const uint32_t CPUSubtype;
31   unsigned LocalDifference_RIT;
32
33 protected:
34   MCMachObjectTargetWriter(bool Is64Bit_, uint32_t CPUType_,
35                            uint32_t CPUSubtype_);
36
37   void setLocalDifferenceRelocationType(unsigned Type) {
38     LocalDifference_RIT = Type;
39   }
40
41 public:
42   virtual ~MCMachObjectTargetWriter();
43
44   /// \name Lifetime Management
45   /// @{
46
47   virtual void reset() {}
48
49   /// @}
50
51   /// \name Accessors
52   /// @{
53
54   bool is64Bit() const { return Is64Bit; }
55   uint32_t getCPUType() const { return CPUType; }
56   uint32_t getCPUSubtype() const { return CPUSubtype; }
57   unsigned getLocalDifferenceRelocationType() const {
58     return LocalDifference_RIT;
59   }
60
61   /// @}
62
63   /// \name API
64   /// @{
65
66   virtual void recordRelocation(MachObjectWriter *Writer, MCAssembler &Asm,
67                                 const MCAsmLayout &Layout,
68                                 const MCFragment *Fragment,
69                                 const MCFixup &Fixup, MCValue Target,
70                                 uint64_t &FixedValue) = 0;
71
72   /// @}
73 };
74
75 class MachObjectWriter : public MCObjectWriter {
76   /// Helper struct for containing some precomputed information on symbols.
77   struct MachSymbolData {
78     const MCSymbol *Symbol;
79     uint64_t StringIndex;
80     uint8_t SectionIndex;
81
82     // Support lexicographic sorting.
83     bool operator<(const MachSymbolData &RHS) const;
84   };
85
86   /// The target specific Mach-O writer instance.
87   std::unique_ptr<MCMachObjectTargetWriter> TargetObjectWriter;
88
89   /// \name Relocation Data
90   /// @{
91
92   struct RelAndSymbol {
93     const MCSymbol *Sym;
94     MachO::any_relocation_info MRE;
95     RelAndSymbol(const MCSymbol *Sym, const MachO::any_relocation_info &MRE)
96         : Sym(Sym), MRE(MRE) {}
97   };
98
99   llvm::DenseMap<const MCSection *, std::vector<RelAndSymbol>> Relocations;
100   llvm::DenseMap<const MCSection *, unsigned> IndirectSymBase;
101
102   SectionAddrMap SectionAddress;
103
104   /// @}
105   /// \name Symbol Table Data
106   /// @{
107
108   StringTableBuilder StringTable{StringTableBuilder::MachO};
109   std::vector<MachSymbolData> LocalSymbolData;
110   std::vector<MachSymbolData> ExternalSymbolData;
111   std::vector<MachSymbolData> UndefinedSymbolData;
112
113   /// @}
114
115   MachSymbolData *findSymbolData(const MCSymbol &Sym);
116
117 public:
118   MachObjectWriter(MCMachObjectTargetWriter *MOTW, raw_pwrite_stream &OS,
119                    bool IsLittleEndian)
120       : MCObjectWriter(OS, IsLittleEndian), TargetObjectWriter(MOTW) {}
121
122   const MCSymbol &findAliasedSymbol(const MCSymbol &Sym) const;
123
124   /// \name Lifetime management Methods
125   /// @{
126
127   void reset() override;
128
129   /// @}
130
131   /// \name Utility Methods
132   /// @{
133
134   bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
135
136   SectionAddrMap &getSectionAddressMap() { return SectionAddress; }
137
138   uint64_t getSectionAddress(const MCSection *Sec) const {
139     return SectionAddress.lookup(Sec);
140   }
141   uint64_t getSymbolAddress(const MCSymbol &S, const MCAsmLayout &Layout) const;
142
143   uint64_t getFragmentAddress(const MCFragment *Fragment,
144                               const MCAsmLayout &Layout) const;
145
146   uint64_t getPaddingSize(const MCSection *SD, const MCAsmLayout &Layout) const;
147
148   bool doesSymbolRequireExternRelocation(const MCSymbol &S);
149
150   /// @}
151
152   /// \name Target Writer Proxy Accessors
153   /// @{
154
155   bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
156   bool isX86_64() const {
157     uint32_t CPUType = TargetObjectWriter->getCPUType();
158     return CPUType == MachO::CPU_TYPE_X86_64;
159   }
160
161   /// @}
162
163   void writeHeader(MachO::HeaderFileType Type, unsigned NumLoadCommands,
164                    unsigned LoadCommandsSize, bool SubsectionsViaSymbols);
165
166   /// Write a segment load command.
167   ///
168   /// \param NumSections The number of sections in this segment.
169   /// \param SectionDataSize The total size of the sections.
170   void writeSegmentLoadCommand(StringRef Name, unsigned NumSections,
171                                uint64_t VMAddr, uint64_t VMSize,
172                                uint64_t SectionDataStartOffset,
173                                uint64_t SectionDataSize, uint32_t MaxProt,
174                                uint32_t InitProt);
175
176   void writeSection(const MCAsmLayout &Layout, const MCSection &Sec,
177                     uint64_t VMAddr, uint64_t FileOffset, unsigned Flags,
178                     uint64_t RelocationsStart, unsigned NumRelocations);
179
180   void writeSymtabLoadCommand(uint32_t SymbolOffset, uint32_t NumSymbols,
181                               uint32_t StringTableOffset,
182                               uint32_t StringTableSize);
183
184   void writeDysymtabLoadCommand(
185       uint32_t FirstLocalSymbol, uint32_t NumLocalSymbols,
186       uint32_t FirstExternalSymbol, uint32_t NumExternalSymbols,
187       uint32_t FirstUndefinedSymbol, uint32_t NumUndefinedSymbols,
188       uint32_t IndirectSymbolOffset, uint32_t NumIndirectSymbols);
189
190   void writeNlist(MachSymbolData &MSD, const MCAsmLayout &Layout);
191
192   void writeLinkeditLoadCommand(uint32_t Type, uint32_t DataOffset,
193                                 uint32_t DataSize);
194
195   void writeLinkerOptionsLoadCommand(const std::vector<std::string> &Options);
196
197   // FIXME: We really need to improve the relocation validation. Basically, we
198   // want to implement a separate computation which evaluates the relocation
199   // entry as the linker would, and verifies that the resultant fixup value is
200   // exactly what the encoder wanted. This will catch several classes of
201   // problems:
202   //
203   //  - Relocation entry bugs, the two algorithms are unlikely to have the same
204   //    exact bug.
205   //
206   //  - Relaxation issues, where we forget to relax something.
207   //
208   //  - Input errors, where something cannot be correctly encoded. 'as' allows
209   //    these through in many cases.
210
211   // Add a relocation to be output in the object file. At the time this is
212   // called, the symbol indexes are not know, so if the relocation refers
213   // to a symbol it should be passed as \p RelSymbol so that it can be updated
214   // afterwards. If the relocation doesn't refer to a symbol, nullptr should be
215   // used.
216   void addRelocation(const MCSymbol *RelSymbol, const MCSection *Sec,
217                      MachO::any_relocation_info &MRE) {
218     RelAndSymbol P(RelSymbol, MRE);
219     Relocations[Sec].push_back(P);
220   }
221
222   void recordScatteredRelocation(const MCAssembler &Asm,
223                                  const MCAsmLayout &Layout,
224                                  const MCFragment *Fragment,
225                                  const MCFixup &Fixup, MCValue Target,
226                                  unsigned Log2Size, uint64_t &FixedValue);
227
228   void recordTLVPRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
229                             const MCFragment *Fragment, const MCFixup &Fixup,
230                             MCValue Target, uint64_t &FixedValue);
231
232   void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
233                         const MCFragment *Fragment, const MCFixup &Fixup,
234                         MCValue Target, bool &IsPCRel,
235                         uint64_t &FixedValue) override;
236
237   void bindIndirectSymbols(MCAssembler &Asm);
238
239   /// Compute the symbol table data.
240   void computeSymbolTable(MCAssembler &Asm,
241                           std::vector<MachSymbolData> &LocalSymbolData,
242                           std::vector<MachSymbolData> &ExternalSymbolData,
243                           std::vector<MachSymbolData> &UndefinedSymbolData);
244
245   void computeSectionAddresses(const MCAssembler &Asm,
246                                const MCAsmLayout &Layout);
247
248   void executePostLayoutBinding(MCAssembler &Asm,
249                                 const MCAsmLayout &Layout) override;
250
251   bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
252                                               const MCSymbol &A,
253                                               const MCSymbol &B,
254                                               bool InSet) const override;
255
256   bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
257                                               const MCSymbol &SymA,
258                                               const MCFragment &FB, bool InSet,
259                                               bool IsPCRel) const override;
260
261   void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
262 };
263
264 /// Construct a new Mach-O writer instance.
265 ///
266 /// This routine takes ownership of the target writer subclass.
267 ///
268 /// \param MOTW - The target specific Mach-O writer subclass.
269 /// \param OS - The stream to write to.
270 /// \returns The constructed object writer.
271 MCObjectWriter *createMachObjectWriter(MCMachObjectTargetWriter *MOTW,
272                                        raw_pwrite_stream &OS,
273                                        bool IsLittleEndian);
274
275 } // End llvm namespace
276
277 #endif