blob: d8729bdbc4bbd017779b190328ca840628d2f5a2 [file] [log] [blame]
Chris Lattner2c52b792010-07-11 22:07:02 +00001//===-- llvm/MC/WinCOFFObjectWriter.cpp -------------------------*- 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// This file contains an implementation of a Win32 COFF object file writer.
11//
12//===----------------------------------------------------------------------===//
13
Rafael Espindola908d2ed2011-12-24 02:14:02 +000014#include "llvm/MC/MCWinCOFFObjectWriter.h"
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000015#include "llvm/ADT/DenseMap.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000016#include "llvm/ADT/STLExtras.h"
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000017#include "llvm/ADT/StringMap.h"
18#include "llvm/ADT/StringRef.h"
Nico Riecka37acf72013-07-06 12:13:10 +000019#include "llvm/ADT/Twine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/MC/MCAsmLayout.h"
21#include "llvm/MC/MCAssembler.h"
22#include "llvm/MC/MCContext.h"
23#include "llvm/MC/MCExpr.h"
24#include "llvm/MC/MCObjectWriter.h"
25#include "llvm/MC/MCSection.h"
26#include "llvm/MC/MCSectionCOFF.h"
27#include "llvm/MC/MCSymbol.h"
28#include "llvm/MC/MCValue.h"
Hans Wennborgf26bfc12014-09-29 22:43:20 +000029#include "llvm/MC/StringTableBuilder.h"
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000030#include "llvm/Support/COFF.h"
31#include "llvm/Support/Debug.h"
Hans Wennborgba80b5d2014-09-28 00:22:27 +000032#include "llvm/Support/Endian.h"
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000033#include "llvm/Support/ErrorHandling.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000034#include "llvm/Support/TimeValue.h"
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000035#include <cstdio>
36
Chris Lattner2c52b792010-07-11 22:07:02 +000037using namespace llvm;
38
Chandler Carruthf58e3762014-04-22 03:04:17 +000039#define DEBUG_TYPE "WinCOFFObjectWriter"
40
Chris Lattner2c52b792010-07-11 22:07:02 +000041namespace {
Dmitri Gribenko226fea52013-01-13 16:01:15 +000042typedef SmallString<COFF::NameSize> name;
Chris Lattner2c52b792010-07-11 22:07:02 +000043
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000044enum AuxiliaryType {
45 ATFunctionDefinition,
46 ATbfAndefSymbol,
47 ATWeakExternal,
48 ATFile,
49 ATSectionDefinition
50};
Chris Lattner2c52b792010-07-11 22:07:02 +000051
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000052struct AuxSymbol {
53 AuxiliaryType AuxType;
54 COFF::Auxiliary Aux;
55};
Chris Lattner2c52b792010-07-11 22:07:02 +000056
Michael J. Spencerd6283772010-09-27 08:58:26 +000057class COFFSymbol;
58class COFFSection;
59
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000060class COFFSymbol {
61public:
62 COFF::symbol Data;
Chris Lattner2c52b792010-07-11 22:07:02 +000063
Dmitri Gribenko226fea52013-01-13 16:01:15 +000064 typedef SmallVector<AuxSymbol, 1> AuxiliarySymbols;
Chris Lattner2c52b792010-07-11 22:07:02 +000065
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000066 name Name;
Michael J. Spencerce2e5352010-09-27 21:17:39 +000067 int Index;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000068 AuxiliarySymbols Aux;
69 COFFSymbol *Other;
Michael J. Spencerd6283772010-09-27 08:58:26 +000070 COFFSection *Section;
71 int Relocations;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000072
73 MCSymbolData const *MCData;
74
Dmitri Gribenko226fea52013-01-13 16:01:15 +000075 COFFSymbol(StringRef name);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000076 void set_name_offset(uint32_t Offset);
Michael J. Spencerd6283772010-09-27 08:58:26 +000077
78 bool should_keep() const;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000079};
80
81// This class contains staging data for a COFF relocation entry.
82struct COFFRelocation {
83 COFF::relocation Data;
84 COFFSymbol *Symb;
85
Craig Topperbb694de2014-04-13 04:57:38 +000086 COFFRelocation() : Symb(nullptr) {}
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000087 static size_t size() { return COFF::RelocationSize; }
88};
89
90typedef std::vector<COFFRelocation> relocations;
91
92class COFFSection {
93public:
94 COFF::section Header;
95
96 std::string Name;
Michael J. Spencerce2e5352010-09-27 21:17:39 +000097 int Number;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000098 MCSectionData const *MCData;
Michael J. Spencerd6283772010-09-27 08:58:26 +000099 COFFSymbol *Symbol;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000100 relocations Relocations;
101
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000102 COFFSection(StringRef name);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000103 static size_t size();
104};
105
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000106class WinCOFFObjectWriter : public MCObjectWriter {
107public:
108
David Blaikief564ab62014-04-15 05:25:03 +0000109 typedef std::vector<std::unique_ptr<COFFSymbol>> symbols;
110 typedef std::vector<std::unique_ptr<COFFSection>> sections;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000111
Michael J. Spencer17990d52010-10-16 08:25:57 +0000112 typedef DenseMap<MCSymbol const *, COFFSymbol *> symbol_map;
113 typedef DenseMap<MCSection const *, COFFSection *> section_map;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000114
Ahmed Charles56440fd2014-03-06 05:51:42 +0000115 std::unique_ptr<MCWinCOFFObjectTargetWriter> TargetObjectWriter;
Rafael Espindola908d2ed2011-12-24 02:14:02 +0000116
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000117 // Root level file contents.
118 COFF::header Header;
119 sections Sections;
120 symbols Symbols;
Hans Wennborgf26bfc12014-09-29 22:43:20 +0000121 StringTableBuilder Strings;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000122
123 // Maps used during object file creation.
124 section_map SectionMap;
125 symbol_map SymbolMap;
126
David Majnemer4d571592014-09-15 19:42:42 +0000127 bool UseBigObj;
128
Rafael Espindola908d2ed2011-12-24 02:14:02 +0000129 WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW, raw_ostream &OS);
Yaron Kerencca43c12014-09-16 21:31:04 +0000130
131 void reset() override {
132 memset(&Header, 0, sizeof(Header));
133 Header.Machine = TargetObjectWriter->getMachine();
134 Sections.clear();
135 Symbols.clear();
136 Strings.clear();
137 SectionMap.clear();
138 SymbolMap.clear();
139 MCObjectWriter::reset();
140 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000141
Michael J. Spencer17990d52010-10-16 08:25:57 +0000142 COFFSymbol *createSymbol(StringRef Name);
143 COFFSymbol *GetOrCreateCOFFSymbol(const MCSymbol * Symbol);
144 COFFSection *createSection(StringRef Name);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000145
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000146 template <typename object_t, typename list_t>
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000147 object_t *createCOFFEntity(StringRef Name, list_t &List);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000148
149 void DefineSection(MCSectionData const &SectionData);
Reid Klecknerc1e76212013-09-17 23:18:05 +0000150 void DefineSymbol(MCSymbolData const &SymbolData, MCAssembler &Assembler,
151 const MCAsmLayout &Layout);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000152
Hans Wennborgf26bfc12014-09-29 22:43:20 +0000153 void SetSymbolName(COFFSymbol &S);
154 void SetSectionName(COFFSection &S);
Michael J. Spencerd6283772010-09-27 08:58:26 +0000155
David Majnemer299674e2014-07-13 04:31:19 +0000156 bool ExportSymbol(const MCSymbol &Symbol, MCAssembler &Asm);
Reid Kleckner8b2ad2a2013-11-18 23:08:12 +0000157
Michael J. Spencerd6283772010-09-27 08:58:26 +0000158 bool IsPhysicalSection(COFFSection *S);
159
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000160 // Entity writing methods.
161
162 void WriteFileHeader(const COFF::header &Header);
David Blaikief564ab62014-04-15 05:25:03 +0000163 void WriteSymbol(const COFFSymbol &S);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000164 void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
165 void WriteSectionHeader(const COFF::section &S);
166 void WriteRelocation(const COFF::relocation &R);
167
168 // MCObjectWriter interface implementation.
169
Craig Topper34a61bc2014-03-08 07:02:02 +0000170 void ExecutePostLayoutBinding(MCAssembler &Asm,
171 const MCAsmLayout &Layout) override;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000172
David Majnemer2cc4bc772014-11-11 08:43:57 +0000173 bool IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
174 const MCSymbolData &DataA,
175 const MCFragment &FB, bool InSet,
176 bool IsPCRel) const override;
177
Rafael Espindola26585542015-01-19 21:11:14 +0000178 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
Craig Topper34a61bc2014-03-08 07:02:02 +0000179 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindola5904e122014-03-29 06:26:49 +0000180 MCValue Target, bool &IsPCRel,
181 uint64_t &FixedValue) override;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000182
Craig Topper34a61bc2014-03-08 07:02:02 +0000183 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000184};
Chris Lattner2c52b792010-07-11 22:07:02 +0000185}
186
Hans Wennborgba80b5d2014-09-28 00:22:27 +0000187static inline void write_uint32_le(void *Data, uint32_t Value) {
188 support::endian::write<uint32_t, support::little, support::unaligned>(Data,
189 Value);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000190}
191
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000192//------------------------------------------------------------------------------
193// Symbol class implementation
194
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000195COFFSymbol::COFFSymbol(StringRef name)
Michael J. Spencerd6283772010-09-27 08:58:26 +0000196 : Name(name.begin(), name.end())
Craig Topperbb694de2014-04-13 04:57:38 +0000197 , Other(nullptr)
198 , Section(nullptr)
Michael J. Spencerd6283772010-09-27 08:58:26 +0000199 , Relocations(0)
Craig Topperbb694de2014-04-13 04:57:38 +0000200 , MCData(nullptr) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000201 memset(&Data, 0, sizeof(Data));
202}
203
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000204// In the case that the name does not fit within 8 bytes, the offset
205// into the string table is stored in the last 4 bytes instead, leaving
206// the first 4 bytes as 0.
207void COFFSymbol::set_name_offset(uint32_t Offset) {
208 write_uint32_le(Data.Name + 0, 0);
209 write_uint32_le(Data.Name + 4, Offset);
210}
211
Michael J. Spencerd6283772010-09-27 08:58:26 +0000212/// logic to decide if the symbol should be reported in the symbol table
213bool COFFSymbol::should_keep() const {
214 // no section means its external, keep it
Craig Topperbb694de2014-04-13 04:57:38 +0000215 if (!Section)
Michael J. Spencerd6283772010-09-27 08:58:26 +0000216 return true;
217
218 // if it has relocations pointing at it, keep it
219 if (Relocations > 0) {
220 assert(Section->Number != -1 && "Sections with relocations must be real!");
221 return true;
222 }
223
224 // if the section its in is being droped, drop it
225 if (Section->Number == -1)
226 return false;
227
228 // if it is the section symbol, keep it
229 if (Section->Symbol == this)
230 return true;
231
232 // if its temporary, drop it
233 if (MCData && MCData->getSymbol().isTemporary())
234 return false;
235
236 // otherwise, keep it
237 return true;
238}
239
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000240//------------------------------------------------------------------------------
241// Section class implementation
242
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000243COFFSection::COFFSection(StringRef name)
Michael J. Spencerd6283772010-09-27 08:58:26 +0000244 : Name(name)
Craig Topperbb694de2014-04-13 04:57:38 +0000245 , MCData(nullptr)
246 , Symbol(nullptr) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000247 memset(&Header, 0, sizeof(Header));
248}
249
250size_t COFFSection::size() {
251 return COFF::SectionSize;
252}
253
254//------------------------------------------------------------------------------
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000255// WinCOFFObjectWriter class implementation
256
Rafael Espindola908d2ed2011-12-24 02:14:02 +0000257WinCOFFObjectWriter::WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
258 raw_ostream &OS)
David Majnemer4d571592014-09-15 19:42:42 +0000259 : MCObjectWriter(OS, true), TargetObjectWriter(MOTW) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000260 memset(&Header, 0, sizeof(Header));
Michael J. Spencer377aa202010-08-21 05:58:13 +0000261
Rafael Espindola908d2ed2011-12-24 02:14:02 +0000262 Header.Machine = TargetObjectWriter->getMachine();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000263}
264
Michael J. Spencer17990d52010-10-16 08:25:57 +0000265COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000266 return createCOFFEntity<COFFSymbol>(Name, Symbols);
267}
268
Yaron Keren56919ef2014-12-04 08:30:39 +0000269COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol *Symbol) {
Michael J. Spencer17990d52010-10-16 08:25:57 +0000270 symbol_map::iterator i = SymbolMap.find(Symbol);
271 if (i != SymbolMap.end())
272 return i->second;
Yaron Keren56919ef2014-12-04 08:30:39 +0000273 COFFSymbol *RetSymbol =
274 createCOFFEntity<COFFSymbol>(Symbol->getName(), Symbols);
Michael J. Spencer17990d52010-10-16 08:25:57 +0000275 SymbolMap[Symbol] = RetSymbol;
276 return RetSymbol;
277}
278
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000279COFFSection *WinCOFFObjectWriter::createSection(StringRef Name) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000280 return createCOFFEntity<COFFSection>(Name, Sections);
281}
282
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000283/// A template used to lookup or create a symbol/section, and initialize it if
284/// needed.
285template <typename object_t, typename list_t>
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000286object_t *WinCOFFObjectWriter::createCOFFEntity(StringRef Name,
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000287 list_t &List) {
David Blaikief564ab62014-04-15 05:25:03 +0000288 List.push_back(make_unique<object_t>(Name));
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000289
David Blaikief564ab62014-04-15 05:25:03 +0000290 return List.back().get();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000291}
292
293/// This function takes a section data object from the assembler
294/// and creates the associated COFF section staging object.
295void WinCOFFObjectWriter::DefineSection(MCSectionData const &SectionData) {
Michael J. Spencerbe52c622010-10-09 11:00:37 +0000296 assert(SectionData.getSection().getVariant() == MCSection::SV_COFF
Alp Tokerf907b892013-12-05 05:44:44 +0000297 && "Got non-COFF section in the COFF backend!");
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000298 // FIXME: Not sure how to verify this (at least in a debug build).
299 MCSectionCOFF const &Sec =
300 static_cast<MCSectionCOFF const &>(SectionData.getSection());
301
302 COFFSection *coff_section = createSection(Sec.getSectionName());
303 COFFSymbol *coff_symbol = createSymbol(Sec.getSectionName());
Rafael Espindola0766ae02014-06-06 19:26:12 +0000304 if (Sec.getSelection() != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
305 if (const MCSymbol *S = Sec.getCOMDATSymbol()) {
306 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S);
307 if (COMDATSymbol->Section)
308 report_fatal_error("two sections have the same comdat");
309 COMDATSymbol->Section = coff_section;
310 }
311 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000312
Michael J. Spencerd6283772010-09-27 08:58:26 +0000313 coff_section->Symbol = coff_symbol;
314 coff_symbol->Section = coff_section;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000315 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000316
317 // In this case the auxiliary symbol is a Section Definition.
318 coff_symbol->Aux.resize(1);
319 memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
320 coff_symbol->Aux[0].AuxType = ATSectionDefinition;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000321 coff_symbol->Aux[0].Aux.SectionDefinition.Selection = Sec.getSelection();
322
323 coff_section->Header.Characteristics = Sec.getCharacteristics();
324
325 uint32_t &Characteristics = coff_section->Header.Characteristics;
326 switch (SectionData.getAlignment()) {
327 case 1: Characteristics |= COFF::IMAGE_SCN_ALIGN_1BYTES; break;
328 case 2: Characteristics |= COFF::IMAGE_SCN_ALIGN_2BYTES; break;
329 case 4: Characteristics |= COFF::IMAGE_SCN_ALIGN_4BYTES; break;
330 case 8: Characteristics |= COFF::IMAGE_SCN_ALIGN_8BYTES; break;
331 case 16: Characteristics |= COFF::IMAGE_SCN_ALIGN_16BYTES; break;
332 case 32: Characteristics |= COFF::IMAGE_SCN_ALIGN_32BYTES; break;
333 case 64: Characteristics |= COFF::IMAGE_SCN_ALIGN_64BYTES; break;
334 case 128: Characteristics |= COFF::IMAGE_SCN_ALIGN_128BYTES; break;
335 case 256: Characteristics |= COFF::IMAGE_SCN_ALIGN_256BYTES; break;
336 case 512: Characteristics |= COFF::IMAGE_SCN_ALIGN_512BYTES; break;
337 case 1024: Characteristics |= COFF::IMAGE_SCN_ALIGN_1024BYTES; break;
338 case 2048: Characteristics |= COFF::IMAGE_SCN_ALIGN_2048BYTES; break;
339 case 4096: Characteristics |= COFF::IMAGE_SCN_ALIGN_4096BYTES; break;
340 case 8192: Characteristics |= COFF::IMAGE_SCN_ALIGN_8192BYTES; break;
341 default:
342 llvm_unreachable("unsupported section alignment");
343 }
344
345 // Bind internal COFF section to MC section.
346 coff_section->MCData = &SectionData;
Michael J. Spencer17990d52010-10-16 08:25:57 +0000347 SectionMap[&SectionData.getSection()] = coff_section;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000348}
349
Rafael Espindolaff68cb72014-05-01 00:10:17 +0000350static uint64_t getSymbolValue(const MCSymbolData &Data,
351 const MCAsmLayout &Layout) {
352 if (Data.isCommon() && Data.isExternal())
353 return Data.getCommonSize();
354
355 uint64_t Res;
356 if (!Layout.getSymbolOffset(&Data, Res))
357 return 0;
358
359 return Res;
360}
361
David Majnemera9bdb322014-04-08 22:33:40 +0000362/// This function takes a symbol data object from the assembler
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000363/// and creates the associated COFF symbol staging object.
Peter Collingbourne89886872013-04-22 18:48:56 +0000364void WinCOFFObjectWriter::DefineSymbol(MCSymbolData const &SymbolData,
Reid Klecknerc1e76212013-09-17 23:18:05 +0000365 MCAssembler &Assembler,
366 const MCAsmLayout &Layout) {
Peter Collingbourne89886872013-04-22 18:48:56 +0000367 MCSymbol const &Symbol = SymbolData.getSymbol();
Michael J. Spencer54b24e12013-01-29 22:10:07 +0000368 COFFSymbol *coff_symbol = GetOrCreateCOFFSymbol(&Symbol);
Peter Collingbourne89886872013-04-22 18:48:56 +0000369 SymbolMap[&Symbol] = coff_symbol;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000370
Michael J. Spencer17990d52010-10-16 08:25:57 +0000371 if (SymbolData.getFlags() & COFF::SF_WeakExternal) {
372 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
373
Michael J. Spencer54b24e12013-01-29 22:10:07 +0000374 if (Symbol.isVariable()) {
Peter Collingbourne89886872013-04-22 18:48:56 +0000375 const MCSymbolRefExpr *SymRef =
376 dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
Michael J. Spencer17990d52010-10-16 08:25:57 +0000377
Peter Collingbourne89886872013-04-22 18:48:56 +0000378 if (!SymRef)
379 report_fatal_error("Weak externals may only alias symbols");
Michael J. Spencer17990d52010-10-16 08:25:57 +0000380
Peter Collingbourne89886872013-04-22 18:48:56 +0000381 coff_symbol->Other = GetOrCreateCOFFSymbol(&SymRef->getSymbol());
Michael J. Spencer17990d52010-10-16 08:25:57 +0000382 } else {
383 std::string WeakName = std::string(".weak.")
Michael J. Spencer54b24e12013-01-29 22:10:07 +0000384 + Symbol.getName().str()
Michael J. Spencer17990d52010-10-16 08:25:57 +0000385 + ".default";
386 COFFSymbol *WeakDefault = createSymbol(WeakName);
387 WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
388 WeakDefault->Data.StorageClass = COFF::IMAGE_SYM_CLASS_EXTERNAL;
389 WeakDefault->Data.Type = 0;
390 WeakDefault->Data.Value = 0;
391 coff_symbol->Other = WeakDefault;
392 }
393
394 // Setup the Weak External auxiliary symbol.
395 coff_symbol->Aux.resize(1);
396 memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
397 coff_symbol->Aux[0].AuxType = ATWeakExternal;
398 coff_symbol->Aux[0].Aux.WeakExternal.TagIndex = 0;
399 coff_symbol->Aux[0].Aux.WeakExternal.Characteristics =
400 COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY;
Peter Collingbourne89886872013-04-22 18:48:56 +0000401
402 coff_symbol->MCData = &SymbolData;
403 } else {
Rafael Espindolaea9f9d42014-05-01 19:02:03 +0000404 const MCSymbolData &ResSymData = Assembler.getSymbolData(Symbol);
Rafael Espindola575f79a2014-05-01 13:37:57 +0000405 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
Rafael Espindolaff68cb72014-05-01 00:10:17 +0000406 coff_symbol->Data.Value = getSymbolValue(ResSymData, Layout);
Reid Klecknerc1e76212013-09-17 23:18:05 +0000407
Peter Collingbourne89886872013-04-22 18:48:56 +0000408 coff_symbol->Data.Type = (ResSymData.getFlags() & 0x0000FFFF) >> 0;
409 coff_symbol->Data.StorageClass = (ResSymData.getFlags() & 0x00FF0000) >> 16;
410
411 // If no storage class was specified in the streamer, define it here.
412 if (coff_symbol->Data.StorageClass == 0) {
David Majnemer299674e2014-07-13 04:31:19 +0000413 bool IsExternal =
414 ResSymData.isExternal() ||
415 (!ResSymData.getFragment() && !ResSymData.getSymbol().isVariable());
Peter Collingbourne89886872013-04-22 18:48:56 +0000416
David Majnemer299674e2014-07-13 04:31:19 +0000417 coff_symbol->Data.StorageClass = IsExternal
418 ? COFF::IMAGE_SYM_CLASS_EXTERNAL
419 : COFF::IMAGE_SYM_CLASS_STATIC;
Peter Collingbourne89886872013-04-22 18:48:56 +0000420 }
421
Rafael Espindola575f79a2014-05-01 13:37:57 +0000422 if (!Base) {
Reid Klecknerc1e76212013-09-17 23:18:05 +0000423 coff_symbol->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
Rafael Espindola575f79a2014-05-01 13:37:57 +0000424 } else {
425 const MCSymbolData &BaseData = Assembler.getSymbolData(*Base);
Benjamin Kramer3e67db92014-10-11 15:07:21 +0000426 if (BaseData.getFragment()) {
Rafael Espindola0766ae02014-06-06 19:26:12 +0000427 COFFSection *Sec =
Benjamin Kramer3e67db92014-10-11 15:07:21 +0000428 SectionMap[&BaseData.getFragment()->getParent()->getSection()];
Rafael Espindola0766ae02014-06-06 19:26:12 +0000429
430 if (coff_symbol->Section && coff_symbol->Section != Sec)
431 report_fatal_error("conflicting sections for symbol");
432
433 coff_symbol->Section = Sec;
434 }
Rafael Espindola575f79a2014-05-01 13:37:57 +0000435 }
Peter Collingbourne89886872013-04-22 18:48:56 +0000436
437 coff_symbol->MCData = &ResSymData;
Michael J. Spencer17990d52010-10-16 08:25:57 +0000438 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000439}
440
Nico Rieck01143f92014-02-25 09:50:40 +0000441// Maximum offsets for different string table entry encodings.
442static const unsigned Max6DecimalOffset = 999999;
443static const unsigned Max7DecimalOffset = 9999999;
444static const uint64_t MaxBase64Offset = 0xFFFFFFFFFULL; // 64^6, including 0
445
Nico Rieck9d2c15e2014-02-22 16:12:20 +0000446// Encode a string table entry offset in base 64, padded to 6 chars, and
447// prefixed with a double slash: '//AAAAAA', '//AAAAAB', ...
448// Buffer must be at least 8 bytes large. No terminating null appended.
449static void encodeBase64StringEntry(char* Buffer, uint64_t Value) {
Nico Rieck01143f92014-02-25 09:50:40 +0000450 assert(Value > Max7DecimalOffset && Value <= MaxBase64Offset &&
Nico Rieck9d2c15e2014-02-22 16:12:20 +0000451 "Illegal section name encoding for value");
452
453 static const char Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
454 "abcdefghijklmnopqrstuvwxyz"
455 "0123456789+/";
456
457 Buffer[0] = '/';
458 Buffer[1] = '/';
459
460 char* Ptr = Buffer + 7;
461 for (unsigned i = 0; i < 6; ++i) {
462 unsigned Rem = Value % 64;
463 Value /= 64;
464 *(Ptr--) = Alphabet[Rem];
465 }
466}
467
Hans Wennborgf26bfc12014-09-29 22:43:20 +0000468void WinCOFFObjectWriter::SetSectionName(COFFSection &S) {
Michael J. Spencerd6283772010-09-27 08:58:26 +0000469 if (S.Name.size() > COFF::NameSize) {
Hans Wennborgf26bfc12014-09-29 22:43:20 +0000470 uint64_t StringTableEntry = Strings.getOffset(S.Name);
Michael J. Spencerd6283772010-09-27 08:58:26 +0000471
Nico Rieck01143f92014-02-25 09:50:40 +0000472 if (StringTableEntry <= Max6DecimalOffset) {
Nico Rieck2c9c89b2013-07-29 12:30:12 +0000473 std::sprintf(S.Header.Name, "/%d", unsigned(StringTableEntry));
Nico Rieck01143f92014-02-25 09:50:40 +0000474 } else if (StringTableEntry <= Max7DecimalOffset) {
Nico Rieck2c9c89b2013-07-29 12:30:12 +0000475 // With seven digits, we have to skip the terminating null. Because
476 // sprintf always appends it, we use a larger temporary buffer.
477 char buffer[9] = { };
478 std::sprintf(buffer, "/%d", unsigned(StringTableEntry));
479 std::memcpy(S.Header.Name, buffer, 8);
Nico Rieck01143f92014-02-25 09:50:40 +0000480 } else if (StringTableEntry <= MaxBase64Offset) {
Nico Rieck9d2c15e2014-02-22 16:12:20 +0000481 // Starting with 10,000,000, offsets are encoded as base64.
482 encodeBase64StringEntry(S.Header.Name, StringTableEntry);
Nico Rieck2c9c89b2013-07-29 12:30:12 +0000483 } else {
Nico Rieck9d2c15e2014-02-22 16:12:20 +0000484 report_fatal_error("COFF string table is greater than 64 GB.");
Nico Rieck2c9c89b2013-07-29 12:30:12 +0000485 }
Michael J. Spencerd6283772010-09-27 08:58:26 +0000486 } else
487 std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
Michael J. Spencerd6283772010-09-27 08:58:26 +0000488}
489
Hans Wennborgf26bfc12014-09-29 22:43:20 +0000490void WinCOFFObjectWriter::SetSymbolName(COFFSymbol &S) {
491 if (S.Name.size() > COFF::NameSize)
492 S.set_name_offset(Strings.getOffset(S.Name));
493 else
Michael J. Spencerd6283772010-09-27 08:58:26 +0000494 std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
Michael J. Spencerd6283772010-09-27 08:58:26 +0000495}
496
David Majnemer299674e2014-07-13 04:31:19 +0000497bool WinCOFFObjectWriter::ExportSymbol(const MCSymbol &Symbol,
Reid Kleckner8b2ad2a2013-11-18 23:08:12 +0000498 MCAssembler &Asm) {
499 // This doesn't seem to be right. Strings referred to from the .data section
500 // need symbols so they can be linked to code in the .text section right?
501
David Majnemer299674e2014-07-13 04:31:19 +0000502 // return Asm.isSymbolLinkerVisible(Symbol);
503
504 // Non-temporary labels should always be visible to the linker.
505 if (!Symbol.isTemporary())
506 return true;
507
508 // Absolute temporary labels are never visible.
509 if (!Symbol.isInSection())
510 return false;
Reid Kleckner8b2ad2a2013-11-18 23:08:12 +0000511
512 // For now, all non-variable symbols are exported,
513 // the linker will sort the rest out for us.
David Majnemer299674e2014-07-13 04:31:19 +0000514 return !Symbol.isVariable();
Reid Kleckner8b2ad2a2013-11-18 23:08:12 +0000515}
516
Michael J. Spencerd6283772010-09-27 08:58:26 +0000517bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
518 return (S->Header.Characteristics
519 & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000520}
521
522//------------------------------------------------------------------------------
523// entity writing methods
524
525void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
David Majnemer4d571592014-09-15 19:42:42 +0000526 if (UseBigObj) {
527 WriteLE16(COFF::IMAGE_FILE_MACHINE_UNKNOWN);
528 WriteLE16(0xFFFF);
529 WriteLE16(COFF::BigObjHeader::MinBigObjectVersion);
530 WriteLE16(Header.Machine);
531 WriteLE32(Header.TimeDateStamp);
532 for (uint8_t MagicChar : COFF::BigObjMagic)
533 Write8(MagicChar);
David Majnemer15f7ed92014-09-15 20:28:38 +0000534 WriteLE32(0);
535 WriteLE32(0);
536 WriteLE32(0);
537 WriteLE32(0);
David Majnemer4d571592014-09-15 19:42:42 +0000538 WriteLE32(Header.NumberOfSections);
539 WriteLE32(Header.PointerToSymbolTable);
540 WriteLE32(Header.NumberOfSymbols);
541 } else {
542 WriteLE16(Header.Machine);
543 WriteLE16(static_cast<int16_t>(Header.NumberOfSections));
544 WriteLE32(Header.TimeDateStamp);
545 WriteLE32(Header.PointerToSymbolTable);
546 WriteLE32(Header.NumberOfSymbols);
547 WriteLE16(Header.SizeOfOptionalHeader);
548 WriteLE16(Header.Characteristics);
549 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000550}
551
David Blaikief564ab62014-04-15 05:25:03 +0000552void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol &S) {
553 WriteBytes(StringRef(S.Data.Name, COFF::NameSize));
554 WriteLE32(S.Data.Value);
David Majnemer4d571592014-09-15 19:42:42 +0000555 if (UseBigObj)
556 WriteLE32(S.Data.SectionNumber);
557 else
558 WriteLE16(static_cast<int16_t>(S.Data.SectionNumber));
David Blaikief564ab62014-04-15 05:25:03 +0000559 WriteLE16(S.Data.Type);
560 Write8(S.Data.StorageClass);
561 Write8(S.Data.NumberOfAuxSymbols);
562 WriteAuxiliarySymbols(S.Aux);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000563}
564
565void WinCOFFObjectWriter::WriteAuxiliarySymbols(
566 const COFFSymbol::AuxiliarySymbols &S) {
567 for(COFFSymbol::AuxiliarySymbols::const_iterator i = S.begin(), e = S.end();
568 i != e; ++i) {
569 switch(i->AuxType) {
570 case ATFunctionDefinition:
571 WriteLE32(i->Aux.FunctionDefinition.TagIndex);
572 WriteLE32(i->Aux.FunctionDefinition.TotalSize);
573 WriteLE32(i->Aux.FunctionDefinition.PointerToLinenumber);
574 WriteLE32(i->Aux.FunctionDefinition.PointerToNextFunction);
575 WriteZeros(sizeof(i->Aux.FunctionDefinition.unused));
David Majnemer4d571592014-09-15 19:42:42 +0000576 if (UseBigObj)
577 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000578 break;
579 case ATbfAndefSymbol:
580 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused1));
581 WriteLE16(i->Aux.bfAndefSymbol.Linenumber);
582 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused2));
583 WriteLE32(i->Aux.bfAndefSymbol.PointerToNextFunction);
584 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused3));
David Majnemer4d571592014-09-15 19:42:42 +0000585 if (UseBigObj)
586 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000587 break;
588 case ATWeakExternal:
589 WriteLE32(i->Aux.WeakExternal.TagIndex);
590 WriteLE32(i->Aux.WeakExternal.Characteristics);
591 WriteZeros(sizeof(i->Aux.WeakExternal.unused));
David Majnemer4d571592014-09-15 19:42:42 +0000592 if (UseBigObj)
593 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000594 break;
595 case ATFile:
David Majnemer4d571592014-09-15 19:42:42 +0000596 WriteBytes(
597 StringRef(reinterpret_cast<const char *>(&i->Aux),
598 UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size));
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000599 break;
600 case ATSectionDefinition:
601 WriteLE32(i->Aux.SectionDefinition.Length);
602 WriteLE16(i->Aux.SectionDefinition.NumberOfRelocations);
603 WriteLE16(i->Aux.SectionDefinition.NumberOfLinenumbers);
604 WriteLE32(i->Aux.SectionDefinition.CheckSum);
David Majnemer4d571592014-09-15 19:42:42 +0000605 WriteLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number));
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000606 Write8(i->Aux.SectionDefinition.Selection);
607 WriteZeros(sizeof(i->Aux.SectionDefinition.unused));
David Majnemer4d571592014-09-15 19:42:42 +0000608 WriteLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number >> 16));
609 if (UseBigObj)
610 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000611 break;
612 }
613 }
614}
615
616void WinCOFFObjectWriter::WriteSectionHeader(const COFF::section &S) {
617 WriteBytes(StringRef(S.Name, COFF::NameSize));
618
619 WriteLE32(S.VirtualSize);
620 WriteLE32(S.VirtualAddress);
621 WriteLE32(S.SizeOfRawData);
622 WriteLE32(S.PointerToRawData);
623 WriteLE32(S.PointerToRelocations);
624 WriteLE32(S.PointerToLineNumbers);
625 WriteLE16(S.NumberOfRelocations);
626 WriteLE16(S.NumberOfLineNumbers);
627 WriteLE32(S.Characteristics);
628}
629
630void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
631 WriteLE32(R.VirtualAddress);
632 WriteLE32(R.SymbolTableIndex);
633 WriteLE16(R.Type);
Chris Lattner2c52b792010-07-11 22:07:02 +0000634}
635
636////////////////////////////////////////////////////////////////////////////////
637// MCObjectWriter interface implementations
638
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000639void WinCOFFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
640 const MCAsmLayout &Layout) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000641 // "Define" each section & symbol. This creates section & symbol
Michael J. Spencerd6283772010-09-27 08:58:26 +0000642 // entries in the staging area.
Yaron Keren56919ef2014-12-04 08:30:39 +0000643 for (const auto &Section : Asm)
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000644 DefineSection(Section);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000645
David Blaikie583a31c2014-04-18 18:24:25 +0000646 for (MCSymbolData &SD : Asm.symbols())
David Majnemer299674e2014-07-13 04:31:19 +0000647 if (ExportSymbol(SD.getSymbol(), Asm))
David Blaikie583a31c2014-04-18 18:24:25 +0000648 DefineSymbol(SD, Asm, Layout);
Chris Lattner2c52b792010-07-11 22:07:02 +0000649}
650
David Majnemer2cc4bc772014-11-11 08:43:57 +0000651bool WinCOFFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
652 const MCAssembler &Asm, const MCSymbolData &DataA, const MCFragment &FB,
653 bool InSet, bool IsPCRel) const {
654 // MS LINK expects to be able to replace all references to a function with a
655 // thunk to implement their /INCREMENTAL feature. Make sure we don't optimize
656 // away any relocations to functions.
657 if ((((DataA.getFlags() & COFF::SF_TypeMask) >> COFF::SF_TypeShift) >>
658 COFF::SCT_COMPLEX_TYPE_SHIFT) == COFF::IMAGE_SYM_DTYPE_FUNCTION)
659 return false;
660 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, DataA, FB,
661 InSet, IsPCRel);
662}
663
Rafael Espindola26585542015-01-19 21:11:14 +0000664void WinCOFFObjectWriter::RecordRelocation(
665 MCAssembler &Asm, const MCAsmLayout &Layout, const MCFragment *Fragment,
666 const MCFixup &Fixup, MCValue Target, bool &IsPCRel, uint64_t &FixedValue) {
Craig Topperbb694de2014-04-13 04:57:38 +0000667 assert(Target.getSymA() && "Relocation must reference a symbol!");
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000668
Reid Klecknerdae7b4e2013-07-15 19:41:21 +0000669 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
670 const MCSymbol &A = Symbol.AliasedSymbol();
Timur Iskhodzhanov3e4ac4e2014-01-30 21:13:05 +0000671 if (!Asm.hasSymbolData(A))
672 Asm.getContext().FatalError(
673 Fixup.getLoc(),
674 Twine("symbol '") + A.getName() + "' can not be undefined");
675
David Blaikie908f4d42014-04-24 16:59:40 +0000676 const MCSymbolData &A_SD = Asm.getSymbolData(A);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000677
678 MCSectionData const *SectionData = Fragment->getParent();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000679
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000680 // Mark this symbol as requiring an entry in the symbol table.
Michael J. Spencer17990d52010-10-16 08:25:57 +0000681 assert(SectionMap.find(&SectionData->getSection()) != SectionMap.end() &&
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000682 "Section must already have been defined in ExecutePostLayoutBinding!");
Michael J. Spencer17990d52010-10-16 08:25:57 +0000683 assert(SymbolMap.find(&A_SD.getSymbol()) != SymbolMap.end() &&
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000684 "Symbol must already have been defined in ExecutePostLayoutBinding!");
685
Michael J. Spencer17990d52010-10-16 08:25:57 +0000686 COFFSection *coff_section = SectionMap[&SectionData->getSection()];
687 COFFSymbol *coff_symbol = SymbolMap[&A_SD.getSymbol()];
Rafael Espindolaed164772011-04-20 14:01:45 +0000688 const MCSymbolRefExpr *SymB = Target.getSymB();
David Majnemera45a1762014-01-06 07:39:46 +0000689 bool CrossSection = false;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000690
David Majnemera45a1762014-01-06 07:39:46 +0000691 if (SymB) {
692 const MCSymbol *B = &SymB->getSymbol();
David Blaikie908f4d42014-04-24 16:59:40 +0000693 const MCSymbolData &B_SD = Asm.getSymbolData(*B);
David Majnemera45a1762014-01-06 07:39:46 +0000694 if (!B_SD.getFragment())
695 Asm.getContext().FatalError(
696 Fixup.getLoc(),
697 Twine("symbol '") + B->getName() +
698 "' can not be undefined in a subtraction expression");
699
700 if (!A_SD.getFragment())
701 Asm.getContext().FatalError(
702 Fixup.getLoc(),
703 Twine("symbol '") + Symbol.getName() +
704 "' can not be undefined in a subtraction expression");
705
706 CrossSection = &Symbol.getSection() != &B->getSection();
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000707
Rafael Espindolac3dc4862011-04-21 18:36:50 +0000708 // Offset of the symbol in the section
709 int64_t a = Layout.getSymbolOffset(&B_SD);
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000710
Nico Weber7f654a82014-11-11 01:13:42 +0000711 // Offset of the relocation in the section
Rafael Espindolac3dc4862011-04-21 18:36:50 +0000712 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
713
714 FixedValue = b - a;
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000715 // In the case where we have SymbA and SymB, we just need to store the delta
716 // between the two symbols. Update FixedValue to account for the delta, and
717 // skip recording the relocation.
Rafael Espindolaed164772011-04-20 14:01:45 +0000718 if (!CrossSection)
719 return;
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000720 } else {
721 FixedValue = Target.getConstant();
722 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000723
724 COFFRelocation Reloc;
725
Daniel Dunbar727be432010-07-31 21:08:54 +0000726 Reloc.Data.SymbolTableIndex = 0;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000727 Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
Michael J. Spencerd6283772010-09-27 08:58:26 +0000728
Michael J. Spencera65d17a2010-10-05 19:48:12 +0000729 // Turn relocations for temporary symbols into section relocations.
Rafael Espindolaed164772011-04-20 14:01:45 +0000730 if (coff_symbol->MCData->getSymbol().isTemporary() || CrossSection) {
Michael J. Spencerd6283772010-09-27 08:58:26 +0000731 Reloc.Symb = coff_symbol->Section->Symbol;
Benjamin Kramer3e67db92014-10-11 15:07:21 +0000732 FixedValue += Layout.getFragmentOffset(coff_symbol->MCData->getFragment()) +
733 coff_symbol->MCData->getOffset();
Michael J. Spencerd6283772010-09-27 08:58:26 +0000734 } else
735 Reloc.Symb = coff_symbol;
736
737 ++Reloc.Symb->Relocations;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000738
739 Reloc.Data.VirtualAddress += Fixup.getOffset();
Nico Rieck1da45292013-04-10 23:28:17 +0000740 Reloc.Data.Type = TargetObjectWriter->getRelocType(Target, Fixup,
741 CrossSection);
Rafael Espindolae61724a2011-12-22 22:21:47 +0000742
743 // FIXME: Can anyone explain what this does other than adjust for the size
744 // of the offset?
Saleem Abdulrasool2c080512014-04-13 20:47:55 +0000745 if ((Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 &&
746 Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32) ||
747 (Header.Machine == COFF::IMAGE_FILE_MACHINE_I386 &&
748 Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32))
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000749 FixedValue += 4;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000750
Saleem Abdulrasool84b952b2014-04-27 03:48:22 +0000751 if (Header.Machine == COFF::IMAGE_FILE_MACHINE_ARMNT) {
752 switch (Reloc.Data.Type) {
753 case COFF::IMAGE_REL_ARM_ABSOLUTE:
754 case COFF::IMAGE_REL_ARM_ADDR32:
755 case COFF::IMAGE_REL_ARM_ADDR32NB:
756 case COFF::IMAGE_REL_ARM_TOKEN:
757 case COFF::IMAGE_REL_ARM_SECTION:
758 case COFF::IMAGE_REL_ARM_SECREL:
759 break;
760 case COFF::IMAGE_REL_ARM_BRANCH11:
761 case COFF::IMAGE_REL_ARM_BLX11:
762 // IMAGE_REL_ARM_BRANCH11 and IMAGE_REL_ARM_BLX11 are only used for
763 // pre-ARMv7, which implicitly rules it out of ARMNT (it would be valid
764 // for Windows CE).
765 case COFF::IMAGE_REL_ARM_BRANCH24:
766 case COFF::IMAGE_REL_ARM_BLX24:
767 case COFF::IMAGE_REL_ARM_MOV32A:
768 // IMAGE_REL_ARM_BRANCH24, IMAGE_REL_ARM_BLX24, IMAGE_REL_ARM_MOV32A are
769 // only used for ARM mode code, which is documented as being unsupported
Alp Tokerbeaca192014-05-15 01:52:21 +0000770 // by Windows on ARM. Empirical proof indicates that masm is able to
Saleem Abdulrasool84b952b2014-04-27 03:48:22 +0000771 // generate the relocations however the rest of the MSVC toolchain is
772 // unable to handle it.
773 llvm_unreachable("unsupported relocation");
774 break;
775 case COFF::IMAGE_REL_ARM_MOV32T:
776 break;
777 case COFF::IMAGE_REL_ARM_BRANCH20T:
778 case COFF::IMAGE_REL_ARM_BRANCH24T:
779 case COFF::IMAGE_REL_ARM_BLX23T:
780 // IMAGE_REL_BRANCH20T, IMAGE_REL_ARM_BRANCH24T, IMAGE_REL_ARM_BLX23T all
781 // perform a 4 byte adjustment to the relocation. Relative branches are
782 // offset by 4 on ARM, however, because there is no RELA relocations, all
783 // branches are offset by 4.
784 FixedValue = FixedValue + 4;
785 break;
786 }
787 }
788
Saleem Abdulrasool54bed122014-05-21 23:17:50 +0000789 if (TargetObjectWriter->recordRelocation(Fixup))
790 coff_section->Relocations.push_back(Reloc);
Chris Lattner2c52b792010-07-11 22:07:02 +0000791}
792
Rafael Espindolabce26a12010-10-05 15:11:03 +0000793void WinCOFFObjectWriter::WriteObject(MCAssembler &Asm,
Chris Lattner2c52b792010-07-11 22:07:02 +0000794 const MCAsmLayout &Layout) {
David Majnemer4d571592014-09-15 19:42:42 +0000795 size_t SectionsSize = Sections.size();
796 if (SectionsSize > static_cast<size_t>(INT32_MAX))
797 report_fatal_error(
798 "PE COFF object files can't have more than 2147483647 sections");
Michael J. Spencerd6283772010-09-27 08:58:26 +0000799
David Majnemer4d571592014-09-15 19:42:42 +0000800 // Assign symbol and section indexes and offsets.
801 int32_t NumberOfSections = static_cast<int32_t>(SectionsSize);
802
803 UseBigObj = NumberOfSections > COFF::MaxNumberOfSections16;
804
805 DenseMap<COFFSection *, int32_t> SectionIndices(
806 NextPowerOf2(NumberOfSections));
Hans Wennborgf26bfc12014-09-29 22:43:20 +0000807
808 // Assign section numbers.
David Majnemer4d571592014-09-15 19:42:42 +0000809 size_t Number = 1;
David Majnemer9ab5ff12014-08-28 04:02:50 +0000810 for (const auto &Section : Sections) {
David Majnemer4d571592014-09-15 19:42:42 +0000811 SectionIndices[Section.get()] = Number;
Hans Wennborgf26bfc12014-09-29 22:43:20 +0000812 Section->Number = Number;
813 Section->Symbol->Data.SectionNumber = Number;
814 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = Number;
David Majnemer4d571592014-09-15 19:42:42 +0000815 ++Number;
Michael J. Spencerd6283772010-09-27 08:58:26 +0000816 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000817
David Majnemer4d571592014-09-15 19:42:42 +0000818 Header.NumberOfSections = NumberOfSections;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000819 Header.NumberOfSymbols = 0;
820
David Majnemer4d571592014-09-15 19:42:42 +0000821 for (auto FI = Asm.file_names_begin(), FE = Asm.file_names_end();
822 FI != FE; ++FI) {
823 // round up to calculate the number of auxiliary symbols required
824 unsigned SymbolSize = UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size;
825 unsigned Count = (FI->size() + SymbolSize - 1) / SymbolSize;
826
827 COFFSymbol *file = createSymbol(".file");
828 file->Data.SectionNumber = COFF::IMAGE_SYM_DEBUG;
829 file->Data.StorageClass = COFF::IMAGE_SYM_CLASS_FILE;
830 file->Aux.resize(Count);
831
832 unsigned Offset = 0;
833 unsigned Length = FI->size();
Yaron Keren56919ef2014-12-04 08:30:39 +0000834 for (auto &Aux : file->Aux) {
David Majnemer4d571592014-09-15 19:42:42 +0000835 Aux.AuxType = ATFile;
836
837 if (Length > SymbolSize) {
838 memcpy(&Aux.Aux, FI->c_str() + Offset, SymbolSize);
839 Length = Length - SymbolSize;
840 } else {
841 memcpy(&Aux.Aux, FI->c_str() + Offset, Length);
842 memset((char *)&Aux.Aux + Length, 0, SymbolSize - Length);
843 break;
844 }
845
846 Offset += SymbolSize;
847 }
848 }
849
David Majnemer9ab5ff12014-08-28 04:02:50 +0000850 for (auto &Symbol : Symbols) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000851 // Update section number & offset for symbols that have them.
Rafael Espindola575f79a2014-05-01 13:37:57 +0000852 if (Symbol->Section)
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000853 Symbol->Data.SectionNumber = Symbol->Section->Number;
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000854 if (Symbol->should_keep()) {
Hans Wennborgf26bfc12014-09-29 22:43:20 +0000855 Symbol->Index = Header.NumberOfSymbols++;
Michael J. Spencerd6283772010-09-27 08:58:26 +0000856 // Update auxiliary symbol info.
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000857 Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
858 Header.NumberOfSymbols += Symbol->Data.NumberOfAuxSymbols;
Michael J. Spencerd6283772010-09-27 08:58:26 +0000859 } else
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000860 Symbol->Index = -1;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000861 }
862
Hans Wennborgf26bfc12014-09-29 22:43:20 +0000863 // Build string table.
864 for (const auto &S : Sections)
865 if (S->Name.size() > COFF::NameSize)
866 Strings.add(S->Name);
867 for (const auto &S : Symbols)
868 if (S->should_keep() && S->Name.size() > COFF::NameSize)
869 Strings.add(S->Name);
870 Strings.finalize(StringTableBuilder::WinCOFF);
871
872 // Set names.
873 for (const auto &S : Sections)
874 SetSectionName(*S);
875 for (auto &S : Symbols)
876 if (S->should_keep())
877 SetSymbolName(*S);
878
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000879 // Fixup weak external references.
Yaron Keren56919ef2014-12-04 08:30:39 +0000880 for (auto &Symbol : Symbols) {
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000881 if (Symbol->Other) {
882 assert(Symbol->Index != -1);
883 assert(Symbol->Aux.size() == 1 && "Symbol must contain one aux symbol!");
884 assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000885 "Symbol's aux symbol must be a Weak External!");
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000886 Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->Index;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000887 }
888 }
889
Nico Riecka37acf72013-07-06 12:13:10 +0000890 // Fixup associative COMDAT sections.
Yaron Keren56919ef2014-12-04 08:30:39 +0000891 for (auto &Section : Sections) {
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000892 if (Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
Nico Riecka37acf72013-07-06 12:13:10 +0000893 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
894 continue;
895
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000896 const MCSectionCOFF &MCSec =
897 static_cast<const MCSectionCOFF &>(Section->MCData->getSection());
Nico Riecka37acf72013-07-06 12:13:10 +0000898
Rafael Espindola0766ae02014-06-06 19:26:12 +0000899 const MCSymbol *COMDAT = MCSec.getCOMDATSymbol();
900 assert(COMDAT);
901 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(COMDAT);
902 assert(COMDATSymbol);
903 COFFSection *Assoc = COMDATSymbol->Section;
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000904 if (!Assoc)
Rafael Espindola0766ae02014-06-06 19:26:12 +0000905 report_fatal_error(
906 Twine("Missing associated COMDAT section for section ") +
907 MCSec.getSectionName());
Nico Riecka37acf72013-07-06 12:13:10 +0000908
909 // Skip this section if the associated section is unused.
910 if (Assoc->Number == -1)
911 continue;
912
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000913 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = SectionIndices[Assoc];
Nico Riecka37acf72013-07-06 12:13:10 +0000914 }
915
916
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000917 // Assign file offsets to COFF object file structures.
918
919 unsigned offset = 0;
920
David Majnemer4d571592014-09-15 19:42:42 +0000921 if (UseBigObj)
922 offset += COFF::Header32Size;
923 else
924 offset += COFF::Header16Size;
Michael J. Spencerd6283772010-09-27 08:58:26 +0000925 offset += COFF::SectionSize * Header.NumberOfSections;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000926
Yaron Keren56919ef2014-12-04 08:30:39 +0000927 for (const auto &Section : Asm) {
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000928 COFFSection *Sec = SectionMap[&Section.getSection()];
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000929
Michael J. Spencerd6283772010-09-27 08:58:26 +0000930 if (Sec->Number == -1)
931 continue;
932
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000933 Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(&Section);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000934
Michael J. Spencerd6283772010-09-27 08:58:26 +0000935 if (IsPhysicalSection(Sec)) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000936 Sec->Header.PointerToRawData = offset;
937
938 offset += Sec->Header.SizeOfRawData;
939 }
940
941 if (Sec->Relocations.size() > 0) {
Michael J. Spencerfa39bd22012-03-15 09:03:03 +0000942 bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
943
944 if (RelocationsOverflow) {
David Majnemer9ab5ff12014-08-28 04:02:50 +0000945 // Signal overflow by setting NumberOfRelocations to max value. Actual
Michael J. Spencerfa39bd22012-03-15 09:03:03 +0000946 // size is found in reloc #0. Microsoft tools understand this.
947 Sec->Header.NumberOfRelocations = 0xffff;
948 } else {
949 Sec->Header.NumberOfRelocations = Sec->Relocations.size();
950 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000951 Sec->Header.PointerToRelocations = offset;
952
Michael J. Spencerfa39bd22012-03-15 09:03:03 +0000953 if (RelocationsOverflow) {
954 // Reloc #0 will contain actual count, so make room for it.
955 offset += COFF::RelocationSize;
956 }
957
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000958 offset += COFF::RelocationSize * Sec->Relocations.size();
959
Yaron Keren56919ef2014-12-04 08:30:39 +0000960 for (auto &Relocation : Sec->Relocations) {
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000961 assert(Relocation.Symb->Index != -1);
962 Relocation.Data.SymbolTableIndex = Relocation.Symb->Index;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000963 }
964 }
965
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000966 assert(Sec->Symbol->Aux.size() == 1 &&
967 "Section's symbol must have one aux!");
Michael J. Spencerd6283772010-09-27 08:58:26 +0000968 AuxSymbol &Aux = Sec->Symbol->Aux[0];
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000969 assert(Aux.AuxType == ATSectionDefinition &&
970 "Section's symbol's aux symbol must be a Section Definition!");
971 Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
972 Aux.Aux.SectionDefinition.NumberOfRelocations =
973 Sec->Header.NumberOfRelocations;
974 Aux.Aux.SectionDefinition.NumberOfLinenumbers =
975 Sec->Header.NumberOfLineNumbers;
976 }
977
978 Header.PointerToSymbolTable = offset;
979
Rafael Espindola5ac4ad22013-12-04 02:26:54 +0000980 // We want a deterministic output. It looks like GNU as also writes 0 in here.
Rafael Espindola9201e6b2013-12-04 02:02:55 +0000981 Header.TimeDateStamp = 0;
Michael J. Spencera6cfbeb2010-08-03 04:43:33 +0000982
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000983 // Write it all to disk...
984 WriteFileHeader(Header);
985
986 {
987 sections::iterator i, ie;
988 MCAssembler::const_iterator j, je;
989
Yaron Keren56919ef2014-12-04 08:30:39 +0000990 for (auto &Section : Sections) {
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000991 if (Section->Number != -1) {
992 if (Section->Relocations.size() >= 0xffff)
993 Section->Header.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL;
994 WriteSectionHeader(Section->Header);
Michael J. Spencerfa39bd22012-03-15 09:03:03 +0000995 }
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000996 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000997
998 for (i = Sections.begin(), ie = Sections.end(),
999 j = Asm.begin(), je = Asm.end();
Michael J. Spencerd6283772010-09-27 08:58:26 +00001000 (i != ie) && (j != je); ++i, ++j) {
1001
1002 if ((*i)->Number == -1)
1003 continue;
1004
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001005 if ((*i)->Header.PointerToRawData != 0) {
1006 assert(OS.tell() == (*i)->Header.PointerToRawData &&
1007 "Section::PointerToRawData is insane!");
1008
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001009 Asm.writeSectionData(j, Layout);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001010 }
1011
1012 if ((*i)->Relocations.size() > 0) {
1013 assert(OS.tell() == (*i)->Header.PointerToRelocations &&
1014 "Section::PointerToRelocations is insane!");
1015
Michael J. Spencerfa39bd22012-03-15 09:03:03 +00001016 if ((*i)->Relocations.size() >= 0xffff) {
1017 // In case of overflow, write actual relocation count as first
1018 // relocation. Including the synthetic reloc itself (+ 1).
1019 COFF::relocation r;
1020 r.VirtualAddress = (*i)->Relocations.size() + 1;
1021 r.SymbolTableIndex = 0;
1022 r.Type = 0;
1023 WriteRelocation(r);
1024 }
1025
Yaron Keren56919ef2014-12-04 08:30:39 +00001026 for (const auto &Relocation : (*i)->Relocations)
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +00001027 WriteRelocation(Relocation.Data);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001028 } else
1029 assert((*i)->Header.PointerToRelocations == 0 &&
1030 "Section::PointerToRelocations is insane!");
1031 }
1032 }
1033
1034 assert(OS.tell() == Header.PointerToSymbolTable &&
1035 "Header::PointerToSymbolTable is insane!");
1036
Yaron Keren56919ef2014-12-04 08:30:39 +00001037 for (auto &Symbol : Symbols)
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +00001038 if (Symbol->Index != -1)
1039 WriteSymbol(*Symbol);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001040
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001041 OS.write(Strings.data().data(), Strings.data().size());
Chris Lattner2c52b792010-07-11 22:07:02 +00001042}
1043
Rafael Espindola908d2ed2011-12-24 02:14:02 +00001044MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_) :
1045 Machine(Machine_) {
1046}
1047
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +00001048// Pin the vtable to this file.
1049void MCWinCOFFObjectTargetWriter::anchor() {}
1050
Chris Lattner2c52b792010-07-11 22:07:02 +00001051//------------------------------------------------------------------------------
1052// WinCOFFObjectWriter factory function
1053
1054namespace llvm {
Rafael Espindola908d2ed2011-12-24 02:14:02 +00001055 MCObjectWriter *createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
1056 raw_ostream &OS) {
1057 return new WinCOFFObjectWriter(MOTW, OS);
Chris Lattner2c52b792010-07-11 22:07:02 +00001058 }
Michael J. Spencerc2129372010-07-26 03:01:28 +00001059}