SanitizerArgs.cpp 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338
  1. //===--- SanitizerArgs.cpp - Arguments for sanitizer tools ---------------===//
  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. #include "clang/Driver/SanitizerArgs.h"
  9. #include "ToolChains/CommonArgs.h"
  10. #include "clang/Basic/Sanitizers.h"
  11. #include "clang/Driver/Driver.h"
  12. #include "clang/Driver/DriverDiagnostic.h"
  13. #include "clang/Driver/Options.h"
  14. #include "clang/Driver/ToolChain.h"
  15. #include "llvm/ADT/StringExtras.h"
  16. #include "llvm/ADT/StringSwitch.h"
  17. #include "llvm/Support/Path.h"
  18. #include "llvm/Support/SpecialCaseList.h"
  19. #include "llvm/Support/AArch64TargetParser.h"
  20. #include "llvm/Support/TargetParser.h"
  21. #include "llvm/Support/VirtualFileSystem.h"
  22. #include "llvm/Transforms/Instrumentation/AddressSanitizerOptions.h"
  23. #include <memory>
  24. using namespace clang;
  25. using namespace clang::driver;
  26. using namespace llvm::opt;
  27. static const SanitizerMask NeedsUbsanRt =
  28. SanitizerKind::Undefined | SanitizerKind::Integer |
  29. SanitizerKind::ImplicitConversion | SanitizerKind::Nullability |
  30. SanitizerKind::CFI | SanitizerKind::FloatDivideByZero |
  31. SanitizerKind::ObjCCast;
  32. static const SanitizerMask NeedsUbsanCxxRt =
  33. SanitizerKind::Vptr | SanitizerKind::CFI;
  34. static const SanitizerMask NotAllowedWithTrap = SanitizerKind::Vptr;
  35. static const SanitizerMask NotAllowedWithMinimalRuntime =
  36. SanitizerKind::Function | SanitizerKind::Vptr;
  37. static const SanitizerMask RequiresPIE =
  38. SanitizerKind::DataFlow | SanitizerKind::HWAddress | SanitizerKind::Scudo;
  39. static const SanitizerMask NeedsUnwindTables =
  40. SanitizerKind::Address | SanitizerKind::HWAddress | SanitizerKind::Thread |
  41. SanitizerKind::Memory | SanitizerKind::DataFlow;
  42. static const SanitizerMask SupportsCoverage =
  43. SanitizerKind::Address | SanitizerKind::HWAddress |
  44. SanitizerKind::KernelAddress | SanitizerKind::KernelHWAddress |
  45. SanitizerKind::MemTag | SanitizerKind::Memory |
  46. SanitizerKind::KernelMemory | SanitizerKind::Leak |
  47. SanitizerKind::Undefined | SanitizerKind::Integer | SanitizerKind::Bounds |
  48. SanitizerKind::ImplicitConversion | SanitizerKind::Nullability |
  49. SanitizerKind::DataFlow | SanitizerKind::Fuzzer |
  50. SanitizerKind::FuzzerNoLink | SanitizerKind::FloatDivideByZero |
  51. SanitizerKind::SafeStack | SanitizerKind::ShadowCallStack |
  52. SanitizerKind::Thread | SanitizerKind::ObjCCast;
  53. static const SanitizerMask RecoverableByDefault =
  54. SanitizerKind::Undefined | SanitizerKind::Integer |
  55. SanitizerKind::ImplicitConversion | SanitizerKind::Nullability |
  56. SanitizerKind::FloatDivideByZero | SanitizerKind::ObjCCast;
  57. static const SanitizerMask Unrecoverable =
  58. SanitizerKind::Unreachable | SanitizerKind::Return;
  59. static const SanitizerMask AlwaysRecoverable =
  60. SanitizerKind::KernelAddress | SanitizerKind::KernelHWAddress;
  61. static const SanitizerMask NeedsLTO = SanitizerKind::CFI;
  62. static const SanitizerMask TrappingSupported =
  63. (SanitizerKind::Undefined & ~SanitizerKind::Vptr) | SanitizerKind::Integer |
  64. SanitizerKind::Nullability | SanitizerKind::LocalBounds |
  65. SanitizerKind::CFI | SanitizerKind::FloatDivideByZero |
  66. SanitizerKind::ObjCCast;
  67. static const SanitizerMask TrappingDefault = SanitizerKind::CFI;
  68. static const SanitizerMask CFIClasses =
  69. SanitizerKind::CFIVCall | SanitizerKind::CFINVCall |
  70. SanitizerKind::CFIMFCall | SanitizerKind::CFIDerivedCast |
  71. SanitizerKind::CFIUnrelatedCast;
  72. static const SanitizerMask CompatibleWithMinimalRuntime =
  73. TrappingSupported | SanitizerKind::Scudo | SanitizerKind::ShadowCallStack |
  74. SanitizerKind::MemTag;
  75. enum CoverageFeature {
  76. CoverageFunc = 1 << 0,
  77. CoverageBB = 1 << 1,
  78. CoverageEdge = 1 << 2,
  79. CoverageIndirCall = 1 << 3,
  80. CoverageTraceBB = 1 << 4, // Deprecated.
  81. CoverageTraceCmp = 1 << 5,
  82. CoverageTraceDiv = 1 << 6,
  83. CoverageTraceGep = 1 << 7,
  84. Coverage8bitCounters = 1 << 8, // Deprecated.
  85. CoverageTracePC = 1 << 9,
  86. CoverageTracePCGuard = 1 << 10,
  87. CoverageNoPrune = 1 << 11,
  88. CoverageInline8bitCounters = 1 << 12,
  89. CoveragePCTable = 1 << 13,
  90. CoverageStackDepth = 1 << 14,
  91. CoverageInlineBoolFlag = 1 << 15,
  92. CoverageTraceLoads = 1 << 16,
  93. CoverageTraceStores = 1 << 17,
  94. };
  95. /// Parse a -fsanitize= or -fno-sanitize= argument's values, diagnosing any
  96. /// invalid components. Returns a SanitizerMask.
  97. static SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
  98. bool DiagnoseErrors);
  99. /// Parse -f(no-)?sanitize-coverage= flag values, diagnosing any invalid
  100. /// components. Returns OR of members of \c CoverageFeature enumeration.
  101. static int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A,
  102. bool DiagnoseErrors);
  103. /// Produce an argument string from ArgList \p Args, which shows how it
  104. /// provides some sanitizer kind from \p Mask. For example, the argument list
  105. /// "-fsanitize=thread,vptr -fsanitize=address" with mask \c NeedsUbsanRt
  106. /// would produce "-fsanitize=vptr".
  107. static std::string lastArgumentForMask(const Driver &D,
  108. const llvm::opt::ArgList &Args,
  109. SanitizerMask Mask);
  110. /// Produce an argument string from argument \p A, which shows how it provides
  111. /// a value in \p Mask. For instance, the argument
  112. /// "-fsanitize=address,alignment" with mask \c NeedsUbsanRt would produce
  113. /// "-fsanitize=alignment".
  114. static std::string describeSanitizeArg(const llvm::opt::Arg *A,
  115. SanitizerMask Mask);
  116. /// Produce a string containing comma-separated names of sanitizers in \p
  117. /// Sanitizers set.
  118. static std::string toString(const clang::SanitizerSet &Sanitizers);
  119. static void validateSpecialCaseListFormat(const Driver &D,
  120. std::vector<std::string> &SCLFiles,
  121. unsigned MalformedSCLErrorDiagID,
  122. bool DiagnoseErrors) {
  123. if (SCLFiles.empty())
  124. return;
  125. std::string BLError;
  126. std::unique_ptr<llvm::SpecialCaseList> SCL(
  127. llvm::SpecialCaseList::create(SCLFiles, D.getVFS(), BLError));
  128. if (!SCL.get() && DiagnoseErrors)
  129. D.Diag(MalformedSCLErrorDiagID) << BLError;
  130. }
  131. static void addDefaultIgnorelists(const Driver &D, SanitizerMask Kinds,
  132. std::vector<std::string> &IgnorelistFiles,
  133. bool DiagnoseErrors) {
  134. struct Ignorelist {
  135. const char *File;
  136. SanitizerMask Mask;
  137. } Ignorelists[] = {{"asan_ignorelist.txt", SanitizerKind::Address},
  138. {"hwasan_ignorelist.txt", SanitizerKind::HWAddress},
  139. {"memtag_ignorelist.txt", SanitizerKind::MemTag},
  140. {"msan_ignorelist.txt", SanitizerKind::Memory},
  141. {"tsan_ignorelist.txt", SanitizerKind::Thread},
  142. {"dfsan_abilist.txt", SanitizerKind::DataFlow},
  143. {"cfi_ignorelist.txt", SanitizerKind::CFI},
  144. {"ubsan_ignorelist.txt",
  145. SanitizerKind::Undefined | SanitizerKind::Integer |
  146. SanitizerKind::Nullability |
  147. SanitizerKind::FloatDivideByZero}};
  148. for (auto BL : Ignorelists) {
  149. if (!(Kinds & BL.Mask))
  150. continue;
  151. clang::SmallString<64> Path(D.ResourceDir);
  152. llvm::sys::path::append(Path, "share", BL.File);
  153. if (D.getVFS().exists(Path))
  154. IgnorelistFiles.push_back(std::string(Path.str()));
  155. else if (BL.Mask == SanitizerKind::CFI && DiagnoseErrors)
  156. // If cfi_ignorelist.txt cannot be found in the resource dir, driver
  157. // should fail.
  158. D.Diag(clang::diag::err_drv_no_such_file) << Path;
  159. }
  160. validateSpecialCaseListFormat(
  161. D, IgnorelistFiles, clang::diag::err_drv_malformed_sanitizer_ignorelist,
  162. DiagnoseErrors);
  163. }
  164. /// Parse -f(no-)?sanitize-(coverage-)?(white|ignore)list argument's values,
  165. /// diagnosing any invalid file paths and validating special case list format.
  166. static void parseSpecialCaseListArg(const Driver &D,
  167. const llvm::opt::ArgList &Args,
  168. std::vector<std::string> &SCLFiles,
  169. llvm::opt::OptSpecifier SCLOptionID,
  170. llvm::opt::OptSpecifier NoSCLOptionID,
  171. unsigned MalformedSCLErrorDiagID,
  172. bool DiagnoseErrors) {
  173. for (const auto *Arg : Args) {
  174. // Match -fsanitize-(coverage-)?(white|ignore)list.
  175. if (Arg->getOption().matches(SCLOptionID)) {
  176. Arg->claim();
  177. std::string SCLPath = Arg->getValue();
  178. if (D.getVFS().exists(SCLPath)) {
  179. SCLFiles.push_back(SCLPath);
  180. } else if (DiagnoseErrors) {
  181. D.Diag(clang::diag::err_drv_no_such_file) << SCLPath;
  182. }
  183. // Match -fno-sanitize-ignorelist.
  184. } else if (Arg->getOption().matches(NoSCLOptionID)) {
  185. Arg->claim();
  186. SCLFiles.clear();
  187. }
  188. }
  189. validateSpecialCaseListFormat(D, SCLFiles, MalformedSCLErrorDiagID,
  190. DiagnoseErrors);
  191. }
  192. /// Sets group bits for every group that has at least one representative already
  193. /// enabled in \p Kinds.
  194. static SanitizerMask setGroupBits(SanitizerMask Kinds) {
  195. #define SANITIZER(NAME, ID)
  196. #define SANITIZER_GROUP(NAME, ID, ALIAS) \
  197. if (Kinds & SanitizerKind::ID) \
  198. Kinds |= SanitizerKind::ID##Group;
  199. #include "clang/Basic/Sanitizers.def"
  200. return Kinds;
  201. }
  202. static SanitizerMask parseSanitizeTrapArgs(const Driver &D,
  203. const llvm::opt::ArgList &Args,
  204. bool DiagnoseErrors) {
  205. SanitizerMask TrapRemove; // During the loop below, the accumulated set of
  206. // sanitizers disabled by the current sanitizer
  207. // argument or any argument after it.
  208. SanitizerMask TrappingKinds;
  209. SanitizerMask TrappingSupportedWithGroups = setGroupBits(TrappingSupported);
  210. for (const llvm::opt::Arg *Arg : llvm::reverse(Args)) {
  211. if (Arg->getOption().matches(options::OPT_fsanitize_trap_EQ)) {
  212. Arg->claim();
  213. SanitizerMask Add = parseArgValues(D, Arg, true);
  214. Add &= ~TrapRemove;
  215. SanitizerMask InvalidValues = Add & ~TrappingSupportedWithGroups;
  216. if (InvalidValues && DiagnoseErrors) {
  217. SanitizerSet S;
  218. S.Mask = InvalidValues;
  219. D.Diag(diag::err_drv_unsupported_option_argument) << "-fsanitize-trap"
  220. << toString(S);
  221. }
  222. TrappingKinds |= expandSanitizerGroups(Add) & ~TrapRemove;
  223. } else if (Arg->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) {
  224. Arg->claim();
  225. TrapRemove |=
  226. expandSanitizerGroups(parseArgValues(D, Arg, DiagnoseErrors));
  227. }
  228. }
  229. // Apply default trapping behavior.
  230. TrappingKinds |= TrappingDefault & ~TrapRemove;
  231. return TrappingKinds;
  232. }
  233. bool SanitizerArgs::needsFuzzerInterceptors() const {
  234. return needsFuzzer() && !needsAsanRt() && !needsTsanRt() && !needsMsanRt();
  235. }
  236. bool SanitizerArgs::needsUbsanRt() const {
  237. // All of these include ubsan.
  238. if (needsAsanRt() || needsMsanRt() || needsHwasanRt() || needsTsanRt() ||
  239. needsDfsanRt() || needsLsanRt() || needsCfiDiagRt() ||
  240. (needsScudoRt() && !requiresMinimalRuntime()))
  241. return false;
  242. return (Sanitizers.Mask & NeedsUbsanRt & ~TrapSanitizers.Mask) ||
  243. CoverageFeatures;
  244. }
  245. bool SanitizerArgs::needsCfiRt() const {
  246. return !(Sanitizers.Mask & SanitizerKind::CFI & ~TrapSanitizers.Mask) &&
  247. CfiCrossDso && !ImplicitCfiRuntime;
  248. }
  249. bool SanitizerArgs::needsCfiDiagRt() const {
  250. return (Sanitizers.Mask & SanitizerKind::CFI & ~TrapSanitizers.Mask) &&
  251. CfiCrossDso && !ImplicitCfiRuntime;
  252. }
  253. bool SanitizerArgs::requiresPIE() const {
  254. return NeedPIE || (Sanitizers.Mask & RequiresPIE);
  255. }
  256. bool SanitizerArgs::needsUnwindTables() const {
  257. return static_cast<bool>(Sanitizers.Mask & NeedsUnwindTables);
  258. }
  259. bool SanitizerArgs::needsLTO() const {
  260. return static_cast<bool>(Sanitizers.Mask & NeedsLTO);
  261. }
  262. SanitizerArgs::SanitizerArgs(const ToolChain &TC,
  263. const llvm::opt::ArgList &Args,
  264. bool DiagnoseErrors) {
  265. SanitizerMask AllRemove; // During the loop below, the accumulated set of
  266. // sanitizers disabled by the current sanitizer
  267. // argument or any argument after it.
  268. SanitizerMask AllAddedKinds; // Mask of all sanitizers ever enabled by
  269. // -fsanitize= flags (directly or via group
  270. // expansion), some of which may be disabled
  271. // later. Used to carefully prune
  272. // unused-argument diagnostics.
  273. SanitizerMask DiagnosedKinds; // All Kinds we have diagnosed up to now.
  274. // Used to deduplicate diagnostics.
  275. SanitizerMask Kinds;
  276. const SanitizerMask Supported = setGroupBits(TC.getSupportedSanitizers());
  277. CfiCrossDso = Args.hasFlag(options::OPT_fsanitize_cfi_cross_dso,
  278. options::OPT_fno_sanitize_cfi_cross_dso, false);
  279. ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
  280. const Driver &D = TC.getDriver();
  281. SanitizerMask TrappingKinds = parseSanitizeTrapArgs(D, Args, DiagnoseErrors);
  282. SanitizerMask InvalidTrappingKinds = TrappingKinds & NotAllowedWithTrap;
  283. MinimalRuntime =
  284. Args.hasFlag(options::OPT_fsanitize_minimal_runtime,
  285. options::OPT_fno_sanitize_minimal_runtime, MinimalRuntime);
  286. // The object size sanitizer should not be enabled at -O0.
  287. Arg *OptLevel = Args.getLastArg(options::OPT_O_Group);
  288. bool RemoveObjectSizeAtO0 =
  289. !OptLevel || OptLevel->getOption().matches(options::OPT_O0);
  290. for (const llvm::opt::Arg *Arg : llvm::reverse(Args)) {
  291. if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
  292. Arg->claim();
  293. SanitizerMask Add = parseArgValues(D, Arg, DiagnoseErrors);
  294. if (RemoveObjectSizeAtO0) {
  295. AllRemove |= SanitizerKind::ObjectSize;
  296. // The user explicitly enabled the object size sanitizer. Warn
  297. // that this does nothing at -O0.
  298. if ((Add & SanitizerKind::ObjectSize) && DiagnoseErrors)
  299. D.Diag(diag::warn_drv_object_size_disabled_O0)
  300. << Arg->getAsString(Args);
  301. }
  302. AllAddedKinds |= expandSanitizerGroups(Add);
  303. // Avoid diagnosing any sanitizer which is disabled later.
  304. Add &= ~AllRemove;
  305. // At this point we have not expanded groups, so any unsupported
  306. // sanitizers in Add are those which have been explicitly enabled.
  307. // Diagnose them.
  308. if (SanitizerMask KindsToDiagnose =
  309. Add & InvalidTrappingKinds & ~DiagnosedKinds) {
  310. if (DiagnoseErrors) {
  311. std::string Desc = describeSanitizeArg(Arg, KindsToDiagnose);
  312. D.Diag(diag::err_drv_argument_not_allowed_with)
  313. << Desc << "-fsanitize-trap=undefined";
  314. }
  315. DiagnosedKinds |= KindsToDiagnose;
  316. }
  317. Add &= ~InvalidTrappingKinds;
  318. if (MinimalRuntime) {
  319. if (SanitizerMask KindsToDiagnose =
  320. Add & NotAllowedWithMinimalRuntime & ~DiagnosedKinds) {
  321. if (DiagnoseErrors) {
  322. std::string Desc = describeSanitizeArg(Arg, KindsToDiagnose);
  323. D.Diag(diag::err_drv_argument_not_allowed_with)
  324. << Desc << "-fsanitize-minimal-runtime";
  325. }
  326. DiagnosedKinds |= KindsToDiagnose;
  327. }
  328. Add &= ~NotAllowedWithMinimalRuntime;
  329. }
  330. // FIXME: Make CFI on member function calls compatible with cross-DSO CFI.
  331. // There are currently two problems:
  332. // - Virtual function call checks need to pass a pointer to the function
  333. // address to llvm.type.test and a pointer to the address point to the
  334. // diagnostic function. Currently we pass the same pointer to both
  335. // places.
  336. // - Non-virtual function call checks may need to check multiple type
  337. // identifiers.
  338. // Fixing both of those may require changes to the cross-DSO CFI
  339. // interface.
  340. if (CfiCrossDso && (Add & SanitizerKind::CFIMFCall & ~DiagnosedKinds)) {
  341. if (DiagnoseErrors)
  342. D.Diag(diag::err_drv_argument_not_allowed_with)
  343. << "-fsanitize=cfi-mfcall"
  344. << "-fsanitize-cfi-cross-dso";
  345. Add &= ~SanitizerKind::CFIMFCall;
  346. DiagnosedKinds |= SanitizerKind::CFIMFCall;
  347. }
  348. if (SanitizerMask KindsToDiagnose = Add & ~Supported & ~DiagnosedKinds) {
  349. if (DiagnoseErrors) {
  350. std::string Desc = describeSanitizeArg(Arg, KindsToDiagnose);
  351. D.Diag(diag::err_drv_unsupported_opt_for_target)
  352. << Desc << TC.getTriple().str();
  353. }
  354. DiagnosedKinds |= KindsToDiagnose;
  355. }
  356. Add &= Supported;
  357. // Test for -fno-rtti + explicit -fsanitizer=vptr before expanding groups
  358. // so we don't error out if -fno-rtti and -fsanitize=undefined were
  359. // passed.
  360. if ((Add & SanitizerKind::Vptr) && (RTTIMode == ToolChain::RM_Disabled)) {
  361. if (const llvm::opt::Arg *NoRTTIArg = TC.getRTTIArg()) {
  362. assert(NoRTTIArg->getOption().matches(options::OPT_fno_rtti) &&
  363. "RTTI disabled without -fno-rtti option?");
  364. // The user explicitly passed -fno-rtti with -fsanitize=vptr, but
  365. // the vptr sanitizer requires RTTI, so this is a user error.
  366. if (DiagnoseErrors)
  367. D.Diag(diag::err_drv_argument_not_allowed_with)
  368. << "-fsanitize=vptr" << NoRTTIArg->getAsString(Args);
  369. } else {
  370. // The vptr sanitizer requires RTTI, but RTTI is disabled (by
  371. // default). Warn that the vptr sanitizer is being disabled.
  372. if (DiagnoseErrors)
  373. D.Diag(diag::warn_drv_disabling_vptr_no_rtti_default);
  374. }
  375. // Take out the Vptr sanitizer from the enabled sanitizers
  376. AllRemove |= SanitizerKind::Vptr;
  377. }
  378. Add = expandSanitizerGroups(Add);
  379. // Group expansion may have enabled a sanitizer which is disabled later.
  380. Add &= ~AllRemove;
  381. // Silently discard any unsupported sanitizers implicitly enabled through
  382. // group expansion.
  383. Add &= ~InvalidTrappingKinds;
  384. if (MinimalRuntime) {
  385. Add &= ~NotAllowedWithMinimalRuntime;
  386. }
  387. if (CfiCrossDso)
  388. Add &= ~SanitizerKind::CFIMFCall;
  389. Add &= Supported;
  390. if (Add & SanitizerKind::Fuzzer)
  391. Add |= SanitizerKind::FuzzerNoLink;
  392. // Enable coverage if the fuzzing flag is set.
  393. if (Add & SanitizerKind::FuzzerNoLink) {
  394. CoverageFeatures |= CoverageInline8bitCounters | CoverageIndirCall |
  395. CoverageTraceCmp | CoveragePCTable;
  396. // Due to TLS differences, stack depth tracking is only enabled on Linux
  397. if (TC.getTriple().isOSLinux())
  398. CoverageFeatures |= CoverageStackDepth;
  399. }
  400. Kinds |= Add;
  401. } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
  402. Arg->claim();
  403. SanitizerMask Remove = parseArgValues(D, Arg, DiagnoseErrors);
  404. AllRemove |= expandSanitizerGroups(Remove);
  405. }
  406. }
  407. std::pair<SanitizerMask, SanitizerMask> IncompatibleGroups[] = {
  408. std::make_pair(SanitizerKind::Address,
  409. SanitizerKind::Thread | SanitizerKind::Memory),
  410. std::make_pair(SanitizerKind::Thread, SanitizerKind::Memory),
  411. std::make_pair(SanitizerKind::Leak,
  412. SanitizerKind::Thread | SanitizerKind::Memory),
  413. std::make_pair(SanitizerKind::KernelAddress,
  414. SanitizerKind::Address | SanitizerKind::Leak |
  415. SanitizerKind::Thread | SanitizerKind::Memory),
  416. std::make_pair(SanitizerKind::HWAddress,
  417. SanitizerKind::Address | SanitizerKind::Thread |
  418. SanitizerKind::Memory | SanitizerKind::KernelAddress),
  419. std::make_pair(SanitizerKind::Scudo,
  420. SanitizerKind::Address | SanitizerKind::HWAddress |
  421. SanitizerKind::Leak | SanitizerKind::Thread |
  422. SanitizerKind::Memory | SanitizerKind::KernelAddress),
  423. std::make_pair(SanitizerKind::SafeStack,
  424. (TC.getTriple().isOSFuchsia() ? SanitizerMask()
  425. : SanitizerKind::Leak) |
  426. SanitizerKind::Address | SanitizerKind::HWAddress |
  427. SanitizerKind::Thread | SanitizerKind::Memory |
  428. SanitizerKind::KernelAddress),
  429. std::make_pair(SanitizerKind::KernelHWAddress,
  430. SanitizerKind::Address | SanitizerKind::HWAddress |
  431. SanitizerKind::Leak | SanitizerKind::Thread |
  432. SanitizerKind::Memory | SanitizerKind::KernelAddress |
  433. SanitizerKind::SafeStack),
  434. std::make_pair(SanitizerKind::KernelMemory,
  435. SanitizerKind::Address | SanitizerKind::HWAddress |
  436. SanitizerKind::Leak | SanitizerKind::Thread |
  437. SanitizerKind::Memory | SanitizerKind::KernelAddress |
  438. SanitizerKind::Scudo | SanitizerKind::SafeStack),
  439. std::make_pair(SanitizerKind::MemTag,
  440. SanitizerKind::Address | SanitizerKind::KernelAddress |
  441. SanitizerKind::HWAddress |
  442. SanitizerKind::KernelHWAddress)};
  443. // Enable toolchain specific default sanitizers if not explicitly disabled.
  444. SanitizerMask Default = TC.getDefaultSanitizers() & ~AllRemove;
  445. // Disable default sanitizers that are incompatible with explicitly requested
  446. // ones.
  447. for (auto G : IncompatibleGroups) {
  448. SanitizerMask Group = G.first;
  449. if ((Default & Group) && (Kinds & G.second))
  450. Default &= ~Group;
  451. }
  452. Kinds |= Default;
  453. // We disable the vptr sanitizer if it was enabled by group expansion but RTTI
  454. // is disabled.
  455. if ((Kinds & SanitizerKind::Vptr) && (RTTIMode == ToolChain::RM_Disabled)) {
  456. Kinds &= ~SanitizerKind::Vptr;
  457. }
  458. // Check that LTO is enabled if we need it.
  459. if ((Kinds & NeedsLTO) && !D.isUsingLTO() && DiagnoseErrors) {
  460. D.Diag(diag::err_drv_argument_only_allowed_with)
  461. << lastArgumentForMask(D, Args, Kinds & NeedsLTO) << "-flto";
  462. }
  463. if ((Kinds & SanitizerKind::ShadowCallStack) &&
  464. ((TC.getTriple().isAArch64() &&
  465. !llvm::AArch64::isX18ReservedByDefault(TC.getTriple())) ||
  466. TC.getTriple().isRISCV()) &&
  467. !Args.hasArg(options::OPT_ffixed_x18) && DiagnoseErrors) {
  468. D.Diag(diag::err_drv_argument_only_allowed_with)
  469. << lastArgumentForMask(D, Args, Kinds & SanitizerKind::ShadowCallStack)
  470. << "-ffixed-x18";
  471. }
  472. // Report error if there are non-trapping sanitizers that require
  473. // c++abi-specific parts of UBSan runtime, and they are not provided by the
  474. // toolchain. We don't have a good way to check the latter, so we just
  475. // check if the toolchan supports vptr.
  476. if (~Supported & SanitizerKind::Vptr) {
  477. SanitizerMask KindsToDiagnose = Kinds & ~TrappingKinds & NeedsUbsanCxxRt;
  478. // The runtime library supports the Microsoft C++ ABI, but only well enough
  479. // for CFI. FIXME: Remove this once we support vptr on Windows.
  480. if (TC.getTriple().isOSWindows())
  481. KindsToDiagnose &= ~SanitizerKind::CFI;
  482. if (KindsToDiagnose) {
  483. SanitizerSet S;
  484. S.Mask = KindsToDiagnose;
  485. if (DiagnoseErrors)
  486. D.Diag(diag::err_drv_unsupported_opt_for_target)
  487. << ("-fno-sanitize-trap=" + toString(S)) << TC.getTriple().str();
  488. Kinds &= ~KindsToDiagnose;
  489. }
  490. }
  491. // Warn about incompatible groups of sanitizers.
  492. for (auto G : IncompatibleGroups) {
  493. SanitizerMask Group = G.first;
  494. if (Kinds & Group) {
  495. if (SanitizerMask Incompatible = Kinds & G.second) {
  496. if (DiagnoseErrors)
  497. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  498. << lastArgumentForMask(D, Args, Group)
  499. << lastArgumentForMask(D, Args, Incompatible);
  500. Kinds &= ~Incompatible;
  501. }
  502. }
  503. }
  504. // FIXME: Currently -fsanitize=leak is silently ignored in the presence of
  505. // -fsanitize=address. Perhaps it should print an error, or perhaps
  506. // -f(-no)sanitize=leak should change whether leak detection is enabled by
  507. // default in ASan?
  508. // Parse -f(no-)?sanitize-recover flags.
  509. SanitizerMask RecoverableKinds = RecoverableByDefault | AlwaysRecoverable;
  510. SanitizerMask DiagnosedUnrecoverableKinds;
  511. SanitizerMask DiagnosedAlwaysRecoverableKinds;
  512. for (const auto *Arg : Args) {
  513. if (Arg->getOption().matches(options::OPT_fsanitize_recover_EQ)) {
  514. SanitizerMask Add = parseArgValues(D, Arg, DiagnoseErrors);
  515. // Report error if user explicitly tries to recover from unrecoverable
  516. // sanitizer.
  517. if (SanitizerMask KindsToDiagnose =
  518. Add & Unrecoverable & ~DiagnosedUnrecoverableKinds) {
  519. SanitizerSet SetToDiagnose;
  520. SetToDiagnose.Mask |= KindsToDiagnose;
  521. if (DiagnoseErrors)
  522. D.Diag(diag::err_drv_unsupported_option_argument)
  523. << Arg->getOption().getName() << toString(SetToDiagnose);
  524. DiagnosedUnrecoverableKinds |= KindsToDiagnose;
  525. }
  526. RecoverableKinds |= expandSanitizerGroups(Add);
  527. Arg->claim();
  528. } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover_EQ)) {
  529. SanitizerMask Remove = parseArgValues(D, Arg, DiagnoseErrors);
  530. // Report error if user explicitly tries to disable recovery from
  531. // always recoverable sanitizer.
  532. if (SanitizerMask KindsToDiagnose =
  533. Remove & AlwaysRecoverable & ~DiagnosedAlwaysRecoverableKinds) {
  534. SanitizerSet SetToDiagnose;
  535. SetToDiagnose.Mask |= KindsToDiagnose;
  536. if (DiagnoseErrors)
  537. D.Diag(diag::err_drv_unsupported_option_argument)
  538. << Arg->getOption().getName() << toString(SetToDiagnose);
  539. DiagnosedAlwaysRecoverableKinds |= KindsToDiagnose;
  540. }
  541. RecoverableKinds &= ~expandSanitizerGroups(Remove);
  542. Arg->claim();
  543. }
  544. }
  545. RecoverableKinds &= Kinds;
  546. RecoverableKinds &= ~Unrecoverable;
  547. TrappingKinds &= Kinds;
  548. RecoverableKinds &= ~TrappingKinds;
  549. // Setup ignorelist files.
  550. // Add default ignorelist from resource directory for activated sanitizers,
  551. // and validate special case lists format.
  552. if (!Args.hasArgNoClaim(options::OPT_fno_sanitize_ignorelist))
  553. addDefaultIgnorelists(D, Kinds, SystemIgnorelistFiles, DiagnoseErrors);
  554. // Parse -f(no-)?sanitize-ignorelist options.
  555. // This also validates special case lists format.
  556. parseSpecialCaseListArg(
  557. D, Args, UserIgnorelistFiles, options::OPT_fsanitize_ignorelist_EQ,
  558. options::OPT_fno_sanitize_ignorelist,
  559. clang::diag::err_drv_malformed_sanitizer_ignorelist, DiagnoseErrors);
  560. // Parse -f[no-]sanitize-memory-track-origins[=level] options.
  561. if (AllAddedKinds & SanitizerKind::Memory) {
  562. if (Arg *A =
  563. Args.getLastArg(options::OPT_fsanitize_memory_track_origins_EQ,
  564. options::OPT_fsanitize_memory_track_origins,
  565. options::OPT_fno_sanitize_memory_track_origins)) {
  566. if (A->getOption().matches(options::OPT_fsanitize_memory_track_origins)) {
  567. MsanTrackOrigins = 2;
  568. } else if (A->getOption().matches(
  569. options::OPT_fno_sanitize_memory_track_origins)) {
  570. MsanTrackOrigins = 0;
  571. } else {
  572. StringRef S = A->getValue();
  573. if (S.getAsInteger(0, MsanTrackOrigins) || MsanTrackOrigins < 0 ||
  574. MsanTrackOrigins > 2) {
  575. if (DiagnoseErrors)
  576. D.Diag(clang::diag::err_drv_invalid_value)
  577. << A->getAsString(Args) << S;
  578. }
  579. }
  580. }
  581. MsanUseAfterDtor =
  582. Args.hasFlag(options::OPT_fsanitize_memory_use_after_dtor,
  583. options::OPT_fno_sanitize_memory_use_after_dtor,
  584. MsanUseAfterDtor);
  585. MsanParamRetval = Args.hasFlag(
  586. options::OPT_fsanitize_memory_param_retval,
  587. options::OPT_fno_sanitize_memory_param_retval, MsanParamRetval);
  588. NeedPIE |= !(TC.getTriple().isOSLinux() &&
  589. TC.getTriple().getArch() == llvm::Triple::x86_64);
  590. } else {
  591. MsanUseAfterDtor = false;
  592. MsanParamRetval = false;
  593. }
  594. if (AllAddedKinds & SanitizerKind::Thread) {
  595. TsanMemoryAccess = Args.hasFlag(
  596. options::OPT_fsanitize_thread_memory_access,
  597. options::OPT_fno_sanitize_thread_memory_access, TsanMemoryAccess);
  598. TsanFuncEntryExit = Args.hasFlag(
  599. options::OPT_fsanitize_thread_func_entry_exit,
  600. options::OPT_fno_sanitize_thread_func_entry_exit, TsanFuncEntryExit);
  601. TsanAtomics =
  602. Args.hasFlag(options::OPT_fsanitize_thread_atomics,
  603. options::OPT_fno_sanitize_thread_atomics, TsanAtomics);
  604. }
  605. if (AllAddedKinds & SanitizerKind::CFI) {
  606. // Without PIE, external function address may resolve to a PLT record, which
  607. // can not be verified by the target module.
  608. NeedPIE |= CfiCrossDso;
  609. CfiICallGeneralizePointers =
  610. Args.hasArg(options::OPT_fsanitize_cfi_icall_generalize_pointers);
  611. if (CfiCrossDso && CfiICallGeneralizePointers && DiagnoseErrors)
  612. D.Diag(diag::err_drv_argument_not_allowed_with)
  613. << "-fsanitize-cfi-cross-dso"
  614. << "-fsanitize-cfi-icall-generalize-pointers";
  615. CfiCanonicalJumpTables =
  616. Args.hasFlag(options::OPT_fsanitize_cfi_canonical_jump_tables,
  617. options::OPT_fno_sanitize_cfi_canonical_jump_tables, true);
  618. }
  619. Stats = Args.hasFlag(options::OPT_fsanitize_stats,
  620. options::OPT_fno_sanitize_stats, false);
  621. if (MinimalRuntime) {
  622. SanitizerMask IncompatibleMask =
  623. Kinds & ~setGroupBits(CompatibleWithMinimalRuntime);
  624. if (IncompatibleMask && DiagnoseErrors)
  625. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  626. << "-fsanitize-minimal-runtime"
  627. << lastArgumentForMask(D, Args, IncompatibleMask);
  628. SanitizerMask NonTrappingCfi = Kinds & SanitizerKind::CFI & ~TrappingKinds;
  629. if (NonTrappingCfi && DiagnoseErrors)
  630. D.Diag(clang::diag::err_drv_argument_only_allowed_with)
  631. << "fsanitize-minimal-runtime"
  632. << "fsanitize-trap=cfi";
  633. }
  634. // Parse -f(no-)?sanitize-coverage flags if coverage is supported by the
  635. // enabled sanitizers.
  636. for (const auto *Arg : Args) {
  637. if (Arg->getOption().matches(options::OPT_fsanitize_coverage)) {
  638. int LegacySanitizeCoverage;
  639. if (Arg->getNumValues() == 1 &&
  640. !StringRef(Arg->getValue(0))
  641. .getAsInteger(0, LegacySanitizeCoverage)) {
  642. CoverageFeatures = 0;
  643. Arg->claim();
  644. if (LegacySanitizeCoverage != 0 && DiagnoseErrors) {
  645. D.Diag(diag::warn_drv_deprecated_arg)
  646. << Arg->getAsString(Args) << "-fsanitize-coverage=trace-pc-guard";
  647. }
  648. continue;
  649. }
  650. CoverageFeatures |= parseCoverageFeatures(D, Arg, DiagnoseErrors);
  651. // Disable coverage and not claim the flags if there is at least one
  652. // non-supporting sanitizer.
  653. if (!(AllAddedKinds & ~AllRemove & ~setGroupBits(SupportsCoverage))) {
  654. Arg->claim();
  655. } else {
  656. CoverageFeatures = 0;
  657. }
  658. } else if (Arg->getOption().matches(options::OPT_fno_sanitize_coverage)) {
  659. Arg->claim();
  660. CoverageFeatures &= ~parseCoverageFeatures(D, Arg, DiagnoseErrors);
  661. }
  662. }
  663. // Choose at most one coverage type: function, bb, or edge.
  664. if (DiagnoseErrors) {
  665. if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageBB))
  666. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  667. << "-fsanitize-coverage=func"
  668. << "-fsanitize-coverage=bb";
  669. if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageEdge))
  670. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  671. << "-fsanitize-coverage=func"
  672. << "-fsanitize-coverage=edge";
  673. if ((CoverageFeatures & CoverageBB) && (CoverageFeatures & CoverageEdge))
  674. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  675. << "-fsanitize-coverage=bb"
  676. << "-fsanitize-coverage=edge";
  677. // Basic block tracing and 8-bit counters require some type of coverage
  678. // enabled.
  679. if (CoverageFeatures & CoverageTraceBB)
  680. D.Diag(clang::diag::warn_drv_deprecated_arg)
  681. << "-fsanitize-coverage=trace-bb"
  682. << "-fsanitize-coverage=trace-pc-guard";
  683. if (CoverageFeatures & Coverage8bitCounters)
  684. D.Diag(clang::diag::warn_drv_deprecated_arg)
  685. << "-fsanitize-coverage=8bit-counters"
  686. << "-fsanitize-coverage=trace-pc-guard";
  687. }
  688. int InsertionPointTypes = CoverageFunc | CoverageBB | CoverageEdge;
  689. int InstrumentationTypes = CoverageTracePC | CoverageTracePCGuard |
  690. CoverageInline8bitCounters | CoverageTraceLoads |
  691. CoverageTraceStores | CoverageInlineBoolFlag;
  692. if ((CoverageFeatures & InsertionPointTypes) &&
  693. !(CoverageFeatures & InstrumentationTypes) && DiagnoseErrors) {
  694. D.Diag(clang::diag::warn_drv_deprecated_arg)
  695. << "-fsanitize-coverage=[func|bb|edge]"
  696. << "-fsanitize-coverage=[func|bb|edge],[trace-pc-guard|trace-pc]";
  697. }
  698. // trace-pc w/o func/bb/edge implies edge.
  699. if (!(CoverageFeatures & InsertionPointTypes)) {
  700. if (CoverageFeatures &
  701. (CoverageTracePC | CoverageTracePCGuard | CoverageInline8bitCounters |
  702. CoverageInlineBoolFlag))
  703. CoverageFeatures |= CoverageEdge;
  704. if (CoverageFeatures & CoverageStackDepth)
  705. CoverageFeatures |= CoverageFunc;
  706. }
  707. // Parse -fsanitize-coverage-(ignore|white)list options if coverage enabled.
  708. // This also validates special case lists format.
  709. // Here, OptSpecifier() acts as a never-matching command-line argument.
  710. // So, there is no way to clear coverage lists but you can append to them.
  711. if (CoverageFeatures) {
  712. parseSpecialCaseListArg(
  713. D, Args, CoverageAllowlistFiles,
  714. options::OPT_fsanitize_coverage_allowlist, OptSpecifier(),
  715. clang::diag::err_drv_malformed_sanitizer_coverage_allowlist,
  716. DiagnoseErrors);
  717. parseSpecialCaseListArg(
  718. D, Args, CoverageIgnorelistFiles,
  719. options::OPT_fsanitize_coverage_ignorelist, OptSpecifier(),
  720. clang::diag::err_drv_malformed_sanitizer_coverage_ignorelist,
  721. DiagnoseErrors);
  722. }
  723. SharedRuntime =
  724. Args.hasFlag(options::OPT_shared_libsan, options::OPT_static_libsan,
  725. TC.getTriple().isAndroid() || TC.getTriple().isOSFuchsia() ||
  726. TC.getTriple().isOSDarwin());
  727. ImplicitCfiRuntime = TC.getTriple().isAndroid();
  728. if (AllAddedKinds & SanitizerKind::Address) {
  729. NeedPIE |= TC.getTriple().isOSFuchsia();
  730. if (Arg *A =
  731. Args.getLastArg(options::OPT_fsanitize_address_field_padding)) {
  732. StringRef S = A->getValue();
  733. // Legal values are 0 and 1, 2, but in future we may add more levels.
  734. if ((S.getAsInteger(0, AsanFieldPadding) || AsanFieldPadding < 0 ||
  735. AsanFieldPadding > 2) &&
  736. DiagnoseErrors) {
  737. D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
  738. }
  739. }
  740. if (Arg *WindowsDebugRTArg =
  741. Args.getLastArg(options::OPT__SLASH_MTd, options::OPT__SLASH_MT,
  742. options::OPT__SLASH_MDd, options::OPT__SLASH_MD,
  743. options::OPT__SLASH_LDd, options::OPT__SLASH_LD)) {
  744. switch (WindowsDebugRTArg->getOption().getID()) {
  745. case options::OPT__SLASH_MTd:
  746. case options::OPT__SLASH_MDd:
  747. case options::OPT__SLASH_LDd:
  748. if (DiagnoseErrors) {
  749. D.Diag(clang::diag::err_drv_argument_not_allowed_with)
  750. << WindowsDebugRTArg->getAsString(Args)
  751. << lastArgumentForMask(D, Args, SanitizerKind::Address);
  752. D.Diag(clang::diag::note_drv_address_sanitizer_debug_runtime);
  753. }
  754. }
  755. }
  756. AsanUseAfterScope = Args.hasFlag(
  757. options::OPT_fsanitize_address_use_after_scope,
  758. options::OPT_fno_sanitize_address_use_after_scope, AsanUseAfterScope);
  759. AsanPoisonCustomArrayCookie = Args.hasFlag(
  760. options::OPT_fsanitize_address_poison_custom_array_cookie,
  761. options::OPT_fno_sanitize_address_poison_custom_array_cookie,
  762. AsanPoisonCustomArrayCookie);
  763. AsanOutlineInstrumentation =
  764. Args.hasFlag(options::OPT_fsanitize_address_outline_instrumentation,
  765. options::OPT_fno_sanitize_address_outline_instrumentation,
  766. AsanOutlineInstrumentation);
  767. // As a workaround for a bug in gold 2.26 and earlier, dead stripping of
  768. // globals in ASan is disabled by default on ELF targets.
  769. // See https://sourceware.org/bugzilla/show_bug.cgi?id=19002
  770. AsanGlobalsDeadStripping =
  771. !TC.getTriple().isOSBinFormatELF() || TC.getTriple().isOSFuchsia() ||
  772. TC.getTriple().isPS4() ||
  773. Args.hasArg(options::OPT_fsanitize_address_globals_dead_stripping);
  774. AsanUseOdrIndicator =
  775. Args.hasFlag(options::OPT_fsanitize_address_use_odr_indicator,
  776. options::OPT_fno_sanitize_address_use_odr_indicator,
  777. AsanUseOdrIndicator);
  778. if (AllAddedKinds & SanitizerKind::PointerCompare & ~AllRemove) {
  779. AsanInvalidPointerCmp = true;
  780. }
  781. if (AllAddedKinds & SanitizerKind::PointerSubtract & ~AllRemove) {
  782. AsanInvalidPointerSub = true;
  783. }
  784. if (TC.getTriple().isOSDarwin() &&
  785. (Args.hasArg(options::OPT_mkernel) ||
  786. Args.hasArg(options::OPT_fapple_kext))) {
  787. AsanDtorKind = llvm::AsanDtorKind::None;
  788. }
  789. if (const auto *Arg =
  790. Args.getLastArg(options::OPT_sanitize_address_destructor_EQ)) {
  791. auto parsedAsanDtorKind = AsanDtorKindFromString(Arg->getValue());
  792. if (parsedAsanDtorKind == llvm::AsanDtorKind::Invalid && DiagnoseErrors) {
  793. TC.getDriver().Diag(clang::diag::err_drv_unsupported_option_argument)
  794. << Arg->getOption().getName() << Arg->getValue();
  795. }
  796. AsanDtorKind = parsedAsanDtorKind;
  797. }
  798. if (const auto *Arg = Args.getLastArg(
  799. options::OPT_sanitize_address_use_after_return_EQ)) {
  800. auto parsedAsanUseAfterReturn =
  801. AsanDetectStackUseAfterReturnModeFromString(Arg->getValue());
  802. if (parsedAsanUseAfterReturn ==
  803. llvm::AsanDetectStackUseAfterReturnMode::Invalid &&
  804. DiagnoseErrors) {
  805. TC.getDriver().Diag(clang::diag::err_drv_unsupported_option_argument)
  806. << Arg->getOption().getName() << Arg->getValue();
  807. }
  808. AsanUseAfterReturn = parsedAsanUseAfterReturn;
  809. }
  810. } else {
  811. AsanUseAfterScope = false;
  812. // -fsanitize=pointer-compare/pointer-subtract requires -fsanitize=address.
  813. SanitizerMask DetectInvalidPointerPairs =
  814. SanitizerKind::PointerCompare | SanitizerKind::PointerSubtract;
  815. if ((AllAddedKinds & DetectInvalidPointerPairs & ~AllRemove) &&
  816. DiagnoseErrors) {
  817. TC.getDriver().Diag(clang::diag::err_drv_argument_only_allowed_with)
  818. << lastArgumentForMask(D, Args,
  819. SanitizerKind::PointerCompare |
  820. SanitizerKind::PointerSubtract)
  821. << "-fsanitize=address";
  822. }
  823. }
  824. if (AllAddedKinds & SanitizerKind::HWAddress) {
  825. if (Arg *HwasanAbiArg =
  826. Args.getLastArg(options::OPT_fsanitize_hwaddress_abi_EQ)) {
  827. HwasanAbi = HwasanAbiArg->getValue();
  828. if (HwasanAbi != "platform" && HwasanAbi != "interceptor" &&
  829. DiagnoseErrors)
  830. D.Diag(clang::diag::err_drv_invalid_value)
  831. << HwasanAbiArg->getAsString(Args) << HwasanAbi;
  832. } else {
  833. HwasanAbi = "interceptor";
  834. }
  835. if (TC.getTriple().getArch() == llvm::Triple::x86_64)
  836. HwasanUseAliases = Args.hasFlag(
  837. options::OPT_fsanitize_hwaddress_experimental_aliasing,
  838. options::OPT_fno_sanitize_hwaddress_experimental_aliasing,
  839. HwasanUseAliases);
  840. }
  841. if (AllAddedKinds & SanitizerKind::SafeStack) {
  842. // SafeStack runtime is built into the system on Android and Fuchsia.
  843. SafeStackRuntime =
  844. !TC.getTriple().isAndroid() && !TC.getTriple().isOSFuchsia();
  845. }
  846. LinkRuntimes =
  847. Args.hasFlag(options::OPT_fsanitize_link_runtime,
  848. options::OPT_fno_sanitize_link_runtime, LinkRuntimes);
  849. // Parse -link-cxx-sanitizer flag.
  850. LinkCXXRuntimes = Args.hasArg(options::OPT_fsanitize_link_cxx_runtime,
  851. options::OPT_fno_sanitize_link_cxx_runtime,
  852. LinkCXXRuntimes) ||
  853. D.CCCIsCXX();
  854. NeedsMemProfRt = Args.hasFlag(options::OPT_fmemory_profile,
  855. options::OPT_fmemory_profile_EQ,
  856. options::OPT_fno_memory_profile, false);
  857. // Finally, initialize the set of available and recoverable sanitizers.
  858. Sanitizers.Mask |= Kinds;
  859. RecoverableSanitizers.Mask |= RecoverableKinds;
  860. TrapSanitizers.Mask |= TrappingKinds;
  861. assert(!(RecoverableKinds & TrappingKinds) &&
  862. "Overlap between recoverable and trapping sanitizers");
  863. }
  864. static std::string toString(const clang::SanitizerSet &Sanitizers) {
  865. std::string Res;
  866. #define SANITIZER(NAME, ID) \
  867. if (Sanitizers.has(SanitizerKind::ID)) { \
  868. if (!Res.empty()) \
  869. Res += ","; \
  870. Res += NAME; \
  871. }
  872. #include "clang/Basic/Sanitizers.def"
  873. return Res;
  874. }
  875. static void addSpecialCaseListOpt(const llvm::opt::ArgList &Args,
  876. llvm::opt::ArgStringList &CmdArgs,
  877. const char *SCLOptFlag,
  878. const std::vector<std::string> &SCLFiles) {
  879. for (const auto &SCLPath : SCLFiles) {
  880. SmallString<64> SCLOpt(SCLOptFlag);
  881. SCLOpt += SCLPath;
  882. CmdArgs.push_back(Args.MakeArgString(SCLOpt));
  883. }
  884. }
  885. static void addIncludeLinkerOption(const ToolChain &TC,
  886. const llvm::opt::ArgList &Args,
  887. llvm::opt::ArgStringList &CmdArgs,
  888. StringRef SymbolName) {
  889. SmallString<64> LinkerOptionFlag;
  890. LinkerOptionFlag = "--linker-option=/include:";
  891. if (TC.getTriple().getArch() == llvm::Triple::x86) {
  892. // Win32 mangles C function names with a '_' prefix.
  893. LinkerOptionFlag += '_';
  894. }
  895. LinkerOptionFlag += SymbolName;
  896. CmdArgs.push_back(Args.MakeArgString(LinkerOptionFlag));
  897. }
  898. static bool hasTargetFeatureMTE(const llvm::opt::ArgStringList &CmdArgs) {
  899. for (auto Start = CmdArgs.begin(), End = CmdArgs.end(); Start != End; ++Start) {
  900. auto It = std::find(Start, End, StringRef("+mte"));
  901. if (It == End)
  902. break;
  903. if (It > Start && *std::prev(It) == StringRef("-target-feature"))
  904. return true;
  905. Start = It;
  906. }
  907. return false;
  908. }
  909. void SanitizerArgs::addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args,
  910. llvm::opt::ArgStringList &CmdArgs,
  911. types::ID InputType) const {
  912. // NVPTX doesn't currently support sanitizers. Bailing out here means
  913. // that e.g. -fsanitize=address applies only to host code, which is what we
  914. // want for now.
  915. //
  916. // AMDGPU sanitizer support is experimental and controlled by -fgpu-sanitize.
  917. if (TC.getTriple().isNVPTX() ||
  918. (TC.getTriple().isAMDGPU() &&
  919. !Args.hasFlag(options::OPT_fgpu_sanitize,
  920. options::OPT_fno_gpu_sanitize)))
  921. return;
  922. // Translate available CoverageFeatures to corresponding clang-cc1 flags.
  923. // Do it even if Sanitizers.empty() since some forms of coverage don't require
  924. // sanitizers.
  925. std::pair<int, const char *> CoverageFlags[] = {
  926. std::make_pair(CoverageFunc, "-fsanitize-coverage-type=1"),
  927. std::make_pair(CoverageBB, "-fsanitize-coverage-type=2"),
  928. std::make_pair(CoverageEdge, "-fsanitize-coverage-type=3"),
  929. std::make_pair(CoverageIndirCall, "-fsanitize-coverage-indirect-calls"),
  930. std::make_pair(CoverageTraceBB, "-fsanitize-coverage-trace-bb"),
  931. std::make_pair(CoverageTraceCmp, "-fsanitize-coverage-trace-cmp"),
  932. std::make_pair(CoverageTraceDiv, "-fsanitize-coverage-trace-div"),
  933. std::make_pair(CoverageTraceGep, "-fsanitize-coverage-trace-gep"),
  934. std::make_pair(Coverage8bitCounters, "-fsanitize-coverage-8bit-counters"),
  935. std::make_pair(CoverageTracePC, "-fsanitize-coverage-trace-pc"),
  936. std::make_pair(CoverageTracePCGuard,
  937. "-fsanitize-coverage-trace-pc-guard"),
  938. std::make_pair(CoverageInline8bitCounters,
  939. "-fsanitize-coverage-inline-8bit-counters"),
  940. std::make_pair(CoverageInlineBoolFlag,
  941. "-fsanitize-coverage-inline-bool-flag"),
  942. std::make_pair(CoveragePCTable, "-fsanitize-coverage-pc-table"),
  943. std::make_pair(CoverageNoPrune, "-fsanitize-coverage-no-prune"),
  944. std::make_pair(CoverageStackDepth, "-fsanitize-coverage-stack-depth"),
  945. std::make_pair(CoverageTraceLoads, "-fsanitize-coverage-trace-loads"),
  946. std::make_pair(CoverageTraceStores, "-fsanitize-coverage-trace-stores")};
  947. for (auto F : CoverageFlags) {
  948. if (CoverageFeatures & F.first)
  949. CmdArgs.push_back(F.second);
  950. }
  951. addSpecialCaseListOpt(
  952. Args, CmdArgs, "-fsanitize-coverage-allowlist=", CoverageAllowlistFiles);
  953. addSpecialCaseListOpt(Args, CmdArgs, "-fsanitize-coverage-ignorelist=",
  954. CoverageIgnorelistFiles);
  955. if (TC.getTriple().isOSWindows() && needsUbsanRt()) {
  956. // Instruct the code generator to embed linker directives in the object file
  957. // that cause the required runtime libraries to be linked.
  958. CmdArgs.push_back(
  959. Args.MakeArgString("--dependent-lib=" +
  960. TC.getCompilerRTBasename(Args, "ubsan_standalone")));
  961. if (types::isCXX(InputType))
  962. CmdArgs.push_back(Args.MakeArgString(
  963. "--dependent-lib=" +
  964. TC.getCompilerRTBasename(Args, "ubsan_standalone_cxx")));
  965. }
  966. if (TC.getTriple().isOSWindows() && needsStatsRt()) {
  967. CmdArgs.push_back(Args.MakeArgString(
  968. "--dependent-lib=" + TC.getCompilerRTBasename(Args, "stats_client")));
  969. // The main executable must export the stats runtime.
  970. // FIXME: Only exporting from the main executable (e.g. based on whether the
  971. // translation unit defines main()) would save a little space, but having
  972. // multiple copies of the runtime shouldn't hurt.
  973. CmdArgs.push_back(Args.MakeArgString(
  974. "--dependent-lib=" + TC.getCompilerRTBasename(Args, "stats")));
  975. addIncludeLinkerOption(TC, Args, CmdArgs, "__sanitizer_stats_register");
  976. }
  977. if (Sanitizers.empty())
  978. return;
  979. CmdArgs.push_back(Args.MakeArgString("-fsanitize=" + toString(Sanitizers)));
  980. if (!RecoverableSanitizers.empty())
  981. CmdArgs.push_back(Args.MakeArgString("-fsanitize-recover=" +
  982. toString(RecoverableSanitizers)));
  983. if (!TrapSanitizers.empty())
  984. CmdArgs.push_back(
  985. Args.MakeArgString("-fsanitize-trap=" + toString(TrapSanitizers)));
  986. addSpecialCaseListOpt(Args, CmdArgs,
  987. "-fsanitize-ignorelist=", UserIgnorelistFiles);
  988. addSpecialCaseListOpt(Args, CmdArgs,
  989. "-fsanitize-system-ignorelist=", SystemIgnorelistFiles);
  990. if (MsanTrackOrigins)
  991. CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-track-origins=" +
  992. Twine(MsanTrackOrigins)));
  993. if (MsanUseAfterDtor)
  994. CmdArgs.push_back("-fsanitize-memory-use-after-dtor");
  995. if (MsanParamRetval)
  996. CmdArgs.push_back("-fsanitize-memory-param-retval");
  997. // FIXME: Pass these parameters as function attributes, not as -llvm flags.
  998. if (!TsanMemoryAccess) {
  999. CmdArgs.push_back("-mllvm");
  1000. CmdArgs.push_back("-tsan-instrument-memory-accesses=0");
  1001. CmdArgs.push_back("-mllvm");
  1002. CmdArgs.push_back("-tsan-instrument-memintrinsics=0");
  1003. }
  1004. if (!TsanFuncEntryExit) {
  1005. CmdArgs.push_back("-mllvm");
  1006. CmdArgs.push_back("-tsan-instrument-func-entry-exit=0");
  1007. }
  1008. if (!TsanAtomics) {
  1009. CmdArgs.push_back("-mllvm");
  1010. CmdArgs.push_back("-tsan-instrument-atomics=0");
  1011. }
  1012. if (HwasanUseAliases) {
  1013. CmdArgs.push_back("-mllvm");
  1014. CmdArgs.push_back("-hwasan-experimental-use-page-aliases=1");
  1015. }
  1016. if (CfiCrossDso)
  1017. CmdArgs.push_back("-fsanitize-cfi-cross-dso");
  1018. if (CfiICallGeneralizePointers)
  1019. CmdArgs.push_back("-fsanitize-cfi-icall-generalize-pointers");
  1020. if (CfiCanonicalJumpTables)
  1021. CmdArgs.push_back("-fsanitize-cfi-canonical-jump-tables");
  1022. if (Stats)
  1023. CmdArgs.push_back("-fsanitize-stats");
  1024. if (MinimalRuntime)
  1025. CmdArgs.push_back("-fsanitize-minimal-runtime");
  1026. if (AsanFieldPadding)
  1027. CmdArgs.push_back(Args.MakeArgString("-fsanitize-address-field-padding=" +
  1028. Twine(AsanFieldPadding)));
  1029. if (AsanUseAfterScope)
  1030. CmdArgs.push_back("-fsanitize-address-use-after-scope");
  1031. if (AsanPoisonCustomArrayCookie)
  1032. CmdArgs.push_back("-fsanitize-address-poison-custom-array-cookie");
  1033. if (AsanGlobalsDeadStripping)
  1034. CmdArgs.push_back("-fsanitize-address-globals-dead-stripping");
  1035. if (AsanUseOdrIndicator)
  1036. CmdArgs.push_back("-fsanitize-address-use-odr-indicator");
  1037. if (AsanInvalidPointerCmp) {
  1038. CmdArgs.push_back("-mllvm");
  1039. CmdArgs.push_back("-asan-detect-invalid-pointer-cmp");
  1040. }
  1041. if (AsanInvalidPointerSub) {
  1042. CmdArgs.push_back("-mllvm");
  1043. CmdArgs.push_back("-asan-detect-invalid-pointer-sub");
  1044. }
  1045. if (AsanOutlineInstrumentation) {
  1046. CmdArgs.push_back("-mllvm");
  1047. CmdArgs.push_back("-asan-instrumentation-with-call-threshold=0");
  1048. }
  1049. // Only pass the option to the frontend if the user requested,
  1050. // otherwise the frontend will just use the codegen default.
  1051. if (AsanDtorKind != llvm::AsanDtorKind::Invalid) {
  1052. CmdArgs.push_back(Args.MakeArgString("-fsanitize-address-destructor=" +
  1053. AsanDtorKindToString(AsanDtorKind)));
  1054. }
  1055. if (AsanUseAfterReturn != llvm::AsanDetectStackUseAfterReturnMode::Invalid) {
  1056. CmdArgs.push_back(Args.MakeArgString(
  1057. "-fsanitize-address-use-after-return=" +
  1058. AsanDetectStackUseAfterReturnModeToString(AsanUseAfterReturn)));
  1059. }
  1060. if (!HwasanAbi.empty()) {
  1061. CmdArgs.push_back("-default-function-attr");
  1062. CmdArgs.push_back(Args.MakeArgString("hwasan-abi=" + HwasanAbi));
  1063. }
  1064. if (Sanitizers.has(SanitizerKind::HWAddress) && !HwasanUseAliases) {
  1065. CmdArgs.push_back("-target-feature");
  1066. CmdArgs.push_back("+tagged-globals");
  1067. }
  1068. // MSan: Workaround for PR16386.
  1069. // ASan: This is mainly to help LSan with cases such as
  1070. // https://github.com/google/sanitizers/issues/373
  1071. // We can't make this conditional on -fsanitize=leak, as that flag shouldn't
  1072. // affect compilation.
  1073. if (Sanitizers.has(SanitizerKind::Memory) ||
  1074. Sanitizers.has(SanitizerKind::Address))
  1075. CmdArgs.push_back("-fno-assume-sane-operator-new");
  1076. // libFuzzer wants to intercept calls to certain library functions, so the
  1077. // following -fno-builtin-* flags force the compiler to emit interposable
  1078. // libcalls to these functions. Other sanitizers effectively do the same thing
  1079. // by marking all library call sites with NoBuiltin attribute in their LLVM
  1080. // pass. (see llvm::maybeMarkSanitizerLibraryCallNoBuiltin)
  1081. if (Sanitizers.has(SanitizerKind::FuzzerNoLink)) {
  1082. CmdArgs.push_back("-fno-builtin-bcmp");
  1083. CmdArgs.push_back("-fno-builtin-memcmp");
  1084. CmdArgs.push_back("-fno-builtin-strncmp");
  1085. CmdArgs.push_back("-fno-builtin-strcmp");
  1086. CmdArgs.push_back("-fno-builtin-strncasecmp");
  1087. CmdArgs.push_back("-fno-builtin-strcasecmp");
  1088. CmdArgs.push_back("-fno-builtin-strstr");
  1089. CmdArgs.push_back("-fno-builtin-strcasestr");
  1090. CmdArgs.push_back("-fno-builtin-memmem");
  1091. }
  1092. // Require -fvisibility= flag on non-Windows when compiling if vptr CFI is
  1093. // enabled.
  1094. if (Sanitizers.hasOneOf(CFIClasses) && !TC.getTriple().isOSWindows() &&
  1095. !Args.hasArg(options::OPT_fvisibility_EQ)) {
  1096. TC.getDriver().Diag(clang::diag::err_drv_argument_only_allowed_with)
  1097. << lastArgumentForMask(TC.getDriver(), Args,
  1098. Sanitizers.Mask & CFIClasses)
  1099. << "-fvisibility=";
  1100. }
  1101. if (Sanitizers.has(SanitizerKind::MemTag) && !hasTargetFeatureMTE(CmdArgs))
  1102. TC.getDriver().Diag(diag::err_stack_tagging_requires_hardware_feature);
  1103. }
  1104. SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
  1105. bool DiagnoseErrors) {
  1106. assert((A->getOption().matches(options::OPT_fsanitize_EQ) ||
  1107. A->getOption().matches(options::OPT_fno_sanitize_EQ) ||
  1108. A->getOption().matches(options::OPT_fsanitize_recover_EQ) ||
  1109. A->getOption().matches(options::OPT_fno_sanitize_recover_EQ) ||
  1110. A->getOption().matches(options::OPT_fsanitize_trap_EQ) ||
  1111. A->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) &&
  1112. "Invalid argument in parseArgValues!");
  1113. SanitizerMask Kinds;
  1114. for (int i = 0, n = A->getNumValues(); i != n; ++i) {
  1115. const char *Value = A->getValue(i);
  1116. SanitizerMask Kind;
  1117. // Special case: don't accept -fsanitize=all.
  1118. if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
  1119. 0 == strcmp("all", Value))
  1120. Kind = SanitizerMask();
  1121. else
  1122. Kind = parseSanitizerValue(Value, /*AllowGroups=*/true);
  1123. if (Kind)
  1124. Kinds |= Kind;
  1125. else if (DiagnoseErrors)
  1126. D.Diag(clang::diag::err_drv_unsupported_option_argument)
  1127. << A->getOption().getName() << Value;
  1128. }
  1129. return Kinds;
  1130. }
  1131. int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A,
  1132. bool DiagnoseErrors) {
  1133. assert(A->getOption().matches(options::OPT_fsanitize_coverage) ||
  1134. A->getOption().matches(options::OPT_fno_sanitize_coverage));
  1135. int Features = 0;
  1136. for (int i = 0, n = A->getNumValues(); i != n; ++i) {
  1137. const char *Value = A->getValue(i);
  1138. int F = llvm::StringSwitch<int>(Value)
  1139. .Case("func", CoverageFunc)
  1140. .Case("bb", CoverageBB)
  1141. .Case("edge", CoverageEdge)
  1142. .Case("indirect-calls", CoverageIndirCall)
  1143. .Case("trace-bb", CoverageTraceBB)
  1144. .Case("trace-cmp", CoverageTraceCmp)
  1145. .Case("trace-div", CoverageTraceDiv)
  1146. .Case("trace-gep", CoverageTraceGep)
  1147. .Case("8bit-counters", Coverage8bitCounters)
  1148. .Case("trace-pc", CoverageTracePC)
  1149. .Case("trace-pc-guard", CoverageTracePCGuard)
  1150. .Case("no-prune", CoverageNoPrune)
  1151. .Case("inline-8bit-counters", CoverageInline8bitCounters)
  1152. .Case("inline-bool-flag", CoverageInlineBoolFlag)
  1153. .Case("pc-table", CoveragePCTable)
  1154. .Case("stack-depth", CoverageStackDepth)
  1155. .Case("trace-loads", CoverageTraceLoads)
  1156. .Case("trace-stores", CoverageTraceStores)
  1157. .Default(0);
  1158. if (F == 0 && DiagnoseErrors)
  1159. D.Diag(clang::diag::err_drv_unsupported_option_argument)
  1160. << A->getOption().getName() << Value;
  1161. Features |= F;
  1162. }
  1163. return Features;
  1164. }
  1165. std::string lastArgumentForMask(const Driver &D, const llvm::opt::ArgList &Args,
  1166. SanitizerMask Mask) {
  1167. for (llvm::opt::ArgList::const_reverse_iterator I = Args.rbegin(),
  1168. E = Args.rend();
  1169. I != E; ++I) {
  1170. const auto *Arg = *I;
  1171. if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
  1172. SanitizerMask AddKinds =
  1173. expandSanitizerGroups(parseArgValues(D, Arg, false));
  1174. if (AddKinds & Mask)
  1175. return describeSanitizeArg(Arg, Mask);
  1176. } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
  1177. SanitizerMask RemoveKinds =
  1178. expandSanitizerGroups(parseArgValues(D, Arg, false));
  1179. Mask &= ~RemoveKinds;
  1180. }
  1181. }
  1182. llvm_unreachable("arg list didn't provide expected value");
  1183. }
  1184. std::string describeSanitizeArg(const llvm::opt::Arg *A, SanitizerMask Mask) {
  1185. assert(A->getOption().matches(options::OPT_fsanitize_EQ)
  1186. && "Invalid argument in describeSanitizerArg!");
  1187. std::string Sanitizers;
  1188. for (int i = 0, n = A->getNumValues(); i != n; ++i) {
  1189. if (expandSanitizerGroups(
  1190. parseSanitizerValue(A->getValue(i), /*AllowGroups=*/true)) &
  1191. Mask) {
  1192. if (!Sanitizers.empty())
  1193. Sanitizers += ",";
  1194. Sanitizers += A->getValue(i);
  1195. }
  1196. }
  1197. assert(!Sanitizers.empty() && "arg didn't provide expected value");
  1198. return "-fsanitize=" + Sanitizers;
  1199. }