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