blob: 90233c7c1a006c748ac5369b9f90642f0b5e2f01 [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"
16#include "llvm/ADT/StringMap.h"
17#include "llvm/ADT/StringRef.h"
David Blaikief564ab62014-04-15 05:25:03 +000018#include "llvm/ADT/STLExtras.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"
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000029#include "llvm/Support/COFF.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/ErrorHandling.h"
Michael J. Spencer447762d2010-11-29 18:16:10 +000032#include "llvm/Support/TimeValue.h"
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000033#include <cstdio>
34
Chris Lattner2c52b792010-07-11 22:07:02 +000035using namespace llvm;
36
Chandler Carruthf58e3762014-04-22 03:04:17 +000037#define DEBUG_TYPE "WinCOFFObjectWriter"
38
Chris Lattner2c52b792010-07-11 22:07:02 +000039namespace {
Dmitri Gribenko226fea52013-01-13 16:01:15 +000040typedef SmallString<COFF::NameSize> name;
Chris Lattner2c52b792010-07-11 22:07:02 +000041
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000042enum AuxiliaryType {
43 ATFunctionDefinition,
44 ATbfAndefSymbol,
45 ATWeakExternal,
46 ATFile,
47 ATSectionDefinition
48};
Chris Lattner2c52b792010-07-11 22:07:02 +000049
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000050struct AuxSymbol {
51 AuxiliaryType AuxType;
52 COFF::Auxiliary Aux;
53};
Chris Lattner2c52b792010-07-11 22:07:02 +000054
Michael J. Spencerd6283772010-09-27 08:58:26 +000055class COFFSymbol;
56class COFFSection;
57
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000058class COFFSymbol {
59public:
60 COFF::symbol Data;
Chris Lattner2c52b792010-07-11 22:07:02 +000061
Dmitri Gribenko226fea52013-01-13 16:01:15 +000062 typedef SmallVector<AuxSymbol, 1> AuxiliarySymbols;
Chris Lattner2c52b792010-07-11 22:07:02 +000063
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000064 name Name;
Michael J. Spencerce2e5352010-09-27 21:17:39 +000065 int Index;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000066 AuxiliarySymbols Aux;
67 COFFSymbol *Other;
Michael J. Spencerd6283772010-09-27 08:58:26 +000068 COFFSection *Section;
69 int Relocations;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000070
71 MCSymbolData const *MCData;
72
Dmitri Gribenko226fea52013-01-13 16:01:15 +000073 COFFSymbol(StringRef name);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000074 void set_name_offset(uint32_t Offset);
Michael J. Spencerd6283772010-09-27 08:58:26 +000075
76 bool should_keep() const;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000077};
78
79// This class contains staging data for a COFF relocation entry.
80struct COFFRelocation {
81 COFF::relocation Data;
82 COFFSymbol *Symb;
83
Craig Topperbb694de2014-04-13 04:57:38 +000084 COFFRelocation() : Symb(nullptr) {}
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000085 static size_t size() { return COFF::RelocationSize; }
86};
87
88typedef std::vector<COFFRelocation> relocations;
89
90class COFFSection {
91public:
92 COFF::section Header;
93
94 std::string Name;
Michael J. Spencerce2e5352010-09-27 21:17:39 +000095 int Number;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000096 MCSectionData const *MCData;
Michael J. Spencerd6283772010-09-27 08:58:26 +000097 COFFSymbol *Symbol;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000098 relocations Relocations;
99
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000100 COFFSection(StringRef name);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000101 static size_t size();
102};
103
104// This class holds the COFF string table.
105class StringTable {
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000106 typedef StringMap<size_t> map;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000107 map Map;
108
109 void update_length();
110public:
111 std::vector<char> Data;
112
113 StringTable();
114 size_t size() const;
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000115 size_t insert(StringRef String);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000116};
117
118class WinCOFFObjectWriter : public MCObjectWriter {
119public:
120
David Blaikief564ab62014-04-15 05:25:03 +0000121 typedef std::vector<std::unique_ptr<COFFSymbol>> symbols;
122 typedef std::vector<std::unique_ptr<COFFSection>> sections;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000123
Michael J. Spencer17990d52010-10-16 08:25:57 +0000124 typedef DenseMap<MCSymbol const *, COFFSymbol *> symbol_map;
125 typedef DenseMap<MCSection const *, COFFSection *> section_map;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000126
Ahmed Charles56440fd2014-03-06 05:51:42 +0000127 std::unique_ptr<MCWinCOFFObjectTargetWriter> TargetObjectWriter;
Rafael Espindola908d2ed2011-12-24 02:14:02 +0000128
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000129 // Root level file contents.
130 COFF::header Header;
131 sections Sections;
132 symbols Symbols;
133 StringTable Strings;
134
135 // Maps used during object file creation.
136 section_map SectionMap;
137 symbol_map SymbolMap;
138
David Majnemer4d571592014-09-15 19:42:42 +0000139 bool UseBigObj;
140
Rafael Espindola908d2ed2011-12-24 02:14:02 +0000141 WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW, raw_ostream &OS);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000142
Michael J. Spencer17990d52010-10-16 08:25:57 +0000143 COFFSymbol *createSymbol(StringRef Name);
144 COFFSymbol *GetOrCreateCOFFSymbol(const MCSymbol * Symbol);
145 COFFSection *createSection(StringRef Name);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000146
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000147 template <typename object_t, typename list_t>
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000148 object_t *createCOFFEntity(StringRef Name, list_t &List);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000149
150 void DefineSection(MCSectionData const &SectionData);
Reid Klecknerc1e76212013-09-17 23:18:05 +0000151 void DefineSymbol(MCSymbolData const &SymbolData, MCAssembler &Assembler,
152 const MCAsmLayout &Layout);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000153
Michael J. Spencerd6283772010-09-27 08:58:26 +0000154 void MakeSymbolReal(COFFSymbol &S, size_t Index);
155 void MakeSectionReal(COFFSection &S, size_t Number);
156
David Majnemer299674e2014-07-13 04:31:19 +0000157 bool ExportSymbol(const MCSymbol &Symbol, MCAssembler &Asm);
Reid Kleckner8b2ad2a2013-11-18 23:08:12 +0000158
Michael J. Spencerd6283772010-09-27 08:58:26 +0000159 bool IsPhysicalSection(COFFSection *S);
160
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000161 // Entity writing methods.
162
163 void WriteFileHeader(const COFF::header &Header);
David Blaikief564ab62014-04-15 05:25:03 +0000164 void WriteSymbol(const COFFSymbol &S);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000165 void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
166 void WriteSectionHeader(const COFF::section &S);
167 void WriteRelocation(const COFF::relocation &R);
168
169 // MCObjectWriter interface implementation.
170
Craig Topper34a61bc2014-03-08 07:02:02 +0000171 void ExecutePostLayoutBinding(MCAssembler &Asm,
172 const MCAsmLayout &Layout) override;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000173
Craig Topper34a61bc2014-03-08 07:02:02 +0000174 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
175 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindola5904e122014-03-29 06:26:49 +0000176 MCValue Target, bool &IsPCRel,
177 uint64_t &FixedValue) override;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000178
Craig Topper34a61bc2014-03-08 07:02:02 +0000179 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000180};
Chris Lattner2c52b792010-07-11 22:07:02 +0000181}
182
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000183static inline void write_uint32_le(void *Data, uint32_t const &Value) {
184 uint8_t *Ptr = reinterpret_cast<uint8_t *>(Data);
185 Ptr[0] = (Value & 0x000000FF) >> 0;
186 Ptr[1] = (Value & 0x0000FF00) >> 8;
187 Ptr[2] = (Value & 0x00FF0000) >> 16;
188 Ptr[3] = (Value & 0xFF000000) >> 24;
189}
190
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000191//------------------------------------------------------------------------------
192// Symbol class implementation
193
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000194COFFSymbol::COFFSymbol(StringRef name)
Michael J. Spencerd6283772010-09-27 08:58:26 +0000195 : Name(name.begin(), name.end())
Craig Topperbb694de2014-04-13 04:57:38 +0000196 , Other(nullptr)
197 , Section(nullptr)
Michael J. Spencerd6283772010-09-27 08:58:26 +0000198 , Relocations(0)
Craig Topperbb694de2014-04-13 04:57:38 +0000199 , MCData(nullptr) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000200 memset(&Data, 0, sizeof(Data));
201}
202
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000203// In the case that the name does not fit within 8 bytes, the offset
204// into the string table is stored in the last 4 bytes instead, leaving
205// the first 4 bytes as 0.
206void COFFSymbol::set_name_offset(uint32_t Offset) {
207 write_uint32_le(Data.Name + 0, 0);
208 write_uint32_le(Data.Name + 4, Offset);
209}
210
Michael J. Spencerd6283772010-09-27 08:58:26 +0000211/// logic to decide if the symbol should be reported in the symbol table
212bool COFFSymbol::should_keep() const {
213 // no section means its external, keep it
Craig Topperbb694de2014-04-13 04:57:38 +0000214 if (!Section)
Michael J. Spencerd6283772010-09-27 08:58:26 +0000215 return true;
216
217 // if it has relocations pointing at it, keep it
218 if (Relocations > 0) {
219 assert(Section->Number != -1 && "Sections with relocations must be real!");
220 return true;
221 }
222
223 // if the section its in is being droped, drop it
224 if (Section->Number == -1)
225 return false;
226
227 // if it is the section symbol, keep it
228 if (Section->Symbol == this)
229 return true;
230
231 // if its temporary, drop it
232 if (MCData && MCData->getSymbol().isTemporary())
233 return false;
234
235 // otherwise, keep it
236 return true;
237}
238
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000239//------------------------------------------------------------------------------
240// Section class implementation
241
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000242COFFSection::COFFSection(StringRef name)
Michael J. Spencerd6283772010-09-27 08:58:26 +0000243 : Name(name)
Craig Topperbb694de2014-04-13 04:57:38 +0000244 , MCData(nullptr)
245 , Symbol(nullptr) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000246 memset(&Header, 0, sizeof(Header));
247}
248
249size_t COFFSection::size() {
250 return COFF::SectionSize;
251}
252
253//------------------------------------------------------------------------------
254// StringTable class implementation
255
256/// Write the length of the string table into Data.
257/// The length of the string table includes uint32 length header.
258void StringTable::update_length() {
259 write_uint32_le(&Data.front(), Data.size());
260}
261
262StringTable::StringTable() {
263 // The string table data begins with the length of the entire string table
264 // including the length header. Allocate space for this header.
265 Data.resize(4);
Michael J. Spencer5ca95bc2011-11-08 19:52:32 +0000266 update_length();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000267}
268
269size_t StringTable::size() const {
270 return Data.size();
271}
272
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000273/// Add String to the table iff it is not already there.
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000274/// @returns the index into the string table where the string is now located.
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000275size_t StringTable::insert(StringRef String) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000276 map::iterator i = Map.find(String);
277
278 if (i != Map.end())
279 return i->second;
280
281 size_t Offset = Data.size();
282
283 // Insert string data into string table.
284 Data.insert(Data.end(), String.begin(), String.end());
285 Data.push_back('\0');
286
287 // Put a reference to it in the map.
288 Map[String] = Offset;
289
290 // Update the internal length field.
291 update_length();
292
293 return Offset;
294}
295
296//------------------------------------------------------------------------------
297// WinCOFFObjectWriter class implementation
298
Rafael Espindola908d2ed2011-12-24 02:14:02 +0000299WinCOFFObjectWriter::WinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
300 raw_ostream &OS)
David Majnemer4d571592014-09-15 19:42:42 +0000301 : MCObjectWriter(OS, true), TargetObjectWriter(MOTW) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000302 memset(&Header, 0, sizeof(Header));
Michael J. Spencer377aa202010-08-21 05:58:13 +0000303
Rafael Espindola908d2ed2011-12-24 02:14:02 +0000304 Header.Machine = TargetObjectWriter->getMachine();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000305}
306
Michael J. Spencer17990d52010-10-16 08:25:57 +0000307COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000308 return createCOFFEntity<COFFSymbol>(Name, Symbols);
309}
310
Michael J. Spencer17990d52010-10-16 08:25:57 +0000311COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol * Symbol){
312 symbol_map::iterator i = SymbolMap.find(Symbol);
313 if (i != SymbolMap.end())
314 return i->second;
315 COFFSymbol *RetSymbol
316 = createCOFFEntity<COFFSymbol>(Symbol->getName(), Symbols);
317 SymbolMap[Symbol] = RetSymbol;
318 return RetSymbol;
319}
320
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000321COFFSection *WinCOFFObjectWriter::createSection(StringRef Name) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000322 return createCOFFEntity<COFFSection>(Name, Sections);
323}
324
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000325/// A template used to lookup or create a symbol/section, and initialize it if
326/// needed.
327template <typename object_t, typename list_t>
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000328object_t *WinCOFFObjectWriter::createCOFFEntity(StringRef Name,
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000329 list_t &List) {
David Blaikief564ab62014-04-15 05:25:03 +0000330 List.push_back(make_unique<object_t>(Name));
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000331
David Blaikief564ab62014-04-15 05:25:03 +0000332 return List.back().get();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000333}
334
335/// This function takes a section data object from the assembler
336/// and creates the associated COFF section staging object.
337void WinCOFFObjectWriter::DefineSection(MCSectionData const &SectionData) {
Michael J. Spencerbe52c622010-10-09 11:00:37 +0000338 assert(SectionData.getSection().getVariant() == MCSection::SV_COFF
Alp Tokerf907b892013-12-05 05:44:44 +0000339 && "Got non-COFF section in the COFF backend!");
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000340 // FIXME: Not sure how to verify this (at least in a debug build).
341 MCSectionCOFF const &Sec =
342 static_cast<MCSectionCOFF const &>(SectionData.getSection());
343
344 COFFSection *coff_section = createSection(Sec.getSectionName());
345 COFFSymbol *coff_symbol = createSymbol(Sec.getSectionName());
Rafael Espindola0766ae02014-06-06 19:26:12 +0000346 if (Sec.getSelection() != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
347 if (const MCSymbol *S = Sec.getCOMDATSymbol()) {
348 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S);
349 if (COMDATSymbol->Section)
350 report_fatal_error("two sections have the same comdat");
351 COMDATSymbol->Section = coff_section;
352 }
353 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000354
Michael J. Spencerd6283772010-09-27 08:58:26 +0000355 coff_section->Symbol = coff_symbol;
356 coff_symbol->Section = coff_section;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000357 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000358
359 // In this case the auxiliary symbol is a Section Definition.
360 coff_symbol->Aux.resize(1);
361 memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
362 coff_symbol->Aux[0].AuxType = ATSectionDefinition;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000363 coff_symbol->Aux[0].Aux.SectionDefinition.Selection = Sec.getSelection();
364
365 coff_section->Header.Characteristics = Sec.getCharacteristics();
366
367 uint32_t &Characteristics = coff_section->Header.Characteristics;
368 switch (SectionData.getAlignment()) {
369 case 1: Characteristics |= COFF::IMAGE_SCN_ALIGN_1BYTES; break;
370 case 2: Characteristics |= COFF::IMAGE_SCN_ALIGN_2BYTES; break;
371 case 4: Characteristics |= COFF::IMAGE_SCN_ALIGN_4BYTES; break;
372 case 8: Characteristics |= COFF::IMAGE_SCN_ALIGN_8BYTES; break;
373 case 16: Characteristics |= COFF::IMAGE_SCN_ALIGN_16BYTES; break;
374 case 32: Characteristics |= COFF::IMAGE_SCN_ALIGN_32BYTES; break;
375 case 64: Characteristics |= COFF::IMAGE_SCN_ALIGN_64BYTES; break;
376 case 128: Characteristics |= COFF::IMAGE_SCN_ALIGN_128BYTES; break;
377 case 256: Characteristics |= COFF::IMAGE_SCN_ALIGN_256BYTES; break;
378 case 512: Characteristics |= COFF::IMAGE_SCN_ALIGN_512BYTES; break;
379 case 1024: Characteristics |= COFF::IMAGE_SCN_ALIGN_1024BYTES; break;
380 case 2048: Characteristics |= COFF::IMAGE_SCN_ALIGN_2048BYTES; break;
381 case 4096: Characteristics |= COFF::IMAGE_SCN_ALIGN_4096BYTES; break;
382 case 8192: Characteristics |= COFF::IMAGE_SCN_ALIGN_8192BYTES; break;
383 default:
384 llvm_unreachable("unsupported section alignment");
385 }
386
387 // Bind internal COFF section to MC section.
388 coff_section->MCData = &SectionData;
Michael J. Spencer17990d52010-10-16 08:25:57 +0000389 SectionMap[&SectionData.getSection()] = coff_section;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000390}
391
Rafael Espindolaff68cb72014-05-01 00:10:17 +0000392static uint64_t getSymbolValue(const MCSymbolData &Data,
393 const MCAsmLayout &Layout) {
394 if (Data.isCommon() && Data.isExternal())
395 return Data.getCommonSize();
396
397 uint64_t Res;
398 if (!Layout.getSymbolOffset(&Data, Res))
399 return 0;
400
401 return Res;
402}
403
David Majnemera9bdb322014-04-08 22:33:40 +0000404/// This function takes a symbol data object from the assembler
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000405/// and creates the associated COFF symbol staging object.
Peter Collingbourne89886872013-04-22 18:48:56 +0000406void WinCOFFObjectWriter::DefineSymbol(MCSymbolData const &SymbolData,
Reid Klecknerc1e76212013-09-17 23:18:05 +0000407 MCAssembler &Assembler,
408 const MCAsmLayout &Layout) {
Peter Collingbourne89886872013-04-22 18:48:56 +0000409 MCSymbol const &Symbol = SymbolData.getSymbol();
Michael J. Spencer54b24e12013-01-29 22:10:07 +0000410 COFFSymbol *coff_symbol = GetOrCreateCOFFSymbol(&Symbol);
Peter Collingbourne89886872013-04-22 18:48:56 +0000411 SymbolMap[&Symbol] = coff_symbol;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000412
Michael J. Spencer17990d52010-10-16 08:25:57 +0000413 if (SymbolData.getFlags() & COFF::SF_WeakExternal) {
414 coff_symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
415
Michael J. Spencer54b24e12013-01-29 22:10:07 +0000416 if (Symbol.isVariable()) {
Peter Collingbourne89886872013-04-22 18:48:56 +0000417 const MCSymbolRefExpr *SymRef =
418 dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
Michael J. Spencer17990d52010-10-16 08:25:57 +0000419
Peter Collingbourne89886872013-04-22 18:48:56 +0000420 if (!SymRef)
421 report_fatal_error("Weak externals may only alias symbols");
Michael J. Spencer17990d52010-10-16 08:25:57 +0000422
Peter Collingbourne89886872013-04-22 18:48:56 +0000423 coff_symbol->Other = GetOrCreateCOFFSymbol(&SymRef->getSymbol());
Michael J. Spencer17990d52010-10-16 08:25:57 +0000424 } else {
425 std::string WeakName = std::string(".weak.")
Michael J. Spencer54b24e12013-01-29 22:10:07 +0000426 + Symbol.getName().str()
Michael J. Spencer17990d52010-10-16 08:25:57 +0000427 + ".default";
428 COFFSymbol *WeakDefault = createSymbol(WeakName);
429 WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
430 WeakDefault->Data.StorageClass = COFF::IMAGE_SYM_CLASS_EXTERNAL;
431 WeakDefault->Data.Type = 0;
432 WeakDefault->Data.Value = 0;
433 coff_symbol->Other = WeakDefault;
434 }
435
436 // Setup the Weak External auxiliary symbol.
437 coff_symbol->Aux.resize(1);
438 memset(&coff_symbol->Aux[0], 0, sizeof(coff_symbol->Aux[0]));
439 coff_symbol->Aux[0].AuxType = ATWeakExternal;
440 coff_symbol->Aux[0].Aux.WeakExternal.TagIndex = 0;
441 coff_symbol->Aux[0].Aux.WeakExternal.Characteristics =
442 COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY;
Peter Collingbourne89886872013-04-22 18:48:56 +0000443
444 coff_symbol->MCData = &SymbolData;
445 } else {
Rafael Espindolaea9f9d42014-05-01 19:02:03 +0000446 const MCSymbolData &ResSymData = Assembler.getSymbolData(Symbol);
Rafael Espindola575f79a2014-05-01 13:37:57 +0000447 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
Rafael Espindolaff68cb72014-05-01 00:10:17 +0000448 coff_symbol->Data.Value = getSymbolValue(ResSymData, Layout);
Reid Klecknerc1e76212013-09-17 23:18:05 +0000449
Peter Collingbourne89886872013-04-22 18:48:56 +0000450 coff_symbol->Data.Type = (ResSymData.getFlags() & 0x0000FFFF) >> 0;
451 coff_symbol->Data.StorageClass = (ResSymData.getFlags() & 0x00FF0000) >> 16;
452
453 // If no storage class was specified in the streamer, define it here.
454 if (coff_symbol->Data.StorageClass == 0) {
David Majnemer299674e2014-07-13 04:31:19 +0000455 bool IsExternal =
456 ResSymData.isExternal() ||
457 (!ResSymData.getFragment() && !ResSymData.getSymbol().isVariable());
Peter Collingbourne89886872013-04-22 18:48:56 +0000458
David Majnemer299674e2014-07-13 04:31:19 +0000459 coff_symbol->Data.StorageClass = IsExternal
460 ? COFF::IMAGE_SYM_CLASS_EXTERNAL
461 : COFF::IMAGE_SYM_CLASS_STATIC;
Peter Collingbourne89886872013-04-22 18:48:56 +0000462 }
463
Rafael Espindola575f79a2014-05-01 13:37:57 +0000464 if (!Base) {
Reid Klecknerc1e76212013-09-17 23:18:05 +0000465 coff_symbol->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
Rafael Espindola575f79a2014-05-01 13:37:57 +0000466 } else {
467 const MCSymbolData &BaseData = Assembler.getSymbolData(*Base);
Rafael Espindola0766ae02014-06-06 19:26:12 +0000468 if (BaseData.Fragment) {
469 COFFSection *Sec =
Rafael Espindola575f79a2014-05-01 13:37:57 +0000470 SectionMap[&BaseData.Fragment->getParent()->getSection()];
Rafael Espindola0766ae02014-06-06 19:26:12 +0000471
472 if (coff_symbol->Section && coff_symbol->Section != Sec)
473 report_fatal_error("conflicting sections for symbol");
474
475 coff_symbol->Section = Sec;
476 }
Rafael Espindola575f79a2014-05-01 13:37:57 +0000477 }
Peter Collingbourne89886872013-04-22 18:48:56 +0000478
479 coff_symbol->MCData = &ResSymData;
Michael J. Spencer17990d52010-10-16 08:25:57 +0000480 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000481}
482
Nico Rieck01143f92014-02-25 09:50:40 +0000483// Maximum offsets for different string table entry encodings.
484static const unsigned Max6DecimalOffset = 999999;
485static const unsigned Max7DecimalOffset = 9999999;
486static const uint64_t MaxBase64Offset = 0xFFFFFFFFFULL; // 64^6, including 0
487
Nico Rieck9d2c15e2014-02-22 16:12:20 +0000488// Encode a string table entry offset in base 64, padded to 6 chars, and
489// prefixed with a double slash: '//AAAAAA', '//AAAAAB', ...
490// Buffer must be at least 8 bytes large. No terminating null appended.
491static void encodeBase64StringEntry(char* Buffer, uint64_t Value) {
Nico Rieck01143f92014-02-25 09:50:40 +0000492 assert(Value > Max7DecimalOffset && Value <= MaxBase64Offset &&
Nico Rieck9d2c15e2014-02-22 16:12:20 +0000493 "Illegal section name encoding for value");
494
495 static const char Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
496 "abcdefghijklmnopqrstuvwxyz"
497 "0123456789+/";
498
499 Buffer[0] = '/';
500 Buffer[1] = '/';
501
502 char* Ptr = Buffer + 7;
503 for (unsigned i = 0; i < 6; ++i) {
504 unsigned Rem = Value % 64;
505 Value /= 64;
506 *(Ptr--) = Alphabet[Rem];
507 }
508}
509
Michael J. Spencerd6283772010-09-27 08:58:26 +0000510/// making a section real involves assigned it a number and putting
511/// name into the string table if needed
512void WinCOFFObjectWriter::MakeSectionReal(COFFSection &S, size_t Number) {
513 if (S.Name.size() > COFF::NameSize) {
Nico Rieck2c9c89b2013-07-29 12:30:12 +0000514 uint64_t StringTableEntry = Strings.insert(S.Name.c_str());
Michael J. Spencerd6283772010-09-27 08:58:26 +0000515
Nico Rieck01143f92014-02-25 09:50:40 +0000516 if (StringTableEntry <= Max6DecimalOffset) {
Nico Rieck2c9c89b2013-07-29 12:30:12 +0000517 std::sprintf(S.Header.Name, "/%d", unsigned(StringTableEntry));
Nico Rieck01143f92014-02-25 09:50:40 +0000518 } else if (StringTableEntry <= Max7DecimalOffset) {
Nico Rieck2c9c89b2013-07-29 12:30:12 +0000519 // With seven digits, we have to skip the terminating null. Because
520 // sprintf always appends it, we use a larger temporary buffer.
521 char buffer[9] = { };
522 std::sprintf(buffer, "/%d", unsigned(StringTableEntry));
523 std::memcpy(S.Header.Name, buffer, 8);
Nico Rieck01143f92014-02-25 09:50:40 +0000524 } else if (StringTableEntry <= MaxBase64Offset) {
Nico Rieck9d2c15e2014-02-22 16:12:20 +0000525 // Starting with 10,000,000, offsets are encoded as base64.
526 encodeBase64StringEntry(S.Header.Name, StringTableEntry);
Nico Rieck2c9c89b2013-07-29 12:30:12 +0000527 } else {
Nico Rieck9d2c15e2014-02-22 16:12:20 +0000528 report_fatal_error("COFF string table is greater than 64 GB.");
Nico Rieck2c9c89b2013-07-29 12:30:12 +0000529 }
Michael J. Spencerd6283772010-09-27 08:58:26 +0000530 } else
531 std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
532
533 S.Number = Number;
534 S.Symbol->Data.SectionNumber = S.Number;
535 S.Symbol->Aux[0].Aux.SectionDefinition.Number = S.Number;
536}
537
538void WinCOFFObjectWriter::MakeSymbolReal(COFFSymbol &S, size_t Index) {
539 if (S.Name.size() > COFF::NameSize) {
540 size_t StringTableEntry = Strings.insert(S.Name.c_str());
541
542 S.set_name_offset(StringTableEntry);
543 } else
544 std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
545 S.Index = Index;
546}
547
David Majnemer299674e2014-07-13 04:31:19 +0000548bool WinCOFFObjectWriter::ExportSymbol(const MCSymbol &Symbol,
Reid Kleckner8b2ad2a2013-11-18 23:08:12 +0000549 MCAssembler &Asm) {
550 // This doesn't seem to be right. Strings referred to from the .data section
551 // need symbols so they can be linked to code in the .text section right?
552
David Majnemer299674e2014-07-13 04:31:19 +0000553 // return Asm.isSymbolLinkerVisible(Symbol);
554
555 // Non-temporary labels should always be visible to the linker.
556 if (!Symbol.isTemporary())
557 return true;
558
559 // Absolute temporary labels are never visible.
560 if (!Symbol.isInSection())
561 return false;
Reid Kleckner8b2ad2a2013-11-18 23:08:12 +0000562
563 // For now, all non-variable symbols are exported,
564 // the linker will sort the rest out for us.
David Majnemer299674e2014-07-13 04:31:19 +0000565 return !Symbol.isVariable();
Reid Kleckner8b2ad2a2013-11-18 23:08:12 +0000566}
567
Michael J. Spencerd6283772010-09-27 08:58:26 +0000568bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
569 return (S->Header.Characteristics
570 & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) == 0;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000571}
572
573//------------------------------------------------------------------------------
574// entity writing methods
575
576void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
David Majnemer4d571592014-09-15 19:42:42 +0000577 if (UseBigObj) {
578 WriteLE16(COFF::IMAGE_FILE_MACHINE_UNKNOWN);
579 WriteLE16(0xFFFF);
580 WriteLE16(COFF::BigObjHeader::MinBigObjectVersion);
581 WriteLE16(Header.Machine);
582 WriteLE32(Header.TimeDateStamp);
583 for (uint8_t MagicChar : COFF::BigObjMagic)
584 Write8(MagicChar);
585 WriteZeros(sizeof(COFF::BigObjHeader::unused1));
586 WriteZeros(sizeof(COFF::BigObjHeader::unused2));
587 WriteZeros(sizeof(COFF::BigObjHeader::unused3));
588 WriteZeros(sizeof(COFF::BigObjHeader::unused4));
589 WriteLE32(Header.NumberOfSections);
590 WriteLE32(Header.PointerToSymbolTable);
591 WriteLE32(Header.NumberOfSymbols);
592 } else {
593 WriteLE16(Header.Machine);
594 WriteLE16(static_cast<int16_t>(Header.NumberOfSections));
595 WriteLE32(Header.TimeDateStamp);
596 WriteLE32(Header.PointerToSymbolTable);
597 WriteLE32(Header.NumberOfSymbols);
598 WriteLE16(Header.SizeOfOptionalHeader);
599 WriteLE16(Header.Characteristics);
600 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000601}
602
David Blaikief564ab62014-04-15 05:25:03 +0000603void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol &S) {
604 WriteBytes(StringRef(S.Data.Name, COFF::NameSize));
605 WriteLE32(S.Data.Value);
David Majnemer4d571592014-09-15 19:42:42 +0000606 if (UseBigObj)
607 WriteLE32(S.Data.SectionNumber);
608 else
609 WriteLE16(static_cast<int16_t>(S.Data.SectionNumber));
David Blaikief564ab62014-04-15 05:25:03 +0000610 WriteLE16(S.Data.Type);
611 Write8(S.Data.StorageClass);
612 Write8(S.Data.NumberOfAuxSymbols);
613 WriteAuxiliarySymbols(S.Aux);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000614}
615
616void WinCOFFObjectWriter::WriteAuxiliarySymbols(
617 const COFFSymbol::AuxiliarySymbols &S) {
618 for(COFFSymbol::AuxiliarySymbols::const_iterator i = S.begin(), e = S.end();
619 i != e; ++i) {
620 switch(i->AuxType) {
621 case ATFunctionDefinition:
622 WriteLE32(i->Aux.FunctionDefinition.TagIndex);
623 WriteLE32(i->Aux.FunctionDefinition.TotalSize);
624 WriteLE32(i->Aux.FunctionDefinition.PointerToLinenumber);
625 WriteLE32(i->Aux.FunctionDefinition.PointerToNextFunction);
626 WriteZeros(sizeof(i->Aux.FunctionDefinition.unused));
David Majnemer4d571592014-09-15 19:42:42 +0000627 if (UseBigObj)
628 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000629 break;
630 case ATbfAndefSymbol:
631 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused1));
632 WriteLE16(i->Aux.bfAndefSymbol.Linenumber);
633 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused2));
634 WriteLE32(i->Aux.bfAndefSymbol.PointerToNextFunction);
635 WriteZeros(sizeof(i->Aux.bfAndefSymbol.unused3));
David Majnemer4d571592014-09-15 19:42:42 +0000636 if (UseBigObj)
637 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000638 break;
639 case ATWeakExternal:
640 WriteLE32(i->Aux.WeakExternal.TagIndex);
641 WriteLE32(i->Aux.WeakExternal.Characteristics);
642 WriteZeros(sizeof(i->Aux.WeakExternal.unused));
David Majnemer4d571592014-09-15 19:42:42 +0000643 if (UseBigObj)
644 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000645 break;
646 case ATFile:
David Majnemer4d571592014-09-15 19:42:42 +0000647 WriteBytes(
648 StringRef(reinterpret_cast<const char *>(&i->Aux),
649 UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size));
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000650 break;
651 case ATSectionDefinition:
652 WriteLE32(i->Aux.SectionDefinition.Length);
653 WriteLE16(i->Aux.SectionDefinition.NumberOfRelocations);
654 WriteLE16(i->Aux.SectionDefinition.NumberOfLinenumbers);
655 WriteLE32(i->Aux.SectionDefinition.CheckSum);
David Majnemer4d571592014-09-15 19:42:42 +0000656 WriteLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number));
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000657 Write8(i->Aux.SectionDefinition.Selection);
658 WriteZeros(sizeof(i->Aux.SectionDefinition.unused));
David Majnemer4d571592014-09-15 19:42:42 +0000659 WriteLE16(static_cast<int16_t>(i->Aux.SectionDefinition.Number >> 16));
660 if (UseBigObj)
661 WriteZeros(COFF::Symbol32Size - COFF::Symbol16Size);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000662 break;
663 }
664 }
665}
666
667void WinCOFFObjectWriter::WriteSectionHeader(const COFF::section &S) {
668 WriteBytes(StringRef(S.Name, COFF::NameSize));
669
670 WriteLE32(S.VirtualSize);
671 WriteLE32(S.VirtualAddress);
672 WriteLE32(S.SizeOfRawData);
673 WriteLE32(S.PointerToRawData);
674 WriteLE32(S.PointerToRelocations);
675 WriteLE32(S.PointerToLineNumbers);
676 WriteLE16(S.NumberOfRelocations);
677 WriteLE16(S.NumberOfLineNumbers);
678 WriteLE32(S.Characteristics);
679}
680
681void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
682 WriteLE32(R.VirtualAddress);
683 WriteLE32(R.SymbolTableIndex);
684 WriteLE16(R.Type);
Chris Lattner2c52b792010-07-11 22:07:02 +0000685}
686
687////////////////////////////////////////////////////////////////////////////////
688// MCObjectWriter interface implementations
689
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000690void WinCOFFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
691 const MCAsmLayout &Layout) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000692 // "Define" each section & symbol. This creates section & symbol
Michael J. Spencerd6283772010-09-27 08:58:26 +0000693 // entries in the staging area.
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000694 for (const auto & Section : Asm)
695 DefineSection(Section);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000696
David Blaikie583a31c2014-04-18 18:24:25 +0000697 for (MCSymbolData &SD : Asm.symbols())
David Majnemer299674e2014-07-13 04:31:19 +0000698 if (ExportSymbol(SD.getSymbol(), Asm))
David Blaikie583a31c2014-04-18 18:24:25 +0000699 DefineSymbol(SD, Asm, Layout);
Chris Lattner2c52b792010-07-11 22:07:02 +0000700}
701
702void WinCOFFObjectWriter::RecordRelocation(const MCAssembler &Asm,
703 const MCAsmLayout &Layout,
704 const MCFragment *Fragment,
705 const MCFixup &Fixup,
706 MCValue Target,
Rafael Espindola5904e122014-03-29 06:26:49 +0000707 bool &IsPCRel,
Chris Lattner2c52b792010-07-11 22:07:02 +0000708 uint64_t &FixedValue) {
Craig Topperbb694de2014-04-13 04:57:38 +0000709 assert(Target.getSymA() && "Relocation must reference a symbol!");
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000710
Reid Klecknerdae7b4e2013-07-15 19:41:21 +0000711 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
712 const MCSymbol &A = Symbol.AliasedSymbol();
Timur Iskhodzhanov3e4ac4e2014-01-30 21:13:05 +0000713 if (!Asm.hasSymbolData(A))
714 Asm.getContext().FatalError(
715 Fixup.getLoc(),
716 Twine("symbol '") + A.getName() + "' can not be undefined");
717
David Blaikie908f4d42014-04-24 16:59:40 +0000718 const MCSymbolData &A_SD = Asm.getSymbolData(A);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000719
720 MCSectionData const *SectionData = Fragment->getParent();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000721
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000722 // Mark this symbol as requiring an entry in the symbol table.
Michael J. Spencer17990d52010-10-16 08:25:57 +0000723 assert(SectionMap.find(&SectionData->getSection()) != SectionMap.end() &&
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000724 "Section must already have been defined in ExecutePostLayoutBinding!");
Michael J. Spencer17990d52010-10-16 08:25:57 +0000725 assert(SymbolMap.find(&A_SD.getSymbol()) != SymbolMap.end() &&
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000726 "Symbol must already have been defined in ExecutePostLayoutBinding!");
727
Michael J. Spencer17990d52010-10-16 08:25:57 +0000728 COFFSection *coff_section = SectionMap[&SectionData->getSection()];
729 COFFSymbol *coff_symbol = SymbolMap[&A_SD.getSymbol()];
Rafael Espindolaed164772011-04-20 14:01:45 +0000730 const MCSymbolRefExpr *SymB = Target.getSymB();
David Majnemera45a1762014-01-06 07:39:46 +0000731 bool CrossSection = false;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000732
David Majnemera45a1762014-01-06 07:39:46 +0000733 if (SymB) {
734 const MCSymbol *B = &SymB->getSymbol();
David Blaikie908f4d42014-04-24 16:59:40 +0000735 const MCSymbolData &B_SD = Asm.getSymbolData(*B);
David Majnemera45a1762014-01-06 07:39:46 +0000736 if (!B_SD.getFragment())
737 Asm.getContext().FatalError(
738 Fixup.getLoc(),
739 Twine("symbol '") + B->getName() +
740 "' can not be undefined in a subtraction expression");
741
742 if (!A_SD.getFragment())
743 Asm.getContext().FatalError(
744 Fixup.getLoc(),
745 Twine("symbol '") + Symbol.getName() +
746 "' can not be undefined in a subtraction expression");
747
748 CrossSection = &Symbol.getSection() != &B->getSection();
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000749
Rafael Espindolac3dc4862011-04-21 18:36:50 +0000750 // Offset of the symbol in the section
751 int64_t a = Layout.getSymbolOffset(&B_SD);
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000752
Rafael Espindolac3dc4862011-04-21 18:36:50 +0000753 // Ofeset of the relocation in the section
754 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
755
756 FixedValue = b - a;
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000757 // In the case where we have SymbA and SymB, we just need to store the delta
758 // between the two symbols. Update FixedValue to account for the delta, and
759 // skip recording the relocation.
Rafael Espindolaed164772011-04-20 14:01:45 +0000760 if (!CrossSection)
761 return;
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000762 } else {
763 FixedValue = Target.getConstant();
764 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000765
766 COFFRelocation Reloc;
767
Daniel Dunbar727be432010-07-31 21:08:54 +0000768 Reloc.Data.SymbolTableIndex = 0;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000769 Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
Michael J. Spencerd6283772010-09-27 08:58:26 +0000770
Michael J. Spencera65d17a2010-10-05 19:48:12 +0000771 // Turn relocations for temporary symbols into section relocations.
Rafael Espindolaed164772011-04-20 14:01:45 +0000772 if (coff_symbol->MCData->getSymbol().isTemporary() || CrossSection) {
Michael J. Spencerd6283772010-09-27 08:58:26 +0000773 Reloc.Symb = coff_symbol->Section->Symbol;
Michael J. Spencera3b34ed2010-10-05 19:48:03 +0000774 FixedValue += Layout.getFragmentOffset(coff_symbol->MCData->Fragment)
775 + coff_symbol->MCData->getOffset();
Michael J. Spencerd6283772010-09-27 08:58:26 +0000776 } else
777 Reloc.Symb = coff_symbol;
778
779 ++Reloc.Symb->Relocations;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000780
781 Reloc.Data.VirtualAddress += Fixup.getOffset();
Nico Rieck1da45292013-04-10 23:28:17 +0000782 Reloc.Data.Type = TargetObjectWriter->getRelocType(Target, Fixup,
783 CrossSection);
Rafael Espindolae61724a2011-12-22 22:21:47 +0000784
785 // FIXME: Can anyone explain what this does other than adjust for the size
786 // of the offset?
Saleem Abdulrasool2c080512014-04-13 20:47:55 +0000787 if ((Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 &&
788 Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32) ||
789 (Header.Machine == COFF::IMAGE_FILE_MACHINE_I386 &&
790 Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32))
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000791 FixedValue += 4;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000792
Saleem Abdulrasool84b952b2014-04-27 03:48:22 +0000793 if (Header.Machine == COFF::IMAGE_FILE_MACHINE_ARMNT) {
794 switch (Reloc.Data.Type) {
795 case COFF::IMAGE_REL_ARM_ABSOLUTE:
796 case COFF::IMAGE_REL_ARM_ADDR32:
797 case COFF::IMAGE_REL_ARM_ADDR32NB:
798 case COFF::IMAGE_REL_ARM_TOKEN:
799 case COFF::IMAGE_REL_ARM_SECTION:
800 case COFF::IMAGE_REL_ARM_SECREL:
801 break;
802 case COFF::IMAGE_REL_ARM_BRANCH11:
803 case COFF::IMAGE_REL_ARM_BLX11:
804 // IMAGE_REL_ARM_BRANCH11 and IMAGE_REL_ARM_BLX11 are only used for
805 // pre-ARMv7, which implicitly rules it out of ARMNT (it would be valid
806 // for Windows CE).
807 case COFF::IMAGE_REL_ARM_BRANCH24:
808 case COFF::IMAGE_REL_ARM_BLX24:
809 case COFF::IMAGE_REL_ARM_MOV32A:
810 // IMAGE_REL_ARM_BRANCH24, IMAGE_REL_ARM_BLX24, IMAGE_REL_ARM_MOV32A are
811 // only used for ARM mode code, which is documented as being unsupported
Alp Tokerbeaca192014-05-15 01:52:21 +0000812 // by Windows on ARM. Empirical proof indicates that masm is able to
Saleem Abdulrasool84b952b2014-04-27 03:48:22 +0000813 // generate the relocations however the rest of the MSVC toolchain is
814 // unable to handle it.
815 llvm_unreachable("unsupported relocation");
816 break;
817 case COFF::IMAGE_REL_ARM_MOV32T:
818 break;
819 case COFF::IMAGE_REL_ARM_BRANCH20T:
820 case COFF::IMAGE_REL_ARM_BRANCH24T:
821 case COFF::IMAGE_REL_ARM_BLX23T:
822 // IMAGE_REL_BRANCH20T, IMAGE_REL_ARM_BRANCH24T, IMAGE_REL_ARM_BLX23T all
823 // perform a 4 byte adjustment to the relocation. Relative branches are
824 // offset by 4 on ARM, however, because there is no RELA relocations, all
825 // branches are offset by 4.
826 FixedValue = FixedValue + 4;
827 break;
828 }
829 }
830
Saleem Abdulrasool54bed122014-05-21 23:17:50 +0000831 if (TargetObjectWriter->recordRelocation(Fixup))
832 coff_section->Relocations.push_back(Reloc);
Chris Lattner2c52b792010-07-11 22:07:02 +0000833}
834
Rafael Espindolabce26a12010-10-05 15:11:03 +0000835void WinCOFFObjectWriter::WriteObject(MCAssembler &Asm,
Chris Lattner2c52b792010-07-11 22:07:02 +0000836 const MCAsmLayout &Layout) {
David Majnemer4d571592014-09-15 19:42:42 +0000837 size_t SectionsSize = Sections.size();
838 if (SectionsSize > static_cast<size_t>(INT32_MAX))
839 report_fatal_error(
840 "PE COFF object files can't have more than 2147483647 sections");
Michael J. Spencerd6283772010-09-27 08:58:26 +0000841
David Majnemer4d571592014-09-15 19:42:42 +0000842 // Assign symbol and section indexes and offsets.
843 int32_t NumberOfSections = static_cast<int32_t>(SectionsSize);
844
845 UseBigObj = NumberOfSections > COFF::MaxNumberOfSections16;
846
847 DenseMap<COFFSection *, int32_t> SectionIndices(
848 NextPowerOf2(NumberOfSections));
849 size_t Number = 1;
David Majnemer9ab5ff12014-08-28 04:02:50 +0000850 for (const auto &Section : Sections) {
David Majnemer4d571592014-09-15 19:42:42 +0000851 SectionIndices[Section.get()] = Number;
Saleem Abdulrasoole9bd9162014-06-06 21:40:16 +0000852 MakeSectionReal(*Section, Number);
David Majnemer4d571592014-09-15 19:42:42 +0000853 ++Number;
Michael J. Spencerd6283772010-09-27 08:58:26 +0000854 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000855
David Majnemer4d571592014-09-15 19:42:42 +0000856 Header.NumberOfSections = NumberOfSections;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000857 Header.NumberOfSymbols = 0;
858
David Majnemer4d571592014-09-15 19:42:42 +0000859 for (auto FI = Asm.file_names_begin(), FE = Asm.file_names_end();
860 FI != FE; ++FI) {
861 // round up to calculate the number of auxiliary symbols required
862 unsigned SymbolSize = UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size;
863 unsigned Count = (FI->size() + SymbolSize - 1) / SymbolSize;
864
865 COFFSymbol *file = createSymbol(".file");
866 file->Data.SectionNumber = COFF::IMAGE_SYM_DEBUG;
867 file->Data.StorageClass = COFF::IMAGE_SYM_CLASS_FILE;
868 file->Aux.resize(Count);
869
870 unsigned Offset = 0;
871 unsigned Length = FI->size();
872 for (auto & Aux : file->Aux) {
873 Aux.AuxType = ATFile;
874
875 if (Length > SymbolSize) {
876 memcpy(&Aux.Aux, FI->c_str() + Offset, SymbolSize);
877 Length = Length - SymbolSize;
878 } else {
879 memcpy(&Aux.Aux, FI->c_str() + Offset, Length);
880 memset((char *)&Aux.Aux + Length, 0, SymbolSize - Length);
881 break;
882 }
883
884 Offset += SymbolSize;
885 }
886 }
887
David Majnemer9ab5ff12014-08-28 04:02:50 +0000888 for (auto &Symbol : Symbols) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000889 // Update section number & offset for symbols that have them.
Rafael Espindola575f79a2014-05-01 13:37:57 +0000890 if (Symbol->Section)
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000891 Symbol->Data.SectionNumber = Symbol->Section->Number;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000892
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000893 if (Symbol->should_keep()) {
894 MakeSymbolReal(*Symbol, Header.NumberOfSymbols++);
Michael J. Spencerd6283772010-09-27 08:58:26 +0000895
896 // Update auxiliary symbol info.
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000897 Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
898 Header.NumberOfSymbols += Symbol->Data.NumberOfAuxSymbols;
Michael J. Spencerd6283772010-09-27 08:58:26 +0000899 } else
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000900 Symbol->Index = -1;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000901 }
902
903 // Fixup weak external references.
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000904 for (auto & Symbol : Symbols) {
905 if (Symbol->Other) {
906 assert(Symbol->Index != -1);
907 assert(Symbol->Aux.size() == 1 && "Symbol must contain one aux symbol!");
908 assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000909 "Symbol's aux symbol must be a Weak External!");
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000910 Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->Index;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000911 }
912 }
913
Nico Riecka37acf72013-07-06 12:13:10 +0000914 // Fixup associative COMDAT sections.
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000915 for (auto & Section : Sections) {
916 if (Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
Nico Riecka37acf72013-07-06 12:13:10 +0000917 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
918 continue;
919
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000920 const MCSectionCOFF &MCSec =
921 static_cast<const MCSectionCOFF &>(Section->MCData->getSection());
Nico Riecka37acf72013-07-06 12:13:10 +0000922
Rafael Espindola0766ae02014-06-06 19:26:12 +0000923 const MCSymbol *COMDAT = MCSec.getCOMDATSymbol();
924 assert(COMDAT);
925 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(COMDAT);
926 assert(COMDATSymbol);
927 COFFSection *Assoc = COMDATSymbol->Section;
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000928 if (!Assoc)
Rafael Espindola0766ae02014-06-06 19:26:12 +0000929 report_fatal_error(
930 Twine("Missing associated COMDAT section for section ") +
931 MCSec.getSectionName());
Nico Riecka37acf72013-07-06 12:13:10 +0000932
933 // Skip this section if the associated section is unused.
934 if (Assoc->Number == -1)
935 continue;
936
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000937 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = SectionIndices[Assoc];
Nico Riecka37acf72013-07-06 12:13:10 +0000938 }
939
940
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000941 // Assign file offsets to COFF object file structures.
942
943 unsigned offset = 0;
944
David Majnemer4d571592014-09-15 19:42:42 +0000945 if (UseBigObj)
946 offset += COFF::Header32Size;
947 else
948 offset += COFF::Header16Size;
Michael J. Spencerd6283772010-09-27 08:58:26 +0000949 offset += COFF::SectionSize * Header.NumberOfSections;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000950
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000951 for (const auto & Section : Asm) {
952 COFFSection *Sec = SectionMap[&Section.getSection()];
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000953
Michael J. Spencerd6283772010-09-27 08:58:26 +0000954 if (Sec->Number == -1)
955 continue;
956
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000957 Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(&Section);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000958
Michael J. Spencerd6283772010-09-27 08:58:26 +0000959 if (IsPhysicalSection(Sec)) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000960 Sec->Header.PointerToRawData = offset;
961
962 offset += Sec->Header.SizeOfRawData;
963 }
964
965 if (Sec->Relocations.size() > 0) {
Michael J. Spencerfa39bd22012-03-15 09:03:03 +0000966 bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
967
968 if (RelocationsOverflow) {
David Majnemer9ab5ff12014-08-28 04:02:50 +0000969 // Signal overflow by setting NumberOfRelocations to max value. Actual
Michael J. Spencerfa39bd22012-03-15 09:03:03 +0000970 // size is found in reloc #0. Microsoft tools understand this.
971 Sec->Header.NumberOfRelocations = 0xffff;
972 } else {
973 Sec->Header.NumberOfRelocations = Sec->Relocations.size();
974 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000975 Sec->Header.PointerToRelocations = offset;
976
Michael J. Spencerfa39bd22012-03-15 09:03:03 +0000977 if (RelocationsOverflow) {
978 // Reloc #0 will contain actual count, so make room for it.
979 offset += COFF::RelocationSize;
980 }
981
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000982 offset += COFF::RelocationSize * Sec->Relocations.size();
983
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000984 for (auto & Relocation : Sec->Relocations) {
985 assert(Relocation.Symb->Index != -1);
986 Relocation.Data.SymbolTableIndex = Relocation.Symb->Index;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000987 }
988 }
989
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000990 assert(Sec->Symbol->Aux.size() == 1 &&
991 "Section's symbol must have one aux!");
Michael J. Spencerd6283772010-09-27 08:58:26 +0000992 AuxSymbol &Aux = Sec->Symbol->Aux[0];
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000993 assert(Aux.AuxType == ATSectionDefinition &&
994 "Section's symbol's aux symbol must be a Section Definition!");
995 Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
996 Aux.Aux.SectionDefinition.NumberOfRelocations =
997 Sec->Header.NumberOfRelocations;
998 Aux.Aux.SectionDefinition.NumberOfLinenumbers =
999 Sec->Header.NumberOfLineNumbers;
1000 }
1001
1002 Header.PointerToSymbolTable = offset;
1003
Rafael Espindola5ac4ad22013-12-04 02:26:54 +00001004 // We want a deterministic output. It looks like GNU as also writes 0 in here.
Rafael Espindola9201e6b2013-12-04 02:02:55 +00001005 Header.TimeDateStamp = 0;
Michael J. Spencera6cfbeb2010-08-03 04:43:33 +00001006
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001007 // Write it all to disk...
1008 WriteFileHeader(Header);
1009
1010 {
1011 sections::iterator i, ie;
1012 MCAssembler::const_iterator j, je;
1013
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +00001014 for (auto & Section : Sections) {
1015 if (Section->Number != -1) {
1016 if (Section->Relocations.size() >= 0xffff)
1017 Section->Header.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL;
1018 WriteSectionHeader(Section->Header);
Michael J. Spencerfa39bd22012-03-15 09:03:03 +00001019 }
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +00001020 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001021
1022 for (i = Sections.begin(), ie = Sections.end(),
1023 j = Asm.begin(), je = Asm.end();
Michael J. Spencerd6283772010-09-27 08:58:26 +00001024 (i != ie) && (j != je); ++i, ++j) {
1025
1026 if ((*i)->Number == -1)
1027 continue;
1028
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001029 if ((*i)->Header.PointerToRawData != 0) {
1030 assert(OS.tell() == (*i)->Header.PointerToRawData &&
1031 "Section::PointerToRawData is insane!");
1032
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001033 Asm.writeSectionData(j, Layout);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001034 }
1035
1036 if ((*i)->Relocations.size() > 0) {
1037 assert(OS.tell() == (*i)->Header.PointerToRelocations &&
1038 "Section::PointerToRelocations is insane!");
1039
Michael J. Spencerfa39bd22012-03-15 09:03:03 +00001040 if ((*i)->Relocations.size() >= 0xffff) {
1041 // In case of overflow, write actual relocation count as first
1042 // relocation. Including the synthetic reloc itself (+ 1).
1043 COFF::relocation r;
1044 r.VirtualAddress = (*i)->Relocations.size() + 1;
1045 r.SymbolTableIndex = 0;
1046 r.Type = 0;
1047 WriteRelocation(r);
1048 }
1049
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +00001050 for (const auto & Relocation : (*i)->Relocations)
1051 WriteRelocation(Relocation.Data);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001052 } else
1053 assert((*i)->Header.PointerToRelocations == 0 &&
1054 "Section::PointerToRelocations is insane!");
1055 }
1056 }
1057
1058 assert(OS.tell() == Header.PointerToSymbolTable &&
1059 "Header::PointerToSymbolTable is insane!");
1060
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +00001061 for (auto & Symbol : Symbols)
1062 if (Symbol->Index != -1)
1063 WriteSymbol(*Symbol);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001064
1065 OS.write((char const *)&Strings.Data.front(), Strings.Data.size());
Chris Lattner2c52b792010-07-11 22:07:02 +00001066}
1067
Rafael Espindola908d2ed2011-12-24 02:14:02 +00001068MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_) :
1069 Machine(Machine_) {
1070}
1071
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +00001072// Pin the vtable to this file.
1073void MCWinCOFFObjectTargetWriter::anchor() {}
1074
Chris Lattner2c52b792010-07-11 22:07:02 +00001075//------------------------------------------------------------------------------
1076// WinCOFFObjectWriter factory function
1077
1078namespace llvm {
Rafael Espindola908d2ed2011-12-24 02:14:02 +00001079 MCObjectWriter *createWinCOFFObjectWriter(MCWinCOFFObjectTargetWriter *MOTW,
1080 raw_ostream &OS) {
1081 return new WinCOFFObjectWriter(MOTW, OS);
Chris Lattner2c52b792010-07-11 22:07:02 +00001082 }
Michael J. Spencerc2129372010-07-26 03:01:28 +00001083}