xref: /freebsd/contrib/llvm-project/clang/lib/Driver/ToolChains/OpenBSD.cpp (revision 02e9120893770924227138ba49df1edb3896112a)
1 //===--- OpenBSD.cpp - OpenBSD ToolChain Implementations --------*- C++ -*-===//
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 #include "OpenBSD.h"
10 #include "Arch/ARM.h"
11 #include "Arch/Mips.h"
12 #include "Arch/Sparc.h"
13 #include "CommonArgs.h"
14 #include "clang/Config/config.h"
15 #include "clang/Driver/Compilation.h"
16 #include "clang/Driver/Options.h"
17 #include "clang/Driver/SanitizerArgs.h"
18 #include "llvm/Option/ArgList.h"
19 #include "llvm/Support/Path.h"
20 #include "llvm/Support/VirtualFileSystem.h"
21 
22 using namespace clang::driver;
23 using namespace clang::driver::tools;
24 using namespace clang::driver::toolchains;
25 using namespace clang;
26 using namespace llvm::opt;
27 
28 void openbsd::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
29                                       const InputInfo &Output,
30                                       const InputInfoList &Inputs,
31                                       const ArgList &Args,
32                                       const char *LinkingOutput) const {
33   const toolchains::OpenBSD &ToolChain =
34       static_cast<const toolchains::OpenBSD &>(getToolChain());
35   const Driver &D = ToolChain.getDriver();
36   const llvm::Triple &Triple = ToolChain.getTriple();
37 
38   claimNoWarnArgs(Args);
39   ArgStringList CmdArgs;
40 
41   switch (ToolChain.getArch()) {
42   case llvm::Triple::x86:
43     // When building 32-bit code on OpenBSD/amd64, we have to explicitly
44     // instruct as in the base system to assemble 32-bit code.
45     CmdArgs.push_back("--32");
46     break;
47 
48   case llvm::Triple::arm:
49   case llvm::Triple::armeb: {
50     StringRef MArch, MCPU;
51     arm::getARMArchCPUFromArgs(Args, MArch, MCPU, /*FromAs*/ true);
52     std::string Arch = arm::getARMTargetCPU(MCPU, MArch, Triple);
53     CmdArgs.push_back(Args.MakeArgString("-mcpu=" + Arch));
54     break;
55   }
56 
57   case llvm::Triple::ppc:
58     CmdArgs.push_back("-mppc");
59     CmdArgs.push_back("-many");
60     break;
61 
62   case llvm::Triple::sparcv9: {
63     CmdArgs.push_back("-64");
64     std::string CPU = getCPUName(D, Args, Triple);
65     CmdArgs.push_back(sparc::getSparcAsmModeForCPU(CPU, Triple));
66     AddAssemblerKPIC(ToolChain, Args, CmdArgs);
67     break;
68   }
69 
70   case llvm::Triple::mips64:
71   case llvm::Triple::mips64el: {
72     StringRef CPUName;
73     StringRef ABIName;
74     mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
75 
76     CmdArgs.push_back("-march");
77     CmdArgs.push_back(CPUName.data());
78 
79     CmdArgs.push_back("-mabi");
80     CmdArgs.push_back(mips::getGnuCompatibleMipsABIName(ABIName).data());
81 
82     if (Triple.isLittleEndian())
83       CmdArgs.push_back("-EL");
84     else
85       CmdArgs.push_back("-EB");
86 
87     AddAssemblerKPIC(ToolChain, Args, CmdArgs);
88     break;
89   }
90 
91   default:
92     break;
93   }
94 
95   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, options::OPT_Xassembler);
96 
97   CmdArgs.push_back("-o");
98   CmdArgs.push_back(Output.getFilename());
99 
100   for (const auto &II : Inputs)
101     CmdArgs.push_back(II.getFilename());
102 
103   const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("as"));
104   C.addCommand(std::make_unique<Command>(JA, *this,
105                                          ResponseFileSupport::AtFileCurCP(),
106                                          Exec, CmdArgs, Inputs, Output));
107 }
108 
109 void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
110                                    const InputInfo &Output,
111                                    const InputInfoList &Inputs,
112                                    const ArgList &Args,
113                                    const char *LinkingOutput) const {
114   const toolchains::OpenBSD &ToolChain =
115       static_cast<const toolchains::OpenBSD &>(getToolChain());
116   const Driver &D = ToolChain.getDriver();
117   const llvm::Triple::ArchType Arch = ToolChain.getArch();
118   ArgStringList CmdArgs;
119   bool Static = Args.hasArg(options::OPT_static);
120   bool Shared = Args.hasArg(options::OPT_shared);
121   bool Profiling = Args.hasArg(options::OPT_pg);
122   bool Pie = Args.hasArg(options::OPT_pie);
123   bool Nopie = Args.hasArg(options::OPT_nopie);
124 
125   // Silence warning for "clang -g foo.o -o foo"
126   Args.ClaimAllArgs(options::OPT_g_Group);
127   // and "clang -emit-llvm foo.o -o foo"
128   Args.ClaimAllArgs(options::OPT_emit_llvm);
129   // and for "clang -w foo.o -o foo". Other warning options are already
130   // handled somewhere else.
131   Args.ClaimAllArgs(options::OPT_w);
132 
133   if (!D.SysRoot.empty())
134     CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
135 
136   if (Arch == llvm::Triple::mips64)
137     CmdArgs.push_back("-EB");
138   else if (Arch == llvm::Triple::mips64el)
139     CmdArgs.push_back("-EL");
140 
141   if (!Args.hasArg(options::OPT_nostdlib) && !Shared) {
142     CmdArgs.push_back("-e");
143     CmdArgs.push_back("__start");
144   }
145 
146   CmdArgs.push_back("--eh-frame-hdr");
147   if (Static) {
148     CmdArgs.push_back("-Bstatic");
149   } else {
150     if (Args.hasArg(options::OPT_rdynamic))
151       CmdArgs.push_back("-export-dynamic");
152     CmdArgs.push_back("-Bdynamic");
153     if (Shared) {
154       CmdArgs.push_back("-shared");
155     } else if (!Args.hasArg(options::OPT_r)) {
156       CmdArgs.push_back("-dynamic-linker");
157       CmdArgs.push_back("/usr/libexec/ld.so");
158     }
159   }
160 
161   if (Pie)
162     CmdArgs.push_back("-pie");
163   if (Nopie || Profiling)
164     CmdArgs.push_back("-nopie");
165 
166   if (Arch == llvm::Triple::riscv64)
167     CmdArgs.push_back("-X");
168 
169   if (Output.isFilename()) {
170     CmdArgs.push_back("-o");
171     CmdArgs.push_back(Output.getFilename());
172   } else {
173     assert(Output.isNothing() && "Invalid output.");
174   }
175 
176   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
177                    options::OPT_r)) {
178     const char *crt0 = nullptr;
179     const char *crtbegin = nullptr;
180     if (!Shared) {
181       if (Profiling)
182         crt0 = "gcrt0.o";
183       else if (Static && !Nopie)
184         crt0 = "rcrt0.o";
185       else
186         crt0 = "crt0.o";
187       crtbegin = "crtbegin.o";
188     } else {
189       crtbegin = "crtbeginS.o";
190     }
191 
192     if (crt0)
193       CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt0)));
194     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin)));
195   }
196 
197   Args.AddAllArgs(CmdArgs, options::OPT_L);
198   ToolChain.AddFilePathLibArgs(Args, CmdArgs);
199   Args.AddAllArgs(CmdArgs,
200                   {options::OPT_T_Group, options::OPT_s, options::OPT_t,
201                    options::OPT_Z_Flag, options::OPT_r});
202 
203   bool NeedsSanitizerDeps = addSanitizerRuntimes(ToolChain, Args, CmdArgs);
204   bool NeedsXRayDeps = addXRayRuntime(ToolChain, Args, CmdArgs);
205   AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA);
206 
207   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs,
208                    options::OPT_r)) {
209     // Use the static OpenMP runtime with -static-openmp
210     bool StaticOpenMP = Args.hasArg(options::OPT_static_openmp) && !Static;
211     addOpenMPRuntime(CmdArgs, ToolChain, Args, StaticOpenMP);
212 
213     if (D.CCCIsCXX()) {
214       if (ToolChain.ShouldLinkCXXStdlib(Args))
215         ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
216       if (Profiling)
217         CmdArgs.push_back("-lm_p");
218       else
219         CmdArgs.push_back("-lm");
220     }
221     if (NeedsSanitizerDeps) {
222       CmdArgs.push_back(ToolChain.getCompilerRTArgString(Args, "builtins"));
223       linkSanitizerRuntimeDeps(ToolChain, CmdArgs);
224     }
225     if (NeedsXRayDeps) {
226       CmdArgs.push_back(ToolChain.getCompilerRTArgString(Args, "builtins"));
227       linkXRayRuntimeDeps(ToolChain, CmdArgs);
228     }
229     // FIXME: For some reason GCC passes -lgcc before adding
230     // the default system libraries. Just mimic this for now.
231     CmdArgs.push_back("-lcompiler_rt");
232 
233     if (Args.hasArg(options::OPT_pthread)) {
234       if (!Shared && Profiling)
235         CmdArgs.push_back("-lpthread_p");
236       else
237         CmdArgs.push_back("-lpthread");
238     }
239 
240     if (!Shared) {
241       if (Profiling)
242         CmdArgs.push_back("-lc_p");
243       else
244         CmdArgs.push_back("-lc");
245     }
246 
247     CmdArgs.push_back("-lcompiler_rt");
248   }
249 
250   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
251                    options::OPT_r)) {
252     const char *crtend = nullptr;
253     if (!Shared)
254       crtend = "crtend.o";
255     else
256       crtend = "crtendS.o";
257 
258     CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend)));
259   }
260 
261   ToolChain.addProfileRTLibs(Args, CmdArgs);
262 
263   const char *Exec = Args.MakeArgString(ToolChain.GetLinkerPath());
264   C.addCommand(std::make_unique<Command>(JA, *this,
265                                          ResponseFileSupport::AtFileCurCP(),
266                                          Exec, CmdArgs, Inputs, Output));
267 }
268 
269 SanitizerMask OpenBSD::getSupportedSanitizers() const {
270   const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
271   const bool IsX86_64 = getTriple().getArch() == llvm::Triple::x86_64;
272 
273   // For future use, only UBsan at the moment
274   SanitizerMask Res = ToolChain::getSupportedSanitizers();
275 
276   if (IsX86 || IsX86_64) {
277     Res |= SanitizerKind::Vptr;
278     Res |= SanitizerKind::Fuzzer;
279     Res |= SanitizerKind::FuzzerNoLink;
280   }
281 
282   return Res;
283 }
284 
285 /// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly.
286 
287 OpenBSD::OpenBSD(const Driver &D, const llvm::Triple &Triple,
288                  const ArgList &Args)
289     : Generic_ELF(D, Triple, Args) {
290   getFilePaths().push_back(concat(getDriver().SysRoot, "/usr/lib"));
291 }
292 
293 void OpenBSD::AddClangSystemIncludeArgs(
294     const llvm::opt::ArgList &DriverArgs,
295     llvm::opt::ArgStringList &CC1Args) const {
296   const Driver &D = getDriver();
297 
298   if (DriverArgs.hasArg(clang::driver::options::OPT_nostdinc))
299     return;
300 
301   if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
302     SmallString<128> Dir(D.ResourceDir);
303     llvm::sys::path::append(Dir, "include");
304     addSystemInclude(DriverArgs, CC1Args, Dir.str());
305   }
306 
307   if (DriverArgs.hasArg(options::OPT_nostdlibinc))
308     return;
309 
310   // Check for configure-time C include directories.
311   StringRef CIncludeDirs(C_INCLUDE_DIRS);
312   if (CIncludeDirs != "") {
313     SmallVector<StringRef, 5> dirs;
314     CIncludeDirs.split(dirs, ":");
315     for (StringRef dir : dirs) {
316       StringRef Prefix =
317           llvm::sys::path::is_absolute(dir) ? StringRef(D.SysRoot) : "";
318       addExternCSystemInclude(DriverArgs, CC1Args, Prefix + dir);
319     }
320     return;
321   }
322 
323   addExternCSystemInclude(DriverArgs, CC1Args,
324                           concat(D.SysRoot, "/usr/include"));
325 }
326 
327 void OpenBSD::addLibCxxIncludePaths(const llvm::opt::ArgList &DriverArgs,
328                                     llvm::opt::ArgStringList &CC1Args) const {
329   addSystemInclude(DriverArgs, CC1Args,
330                    concat(getDriver().SysRoot, "/usr/include/c++/v1"));
331 }
332 
333 void OpenBSD::AddCXXStdlibLibArgs(const ArgList &Args,
334                                   ArgStringList &CmdArgs) const {
335   bool Profiling = Args.hasArg(options::OPT_pg);
336 
337   CmdArgs.push_back(Profiling ? "-lc++_p" : "-lc++");
338   if (Args.hasArg(options::OPT_fexperimental_library))
339     CmdArgs.push_back("-lc++experimental");
340   CmdArgs.push_back(Profiling ? "-lc++abi_p" : "-lc++abi");
341   CmdArgs.push_back(Profiling ? "-lpthread_p" : "-lpthread");
342 }
343 
344 std::string OpenBSD::getCompilerRT(const ArgList &Args, StringRef Component,
345                                    FileType Type) const {
346   if (Component == "builtins") {
347     SmallString<128> Path(getDriver().SysRoot);
348     llvm::sys::path::append(Path, "/usr/lib/libcompiler_rt.a");
349     return std::string(Path.str());
350   }
351   SmallString<128> P(getDriver().ResourceDir);
352   std::string CRTBasename =
353       buildCompilerRTBasename(Args, Component, Type, /*AddArch=*/false);
354   llvm::sys::path::append(P, "lib", CRTBasename);
355   // Checks if this is the base system case which uses a different location.
356   if (getVFS().exists(P))
357     return std::string(P.str());
358   return ToolChain::getCompilerRT(Args, Component, Type);
359 }
360 
361 Tool *OpenBSD::buildAssembler() const {
362   return new tools::openbsd::Assembler(*this);
363 }
364 
365 Tool *OpenBSD::buildLinker() const { return new tools::openbsd::Linker(*this); }
366 
367 bool OpenBSD::HasNativeLLVMSupport() const { return true; }
368 
369 ToolChain::UnwindTableLevel
370 OpenBSD::getDefaultUnwindTableLevel(const ArgList &Args) const {
371   switch (getArch()) {
372   case llvm::Triple::arm:
373     return UnwindTableLevel::None;
374   default:
375     return UnwindTableLevel::Asynchronous;
376   }
377 }
378