1 //===- llvm/MC/MCWinCOFFStreamer.cpp --------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains an implementation of a Windows COFF object file streamer.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/MC/MCWinCOFFStreamer.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/Triple.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/BinaryFormat/COFF.h"
19 #include "llvm/MC/MCAsmBackend.h"
20 #include "llvm/MC/MCAssembler.h"
21 #include "llvm/MC/MCCodeEmitter.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCFixup.h"
25 #include "llvm/MC/MCFragment.h"
26 #include "llvm/MC/MCObjectFileInfo.h"
27 #include "llvm/MC/MCObjectStreamer.h"
28 #include "llvm/MC/MCObjectWriter.h"
29 #include "llvm/MC/MCSection.h"
30 #include "llvm/MC/MCSymbolCOFF.h"
31 #include "llvm/Support/Casting.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/SMLoc.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include <algorithm>
37 #include <cstdint>
38 
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "WinCOFFStreamer"
42 
43 MCWinCOFFStreamer::MCWinCOFFStreamer(MCContext &Context,
44                                      std::unique_ptr<MCAsmBackend> MAB,
45                                      std::unique_ptr<MCCodeEmitter> CE,
46                                      std::unique_ptr<MCObjectWriter> OW)
47     : MCObjectStreamer(Context, std::move(MAB), std::move(OW), std::move(CE)),
48       CurSymbol(nullptr) {}
49 
50 void MCWinCOFFStreamer::emitInstToData(const MCInst &Inst,
51                                        const MCSubtargetInfo &STI) {
52   MCDataFragment *DF = getOrCreateDataFragment();
53 
54   SmallVector<MCFixup, 4> Fixups;
55   SmallString<256> Code;
56   raw_svector_ostream VecOS(Code);
57   getAssembler().getEmitter().encodeInstruction(Inst, VecOS, Fixups, STI);
58 
59   // Add the fixups and data.
60   for (unsigned i = 0, e = Fixups.size(); i != e; ++i) {
61     Fixups[i].setOffset(Fixups[i].getOffset() + DF->getContents().size());
62     DF->getFixups().push_back(Fixups[i]);
63   }
64   DF->setHasInstructions(STI);
65   DF->getContents().append(Code.begin(), Code.end());
66 }
67 
68 void MCWinCOFFStreamer::initSections(bool NoExecStack,
69                                      const MCSubtargetInfo &STI) {
70   // FIXME: this is identical to the ELF one.
71   // This emulates the same behavior of GNU as. This makes it easier
72   // to compare the output as the major sections are in the same order.
73   switchSection(getContext().getObjectFileInfo()->getTextSection());
74   emitCodeAlignment(Align(4), &STI);
75 
76   switchSection(getContext().getObjectFileInfo()->getDataSection());
77   emitCodeAlignment(Align(4), &STI);
78 
79   switchSection(getContext().getObjectFileInfo()->getBSSSection());
80   emitCodeAlignment(Align(4), &STI);
81 
82   switchSection(getContext().getObjectFileInfo()->getTextSection());
83 }
84 
85 void MCWinCOFFStreamer::emitLabel(MCSymbol *S, SMLoc Loc) {
86   auto *Symbol = cast<MCSymbolCOFF>(S);
87   MCObjectStreamer::emitLabel(Symbol, Loc);
88 }
89 
90 void MCWinCOFFStreamer::emitAssemblerFlag(MCAssemblerFlag Flag) {
91   // Let the target do whatever target specific stuff it needs to do.
92   getAssembler().getBackend().handleAssemblerFlag(Flag);
93 
94   switch (Flag) {
95   // None of these require COFF specific handling.
96   case MCAF_SyntaxUnified:
97   case MCAF_Code16:
98   case MCAF_Code32:
99   case MCAF_Code64:
100     break;
101   case MCAF_SubsectionsViaSymbols:
102     llvm_unreachable("COFF doesn't support .subsections_via_symbols");
103   }
104 }
105 
106 void MCWinCOFFStreamer::emitThumbFunc(MCSymbol *Func) {
107   llvm_unreachable("not implemented");
108 }
109 
110 bool MCWinCOFFStreamer::emitSymbolAttribute(MCSymbol *S,
111                                             MCSymbolAttr Attribute) {
112   auto *Symbol = cast<MCSymbolCOFF>(S);
113   getAssembler().registerSymbol(*Symbol);
114 
115   switch (Attribute) {
116   default: return false;
117   case MCSA_WeakReference:
118   case MCSA_Weak:
119     Symbol->setIsWeakExternal();
120     Symbol->setExternal(true);
121     break;
122   case MCSA_Global:
123     Symbol->setExternal(true);
124     break;
125   case MCSA_AltEntry:
126     llvm_unreachable("COFF doesn't support the .alt_entry attribute");
127   }
128 
129   return true;
130 }
131 
132 void MCWinCOFFStreamer::emitSymbolDesc(MCSymbol *Symbol, unsigned DescValue) {
133   llvm_unreachable("not implemented");
134 }
135 
136 void MCWinCOFFStreamer::beginCOFFSymbolDef(MCSymbol const *S) {
137   auto *Symbol = cast<MCSymbolCOFF>(S);
138   if (CurSymbol)
139     Error("starting a new symbol definition without completing the "
140           "previous one");
141   CurSymbol = Symbol;
142 }
143 
144 void MCWinCOFFStreamer::emitCOFFSymbolStorageClass(int StorageClass) {
145   if (!CurSymbol) {
146     Error("storage class specified outside of symbol definition");
147     return;
148   }
149 
150   if (StorageClass & ~COFF::SSC_Invalid) {
151     Error("storage class value '" + Twine(StorageClass) +
152                "' out of range");
153     return;
154   }
155 
156   getAssembler().registerSymbol(*CurSymbol);
157   cast<MCSymbolCOFF>(CurSymbol)->setClass((uint16_t)StorageClass);
158 }
159 
160 void MCWinCOFFStreamer::emitCOFFSymbolType(int Type) {
161   if (!CurSymbol) {
162     Error("symbol type specified outside of a symbol definition");
163     return;
164   }
165 
166   if (Type & ~0xffff) {
167     Error("type value '" + Twine(Type) + "' out of range");
168     return;
169   }
170 
171   getAssembler().registerSymbol(*CurSymbol);
172   cast<MCSymbolCOFF>(CurSymbol)->setType((uint16_t)Type);
173 }
174 
175 void MCWinCOFFStreamer::endCOFFSymbolDef() {
176   if (!CurSymbol)
177     Error("ending symbol definition without starting one");
178   CurSymbol = nullptr;
179 }
180 
181 void MCWinCOFFStreamer::emitCOFFSafeSEH(MCSymbol const *Symbol) {
182   // SafeSEH is a feature specific to 32-bit x86.  It does not exist (and is
183   // unnecessary) on all platforms which use table-based exception dispatch.
184   if (getContext().getTargetTriple().getArch() != Triple::x86)
185     return;
186 
187   const MCSymbolCOFF *CSymbol = cast<MCSymbolCOFF>(Symbol);
188   if (CSymbol->isSafeSEH())
189     return;
190 
191   MCSection *SXData = getContext().getObjectFileInfo()->getSXDataSection();
192   getAssembler().registerSection(*SXData);
193   SXData->ensureMinAlignment(Align(4));
194 
195   new MCSymbolIdFragment(Symbol, SXData);
196 
197   getAssembler().registerSymbol(*Symbol);
198   CSymbol->setIsSafeSEH();
199 
200   // The Microsoft linker requires that the symbol type of a handler be
201   // function. Go ahead and oblige it here.
202   CSymbol->setType(COFF::IMAGE_SYM_DTYPE_FUNCTION
203                    << COFF::SCT_COMPLEX_TYPE_SHIFT);
204 }
205 
206 void MCWinCOFFStreamer::emitCOFFSymbolIndex(MCSymbol const *Symbol) {
207   MCSection *Sec = getCurrentSectionOnly();
208   getAssembler().registerSection(*Sec);
209   Sec->ensureMinAlignment(Align(4));
210 
211   new MCSymbolIdFragment(Symbol, getCurrentSectionOnly());
212 
213   getAssembler().registerSymbol(*Symbol);
214 }
215 
216 void MCWinCOFFStreamer::emitCOFFSectionIndex(const MCSymbol *Symbol) {
217   visitUsedSymbol(*Symbol);
218   MCDataFragment *DF = getOrCreateDataFragment();
219   const MCSymbolRefExpr *SRE = MCSymbolRefExpr::create(Symbol, getContext());
220   MCFixup Fixup = MCFixup::create(DF->getContents().size(), SRE, FK_SecRel_2);
221   DF->getFixups().push_back(Fixup);
222   DF->getContents().resize(DF->getContents().size() + 2, 0);
223 }
224 
225 void MCWinCOFFStreamer::emitCOFFSecRel32(const MCSymbol *Symbol,
226                                          uint64_t Offset) {
227   visitUsedSymbol(*Symbol);
228   MCDataFragment *DF = getOrCreateDataFragment();
229   // Create Symbol A for the relocation relative reference.
230   const MCExpr *MCE = MCSymbolRefExpr::create(Symbol, getContext());
231   // Add the constant offset, if given.
232   if (Offset)
233     MCE = MCBinaryExpr::createAdd(
234         MCE, MCConstantExpr::create(Offset, getContext()), getContext());
235   // Build the secrel32 relocation.
236   MCFixup Fixup = MCFixup::create(DF->getContents().size(), MCE, FK_SecRel_4);
237   // Record the relocation.
238   DF->getFixups().push_back(Fixup);
239   // Emit 4 bytes (zeros) to the object file.
240   DF->getContents().resize(DF->getContents().size() + 4, 0);
241 }
242 
243 void MCWinCOFFStreamer::emitCOFFImgRel32(const MCSymbol *Symbol,
244                                          int64_t Offset) {
245   visitUsedSymbol(*Symbol);
246   MCDataFragment *DF = getOrCreateDataFragment();
247   // Create Symbol A for the relocation relative reference.
248   const MCExpr *MCE = MCSymbolRefExpr::create(
249       Symbol, MCSymbolRefExpr::VK_COFF_IMGREL32, getContext());
250   // Add the constant offset, if given.
251   if (Offset)
252     MCE = MCBinaryExpr::createAdd(
253         MCE, MCConstantExpr::create(Offset, getContext()), getContext());
254   // Build the imgrel relocation.
255   MCFixup Fixup = MCFixup::create(DF->getContents().size(), MCE, FK_Data_4);
256   // Record the relocation.
257   DF->getFixups().push_back(Fixup);
258   // Emit 4 bytes (zeros) to the object file.
259   DF->getContents().resize(DF->getContents().size() + 4, 0);
260 }
261 
262 void MCWinCOFFStreamer::emitCommonSymbol(MCSymbol *S, uint64_t Size,
263                                          Align ByteAlignment) {
264   auto *Symbol = cast<MCSymbolCOFF>(S);
265 
266   const Triple &T = getContext().getTargetTriple();
267   if (T.isWindowsMSVCEnvironment()) {
268     if (ByteAlignment > 32)
269       report_fatal_error("alignment is limited to 32-bytes");
270 
271     // Round size up to alignment so that we will honor the alignment request.
272     Size = std::max(Size, ByteAlignment.value());
273   }
274 
275   getAssembler().registerSymbol(*Symbol);
276   Symbol->setExternal(true);
277   Symbol->setCommon(Size, ByteAlignment);
278 
279   if (!T.isWindowsMSVCEnvironment() && ByteAlignment > 1) {
280     SmallString<128> Directive;
281     raw_svector_ostream OS(Directive);
282     const MCObjectFileInfo *MFI = getContext().getObjectFileInfo();
283 
284     OS << " -aligncomm:\"" << Symbol->getName() << "\","
285        << Log2_32_Ceil(ByteAlignment.value());
286 
287     pushSection();
288     switchSection(MFI->getDrectveSection());
289     emitBytes(Directive);
290     popSection();
291   }
292 }
293 
294 void MCWinCOFFStreamer::emitLocalCommonSymbol(MCSymbol *S, uint64_t Size,
295                                               Align ByteAlignment) {
296   auto *Symbol = cast<MCSymbolCOFF>(S);
297 
298   MCSection *Section = getContext().getObjectFileInfo()->getBSSSection();
299   pushSection();
300   switchSection(Section);
301   emitValueToAlignment(ByteAlignment, 0, 1, 0);
302   emitLabel(Symbol);
303   Symbol->setExternal(false);
304   emitZeros(Size);
305   popSection();
306 }
307 
308 void MCWinCOFFStreamer::emitWeakReference(MCSymbol *AliasS,
309                                           const MCSymbol *Symbol) {
310   auto *Alias = cast<MCSymbolCOFF>(AliasS);
311   emitSymbolAttribute(Alias, MCSA_Weak);
312 
313   getAssembler().registerSymbol(*Symbol);
314   Alias->setVariableValue(MCSymbolRefExpr::create(
315       Symbol, MCSymbolRefExpr::VK_WEAKREF, getContext()));
316 }
317 
318 void MCWinCOFFStreamer::emitZerofill(MCSection *Section, MCSymbol *Symbol,
319                                      uint64_t Size, Align ByteAlignment,
320                                      SMLoc Loc) {
321   llvm_unreachable("not implemented");
322 }
323 
324 void MCWinCOFFStreamer::emitTBSSSymbol(MCSection *Section, MCSymbol *Symbol,
325                                        uint64_t Size, Align ByteAlignment) {
326   llvm_unreachable("not implemented");
327 }
328 
329 // TODO: Implement this if you want to emit .comment section in COFF obj files.
330 void MCWinCOFFStreamer::emitIdent(StringRef IdentString) {
331   llvm_unreachable("not implemented");
332 }
333 
334 void MCWinCOFFStreamer::emitWinEHHandlerData(SMLoc Loc) {
335   llvm_unreachable("not implemented");
336 }
337 
338 void MCWinCOFFStreamer::emitCGProfileEntry(const MCSymbolRefExpr *From,
339                                            const MCSymbolRefExpr *To,
340                                            uint64_t Count) {
341   // Ignore temporary symbols for now.
342   if (!From->getSymbol().isTemporary() && !To->getSymbol().isTemporary())
343     getAssembler().CGProfile.push_back({From, To, Count});
344 }
345 
346 void MCWinCOFFStreamer::finalizeCGProfileEntry(const MCSymbolRefExpr *&SRE) {
347   const MCSymbol *S = &SRE->getSymbol();
348   bool Created;
349   getAssembler().registerSymbol(*S, &Created);
350   if (Created)
351     cast<MCSymbolCOFF>(S)->setExternal(true);
352 }
353 
354 void MCWinCOFFStreamer::finalizeCGProfile() {
355   for (MCAssembler::CGProfileEntry &E : getAssembler().CGProfile) {
356     finalizeCGProfileEntry(E.From);
357     finalizeCGProfileEntry(E.To);
358   }
359 }
360 
361 void MCWinCOFFStreamer::finishImpl() {
362   finalizeCGProfile();
363 
364   MCObjectStreamer::finishImpl();
365 }
366 
367 void MCWinCOFFStreamer::Error(const Twine &Msg) const {
368   getContext().reportError(SMLoc(), Msg);
369 }
370