1//===--- Solaris.cpp - Solaris 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 "Solaris.h"
10#include "CommonArgs.h"
11#include "Gnu.h"
12#include "clang/Basic/LangStandard.h"
13#include "clang/Config/config.h"
14#include "clang/Driver/Compilation.h"
15#include "clang/Driver/Driver.h"
16#include "clang/Driver/DriverDiagnostic.h"
17#include "clang/Driver/Options.h"
18#include "clang/Driver/SanitizerArgs.h"
19#include "clang/Driver/ToolChain.h"
20#include "llvm/ADT/StringSwitch.h"
21#include "llvm/Option/ArgList.h"
22#include "llvm/Support/FileSystem.h"
23#include "llvm/Support/Path.h"
24
25using namespace clang::driver;
26using namespace clang::driver::tools;
27using namespace clang::driver::toolchains;
28using namespace clang;
29using namespace llvm::opt;
30
31void solaris::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
32 const InputInfo &Output,
33 const InputInfoList &Inputs,
34 const ArgList &Args,
35 const char *LinkingOutput) const {
36 // Just call the Gnu version, which enforces gas on Solaris.
37 gnutools::Assembler::ConstructJob(C, JA, Output, Inputs, TCArgs: Args, LinkingOutput);
38}
39
40bool solaris::isLinkerGnuLd(const ToolChain &TC, const ArgList &Args) {
41 // Only used if targetting Solaris.
42 const Arg *A = Args.getLastArg(Ids: options::OPT_fuse_ld_EQ);
43 StringRef UseLinker = A ? A->getValue() : CLANG_DEFAULT_LINKER;
44 return UseLinker == "bfd" || UseLinker == "gld";
45}
46
47static bool getPIE(const ArgList &Args, const ToolChain &TC) {
48 if (Args.hasArg(Ids: options::OPT_shared) || Args.hasArg(Ids: options::OPT_static) ||
49 Args.hasArg(Ids: options::OPT_r))
50 return false;
51
52 return Args.hasFlag(Pos: options::OPT_pie, Neg: options::OPT_no_pie,
53 Default: TC.isPIEDefault(Args));
54}
55
56// FIXME: Need to handle CLANG_DEFAULT_LINKER here?
57std::string solaris::Linker::getLinkerPath(const ArgList &Args) const {
58 const ToolChain &ToolChain = getToolChain();
59 if (const Arg *A = Args.getLastArg(Ids: options::OPT_fuse_ld_EQ)) {
60 StringRef UseLinker = A->getValue();
61 if (!UseLinker.empty()) {
62 if (llvm::sys::path::is_absolute(path: UseLinker) &&
63 llvm::sys::fs::can_execute(Path: UseLinker))
64 return std::string(UseLinker);
65
66 // Accept 'bfd' and 'gld' as aliases for the GNU linker.
67 if (UseLinker == "bfd" || UseLinker == "gld")
68 // FIXME: Could also use /usr/bin/gld here.
69 return "/usr/gnu/bin/ld";
70
71 // Accept 'ld' as alias for the default linker
72 if (UseLinker != "ld")
73 ToolChain.getDriver().Diag(DiagID: diag::err_drv_invalid_linker_name)
74 << A->getAsString(Args);
75 }
76 }
77
78 // getDefaultLinker() always returns an absolute path.
79 return ToolChain.getDefaultLinker();
80}
81
82void solaris::Linker::ConstructJob(Compilation &C, const JobAction &JA,
83 const InputInfo &Output,
84 const InputInfoList &Inputs,
85 const ArgList &Args,
86 const char *LinkingOutput) const {
87 const auto &ToolChain = static_cast<const Solaris &>(getToolChain());
88 const Driver &D = ToolChain.getDriver();
89 const llvm::Triple::ArchType Arch = ToolChain.getArch();
90 const bool IsPIE = getPIE(Args, TC: ToolChain);
91 const bool LinkerIsGnuLd = isLinkerGnuLd(TC: ToolChain, Args);
92 ArgStringList CmdArgs;
93
94 // Demangle C++ names in errors. GNU ld already defaults to --demangle.
95 if (!LinkerIsGnuLd)
96 CmdArgs.push_back(Elt: "-C");
97
98 if (!Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_shared,
99 Ids: options::OPT_r)) {
100 CmdArgs.push_back(Elt: "-e");
101 CmdArgs.push_back(Elt: "_start");
102 }
103
104 if (IsPIE) {
105 if (LinkerIsGnuLd) {
106 CmdArgs.push_back(Elt: "-pie");
107 } else {
108 CmdArgs.push_back(Elt: "-z");
109 CmdArgs.push_back(Elt: "type=pie");
110 }
111 }
112
113 if (Args.hasArg(Ids: options::OPT_static)) {
114 CmdArgs.push_back(Elt: "-Bstatic");
115 CmdArgs.push_back(Elt: "-dn");
116 } else {
117 if (!Args.hasArg(Ids: options::OPT_r) && Args.hasArg(Ids: options::OPT_shared))
118 CmdArgs.push_back(Elt: "-shared");
119
120 // libpthread has been folded into libc since Solaris 10, no need to do
121 // anything for pthreads. Claim argument to avoid warning.
122 Args.ClaimAllArgs(Id0: options::OPT_pthread);
123 Args.ClaimAllArgs(Id0: options::OPT_pthreads);
124 }
125
126 if (LinkerIsGnuLd) {
127 // Set the correct linker emulation for 32- and 64-bit Solaris.
128 switch (Arch) {
129 case llvm::Triple::x86:
130 CmdArgs.push_back(Elt: "-m");
131 CmdArgs.push_back(Elt: "elf_i386_sol2");
132 break;
133 case llvm::Triple::x86_64:
134 CmdArgs.push_back(Elt: "-m");
135 CmdArgs.push_back(Elt: "elf_x86_64_sol2");
136 break;
137 case llvm::Triple::sparc:
138 CmdArgs.push_back(Elt: "-m");
139 CmdArgs.push_back(Elt: "elf32_sparc_sol2");
140 break;
141 case llvm::Triple::sparcv9:
142 CmdArgs.push_back(Elt: "-m");
143 CmdArgs.push_back(Elt: "elf64_sparc_sol2");
144 break;
145 default:
146 break;
147 }
148
149 if (Args.hasArg(Ids: options::OPT_rdynamic))
150 CmdArgs.push_back(Elt: "-export-dynamic");
151
152 CmdArgs.push_back(Elt: "--eh-frame-hdr");
153 } else {
154 // -rdynamic is a no-op with Solaris ld. Claim argument to avoid warning.
155 Args.ClaimAllArgs(Id0: options::OPT_rdynamic);
156 }
157
158 assert((Output.isFilename() || Output.isNothing()) && "Invalid output.");
159 if (Output.isFilename()) {
160 CmdArgs.push_back(Elt: "-o");
161 CmdArgs.push_back(Elt: Output.getFilename());
162 }
163
164 if (!Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nostartfiles,
165 Ids: options::OPT_r)) {
166 if (!Args.hasArg(Ids: options::OPT_shared))
167 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ToolChain.GetFilePath(Name: "crt1.o")));
168
169 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ToolChain.GetFilePath(Name: "crti.o")));
170
171 const Arg *Std = Args.getLastArg(Ids: options::OPT_std_EQ, Ids: options::OPT_ansi);
172 bool HaveAnsi = false;
173 const LangStandard *LangStd = nullptr;
174 if (Std) {
175 HaveAnsi = Std->getOption().matches(ID: options::OPT_ansi);
176 if (!HaveAnsi)
177 LangStd = LangStandard::getLangStandardForName(Name: Std->getValue());
178 }
179
180 const char *values_X = "values-Xa.o";
181 // Use values-Xc.o for -ansi, -std=c*, -std=iso9899:199409.
182 if (HaveAnsi || (LangStd && !LangStd->isGNUMode()))
183 values_X = "values-Xc.o";
184 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ToolChain.GetFilePath(Name: values_X)));
185
186 const char *values_xpg = "values-xpg6.o";
187 // Use values-xpg4.o for -std=c90, -std=gnu90, -std=iso9899:199409.
188 if (LangStd && LangStd->getLanguage() == Language::C && !LangStd->isC99())
189 values_xpg = "values-xpg4.o";
190 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ToolChain.GetFilePath(Name: values_xpg)));
191
192 const char *crtbegin = nullptr;
193 if (Args.hasArg(Ids: options::OPT_shared) || IsPIE)
194 crtbegin = "crtbeginS.o";
195 else
196 crtbegin = "crtbegin.o";
197 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ToolChain.GetFilePath(Name: crtbegin)));
198 // Add crtfastmath.o if available and fast math is enabled.
199 ToolChain.addFastMathRuntimeIfAvailable(Args, CmdArgs);
200 }
201
202 ToolChain.AddFilePathLibArgs(Args, CmdArgs);
203
204 Args.addAllArgs(Output&: CmdArgs, Ids: {options::OPT_L, options::OPT_T_Group});
205
206 bool NeedsSanitizerDeps = addSanitizerRuntimes(TC: ToolChain, Args, CmdArgs);
207 AddLinkerInputs(TC: ToolChain, Inputs, Args, CmdArgs, JA);
208
209 if (!Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nodefaultlibs,
210 Ids: options::OPT_r)) {
211 // Use the static OpenMP runtime with -static-openmp
212 bool StaticOpenMP = Args.hasArg(Ids: options::OPT_static_openmp) &&
213 !Args.hasArg(Ids: options::OPT_static);
214 addOpenMPRuntime(C, CmdArgs, TC: ToolChain, Args, ForceStaticHostRuntime: StaticOpenMP);
215
216 if (D.CCCIsCXX()) {
217 if (ToolChain.ShouldLinkCXXStdlib(Args))
218 ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs);
219 CmdArgs.push_back(Elt: "-lm");
220 }
221 // Silence warnings when linking C code with a C++ '-stdlib' argument.
222 Args.ClaimAllArgs(Id0: options::OPT_stdlib_EQ);
223 // Additional linker set-up and flags for Fortran. This is required in order
224 // to generate executables. As Fortran runtime depends on the C runtime,
225 // these dependencies need to be listed before the C runtime below.
226 if (D.IsFlangMode()) {
227 addFortranRuntimeLibraryPath(TC: getToolChain(), Args, CmdArgs);
228 addFortranRuntimeLibs(TC: getToolChain(), Args, CmdArgs);
229 CmdArgs.push_back(Elt: "-lm");
230 }
231 if (Args.hasArg(Ids: options::OPT_fstack_protector) ||
232 Args.hasArg(Ids: options::OPT_fstack_protector_strong) ||
233 Args.hasArg(Ids: options::OPT_fstack_protector_all)) {
234 // Explicitly link ssp libraries, not folded into Solaris libc.
235 CmdArgs.push_back(Elt: "-lssp_nonshared");
236 CmdArgs.push_back(Elt: "-lssp");
237 }
238 // LLVM support for atomics on 32-bit SPARC V8+ is incomplete, so
239 // forcibly link with libatomic as a workaround.
240 if (Arch == llvm::Triple::sparc) {
241 addAsNeededOption(TC: ToolChain, Args, CmdArgs, as_needed: true);
242 CmdArgs.push_back(Elt: "-latomic");
243 addAsNeededOption(TC: ToolChain, Args, CmdArgs, as_needed: false);
244 }
245 addAsNeededOption(TC: ToolChain, Args, CmdArgs, as_needed: true);
246 CmdArgs.push_back(Elt: "-lgcc_s");
247 addAsNeededOption(TC: ToolChain, Args, CmdArgs, as_needed: false);
248 CmdArgs.push_back(Elt: "-lc");
249 if (!Args.hasArg(Ids: options::OPT_shared)) {
250 CmdArgs.push_back(Elt: "-lgcc");
251 }
252 const SanitizerArgs &SA = ToolChain.getSanitizerArgs(JobArgs: Args);
253 if (NeedsSanitizerDeps) {
254 linkSanitizerRuntimeDeps(TC: ToolChain, Args, CmdArgs);
255
256 // Work around Solaris/amd64 ld bug when calling __tls_get_addr directly.
257 // However, ld -z relax=transtls is available since Solaris 11.2, but not
258 // in Illumos.
259 if (Arch == llvm::Triple::x86_64 &&
260 (SA.needsAsanRt() || SA.needsStatsRt() ||
261 (SA.needsUbsanRt() && !SA.requiresMinimalRuntime())) &&
262 !LinkerIsGnuLd) {
263 CmdArgs.push_back(Elt: "-z");
264 CmdArgs.push_back(Elt: "relax=transtls");
265 }
266 }
267 // Avoid AsanInitInternal cycle, Issue #64126.
268 if (ToolChain.getTriple().isX86() && SA.needsSharedRt() &&
269 SA.needsAsanRt()) {
270 CmdArgs.push_back(Elt: "-z");
271 CmdArgs.push_back(Elt: "now");
272 }
273 }
274
275 if (!Args.hasArg(Ids: options::OPT_nostdlib, Ids: options::OPT_nostartfiles,
276 Ids: options::OPT_r)) {
277 const char *crtend = nullptr;
278 if (Args.hasArg(Ids: options::OPT_shared) || IsPIE)
279 crtend = "crtendS.o";
280 else
281 crtend = "crtend.o";
282 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ToolChain.GetFilePath(Name: crtend)));
283 CmdArgs.push_back(Elt: Args.MakeArgString(Str: ToolChain.GetFilePath(Name: "crtn.o")));
284 }
285
286 ToolChain.addProfileRTLibs(Args, CmdArgs);
287
288 const char *Exec = Args.MakeArgString(Str: getLinkerPath(Args));
289 C.addCommand(C: std::make_unique<Command>(args: JA, args: *this, args: ResponseFileSupport::None(),
290 args&: Exec, args&: CmdArgs, args: Inputs, args: Output));
291}
292
293static StringRef getSolarisLibSuffix(const llvm::Triple &Triple) {
294 switch (Triple.getArch()) {
295 case llvm::Triple::x86:
296 case llvm::Triple::sparc:
297 default:
298 break;
299 case llvm::Triple::x86_64:
300 return "/amd64";
301 case llvm::Triple::sparcv9:
302 return "/sparcv9";
303 }
304 return "";
305}
306
307/// Solaris - Solaris tool chain which can call as(1) and ld(1) directly.
308
309Solaris::Solaris(const Driver &D, const llvm::Triple &Triple,
310 const ArgList &Args)
311 : Generic_ELF(D, Triple, Args) {
312
313 GCCInstallation.init(TargetTriple: Triple, Args);
314
315 StringRef LibSuffix = getSolarisLibSuffix(Triple);
316 path_list &Paths = getFilePaths();
317 if (GCCInstallation.isValid()) {
318 // On Solaris gcc uses both an architecture-specific path with triple in it
319 // as well as a more generic lib path (+arch suffix).
320 addPathIfExists(D,
321 Path: GCCInstallation.getInstallPath() +
322 GCCInstallation.getMultilib().gccSuffix(),
323 Paths);
324 addPathIfExists(D, Path: GCCInstallation.getParentLibPath() + LibSuffix, Paths);
325 }
326
327 // If we are currently running Clang inside of the requested system root,
328 // add its parent library path to those searched.
329 if (StringRef(D.Dir).starts_with(Prefix: D.SysRoot))
330 addPathIfExists(D, Path: D.Dir + "/../lib", Paths);
331
332 addPathIfExists(D, Path: D.SysRoot + "/usr/lib" + LibSuffix, Paths);
333}
334
335SanitizerMask Solaris::getSupportedSanitizers() const {
336 const bool IsX86 = getTriple().getArch() == llvm::Triple::x86;
337 SanitizerMask Res = ToolChain::getSupportedSanitizers();
338 // FIXME: Omit X86_64 until 64-bit support is figured out.
339 if (IsX86) {
340 Res |= SanitizerKind::Address;
341 Res |= SanitizerKind::PointerCompare;
342 Res |= SanitizerKind::PointerSubtract;
343 }
344 Res |= SanitizerKind::SafeStack;
345 Res |= SanitizerKind::Vptr;
346 return Res;
347}
348
349const char *Solaris::getDefaultLinker() const {
350 // FIXME: Only handle Solaris ld and GNU ld here.
351 return llvm::StringSwitch<const char *>(CLANG_DEFAULT_LINKER)
352 .Cases(S0: "bfd", S1: "gld", Value: "/usr/gnu/bin/ld")
353 .Default(Value: "/usr/bin/ld");
354}
355
356Tool *Solaris::buildAssembler() const {
357 return new tools::solaris::Assembler(*this);
358}
359
360Tool *Solaris::buildLinker() const { return new tools::solaris::Linker(*this); }
361
362void Solaris::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
363 ArgStringList &CC1Args) const {
364 const Driver &D = getDriver();
365
366 if (DriverArgs.hasArg(Ids: clang::driver::options::OPT_nostdinc))
367 return;
368
369 if (!DriverArgs.hasArg(Ids: options::OPT_nostdlibinc))
370 addSystemInclude(DriverArgs, CC1Args, Path: D.SysRoot + "/usr/local/include");
371
372 if (!DriverArgs.hasArg(Ids: options::OPT_nobuiltininc)) {
373 SmallString<128> P(D.ResourceDir);
374 llvm::sys::path::append(path&: P, a: "include");
375 addSystemInclude(DriverArgs, CC1Args, Path: P);
376 }
377
378 if (DriverArgs.hasArg(Ids: options::OPT_nostdlibinc))
379 return;
380
381 // Check for configure-time C include directories.
382 StringRef CIncludeDirs(C_INCLUDE_DIRS);
383 if (CIncludeDirs != "") {
384 SmallVector<StringRef, 5> dirs;
385 CIncludeDirs.split(A&: dirs, Separator: ":");
386 for (StringRef dir : dirs) {
387 StringRef Prefix =
388 llvm::sys::path::is_absolute(path: dir) ? "" : StringRef(D.SysRoot);
389 addExternCSystemInclude(DriverArgs, CC1Args, Path: Prefix + dir);
390 }
391 return;
392 }
393
394 // Add include directories specific to the selected multilib set and multilib.
395 if (GCCInstallation.isValid()) {
396 const MultilibSet::IncludeDirsFunc &Callback =
397 Multilibs.includeDirsCallback();
398 if (Callback) {
399 for (const auto &Path : Callback(GCCInstallation.getMultilib()))
400 addExternCSystemIncludeIfExists(
401 DriverArgs, CC1Args, Path: GCCInstallation.getInstallPath() + Path);
402 }
403 }
404
405 addExternCSystemInclude(DriverArgs, CC1Args, Path: D.SysRoot + "/usr/include");
406}
407
408void Solaris::addLibStdCxxIncludePaths(
409 const llvm::opt::ArgList &DriverArgs,
410 llvm::opt::ArgStringList &CC1Args) const {
411 // We need a detected GCC installation on Solaris (similar to Linux)
412 // to provide libstdc++'s headers.
413 if (!GCCInstallation.isValid())
414 return;
415
416 // By default, look for the C++ headers in an include directory adjacent to
417 // the lib directory of the GCC installation.
418 // On Solaris this usually looks like /usr/gcc/X.Y/include/c++/X.Y.Z
419 StringRef LibDir = GCCInstallation.getParentLibPath();
420 StringRef TripleStr = GCCInstallation.getTriple().str();
421 const Multilib &Multilib = GCCInstallation.getMultilib();
422 const GCCVersion &Version = GCCInstallation.getVersion();
423
424 // The primary search for libstdc++ supports multiarch variants.
425 addLibStdCXXIncludePaths(IncludeDir: LibDir.str() + "/../include/c++/" + Version.Text,
426 Triple: TripleStr, IncludeSuffix: Multilib.includeSuffix(), DriverArgs,
427 CC1Args);
428}
429