blob: f63d491c8253f748dca98d8fea1a84c0ed4c222c [file] [log] [blame]
Eugene Zelenko1d435522017-02-07 23:02:00 +00001//===- llvm/MC/WinCOFFObjectWriter.cpp ------------------------------------===//
Chris Lattner2c52b792010-07-11 22:07:02 +00002//
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
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000014#include "llvm/ADT/DenseMap.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000015#include "llvm/ADT/STLExtras.h"
Eugene Zelenko1d435522017-02-07 23:02:00 +000016#include "llvm/ADT/SmallString.h"
17#include "llvm/ADT/SmallVector.h"
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000018#include "llvm/ADT/StringRef.h"
Nico Riecka37acf72013-07-06 12:13:10 +000019#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000020#include "llvm/BinaryFormat/COFF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/MC/MCAsmLayout.h"
22#include "llvm/MC/MCAssembler.h"
23#include "llvm/MC/MCContext.h"
24#include "llvm/MC/MCExpr.h"
Eugene Zelenko1d435522017-02-07 23:02:00 +000025#include "llvm/MC/MCFixup.h"
26#include "llvm/MC/MCFragment.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000027#include "llvm/MC/MCObjectWriter.h"
28#include "llvm/MC/MCSection.h"
29#include "llvm/MC/MCSectionCOFF.h"
Eugene Zelenko1d435522017-02-07 23:02:00 +000030#include "llvm/MC/MCSymbol.h"
Pete Cooperad9f9c32015-06-08 17:17:12 +000031#include "llvm/MC/MCSymbolCOFF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000032#include "llvm/MC/MCValue.h"
Eugene Zelenko1d435522017-02-07 23:02:00 +000033#include "llvm/MC/MCWinCOFFObjectWriter.h"
Hans Wennborgf26bfc12014-09-29 22:43:20 +000034#include "llvm/MC/StringTableBuilder.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000035#include "llvm/Support/Casting.h"
Hans Wennborgba80b5d2014-09-28 00:22:27 +000036#include "llvm/Support/Endian.h"
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000037#include "llvm/Support/ErrorHandling.h"
David Majnemer6ddc6362015-09-01 21:23:58 +000038#include "llvm/Support/JamCRC.h"
Eugene Zelenko1d435522017-02-07 23:02:00 +000039#include "llvm/Support/MathExtras.h"
40#include "llvm/Support/raw_ostream.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000041#include <algorithm>
Eugene Zelenko1d435522017-02-07 23:02:00 +000042#include <cassert>
43#include <cstddef>
44#include <cstdint>
45#include <cstring>
David Majnemer088ba022015-09-01 23:46:11 +000046#include <ctime>
Eugene Zelenko1d435522017-02-07 23:02:00 +000047#include <memory>
48#include <string>
49#include <vector>
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000050
Chris Lattner2c52b792010-07-11 22:07:02 +000051using namespace llvm;
Rui Ueyama86e3ef92017-02-14 23:28:19 +000052using llvm::support::endian::write32le;
Chris Lattner2c52b792010-07-11 22:07:02 +000053
Chandler Carruthf58e3762014-04-22 03:04:17 +000054#define DEBUG_TYPE "WinCOFFObjectWriter"
55
Chris Lattner2c52b792010-07-11 22:07:02 +000056namespace {
Eugene Zelenko1d435522017-02-07 23:02:00 +000057
Eugene Zelenko7975b992017-04-26 22:31:39 +000058using name = SmallString<COFF::NameSize>;
Chris Lattner2c52b792010-07-11 22:07:02 +000059
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000060enum AuxiliaryType {
61 ATFunctionDefinition,
62 ATbfAndefSymbol,
63 ATWeakExternal,
64 ATFile,
65 ATSectionDefinition
66};
Chris Lattner2c52b792010-07-11 22:07:02 +000067
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000068struct AuxSymbol {
Rafael Espindola11e9e212015-05-27 14:37:12 +000069 AuxiliaryType AuxType;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000070 COFF::Auxiliary Aux;
71};
Chris Lattner2c52b792010-07-11 22:07:02 +000072
Michael J. Spencerd6283772010-09-27 08:58:26 +000073class COFFSection;
74
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000075class COFFSymbol {
76public:
Rui Ueyamacbb4e7c2017-02-14 23:28:01 +000077 COFF::symbol Data = {};
Chris Lattner2c52b792010-07-11 22:07:02 +000078
Eugene Zelenko7975b992017-04-26 22:31:39 +000079 using AuxiliarySymbols = SmallVector<AuxSymbol, 1>;
Chris Lattner2c52b792010-07-11 22:07:02 +000080
Rafael Espindola11e9e212015-05-27 14:37:12 +000081 name Name;
82 int Index;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000083 AuxiliarySymbols Aux;
Eugene Zelenko1d435522017-02-07 23:02:00 +000084 COFFSymbol *Other = nullptr;
85 COFFSection *Section = nullptr;
86 int Relocations = 0;
87 const MCSymbol *MC = nullptr;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000088
Rui Ueyamacbb4e7c2017-02-14 23:28:01 +000089 COFFSymbol(StringRef Name) : Name(Name) {}
Eugene Zelenko1d435522017-02-07 23:02:00 +000090
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000091 void set_name_offset(uint32_t Offset);
Michael J. Spencerd6283772010-09-27 08:58:26 +000092
David Majnemer4eecd302015-05-30 04:56:02 +000093 int64_t getIndex() const { return Index; }
94 void setIndex(int Value) {
95 Index = Value;
96 if (MC)
97 MC->setIndex(static_cast<uint32_t>(Value));
98 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +000099};
100
101// This class contains staging data for a COFF relocation entry.
102struct COFFRelocation {
103 COFF::relocation Data;
Eugene Zelenko1d435522017-02-07 23:02:00 +0000104 COFFSymbol *Symb = nullptr;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000105
Eugene Zelenko1d435522017-02-07 23:02:00 +0000106 COFFRelocation() = default;
107
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000108 static size_t size() { return COFF::RelocationSize; }
109};
110
Eugene Zelenko7975b992017-04-26 22:31:39 +0000111using relocations = std::vector<COFFRelocation>;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000112
113class COFFSection {
114public:
Rui Ueyamacbb4e7c2017-02-14 23:28:01 +0000115 COFF::section Header = {};
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000116
Rafael Espindola11e9e212015-05-27 14:37:12 +0000117 std::string Name;
118 int Number;
Eugene Zelenko1d435522017-02-07 23:02:00 +0000119 MCSectionCOFF const *MCSection = nullptr;
120 COFFSymbol *Symbol = nullptr;
Rafael Espindola11e9e212015-05-27 14:37:12 +0000121 relocations Relocations;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000122
Rui Ueyamacbb4e7c2017-02-14 23:28:01 +0000123 COFFSection(StringRef Name) : Name(Name) {}
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000124};
125
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000126class WinCOFFObjectWriter : public MCObjectWriter {
127public:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000128 support::endian::Writer W;
129
Eugene Zelenko7975b992017-04-26 22:31:39 +0000130 using symbols = std::vector<std::unique_ptr<COFFSymbol>>;
131 using sections = std::vector<std::unique_ptr<COFFSection>>;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000132
Eugene Zelenko7975b992017-04-26 22:31:39 +0000133 using symbol_map = DenseMap<MCSymbol const *, COFFSymbol *>;
134 using section_map = DenseMap<MCSection const *, COFFSection *>;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000135
Ahmed Charles56440fd2014-03-06 05:51:42 +0000136 std::unique_ptr<MCWinCOFFObjectTargetWriter> TargetObjectWriter;
Rafael Espindola908d2ed2011-12-24 02:14:02 +0000137
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000138 // Root level file contents.
Rui Ueyamacbb4e7c2017-02-14 23:28:01 +0000139 COFF::header Header = {};
Rafael Espindola11e9e212015-05-27 14:37:12 +0000140 sections Sections;
141 symbols Symbols;
Rafael Espindola21956e42015-10-23 21:48:05 +0000142 StringTableBuilder Strings{StringTableBuilder::WinCOFF};
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000143
144 // Maps used during object file creation.
145 section_map SectionMap;
Rafael Espindola11e9e212015-05-27 14:37:12 +0000146 symbol_map SymbolMap;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000147
David Majnemer4d571592014-09-15 19:42:42 +0000148 bool UseBigObj;
149
Lang Hames77dff392017-10-10 00:50:29 +0000150 WinCOFFObjectWriter(std::unique_ptr<MCWinCOFFObjectTargetWriter> MOTW,
151 raw_pwrite_stream &OS);
Rafael Espindola37099d92015-04-09 18:08:15 +0000152
Yaron Kerencca43c12014-09-16 21:31:04 +0000153 void reset() override {
154 memset(&Header, 0, sizeof(Header));
155 Header.Machine = TargetObjectWriter->getMachine();
156 Sections.clear();
157 Symbols.clear();
158 Strings.clear();
159 SectionMap.clear();
160 SymbolMap.clear();
161 MCObjectWriter::reset();
162 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000163
Michael J. Spencer17990d52010-10-16 08:25:57 +0000164 COFFSymbol *createSymbol(StringRef Name);
Rafael Espindola11e9e212015-05-27 14:37:12 +0000165 COFFSymbol *GetOrCreateCOFFSymbol(const MCSymbol *Symbol);
Michael J. Spencer17990d52010-10-16 08:25:57 +0000166 COFFSection *createSection(StringRef Name);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000167
Rafael Espindolaf59264f2015-05-27 14:45:54 +0000168 void defineSection(MCSectionCOFF const &Sec);
Rafael Espindola732eeaf22016-05-26 20:31:00 +0000169
170 COFFSymbol *getLinkedSymbol(const MCSymbol &Symbol);
Duncan P. N. Exon Smithe8fb3a22015-05-20 19:34:08 +0000171 void DefineSymbol(const MCSymbol &Symbol, MCAssembler &Assembler,
Reid Klecknerc1e76212013-09-17 23:18:05 +0000172 const MCAsmLayout &Layout);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000173
Hans Wennborgf26bfc12014-09-29 22:43:20 +0000174 void SetSymbolName(COFFSymbol &S);
175 void SetSectionName(COFFSection &S);
Michael J. Spencerd6283772010-09-27 08:58:26 +0000176
Michael J. Spencerd6283772010-09-27 08:58:26 +0000177 bool IsPhysicalSection(COFFSection *S);
178
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000179 // Entity writing methods.
180
181 void WriteFileHeader(const COFF::header &Header);
David Blaikief564ab62014-04-15 05:25:03 +0000182 void WriteSymbol(const COFFSymbol &S);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000183 void WriteAuxiliarySymbols(const COFFSymbol::AuxiliarySymbols &S);
Rui Ueyamaac20c172017-02-17 17:32:54 +0000184 void writeSectionHeaders();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000185 void WriteRelocation(const COFF::relocation &R);
Rui Ueyama26ca0bd2017-02-16 02:56:06 +0000186 uint32_t writeSectionContents(MCAssembler &Asm, const MCAsmLayout &Layout,
187 const MCSection &MCSec);
Rui Ueyamaaf20f102017-02-16 02:35:48 +0000188 void writeSection(MCAssembler &Asm, const MCAsmLayout &Layout,
189 const COFFSection &Sec, const MCSection &MCSec);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000190
191 // MCObjectWriter interface implementation.
192
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000193 void executePostLayoutBinding(MCAssembler &Asm,
Craig Topper34a61bc2014-03-08 07:02:02 +0000194 const MCAsmLayout &Layout) override;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000195
Jim Grosbach36e60e92015-06-04 22:24:41 +0000196 bool isSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
Duncan P. N. Exon Smithd81ba532015-05-16 01:01:55 +0000197 const MCSymbol &SymA,
David Majnemer2cc4bc772014-11-11 08:43:57 +0000198 const MCFragment &FB, bool InSet,
199 bool IsPCRel) const override;
200
Jim Grosbach36e60e92015-06-04 22:24:41 +0000201 void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
Craig Topper34a61bc2014-03-08 07:02:02 +0000202 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000203 MCValue Target, uint64_t &FixedValue) override;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000204
Rui Ueyamaaf20f102017-02-16 02:35:48 +0000205 void createFileSymbols(MCAssembler &Asm);
206 void assignSectionNumbers();
207 void assignFileOffsets(MCAssembler &Asm, const MCAsmLayout &Layout);
208
Peter Collingbourne438390f2018-05-21 18:23:50 +0000209 uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000210};
Eugene Zelenko1d435522017-02-07 23:02:00 +0000211
212} // end anonymous namespace
Chris Lattner2c52b792010-07-11 22:07:02 +0000213
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000214//------------------------------------------------------------------------------
215// Symbol class implementation
216
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000217// In the case that the name does not fit within 8 bytes, the offset
218// into the string table is stored in the last 4 bytes instead, leaving
219// the first 4 bytes as 0.
220void COFFSymbol::set_name_offset(uint32_t Offset) {
Rui Ueyama86e3ef92017-02-14 23:28:19 +0000221 write32le(Data.Name + 0, 0);
222 write32le(Data.Name + 4, Offset);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000223}
224
225//------------------------------------------------------------------------------
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000226// WinCOFFObjectWriter class implementation
227
Lang Hames77dff392017-10-10 00:50:29 +0000228WinCOFFObjectWriter::WinCOFFObjectWriter(
229 std::unique_ptr<MCWinCOFFObjectTargetWriter> MOTW, raw_pwrite_stream &OS)
Peter Collingbourne59a6fc42018-05-21 18:28:57 +0000230 : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {
Rafael Espindola908d2ed2011-12-24 02:14:02 +0000231 Header.Machine = TargetObjectWriter->getMachine();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000232}
233
Michael J. Spencer17990d52010-10-16 08:25:57 +0000234COFFSymbol *WinCOFFObjectWriter::createSymbol(StringRef Name) {
Rui Ueyamadfc8aa82017-02-14 23:58:19 +0000235 Symbols.push_back(make_unique<COFFSymbol>(Name));
236 return Symbols.back().get();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000237}
238
Yaron Keren56919ef2014-12-04 08:30:39 +0000239COFFSymbol *WinCOFFObjectWriter::GetOrCreateCOFFSymbol(const MCSymbol *Symbol) {
Rui Ueyama0fcdb482017-02-14 23:47:34 +0000240 COFFSymbol *&Ret = SymbolMap[Symbol];
241 if (!Ret)
Rui Ueyamadfc8aa82017-02-14 23:58:19 +0000242 Ret = createSymbol(Symbol->getName());
Rui Ueyama0fcdb482017-02-14 23:47:34 +0000243 return Ret;
Michael J. Spencer17990d52010-10-16 08:25:57 +0000244}
245
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000246COFFSection *WinCOFFObjectWriter::createSection(StringRef Name) {
Rui Ueyamadfc8aa82017-02-14 23:58:19 +0000247 Sections.emplace_back(make_unique<COFFSection>(Name));
248 return Sections.back().get();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000249}
250
Rui Ueyama24e27b42017-02-15 00:15:54 +0000251static uint32_t getAlignment(const MCSectionCOFF &Sec) {
252 switch (Sec.getAlignment()) {
253 case 1:
254 return COFF::IMAGE_SCN_ALIGN_1BYTES;
255 case 2:
256 return COFF::IMAGE_SCN_ALIGN_2BYTES;
257 case 4:
258 return COFF::IMAGE_SCN_ALIGN_4BYTES;
259 case 8:
260 return COFF::IMAGE_SCN_ALIGN_8BYTES;
261 case 16:
262 return COFF::IMAGE_SCN_ALIGN_16BYTES;
263 case 32:
264 return COFF::IMAGE_SCN_ALIGN_32BYTES;
265 case 64:
266 return COFF::IMAGE_SCN_ALIGN_64BYTES;
267 case 128:
268 return COFF::IMAGE_SCN_ALIGN_128BYTES;
269 case 256:
270 return COFF::IMAGE_SCN_ALIGN_256BYTES;
271 case 512:
272 return COFF::IMAGE_SCN_ALIGN_512BYTES;
273 case 1024:
274 return COFF::IMAGE_SCN_ALIGN_1024BYTES;
275 case 2048:
276 return COFF::IMAGE_SCN_ALIGN_2048BYTES;
277 case 4096:
278 return COFF::IMAGE_SCN_ALIGN_4096BYTES;
279 case 8192:
280 return COFF::IMAGE_SCN_ALIGN_8192BYTES;
281 }
282 llvm_unreachable("unsupported section alignment");
283}
284
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000285/// This function takes a section data object from the assembler
286/// and creates the associated COFF section staging object.
Rui Ueyama09786c42017-02-15 00:28:48 +0000287void WinCOFFObjectWriter::defineSection(const MCSectionCOFF &MCSec) {
288 COFFSection *Section = createSection(MCSec.getSectionName());
289 COFFSymbol *Symbol = createSymbol(MCSec.getSectionName());
290 Section->Symbol = Symbol;
291 Symbol->Section = Section;
292 Symbol->Data.StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
Rui Ueyama24e27b42017-02-15 00:15:54 +0000293
294 // Create a COMDAT symbol if needed.
Rui Ueyama09786c42017-02-15 00:28:48 +0000295 if (MCSec.getSelection() != COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
296 if (const MCSymbol *S = MCSec.getCOMDATSymbol()) {
Rafael Espindola0766ae02014-06-06 19:26:12 +0000297 COFFSymbol *COMDATSymbol = GetOrCreateCOFFSymbol(S);
298 if (COMDATSymbol->Section)
299 report_fatal_error("two sections have the same comdat");
Rui Ueyama09786c42017-02-15 00:28:48 +0000300 COMDATSymbol->Section = Section;
Rafael Espindola0766ae02014-06-06 19:26:12 +0000301 }
302 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000303
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000304 // In this case the auxiliary symbol is a Section Definition.
Rui Ueyama09786c42017-02-15 00:28:48 +0000305 Symbol->Aux.resize(1);
306 Symbol->Aux[0] = {};
307 Symbol->Aux[0].AuxType = ATSectionDefinition;
308 Symbol->Aux[0].Aux.SectionDefinition.Selection = MCSec.getSelection();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000309
Rui Ueyama09786c42017-02-15 00:28:48 +0000310 // Set section alignment.
311 Section->Header.Characteristics = MCSec.getCharacteristics();
312 Section->Header.Characteristics |= getAlignment(MCSec);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000313
314 // Bind internal COFF section to MC section.
Rui Ueyama09786c42017-02-15 00:28:48 +0000315 Section->MCSection = &MCSec;
316 SectionMap[&MCSec] = Section;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000317}
318
Duncan P. N. Exon Smithe8fb3a22015-05-20 19:34:08 +0000319static uint64_t getSymbolValue(const MCSymbol &Symbol,
Rafael Espindolaff68cb72014-05-01 00:10:17 +0000320 const MCAsmLayout &Layout) {
Rafael Espindola4d37b2a2015-05-29 21:45:01 +0000321 if (Symbol.isCommon() && Symbol.isExternal())
Rafael Espindola14672502015-05-29 17:48:04 +0000322 return Symbol.getCommonSize();
Rafael Espindolaff68cb72014-05-01 00:10:17 +0000323
324 uint64_t Res;
Duncan P. N. Exon Smithe8fb3a22015-05-20 19:34:08 +0000325 if (!Layout.getSymbolOffset(Symbol, Res))
Rafael Espindolaff68cb72014-05-01 00:10:17 +0000326 return 0;
327
328 return Res;
329}
330
Rafael Espindola732eeaf22016-05-26 20:31:00 +0000331COFFSymbol *WinCOFFObjectWriter::getLinkedSymbol(const MCSymbol &Symbol) {
332 if (!Symbol.isVariable())
333 return nullptr;
334
335 const MCSymbolRefExpr *SymRef =
336 dyn_cast<MCSymbolRefExpr>(Symbol.getVariableValue());
337 if (!SymRef)
338 return nullptr;
339
340 const MCSymbol &Aliasee = SymRef->getSymbol();
341 if (!Aliasee.isUndefined())
342 return nullptr;
343 return GetOrCreateCOFFSymbol(&Aliasee);
344}
345
David Majnemera9bdb322014-04-08 22:33:40 +0000346/// This function takes a symbol data object from the assembler
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000347/// and creates the associated COFF symbol staging object.
Rui Ueyama789c4222017-02-15 01:09:01 +0000348void WinCOFFObjectWriter::DefineSymbol(const MCSymbol &MCSym,
Reid Klecknerc1e76212013-09-17 23:18:05 +0000349 MCAssembler &Assembler,
350 const MCAsmLayout &Layout) {
Rui Ueyama789c4222017-02-15 01:09:01 +0000351 COFFSymbol *Sym = GetOrCreateCOFFSymbol(&MCSym);
352 const MCSymbol *Base = Layout.getBaseSymbol(MCSym);
Rafael Espindola30c080a2016-05-26 18:48:23 +0000353 COFFSection *Sec = nullptr;
354 if (Base && Base->getFragment()) {
355 Sec = SectionMap[Base->getFragment()->getParent()];
Rui Ueyama789c4222017-02-15 01:09:01 +0000356 if (Sym->Section && Sym->Section != Sec)
Rafael Espindola30c080a2016-05-26 18:48:23 +0000357 report_fatal_error("conflicting sections for symbol");
358 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000359
Rafael Espindola732eeaf22016-05-26 20:31:00 +0000360 COFFSymbol *Local = nullptr;
Rui Ueyama789c4222017-02-15 01:09:01 +0000361 if (cast<MCSymbolCOFF>(MCSym).isWeakExternal()) {
362 Sym->Data.StorageClass = COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL;
Michael J. Spencer17990d52010-10-16 08:25:57 +0000363
Rui Ueyama789c4222017-02-15 01:09:01 +0000364 COFFSymbol *WeakDefault = getLinkedSymbol(MCSym);
Rafael Espindola732eeaf22016-05-26 20:31:00 +0000365 if (!WeakDefault) {
Rui Ueyama789c4222017-02-15 01:09:01 +0000366 std::string WeakName = (".weak." + MCSym.getName() + ".default").str();
Rafael Espindola732eeaf22016-05-26 20:31:00 +0000367 WeakDefault = createSymbol(WeakName);
Rafael Espindola30c080a2016-05-26 18:48:23 +0000368 if (!Sec)
369 WeakDefault->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
370 else
371 WeakDefault->Section = Sec;
Rafael Espindola732eeaf22016-05-26 20:31:00 +0000372 Local = WeakDefault;
Michael J. Spencer17990d52010-10-16 08:25:57 +0000373 }
374
Rui Ueyama789c4222017-02-15 01:09:01 +0000375 Sym->Other = WeakDefault;
Rafael Espindola732eeaf22016-05-26 20:31:00 +0000376
Michael J. Spencer17990d52010-10-16 08:25:57 +0000377 // Setup the Weak External auxiliary symbol.
Rui Ueyama789c4222017-02-15 01:09:01 +0000378 Sym->Aux.resize(1);
379 memset(&Sym->Aux[0], 0, sizeof(Sym->Aux[0]));
380 Sym->Aux[0].AuxType = ATWeakExternal;
381 Sym->Aux[0].Aux.WeakExternal.TagIndex = 0;
382 Sym->Aux[0].Aux.WeakExternal.Characteristics =
Rafael Espindola11e9e212015-05-27 14:37:12 +0000383 COFF::IMAGE_WEAK_EXTERN_SEARCH_LIBRARY;
Peter Collingbourne89886872013-04-22 18:48:56 +0000384 } else {
Rafael Espindola30c080a2016-05-26 18:48:23 +0000385 if (!Base)
Rui Ueyama789c4222017-02-15 01:09:01 +0000386 Sym->Data.SectionNumber = COFF::IMAGE_SYM_ABSOLUTE;
Rafael Espindola30c080a2016-05-26 18:48:23 +0000387 else
Rui Ueyama789c4222017-02-15 01:09:01 +0000388 Sym->Section = Sec;
389 Local = Sym;
Michael J. Spencer17990d52010-10-16 08:25:57 +0000390 }
Rafael Espindola732eeaf22016-05-26 20:31:00 +0000391
392 if (Local) {
Rui Ueyama789c4222017-02-15 01:09:01 +0000393 Local->Data.Value = getSymbolValue(MCSym, Layout);
Rafael Espindola732eeaf22016-05-26 20:31:00 +0000394
Rui Ueyama789c4222017-02-15 01:09:01 +0000395 const MCSymbolCOFF &SymbolCOFF = cast<MCSymbolCOFF>(MCSym);
Rafael Espindola732eeaf22016-05-26 20:31:00 +0000396 Local->Data.Type = SymbolCOFF.getType();
397 Local->Data.StorageClass = SymbolCOFF.getClass();
398
399 // If no storage class was specified in the streamer, define it here.
400 if (Local->Data.StorageClass == COFF::IMAGE_SYM_CLASS_NULL) {
Rui Ueyama789c4222017-02-15 01:09:01 +0000401 bool IsExternal = MCSym.isExternal() ||
402 (!MCSym.getFragment() && !MCSym.isVariable());
Rafael Espindola732eeaf22016-05-26 20:31:00 +0000403
404 Local->Data.StorageClass = IsExternal ? COFF::IMAGE_SYM_CLASS_EXTERNAL
405 : COFF::IMAGE_SYM_CLASS_STATIC;
406 }
407 }
408
Rui Ueyama789c4222017-02-15 01:09:01 +0000409 Sym->MC = &MCSym;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000410}
411
Nico Rieck01143f92014-02-25 09:50:40 +0000412// Maximum offsets for different string table entry encodings.
David Majnemerf088f522016-01-24 20:46:11 +0000413enum : unsigned { Max7DecimalOffset = 9999999U };
414enum : uint64_t { MaxBase64Offset = 0xFFFFFFFFFULL }; // 64^6, including 0
Nico Rieck01143f92014-02-25 09:50:40 +0000415
Nico Rieck9d2c15e2014-02-22 16:12:20 +0000416// Encode a string table entry offset in base 64, padded to 6 chars, and
417// prefixed with a double slash: '//AAAAAA', '//AAAAAB', ...
418// Buffer must be at least 8 bytes large. No terminating null appended.
Rafael Espindola11e9e212015-05-27 14:37:12 +0000419static void encodeBase64StringEntry(char *Buffer, uint64_t Value) {
Nico Rieck01143f92014-02-25 09:50:40 +0000420 assert(Value > Max7DecimalOffset && Value <= MaxBase64Offset &&
Nico Rieck9d2c15e2014-02-22 16:12:20 +0000421 "Illegal section name encoding for value");
422
423 static const char Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
424 "abcdefghijklmnopqrstuvwxyz"
425 "0123456789+/";
426
427 Buffer[0] = '/';
428 Buffer[1] = '/';
429
Rafael Espindola11e9e212015-05-27 14:37:12 +0000430 char *Ptr = Buffer + 7;
Nico Rieck9d2c15e2014-02-22 16:12:20 +0000431 for (unsigned i = 0; i < 6; ++i) {
432 unsigned Rem = Value % 64;
433 Value /= 64;
434 *(Ptr--) = Alphabet[Rem];
435 }
436}
437
Hans Wennborgf26bfc12014-09-29 22:43:20 +0000438void WinCOFFObjectWriter::SetSectionName(COFFSection &S) {
Rui Ueyamaa39d1482017-02-15 01:09:20 +0000439 if (S.Name.size() <= COFF::NameSize) {
Michael J. Spencerd6283772010-09-27 08:58:26 +0000440 std::memcpy(S.Header.Name, S.Name.c_str(), S.Name.size());
Rui Ueyamaa39d1482017-02-15 01:09:20 +0000441 return;
David Majnemerf088f522016-01-24 20:46:11 +0000442 }
Rui Ueyamaa39d1482017-02-15 01:09:20 +0000443
444 uint64_t StringTableEntry = Strings.getOffset(S.Name);
445 if (StringTableEntry <= Max7DecimalOffset) {
Rui Ueyama4b58f5772017-02-15 01:48:33 +0000446 SmallVector<char, COFF::NameSize> Buffer;
447 Twine('/').concat(Twine(StringTableEntry)).toVector(Buffer);
448 assert(Buffer.size() <= COFF::NameSize && Buffer.size() >= 2);
449 std::memcpy(S.Header.Name, Buffer.data(), Buffer.size());
Rui Ueyamaa39d1482017-02-15 01:09:20 +0000450 return;
451 }
452 if (StringTableEntry <= MaxBase64Offset) {
453 // Starting with 10,000,000, offsets are encoded as base64.
454 encodeBase64StringEntry(S.Header.Name, StringTableEntry);
455 return;
456 }
457 report_fatal_error("COFF string table is greater than 64 GB.");
Michael J. Spencerd6283772010-09-27 08:58:26 +0000458}
459
Hans Wennborgf26bfc12014-09-29 22:43:20 +0000460void WinCOFFObjectWriter::SetSymbolName(COFFSymbol &S) {
461 if (S.Name.size() > COFF::NameSize)
462 S.set_name_offset(Strings.getOffset(S.Name));
463 else
Michael J. Spencerd6283772010-09-27 08:58:26 +0000464 std::memcpy(S.Data.Name, S.Name.c_str(), S.Name.size());
Michael J. Spencerd6283772010-09-27 08:58:26 +0000465}
466
Michael J. Spencerd6283772010-09-27 08:58:26 +0000467bool WinCOFFObjectWriter::IsPhysicalSection(COFFSection *S) {
Rafael Espindola11e9e212015-05-27 14:37:12 +0000468 return (S->Header.Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) ==
469 0;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000470}
471
472//------------------------------------------------------------------------------
473// entity writing methods
474
475void WinCOFFObjectWriter::WriteFileHeader(const COFF::header &Header) {
David Majnemer4d571592014-09-15 19:42:42 +0000476 if (UseBigObj) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000477 W.write<uint16_t>(COFF::IMAGE_FILE_MACHINE_UNKNOWN);
478 W.write<uint16_t>(0xFFFF);
479 W.write<uint16_t>(COFF::BigObjHeader::MinBigObjectVersion);
480 W.write<uint16_t>(Header.Machine);
481 W.write<uint32_t>(Header.TimeDateStamp);
482 W.OS.write(COFF::BigObjMagic, sizeof(COFF::BigObjMagic));
483 W.write<uint32_t>(0);
484 W.write<uint32_t>(0);
485 W.write<uint32_t>(0);
486 W.write<uint32_t>(0);
487 W.write<uint32_t>(Header.NumberOfSections);
488 W.write<uint32_t>(Header.PointerToSymbolTable);
489 W.write<uint32_t>(Header.NumberOfSymbols);
David Majnemer4d571592014-09-15 19:42:42 +0000490 } else {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000491 W.write<uint16_t>(Header.Machine);
492 W.write<uint16_t>(static_cast<int16_t>(Header.NumberOfSections));
493 W.write<uint32_t>(Header.TimeDateStamp);
494 W.write<uint32_t>(Header.PointerToSymbolTable);
495 W.write<uint32_t>(Header.NumberOfSymbols);
496 W.write<uint16_t>(Header.SizeOfOptionalHeader);
497 W.write<uint16_t>(Header.Characteristics);
David Majnemer4d571592014-09-15 19:42:42 +0000498 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000499}
500
David Blaikief564ab62014-04-15 05:25:03 +0000501void WinCOFFObjectWriter::WriteSymbol(const COFFSymbol &S) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000502 W.OS.write(S.Data.Name, COFF::NameSize);
503 W.write<uint32_t>(S.Data.Value);
David Majnemer4d571592014-09-15 19:42:42 +0000504 if (UseBigObj)
Peter Collingbournef17b1492018-05-21 18:17:42 +0000505 W.write<uint32_t>(S.Data.SectionNumber);
David Majnemer4d571592014-09-15 19:42:42 +0000506 else
Peter Collingbournef17b1492018-05-21 18:17:42 +0000507 W.write<uint16_t>(static_cast<int16_t>(S.Data.SectionNumber));
508 W.write<uint16_t>(S.Data.Type);
509 W.OS << char(S.Data.StorageClass);
510 W.OS << char(S.Data.NumberOfAuxSymbols);
David Blaikief564ab62014-04-15 05:25:03 +0000511 WriteAuxiliarySymbols(S.Aux);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000512}
513
514void WinCOFFObjectWriter::WriteAuxiliarySymbols(
Rafael Espindola11e9e212015-05-27 14:37:12 +0000515 const COFFSymbol::AuxiliarySymbols &S) {
Benjamin Kramer7b4658f2016-06-26 14:49:00 +0000516 for (const AuxSymbol &i : S) {
517 switch (i.AuxType) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000518 case ATFunctionDefinition:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000519 W.write<uint32_t>(i.Aux.FunctionDefinition.TagIndex);
520 W.write<uint32_t>(i.Aux.FunctionDefinition.TotalSize);
521 W.write<uint32_t>(i.Aux.FunctionDefinition.PointerToLinenumber);
522 W.write<uint32_t>(i.Aux.FunctionDefinition.PointerToNextFunction);
523 W.OS.write_zeros(sizeof(i.Aux.FunctionDefinition.unused));
David Majnemer4d571592014-09-15 19:42:42 +0000524 if (UseBigObj)
Peter Collingbournef17b1492018-05-21 18:17:42 +0000525 W.OS.write_zeros(COFF::Symbol32Size - COFF::Symbol16Size);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000526 break;
527 case ATbfAndefSymbol:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000528 W.OS.write_zeros(sizeof(i.Aux.bfAndefSymbol.unused1));
529 W.write<uint16_t>(i.Aux.bfAndefSymbol.Linenumber);
530 W.OS.write_zeros(sizeof(i.Aux.bfAndefSymbol.unused2));
531 W.write<uint32_t>(i.Aux.bfAndefSymbol.PointerToNextFunction);
532 W.OS.write_zeros(sizeof(i.Aux.bfAndefSymbol.unused3));
David Majnemer4d571592014-09-15 19:42:42 +0000533 if (UseBigObj)
Peter Collingbournef17b1492018-05-21 18:17:42 +0000534 W.OS.write_zeros(COFF::Symbol32Size - COFF::Symbol16Size);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000535 break;
536 case ATWeakExternal:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000537 W.write<uint32_t>(i.Aux.WeakExternal.TagIndex);
538 W.write<uint32_t>(i.Aux.WeakExternal.Characteristics);
539 W.OS.write_zeros(sizeof(i.Aux.WeakExternal.unused));
David Majnemer4d571592014-09-15 19:42:42 +0000540 if (UseBigObj)
Peter Collingbournef17b1492018-05-21 18:17:42 +0000541 W.OS.write_zeros(COFF::Symbol32Size - COFF::Symbol16Size);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000542 break;
543 case ATFile:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000544 W.OS.write(reinterpret_cast<const char *>(&i.Aux),
545 UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000546 break;
547 case ATSectionDefinition:
Peter Collingbournef17b1492018-05-21 18:17:42 +0000548 W.write<uint32_t>(i.Aux.SectionDefinition.Length);
549 W.write<uint16_t>(i.Aux.SectionDefinition.NumberOfRelocations);
550 W.write<uint16_t>(i.Aux.SectionDefinition.NumberOfLinenumbers);
551 W.write<uint32_t>(i.Aux.SectionDefinition.CheckSum);
552 W.write<uint16_t>(static_cast<int16_t>(i.Aux.SectionDefinition.Number));
553 W.OS << char(i.Aux.SectionDefinition.Selection);
554 W.OS.write_zeros(sizeof(i.Aux.SectionDefinition.unused));
555 W.write<uint16_t>(static_cast<int16_t>(i.Aux.SectionDefinition.Number >> 16));
David Majnemer4d571592014-09-15 19:42:42 +0000556 if (UseBigObj)
Peter Collingbournef17b1492018-05-21 18:17:42 +0000557 W.OS.write_zeros(COFF::Symbol32Size - COFF::Symbol16Size);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000558 break;
559 }
560 }
561}
562
Rui Ueyamaac20c172017-02-17 17:32:54 +0000563// Write the section header.
564void WinCOFFObjectWriter::writeSectionHeaders() {
565 // Section numbers must be monotonically increasing in the section
566 // header, but our Sections array is not sorted by section number,
567 // so make a copy of Sections and sort it.
568 std::vector<COFFSection *> Arr;
569 for (auto &Section : Sections)
570 Arr.push_back(Section.get());
Mandeep Singh Grangdb456ef2018-04-13 19:47:01 +0000571 llvm::sort(Arr.begin(), Arr.end(),
572 [](const COFFSection *A, const COFFSection *B) {
573 return A->Number < B->Number;
574 });
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000575
Rui Ueyamaac20c172017-02-17 17:32:54 +0000576 for (auto &Section : Arr) {
577 if (Section->Number == -1)
578 continue;
579
580 COFF::section &S = Section->Header;
581 if (Section->Relocations.size() >= 0xffff)
582 S.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL;
Peter Collingbournef17b1492018-05-21 18:17:42 +0000583 W.OS.write(S.Name, COFF::NameSize);
584 W.write<uint32_t>(S.VirtualSize);
585 W.write<uint32_t>(S.VirtualAddress);
586 W.write<uint32_t>(S.SizeOfRawData);
587 W.write<uint32_t>(S.PointerToRawData);
588 W.write<uint32_t>(S.PointerToRelocations);
589 W.write<uint32_t>(S.PointerToLineNumbers);
590 W.write<uint16_t>(S.NumberOfRelocations);
591 W.write<uint16_t>(S.NumberOfLineNumbers);
592 W.write<uint32_t>(S.Characteristics);
Rui Ueyamaac20c172017-02-17 17:32:54 +0000593 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000594}
595
596void WinCOFFObjectWriter::WriteRelocation(const COFF::relocation &R) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000597 W.write<uint32_t>(R.VirtualAddress);
598 W.write<uint32_t>(R.SymbolTableIndex);
599 W.write<uint16_t>(R.Type);
Chris Lattner2c52b792010-07-11 22:07:02 +0000600}
601
Rui Ueyama26ca0bd2017-02-16 02:56:06 +0000602// Write MCSec's contents. What this function does is essentially
603// "Asm.writeSectionData(&MCSec, Layout)", but it's a bit complicated
604// because it needs to compute a CRC.
605uint32_t WinCOFFObjectWriter::writeSectionContents(MCAssembler &Asm,
606 const MCAsmLayout &Layout,
607 const MCSection &MCSec) {
608 // Save the contents of the section to a temporary buffer, we need this
609 // to CRC the data before we dump it into the object file.
610 SmallVector<char, 128> Buf;
611 raw_svector_ostream VecOS(Buf);
Peter Collingbourne147db3e2018-05-21 18:11:35 +0000612 Asm.writeSectionData(VecOS, &MCSec, Layout);
Rui Ueyama26ca0bd2017-02-16 02:56:06 +0000613
614 // Write the section contents to the object file.
Peter Collingbournef17b1492018-05-21 18:17:42 +0000615 W.OS << Buf;
Rui Ueyama26ca0bd2017-02-16 02:56:06 +0000616
617 // Calculate our CRC with an initial value of '0', this is not how
618 // JamCRC is specified but it aligns with the expected output.
619 JamCRC JC(/*Init=*/0);
620 JC.update(Buf);
621 return JC.getCRC();
622}
623
Rui Ueyamaaf20f102017-02-16 02:35:48 +0000624void WinCOFFObjectWriter::writeSection(MCAssembler &Asm,
625 const MCAsmLayout &Layout,
626 const COFFSection &Sec,
627 const MCSection &MCSec) {
628 if (Sec.Number == -1)
629 return;
630
Rui Ueyama26ca0bd2017-02-16 02:56:06 +0000631 // Write the section contents.
Rui Ueyamaaf20f102017-02-16 02:35:48 +0000632 if (Sec.Header.PointerToRawData != 0) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000633 assert(W.OS.tell() <= Sec.Header.PointerToRawData &&
Rui Ueyamaaf20f102017-02-16 02:35:48 +0000634 "Section::PointerToRawData is insane!");
635
Peter Collingbournef17b1492018-05-21 18:17:42 +0000636 unsigned PaddingSize = Sec.Header.PointerToRawData - W.OS.tell();
Rui Ueyama26ca0bd2017-02-16 02:56:06 +0000637 assert(PaddingSize < 4 &&
Rui Ueyamaaf20f102017-02-16 02:35:48 +0000638 "Should only need at most three bytes of padding!");
Peter Collingbournef17b1492018-05-21 18:17:42 +0000639 W.OS.write_zeros(PaddingSize);
Rui Ueyamaaf20f102017-02-16 02:35:48 +0000640
Rui Ueyama26ca0bd2017-02-16 02:56:06 +0000641 uint32_t CRC = writeSectionContents(Asm, Layout, MCSec);
Rui Ueyamaaf20f102017-02-16 02:35:48 +0000642
643 // Update the section definition auxiliary symbol to record the CRC.
644 COFFSection *Sec = SectionMap[&MCSec];
645 COFFSymbol::AuxiliarySymbols &AuxSyms = Sec->Symbol->Aux;
646 assert(AuxSyms.size() == 1 && AuxSyms[0].AuxType == ATSectionDefinition);
647 AuxSymbol &SecDef = AuxSyms[0];
Rui Ueyama26ca0bd2017-02-16 02:56:06 +0000648 SecDef.Aux.SectionDefinition.CheckSum = CRC;
Rui Ueyamaaf20f102017-02-16 02:35:48 +0000649 }
650
Rui Ueyama26ca0bd2017-02-16 02:56:06 +0000651 // Write relocations for this section.
Rui Ueyamaaf20f102017-02-16 02:35:48 +0000652 if (Sec.Relocations.empty()) {
653 assert(Sec.Header.PointerToRelocations == 0 &&
654 "Section::PointerToRelocations is insane!");
655 return;
656 }
657
Peter Collingbournef17b1492018-05-21 18:17:42 +0000658 assert(W.OS.tell() == Sec.Header.PointerToRelocations &&
Rui Ueyamaaf20f102017-02-16 02:35:48 +0000659 "Section::PointerToRelocations is insane!");
660
661 if (Sec.Relocations.size() >= 0xffff) {
662 // In case of overflow, write actual relocation count as first
663 // relocation. Including the synthetic reloc itself (+ 1).
664 COFF::relocation R;
665 R.VirtualAddress = Sec.Relocations.size() + 1;
666 R.SymbolTableIndex = 0;
667 R.Type = 0;
668 WriteRelocation(R);
669 }
670
671 for (const auto &Relocation : Sec.Relocations)
672 WriteRelocation(Relocation.Data);
673}
674
Chris Lattner2c52b792010-07-11 22:07:02 +0000675////////////////////////////////////////////////////////////////////////////////
676// MCObjectWriter interface implementations
677
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000678void WinCOFFObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000679 const MCAsmLayout &Layout) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000680 // "Define" each section & symbol. This creates section & symbol
Michael J. Spencerd6283772010-09-27 08:58:26 +0000681 // entries in the staging area.
Yaron Keren56919ef2014-12-04 08:30:39 +0000682 for (const auto &Section : Asm)
Rafael Espindolaf59264f2015-05-27 14:45:54 +0000683 defineSection(static_cast<const MCSectionCOFF &>(Section));
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000684
Duncan P. N. Exon Smithf48de1c2015-05-16 00:35:24 +0000685 for (const MCSymbol &Symbol : Asm.symbols())
Peter Collingbourne8359a6a2015-11-26 23:29:27 +0000686 if (!Symbol.isTemporary())
Duncan P. N. Exon Smithe8fb3a22015-05-20 19:34:08 +0000687 DefineSymbol(Symbol, Asm, Layout);
Chris Lattner2c52b792010-07-11 22:07:02 +0000688}
689
Jim Grosbach36e60e92015-06-04 22:24:41 +0000690bool WinCOFFObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(
Duncan P. N. Exon Smithd81ba532015-05-16 01:01:55 +0000691 const MCAssembler &Asm, const MCSymbol &SymA, const MCFragment &FB,
Rafael Espindola35d61892015-04-17 21:15:17 +0000692 bool InSet, bool IsPCRel) const {
Reid Kleckner5a5ac652018-03-14 19:24:32 +0000693 // Don't drop relocations between functions, even if they are in the same text
694 // section. Multiple Visual C++ linker features depend on having the
695 // relocations present. The /INCREMENTAL flag will cause these relocations to
696 // point to thunks, and the /GUARD:CF flag assumes that it can use relocations
697 // to approximate the set of all address taken functions. LLD's implementation
698 // of /GUARD:CF also relies on the existance of these relocations.
Pete Cooperad9f9c32015-06-08 17:17:12 +0000699 uint16_t Type = cast<MCSymbolCOFF>(SymA).getType();
Reid Kleckner5a5ac652018-03-14 19:24:32 +0000700 if ((Type >> COFF::SCT_COMPLEX_TYPE_SHIFT) == COFF::IMAGE_SYM_DTYPE_FUNCTION)
David Majnemer2cc4bc772014-11-11 08:43:57 +0000701 return false;
Jim Grosbach36e60e92015-06-04 22:24:41 +0000702 return MCObjectWriter::isSymbolRefDifferenceFullyResolvedImpl(Asm, SymA, FB,
Rafael Espindola35d61892015-04-17 21:15:17 +0000703 InSet, IsPCRel);
David Majnemer2cc4bc772014-11-11 08:43:57 +0000704}
705
Rafael Espindolaceecfe5b2017-07-11 23:56:10 +0000706void WinCOFFObjectWriter::recordRelocation(MCAssembler &Asm,
707 const MCAsmLayout &Layout,
708 const MCFragment *Fragment,
709 const MCFixup &Fixup, MCValue Target,
710 uint64_t &FixedValue) {
Craig Topperbb694de2014-04-13 04:57:38 +0000711 assert(Target.getSymA() && "Relocation must reference a symbol!");
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000712
Peter Collingbourne8359a6a2015-11-26 23:29:27 +0000713 const MCSymbol &A = Target.getSymA()->getSymbol();
Oliver Stannard9be59af2015-11-17 10:00:43 +0000714 if (!A.isRegistered()) {
715 Asm.getContext().reportError(Fixup.getLoc(),
Rafael Espindola11e9e212015-05-27 14:37:12 +0000716 Twine("symbol '") + A.getName() +
717 "' can not be undefined");
Oliver Stannard9be59af2015-11-17 10:00:43 +0000718 return;
719 }
Reid Kleckner85dfb682015-09-16 16:26:29 +0000720 if (A.isTemporary() && A.isUndefined()) {
Oliver Stannard9be59af2015-11-17 10:00:43 +0000721 Asm.getContext().reportError(Fixup.getLoc(),
Reid Kleckner85dfb682015-09-16 16:26:29 +0000722 Twine("assembler label '") + A.getName() +
723 "' can not be undefined");
Oliver Stannard9be59af2015-11-17 10:00:43 +0000724 return;
Reid Kleckner85dfb682015-09-16 16:26:29 +0000725 }
Timur Iskhodzhanov3e4ac4e2014-01-30 21:13:05 +0000726
Rui Ueyama62376782017-02-16 01:06:45 +0000727 MCSection *MCSec = Fragment->getParent();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000728
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000729 // Mark this symbol as requiring an entry in the symbol table.
Rui Ueyama62376782017-02-16 01:06:45 +0000730 assert(SectionMap.find(MCSec) != SectionMap.end() &&
Jim Grosbach56ed0bb2015-06-04 23:25:54 +0000731 "Section must already have been defined in executePostLayoutBinding!");
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000732
Rui Ueyama62376782017-02-16 01:06:45 +0000733 COFFSection *Sec = SectionMap[MCSec];
Rafael Espindolaed164772011-04-20 14:01:45 +0000734 const MCSymbolRefExpr *SymB = Target.getSymB();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000735
David Majnemera45a1762014-01-06 07:39:46 +0000736 if (SymB) {
737 const MCSymbol *B = &SymB->getSymbol();
Oliver Stannard9be59af2015-11-17 10:00:43 +0000738 if (!B->getFragment()) {
739 Asm.getContext().reportError(
David Majnemera45a1762014-01-06 07:39:46 +0000740 Fixup.getLoc(),
741 Twine("symbol '") + B->getName() +
742 "' can not be undefined in a subtraction expression");
Oliver Stannard9be59af2015-11-17 10:00:43 +0000743 return;
744 }
David Majnemera45a1762014-01-06 07:39:46 +0000745
Rafael Espindolac3dc4862011-04-21 18:36:50 +0000746 // Offset of the symbol in the section
Duncan P. N. Exon Smith2a404832015-05-19 23:53:20 +0000747 int64_t OffsetOfB = Layout.getSymbolOffset(*B);
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000748
David Majnemer1de30942015-02-09 06:31:31 +0000749 // Offset of the relocation in the section
750 int64_t OffsetOfRelocation =
751 Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
752
Andy Ayers9e5c8512015-05-14 01:10:41 +0000753 FixedValue = (OffsetOfRelocation - OffsetOfB) + Target.getConstant();
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000754 } else {
755 FixedValue = Target.getConstant();
756 }
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000757
758 COFFRelocation Reloc;
759
Daniel Dunbar727be432010-07-31 21:08:54 +0000760 Reloc.Data.SymbolTableIndex = 0;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000761 Reloc.Data.VirtualAddress = Layout.getFragmentOffset(Fragment);
Michael J. Spencerd6283772010-09-27 08:58:26 +0000762
Michael J. Spencera65d17a2010-10-05 19:48:12 +0000763 // Turn relocations for temporary symbols into section relocations.
Rafael Espindolad2edd132017-06-22 21:57:04 +0000764 if (A.isTemporary()) {
Peter Collingbourne8359a6a2015-11-26 23:29:27 +0000765 MCSection *TargetSection = &A.getSection();
766 assert(
767 SectionMap.find(TargetSection) != SectionMap.end() &&
768 "Section must already have been defined in executePostLayoutBinding!");
769 Reloc.Symb = SectionMap[TargetSection]->Symbol;
770 FixedValue += Layout.getSymbolOffset(A);
771 } else {
772 assert(
773 SymbolMap.find(&A) != SymbolMap.end() &&
774 "Symbol must already have been defined in executePostLayoutBinding!");
775 Reloc.Symb = SymbolMap[&A];
776 }
Michael J. Spencerd6283772010-09-27 08:58:26 +0000777
778 ++Reloc.Symb->Relocations;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000779
780 Reloc.Data.VirtualAddress += Fixup.getOffset();
Rafael Espindola58173b92017-06-23 04:07:44 +0000781 Reloc.Data.Type = TargetObjectWriter->getRelocType(
782 Asm.getContext(), Target, Fixup, SymB, Asm.getBackend());
Rafael Espindolae61724a2011-12-22 22:21:47 +0000783
784 // FIXME: Can anyone explain what this does other than adjust for the size
785 // of the offset?
Saleem Abdulrasool2c080512014-04-13 20:47:55 +0000786 if ((Header.Machine == COFF::IMAGE_FILE_MACHINE_AMD64 &&
787 Reloc.Data.Type == COFF::IMAGE_REL_AMD64_REL32) ||
788 (Header.Machine == COFF::IMAGE_FILE_MACHINE_I386 &&
789 Reloc.Data.Type == COFF::IMAGE_REL_I386_REL32))
Michael J. Spencerccd28d02010-08-24 21:04:52 +0000790 FixedValue += 4;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000791
Saleem Abdulrasool84b952b2014-04-27 03:48:22 +0000792 if (Header.Machine == COFF::IMAGE_FILE_MACHINE_ARMNT) {
793 switch (Reloc.Data.Type) {
794 case COFF::IMAGE_REL_ARM_ABSOLUTE:
795 case COFF::IMAGE_REL_ARM_ADDR32:
796 case COFF::IMAGE_REL_ARM_ADDR32NB:
797 case COFF::IMAGE_REL_ARM_TOKEN:
798 case COFF::IMAGE_REL_ARM_SECTION:
799 case COFF::IMAGE_REL_ARM_SECREL:
800 break;
801 case COFF::IMAGE_REL_ARM_BRANCH11:
802 case COFF::IMAGE_REL_ARM_BLX11:
Rafael Espindola11e9e212015-05-27 14:37:12 +0000803 // IMAGE_REL_ARM_BRANCH11 and IMAGE_REL_ARM_BLX11 are only used for
804 // pre-ARMv7, which implicitly rules it out of ARMNT (it would be valid
805 // for Windows CE).
Saleem Abdulrasool84b952b2014-04-27 03:48:22 +0000806 case COFF::IMAGE_REL_ARM_BRANCH24:
807 case COFF::IMAGE_REL_ARM_BLX24:
808 case COFF::IMAGE_REL_ARM_MOV32A:
809 // IMAGE_REL_ARM_BRANCH24, IMAGE_REL_ARM_BLX24, IMAGE_REL_ARM_MOV32A are
810 // only used for ARM mode code, which is documented as being unsupported
Alp Tokerbeaca192014-05-15 01:52:21 +0000811 // by Windows on ARM. Empirical proof indicates that masm is able to
Saleem Abdulrasool84b952b2014-04-27 03:48:22 +0000812 // generate the relocations however the rest of the MSVC toolchain is
813 // unable to handle it.
814 llvm_unreachable("unsupported relocation");
815 break;
816 case COFF::IMAGE_REL_ARM_MOV32T:
817 break;
818 case COFF::IMAGE_REL_ARM_BRANCH20T:
819 case COFF::IMAGE_REL_ARM_BRANCH24T:
820 case COFF::IMAGE_REL_ARM_BLX23T:
821 // IMAGE_REL_BRANCH20T, IMAGE_REL_ARM_BRANCH24T, IMAGE_REL_ARM_BLX23T all
822 // perform a 4 byte adjustment to the relocation. Relative branches are
823 // offset by 4 on ARM, however, because there is no RELA relocations, all
824 // branches are offset by 4.
825 FixedValue = FixedValue + 4;
826 break;
827 }
828 }
829
Simon Pilgrimf2fbf432016-11-20 13:47:59 +0000830 // The fixed value never makes sense for section indices, ignore it.
David Majnemer408b5e62016-02-05 01:55:49 +0000831 if (Fixup.getKind() == FK_SecRel_2)
832 FixedValue = 0;
833
Saleem Abdulrasool54bed122014-05-21 23:17:50 +0000834 if (TargetObjectWriter->recordRelocation(Fixup))
Rui Ueyama62376782017-02-16 01:06:45 +0000835 Sec->Relocations.push_back(Reloc);
836}
837
838static std::time_t getTime() {
839 std::time_t Now = time(nullptr);
840 if (Now < 0 || !isUInt<32>(Now))
841 return UINT32_MAX;
842 return Now;
Chris Lattner2c52b792010-07-11 22:07:02 +0000843}
844
Rui Ueyamaaf20f102017-02-16 02:35:48 +0000845// Create .file symbols.
846void WinCOFFObjectWriter::createFileSymbols(MCAssembler &Asm) {
Rafael Espindola66f3c9c2015-05-28 18:03:20 +0000847 for (const std::string &Name : Asm.getFileNames()) {
David Majnemer4d571592014-09-15 19:42:42 +0000848 // round up to calculate the number of auxiliary symbols required
849 unsigned SymbolSize = UseBigObj ? COFF::Symbol32Size : COFF::Symbol16Size;
Rafael Espindola66f3c9c2015-05-28 18:03:20 +0000850 unsigned Count = (Name.size() + SymbolSize - 1) / SymbolSize;
David Majnemer4d571592014-09-15 19:42:42 +0000851
Rui Ueyamaaf20f102017-02-16 02:35:48 +0000852 COFFSymbol *File = createSymbol(".file");
853 File->Data.SectionNumber = COFF::IMAGE_SYM_DEBUG;
854 File->Data.StorageClass = COFF::IMAGE_SYM_CLASS_FILE;
855 File->Aux.resize(Count);
David Majnemer4d571592014-09-15 19:42:42 +0000856
857 unsigned Offset = 0;
Rafael Espindola66f3c9c2015-05-28 18:03:20 +0000858 unsigned Length = Name.size();
Rui Ueyamaaf20f102017-02-16 02:35:48 +0000859 for (auto &Aux : File->Aux) {
David Majnemer4d571592014-09-15 19:42:42 +0000860 Aux.AuxType = ATFile;
861
862 if (Length > SymbolSize) {
Rafael Espindola66f3c9c2015-05-28 18:03:20 +0000863 memcpy(&Aux.Aux, Name.c_str() + Offset, SymbolSize);
David Majnemer4d571592014-09-15 19:42:42 +0000864 Length = Length - SymbolSize;
865 } else {
Rafael Espindola66f3c9c2015-05-28 18:03:20 +0000866 memcpy(&Aux.Aux, Name.c_str() + Offset, Length);
David Majnemer4d571592014-09-15 19:42:42 +0000867 memset((char *)&Aux.Aux + Length, 0, SymbolSize - Length);
868 break;
869 }
870
871 Offset += SymbolSize;
872 }
873 }
Rui Ueyamaaf20f102017-02-16 02:35:48 +0000874}
875
Rui Ueyamaac20c172017-02-17 17:32:54 +0000876static bool isAssociative(const COFFSection &Section) {
877 return Section.Symbol->Aux[0].Aux.SectionDefinition.Selection ==
878 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
879}
880
Rui Ueyamaaf20f102017-02-16 02:35:48 +0000881void WinCOFFObjectWriter::assignSectionNumbers() {
882 size_t I = 1;
Rui Ueyamaac20c172017-02-17 17:32:54 +0000883 auto Assign = [&](COFFSection &Section) {
884 Section.Number = I;
885 Section.Symbol->Data.SectionNumber = I;
886 Section.Symbol->Aux[0].Aux.SectionDefinition.Number = I;
Rui Ueyamaaf20f102017-02-16 02:35:48 +0000887 ++I;
Rui Ueyamaac20c172017-02-17 17:32:54 +0000888 };
889
890 // Although it is not explicitly requested by the Microsoft COFF spec,
891 // we should avoid emitting forward associative section references,
892 // because MSVC link.exe as of 2017 cannot handle that.
893 for (const std::unique_ptr<COFFSection> &Section : Sections)
894 if (!isAssociative(*Section))
895 Assign(*Section);
896 for (const std::unique_ptr<COFFSection> &Section : Sections)
897 if (isAssociative(*Section))
898 Assign(*Section);
Rui Ueyamaaf20f102017-02-16 02:35:48 +0000899}
900
901// Assign file offsets to COFF object file structures.
902void WinCOFFObjectWriter::assignFileOffsets(MCAssembler &Asm,
903 const MCAsmLayout &Layout) {
Peter Collingbournef17b1492018-05-21 18:17:42 +0000904 unsigned Offset = W.OS.tell();
Rui Ueyamaaf20f102017-02-16 02:35:48 +0000905
906 Offset += UseBigObj ? COFF::Header32Size : COFF::Header16Size;
907 Offset += COFF::SectionSize * Header.NumberOfSections;
908
909 for (const auto &Section : Asm) {
910 COFFSection *Sec = SectionMap[&Section];
911
912 if (Sec->Number == -1)
913 continue;
914
915 Sec->Header.SizeOfRawData = Layout.getSectionAddressSize(&Section);
916
917 if (IsPhysicalSection(Sec)) {
918 // Align the section data to a four byte boundary.
919 Offset = alignTo(Offset, 4);
920 Sec->Header.PointerToRawData = Offset;
921
922 Offset += Sec->Header.SizeOfRawData;
923 }
924
925 if (!Sec->Relocations.empty()) {
926 bool RelocationsOverflow = Sec->Relocations.size() >= 0xffff;
927
928 if (RelocationsOverflow) {
929 // Signal overflow by setting NumberOfRelocations to max value. Actual
930 // size is found in reloc #0. Microsoft tools understand this.
931 Sec->Header.NumberOfRelocations = 0xffff;
932 } else {
933 Sec->Header.NumberOfRelocations = Sec->Relocations.size();
934 }
935 Sec->Header.PointerToRelocations = Offset;
936
937 if (RelocationsOverflow) {
938 // Reloc #0 will contain actual count, so make room for it.
939 Offset += COFF::RelocationSize;
940 }
941
942 Offset += COFF::RelocationSize * Sec->Relocations.size();
943
944 for (auto &Relocation : Sec->Relocations) {
945 assert(Relocation.Symb->getIndex() != -1);
946 Relocation.Data.SymbolTableIndex = Relocation.Symb->getIndex();
947 }
948 }
949
950 assert(Sec->Symbol->Aux.size() == 1 &&
951 "Section's symbol must have one aux!");
952 AuxSymbol &Aux = Sec->Symbol->Aux[0];
953 assert(Aux.AuxType == ATSectionDefinition &&
954 "Section's symbol's aux symbol must be a Section Definition!");
955 Aux.Aux.SectionDefinition.Length = Sec->Header.SizeOfRawData;
956 Aux.Aux.SectionDefinition.NumberOfRelocations =
957 Sec->Header.NumberOfRelocations;
958 Aux.Aux.SectionDefinition.NumberOfLinenumbers =
959 Sec->Header.NumberOfLineNumbers;
960 }
961
962 Header.PointerToSymbolTable = Offset;
963}
964
Peter Collingbourne438390f2018-05-21 18:23:50 +0000965uint64_t WinCOFFObjectWriter::writeObject(MCAssembler &Asm,
966 const MCAsmLayout &Layout) {
967 uint64_t StartOffset = W.OS.tell();
968
Rui Ueyamaaf20f102017-02-16 02:35:48 +0000969 if (Sections.size() > INT32_MAX)
970 report_fatal_error(
971 "PE COFF object files can't have more than 2147483647 sections");
972
973 UseBigObj = Sections.size() > COFF::MaxNumberOfSections16;
974 Header.NumberOfSections = Sections.size();
975 Header.NumberOfSymbols = 0;
976
977 assignSectionNumbers();
978 createFileSymbols(Asm);
David Majnemer4d571592014-09-15 19:42:42 +0000979
David Majnemer9ab5ff12014-08-28 04:02:50 +0000980 for (auto &Symbol : Symbols) {
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000981 // Update section number & offset for symbols that have them.
Rafael Espindola575f79a2014-05-01 13:37:57 +0000982 if (Symbol->Section)
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +0000983 Symbol->Data.SectionNumber = Symbol->Section->Number;
Peter Collingbourne8359a6a2015-11-26 23:29:27 +0000984 Symbol->setIndex(Header.NumberOfSymbols++);
985 // Update auxiliary symbol info.
986 Symbol->Data.NumberOfAuxSymbols = Symbol->Aux.size();
987 Header.NumberOfSymbols += Symbol->Data.NumberOfAuxSymbols;
Michael J. Spencerb5fc1382010-07-26 02:17:32 +0000988 }
989
Hans Wennborgf26bfc12014-09-29 22:43:20 +0000990 // Build string table.
991 for (const auto &S : Sections)
992 if (S->Name.size() > COFF::NameSize)
993 Strings.add(S->Name);
994 for (const auto &S : Symbols)
Peter Collingbourne8359a6a2015-11-26 23:29:27 +0000995 if (S->Name.size() > COFF::NameSize)
Hans Wennborgf26bfc12014-09-29 22:43:20 +0000996 Strings.add(S->Name);
Rafael Espindola21956e42015-10-23 21:48:05 +0000997 Strings.finalize();
Hans Wennborgf26bfc12014-09-29 22:43:20 +0000998
999 // Set names.
1000 for (const auto &S : Sections)
1001 SetSectionName(*S);
1002 for (auto &S : Symbols)
Peter Collingbourne8359a6a2015-11-26 23:29:27 +00001003 SetSymbolName(*S);
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001004
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001005 // Fixup weak external references.
Yaron Keren56919ef2014-12-04 08:30:39 +00001006 for (auto &Symbol : Symbols) {
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +00001007 if (Symbol->Other) {
David Majnemer4eecd302015-05-30 04:56:02 +00001008 assert(Symbol->getIndex() != -1);
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +00001009 assert(Symbol->Aux.size() == 1 && "Symbol must contain one aux symbol!");
1010 assert(Symbol->Aux[0].AuxType == ATWeakExternal &&
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001011 "Symbol's aux symbol must be a Weak External!");
David Majnemer4eecd302015-05-30 04:56:02 +00001012 Symbol->Aux[0].Aux.WeakExternal.TagIndex = Symbol->Other->getIndex();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001013 }
1014 }
1015
Nico Riecka37acf72013-07-06 12:13:10 +00001016 // Fixup associative COMDAT sections.
Yaron Keren56919ef2014-12-04 08:30:39 +00001017 for (auto &Section : Sections) {
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +00001018 if (Section->Symbol->Aux[0].Aux.SectionDefinition.Selection !=
Nico Riecka37acf72013-07-06 12:13:10 +00001019 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1020 continue;
1021
Rafael Espindolaf59264f2015-05-27 14:45:54 +00001022 const MCSectionCOFF &MCSec = *Section->MCSection;
Reid Kleckner602c0da2018-08-16 21:34:41 +00001023 const MCSymbol *AssocMCSym = MCSec.getCOMDATSymbol();
1024 assert(AssocMCSym);
Nico Riecka37acf72013-07-06 12:13:10 +00001025
Reid Kleckner602c0da2018-08-16 21:34:41 +00001026 // It's an error to try to associate with an undefined symbol or a symbol
1027 // without a section.
1028 if (!AssocMCSym->isInSection()) {
1029 Asm.getContext().reportError(
1030 SMLoc(), Twine("cannot make section ") + MCSec.getSectionName() +
1031 Twine(" associative with sectionless symbol ") +
1032 AssocMCSym->getName());
1033 continue;
1034 }
1035
1036 const auto *AssocMCSec = cast<MCSectionCOFF>(&AssocMCSym->getSection());
1037 assert(SectionMap.count(AssocMCSec));
1038 COFFSection *AssocSec = SectionMap[AssocMCSec];
Nico Riecka37acf72013-07-06 12:13:10 +00001039
1040 // Skip this section if the associated section is unused.
Reid Kleckner602c0da2018-08-16 21:34:41 +00001041 if (AssocSec->Number == -1)
Nico Riecka37acf72013-07-06 12:13:10 +00001042 continue;
1043
Reid Kleckner602c0da2018-08-16 21:34:41 +00001044 Section->Symbol->Aux[0].Aux.SectionDefinition.Number = AssocSec->Number;
Nico Riecka37acf72013-07-06 12:13:10 +00001045 }
1046
Rui Ueyamaaf20f102017-02-16 02:35:48 +00001047 assignFileOffsets(Asm, Layout);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001048
David Majnemer088ba022015-09-01 23:46:11 +00001049 // MS LINK expects to be able to use this timestamp to implement their
1050 // /INCREMENTAL feature.
David Majnemer03e2cc32015-12-21 22:09:27 +00001051 if (Asm.isIncrementalLinkerCompatible()) {
Rui Ueyama62376782017-02-16 01:06:45 +00001052 Header.TimeDateStamp = getTime();
David Majnemer03e2cc32015-12-21 22:09:27 +00001053 } else {
Nico Weber891419a2016-01-06 19:05:19 +00001054 // Have deterministic output if /INCREMENTAL isn't needed. Also matches GNU.
David Majnemer03e2cc32015-12-21 22:09:27 +00001055 Header.TimeDateStamp = 0;
1056 }
Michael J. Spencera6cfbeb2010-08-03 04:43:33 +00001057
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001058 // Write it all to disk...
1059 WriteFileHeader(Header);
Rui Ueyamaac20c172017-02-17 17:32:54 +00001060 writeSectionHeaders();
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001061
Rui Ueyamaaf20f102017-02-16 02:35:48 +00001062 // Write section contents.
1063 sections::iterator I = Sections.begin();
1064 sections::iterator IE = Sections.end();
1065 MCAssembler::iterator J = Asm.begin();
1066 MCAssembler::iterator JE = Asm.end();
1067 for (; I != IE && J != JE; ++I, ++J)
1068 writeSection(Asm, Layout, **I, *J);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001069
Peter Collingbournef17b1492018-05-21 18:17:42 +00001070 assert(W.OS.tell() == Header.PointerToSymbolTable &&
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001071 "Header::PointerToSymbolTable is insane!");
1072
Rui Ueyamaaf20f102017-02-16 02:35:48 +00001073 // Write a symbol table.
Yaron Keren56919ef2014-12-04 08:30:39 +00001074 for (auto &Symbol : Symbols)
David Majnemer4eecd302015-05-30 04:56:02 +00001075 if (Symbol->getIndex() != -1)
Saleem Abdulrasool09ced5f2014-04-28 03:34:48 +00001076 WriteSymbol(*Symbol);
Michael J. Spencerb5fc1382010-07-26 02:17:32 +00001077
Rui Ueyamaaf20f102017-02-16 02:35:48 +00001078 // Write a string table, which completes the entire COFF file.
Peter Collingbournef17b1492018-05-21 18:17:42 +00001079 Strings.write(W.OS);
Peter Collingbourne438390f2018-05-21 18:23:50 +00001080
1081 return W.OS.tell() - StartOffset;
Chris Lattner2c52b792010-07-11 22:07:02 +00001082}
1083
Rafael Espindola11e9e212015-05-27 14:37:12 +00001084MCWinCOFFObjectTargetWriter::MCWinCOFFObjectTargetWriter(unsigned Machine_)
1085 : Machine(Machine_) {}
Rafael Espindola908d2ed2011-12-24 02:14:02 +00001086
Juergen Ributzkad12ccbd2013-11-19 00:57:56 +00001087// Pin the vtable to this file.
1088void MCWinCOFFObjectTargetWriter::anchor() {}
1089
Chris Lattner2c52b792010-07-11 22:07:02 +00001090//------------------------------------------------------------------------------
1091// WinCOFFObjectWriter factory function
1092
Lang Hames60fbc7c2017-10-10 16:28:07 +00001093std::unique_ptr<MCObjectWriter> llvm::createWinCOFFObjectWriter(
Lang Hames77dff392017-10-10 00:50:29 +00001094 std::unique_ptr<MCWinCOFFObjectTargetWriter> MOTW, raw_pwrite_stream &OS) {
Lang Hames60fbc7c2017-10-10 16:28:07 +00001095 return llvm::make_unique<WinCOFFObjectWriter>(std::move(MOTW), OS);
Michael J. Spencerc2129372010-07-26 03:01:28 +00001096}