head	1.1;
branch	1.1.1;
access;
symbols
	netbsd-11-0-RC4:1.1.1.12
	netbsd-11-0-RC3:1.1.1.12
	netbsd-11-0-RC2:1.1.1.12
	netbsd-11-0-RC1:1.1.1.12
	perseant-exfatfs-base-20250801:1.1.1.12
	netbsd-11:1.1.1.12.0.10
	netbsd-11-base:1.1.1.12
	netbsd-10-1-RELEASE:1.1.1.12
	perseant-exfatfs-base-20240630:1.1.1.12
	perseant-exfatfs:1.1.1.12.0.8
	perseant-exfatfs-base:1.1.1.12
	netbsd-8-3-RELEASE:1.1.1.9
	netbsd-9-4-RELEASE:1.1.1.11
	netbsd-10-0-RELEASE:1.1.1.12
	netbsd-10-0-RC6:1.1.1.12
	netbsd-10-0-RC5:1.1.1.12
	netbsd-10-0-RC4:1.1.1.12
	netbsd-10-0-RC3:1.1.1.12
	netbsd-10-0-RC2:1.1.1.12
	netbsd-10-0-RC1:1.1.1.12
	netbsd-10:1.1.1.12.0.6
	netbsd-10-base:1.1.1.12
	netbsd-9-3-RELEASE:1.1.1.11
	cjep_sun2x:1.1.1.12.0.4
	cjep_sun2x-base:1.1.1.12
	cjep_staticlib_x-base1:1.1.1.12
	netbsd-9-2-RELEASE:1.1.1.11
	cjep_staticlib_x:1.1.1.12.0.2
	cjep_staticlib_x-base:1.1.1.12
	netbsd-9-1-RELEASE:1.1.1.11
	phil-wifi-20200421:1.1.1.12
	phil-wifi-20200411:1.1.1.12
	phil-wifi-20200406:1.1.1.12
	netbsd-8-2-RELEASE:1.1.1.9
	netbsd-9-0-RELEASE:1.1.1.11
	netbsd-9-0-RC2:1.1.1.11
	netbsd-9-0-RC1:1.1.1.11
	netbsd-9:1.1.1.11.0.2
	netbsd-9-base:1.1.1.11
	phil-wifi-20190609:1.1.1.11
	netbsd-8-1-RELEASE:1.1.1.9
	netbsd-8-1-RC1:1.1.1.9
	pgoyette-compat-merge-20190127:1.1.1.10.2.1
	pgoyette-compat-20190127:1.1.1.11
	pgoyette-compat-20190118:1.1.1.11
	pgoyette-compat-1226:1.1.1.11
	pgoyette-compat-1126:1.1.1.11
	pgoyette-compat-1020:1.1.1.11
	pgoyette-compat-0930:1.1.1.11
	pgoyette-compat-0906:1.1.1.11
	netbsd-7-2-RELEASE:1.1.1.6.2.1
	pgoyette-compat-0728:1.1.1.11
	clang-337282:1.1.1.11
	netbsd-8-0-RELEASE:1.1.1.9
	phil-wifi:1.1.1.10.0.4
	phil-wifi-base:1.1.1.10
	pgoyette-compat-0625:1.1.1.10
	netbsd-8-0-RC2:1.1.1.9
	pgoyette-compat-0521:1.1.1.10
	pgoyette-compat-0502:1.1.1.10
	pgoyette-compat-0422:1.1.1.10
	netbsd-8-0-RC1:1.1.1.9
	pgoyette-compat-0415:1.1.1.10
	pgoyette-compat-0407:1.1.1.10
	pgoyette-compat-0330:1.1.1.10
	pgoyette-compat-0322:1.1.1.10
	pgoyette-compat-0315:1.1.1.10
	netbsd-7-1-2-RELEASE:1.1.1.6.2.1
	pgoyette-compat:1.1.1.10.0.2
	pgoyette-compat-base:1.1.1.10
	netbsd-7-1-1-RELEASE:1.1.1.6.2.1
	clang-319952:1.1.1.10
	matt-nb8-mediatek:1.1.1.9.0.10
	matt-nb8-mediatek-base:1.1.1.9
	clang-309604:1.1.1.10
	perseant-stdc-iso10646:1.1.1.9.0.8
	perseant-stdc-iso10646-base:1.1.1.9
	netbsd-8:1.1.1.9.0.6
	netbsd-8-base:1.1.1.9
	prg-localcount2-base3:1.1.1.9
	prg-localcount2-base2:1.1.1.9
	prg-localcount2-base1:1.1.1.9
	prg-localcount2:1.1.1.9.0.4
	prg-localcount2-base:1.1.1.9
	pgoyette-localcount-20170426:1.1.1.9
	bouyer-socketcan-base1:1.1.1.9
	pgoyette-localcount-20170320:1.1.1.9
	netbsd-7-1:1.1.1.6.2.1.0.6
	netbsd-7-1-RELEASE:1.1.1.6.2.1
	netbsd-7-1-RC2:1.1.1.6.2.1
	clang-294123:1.1.1.9
	netbsd-7-nhusb-base-20170116:1.1.1.6.2.1
	bouyer-socketcan:1.1.1.9.0.2
	bouyer-socketcan-base:1.1.1.9
	clang-291444:1.1.1.9
	pgoyette-localcount-20170107:1.1.1.8
	netbsd-7-1-RC1:1.1.1.6.2.1
	pgoyette-localcount-20161104:1.1.1.8
	netbsd-7-0-2-RELEASE:1.1.1.6.2.1
	localcount-20160914:1.1.1.8
	netbsd-7-nhusb:1.1.1.6.2.1.0.4
	netbsd-7-nhusb-base:1.1.1.6.2.1
	clang-280599:1.1.1.8
	pgoyette-localcount-20160806:1.1.1.8
	pgoyette-localcount-20160726:1.1.1.8
	pgoyette-localcount:1.1.1.8.0.2
	pgoyette-localcount-base:1.1.1.8
	netbsd-7-0-1-RELEASE:1.1.1.6.2.1
	clang-261930:1.1.1.8
	netbsd-7-0:1.1.1.6.2.1.0.2
	netbsd-7-0-RELEASE:1.1.1.6.2.1
	netbsd-7-0-RC3:1.1.1.6.2.1
	netbsd-7-0-RC2:1.1.1.6.2.1
	netbsd-7-0-RC1:1.1.1.6.2.1
	clang-237755:1.1.1.7
	clang-232565:1.1.1.7
	clang-227398:1.1.1.7
	tls-maxphys-base:1.1.1.6
	tls-maxphys:1.1.1.6.0.4
	netbsd-7:1.1.1.6.0.2
	netbsd-7-base:1.1.1.6
	clang-215315:1.1.1.6
	clang-209886:1.1.1.5
	yamt-pagecache:1.1.1.4.0.4
	yamt-pagecache-base9:1.1.1.4
	tls-earlyentropy:1.1.1.4.0.2
	tls-earlyentropy-base:1.1.1.5
	riastradh-xf86-video-intel-2-7-1-pre-2-21-15:1.1.1.4
	riastradh-drm2-base3:1.1.1.4
	clang-202566:1.1.1.4
	clang-201163:1.1.1.4
	clang-199312:1.1.1.3
	clang-198450:1.1.1.2
	clang-196603:1.1.1.1
	clang-195771:1.1.1.1
	LLVM:1.1.1;
locks; strict;
comment	@// @;


1.1
date	2013.11.28.14.14.52;	author joerg;	state Exp;
branches
	1.1.1.1;
next	;
commitid	ow8OybrawrB1f3fx;

1.1.1.1
date	2013.11.28.14.14.52;	author joerg;	state Exp;
branches;
next	1.1.1.2;
commitid	ow8OybrawrB1f3fx;

1.1.1.2
date	2014.01.05.15.39.28;	author joerg;	state Exp;
branches;
next	1.1.1.3;
commitid	wh3aCSIWykURqWjx;

1.1.1.3
date	2014.01.15.21.26.24;	author joerg;	state Exp;
branches;
next	1.1.1.4;
commitid	NQXlzzA0SPkc5glx;

1.1.1.4
date	2014.02.14.20.07.24;	author joerg;	state Exp;
branches
	1.1.1.4.2.1
	1.1.1.4.4.1;
next	1.1.1.5;
commitid	annVkZ1sc17rF6px;

1.1.1.5
date	2014.05.30.18.14.41;	author joerg;	state Exp;
branches;
next	1.1.1.6;
commitid	8q0kdlBlCn09GACx;

1.1.1.6
date	2014.08.10.17.08.34;	author joerg;	state Exp;
branches
	1.1.1.6.2.1
	1.1.1.6.4.1;
next	1.1.1.7;
commitid	N85tXAN6Ex9VZPLx;

1.1.1.7
date	2015.01.29.19.57.30;	author joerg;	state Exp;
branches;
next	1.1.1.8;
commitid	mlISSizlPKvepX7y;

1.1.1.8
date	2016.02.27.22.12.04;	author joerg;	state Exp;
branches
	1.1.1.8.2.1;
next	1.1.1.9;
commitid	tIimz3oDlh1NpBWy;

1.1.1.9
date	2017.01.11.10.33.39;	author joerg;	state Exp;
branches;
next	1.1.1.10;
commitid	CNnUNfII1jgNmxBz;

1.1.1.10
date	2017.08.01.19.34.59;	author joerg;	state Exp;
branches
	1.1.1.10.2.1
	1.1.1.10.4.1;
next	1.1.1.11;
commitid	pMuDy65V0VicSx1A;

1.1.1.11
date	2018.07.17.18.31.13;	author joerg;	state Exp;
branches;
next	1.1.1.12;
commitid	wDzL46ALjrCZgwKA;

1.1.1.12
date	2019.11.13.22.19.22;	author joerg;	state dead;
branches;
next	;
commitid	QD8YATxuNG34YJKB;

1.1.1.4.2.1
date	2014.08.10.07.08.08;	author tls;	state Exp;
branches;
next	;
commitid	t01A1TLTYxkpGMLx;

1.1.1.4.4.1
date	2014.02.14.20.07.24;	author yamt;	state dead;
branches;
next	1.1.1.4.4.2;
commitid	WSrDtL5nYAUyiyBx;

1.1.1.4.4.2
date	2014.05.22.16.18.27;	author yamt;	state Exp;
branches;
next	;
commitid	WSrDtL5nYAUyiyBx;

1.1.1.6.2.1
date	2015.06.04.20.04.28;	author snj;	state Exp;
branches;
next	;
commitid	yRnjq9fueSo6n9oy;

1.1.1.6.4.1
date	2014.08.10.17.08.34;	author tls;	state dead;
branches;
next	1.1.1.6.4.2;
commitid	jTnpym9Qu0o4R1Nx;

1.1.1.6.4.2
date	2014.08.19.23.47.27;	author tls;	state Exp;
branches;
next	;
commitid	jTnpym9Qu0o4R1Nx;

1.1.1.8.2.1
date	2017.03.20.06.52.37;	author pgoyette;	state Exp;
branches;
next	;
commitid	jjw7cAwgyKq7RfKz;

1.1.1.10.2.1
date	2018.07.28.04.33.18;	author pgoyette;	state Exp;
branches;
next	;
commitid	1UP1xAIUxv1ZgRLA;

1.1.1.10.4.1
date	2019.06.10.21.45.22;	author christos;	state Exp;
branches;
next	1.1.1.10.4.2;
commitid	jtc8rnCzWiEEHGqB;

1.1.1.10.4.2
date	2020.04.13.07.46.33;	author martin;	state dead;
branches;
next	;
commitid	X01YhRUPVUDaec4C;


desc
@@


1.1
log
@Initial revision
@
text
@//===--- SanitizerArgs.cpp - Arguments for sanitizer tools  ---------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Driver/SanitizerArgs.h"

#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Options.h"
#include "clang/Driver/ToolChain.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Transforms/Utils/SpecialCaseList.h"

using namespace clang::driver;
using namespace llvm::opt;

void SanitizerArgs::clear() {
  Kind = 0;
  BlacklistFile = "";
  MsanTrackOrigins = false;
  AsanZeroBaseShadow = false;
  UbsanTrapOnError = false;
}

SanitizerArgs::SanitizerArgs() {
  clear();
}

SanitizerArgs::SanitizerArgs(const ToolChain &TC,
                             const llvm::opt::ArgList &Args) {
  clear();
  unsigned AllAdd = 0;  // All kinds of sanitizers that were turned on
                        // at least once (possibly, disabled further).
  unsigned AllRemove = 0;  // During the loop below, the accumulated set of
                           // sanitizers disabled by the current sanitizer
                           // argument or any argument after it.
  unsigned DiagnosedKinds = 0;  // All Kinds we have diagnosed up to now.
                                // Used to deduplicate diagnostics.
  const Driver &D = TC.getDriver();
  for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
       I != E; ++I) {
    unsigned Add, Remove;
    if (!parse(D, Args, *I, Add, Remove, true))
      continue;
    (*I)->claim();

    AllAdd |= expandGroups(Add);
    AllRemove |= expandGroups(Remove);

    // Avoid diagnosing any sanitizer which is disabled later.
    Add &= ~AllRemove;
    // At this point we have not expanded groups, so any unsupported sanitizers
    // in Add are those which have been explicitly enabled. Diagnose them.
    Add = filterUnsupportedKinds(TC, Add, Args, *I, /*DiagnoseErrors=*/true,
                                 DiagnosedKinds);
    Add = expandGroups(Add);
    // Group expansion may have enabled a sanitizer which is disabled later.
    Add &= ~AllRemove;
    // Silently discard any unsupported sanitizers implicitly enabled through
    // group expansion.
    Add = filterUnsupportedKinds(TC, Add, Args, *I, /*DiagnoseErrors=*/false,
                                 DiagnosedKinds);

    Kind |= Add;
  }

  UbsanTrapOnError =
    Args.hasArg(options::OPT_fcatch_undefined_behavior) ||
    Args.hasFlag(options::OPT_fsanitize_undefined_trap_on_error,
                 options::OPT_fno_sanitize_undefined_trap_on_error, false);

  if (Args.hasArg(options::OPT_fcatch_undefined_behavior) &&
      !Args.hasFlag(options::OPT_fsanitize_undefined_trap_on_error,
                    options::OPT_fno_sanitize_undefined_trap_on_error, true)) {
    D.Diag(diag::err_drv_argument_not_allowed_with)
      << "-fcatch-undefined-behavior"
      << "-fno-sanitize-undefined-trap-on-error";
  }

  // Warn about undefined sanitizer options that require runtime support.
  if (UbsanTrapOnError && notAllowedWithTrap()) {
    if (Args.hasArg(options::OPT_fcatch_undefined_behavior))
      D.Diag(diag::err_drv_argument_not_allowed_with)
        << lastArgumentForKind(D, Args, NotAllowedWithTrap)
        << "-fcatch-undefined-behavior";
    else if (Args.hasFlag(options::OPT_fsanitize_undefined_trap_on_error,
                          options::OPT_fno_sanitize_undefined_trap_on_error,
                          false))
      D.Diag(diag::err_drv_argument_not_allowed_with)
        << lastArgumentForKind(D, Args, NotAllowedWithTrap)
        << "-fsanitize-undefined-trap-on-error";
  }

  // Only one runtime library can be used at once.
  bool NeedsAsan = needsAsanRt();
  bool NeedsTsan = needsTsanRt();
  bool NeedsMsan = needsMsanRt();
  bool NeedsLsan = needsLeakDetection();
  if (NeedsAsan && NeedsTsan)
    D.Diag(diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, NeedsAsanRt)
      << lastArgumentForKind(D, Args, NeedsTsanRt);
  if (NeedsAsan && NeedsMsan)
    D.Diag(diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, NeedsAsanRt)
      << lastArgumentForKind(D, Args, NeedsMsanRt);
  if (NeedsTsan && NeedsMsan)
    D.Diag(diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, NeedsTsanRt)
      << lastArgumentForKind(D, Args, NeedsMsanRt);
  if (NeedsLsan && NeedsTsan)
    D.Diag(diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, NeedsLeakDetection)
      << lastArgumentForKind(D, Args, NeedsTsanRt);
  if (NeedsLsan && NeedsMsan)
    D.Diag(diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, NeedsLeakDetection)
      << lastArgumentForKind(D, Args, NeedsMsanRt);
  // FIXME: Currenly -fsanitize=leak is silently ignored in the presence of
  // -fsanitize=address. Perhaps it should print an error, or perhaps
  // -f(-no)sanitize=leak should change whether leak detection is enabled by
  // default in ASan?

  // If -fsanitize contains extra features of ASan, it should also
  // explicitly contain -fsanitize=address (probably, turned off later in the
  // command line).
  if ((Kind & AddressFull) != 0 && (AllAdd & Address) == 0)
    D.Diag(diag::warn_drv_unused_sanitizer)
     << lastArgumentForKind(D, Args, AddressFull)
     << "-fsanitize=address";

  // Parse -f(no-)sanitize-blacklist options.
  if (Arg *BLArg = Args.getLastArg(options::OPT_fsanitize_blacklist,
                                   options::OPT_fno_sanitize_blacklist)) {
    if (BLArg->getOption().matches(options::OPT_fsanitize_blacklist)) {
      std::string BLPath = BLArg->getValue();
      if (llvm::sys::fs::exists(BLPath)) {
        // Validate the blacklist format.
        std::string BLError;
        llvm::OwningPtr<llvm::SpecialCaseList> SCL(
            llvm::SpecialCaseList::create(BLPath, BLError));
        if (!SCL.get())
          D.Diag(diag::err_drv_malformed_sanitizer_blacklist) << BLError;
        else
          BlacklistFile = BLPath;
      } else {
        D.Diag(diag::err_drv_no_such_file) << BLPath;
      }
    }
  } else {
    // If no -fsanitize-blacklist option is specified, try to look up for
    // blacklist in the resource directory.
    std::string BLPath;
    if (getDefaultBlacklistForKind(D, Kind, BLPath) &&
        llvm::sys::fs::exists(BLPath))
      BlacklistFile = BLPath;
  }

  // Parse -f(no-)sanitize-memory-track-origins options.
  if (NeedsMsan)
    MsanTrackOrigins =
      Args.hasFlag(options::OPT_fsanitize_memory_track_origins,
                   options::OPT_fno_sanitize_memory_track_origins,
                   /* Default */false);

  // Parse -f(no-)sanitize-address-zero-base-shadow options.
  if (NeedsAsan) {
    bool IsAndroid = (TC.getTriple().getEnvironment() == llvm::Triple::Android);
    bool ZeroBaseShadowDefault = IsAndroid;
    AsanZeroBaseShadow =
        Args.hasFlag(options::OPT_fsanitize_address_zero_base_shadow,
                     options::OPT_fno_sanitize_address_zero_base_shadow,
                     ZeroBaseShadowDefault);
    // Zero-base shadow is a requirement on Android.
    if (IsAndroid && !AsanZeroBaseShadow) {
      D.Diag(diag::err_drv_argument_not_allowed_with)
          << "-fno-sanitize-address-zero-base-shadow"
          << lastArgumentForKind(D, Args, Address);
    }
  }
}

void SanitizerArgs::addArgs(const llvm::opt::ArgList &Args,
                            llvm::opt::ArgStringList &CmdArgs) const {
  if (!Kind)
    return;
  SmallString<256> SanitizeOpt("-fsanitize=");
#define SANITIZER(NAME, ID) \
  if (Kind & ID) \
    SanitizeOpt += NAME ",";
#include "clang/Basic/Sanitizers.def"
  SanitizeOpt.pop_back();
  CmdArgs.push_back(Args.MakeArgString(SanitizeOpt));
  if (!BlacklistFile.empty()) {
    SmallString<64> BlacklistOpt("-fsanitize-blacklist=");
    BlacklistOpt += BlacklistFile;
    CmdArgs.push_back(Args.MakeArgString(BlacklistOpt));
  }

  if (MsanTrackOrigins)
    CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-track-origins"));

  if (AsanZeroBaseShadow)
    CmdArgs.push_back(
        Args.MakeArgString("-fsanitize-address-zero-base-shadow"));

  // Workaround for PR16386.
  if (needsMsanRt())
    CmdArgs.push_back(Args.MakeArgString("-fno-assume-sane-operator-new"));
}

unsigned SanitizerArgs::parse(const char *Value) {
  unsigned ParsedKind = llvm::StringSwitch<SanitizeKind>(Value)
#define SANITIZER(NAME, ID) .Case(NAME, ID)
#define SANITIZER_GROUP(NAME, ID, ALIAS) .Case(NAME, ID##Group)
#include "clang/Basic/Sanitizers.def"
    .Default(SanitizeKind());
  // Assume -fsanitize=address implies -fsanitize=init-order,use-after-return.
  // FIXME: This should be either specified in Sanitizers.def, or go away when
  // we get rid of "-fsanitize=init-order,use-after-return" flags at all.
  if (ParsedKind & Address)
    ParsedKind |= InitOrder | UseAfterReturn;
  return ParsedKind;
}

unsigned SanitizerArgs::expandGroups(unsigned Kinds) {
#define SANITIZER(NAME, ID)
#define SANITIZER_GROUP(NAME, ID, ALIAS) if (Kinds & ID##Group) Kinds |= ID;
#include "clang/Basic/Sanitizers.def"
  return Kinds;
}

void SanitizerArgs::filterUnsupportedMask(const ToolChain &TC, unsigned &Kinds,
                                          unsigned Mask,
                                          const llvm::opt::ArgList &Args,
                                          const llvm::opt::Arg *A,
                                          bool DiagnoseErrors,
                                          unsigned &DiagnosedKinds) {
  unsigned MaskedKinds = Kinds & Mask;
  if (!MaskedKinds)
    return;
  Kinds &= ~Mask;
  // Do we have new kinds to diagnose?
  if (DiagnoseErrors && (DiagnosedKinds & MaskedKinds) != MaskedKinds) {
    // Only diagnose the new kinds.
    std::string Desc =
        describeSanitizeArg(Args, A, MaskedKinds & ~DiagnosedKinds);
    TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
        << Desc << TC.getTriple().str();
    DiagnosedKinds |= MaskedKinds;
  }
}

unsigned SanitizerArgs::filterUnsupportedKinds(const ToolChain &TC,
                                               unsigned Kinds,
                                               const llvm::opt::ArgList &Args,
                                               const llvm::opt::Arg *A,
                                               bool DiagnoseErrors,
                                               unsigned &DiagnosedKinds) {
  bool IsLinux = TC.getTriple().getOS() == llvm::Triple::Linux;
  bool IsX86 = TC.getTriple().getArch() == llvm::Triple::x86;
  bool IsX86_64 = TC.getTriple().getArch() == llvm::Triple::x86_64;
  if (!(IsLinux && IsX86_64)) {
    filterUnsupportedMask(TC, Kinds, Thread | Memory | DataFlow, Args, A,
                          DiagnoseErrors, DiagnosedKinds);
  }
  if (!(IsLinux && (IsX86 || IsX86_64))) {
    filterUnsupportedMask(TC, Kinds, Function, Args, A, DiagnoseErrors,
                          DiagnosedKinds);
  }
  return Kinds;
}

unsigned SanitizerArgs::parse(const Driver &D, const llvm::opt::Arg *A,
                              bool DiagnoseErrors) {
  unsigned Kind = 0;
  for (unsigned I = 0, N = A->getNumValues(); I != N; ++I) {
    if (unsigned K = parse(A->getValue(I)))
      Kind |= K;
    else if (DiagnoseErrors)
      D.Diag(diag::err_drv_unsupported_option_argument)
        << A->getOption().getName() << A->getValue(I);
  }
  return Kind;
}

bool SanitizerArgs::parse(const Driver &D, const llvm::opt::ArgList &Args,
                          const llvm::opt::Arg *A, unsigned &Add,
                          unsigned &Remove, bool DiagnoseErrors) {
  Add = 0;
  Remove = 0;
  const char *DeprecatedReplacement = 0;
  if (A->getOption().matches(options::OPT_faddress_sanitizer)) {
    Add = Address;
    DeprecatedReplacement = "-fsanitize=address";
  } else if (A->getOption().matches(options::OPT_fno_address_sanitizer)) {
    Remove = Address;
    DeprecatedReplacement = "-fno-sanitize=address";
  } else if (A->getOption().matches(options::OPT_fthread_sanitizer)) {
    Add = Thread;
    DeprecatedReplacement = "-fsanitize=thread";
  } else if (A->getOption().matches(options::OPT_fno_thread_sanitizer)) {
    Remove = Thread;
    DeprecatedReplacement = "-fno-sanitize=thread";
  } else if (A->getOption().matches(options::OPT_fcatch_undefined_behavior)) {
    Add = UndefinedTrap;
    DeprecatedReplacement =
      "-fsanitize=undefined-trap -fsanitize-undefined-trap-on-error";
  } else if (A->getOption().matches(options::OPT_fbounds_checking) ||
             A->getOption().matches(options::OPT_fbounds_checking_EQ)) {
    Add = LocalBounds;
    DeprecatedReplacement = "-fsanitize=local-bounds";
  } else if (A->getOption().matches(options::OPT_fsanitize_EQ)) {
    Add = parse(D, A, DiagnoseErrors);
  } else if (A->getOption().matches(options::OPT_fno_sanitize_EQ)) {
    Remove = parse(D, A, DiagnoseErrors);
  } else {
    // Flag is not relevant to sanitizers.
    return false;
  }
  // If this is a deprecated synonym, produce a warning directing users
  // towards the new spelling.
  if (DeprecatedReplacement && DiagnoseErrors)
    D.Diag(diag::warn_drv_deprecated_arg)
      << A->getAsString(Args) << DeprecatedReplacement;
  return true;
}

std::string SanitizerArgs::lastArgumentForKind(const Driver &D,
                                               const llvm::opt::ArgList &Args,
                                               unsigned Kind) {
  for (llvm::opt::ArgList::const_reverse_iterator I = Args.rbegin(),
                                                  E = Args.rend();
       I != E; ++I) {
    unsigned Add, Remove;
    if (parse(D, Args, *I, Add, Remove, false) &&
        (expandGroups(Add) & Kind))
      return describeSanitizeArg(Args, *I, Kind);
    Kind &= ~Remove;
  }
  llvm_unreachable("arg list didn't provide expected value");
}

std::string SanitizerArgs::describeSanitizeArg(const llvm::opt::ArgList &Args,
                                               const llvm::opt::Arg *A,
                                               unsigned Mask) {
  if (!A->getOption().matches(options::OPT_fsanitize_EQ))
    return A->getAsString(Args);

  std::string Sanitizers;
  for (unsigned I = 0, N = A->getNumValues(); I != N; ++I) {
    if (expandGroups(parse(A->getValue(I))) & Mask) {
      if (!Sanitizers.empty())
        Sanitizers += ",";
      Sanitizers += A->getValue(I);
    }
  }

  assert(!Sanitizers.empty() && "arg didn't provide expected value");
  return "-fsanitize=" + Sanitizers;
}

bool SanitizerArgs::getDefaultBlacklistForKind(const Driver &D, unsigned Kind,
                                               std::string &BLPath) {
  const char *BlacklistFile = 0;
  if (Kind & NeedsAsanRt)
    BlacklistFile = "asan_blacklist.txt";
  else if (Kind & NeedsMsanRt)
    BlacklistFile = "msan_blacklist.txt";
  else if (Kind & NeedsTsanRt)
    BlacklistFile = "tsan_blacklist.txt";
  else if (Kind & NeedsDfsanRt)
    BlacklistFile = "dfsan_abilist.txt";

  if (BlacklistFile) {
    SmallString<64> Path(D.ResourceDir);
    llvm::sys::path::append(Path, BlacklistFile);
    BLPath = Path.str();
    return true;
  }
  return false;
}
@


1.1.1.1
log
@Import Clang 3.4rc1 r195771.
@
text
@@


1.1.1.2
log
@Import clang 3.5svn r198450.
@
text
@d126 1
a126 1
  // FIXME: Currently -fsanitize=leak is silently ignored in the presence of
@


1.1.1.3
log
@Import Clang 3.5svn r199312
@
text
@d10 1
@


1.1.1.4
log
@Import Clang 3.5svn r201163.
@
text
@d171 5
a175 1
  if (NeedsAsan)
d177 10
a186 1
        (TC.getTriple().getEnvironment() == llvm::Triple::Android);
d209 4
@


1.1.1.4.2.1
log
@Rebase.
@
text
@d14 1
a14 1
#include "llvm/ADT/StringExtras.h"
a18 1
#include <memory>
d26 1
a26 1
  MsanTrackOrigins = 0;
a28 1
  AsanSharedRuntime = false;
d74 1
d78 8
d88 10
a97 3
    D.Diag(diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, NotAllowedWithTrap)
      << "-fsanitize-undefined-trap-on-error";
d146 1
a146 1
        std::unique_ptr<llvm::SpecialCaseList> SCL(
d165 7
a171 25
  // Parse -f[no-]sanitize-memory-track-origins[=level] options.
  if (NeedsMsan) {
    if (Arg *A =
            Args.getLastArg(options::OPT_fsanitize_memory_track_origins_EQ,
                            options::OPT_fsanitize_memory_track_origins,
                            options::OPT_fno_sanitize_memory_track_origins)) {
      if (A->getOption().matches(options::OPT_fsanitize_memory_track_origins)) {
        MsanTrackOrigins = 1;
      } else if (A->getOption().matches(
                     options::OPT_fno_sanitize_memory_track_origins)) {
        MsanTrackOrigins = 0;
      } else {
        StringRef S = A->getValue();
        if (S.getAsInteger(0, MsanTrackOrigins) || MsanTrackOrigins < 0 ||
            MsanTrackOrigins > 2) {
          D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
        }
      }
    }
  }

  if (NeedsAsan) {
    AsanSharedRuntime =
      (TC.getTriple().getEnvironment() == llvm::Triple::Android) ||
      Args.hasArg(options::OPT_shared_libasan);
a173 1
  }
d194 1
a194 2
    CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-track-origins=" +
                                         llvm::utostr(MsanTrackOrigins)));
d281 22
a302 1
  if (A->getOption().matches(options::OPT_fsanitize_EQ)) {
d310 5
d354 1
a354 1
  const char *BlacklistFile = nullptr;
@


1.1.1.5
log
@Import Clang 3.5svn r209886.
@
text
@d14 1
a14 1
#include "llvm/ADT/StringExtras.h"
a18 1
#include <memory>
d26 1
a26 1
  MsanTrackOrigins = 0;
a28 1
  AsanSharedRuntime = false;
d74 1
d78 8
d88 10
a97 3
    D.Diag(diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, NotAllowedWithTrap)
      << "-fsanitize-undefined-trap-on-error";
d146 1
a146 1
        std::unique_ptr<llvm::SpecialCaseList> SCL(
d165 7
a171 25
  // Parse -f[no-]sanitize-memory-track-origins[=level] options.
  if (NeedsMsan) {
    if (Arg *A =
            Args.getLastArg(options::OPT_fsanitize_memory_track_origins_EQ,
                            options::OPT_fsanitize_memory_track_origins,
                            options::OPT_fno_sanitize_memory_track_origins)) {
      if (A->getOption().matches(options::OPT_fsanitize_memory_track_origins)) {
        MsanTrackOrigins = 1;
      } else if (A->getOption().matches(
                     options::OPT_fno_sanitize_memory_track_origins)) {
        MsanTrackOrigins = 0;
      } else {
        StringRef S = A->getValue();
        if (S.getAsInteger(0, MsanTrackOrigins) || MsanTrackOrigins < 0 ||
            MsanTrackOrigins > 2) {
          D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
        }
      }
    }
  }

  if (NeedsAsan) {
    AsanSharedRuntime =
      (TC.getTriple().getEnvironment() == llvm::Triple::Android) ||
      Args.hasArg(options::OPT_shared_libasan);
a173 1
  }
d194 1
a194 2
    CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-track-origins=" +
                                         llvm::utostr(MsanTrackOrigins)));
d281 22
a302 1
  if (A->getOption().matches(options::OPT_fsanitize_EQ)) {
d310 5
d354 1
a354 1
  const char *BlacklistFile = nullptr;
@


1.1.1.6
log
@Import clang 3.6svn r215315.
@
text
@d18 1
a18 1
#include "llvm/Support/SpecialCaseList.h"
d31 4
a34 1
  LinkCXXRuntimes = false;
d116 8
d174 2
a175 2
        Args.hasArg(options::OPT_shared_libasan) ||
        (TC.getTriple().getEnvironment() == llvm::Triple::Android);
a178 4

  // Parse -link-cxx-sanitizer flag.
  LinkCXXRuntimes =
      Args.hasArg(options::OPT_fsanitize_link_cxx_runtime) || D.CCCIsCXX();
d213 5
@


1.1.1.6.2.1
log
@Update LLVM to 3.6.1, requested by joerg in ticket 824.
@
text
@a23 125
namespace {
/// Assign ordinals to possible values of -fsanitize= flag.
/// We use the ordinal values as bit positions within \c SanitizeKind.
enum SanitizeOrdinal {
#define SANITIZER(NAME, ID) SO_##ID,
#define SANITIZER_GROUP(NAME, ID, ALIAS) SO_##ID##Group,
#include "clang/Basic/Sanitizers.def"
  SO_Count
};

/// Represents a set of sanitizer kinds. It is also used to define:
/// 1) set of sanitizers each sanitizer group expands into.
/// 2) set of sanitizers sharing a specific property (e.g.
///    all sanitizers with zero-base shadow).
enum SanitizeKind {
#define SANITIZER(NAME, ID) ID = 1 << SO_##ID,
#define SANITIZER_GROUP(NAME, ID, ALIAS)                                       \
ID = ALIAS, ID##Group = 1 << SO_##ID##Group,
#include "clang/Basic/Sanitizers.def"
  NeedsUbsanRt = Undefined | Integer,
  NotAllowedWithTrap = Vptr,
  RequiresPIE = Memory | DataFlow,
  NeedsUnwindTables = Address | Thread | Memory | DataFlow,
  SupportsCoverage = Address | Memory | Leak | Undefined | Integer,
  RecoverableByDefault = Undefined | Integer,
  Unrecoverable = Address | Unreachable | Return,
  LegacyFsanitizeRecoverMask = Undefined | Integer
};
}

/// Returns true if set of \p Sanitizers contain at least one sanitizer from
/// \p Kinds.
static bool hasOneOf(const clang::SanitizerSet &Sanitizers, unsigned Kinds) {
#define SANITIZER(NAME, ID)                                                    \
  if (Sanitizers.has(clang::SanitizerKind::ID) && (Kinds & ID))                \
    return true;
#include "clang/Basic/Sanitizers.def"
  return false;
}

/// Adds all sanitizers from \p Kinds to \p Sanitizers.
static void addAllOf(clang::SanitizerSet &Sanitizers, unsigned Kinds) {
#define SANITIZER(NAME, ID) \
  if (Kinds & ID) \
    Sanitizers.set(clang::SanitizerKind::ID, true);
#include "clang/Basic/Sanitizers.def"
}

static unsigned toSanitizeKind(clang::SanitizerKind K) {
#define SANITIZER(NAME, ID) \
  if (K == clang::SanitizerKind::ID) \
    return ID;
#include "clang/Basic/Sanitizers.def"
  llvm_unreachable("Invalid SanitizerKind!");
}

/// Parse a single value from a -fsanitize= or -fno-sanitize= value list.
/// Returns a member of the \c SanitizeKind enumeration, or \c 0
/// if \p Value is not known.
static unsigned parseValue(const char *Value);

/// Parse a -fsanitize= or -fno-sanitize= argument's values, diagnosing any
/// invalid components. Returns OR of members of \c SanitizeKind enumeration.
static unsigned parseArgValues(const Driver &D, const llvm::opt::Arg *A,
                               bool DiagnoseErrors);

/// Produce an argument string from ArgList \p Args, which shows how it
/// provides some sanitizer kind from \p Mask. For example, the argument list
/// "-fsanitize=thread,vptr -fsanitize=address" with mask \c NeedsUbsanRt
/// would produce "-fsanitize=vptr".
static std::string lastArgumentForMask(const Driver &D,
                                       const llvm::opt::ArgList &Args,
                                       unsigned Mask);

static std::string lastArgumentForKind(const Driver &D,
                                       const llvm::opt::ArgList &Args,
                                       clang::SanitizerKind K) {
  return lastArgumentForMask(D, Args, toSanitizeKind(K));
}

/// Produce an argument string from argument \p A, which shows how it provides
/// a value in \p Mask. For instance, the argument
/// "-fsanitize=address,alignment" with mask \c NeedsUbsanRt would produce
/// "-fsanitize=alignment".
static std::string describeSanitizeArg(const llvm::opt::Arg *A, unsigned Mask);

/// Produce a string containing comma-separated names of sanitizers in \p
/// Sanitizers set.
static std::string toString(const clang::SanitizerSet &Sanitizers);

/// For each sanitizer group bit set in \p Kinds, set the bits for sanitizers
/// this group enables.
static unsigned expandGroups(unsigned Kinds);

static unsigned getToolchainUnsupportedKinds(const ToolChain &TC) {
  bool IsFreeBSD = TC.getTriple().getOS() == llvm::Triple::FreeBSD;
  bool IsLinux = TC.getTriple().getOS() == llvm::Triple::Linux;
  bool IsX86 = TC.getTriple().getArch() == llvm::Triple::x86;
  bool IsX86_64 = TC.getTriple().getArch() == llvm::Triple::x86_64;

  unsigned Unsupported = 0;
  if (!(IsLinux && IsX86_64)) {
    Unsupported |= Memory | DataFlow;
  }
  if (!((IsLinux || IsFreeBSD) && IsX86_64)) {
    Unsupported |= Thread;
  }
  if (!(IsLinux && (IsX86 || IsX86_64))) {
    Unsupported |= Function;
  }
  return Unsupported;
}

bool SanitizerArgs::needsUbsanRt() const {
  return !UbsanTrapOnError && hasOneOf(Sanitizers, NeedsUbsanRt);
}

bool SanitizerArgs::requiresPIE() const {
  return AsanZeroBaseShadow || hasOneOf(Sanitizers, RequiresPIE);
}

bool SanitizerArgs::needsUnwindTables() const {
  return hasOneOf(Sanitizers, NeedsUnwindTables);
}

d25 1
a25 2
  Sanitizers.clear();
  RecoverableSanitizers.clear();
a26 1
  SanitizeCoverage = 0;
a27 1
  AsanFieldPadding = 0;
d37 2
a43 2
  unsigned Kinds = 0;
  unsigned NotSupported = getToolchainUnsupportedKinds(TC);
d47 21
a67 18
    const auto *Arg = *I;
    if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
      Arg->claim();
      unsigned Add = parseArgValues(D, Arg, true);

      // Avoid diagnosing any sanitizer which is disabled later.
      Add &= ~AllRemove;
      // At this point we have not expanded groups, so any unsupported
      // sanitizers in Add are those which have been explicitly enabled.
      // Diagnose them.
      if (unsigned KindsToDiagnose = Add & NotSupported & ~DiagnosedKinds) {
        // Only diagnose the new kinds.
        std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
        D.Diag(diag::err_drv_unsupported_opt_for_target)
            << Desc << TC.getTriple().str();
        DiagnosedKinds |= KindsToDiagnose;
      }
      Add &= ~NotSupported;
d69 1
a69 13
      Add = expandGroups(Add);
      // Group expansion may have enabled a sanitizer which is disabled later.
      Add &= ~AllRemove;
      // Silently discard any unsupported sanitizers implicitly enabled through
      // group expansion.
      Add &= ~NotSupported;

      Kinds |= Add;
    } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
      Arg->claim();
      unsigned Remove = parseArgValues(D, Arg, true);
      AllRemove |= expandGroups(Remove);
    }
a70 36
  addAllOf(Sanitizers, Kinds);

  // Parse -f(no-)?sanitize-recover flags.
  unsigned RecoverableKinds = RecoverableByDefault;
  unsigned DiagnosedUnrecoverableKinds = 0;
  for (const auto *Arg : Args) {
    if (Arg->getOption().matches(options::OPT_fsanitize_recover)) {
      // FIXME: Add deprecation notice, and then remove this flag.
      RecoverableKinds |= expandGroups(LegacyFsanitizeRecoverMask);
      Arg->claim();
    } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover)) {
      // FIXME: Add deprecation notice, and then remove this flag.
      RecoverableKinds &= ~expandGroups(LegacyFsanitizeRecoverMask);
      Arg->claim();
    } else if (Arg->getOption().matches(options::OPT_fsanitize_recover_EQ)) {
      unsigned Add = parseArgValues(D, Arg, true);
      // Report error if user explicitly tries to recover from unrecoverable
      // sanitizer.
      if (unsigned KindsToDiagnose =
              Add & Unrecoverable & ~DiagnosedUnrecoverableKinds) {
        SanitizerSet SetToDiagnose;
        addAllOf(SetToDiagnose, KindsToDiagnose);
        D.Diag(diag::err_drv_unsupported_option_argument)
            << Arg->getOption().getName() << toString(SetToDiagnose);
        DiagnosedUnrecoverableKinds |= KindsToDiagnose;
      }
      RecoverableKinds |= expandGroups(Add);
      Arg->claim();
    } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover_EQ)) {
      RecoverableKinds &= ~expandGroups(parseArgValues(D, Arg, true));
      Arg->claim();
    }
  }
  RecoverableKinds &= Kinds;
  RecoverableKinds &= ~Unrecoverable;
  addAllOf(RecoverableSanitizers, RecoverableKinds);
d77 3
a79 3
  if (UbsanTrapOnError && hasOneOf(Sanitizers, NotAllowedWithTrap)) {
    D.Diag(clang::diag::err_drv_argument_not_allowed_with)
      << lastArgumentForMask(D, Args, NotAllowedWithTrap)
d83 5
a87 5
  // Check for incompatible sanitizers.
  bool NeedsAsan = Sanitizers.has(SanitizerKind::Address);
  bool NeedsTsan = Sanitizers.has(SanitizerKind::Thread);
  bool NeedsMsan = Sanitizers.has(SanitizerKind::Memory);
  bool NeedsLsan = Sanitizers.has(SanitizerKind::Leak);
d89 3
a91 3
    D.Diag(clang::diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, SanitizerKind::Address)
      << lastArgumentForKind(D, Args, SanitizerKind::Thread);
d93 3
a95 3
    D.Diag(clang::diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, SanitizerKind::Address)
      << lastArgumentForKind(D, Args, SanitizerKind::Memory);
d97 3
a99 3
    D.Diag(clang::diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, SanitizerKind::Thread)
      << lastArgumentForKind(D, Args, SanitizerKind::Memory);
d101 3
a103 3
    D.Diag(clang::diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, SanitizerKind::Leak)
      << lastArgumentForKind(D, Args, SanitizerKind::Thread);
d105 3
a107 3
    D.Diag(clang::diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, SanitizerKind::Leak)
      << lastArgumentForKind(D, Args, SanitizerKind::Memory);
d124 1
a124 1
          D.Diag(clang::diag::err_drv_malformed_sanitizer_blacklist) << BLError;
d128 1
a128 1
        D.Diag(clang::diag::err_drv_no_such_file) << BLPath;
d135 2
a136 1
    if (getDefaultBlacklist(D, BLPath) && llvm::sys::fs::exists(BLPath))
d155 1
a155 1
          D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
a160 11
  // Parse -fsanitize-coverage=N. Currently one of asan/msan/lsan is required.
  if (hasOneOf(Sanitizers, SupportsCoverage)) {
    if (Arg *A = Args.getLastArg(options::OPT_fsanitize_coverage)) {
      StringRef S = A->getValue();
      // Legal values are 0..4.
      if (S.getAsInteger(0, SanitizeCoverage) || SanitizeCoverage < 0 ||
          SanitizeCoverage > 4)
        D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
    }
  }

a166 24
    if (Arg *A =
            Args.getLastArg(options::OPT_fsanitize_address_field_padding)) {
        StringRef S = A->getValue();
        // Legal values are 0 and 1, 2, but in future we may add more levels.
        if (S.getAsInteger(0, AsanFieldPadding) || AsanFieldPadding < 0 ||
            AsanFieldPadding > 2) {
          D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
        }
    }

    if (Arg *WindowsDebugRTArg =
            Args.getLastArg(options::OPT__SLASH_MTd, options::OPT__SLASH_MT,
                            options::OPT__SLASH_MDd, options::OPT__SLASH_MD,
                            options::OPT__SLASH_LDd, options::OPT__SLASH_LD)) {
      switch (WindowsDebugRTArg->getOption().getID()) {
      case options::OPT__SLASH_MTd:
      case options::OPT__SLASH_MDd:
      case options::OPT__SLASH_LDd:
        D.Diag(clang::diag::err_drv_argument_not_allowed_with)
            << WindowsDebugRTArg->getAsString(Args)
            << lastArgumentForKind(D, Args, SanitizerKind::Address);
        D.Diag(clang::diag::note_drv_address_sanitizer_debug_runtime);
      }
    }
a173 12
static std::string toString(const clang::SanitizerSet &Sanitizers) {
  std::string Res;
#define SANITIZER(NAME, ID)                                                    \
  if (Sanitizers.has(clang::SanitizerKind::ID)) {                              \
    if (!Res.empty())                                                          \
      Res += ",";                                                              \
    Res += NAME;                                                               \
  }
#include "clang/Basic/Sanitizers.def"
  return Res;
}

d176 1
a176 1
  if (Sanitizers.empty())
d178 7
a184 9
  CmdArgs.push_back(Args.MakeArgString("-fsanitize=" + toString(Sanitizers)));

  if (!RecoverableSanitizers.empty())
    CmdArgs.push_back(Args.MakeArgString("-fsanitize-recover=" +
                                         toString(RecoverableSanitizers)));

  if (UbsanTrapOnError)
    CmdArgs.push_back("-fsanitize-undefined-trap-on-error");

d194 1
a194 6
  if (AsanFieldPadding)
    CmdArgs.push_back(Args.MakeArgString("-fsanitize-address-field-padding=" +
                                         llvm::utostr(AsanFieldPadding)));
  if (SanitizeCoverage)
    CmdArgs.push_back(Args.MakeArgString("-fsanitize-coverage=" +
                                         llvm::utostr(SanitizeCoverage)));
d196 1
a196 1
  if (Sanitizers.has(SanitizerKind::Memory))
d200 1
a200 21
bool SanitizerArgs::getDefaultBlacklist(const Driver &D, std::string &BLPath) {
  const char *BlacklistFile = nullptr;
  if (Sanitizers.has(SanitizerKind::Address))
    BlacklistFile = "asan_blacklist.txt";
  else if (Sanitizers.has(SanitizerKind::Memory))
    BlacklistFile = "msan_blacklist.txt";
  else if (Sanitizers.has(SanitizerKind::Thread))
    BlacklistFile = "tsan_blacklist.txt";
  else if (Sanitizers.has(SanitizerKind::DataFlow))
    BlacklistFile = "dfsan_abilist.txt";

  if (BlacklistFile) {
    SmallString<64> Path(D.ResourceDir);
    llvm::sys::path::append(Path, BlacklistFile);
    BLPath = Path.str();
    return true;
  }
  return false;
}

unsigned parseValue(const char *Value) {
d209 1
a209 1
unsigned expandGroups(unsigned Kinds) {
d216 44
a259 8
unsigned parseArgValues(const Driver &D, const llvm::opt::Arg *A,
                        bool DiagnoseErrors) {
  assert((A->getOption().matches(options::OPT_fsanitize_EQ) ||
          A->getOption().matches(options::OPT_fno_sanitize_EQ) ||
          A->getOption().matches(options::OPT_fsanitize_recover_EQ) ||
          A->getOption().matches(options::OPT_fno_sanitize_recover_EQ)) &&
         "Invalid argument in parseArgValues!");
  unsigned Kinds = 0;
d261 8
a268 8
    const char *Value = A->getValue(I);
    unsigned Kind;
    // Special case: don't accept -fsanitize=all.
    if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
        0 == strcmp("all", Value))
      Kind = 0;
    else
      Kind = parseValue(Value);
d270 12
a281 5
    if (Kind)
      Kinds |= Kind;
    else if (DiagnoseErrors)
      D.Diag(clang::diag::err_drv_unsupported_option_argument)
          << A->getOption().getName() << Value;
d283 1
a283 1
  return Kinds;
d286 3
a288 2
std::string lastArgumentForMask(const Driver &D, const llvm::opt::ArgList &Args,
                                unsigned Mask) {
d292 5
a296 9
    const auto *Arg = *I;
    if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
      unsigned AddKinds = expandGroups(parseArgValues(D, Arg, false));
      if (AddKinds & Mask)
        return describeSanitizeArg(Arg, Mask);
    } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
      unsigned RemoveKinds = expandGroups(parseArgValues(D, Arg, false));
      Mask &= ~RemoveKinds;
    }
d301 5
a305 3
std::string describeSanitizeArg(const llvm::opt::Arg *A, unsigned Mask) {
  assert(A->getOption().matches(options::OPT_fsanitize_EQ)
         && "Invalid argument in describeSanitizerArg!");
d309 1
a309 1
    if (expandGroups(parseValue(A->getValue(I))) & Mask) {
d319 21
@


1.1.1.7
log
@Import Clang 3.6RC1 r227398.
@
text
@a23 125
namespace {
/// Assign ordinals to possible values of -fsanitize= flag.
/// We use the ordinal values as bit positions within \c SanitizeKind.
enum SanitizeOrdinal {
#define SANITIZER(NAME, ID) SO_##ID,
#define SANITIZER_GROUP(NAME, ID, ALIAS) SO_##ID##Group,
#include "clang/Basic/Sanitizers.def"
  SO_Count
};

/// Represents a set of sanitizer kinds. It is also used to define:
/// 1) set of sanitizers each sanitizer group expands into.
/// 2) set of sanitizers sharing a specific property (e.g.
///    all sanitizers with zero-base shadow).
enum SanitizeKind {
#define SANITIZER(NAME, ID) ID = 1 << SO_##ID,
#define SANITIZER_GROUP(NAME, ID, ALIAS)                                       \
ID = ALIAS, ID##Group = 1 << SO_##ID##Group,
#include "clang/Basic/Sanitizers.def"
  NeedsUbsanRt = Undefined | Integer,
  NotAllowedWithTrap = Vptr,
  RequiresPIE = Memory | DataFlow,
  NeedsUnwindTables = Address | Thread | Memory | DataFlow,
  SupportsCoverage = Address | Memory | Leak | Undefined | Integer,
  RecoverableByDefault = Undefined | Integer,
  Unrecoverable = Address | Unreachable | Return,
  LegacyFsanitizeRecoverMask = Undefined | Integer
};
}

/// Returns true if set of \p Sanitizers contain at least one sanitizer from
/// \p Kinds.
static bool hasOneOf(const clang::SanitizerSet &Sanitizers, unsigned Kinds) {
#define SANITIZER(NAME, ID)                                                    \
  if (Sanitizers.has(clang::SanitizerKind::ID) && (Kinds & ID))                \
    return true;
#include "clang/Basic/Sanitizers.def"
  return false;
}

/// Adds all sanitizers from \p Kinds to \p Sanitizers.
static void addAllOf(clang::SanitizerSet &Sanitizers, unsigned Kinds) {
#define SANITIZER(NAME, ID) \
  if (Kinds & ID) \
    Sanitizers.set(clang::SanitizerKind::ID, true);
#include "clang/Basic/Sanitizers.def"
}

static unsigned toSanitizeKind(clang::SanitizerKind K) {
#define SANITIZER(NAME, ID) \
  if (K == clang::SanitizerKind::ID) \
    return ID;
#include "clang/Basic/Sanitizers.def"
  llvm_unreachable("Invalid SanitizerKind!");
}

/// Parse a single value from a -fsanitize= or -fno-sanitize= value list.
/// Returns a member of the \c SanitizeKind enumeration, or \c 0
/// if \p Value is not known.
static unsigned parseValue(const char *Value);

/// Parse a -fsanitize= or -fno-sanitize= argument's values, diagnosing any
/// invalid components. Returns OR of members of \c SanitizeKind enumeration.
static unsigned parseArgValues(const Driver &D, const llvm::opt::Arg *A,
                               bool DiagnoseErrors);

/// Produce an argument string from ArgList \p Args, which shows how it
/// provides some sanitizer kind from \p Mask. For example, the argument list
/// "-fsanitize=thread,vptr -fsanitize=address" with mask \c NeedsUbsanRt
/// would produce "-fsanitize=vptr".
static std::string lastArgumentForMask(const Driver &D,
                                       const llvm::opt::ArgList &Args,
                                       unsigned Mask);

static std::string lastArgumentForKind(const Driver &D,
                                       const llvm::opt::ArgList &Args,
                                       clang::SanitizerKind K) {
  return lastArgumentForMask(D, Args, toSanitizeKind(K));
}

/// Produce an argument string from argument \p A, which shows how it provides
/// a value in \p Mask. For instance, the argument
/// "-fsanitize=address,alignment" with mask \c NeedsUbsanRt would produce
/// "-fsanitize=alignment".
static std::string describeSanitizeArg(const llvm::opt::Arg *A, unsigned Mask);

/// Produce a string containing comma-separated names of sanitizers in \p
/// Sanitizers set.
static std::string toString(const clang::SanitizerSet &Sanitizers);

/// For each sanitizer group bit set in \p Kinds, set the bits for sanitizers
/// this group enables.
static unsigned expandGroups(unsigned Kinds);

static unsigned getToolchainUnsupportedKinds(const ToolChain &TC) {
  bool IsFreeBSD = TC.getTriple().getOS() == llvm::Triple::FreeBSD;
  bool IsLinux = TC.getTriple().getOS() == llvm::Triple::Linux;
  bool IsX86 = TC.getTriple().getArch() == llvm::Triple::x86;
  bool IsX86_64 = TC.getTriple().getArch() == llvm::Triple::x86_64;

  unsigned Unsupported = 0;
  if (!(IsLinux && IsX86_64)) {
    Unsupported |= Memory | DataFlow;
  }
  if (!((IsLinux || IsFreeBSD) && IsX86_64)) {
    Unsupported |= Thread;
  }
  if (!(IsLinux && (IsX86 || IsX86_64))) {
    Unsupported |= Function;
  }
  return Unsupported;
}

bool SanitizerArgs::needsUbsanRt() const {
  return !UbsanTrapOnError && hasOneOf(Sanitizers, NeedsUbsanRt);
}

bool SanitizerArgs::requiresPIE() const {
  return AsanZeroBaseShadow || hasOneOf(Sanitizers, RequiresPIE);
}

bool SanitizerArgs::needsUnwindTables() const {
  return hasOneOf(Sanitizers, NeedsUnwindTables);
}

d25 1
a25 2
  Sanitizers.clear();
  RecoverableSanitizers.clear();
a26 1
  SanitizeCoverage = 0;
a27 1
  AsanFieldPadding = 0;
d37 2
a43 2
  unsigned Kinds = 0;
  unsigned NotSupported = getToolchainUnsupportedKinds(TC);
d47 21
a67 18
    const auto *Arg = *I;
    if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
      Arg->claim();
      unsigned Add = parseArgValues(D, Arg, true);

      // Avoid diagnosing any sanitizer which is disabled later.
      Add &= ~AllRemove;
      // At this point we have not expanded groups, so any unsupported
      // sanitizers in Add are those which have been explicitly enabled.
      // Diagnose them.
      if (unsigned KindsToDiagnose = Add & NotSupported & ~DiagnosedKinds) {
        // Only diagnose the new kinds.
        std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
        D.Diag(diag::err_drv_unsupported_opt_for_target)
            << Desc << TC.getTriple().str();
        DiagnosedKinds |= KindsToDiagnose;
      }
      Add &= ~NotSupported;
d69 1
a69 13
      Add = expandGroups(Add);
      // Group expansion may have enabled a sanitizer which is disabled later.
      Add &= ~AllRemove;
      // Silently discard any unsupported sanitizers implicitly enabled through
      // group expansion.
      Add &= ~NotSupported;

      Kinds |= Add;
    } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
      Arg->claim();
      unsigned Remove = parseArgValues(D, Arg, true);
      AllRemove |= expandGroups(Remove);
    }
a70 36
  addAllOf(Sanitizers, Kinds);

  // Parse -f(no-)?sanitize-recover flags.
  unsigned RecoverableKinds = RecoverableByDefault;
  unsigned DiagnosedUnrecoverableKinds = 0;
  for (const auto *Arg : Args) {
    if (Arg->getOption().matches(options::OPT_fsanitize_recover)) {
      // FIXME: Add deprecation notice, and then remove this flag.
      RecoverableKinds |= expandGroups(LegacyFsanitizeRecoverMask);
      Arg->claim();
    } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover)) {
      // FIXME: Add deprecation notice, and then remove this flag.
      RecoverableKinds &= ~expandGroups(LegacyFsanitizeRecoverMask);
      Arg->claim();
    } else if (Arg->getOption().matches(options::OPT_fsanitize_recover_EQ)) {
      unsigned Add = parseArgValues(D, Arg, true);
      // Report error if user explicitly tries to recover from unrecoverable
      // sanitizer.
      if (unsigned KindsToDiagnose =
              Add & Unrecoverable & ~DiagnosedUnrecoverableKinds) {
        SanitizerSet SetToDiagnose;
        addAllOf(SetToDiagnose, KindsToDiagnose);
        D.Diag(diag::err_drv_unsupported_option_argument)
            << Arg->getOption().getName() << toString(SetToDiagnose);
        DiagnosedUnrecoverableKinds |= KindsToDiagnose;
      }
      RecoverableKinds |= expandGroups(Add);
      Arg->claim();
    } else if (Arg->getOption().matches(options::OPT_fno_sanitize_recover_EQ)) {
      RecoverableKinds &= ~expandGroups(parseArgValues(D, Arg, true));
      Arg->claim();
    }
  }
  RecoverableKinds &= Kinds;
  RecoverableKinds &= ~Unrecoverable;
  addAllOf(RecoverableSanitizers, RecoverableKinds);
d77 3
a79 3
  if (UbsanTrapOnError && hasOneOf(Sanitizers, NotAllowedWithTrap)) {
    D.Diag(clang::diag::err_drv_argument_not_allowed_with)
      << lastArgumentForMask(D, Args, NotAllowedWithTrap)
d83 5
a87 5
  // Check for incompatible sanitizers.
  bool NeedsAsan = Sanitizers.has(SanitizerKind::Address);
  bool NeedsTsan = Sanitizers.has(SanitizerKind::Thread);
  bool NeedsMsan = Sanitizers.has(SanitizerKind::Memory);
  bool NeedsLsan = Sanitizers.has(SanitizerKind::Leak);
d89 3
a91 3
    D.Diag(clang::diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, SanitizerKind::Address)
      << lastArgumentForKind(D, Args, SanitizerKind::Thread);
d93 3
a95 3
    D.Diag(clang::diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, SanitizerKind::Address)
      << lastArgumentForKind(D, Args, SanitizerKind::Memory);
d97 3
a99 3
    D.Diag(clang::diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, SanitizerKind::Thread)
      << lastArgumentForKind(D, Args, SanitizerKind::Memory);
d101 3
a103 3
    D.Diag(clang::diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, SanitizerKind::Leak)
      << lastArgumentForKind(D, Args, SanitizerKind::Thread);
d105 3
a107 3
    D.Diag(clang::diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, SanitizerKind::Leak)
      << lastArgumentForKind(D, Args, SanitizerKind::Memory);
d124 1
a124 1
          D.Diag(clang::diag::err_drv_malformed_sanitizer_blacklist) << BLError;
d128 1
a128 1
        D.Diag(clang::diag::err_drv_no_such_file) << BLPath;
d135 2
a136 1
    if (getDefaultBlacklist(D, BLPath) && llvm::sys::fs::exists(BLPath))
d155 1
a155 1
          D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
a160 11
  // Parse -fsanitize-coverage=N. Currently one of asan/msan/lsan is required.
  if (hasOneOf(Sanitizers, SupportsCoverage)) {
    if (Arg *A = Args.getLastArg(options::OPT_fsanitize_coverage)) {
      StringRef S = A->getValue();
      // Legal values are 0..4.
      if (S.getAsInteger(0, SanitizeCoverage) || SanitizeCoverage < 0 ||
          SanitizeCoverage > 4)
        D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
    }
  }

a166 24
    if (Arg *A =
            Args.getLastArg(options::OPT_fsanitize_address_field_padding)) {
        StringRef S = A->getValue();
        // Legal values are 0 and 1, 2, but in future we may add more levels.
        if (S.getAsInteger(0, AsanFieldPadding) || AsanFieldPadding < 0 ||
            AsanFieldPadding > 2) {
          D.Diag(clang::diag::err_drv_invalid_value) << A->getAsString(Args) << S;
        }
    }

    if (Arg *WindowsDebugRTArg =
            Args.getLastArg(options::OPT__SLASH_MTd, options::OPT__SLASH_MT,
                            options::OPT__SLASH_MDd, options::OPT__SLASH_MD,
                            options::OPT__SLASH_LDd, options::OPT__SLASH_LD)) {
      switch (WindowsDebugRTArg->getOption().getID()) {
      case options::OPT__SLASH_MTd:
      case options::OPT__SLASH_MDd:
      case options::OPT__SLASH_LDd:
        D.Diag(clang::diag::err_drv_argument_not_allowed_with)
            << WindowsDebugRTArg->getAsString(Args)
            << lastArgumentForKind(D, Args, SanitizerKind::Address);
        D.Diag(clang::diag::note_drv_address_sanitizer_debug_runtime);
      }
    }
a173 12
static std::string toString(const clang::SanitizerSet &Sanitizers) {
  std::string Res;
#define SANITIZER(NAME, ID)                                                    \
  if (Sanitizers.has(clang::SanitizerKind::ID)) {                              \
    if (!Res.empty())                                                          \
      Res += ",";                                                              \
    Res += NAME;                                                               \
  }
#include "clang/Basic/Sanitizers.def"
  return Res;
}

d176 1
a176 1
  if (Sanitizers.empty())
d178 7
a184 9
  CmdArgs.push_back(Args.MakeArgString("-fsanitize=" + toString(Sanitizers)));

  if (!RecoverableSanitizers.empty())
    CmdArgs.push_back(Args.MakeArgString("-fsanitize-recover=" +
                                         toString(RecoverableSanitizers)));

  if (UbsanTrapOnError)
    CmdArgs.push_back("-fsanitize-undefined-trap-on-error");

d194 1
a194 6
  if (AsanFieldPadding)
    CmdArgs.push_back(Args.MakeArgString("-fsanitize-address-field-padding=" +
                                         llvm::utostr(AsanFieldPadding)));
  if (SanitizeCoverage)
    CmdArgs.push_back(Args.MakeArgString("-fsanitize-coverage=" +
                                         llvm::utostr(SanitizeCoverage)));
d196 1
a196 1
  if (Sanitizers.has(SanitizerKind::Memory))
d200 1
a200 21
bool SanitizerArgs::getDefaultBlacklist(const Driver &D, std::string &BLPath) {
  const char *BlacklistFile = nullptr;
  if (Sanitizers.has(SanitizerKind::Address))
    BlacklistFile = "asan_blacklist.txt";
  else if (Sanitizers.has(SanitizerKind::Memory))
    BlacklistFile = "msan_blacklist.txt";
  else if (Sanitizers.has(SanitizerKind::Thread))
    BlacklistFile = "tsan_blacklist.txt";
  else if (Sanitizers.has(SanitizerKind::DataFlow))
    BlacklistFile = "dfsan_abilist.txt";

  if (BlacklistFile) {
    SmallString<64> Path(D.ResourceDir);
    llvm::sys::path::append(Path, BlacklistFile);
    BLPath = Path.str();
    return true;
  }
  return false;
}

unsigned parseValue(const char *Value) {
d209 1
a209 1
unsigned expandGroups(unsigned Kinds) {
d216 44
a259 8
unsigned parseArgValues(const Driver &D, const llvm::opt::Arg *A,
                        bool DiagnoseErrors) {
  assert((A->getOption().matches(options::OPT_fsanitize_EQ) ||
          A->getOption().matches(options::OPT_fno_sanitize_EQ) ||
          A->getOption().matches(options::OPT_fsanitize_recover_EQ) ||
          A->getOption().matches(options::OPT_fno_sanitize_recover_EQ)) &&
         "Invalid argument in parseArgValues!");
  unsigned Kinds = 0;
d261 8
a268 8
    const char *Value = A->getValue(I);
    unsigned Kind;
    // Special case: don't accept -fsanitize=all.
    if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
        0 == strcmp("all", Value))
      Kind = 0;
    else
      Kind = parseValue(Value);
d270 12
a281 5
    if (Kind)
      Kinds |= Kind;
    else if (DiagnoseErrors)
      D.Diag(clang::diag::err_drv_unsupported_option_argument)
          << A->getOption().getName() << Value;
d283 1
a283 1
  return Kinds;
d286 3
a288 2
std::string lastArgumentForMask(const Driver &D, const llvm::opt::ArgList &Args,
                                unsigned Mask) {
d292 5
a296 9
    const auto *Arg = *I;
    if (Arg->getOption().matches(options::OPT_fsanitize_EQ)) {
      unsigned AddKinds = expandGroups(parseArgValues(D, Arg, false));
      if (AddKinds & Mask)
        return describeSanitizeArg(Arg, Mask);
    } else if (Arg->getOption().matches(options::OPT_fno_sanitize_EQ)) {
      unsigned RemoveKinds = expandGroups(parseArgValues(D, Arg, false));
      Mask &= ~RemoveKinds;
    }
d301 5
a305 3
std::string describeSanitizeArg(const llvm::opt::Arg *A, unsigned Mask) {
  assert(A->getOption().matches(options::OPT_fsanitize_EQ)
         && "Invalid argument in describeSanitizerArg!");
d309 1
a309 1
    if (expandGroups(parseValue(A->getValue(I))) & Mask) {
d319 21
@


1.1.1.8
log
@Import Clang 3.8.0rc3 r261930.
@
text
@a9 2
#include "Tools.h"
#include "clang/Basic/Sanitizers.h"
a20 2
using namespace clang;
using namespace clang::SanitizerKind;
d24 20
a43 3
enum : SanitizerMask {
  NeedsUbsanRt = Undefined | Integer | CFI,
  NeedsUbsanCxxRt = Vptr | CFI,
d45 1
a45 1
  RequiresPIE = DataFlow,
d47 1
a47 1
  SupportsCoverage = Address | Memory | Leak | Undefined | Integer | DataFlow,
d49 2
a50 6
  Unrecoverable = Unreachable | Return,
  LegacyFsanitizeRecoverMask = Undefined | Integer,
  NeedsLTO = CFI,
  TrappingSupported =
      (Undefined & ~Vptr) | UnsignedIntegerOverflow | LocalBounds | CFI,
  TrappingDefault = CFI,
d52 27
d80 4
a83 9
enum CoverageFeature {
  CoverageFunc = 1 << 0,
  CoverageBB = 1 << 1,
  CoverageEdge = 1 << 2,
  CoverageIndirCall = 1 << 3,
  CoverageTraceBB = 1 << 4,
  CoverageTraceCmp = 1 << 5,
  Coverage8bitCounters = 1 << 6,
};
d86 3
a88 7
/// invalid components. Returns a SanitizerMask.
static SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
                                    bool DiagnoseErrors);

/// Parse -f(no-)?sanitize-coverage= flag values, diagnosing any invalid
/// components. Returns OR of members of \c CoverageFeature enumeration.
static int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A);
d96 7
a102 1
                                       SanitizerMask Mask);
d108 1
a108 2
static std::string describeSanitizeArg(const llvm::opt::Arg *A,
                                       SanitizerMask Mask);
d114 16
a129 19
static bool getDefaultBlacklist(const Driver &D, SanitizerMask Kinds,
                                std::string &BLPath) {
  const char *BlacklistFile = nullptr;
  if (Kinds & Address)
    BlacklistFile = "asan_blacklist.txt";
  else if (Kinds & Memory)
    BlacklistFile = "msan_blacklist.txt";
  else if (Kinds & Thread)
    BlacklistFile = "tsan_blacklist.txt";
  else if (Kinds & DataFlow)
    BlacklistFile = "dfsan_abilist.txt";
  else if (Kinds & CFI)
    BlacklistFile = "cfi_blacklist.txt";

  if (BlacklistFile) {
    clang::SmallString<64> Path(D.ResourceDir);
    llvm::sys::path::append(Path, BlacklistFile);
    BLPath = Path.str();
    return true;
d131 2
a132 49
  return false;
}

/// Sets group bits for every group that has at least one representative already
/// enabled in \p Kinds.
static SanitizerMask setGroupBits(SanitizerMask Kinds) {
#define SANITIZER(NAME, ID)
#define SANITIZER_GROUP(NAME, ID, ALIAS)                                       \
  if (Kinds & SanitizerKind::ID)                                               \
    Kinds |= SanitizerKind::ID##Group;
#include "clang/Basic/Sanitizers.def"
  return Kinds;
}

static SanitizerMask parseSanitizeTrapArgs(const Driver &D,
                                           const llvm::opt::ArgList &Args) {
  SanitizerMask TrapRemove = 0; // During the loop below, the accumulated set of
                                // sanitizers disabled by the current sanitizer
                                // argument or any argument after it.
  SanitizerMask TrappingKinds = 0;
  SanitizerMask TrappingSupportedWithGroups = setGroupBits(TrappingSupported);

  for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
       I != E; ++I) {
    const auto *Arg = *I;
    if (Arg->getOption().matches(options::OPT_fsanitize_trap_EQ)) {
      Arg->claim();
      SanitizerMask Add = parseArgValues(D, Arg, true);
      Add &= ~TrapRemove;
      if (SanitizerMask InvalidValues = Add & ~TrappingSupportedWithGroups) {
        SanitizerSet S;
        S.Mask = InvalidValues;
        D.Diag(diag::err_drv_unsupported_option_argument) << "-fsanitize-trap"
                                                          << toString(S);
      }
      TrappingKinds |= expandSanitizerGroups(Add) & ~TrapRemove;
    } else if (Arg->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) {
      Arg->claim();
      TrapRemove |= expandSanitizerGroups(parseArgValues(D, Arg, true));
    } else if (Arg->getOption().matches(
                   options::OPT_fsanitize_undefined_trap_on_error)) {
      Arg->claim();
      TrappingKinds |=
          expandSanitizerGroups(UndefinedGroup & ~TrapRemove) & ~TrapRemove;
    } else if (Arg->getOption().matches(
                   options::OPT_fno_sanitize_undefined_trap_on_error)) {
      Arg->claim();
      TrapRemove |= expandSanitizerGroups(UndefinedGroup);
    }
d134 1
a134 5

  // Apply default trapping behavior.
  TrappingKinds |= TrappingDefault & ~TrapRemove;

  return TrappingKinds;
d138 1
a138 13
  return (Sanitizers.Mask & NeedsUbsanRt & ~TrapSanitizers.Mask) &&
         !Sanitizers.has(Address) &&
         !Sanitizers.has(Memory) &&
         !Sanitizers.has(Thread) &&
         !CfiCrossDso;
}

bool SanitizerArgs::needsCfiRt() const {
  return !(Sanitizers.Mask & CFI & ~TrapSanitizers.Mask) && CfiCrossDso;
}

bool SanitizerArgs::needsCfiDiagRt() const {
  return (Sanitizers.Mask & CFI & ~TrapSanitizers.Mask) && CfiCrossDso;
d142 1
a142 1
  return NeedPIE || (Sanitizers.Mask & RequiresPIE);
d146 1
a146 1
  return Sanitizers.Mask & NeedsUnwindTables;
d152 2
a153 4
  TrapSanitizers.clear();
  BlacklistFiles.clear();
  ExtraDeps.clear();
  CoverageFeatures = 0;
a154 2
  MsanUseAfterDtor = false;
  NeedPIE = false;
d156 2
a159 1
  CfiCrossDso = false;
d165 7
a171 14
  SanitizerMask AllRemove = 0;  // During the loop below, the accumulated set of
                                // sanitizers disabled by the current sanitizer
                                // argument or any argument after it.
  SanitizerMask AllAddedKinds = 0;  // Mask of all sanitizers ever enabled by
                                    // -fsanitize= flags (directly or via group
                                    // expansion), some of which may be disabled
                                    // later. Used to carefully prune
                                    // unused-argument diagnostics.
  SanitizerMask DiagnosedKinds = 0;  // All Kinds we have diagnosed up to now.
                                     // Used to deduplicate diagnostics.
  SanitizerMask Kinds = 0;
  const SanitizerMask Supported = setGroupBits(TC.getSupportedSanitizers());
  ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();

a172 3
  SanitizerMask TrappingKinds = parseSanitizeTrapArgs(D, Args);
  SanitizerMask InvalidTrappingKinds = TrappingKinds & NotAllowedWithTrap;

d178 1
a178 2
      SanitizerMask Add = parseArgValues(D, Arg, true);
      AllAddedKinds |= expandSanitizerGroups(Add);
d185 2
a186 9
      if (SanitizerMask KindsToDiagnose =
              Add & InvalidTrappingKinds & ~DiagnosedKinds) {
        std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
        D.Diag(diag::err_drv_argument_not_allowed_with)
            << Desc << "-fsanitize-trap=undefined";
        DiagnosedKinds |= KindsToDiagnose;
      }
      Add &= ~InvalidTrappingKinds;
      if (SanitizerMask KindsToDiagnose = Add & ~Supported & ~DiagnosedKinds) {
d192 1
a192 1
      Add &= Supported;
d194 1
a194 23
      // Test for -fno-rtti + explicit -fsanitizer=vptr before expanding groups
      // so we don't error out if -fno-rtti and -fsanitize=undefined were
      // passed.
      if (Add & Vptr &&
          (RTTIMode == ToolChain::RM_DisabledImplicitly ||
           RTTIMode == ToolChain::RM_DisabledExplicitly)) {
        if (RTTIMode == ToolChain::RM_DisabledImplicitly)
          // Warn about not having rtti enabled if the vptr sanitizer is
          // explicitly enabled
          D.Diag(diag::warn_drv_disabling_vptr_no_rtti_default);
        else {
          const llvm::opt::Arg *NoRTTIArg = TC.getRTTIArg();
          assert(NoRTTIArg &&
                 "RTTI disabled explicitly but we have no argument!");
          D.Diag(diag::err_drv_argument_not_allowed_with)
              << "-fsanitize=vptr" << NoRTTIArg->getAsString(Args);
        }

        // Take out the Vptr sanitizer from the enabled sanitizers
        AllRemove |= Vptr;
      }

      Add = expandSanitizerGroups(Add);
d199 1
a199 2
      Add &= ~InvalidTrappingKinds;
      Add &= Supported;
d204 2
a205 2
      SanitizerMask Remove = parseArgValues(D, Arg, true);
      AllRemove |= expandSanitizerGroups(Remove);
d208 1
a208 57

  // We disable the vptr sanitizer if it was enabled by group expansion but RTTI
  // is disabled.
  if ((Kinds & Vptr) &&
      (RTTIMode == ToolChain::RM_DisabledImplicitly ||
       RTTIMode == ToolChain::RM_DisabledExplicitly)) {
    Kinds &= ~Vptr;
  }

  // Check that LTO is enabled if we need it.
  if ((Kinds & NeedsLTO) && !D.isUsingLTO()) {
    D.Diag(diag::err_drv_argument_only_allowed_with)
        << lastArgumentForMask(D, Args, Kinds & NeedsLTO) << "-flto";
  }

  // Report error if there are non-trapping sanitizers that require
  // c++abi-specific  parts of UBSan runtime, and they are not provided by the
  // toolchain. We don't have a good way to check the latter, so we just
  // check if the toolchan supports vptr.
  if (~Supported & Vptr) {
    SanitizerMask KindsToDiagnose = Kinds & ~TrappingKinds & NeedsUbsanCxxRt;
    // The runtime library supports the Microsoft C++ ABI, but only well enough
    // for CFI. FIXME: Remove this once we support vptr on Windows.
    if (TC.getTriple().isOSWindows())
      KindsToDiagnose &= ~CFI;
    if (KindsToDiagnose) {
      SanitizerSet S;
      S.Mask = KindsToDiagnose;
      D.Diag(diag::err_drv_unsupported_opt_for_target)
          << ("-fno-sanitize-trap=" + toString(S)) << TC.getTriple().str();
      Kinds &= ~KindsToDiagnose;
    }
  }

  // Warn about incompatible groups of sanitizers.
  std::pair<SanitizerMask, SanitizerMask> IncompatibleGroups[] = {
      std::make_pair(Address, Thread), std::make_pair(Address, Memory),
      std::make_pair(Thread, Memory), std::make_pair(Leak, Thread),
      std::make_pair(Leak, Memory), std::make_pair(KernelAddress, Address),
      std::make_pair(KernelAddress, Leak),
      std::make_pair(KernelAddress, Thread),
      std::make_pair(KernelAddress, Memory)};
  for (auto G : IncompatibleGroups) {
    SanitizerMask Group = G.first;
    if (Kinds & Group) {
      if (SanitizerMask Incompatible = Kinds & G.second) {
        D.Diag(clang::diag::err_drv_argument_not_allowed_with)
            << lastArgumentForMask(D, Args, Group)
            << lastArgumentForMask(D, Args, Incompatible);
        Kinds &= ~Incompatible;
      }
    }
  }
  // FIXME: Currently -fsanitize=leak is silently ignored in the presence of
  // -fsanitize=address. Perhaps it should print an error, or perhaps
  // -f(-no)sanitize=leak should change whether leak detection is enabled by
  // default in ASan?
d211 2
a212 2
  SanitizerMask RecoverableKinds = RecoverableByDefault;
  SanitizerMask DiagnosedUnrecoverableKinds = 0;
a213 1
    const char *DeprecatedReplacement = nullptr;
d215 2
a216 2
      DeprecatedReplacement = "-fsanitize-recover=undefined,integer";
      RecoverableKinds |= expandSanitizerGroups(LegacyFsanitizeRecoverMask);
d219 2
a220 2
      DeprecatedReplacement = "-fno-sanitize-recover=undefined,integer";
      RecoverableKinds &= ~expandSanitizerGroups(LegacyFsanitizeRecoverMask);
d223 1
a223 1
      SanitizerMask Add = parseArgValues(D, Arg, true);
d226 1
a226 1
      if (SanitizerMask KindsToDiagnose =
d229 1
a229 1
        SetToDiagnose.Mask |= KindsToDiagnose;
d234 1
a234 1
      RecoverableKinds |= expandSanitizerGroups(Add);
d237 1
a237 1
      RecoverableKinds &= ~expandSanitizerGroups(parseArgValues(D, Arg, true));
a239 4
    if (DeprecatedReplacement) {
      D.Diag(diag::warn_drv_deprecated_arg) << Arg->getAsString(Args)
                                            << DeprecatedReplacement;
    }
d243 1
d245 3
a247 1
  TrappingKinds &= Kinds;
d249 5
a253 6
  // Setup blacklist files.
  // Add default blacklist from resource directory.
  {
    std::string BLPath;
    if (getDefaultBlacklist(D, Kinds, BLPath) && llvm::sys::fs::exists(BLPath))
      BlacklistFiles.push_back(BLPath);
d255 31
d287 4
a290 4
  for (const auto *Arg : Args) {
    if (Arg->getOption().matches(options::OPT_fsanitize_blacklist)) {
      Arg->claim();
      std::string BLPath = Arg->getValue();
d292 9
a300 3
        BlacklistFiles.push_back(BLPath);
        ExtraDeps.push_back(BLPath);
      } else
d302 1
a302 5

    } else if (Arg->getOption().matches(options::OPT_fno_sanitize_blacklist)) {
      Arg->claim();
      BlacklistFiles.clear();
      ExtraDeps.clear();
d304 6
a309 8
  }
  // Validate blacklists format.
  {
    std::string BLError;
    std::unique_ptr<llvm::SpecialCaseList> SCL(
        llvm::SpecialCaseList::create(BlacklistFiles, BLError));
    if (!SCL.get())
      D.Diag(clang::diag::err_drv_malformed_sanitizer_blacklist) << BLError;
d313 1
a313 1
  if (AllAddedKinds & Memory) {
d319 1
a319 1
        MsanTrackOrigins = 2;
d331 10
a340 50
    MsanUseAfterDtor =
        Args.hasArg(options::OPT_fsanitize_memory_use_after_dtor);
    NeedPIE |= !(TC.getTriple().isOSLinux() &&
                 TC.getTriple().getArch() == llvm::Triple::x86_64);
  }

  if (AllAddedKinds & CFI) {
    CfiCrossDso = Args.hasFlag(options::OPT_fsanitize_cfi_cross_dso,
                               options::OPT_fno_sanitize_cfi_cross_dso, false);
    // Without PIE, external function address may resolve to a PLT record, which
    // can not be verified by the target module.
    NeedPIE |= CfiCrossDso;
  }

  // Parse -f(no-)?sanitize-coverage flags if coverage is supported by the
  // enabled sanitizers.
  if (AllAddedKinds & SupportsCoverage) {
    for (const auto *Arg : Args) {
      if (Arg->getOption().matches(options::OPT_fsanitize_coverage)) {
        Arg->claim();
        int LegacySanitizeCoverage;
        if (Arg->getNumValues() == 1 &&
            !StringRef(Arg->getValue(0))
                 .getAsInteger(0, LegacySanitizeCoverage) &&
            LegacySanitizeCoverage >= 0 && LegacySanitizeCoverage <= 4) {
          // TODO: Add deprecation notice for this form.
          switch (LegacySanitizeCoverage) {
          case 0:
            CoverageFeatures = 0;
            break;
          case 1:
            CoverageFeatures = CoverageFunc;
            break;
          case 2:
            CoverageFeatures = CoverageBB;
            break;
          case 3:
            CoverageFeatures = CoverageEdge;
            break;
          case 4:
            CoverageFeatures = CoverageEdge | CoverageIndirCall;
            break;
          }
          continue;
        }
        CoverageFeatures |= parseCoverageFeatures(D, Arg);
      } else if (Arg->getOption().matches(options::OPT_fno_sanitize_coverage)) {
        Arg->claim();
        CoverageFeatures &= ~parseCoverageFeatures(D, Arg);
      }
a342 26
  // Choose at most one coverage type: function, bb, or edge.
  if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageBB))
    D.Diag(clang::diag::err_drv_argument_not_allowed_with)
        << "-fsanitize-coverage=func"
        << "-fsanitize-coverage=bb";
  if ((CoverageFeatures & CoverageFunc) && (CoverageFeatures & CoverageEdge))
    D.Diag(clang::diag::err_drv_argument_not_allowed_with)
        << "-fsanitize-coverage=func"
        << "-fsanitize-coverage=edge";
  if ((CoverageFeatures & CoverageBB) && (CoverageFeatures & CoverageEdge))
    D.Diag(clang::diag::err_drv_argument_not_allowed_with)
        << "-fsanitize-coverage=bb"
        << "-fsanitize-coverage=edge";
  // Basic block tracing and 8-bit counters require some type of coverage
  // enabled.
  int CoverageTypes = CoverageFunc | CoverageBB | CoverageEdge;
  if ((CoverageFeatures & CoverageTraceBB) &&
      !(CoverageFeatures & CoverageTypes))
    D.Diag(clang::diag::err_drv_argument_only_allowed_with)
        << "-fsanitize-coverage=trace-bb"
        << "-fsanitize-coverage=(func|bb|edge)";
  if ((CoverageFeatures & Coverage8bitCounters) &&
      !(CoverageFeatures & CoverageTypes))
    D.Diag(clang::diag::err_drv_argument_only_allowed_with)
        << "-fsanitize-coverage=8bit-counters"
        << "-fsanitize-coverage=(func|bb|edge)";
d344 1
a344 1
  if (AllAddedKinds & Address) {
d346 4
a349 2
        Args.hasArg(options::OPT_shared_libasan) || TC.getTriple().isAndroid();
    NeedPIE |= TC.getTriple().isAndroid();
d370 1
a370 1
            << lastArgumentForMask(D, Args, Address);
a378 5

  // Finally, initialize the set of available and recoverable sanitizers.
  Sanitizers.Mask |= Kinds;
  RecoverableSanitizers.Mask |= RecoverableKinds;
  TrapSanitizers.Mask |= TrappingKinds;
d384 1
a384 1
  if (Sanitizers.has(ID)) {                                                    \
d393 2
a394 3
void SanitizerArgs::addArgs(const ToolChain &TC, const llvm::opt::ArgList &Args,
                            llvm::opt::ArgStringList &CmdArgs,
                            types::ID InputType) const {
d403 2
a404 3
  if (!TrapSanitizers.empty())
    CmdArgs.push_back(
        Args.MakeArgString("-fsanitize-trap=" + toString(TrapSanitizers)));
d406 1
a406 1
  for (const auto &BLPath : BlacklistFiles) {
d408 1
a408 1
    BlacklistOpt += BLPath;
a410 5
  for (const auto &Dep : ExtraDeps) {
    SmallString<64> ExtraDepOpt("-fdepfile-entry=");
    ExtraDepOpt += Dep;
    CmdArgs.push_back(Args.MakeArgString(ExtraDepOpt));
  }
a414 7

  if (MsanUseAfterDtor)
    CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-use-after-dtor"));

  if (CfiCrossDso)
    CmdArgs.push_back(Args.MakeArgString("-fsanitize-cfi-cross-dso"));

d418 24
a441 12
  // Translate available CoverageFeatures to corresponding clang-cc1 flags.
  std::pair<int, const char *> CoverageFlags[] = {
    std::make_pair(CoverageFunc, "-fsanitize-coverage-type=1"),
    std::make_pair(CoverageBB, "-fsanitize-coverage-type=2"),
    std::make_pair(CoverageEdge, "-fsanitize-coverage-type=3"),
    std::make_pair(CoverageIndirCall, "-fsanitize-coverage-indirect-calls"),
    std::make_pair(CoverageTraceBB, "-fsanitize-coverage-trace-bb"),
    std::make_pair(CoverageTraceCmp, "-fsanitize-coverage-trace-cmp"),
    std::make_pair(Coverage8bitCounters, "-fsanitize-coverage-8bit-counters")};
  for (auto F : CoverageFlags) {
    if (CoverageFeatures & F.first)
      CmdArgs.push_back(Args.MakeArgString(F.second));
d443 2
d446 8
d455 5
a459 17
  // MSan: Workaround for PR16386.
  // ASan: This is mainly to help LSan with cases such as
  // https://code.google.com/p/address-sanitizer/issues/detail?id=373
  // We can't make this conditional on -fsanitize=leak, as that flag shouldn't
  // affect compilation.
  if (Sanitizers.has(Memory) || Sanitizers.has(Address))
    CmdArgs.push_back(Args.MakeArgString("-fno-assume-sane-operator-new"));

  if (TC.getTriple().isOSWindows() && needsUbsanRt()) {
    // Instruct the code generator to embed linker directives in the object file
    // that cause the required runtime libraries to be linked.
    CmdArgs.push_back(Args.MakeArgString(
        "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone")));
    if (types::isCXX(InputType))
      CmdArgs.push_back(Args.MakeArgString(
          "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone_cxx")));
  }
d462 2
a463 2
SanitizerMask parseArgValues(const Driver &D, const llvm::opt::Arg *A,
                             bool DiagnoseErrors) {
d467 1
a467 3
          A->getOption().matches(options::OPT_fno_sanitize_recover_EQ) ||
          A->getOption().matches(options::OPT_fsanitize_trap_EQ) ||
          A->getOption().matches(options::OPT_fno_sanitize_trap_EQ)) &&
d469 4
a472 4
  SanitizerMask Kinds = 0;
  for (int i = 0, n = A->getNumValues(); i != n; ++i) {
    const char *Value = A->getValue(i);
    SanitizerMask Kind;
d478 1
a478 1
      Kind = parseSanitizerValue(Value, /*AllowGroups=*/true);
a488 23
int parseCoverageFeatures(const Driver &D, const llvm::opt::Arg *A) {
  assert(A->getOption().matches(options::OPT_fsanitize_coverage) ||
         A->getOption().matches(options::OPT_fno_sanitize_coverage));
  int Features = 0;
  for (int i = 0, n = A->getNumValues(); i != n; ++i) {
    const char *Value = A->getValue(i);
    int F = llvm::StringSwitch<int>(Value)
        .Case("func", CoverageFunc)
        .Case("bb", CoverageBB)
        .Case("edge", CoverageEdge)
        .Case("indirect-calls", CoverageIndirCall)
        .Case("trace-bb", CoverageTraceBB)
        .Case("trace-cmp", CoverageTraceCmp)
        .Case("8bit-counters", Coverage8bitCounters)
        .Default(0);
    if (F == 0)
      D.Diag(clang::diag::err_drv_unsupported_option_argument)
          << A->getOption().getName() << Value;
    Features |= F;
  }
  return Features;
}

d490 1
a490 1
                                SanitizerMask Mask) {
d496 1
a496 2
      SanitizerMask AddKinds =
          expandSanitizerGroups(parseArgValues(D, Arg, false));
d500 1
a500 2
      SanitizerMask RemoveKinds =
          expandSanitizerGroups(parseArgValues(D, Arg, false));
d507 1
a507 1
std::string describeSanitizeArg(const llvm::opt::Arg *A, SanitizerMask Mask) {
d512 2
a513 4
  for (int i = 0, n = A->getNumValues(); i != n; ++i) {
    if (expandSanitizerGroups(
            parseSanitizerValue(A->getValue(i), /*AllowGroups=*/true)) &
        Mask) {
d516 1
a516 1
      Sanitizers += A->getValue(i);
@


1.1.1.8.2.1
log
@Sync with HEAD
@
text
@a41 1
  CFIClasses = CFIVCall | CFINVCall | CFIDerivedCast | CFIUnrelatedCast,
d51 1
a51 5
  CoverageTraceDiv = 1 << 6,
  CoverageTraceGep = 1 << 7,
  Coverage8bitCounters = 1 << 8,
  CoverageTracePC = 1 << 9,
  CoverageTracePCGuard = 1 << 10,
d160 5
a164 5
  return ((Sanitizers.Mask & NeedsUbsanRt & ~TrapSanitizers.Mask) ||
          CoverageFeatures) &&
         !Sanitizers.has(Address) && !Sanitizers.has(Memory) &&
         !Sanitizers.has(Thread) && !Sanitizers.has(DataFlow) && 
         !Sanitizers.has(Leak) && !CfiCrossDso;
d183 16
d201 1
a286 3
  // Enable toolchain specific default sanitizers if not explicitly disabled.
  Kinds |= TC.getDefaultSanitizers() & ~AllRemove;

d327 1
a327 6
      std::make_pair(KernelAddress, Memory),
      std::make_pair(Efficiency, Address),
      std::make_pair(Efficiency, Leak),
      std::make_pair(Efficiency, Thread),
      std::make_pair(Efficiency, Memory),
      std::make_pair(Efficiency, KernelAddress)};
d350 1
a350 2
      DeprecatedReplacement =
          "-fsanitize-recover=undefined,integer' or '-fsanitize-recover=all";
d354 1
a354 2
      DeprecatedReplacement = "-fno-sanitize-recover=undefined,integer' or "
                              "'-fno-sanitize-recover=all";
a442 12
  if (AllAddedKinds & Thread) {
    TsanMemoryAccess = Args.hasFlag(options::OPT_fsanitize_thread_memory_access,
                                    options::OPT_fno_sanitize_thread_memory_access,
                                    TsanMemoryAccess);
    TsanFuncEntryExit = Args.hasFlag(options::OPT_fsanitize_thread_func_entry_exit,
                                     options::OPT_fno_sanitize_thread_func_entry_exit,
                                     TsanFuncEntryExit);
    TsanAtomics = Args.hasFlag(options::OPT_fsanitize_thread_atomics,
                               options::OPT_fno_sanitize_thread_atomics,
                               TsanAtomics);
  }

a450 3
  Stats = Args.hasFlag(options::OPT_fsanitize_stats,
                       options::OPT_fno_sanitize_stats, false);

d453 28
a480 33
  for (const auto *Arg : Args) {
    if (Arg->getOption().matches(options::OPT_fsanitize_coverage)) {
      int LegacySanitizeCoverage;
      if (Arg->getNumValues() == 1 &&
          !StringRef(Arg->getValue(0))
               .getAsInteger(0, LegacySanitizeCoverage) &&
          LegacySanitizeCoverage >= 0 && LegacySanitizeCoverage <= 4) {
        switch (LegacySanitizeCoverage) {
        case 0:
          CoverageFeatures = 0;
          Arg->claim();
          break;
        case 1:
          D.Diag(diag::warn_drv_deprecated_arg) << Arg->getAsString(Args)
                                                << "-fsanitize-coverage=func";
          CoverageFeatures = CoverageFunc;
          break;
        case 2:
          D.Diag(diag::warn_drv_deprecated_arg) << Arg->getAsString(Args)
                                                << "-fsanitize-coverage=bb";
          CoverageFeatures = CoverageBB;
          break;
        case 3:
          D.Diag(diag::warn_drv_deprecated_arg) << Arg->getAsString(Args)
                                                << "-fsanitize-coverage=edge";
          CoverageFeatures = CoverageEdge;
          break;
        case 4:
          D.Diag(diag::warn_drv_deprecated_arg)
              << Arg->getAsString(Args)
              << "-fsanitize-coverage=edge,indirect-calls";
          CoverageFeatures = CoverageEdge | CoverageIndirCall;
          break;
d482 2
a483 7
        continue;
      }
      CoverageFeatures |= parseCoverageFeatures(D, Arg);

      // Disable coverage and not claim the flags if there is at least one
      // non-supporting sanitizer.
      if (!(AllAddedKinds & ~setGroupBits(SupportsCoverage))) {
d485 1
a485 2
      } else {
        CoverageFeatures = 0;
a486 3
    } else if (Arg->getOption().matches(options::OPT_fno_sanitize_coverage)) {
      Arg->claim();
      CoverageFeatures &= ~parseCoverageFeatures(D, Arg);
a514 4
  // trace-pc w/o func/bb/edge implies edge.
  if ((CoverageFeatures & (CoverageTracePC | CoverageTracePCGuard)) &&
      !(CoverageFeatures & CoverageTypes))
    CoverageFeatures |= CoverageEdge;
a543 7

    if (Arg *A = Args.getLastArg(
            options::OPT_fsanitize_address_use_after_scope,
            options::OPT_fno_sanitize_address_use_after_scope)) {
      AsanUseAfterScope = A->getOption().getID() ==
                          options::OPT_fsanitize_address_use_after_scope;
    }
a567 14
static void addIncludeLinkerOption(const ToolChain &TC,
                                   const llvm::opt::ArgList &Args,
                                   llvm::opt::ArgStringList &CmdArgs,
                                   StringRef SymbolName) {
  SmallString<64> LinkerOptionFlag;
  LinkerOptionFlag = "--linker-option=/include:";
  if (TC.getTriple().getArch() == llvm::Triple::x86) {
    // Win32 mangles C function names with a '_' prefix.
    LinkerOptionFlag += '_';
  }
  LinkerOptionFlag += SymbolName;
  CmdArgs.push_back(Args.MakeArgString(LinkerOptionFlag));
}

a570 48
  // NVPTX doesn't currently support sanitizers.  Bailing out here means that
  // e.g. -fsanitize=address applies only to host code, which is what we want
  // for now.
  if (TC.getTriple().isNVPTX())
    return;

  // Translate available CoverageFeatures to corresponding clang-cc1 flags.
  // Do it even if Sanitizers.empty() since some forms of coverage don't require
  // sanitizers.
  std::pair<int, const char *> CoverageFlags[] = {
    std::make_pair(CoverageFunc, "-fsanitize-coverage-type=1"),
    std::make_pair(CoverageBB, "-fsanitize-coverage-type=2"),
    std::make_pair(CoverageEdge, "-fsanitize-coverage-type=3"),
    std::make_pair(CoverageIndirCall, "-fsanitize-coverage-indirect-calls"),
    std::make_pair(CoverageTraceBB, "-fsanitize-coverage-trace-bb"),
    std::make_pair(CoverageTraceCmp, "-fsanitize-coverage-trace-cmp"),
    std::make_pair(CoverageTraceDiv, "-fsanitize-coverage-trace-div"),
    std::make_pair(CoverageTraceGep, "-fsanitize-coverage-trace-gep"),
    std::make_pair(Coverage8bitCounters, "-fsanitize-coverage-8bit-counters"),
    std::make_pair(CoverageTracePC, "-fsanitize-coverage-trace-pc"),
    std::make_pair(CoverageTracePCGuard, "-fsanitize-coverage-trace-pc-guard")};
  for (auto F : CoverageFlags) {
    if (CoverageFeatures & F.first)
      CmdArgs.push_back(Args.MakeArgString(F.second));
  }

  if (TC.getTriple().isOSWindows() && needsUbsanRt()) {
    // Instruct the code generator to embed linker directives in the object file
    // that cause the required runtime libraries to be linked.
    CmdArgs.push_back(Args.MakeArgString(
        "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone")));
    if (types::isCXX(InputType))
      CmdArgs.push_back(Args.MakeArgString(
          "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone_cxx")));
  }
  if (TC.getTriple().isOSWindows() && needsStatsRt()) {
    CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
                                         TC.getCompilerRT(Args, "stats_client")));

    // The main executable must export the stats runtime.
    // FIXME: Only exporting from the main executable (e.g. based on whether the
    // translation unit defines main()) would save a little space, but having
    // multiple copies of the runtime shouldn't hurt.
    CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
                                         TC.getCompilerRT(Args, "stats")));
    addIncludeLinkerOption(TC, Args, CmdArgs, "__sanitizer_stats_register");
  }

a600 16
  // FIXME: Pass these parameters as function attributes, not as -llvm flags.
  if (!TsanMemoryAccess) {
    CmdArgs.push_back("-mllvm");
    CmdArgs.push_back("-tsan-instrument-memory-accesses=0");
    CmdArgs.push_back("-mllvm");
    CmdArgs.push_back("-tsan-instrument-memintrinsics=0");
  }
  if (!TsanFuncEntryExit) {
    CmdArgs.push_back("-mllvm");
    CmdArgs.push_back("-tsan-instrument-func-entry-exit=0");
  }
  if (!TsanAtomics) {
    CmdArgs.push_back("-mllvm");
    CmdArgs.push_back("-tsan-instrument-atomics=0");
  }

a603 3
  if (Stats)
    CmdArgs.push_back(Args.MakeArgString("-fsanitize-stats"));

d607 13
a620 2
  if (AsanUseAfterScope)
    CmdArgs.push_back(Args.MakeArgString("-fsanitize-address-use-after-scope"));
d630 8
a637 8
  // Require -fvisibility= flag on non-Windows when compiling if vptr CFI is
  // enabled.
  if (Sanitizers.hasOneOf(CFIClasses) && !TC.getTriple().isOSWindows() &&
      !Args.hasArg(options::OPT_fvisibility_EQ)) {
    TC.getDriver().Diag(clang::diag::err_drv_argument_only_allowed_with)
        << lastArgumentForMask(TC.getDriver(), Args,
                               Sanitizers.Mask & CFIClasses)
        << "-fvisibility=";
a657 4
    // Similarly, don't accept -fsanitize=efficiency-all.
    else if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
        0 == strcmp("efficiency-all", Value))
      Kind = 0;
a682 2
        .Case("trace-div", CoverageTraceDiv)
        .Case("trace-gep", CoverageTraceGep)
a683 2
        .Case("trace-pc", CoverageTracePC)
        .Case("trace-pc-guard", CoverageTracePCGuard)
@


1.1.1.9
log
@Import Clang pre-4.0.0 r291444.
@
text
@a41 1
  CFIClasses = CFIVCall | CFINVCall | CFIDerivedCast | CFIUnrelatedCast,
d51 1
a51 5
  CoverageTraceDiv = 1 << 6,
  CoverageTraceGep = 1 << 7,
  Coverage8bitCounters = 1 << 8,
  CoverageTracePC = 1 << 9,
  CoverageTracePCGuard = 1 << 10,
d160 5
a164 5
  return ((Sanitizers.Mask & NeedsUbsanRt & ~TrapSanitizers.Mask) ||
          CoverageFeatures) &&
         !Sanitizers.has(Address) && !Sanitizers.has(Memory) &&
         !Sanitizers.has(Thread) && !Sanitizers.has(DataFlow) && 
         !Sanitizers.has(Leak) && !CfiCrossDso;
d183 16
d201 1
a286 3
  // Enable toolchain specific default sanitizers if not explicitly disabled.
  Kinds |= TC.getDefaultSanitizers() & ~AllRemove;

d327 1
a327 6
      std::make_pair(KernelAddress, Memory),
      std::make_pair(Efficiency, Address),
      std::make_pair(Efficiency, Leak),
      std::make_pair(Efficiency, Thread),
      std::make_pair(Efficiency, Memory),
      std::make_pair(Efficiency, KernelAddress)};
d350 1
a350 2
      DeprecatedReplacement =
          "-fsanitize-recover=undefined,integer' or '-fsanitize-recover=all";
d354 1
a354 2
      DeprecatedReplacement = "-fno-sanitize-recover=undefined,integer' or "
                              "'-fno-sanitize-recover=all";
a442 12
  if (AllAddedKinds & Thread) {
    TsanMemoryAccess = Args.hasFlag(options::OPT_fsanitize_thread_memory_access,
                                    options::OPT_fno_sanitize_thread_memory_access,
                                    TsanMemoryAccess);
    TsanFuncEntryExit = Args.hasFlag(options::OPT_fsanitize_thread_func_entry_exit,
                                     options::OPT_fno_sanitize_thread_func_entry_exit,
                                     TsanFuncEntryExit);
    TsanAtomics = Args.hasFlag(options::OPT_fsanitize_thread_atomics,
                               options::OPT_fno_sanitize_thread_atomics,
                               TsanAtomics);
  }

a450 3
  Stats = Args.hasFlag(options::OPT_fsanitize_stats,
                       options::OPT_fno_sanitize_stats, false);

d453 28
a480 33
  for (const auto *Arg : Args) {
    if (Arg->getOption().matches(options::OPT_fsanitize_coverage)) {
      int LegacySanitizeCoverage;
      if (Arg->getNumValues() == 1 &&
          !StringRef(Arg->getValue(0))
               .getAsInteger(0, LegacySanitizeCoverage) &&
          LegacySanitizeCoverage >= 0 && LegacySanitizeCoverage <= 4) {
        switch (LegacySanitizeCoverage) {
        case 0:
          CoverageFeatures = 0;
          Arg->claim();
          break;
        case 1:
          D.Diag(diag::warn_drv_deprecated_arg) << Arg->getAsString(Args)
                                                << "-fsanitize-coverage=func";
          CoverageFeatures = CoverageFunc;
          break;
        case 2:
          D.Diag(diag::warn_drv_deprecated_arg) << Arg->getAsString(Args)
                                                << "-fsanitize-coverage=bb";
          CoverageFeatures = CoverageBB;
          break;
        case 3:
          D.Diag(diag::warn_drv_deprecated_arg) << Arg->getAsString(Args)
                                                << "-fsanitize-coverage=edge";
          CoverageFeatures = CoverageEdge;
          break;
        case 4:
          D.Diag(diag::warn_drv_deprecated_arg)
              << Arg->getAsString(Args)
              << "-fsanitize-coverage=edge,indirect-calls";
          CoverageFeatures = CoverageEdge | CoverageIndirCall;
          break;
d482 2
a483 7
        continue;
      }
      CoverageFeatures |= parseCoverageFeatures(D, Arg);

      // Disable coverage and not claim the flags if there is at least one
      // non-supporting sanitizer.
      if (!(AllAddedKinds & ~setGroupBits(SupportsCoverage))) {
d485 1
a485 2
      } else {
        CoverageFeatures = 0;
a486 3
    } else if (Arg->getOption().matches(options::OPT_fno_sanitize_coverage)) {
      Arg->claim();
      CoverageFeatures &= ~parseCoverageFeatures(D, Arg);
a514 4
  // trace-pc w/o func/bb/edge implies edge.
  if ((CoverageFeatures & (CoverageTracePC | CoverageTracePCGuard)) &&
      !(CoverageFeatures & CoverageTypes))
    CoverageFeatures |= CoverageEdge;
a543 7

    if (Arg *A = Args.getLastArg(
            options::OPT_fsanitize_address_use_after_scope,
            options::OPT_fno_sanitize_address_use_after_scope)) {
      AsanUseAfterScope = A->getOption().getID() ==
                          options::OPT_fsanitize_address_use_after_scope;
    }
a567 14
static void addIncludeLinkerOption(const ToolChain &TC,
                                   const llvm::opt::ArgList &Args,
                                   llvm::opt::ArgStringList &CmdArgs,
                                   StringRef SymbolName) {
  SmallString<64> LinkerOptionFlag;
  LinkerOptionFlag = "--linker-option=/include:";
  if (TC.getTriple().getArch() == llvm::Triple::x86) {
    // Win32 mangles C function names with a '_' prefix.
    LinkerOptionFlag += '_';
  }
  LinkerOptionFlag += SymbolName;
  CmdArgs.push_back(Args.MakeArgString(LinkerOptionFlag));
}

a570 48
  // NVPTX doesn't currently support sanitizers.  Bailing out here means that
  // e.g. -fsanitize=address applies only to host code, which is what we want
  // for now.
  if (TC.getTriple().isNVPTX())
    return;

  // Translate available CoverageFeatures to corresponding clang-cc1 flags.
  // Do it even if Sanitizers.empty() since some forms of coverage don't require
  // sanitizers.
  std::pair<int, const char *> CoverageFlags[] = {
    std::make_pair(CoverageFunc, "-fsanitize-coverage-type=1"),
    std::make_pair(CoverageBB, "-fsanitize-coverage-type=2"),
    std::make_pair(CoverageEdge, "-fsanitize-coverage-type=3"),
    std::make_pair(CoverageIndirCall, "-fsanitize-coverage-indirect-calls"),
    std::make_pair(CoverageTraceBB, "-fsanitize-coverage-trace-bb"),
    std::make_pair(CoverageTraceCmp, "-fsanitize-coverage-trace-cmp"),
    std::make_pair(CoverageTraceDiv, "-fsanitize-coverage-trace-div"),
    std::make_pair(CoverageTraceGep, "-fsanitize-coverage-trace-gep"),
    std::make_pair(Coverage8bitCounters, "-fsanitize-coverage-8bit-counters"),
    std::make_pair(CoverageTracePC, "-fsanitize-coverage-trace-pc"),
    std::make_pair(CoverageTracePCGuard, "-fsanitize-coverage-trace-pc-guard")};
  for (auto F : CoverageFlags) {
    if (CoverageFeatures & F.first)
      CmdArgs.push_back(Args.MakeArgString(F.second));
  }

  if (TC.getTriple().isOSWindows() && needsUbsanRt()) {
    // Instruct the code generator to embed linker directives in the object file
    // that cause the required runtime libraries to be linked.
    CmdArgs.push_back(Args.MakeArgString(
        "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone")));
    if (types::isCXX(InputType))
      CmdArgs.push_back(Args.MakeArgString(
          "--dependent-lib=" + TC.getCompilerRT(Args, "ubsan_standalone_cxx")));
  }
  if (TC.getTriple().isOSWindows() && needsStatsRt()) {
    CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
                                         TC.getCompilerRT(Args, "stats_client")));

    // The main executable must export the stats runtime.
    // FIXME: Only exporting from the main executable (e.g. based on whether the
    // translation unit defines main()) would save a little space, but having
    // multiple copies of the runtime shouldn't hurt.
    CmdArgs.push_back(Args.MakeArgString("--dependent-lib=" +
                                         TC.getCompilerRT(Args, "stats")));
    addIncludeLinkerOption(TC, Args, CmdArgs, "__sanitizer_stats_register");
  }

a600 16
  // FIXME: Pass these parameters as function attributes, not as -llvm flags.
  if (!TsanMemoryAccess) {
    CmdArgs.push_back("-mllvm");
    CmdArgs.push_back("-tsan-instrument-memory-accesses=0");
    CmdArgs.push_back("-mllvm");
    CmdArgs.push_back("-tsan-instrument-memintrinsics=0");
  }
  if (!TsanFuncEntryExit) {
    CmdArgs.push_back("-mllvm");
    CmdArgs.push_back("-tsan-instrument-func-entry-exit=0");
  }
  if (!TsanAtomics) {
    CmdArgs.push_back("-mllvm");
    CmdArgs.push_back("-tsan-instrument-atomics=0");
  }

a603 3
  if (Stats)
    CmdArgs.push_back(Args.MakeArgString("-fsanitize-stats"));

d607 13
a620 2
  if (AsanUseAfterScope)
    CmdArgs.push_back(Args.MakeArgString("-fsanitize-address-use-after-scope"));
d630 8
a637 8
  // Require -fvisibility= flag on non-Windows when compiling if vptr CFI is
  // enabled.
  if (Sanitizers.hasOneOf(CFIClasses) && !TC.getTriple().isOSWindows() &&
      !Args.hasArg(options::OPT_fvisibility_EQ)) {
    TC.getDriver().Diag(clang::diag::err_drv_argument_only_allowed_with)
        << lastArgumentForMask(TC.getDriver(), Args,
                               Sanitizers.Mask & CFIClasses)
        << "-fvisibility=";
a657 4
    // Similarly, don't accept -fsanitize=efficiency-all.
    else if (A->getOption().matches(options::OPT_fsanitize_EQ) &&
        0 == strcmp("efficiency-all", Value))
      Kind = 0;
a682 2
        .Case("trace-div", CoverageTraceDiv)
        .Case("trace-gep", CoverageTraceGep)
a683 2
        .Case("trace-pc", CoverageTracePC)
        .Case("trace-pc-guard", CoverageTracePCGuard)
@


1.1.1.10
log
@Import clang r309604 from branches/release_50
@
text
@d10 1
a10 1
#include "ToolChains/CommonArgs.h"
d29 1
a29 1
  NeedsUbsanRt = Undefined | Integer | Nullability | CFI,
d34 2
a35 3
  SupportsCoverage = Address | KernelAddress | Memory | Leak | Undefined |
                     Integer | Nullability | DataFlow | Fuzzer,
  RecoverableByDefault = Undefined | Integer | Nullability,
d39 2
a40 2
  TrappingSupported = (Undefined & ~Vptr) | UnsignedIntegerOverflow |
                      Nullability | LocalBounds | CFI,
d50 1
a50 1
  CoverageTraceBB = 1 << 4,  // Deprecated.
d54 1
a54 1
  Coverage8bitCounters = 1 << 8,  // Deprecated.
a56 2
  CoverageInline8bitCounters = 1 << 12,
  CoverageNoPrune = 1 << 11,
a207 5
  // The object size sanitizer should not be enabled at -O0.
  Arg *OptLevel = Args.getLastArg(options::OPT_O_Group);
  bool RemoveObjectSizeAtO0 =
      !OptLevel || OptLevel->getOption().matches(options::OPT_O0);

d213 1
a213 12
      SanitizerMask Add = parseArgValues(D, Arg, /*AllowGroups=*/true);

      if (RemoveObjectSizeAtO0) {
        AllRemove |= SanitizerKind::ObjectSize;

        // The user explicitly enabled the object size sanitizer. Warn that
        // that this does nothing at -O0.
        if (Add & SanitizerKind::ObjectSize)
          D.Diag(diag::warn_drv_object_size_disabled_O0)
              << Arg->getAsString(Args);
      }

a266 4
      // Enable coverage if the fuzzing flag is set.
      if (Add & Fuzzer)
        CoverageFeatures |= CoverageTracePCGuard | CoverageIndirCall | CoverageTraceCmp;

d471 23
a493 4
               .getAsInteger(0, LegacySanitizeCoverage)) {
        CoverageFeatures = 0;
        Arg->claim();
        if (LegacySanitizeCoverage != 0) {
d495 4
a498 1
              << Arg->getAsString(Args) << "-fsanitize-coverage=trace-pc-guard";
d531 4
a534 2
  if (CoverageFeatures & CoverageTraceBB)
    D.Diag(clang::diag::warn_drv_deprecated_arg)
d536 4
a539 3
        << "-fsanitize-coverage=trace-pc-guard";
  if (CoverageFeatures & Coverage8bitCounters)
    D.Diag(clang::diag::warn_drv_deprecated_arg)
d541 1
a541 10
        << "-fsanitize-coverage=trace-pc-guard";

  int InsertionPointTypes = CoverageFunc | CoverageBB | CoverageEdge;
  if ((CoverageFeatures & InsertionPointTypes) &&
      !(CoverageFeatures &(CoverageTracePC | CoverageTracePCGuard))) {
    D.Diag(clang::diag::warn_drv_deprecated_arg)
        << "-fsanitize-coverage=[func|bb|edge]"
        << "-fsanitize-coverage=[func|bb|edge],[trace-pc-guard|trace-pc]";
  }

d543 2
a544 3
  if ((CoverageFeatures &
       (CoverageTracePC | CoverageTracePCGuard | CoverageInline8bitCounters)) &&
      !(CoverageFeatures & InsertionPointTypes))
d576 6
a581 12
    AsanUseAfterScope = Args.hasFlag(
        options::OPT_fsanitize_address_use_after_scope,
        options::OPT_fno_sanitize_address_use_after_scope, AsanUseAfterScope);

    // As a workaround for a bug in gold 2.26 and earlier, dead stripping of
    // globals in ASan is disabled by default on ELF targets.
    // See https://sourceware.org/bugzilla/show_bug.cgi?id=19002
    AsanGlobalsDeadStripping =
        !TC.getTriple().isOSBinFormatELF() ||
        Args.hasArg(options::OPT_fsanitize_address_globals_dead_stripping);
  } else {
    AsanUseAfterScope = false;
d643 1
a643 3
    std::make_pair(CoverageTracePCGuard, "-fsanitize-coverage-trace-pc-guard"),
    std::make_pair(CoverageInline8bitCounters, "-fsanitize-coverage-inline-8bit-counters"),
    std::make_pair(CoverageNoPrune, "-fsanitize-coverage-no-prune")};
d646 1
a646 1
      CmdArgs.push_back(F.second);
d699 1
a699 1
    CmdArgs.push_back("-fsanitize-memory-use-after-dtor");
d718 1
a718 1
    CmdArgs.push_back("-fsanitize-cfi-cross-dso");
d721 1
a721 1
    CmdArgs.push_back("-fsanitize-stats");
d728 1
a728 4
    CmdArgs.push_back("-fsanitize-address-use-after-scope");

  if (AsanGlobalsDeadStripping)
    CmdArgs.push_back("-fsanitize-address-globals-dead-stripping");
d736 1
a736 1
    CmdArgs.push_back("-fno-assume-sane-operator-new");
a799 2
        .Case("no-prune", CoverageNoPrune)
        .Case("inline-8bit-counters", CoverageInline8bitCounters)
@


1.1.1.10.4.1
log
@Sync with HEAD
@
text
@a20 1
#include "llvm/Support/TargetParser.h"
d32 4
a35 6
  NotAllowedWithMinimalRuntime = Vptr,
  RequiresPIE = DataFlow | HWAddress | Scudo,
  NeedsUnwindTables = Address | HWAddress | Thread | Memory | DataFlow,
  SupportsCoverage = Address | HWAddress | KernelAddress | KernelHWAddress |
                     Memory | Leak | Undefined | Integer | Nullability |
                     DataFlow | Fuzzer | FuzzerNoLink,
a37 1
  AlwaysRecoverable = KernelAddress | KernelHWAddress,
d43 1
a43 3
  CFIClasses =
      CFIVCall | CFINVCall | CFIMFCall | CFIDerivedCast | CFIUnrelatedCast,
  CompatibleWithMinimalRuntime = TrappingSupported | Scudo,
d58 1
a59 3
  CoverageInline8bitCounters = 1 << 12,
  CoveragePCTable = 1 << 13,
  CoverageStackDepth = 1 << 14,
d90 13
a102 16
static void addDefaultBlacklists(const Driver &D, SanitizerMask Kinds,
                                 std::vector<std::string> &BlacklistFiles) {
  struct Blacklist {
    const char *File;
    SanitizerMask Mask;
  } Blacklists[] = {{"asan_blacklist.txt", Address},
                    {"hwasan_blacklist.txt", HWAddress},
                    {"msan_blacklist.txt", Memory},
                    {"tsan_blacklist.txt", Thread},
                    {"dfsan_abilist.txt", DataFlow},
                    {"cfi_blacklist.txt", CFI},
                    {"ubsan_blacklist.txt", Undefined | Integer | Nullability}};

  for (auto BL : Blacklists) {
    if (!(Kinds & BL.Mask))
      continue;
d104 1
d106 3
a108 7
    llvm::sys::path::append(Path, "share", BL.File);
    if (llvm::sys::fs::exists(Path))
      BlacklistFiles.push_back(Path.str());
    else if (BL.Mask == CFI)
      // If cfi_blacklist.txt cannot be found in the resource dir, driver
      // should fail.
      D.Diag(clang::diag::err_drv_no_such_file) << Path;
d110 1
d168 5
a172 8
  // All of these include ubsan.
  if (needsAsanRt() || needsMsanRt() || needsHwasanRt() || needsTsanRt() ||
      needsDfsanRt() || needsLsanRt() || needsCfiDiagRt() ||
      (needsScudoRt() && !requiresMinimalRuntime()))
    return false;

  return (Sanitizers.Mask & NeedsUbsanRt & ~TrapSanitizers.Mask) ||
         CoverageFeatures;
d176 1
a176 2
  return !(Sanitizers.Mask & CFI & ~TrapSanitizers.Mask) && CfiCrossDso &&
         !ImplicitCfiRuntime;
d180 1
a180 2
  return (Sanitizers.Mask & CFI & ~TrapSanitizers.Mask) && CfiCrossDso &&
         !ImplicitCfiRuntime;
a204 4

  CfiCrossDso = Args.hasFlag(options::OPT_fsanitize_cfi_cross_dso,
                             options::OPT_fno_sanitize_cfi_cross_dso, false);

a210 4
  MinimalRuntime =
      Args.hasFlag(options::OPT_fsanitize_minimal_runtime,
                   options::OPT_fno_sanitize_minimal_runtime, MinimalRuntime);

a247 30

      if (MinimalRuntime) {
        if (SanitizerMask KindsToDiagnose =
                Add & NotAllowedWithMinimalRuntime & ~DiagnosedKinds) {
          std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
          D.Diag(diag::err_drv_argument_not_allowed_with)
              << Desc << "-fsanitize-minimal-runtime";
          DiagnosedKinds |= KindsToDiagnose;
        }
        Add &= ~NotAllowedWithMinimalRuntime;
      }

      // FIXME: Make CFI on member function calls compatible with cross-DSO CFI.
      // There are currently two problems:
      // - Virtual function call checks need to pass a pointer to the function
      //   address to llvm.type.test and a pointer to the address point to the
      //   diagnostic function. Currently we pass the same pointer to both
      //   places.
      // - Non-virtual function call checks may need to check multiple type
      //   identifiers.
      // Fixing both of those may require changes to the cross-DSO CFI
      // interface.
      if (CfiCrossDso && (Add & CFIMFCall & ~DiagnosedKinds)) {
        D.Diag(diag::err_drv_argument_not_allowed_with)
            << "-fsanitize=cfi-mfcall"
            << "-fsanitize-cfi-cross-dso";
        Add &= ~CFIMFCall;
        DiagnosedKinds |= CFIMFCall;
      }

d259 11
a269 6
      if ((Add & Vptr) && (RTTIMode == ToolChain::RM_Disabled)) {
        if (const llvm::opt::Arg *NoRTTIArg = TC.getRTTIArg()) {
          assert(NoRTTIArg->getOption().matches(options::OPT_fno_rtti) &&
                  "RTTI disabled without -fno-rtti option?");
          // The user explicitly passed -fno-rtti with -fsanitize=vptr, but
          // the vptr sanitizer requires RTTI, so this is a user error.
a271 4
        } else {
          // The vptr sanitizer requires RTTI, but RTTI is disabled (by 
          // default). Warn that the vptr sanitizer is being disabled.
          D.Diag(diag::warn_drv_disabling_vptr_no_rtti_default);
a283 5
      if (MinimalRuntime) {
        Add &= ~NotAllowedWithMinimalRuntime;
      }
      if (CfiCrossDso)
        Add &= ~CFIMFCall;
d286 1
d288 1
a288 10
        Add |= FuzzerNoLink;

      // Enable coverage if the fuzzing flag is set.
      if (Add & FuzzerNoLink) {
        CoverageFeatures |= CoverageInline8bitCounters | CoverageIndirCall |
                            CoverageTraceCmp | CoveragePCTable;
        // Due to TLS differences, stack depth tracking is only enabled on Linux
        if (TC.getTriple().isOSLinux())
          CoverageFeatures |= CoverageStackDepth;
      }
a297 19
  std::pair<SanitizerMask, SanitizerMask> IncompatibleGroups[] = {
      std::make_pair(Address, Thread | Memory),
      std::make_pair(Thread, Memory),
      std::make_pair(Leak, Thread | Memory),
      std::make_pair(KernelAddress, Address | Leak | Thread | Memory),
      std::make_pair(HWAddress, Address | Thread | Memory | KernelAddress),
      std::make_pair(Efficiency, Address | HWAddress | Leak | Thread | Memory |
                                     KernelAddress),
      std::make_pair(Scudo, Address | HWAddress | Leak | Thread | Memory |
                                KernelAddress | Efficiency),
      std::make_pair(SafeStack, Address | HWAddress | Leak | Thread | Memory |
                                    KernelAddress | Efficiency),
      std::make_pair(ShadowCallStack, Address | HWAddress | Leak | Thread |
                                          Memory | KernelAddress | Efficiency |
                                          SafeStack),
      std::make_pair(KernelHWAddress, Address | HWAddress | Leak | Thread |
                                          Memory | KernelAddress | Efficiency |
                                          SafeStack | ShadowCallStack)};

d299 1
a299 11
  SanitizerMask Default = TC.getDefaultSanitizers() & ~AllRemove;

  // Disable default sanitizers that are incompatible with explicitly requested
  // ones.
  for (auto G : IncompatibleGroups) {
    SanitizerMask Group = G.first;
    if ((Default & Group) && (Kinds & G.second))
      Default &= ~Group;
  }

  Kinds |= Default;
d303 3
a305 1
  if ((Kinds & Vptr) && (RTTIMode == ToolChain::RM_Disabled)) {
a314 9
  if ((Kinds & ShadowCallStack) &&
      TC.getTriple().getArch() == llvm::Triple::aarch64 &&
      !llvm::AArch64::isX18ReservedByDefault(TC.getTriple()) &&
      !Args.hasArg(options::OPT_ffixed_x18)) {
    D.Diag(diag::err_drv_argument_only_allowed_with)
        << lastArgumentForMask(D, Args, Kinds & ShadowCallStack)
        << "-ffixed-x18";
  }

d335 12
d364 1
a364 1
  SanitizerMask RecoverableKinds = RecoverableByDefault | AlwaysRecoverable;
a365 1
  SanitizerMask DiagnosedAlwaysRecoverableKinds = 0;
d393 1
a393 12
      SanitizerMask Remove = parseArgValues(D, Arg, true);
      // Report error if user explicitly tries to disable recovery from
      // always recoverable sanitizer.
      if (SanitizerMask KindsToDiagnose =
              Remove & AlwaysRecoverable & ~DiagnosedAlwaysRecoverableKinds) {
        SanitizerSet SetToDiagnose;
        SetToDiagnose.Mask |= KindsToDiagnose;
        D.Diag(diag::err_drv_unsupported_option_argument)
            << Arg->getOption().getName() << toString(SetToDiagnose);
        DiagnosedAlwaysRecoverableKinds |= KindsToDiagnose;
      }
      RecoverableKinds &= ~expandSanitizerGroups(Remove);
a404 1
  RecoverableKinds &= ~TrappingKinds;
d408 5
a412 1
  addDefaultBlacklists(D, Kinds, BlacklistFiles);
d421 1
a421 1
      } else {
d423 1
a423 1
      }
d459 1
a459 3
        Args.hasFlag(options::OPT_fsanitize_memory_use_after_dtor,
                     options::OPT_fno_sanitize_memory_use_after_dtor,
                     MsanUseAfterDtor);
a461 2
  } else {
    MsanUseAfterDtor = false;
d477 2
a481 7
    CfiICallGeneralizePointers =
        Args.hasArg(options::OPT_fsanitize_cfi_icall_generalize_pointers);

    if (CfiCrossDso && CfiICallGeneralizePointers)
      D.Diag(diag::err_drv_argument_not_allowed_with)
          << "-fsanitize-cfi-cross-dso"
          << "-fsanitize-cfi-icall-generalize-pointers";
a486 15
  if (MinimalRuntime) {
    SanitizerMask IncompatibleMask =
        Kinds & ~setGroupBits(CompatibleWithMinimalRuntime);
    if (IncompatibleMask)
      D.Diag(clang::diag::err_drv_argument_not_allowed_with)
          << "-fsanitize-minimal-runtime"
          << lastArgumentForMask(D, Args, IncompatibleMask);

    SanitizerMask NonTrappingCfi = Kinds & CFI & ~TrappingKinds;
    if (NonTrappingCfi)
      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
          << "fsanitize-minimal-runtime"
          << "fsanitize-trap=cfi";
  }

d507 1
a507 1
      if (!(AllAddedKinds & ~AllRemove & ~setGroupBits(SupportsCoverage))) {
a541 2
  int InstrumentationTypes =
      CoverageTracePC | CoverageTracePCGuard | CoverageInline8bitCounters;
d543 1
a543 1
      !(CoverageFeatures & InstrumentationTypes)) {
d550 4
a553 15
  if (!(CoverageFeatures & InsertionPointTypes)) {
    if (CoverageFeatures &
        (CoverageTracePC | CoverageTracePCGuard | CoverageInline8bitCounters))
      CoverageFeatures |= CoverageEdge;

    if (CoverageFeatures & CoverageStackDepth)
      CoverageFeatures |= CoverageFunc;
  }

  SharedRuntime =
      Args.hasFlag(options::OPT_shared_libsan, options::OPT_static_libsan,
                   TC.getTriple().isAndroid() || TC.getTriple().isOSFuchsia() ||
                       TC.getTriple().isOSDarwin());

  ImplicitCfiRuntime = TC.getTriple().isAndroid();
d556 3
a558 1
    NeedPIE |= TC.getTriple().isOSFuchsia();
d592 1
a592 1
        !TC.getTriple().isOSBinFormatELF() || TC.getTriple().isOSFuchsia() ||
a597 5
  if (AllAddedKinds & SafeStack) {
    // SafeStack runtime is built into the system on Fuchsia.
    SafeStackRuntime = !TC.getTriple().isOSFuchsia();
  }

a605 2
  assert(!(RecoverableKinds & TrappingKinds) &&
         "Overlap between recoverable and trapping sanitizers");
d659 1
a659 3
    std::make_pair(CoveragePCTable, "-fsanitize-coverage-pc-table"),
    std::make_pair(CoverageNoPrune, "-fsanitize-coverage-no-prune"),
    std::make_pair(CoverageStackDepth, "-fsanitize-coverage-stack-depth")};
d712 1
a712 1
                                         Twine(MsanTrackOrigins)));
a735 3
  if (CfiICallGeneralizePointers)
    CmdArgs.push_back("-fsanitize-cfi-icall-generalize-pointers");

a738 3
  if (MinimalRuntime)
    CmdArgs.push_back("-fsanitize-minimal-runtime");

d741 1
a741 1
                                         Twine(AsanFieldPadding)));
d751 1
a751 1
  // https://github.com/google/sanitizers/issues/373
a820 2
        .Case("pc-table", CoveragePCTable)
        .Case("stack-depth", CoverageStackDepth)
@


1.1.1.10.4.2
log
@Mostly merge changes from HEAD upto 20200411
@
text
@@


1.1.1.10.2.1
log
@Sync with HEAD
@
text
@a20 1
#include "llvm/Support/TargetParser.h"
d32 4
a35 6
  NotAllowedWithMinimalRuntime = Vptr,
  RequiresPIE = DataFlow | HWAddress | Scudo,
  NeedsUnwindTables = Address | HWAddress | Thread | Memory | DataFlow,
  SupportsCoverage = Address | HWAddress | KernelAddress | KernelHWAddress |
                     Memory | Leak | Undefined | Integer | Nullability |
                     DataFlow | Fuzzer | FuzzerNoLink,
a37 1
  AlwaysRecoverable = KernelAddress | KernelHWAddress,
d43 1
a43 3
  CFIClasses =
      CFIVCall | CFINVCall | CFIMFCall | CFIDerivedCast | CFIUnrelatedCast,
  CompatibleWithMinimalRuntime = TrappingSupported | Scudo,
d58 1
a59 3
  CoverageInline8bitCounters = 1 << 12,
  CoveragePCTable = 1 << 13,
  CoverageStackDepth = 1 << 14,
d90 13
a102 16
static void addDefaultBlacklists(const Driver &D, SanitizerMask Kinds,
                                 std::vector<std::string> &BlacklistFiles) {
  struct Blacklist {
    const char *File;
    SanitizerMask Mask;
  } Blacklists[] = {{"asan_blacklist.txt", Address},
                    {"hwasan_blacklist.txt", HWAddress},
                    {"msan_blacklist.txt", Memory},
                    {"tsan_blacklist.txt", Thread},
                    {"dfsan_abilist.txt", DataFlow},
                    {"cfi_blacklist.txt", CFI},
                    {"ubsan_blacklist.txt", Undefined | Integer | Nullability}};

  for (auto BL : Blacklists) {
    if (!(Kinds & BL.Mask))
      continue;
d104 1
d106 3
a108 7
    llvm::sys::path::append(Path, "share", BL.File);
    if (llvm::sys::fs::exists(Path))
      BlacklistFiles.push_back(Path.str());
    else if (BL.Mask == CFI)
      // If cfi_blacklist.txt cannot be found in the resource dir, driver
      // should fail.
      D.Diag(clang::diag::err_drv_no_such_file) << Path;
d110 1
d168 5
a172 8
  // All of these include ubsan.
  if (needsAsanRt() || needsMsanRt() || needsHwasanRt() || needsTsanRt() ||
      needsDfsanRt() || needsLsanRt() || needsCfiDiagRt() ||
      (needsScudoRt() && !requiresMinimalRuntime()))
    return false;

  return (Sanitizers.Mask & NeedsUbsanRt & ~TrapSanitizers.Mask) ||
         CoverageFeatures;
d176 1
a176 2
  return !(Sanitizers.Mask & CFI & ~TrapSanitizers.Mask) && CfiCrossDso &&
         !ImplicitCfiRuntime;
d180 1
a180 2
  return (Sanitizers.Mask & CFI & ~TrapSanitizers.Mask) && CfiCrossDso &&
         !ImplicitCfiRuntime;
a204 4

  CfiCrossDso = Args.hasFlag(options::OPT_fsanitize_cfi_cross_dso,
                             options::OPT_fno_sanitize_cfi_cross_dso, false);

a210 4
  MinimalRuntime =
      Args.hasFlag(options::OPT_fsanitize_minimal_runtime,
                   options::OPT_fno_sanitize_minimal_runtime, MinimalRuntime);

a247 30

      if (MinimalRuntime) {
        if (SanitizerMask KindsToDiagnose =
                Add & NotAllowedWithMinimalRuntime & ~DiagnosedKinds) {
          std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
          D.Diag(diag::err_drv_argument_not_allowed_with)
              << Desc << "-fsanitize-minimal-runtime";
          DiagnosedKinds |= KindsToDiagnose;
        }
        Add &= ~NotAllowedWithMinimalRuntime;
      }

      // FIXME: Make CFI on member function calls compatible with cross-DSO CFI.
      // There are currently two problems:
      // - Virtual function call checks need to pass a pointer to the function
      //   address to llvm.type.test and a pointer to the address point to the
      //   diagnostic function. Currently we pass the same pointer to both
      //   places.
      // - Non-virtual function call checks may need to check multiple type
      //   identifiers.
      // Fixing both of those may require changes to the cross-DSO CFI
      // interface.
      if (CfiCrossDso && (Add & CFIMFCall & ~DiagnosedKinds)) {
        D.Diag(diag::err_drv_argument_not_allowed_with)
            << "-fsanitize=cfi-mfcall"
            << "-fsanitize-cfi-cross-dso";
        Add &= ~CFIMFCall;
        DiagnosedKinds |= CFIMFCall;
      }

d259 11
a269 6
      if ((Add & Vptr) && (RTTIMode == ToolChain::RM_Disabled)) {
        if (const llvm::opt::Arg *NoRTTIArg = TC.getRTTIArg()) {
          assert(NoRTTIArg->getOption().matches(options::OPT_fno_rtti) &&
                  "RTTI disabled without -fno-rtti option?");
          // The user explicitly passed -fno-rtti with -fsanitize=vptr, but
          // the vptr sanitizer requires RTTI, so this is a user error.
a271 4
        } else {
          // The vptr sanitizer requires RTTI, but RTTI is disabled (by 
          // default). Warn that the vptr sanitizer is being disabled.
          D.Diag(diag::warn_drv_disabling_vptr_no_rtti_default);
a283 5
      if (MinimalRuntime) {
        Add &= ~NotAllowedWithMinimalRuntime;
      }
      if (CfiCrossDso)
        Add &= ~CFIMFCall;
d286 1
d288 1
a288 10
        Add |= FuzzerNoLink;

      // Enable coverage if the fuzzing flag is set.
      if (Add & FuzzerNoLink) {
        CoverageFeatures |= CoverageInline8bitCounters | CoverageIndirCall |
                            CoverageTraceCmp | CoveragePCTable;
        // Due to TLS differences, stack depth tracking is only enabled on Linux
        if (TC.getTriple().isOSLinux())
          CoverageFeatures |= CoverageStackDepth;
      }
a297 19
  std::pair<SanitizerMask, SanitizerMask> IncompatibleGroups[] = {
      std::make_pair(Address, Thread | Memory),
      std::make_pair(Thread, Memory),
      std::make_pair(Leak, Thread | Memory),
      std::make_pair(KernelAddress, Address | Leak | Thread | Memory),
      std::make_pair(HWAddress, Address | Thread | Memory | KernelAddress),
      std::make_pair(Efficiency, Address | HWAddress | Leak | Thread | Memory |
                                     KernelAddress),
      std::make_pair(Scudo, Address | HWAddress | Leak | Thread | Memory |
                                KernelAddress | Efficiency),
      std::make_pair(SafeStack, Address | HWAddress | Leak | Thread | Memory |
                                    KernelAddress | Efficiency),
      std::make_pair(ShadowCallStack, Address | HWAddress | Leak | Thread |
                                          Memory | KernelAddress | Efficiency |
                                          SafeStack),
      std::make_pair(KernelHWAddress, Address | HWAddress | Leak | Thread |
                                          Memory | KernelAddress | Efficiency |
                                          SafeStack | ShadowCallStack)};

d299 1
a299 11
  SanitizerMask Default = TC.getDefaultSanitizers() & ~AllRemove;

  // Disable default sanitizers that are incompatible with explicitly requested
  // ones.
  for (auto G : IncompatibleGroups) {
    SanitizerMask Group = G.first;
    if ((Default & Group) && (Kinds & G.second))
      Default &= ~Group;
  }

  Kinds |= Default;
d303 3
a305 1
  if ((Kinds & Vptr) && (RTTIMode == ToolChain::RM_Disabled)) {
a314 9
  if ((Kinds & ShadowCallStack) &&
      TC.getTriple().getArch() == llvm::Triple::aarch64 &&
      !llvm::AArch64::isX18ReservedByDefault(TC.getTriple()) &&
      !Args.hasArg(options::OPT_ffixed_x18)) {
    D.Diag(diag::err_drv_argument_only_allowed_with)
        << lastArgumentForMask(D, Args, Kinds & ShadowCallStack)
        << "-ffixed-x18";
  }

d335 12
d364 1
a364 1
  SanitizerMask RecoverableKinds = RecoverableByDefault | AlwaysRecoverable;
a365 1
  SanitizerMask DiagnosedAlwaysRecoverableKinds = 0;
d393 1
a393 12
      SanitizerMask Remove = parseArgValues(D, Arg, true);
      // Report error if user explicitly tries to disable recovery from
      // always recoverable sanitizer.
      if (SanitizerMask KindsToDiagnose =
              Remove & AlwaysRecoverable & ~DiagnosedAlwaysRecoverableKinds) {
        SanitizerSet SetToDiagnose;
        SetToDiagnose.Mask |= KindsToDiagnose;
        D.Diag(diag::err_drv_unsupported_option_argument)
            << Arg->getOption().getName() << toString(SetToDiagnose);
        DiagnosedAlwaysRecoverableKinds |= KindsToDiagnose;
      }
      RecoverableKinds &= ~expandSanitizerGroups(Remove);
a404 1
  RecoverableKinds &= ~TrappingKinds;
d408 5
a412 1
  addDefaultBlacklists(D, Kinds, BlacklistFiles);
d421 1
a421 1
      } else {
d423 1
a423 1
      }
d459 1
a459 3
        Args.hasFlag(options::OPT_fsanitize_memory_use_after_dtor,
                     options::OPT_fno_sanitize_memory_use_after_dtor,
                     MsanUseAfterDtor);
a461 2
  } else {
    MsanUseAfterDtor = false;
d477 2
a481 7
    CfiICallGeneralizePointers =
        Args.hasArg(options::OPT_fsanitize_cfi_icall_generalize_pointers);

    if (CfiCrossDso && CfiICallGeneralizePointers)
      D.Diag(diag::err_drv_argument_not_allowed_with)
          << "-fsanitize-cfi-cross-dso"
          << "-fsanitize-cfi-icall-generalize-pointers";
a486 15
  if (MinimalRuntime) {
    SanitizerMask IncompatibleMask =
        Kinds & ~setGroupBits(CompatibleWithMinimalRuntime);
    if (IncompatibleMask)
      D.Diag(clang::diag::err_drv_argument_not_allowed_with)
          << "-fsanitize-minimal-runtime"
          << lastArgumentForMask(D, Args, IncompatibleMask);

    SanitizerMask NonTrappingCfi = Kinds & CFI & ~TrappingKinds;
    if (NonTrappingCfi)
      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
          << "fsanitize-minimal-runtime"
          << "fsanitize-trap=cfi";
  }

d507 1
a507 1
      if (!(AllAddedKinds & ~AllRemove & ~setGroupBits(SupportsCoverage))) {
a541 2
  int InstrumentationTypes =
      CoverageTracePC | CoverageTracePCGuard | CoverageInline8bitCounters;
d543 1
a543 1
      !(CoverageFeatures & InstrumentationTypes)) {
d550 4
a553 15
  if (!(CoverageFeatures & InsertionPointTypes)) {
    if (CoverageFeatures &
        (CoverageTracePC | CoverageTracePCGuard | CoverageInline8bitCounters))
      CoverageFeatures |= CoverageEdge;

    if (CoverageFeatures & CoverageStackDepth)
      CoverageFeatures |= CoverageFunc;
  }

  SharedRuntime =
      Args.hasFlag(options::OPT_shared_libsan, options::OPT_static_libsan,
                   TC.getTriple().isAndroid() || TC.getTriple().isOSFuchsia() ||
                       TC.getTriple().isOSDarwin());

  ImplicitCfiRuntime = TC.getTriple().isAndroid();
d556 3
a558 1
    NeedPIE |= TC.getTriple().isOSFuchsia();
d592 1
a592 1
        !TC.getTriple().isOSBinFormatELF() || TC.getTriple().isOSFuchsia() ||
a597 5
  if (AllAddedKinds & SafeStack) {
    // SafeStack runtime is built into the system on Fuchsia.
    SafeStackRuntime = !TC.getTriple().isOSFuchsia();
  }

a605 2
  assert(!(RecoverableKinds & TrappingKinds) &&
         "Overlap between recoverable and trapping sanitizers");
d659 1
a659 3
    std::make_pair(CoveragePCTable, "-fsanitize-coverage-pc-table"),
    std::make_pair(CoverageNoPrune, "-fsanitize-coverage-no-prune"),
    std::make_pair(CoverageStackDepth, "-fsanitize-coverage-stack-depth")};
d712 1
a712 1
                                         Twine(MsanTrackOrigins)));
a735 3
  if (CfiICallGeneralizePointers)
    CmdArgs.push_back("-fsanitize-cfi-icall-generalize-pointers");

a738 3
  if (MinimalRuntime)
    CmdArgs.push_back("-fsanitize-minimal-runtime");

d741 1
a741 1
                                         Twine(AsanFieldPadding)));
d751 1
a751 1
  // https://github.com/google/sanitizers/issues/373
a820 2
        .Case("pc-table", CoveragePCTable)
        .Case("stack-depth", CoverageStackDepth)
@


1.1.1.11
log
@Import clang r337282 from trunk
@
text
@a20 1
#include "llvm/Support/TargetParser.h"
d32 4
a35 6
  NotAllowedWithMinimalRuntime = Vptr,
  RequiresPIE = DataFlow | HWAddress | Scudo,
  NeedsUnwindTables = Address | HWAddress | Thread | Memory | DataFlow,
  SupportsCoverage = Address | HWAddress | KernelAddress | KernelHWAddress |
                     Memory | Leak | Undefined | Integer | Nullability |
                     DataFlow | Fuzzer | FuzzerNoLink,
a37 1
  AlwaysRecoverable = KernelAddress | KernelHWAddress,
d43 1
a43 3
  CFIClasses =
      CFIVCall | CFINVCall | CFIMFCall | CFIDerivedCast | CFIUnrelatedCast,
  CompatibleWithMinimalRuntime = TrappingSupported | Scudo,
d58 1
a59 3
  CoverageInline8bitCounters = 1 << 12,
  CoveragePCTable = 1 << 13,
  CoverageStackDepth = 1 << 14,
d90 13
a102 16
static void addDefaultBlacklists(const Driver &D, SanitizerMask Kinds,
                                 std::vector<std::string> &BlacklistFiles) {
  struct Blacklist {
    const char *File;
    SanitizerMask Mask;
  } Blacklists[] = {{"asan_blacklist.txt", Address},
                    {"hwasan_blacklist.txt", HWAddress},
                    {"msan_blacklist.txt", Memory},
                    {"tsan_blacklist.txt", Thread},
                    {"dfsan_abilist.txt", DataFlow},
                    {"cfi_blacklist.txt", CFI},
                    {"ubsan_blacklist.txt", Undefined | Integer | Nullability}};

  for (auto BL : Blacklists) {
    if (!(Kinds & BL.Mask))
      continue;
d104 1
d106 3
a108 7
    llvm::sys::path::append(Path, "share", BL.File);
    if (llvm::sys::fs::exists(Path))
      BlacklistFiles.push_back(Path.str());
    else if (BL.Mask == CFI)
      // If cfi_blacklist.txt cannot be found in the resource dir, driver
      // should fail.
      D.Diag(clang::diag::err_drv_no_such_file) << Path;
d110 1
d168 5
a172 8
  // All of these include ubsan.
  if (needsAsanRt() || needsMsanRt() || needsHwasanRt() || needsTsanRt() ||
      needsDfsanRt() || needsLsanRt() || needsCfiDiagRt() ||
      (needsScudoRt() && !requiresMinimalRuntime()))
    return false;

  return (Sanitizers.Mask & NeedsUbsanRt & ~TrapSanitizers.Mask) ||
         CoverageFeatures;
d176 1
a176 2
  return !(Sanitizers.Mask & CFI & ~TrapSanitizers.Mask) && CfiCrossDso &&
         !ImplicitCfiRuntime;
d180 1
a180 2
  return (Sanitizers.Mask & CFI & ~TrapSanitizers.Mask) && CfiCrossDso &&
         !ImplicitCfiRuntime;
a204 4

  CfiCrossDso = Args.hasFlag(options::OPT_fsanitize_cfi_cross_dso,
                             options::OPT_fno_sanitize_cfi_cross_dso, false);

a210 4
  MinimalRuntime =
      Args.hasFlag(options::OPT_fsanitize_minimal_runtime,
                   options::OPT_fno_sanitize_minimal_runtime, MinimalRuntime);

a247 30

      if (MinimalRuntime) {
        if (SanitizerMask KindsToDiagnose =
                Add & NotAllowedWithMinimalRuntime & ~DiagnosedKinds) {
          std::string Desc = describeSanitizeArg(*I, KindsToDiagnose);
          D.Diag(diag::err_drv_argument_not_allowed_with)
              << Desc << "-fsanitize-minimal-runtime";
          DiagnosedKinds |= KindsToDiagnose;
        }
        Add &= ~NotAllowedWithMinimalRuntime;
      }

      // FIXME: Make CFI on member function calls compatible with cross-DSO CFI.
      // There are currently two problems:
      // - Virtual function call checks need to pass a pointer to the function
      //   address to llvm.type.test and a pointer to the address point to the
      //   diagnostic function. Currently we pass the same pointer to both
      //   places.
      // - Non-virtual function call checks may need to check multiple type
      //   identifiers.
      // Fixing both of those may require changes to the cross-DSO CFI
      // interface.
      if (CfiCrossDso && (Add & CFIMFCall & ~DiagnosedKinds)) {
        D.Diag(diag::err_drv_argument_not_allowed_with)
            << "-fsanitize=cfi-mfcall"
            << "-fsanitize-cfi-cross-dso";
        Add &= ~CFIMFCall;
        DiagnosedKinds |= CFIMFCall;
      }

d259 11
a269 6
      if ((Add & Vptr) && (RTTIMode == ToolChain::RM_Disabled)) {
        if (const llvm::opt::Arg *NoRTTIArg = TC.getRTTIArg()) {
          assert(NoRTTIArg->getOption().matches(options::OPT_fno_rtti) &&
                  "RTTI disabled without -fno-rtti option?");
          // The user explicitly passed -fno-rtti with -fsanitize=vptr, but
          // the vptr sanitizer requires RTTI, so this is a user error.
a271 4
        } else {
          // The vptr sanitizer requires RTTI, but RTTI is disabled (by 
          // default). Warn that the vptr sanitizer is being disabled.
          D.Diag(diag::warn_drv_disabling_vptr_no_rtti_default);
a283 5
      if (MinimalRuntime) {
        Add &= ~NotAllowedWithMinimalRuntime;
      }
      if (CfiCrossDso)
        Add &= ~CFIMFCall;
d286 1
d288 1
a288 10
        Add |= FuzzerNoLink;

      // Enable coverage if the fuzzing flag is set.
      if (Add & FuzzerNoLink) {
        CoverageFeatures |= CoverageInline8bitCounters | CoverageIndirCall |
                            CoverageTraceCmp | CoveragePCTable;
        // Due to TLS differences, stack depth tracking is only enabled on Linux
        if (TC.getTriple().isOSLinux())
          CoverageFeatures |= CoverageStackDepth;
      }
a297 19
  std::pair<SanitizerMask, SanitizerMask> IncompatibleGroups[] = {
      std::make_pair(Address, Thread | Memory),
      std::make_pair(Thread, Memory),
      std::make_pair(Leak, Thread | Memory),
      std::make_pair(KernelAddress, Address | Leak | Thread | Memory),
      std::make_pair(HWAddress, Address | Thread | Memory | KernelAddress),
      std::make_pair(Efficiency, Address | HWAddress | Leak | Thread | Memory |
                                     KernelAddress),
      std::make_pair(Scudo, Address | HWAddress | Leak | Thread | Memory |
                                KernelAddress | Efficiency),
      std::make_pair(SafeStack, Address | HWAddress | Leak | Thread | Memory |
                                    KernelAddress | Efficiency),
      std::make_pair(ShadowCallStack, Address | HWAddress | Leak | Thread |
                                          Memory | KernelAddress | Efficiency |
                                          SafeStack),
      std::make_pair(KernelHWAddress, Address | HWAddress | Leak | Thread |
                                          Memory | KernelAddress | Efficiency |
                                          SafeStack | ShadowCallStack)};

d299 1
a299 11
  SanitizerMask Default = TC.getDefaultSanitizers() & ~AllRemove;

  // Disable default sanitizers that are incompatible with explicitly requested
  // ones.
  for (auto G : IncompatibleGroups) {
    SanitizerMask Group = G.first;
    if ((Default & Group) && (Kinds & G.second))
      Default &= ~Group;
  }

  Kinds |= Default;
d303 3
a305 1
  if ((Kinds & Vptr) && (RTTIMode == ToolChain::RM_Disabled)) {
a314 9
  if ((Kinds & ShadowCallStack) &&
      TC.getTriple().getArch() == llvm::Triple::aarch64 &&
      !llvm::AArch64::isX18ReservedByDefault(TC.getTriple()) &&
      !Args.hasArg(options::OPT_ffixed_x18)) {
    D.Diag(diag::err_drv_argument_only_allowed_with)
        << lastArgumentForMask(D, Args, Kinds & ShadowCallStack)
        << "-ffixed-x18";
  }

d335 12
d364 1
a364 1
  SanitizerMask RecoverableKinds = RecoverableByDefault | AlwaysRecoverable;
a365 1
  SanitizerMask DiagnosedAlwaysRecoverableKinds = 0;
d393 1
a393 12
      SanitizerMask Remove = parseArgValues(D, Arg, true);
      // Report error if user explicitly tries to disable recovery from
      // always recoverable sanitizer.
      if (SanitizerMask KindsToDiagnose =
              Remove & AlwaysRecoverable & ~DiagnosedAlwaysRecoverableKinds) {
        SanitizerSet SetToDiagnose;
        SetToDiagnose.Mask |= KindsToDiagnose;
        D.Diag(diag::err_drv_unsupported_option_argument)
            << Arg->getOption().getName() << toString(SetToDiagnose);
        DiagnosedAlwaysRecoverableKinds |= KindsToDiagnose;
      }
      RecoverableKinds &= ~expandSanitizerGroups(Remove);
a404 1
  RecoverableKinds &= ~TrappingKinds;
d408 5
a412 1
  addDefaultBlacklists(D, Kinds, BlacklistFiles);
d421 1
a421 1
      } else {
d423 1
a423 1
      }
d459 1
a459 3
        Args.hasFlag(options::OPT_fsanitize_memory_use_after_dtor,
                     options::OPT_fno_sanitize_memory_use_after_dtor,
                     MsanUseAfterDtor);
a461 2
  } else {
    MsanUseAfterDtor = false;
d477 2
a481 7
    CfiICallGeneralizePointers =
        Args.hasArg(options::OPT_fsanitize_cfi_icall_generalize_pointers);

    if (CfiCrossDso && CfiICallGeneralizePointers)
      D.Diag(diag::err_drv_argument_not_allowed_with)
          << "-fsanitize-cfi-cross-dso"
          << "-fsanitize-cfi-icall-generalize-pointers";
a486 15
  if (MinimalRuntime) {
    SanitizerMask IncompatibleMask =
        Kinds & ~setGroupBits(CompatibleWithMinimalRuntime);
    if (IncompatibleMask)
      D.Diag(clang::diag::err_drv_argument_not_allowed_with)
          << "-fsanitize-minimal-runtime"
          << lastArgumentForMask(D, Args, IncompatibleMask);

    SanitizerMask NonTrappingCfi = Kinds & CFI & ~TrappingKinds;
    if (NonTrappingCfi)
      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
          << "fsanitize-minimal-runtime"
          << "fsanitize-trap=cfi";
  }

d507 1
a507 1
      if (!(AllAddedKinds & ~AllRemove & ~setGroupBits(SupportsCoverage))) {
a541 2
  int InstrumentationTypes =
      CoverageTracePC | CoverageTracePCGuard | CoverageInline8bitCounters;
d543 1
a543 1
      !(CoverageFeatures & InstrumentationTypes)) {
d550 4
a553 15
  if (!(CoverageFeatures & InsertionPointTypes)) {
    if (CoverageFeatures &
        (CoverageTracePC | CoverageTracePCGuard | CoverageInline8bitCounters))
      CoverageFeatures |= CoverageEdge;

    if (CoverageFeatures & CoverageStackDepth)
      CoverageFeatures |= CoverageFunc;
  }

  SharedRuntime =
      Args.hasFlag(options::OPT_shared_libsan, options::OPT_static_libsan,
                   TC.getTriple().isAndroid() || TC.getTriple().isOSFuchsia() ||
                       TC.getTriple().isOSDarwin());

  ImplicitCfiRuntime = TC.getTriple().isAndroid();
d556 3
a558 1
    NeedPIE |= TC.getTriple().isOSFuchsia();
d592 1
a592 1
        !TC.getTriple().isOSBinFormatELF() || TC.getTriple().isOSFuchsia() ||
a597 5
  if (AllAddedKinds & SafeStack) {
    // SafeStack runtime is built into the system on Fuchsia.
    SafeStackRuntime = !TC.getTriple().isOSFuchsia();
  }

a605 2
  assert(!(RecoverableKinds & TrappingKinds) &&
         "Overlap between recoverable and trapping sanitizers");
d659 1
a659 3
    std::make_pair(CoveragePCTable, "-fsanitize-coverage-pc-table"),
    std::make_pair(CoverageNoPrune, "-fsanitize-coverage-no-prune"),
    std::make_pair(CoverageStackDepth, "-fsanitize-coverage-stack-depth")};
d712 1
a712 1
                                         Twine(MsanTrackOrigins)));
a735 3
  if (CfiICallGeneralizePointers)
    CmdArgs.push_back("-fsanitize-cfi-icall-generalize-pointers");

a738 3
  if (MinimalRuntime)
    CmdArgs.push_back("-fsanitize-minimal-runtime");

d741 1
a741 1
                                         Twine(AsanFieldPadding)));
d751 1
a751 1
  // https://github.com/google/sanitizers/issues/373
a820 2
        .Case("pc-table", CoveragePCTable)
        .Case("stack-depth", CoverageStackDepth)
@


1.1.1.12
log
@Mark old LLVM instance as dead.
@
text
@@


1.1.1.6.4.1
log
@file SanitizerArgs.cpp was added on branch tls-maxphys on 2014-08-19 23:47:27 +0000
@
text
@d1 339
@


1.1.1.6.4.2
log
@Rebase to HEAD as of a few days ago.
@
text
@a0 339
//===--- SanitizerArgs.cpp - Arguments for sanitizer tools  ---------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Driver/SanitizerArgs.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Options.h"
#include "clang/Driver/ToolChain.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SpecialCaseList.h"
#include <memory>

using namespace clang::driver;
using namespace llvm::opt;

void SanitizerArgs::clear() {
  Kind = 0;
  BlacklistFile = "";
  MsanTrackOrigins = 0;
  AsanZeroBaseShadow = false;
  UbsanTrapOnError = false;
  AsanSharedRuntime = false;
  LinkCXXRuntimes = false;
}

SanitizerArgs::SanitizerArgs(const ToolChain &TC,
                             const llvm::opt::ArgList &Args) {
  clear();
  unsigned AllAdd = 0;  // All kinds of sanitizers that were turned on
                        // at least once (possibly, disabled further).
  unsigned AllRemove = 0;  // During the loop below, the accumulated set of
                           // sanitizers disabled by the current sanitizer
                           // argument or any argument after it.
  unsigned DiagnosedKinds = 0;  // All Kinds we have diagnosed up to now.
                                // Used to deduplicate diagnostics.
  const Driver &D = TC.getDriver();
  for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
       I != E; ++I) {
    unsigned Add, Remove;
    if (!parse(D, Args, *I, Add, Remove, true))
      continue;
    (*I)->claim();

    AllAdd |= expandGroups(Add);
    AllRemove |= expandGroups(Remove);

    // Avoid diagnosing any sanitizer which is disabled later.
    Add &= ~AllRemove;
    // At this point we have not expanded groups, so any unsupported sanitizers
    // in Add are those which have been explicitly enabled. Diagnose them.
    Add = filterUnsupportedKinds(TC, Add, Args, *I, /*DiagnoseErrors=*/true,
                                 DiagnosedKinds);
    Add = expandGroups(Add);
    // Group expansion may have enabled a sanitizer which is disabled later.
    Add &= ~AllRemove;
    // Silently discard any unsupported sanitizers implicitly enabled through
    // group expansion.
    Add = filterUnsupportedKinds(TC, Add, Args, *I, /*DiagnoseErrors=*/false,
                                 DiagnosedKinds);

    Kind |= Add;
  }

  UbsanTrapOnError =
    Args.hasFlag(options::OPT_fsanitize_undefined_trap_on_error,
                 options::OPT_fno_sanitize_undefined_trap_on_error, false);

  // Warn about undefined sanitizer options that require runtime support.
  if (UbsanTrapOnError && notAllowedWithTrap()) {
    D.Diag(diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, NotAllowedWithTrap)
      << "-fsanitize-undefined-trap-on-error";
  }

  // Only one runtime library can be used at once.
  bool NeedsAsan = needsAsanRt();
  bool NeedsTsan = needsTsanRt();
  bool NeedsMsan = needsMsanRt();
  bool NeedsLsan = needsLeakDetection();
  if (NeedsAsan && NeedsTsan)
    D.Diag(diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, NeedsAsanRt)
      << lastArgumentForKind(D, Args, NeedsTsanRt);
  if (NeedsAsan && NeedsMsan)
    D.Diag(diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, NeedsAsanRt)
      << lastArgumentForKind(D, Args, NeedsMsanRt);
  if (NeedsTsan && NeedsMsan)
    D.Diag(diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, NeedsTsanRt)
      << lastArgumentForKind(D, Args, NeedsMsanRt);
  if (NeedsLsan && NeedsTsan)
    D.Diag(diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, NeedsLeakDetection)
      << lastArgumentForKind(D, Args, NeedsTsanRt);
  if (NeedsLsan && NeedsMsan)
    D.Diag(diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, NeedsLeakDetection)
      << lastArgumentForKind(D, Args, NeedsMsanRt);
  // FIXME: Currently -fsanitize=leak is silently ignored in the presence of
  // -fsanitize=address. Perhaps it should print an error, or perhaps
  // -f(-no)sanitize=leak should change whether leak detection is enabled by
  // default in ASan?

  // Parse -f(no-)sanitize-blacklist options.
  if (Arg *BLArg = Args.getLastArg(options::OPT_fsanitize_blacklist,
                                   options::OPT_fno_sanitize_blacklist)) {
    if (BLArg->getOption().matches(options::OPT_fsanitize_blacklist)) {
      std::string BLPath = BLArg->getValue();
      if (llvm::sys::fs::exists(BLPath)) {
        // Validate the blacklist format.
        std::string BLError;
        std::unique_ptr<llvm::SpecialCaseList> SCL(
            llvm::SpecialCaseList::create(BLPath, BLError));
        if (!SCL.get())
          D.Diag(diag::err_drv_malformed_sanitizer_blacklist) << BLError;
        else
          BlacklistFile = BLPath;
      } else {
        D.Diag(diag::err_drv_no_such_file) << BLPath;
      }
    }
  } else {
    // If no -fsanitize-blacklist option is specified, try to look up for
    // blacklist in the resource directory.
    std::string BLPath;
    if (getDefaultBlacklistForKind(D, Kind, BLPath) &&
        llvm::sys::fs::exists(BLPath))
      BlacklistFile = BLPath;
  }

  // Parse -f[no-]sanitize-memory-track-origins[=level] options.
  if (NeedsMsan) {
    if (Arg *A =
            Args.getLastArg(options::OPT_fsanitize_memory_track_origins_EQ,
                            options::OPT_fsanitize_memory_track_origins,
                            options::OPT_fno_sanitize_memory_track_origins)) {
      if (A->getOption().matches(options::OPT_fsanitize_memory_track_origins)) {
        MsanTrackOrigins = 1;
      } else if (A->getOption().matches(
                     options::OPT_fno_sanitize_memory_track_origins)) {
        MsanTrackOrigins = 0;
      } else {
        StringRef S = A->getValue();
        if (S.getAsInteger(0, MsanTrackOrigins) || MsanTrackOrigins < 0 ||
            MsanTrackOrigins > 2) {
          D.Diag(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
        }
      }
    }
  }

  if (NeedsAsan) {
    AsanSharedRuntime =
        Args.hasArg(options::OPT_shared_libasan) ||
        (TC.getTriple().getEnvironment() == llvm::Triple::Android);
    AsanZeroBaseShadow =
        (TC.getTriple().getEnvironment() == llvm::Triple::Android);
  }

  // Parse -link-cxx-sanitizer flag.
  LinkCXXRuntimes =
      Args.hasArg(options::OPT_fsanitize_link_cxx_runtime) || D.CCCIsCXX();
}

void SanitizerArgs::addArgs(const llvm::opt::ArgList &Args,
                            llvm::opt::ArgStringList &CmdArgs) const {
  if (!Kind)
    return;
  SmallString<256> SanitizeOpt("-fsanitize=");
#define SANITIZER(NAME, ID) \
  if (Kind & ID) \
    SanitizeOpt += NAME ",";
#include "clang/Basic/Sanitizers.def"
  SanitizeOpt.pop_back();
  CmdArgs.push_back(Args.MakeArgString(SanitizeOpt));
  if (!BlacklistFile.empty()) {
    SmallString<64> BlacklistOpt("-fsanitize-blacklist=");
    BlacklistOpt += BlacklistFile;
    CmdArgs.push_back(Args.MakeArgString(BlacklistOpt));
  }

  if (MsanTrackOrigins)
    CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-track-origins=" +
                                         llvm::utostr(MsanTrackOrigins)));

  // Workaround for PR16386.
  if (needsMsanRt())
    CmdArgs.push_back(Args.MakeArgString("-fno-assume-sane-operator-new"));
}

unsigned SanitizerArgs::parse(const char *Value) {
  unsigned ParsedKind = llvm::StringSwitch<SanitizeKind>(Value)
#define SANITIZER(NAME, ID) .Case(NAME, ID)
#define SANITIZER_GROUP(NAME, ID, ALIAS) .Case(NAME, ID##Group)
#include "clang/Basic/Sanitizers.def"
    .Default(SanitizeKind());
  return ParsedKind;
}

unsigned SanitizerArgs::expandGroups(unsigned Kinds) {
#define SANITIZER(NAME, ID)
#define SANITIZER_GROUP(NAME, ID, ALIAS) if (Kinds & ID##Group) Kinds |= ID;
#include "clang/Basic/Sanitizers.def"
  return Kinds;
}

void SanitizerArgs::filterUnsupportedMask(const ToolChain &TC, unsigned &Kinds,
                                          unsigned Mask,
                                          const llvm::opt::ArgList &Args,
                                          const llvm::opt::Arg *A,
                                          bool DiagnoseErrors,
                                          unsigned &DiagnosedKinds) {
  unsigned MaskedKinds = Kinds & Mask;
  if (!MaskedKinds)
    return;
  Kinds &= ~Mask;
  // Do we have new kinds to diagnose?
  if (DiagnoseErrors && (DiagnosedKinds & MaskedKinds) != MaskedKinds) {
    // Only diagnose the new kinds.
    std::string Desc =
        describeSanitizeArg(Args, A, MaskedKinds & ~DiagnosedKinds);
    TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
        << Desc << TC.getTriple().str();
    DiagnosedKinds |= MaskedKinds;
  }
}

unsigned SanitizerArgs::filterUnsupportedKinds(const ToolChain &TC,
                                               unsigned Kinds,
                                               const llvm::opt::ArgList &Args,
                                               const llvm::opt::Arg *A,
                                               bool DiagnoseErrors,
                                               unsigned &DiagnosedKinds) {
  bool IsLinux = TC.getTriple().getOS() == llvm::Triple::Linux;
  bool IsX86 = TC.getTriple().getArch() == llvm::Triple::x86;
  bool IsX86_64 = TC.getTriple().getArch() == llvm::Triple::x86_64;
  if (!(IsLinux && IsX86_64)) {
    filterUnsupportedMask(TC, Kinds, Thread | Memory | DataFlow, Args, A,
                          DiagnoseErrors, DiagnosedKinds);
  }
  if (!(IsLinux && (IsX86 || IsX86_64))) {
    filterUnsupportedMask(TC, Kinds, Function, Args, A, DiagnoseErrors,
                          DiagnosedKinds);
  }
  return Kinds;
}

unsigned SanitizerArgs::parse(const Driver &D, const llvm::opt::Arg *A,
                              bool DiagnoseErrors) {
  unsigned Kind = 0;
  for (unsigned I = 0, N = A->getNumValues(); I != N; ++I) {
    if (unsigned K = parse(A->getValue(I)))
      Kind |= K;
    else if (DiagnoseErrors)
      D.Diag(diag::err_drv_unsupported_option_argument)
        << A->getOption().getName() << A->getValue(I);
  }
  return Kind;
}

bool SanitizerArgs::parse(const Driver &D, const llvm::opt::ArgList &Args,
                          const llvm::opt::Arg *A, unsigned &Add,
                          unsigned &Remove, bool DiagnoseErrors) {
  Add = 0;
  Remove = 0;
  if (A->getOption().matches(options::OPT_fsanitize_EQ)) {
    Add = parse(D, A, DiagnoseErrors);
  } else if (A->getOption().matches(options::OPT_fno_sanitize_EQ)) {
    Remove = parse(D, A, DiagnoseErrors);
  } else {
    // Flag is not relevant to sanitizers.
    return false;
  }
  return true;
}

std::string SanitizerArgs::lastArgumentForKind(const Driver &D,
                                               const llvm::opt::ArgList &Args,
                                               unsigned Kind) {
  for (llvm::opt::ArgList::const_reverse_iterator I = Args.rbegin(),
                                                  E = Args.rend();
       I != E; ++I) {
    unsigned Add, Remove;
    if (parse(D, Args, *I, Add, Remove, false) &&
        (expandGroups(Add) & Kind))
      return describeSanitizeArg(Args, *I, Kind);
    Kind &= ~Remove;
  }
  llvm_unreachable("arg list didn't provide expected value");
}

std::string SanitizerArgs::describeSanitizeArg(const llvm::opt::ArgList &Args,
                                               const llvm::opt::Arg *A,
                                               unsigned Mask) {
  if (!A->getOption().matches(options::OPT_fsanitize_EQ))
    return A->getAsString(Args);

  std::string Sanitizers;
  for (unsigned I = 0, N = A->getNumValues(); I != N; ++I) {
    if (expandGroups(parse(A->getValue(I))) & Mask) {
      if (!Sanitizers.empty())
        Sanitizers += ",";
      Sanitizers += A->getValue(I);
    }
  }

  assert(!Sanitizers.empty() && "arg didn't provide expected value");
  return "-fsanitize=" + Sanitizers;
}

bool SanitizerArgs::getDefaultBlacklistForKind(const Driver &D, unsigned Kind,
                                               std::string &BLPath) {
  const char *BlacklistFile = nullptr;
  if (Kind & NeedsAsanRt)
    BlacklistFile = "asan_blacklist.txt";
  else if (Kind & NeedsMsanRt)
    BlacklistFile = "msan_blacklist.txt";
  else if (Kind & NeedsTsanRt)
    BlacklistFile = "tsan_blacklist.txt";
  else if (Kind & NeedsDfsanRt)
    BlacklistFile = "dfsan_abilist.txt";

  if (BlacklistFile) {
    SmallString<64> Path(D.ResourceDir);
    llvm::sys::path::append(Path, BlacklistFile);
    BLPath = Path.str();
    return true;
  }
  return false;
}
@


1.1.1.4.4.1
log
@file SanitizerArgs.cpp was added on branch yamt-pagecache on 2014-05-22 16:18:27 +0000
@
text
@d1 371
@


1.1.1.4.4.2
log
@sync with head.

for a reference, the tree before this commit was tagged
as yamt-pagecache-tag8.

this commit was splitted into small chunks to avoid
a limitation of cvs.  ("Protocol error: too many arguments")
@
text
@a0 371
//===--- SanitizerArgs.cpp - Arguments for sanitizer tools  ---------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Driver/SanitizerArgs.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Options.h"
#include "clang/Driver/ToolChain.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Transforms/Utils/SpecialCaseList.h"

using namespace clang::driver;
using namespace llvm::opt;

void SanitizerArgs::clear() {
  Kind = 0;
  BlacklistFile = "";
  MsanTrackOrigins = false;
  AsanZeroBaseShadow = false;
  UbsanTrapOnError = false;
}

SanitizerArgs::SanitizerArgs() {
  clear();
}

SanitizerArgs::SanitizerArgs(const ToolChain &TC,
                             const llvm::opt::ArgList &Args) {
  clear();
  unsigned AllAdd = 0;  // All kinds of sanitizers that were turned on
                        // at least once (possibly, disabled further).
  unsigned AllRemove = 0;  // During the loop below, the accumulated set of
                           // sanitizers disabled by the current sanitizer
                           // argument or any argument after it.
  unsigned DiagnosedKinds = 0;  // All Kinds we have diagnosed up to now.
                                // Used to deduplicate diagnostics.
  const Driver &D = TC.getDriver();
  for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend();
       I != E; ++I) {
    unsigned Add, Remove;
    if (!parse(D, Args, *I, Add, Remove, true))
      continue;
    (*I)->claim();

    AllAdd |= expandGroups(Add);
    AllRemove |= expandGroups(Remove);

    // Avoid diagnosing any sanitizer which is disabled later.
    Add &= ~AllRemove;
    // At this point we have not expanded groups, so any unsupported sanitizers
    // in Add are those which have been explicitly enabled. Diagnose them.
    Add = filterUnsupportedKinds(TC, Add, Args, *I, /*DiagnoseErrors=*/true,
                                 DiagnosedKinds);
    Add = expandGroups(Add);
    // Group expansion may have enabled a sanitizer which is disabled later.
    Add &= ~AllRemove;
    // Silently discard any unsupported sanitizers implicitly enabled through
    // group expansion.
    Add = filterUnsupportedKinds(TC, Add, Args, *I, /*DiagnoseErrors=*/false,
                                 DiagnosedKinds);

    Kind |= Add;
  }

  UbsanTrapOnError =
    Args.hasArg(options::OPT_fcatch_undefined_behavior) ||
    Args.hasFlag(options::OPT_fsanitize_undefined_trap_on_error,
                 options::OPT_fno_sanitize_undefined_trap_on_error, false);

  if (Args.hasArg(options::OPT_fcatch_undefined_behavior) &&
      !Args.hasFlag(options::OPT_fsanitize_undefined_trap_on_error,
                    options::OPT_fno_sanitize_undefined_trap_on_error, true)) {
    D.Diag(diag::err_drv_argument_not_allowed_with)
      << "-fcatch-undefined-behavior"
      << "-fno-sanitize-undefined-trap-on-error";
  }

  // Warn about undefined sanitizer options that require runtime support.
  if (UbsanTrapOnError && notAllowedWithTrap()) {
    if (Args.hasArg(options::OPT_fcatch_undefined_behavior))
      D.Diag(diag::err_drv_argument_not_allowed_with)
        << lastArgumentForKind(D, Args, NotAllowedWithTrap)
        << "-fcatch-undefined-behavior";
    else if (Args.hasFlag(options::OPT_fsanitize_undefined_trap_on_error,
                          options::OPT_fno_sanitize_undefined_trap_on_error,
                          false))
      D.Diag(diag::err_drv_argument_not_allowed_with)
        << lastArgumentForKind(D, Args, NotAllowedWithTrap)
        << "-fsanitize-undefined-trap-on-error";
  }

  // Only one runtime library can be used at once.
  bool NeedsAsan = needsAsanRt();
  bool NeedsTsan = needsTsanRt();
  bool NeedsMsan = needsMsanRt();
  bool NeedsLsan = needsLeakDetection();
  if (NeedsAsan && NeedsTsan)
    D.Diag(diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, NeedsAsanRt)
      << lastArgumentForKind(D, Args, NeedsTsanRt);
  if (NeedsAsan && NeedsMsan)
    D.Diag(diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, NeedsAsanRt)
      << lastArgumentForKind(D, Args, NeedsMsanRt);
  if (NeedsTsan && NeedsMsan)
    D.Diag(diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, NeedsTsanRt)
      << lastArgumentForKind(D, Args, NeedsMsanRt);
  if (NeedsLsan && NeedsTsan)
    D.Diag(diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, NeedsLeakDetection)
      << lastArgumentForKind(D, Args, NeedsTsanRt);
  if (NeedsLsan && NeedsMsan)
    D.Diag(diag::err_drv_argument_not_allowed_with)
      << lastArgumentForKind(D, Args, NeedsLeakDetection)
      << lastArgumentForKind(D, Args, NeedsMsanRt);
  // FIXME: Currently -fsanitize=leak is silently ignored in the presence of
  // -fsanitize=address. Perhaps it should print an error, or perhaps
  // -f(-no)sanitize=leak should change whether leak detection is enabled by
  // default in ASan?

  // If -fsanitize contains extra features of ASan, it should also
  // explicitly contain -fsanitize=address (probably, turned off later in the
  // command line).
  if ((Kind & AddressFull) != 0 && (AllAdd & Address) == 0)
    D.Diag(diag::warn_drv_unused_sanitizer)
     << lastArgumentForKind(D, Args, AddressFull)
     << "-fsanitize=address";

  // Parse -f(no-)sanitize-blacklist options.
  if (Arg *BLArg = Args.getLastArg(options::OPT_fsanitize_blacklist,
                                   options::OPT_fno_sanitize_blacklist)) {
    if (BLArg->getOption().matches(options::OPT_fsanitize_blacklist)) {
      std::string BLPath = BLArg->getValue();
      if (llvm::sys::fs::exists(BLPath)) {
        // Validate the blacklist format.
        std::string BLError;
        llvm::OwningPtr<llvm::SpecialCaseList> SCL(
            llvm::SpecialCaseList::create(BLPath, BLError));
        if (!SCL.get())
          D.Diag(diag::err_drv_malformed_sanitizer_blacklist) << BLError;
        else
          BlacklistFile = BLPath;
      } else {
        D.Diag(diag::err_drv_no_such_file) << BLPath;
      }
    }
  } else {
    // If no -fsanitize-blacklist option is specified, try to look up for
    // blacklist in the resource directory.
    std::string BLPath;
    if (getDefaultBlacklistForKind(D, Kind, BLPath) &&
        llvm::sys::fs::exists(BLPath))
      BlacklistFile = BLPath;
  }

  // Parse -f(no-)sanitize-memory-track-origins options.
  if (NeedsMsan)
    MsanTrackOrigins =
      Args.hasFlag(options::OPT_fsanitize_memory_track_origins,
                   options::OPT_fno_sanitize_memory_track_origins,
                   /* Default */false);
  if (NeedsAsan)
    AsanZeroBaseShadow =
        (TC.getTriple().getEnvironment() == llvm::Triple::Android);
}

void SanitizerArgs::addArgs(const llvm::opt::ArgList &Args,
                            llvm::opt::ArgStringList &CmdArgs) const {
  if (!Kind)
    return;
  SmallString<256> SanitizeOpt("-fsanitize=");
#define SANITIZER(NAME, ID) \
  if (Kind & ID) \
    SanitizeOpt += NAME ",";
#include "clang/Basic/Sanitizers.def"
  SanitizeOpt.pop_back();
  CmdArgs.push_back(Args.MakeArgString(SanitizeOpt));
  if (!BlacklistFile.empty()) {
    SmallString<64> BlacklistOpt("-fsanitize-blacklist=");
    BlacklistOpt += BlacklistFile;
    CmdArgs.push_back(Args.MakeArgString(BlacklistOpt));
  }

  if (MsanTrackOrigins)
    CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-track-origins"));

  // Workaround for PR16386.
  if (needsMsanRt())
    CmdArgs.push_back(Args.MakeArgString("-fno-assume-sane-operator-new"));
}

unsigned SanitizerArgs::parse(const char *Value) {
  unsigned ParsedKind = llvm::StringSwitch<SanitizeKind>(Value)
#define SANITIZER(NAME, ID) .Case(NAME, ID)
#define SANITIZER_GROUP(NAME, ID, ALIAS) .Case(NAME, ID##Group)
#include "clang/Basic/Sanitizers.def"
    .Default(SanitizeKind());
  // Assume -fsanitize=address implies -fsanitize=init-order,use-after-return.
  // FIXME: This should be either specified in Sanitizers.def, or go away when
  // we get rid of "-fsanitize=init-order,use-after-return" flags at all.
  if (ParsedKind & Address)
    ParsedKind |= InitOrder | UseAfterReturn;
  return ParsedKind;
}

unsigned SanitizerArgs::expandGroups(unsigned Kinds) {
#define SANITIZER(NAME, ID)
#define SANITIZER_GROUP(NAME, ID, ALIAS) if (Kinds & ID##Group) Kinds |= ID;
#include "clang/Basic/Sanitizers.def"
  return Kinds;
}

void SanitizerArgs::filterUnsupportedMask(const ToolChain &TC, unsigned &Kinds,
                                          unsigned Mask,
                                          const llvm::opt::ArgList &Args,
                                          const llvm::opt::Arg *A,
                                          bool DiagnoseErrors,
                                          unsigned &DiagnosedKinds) {
  unsigned MaskedKinds = Kinds & Mask;
  if (!MaskedKinds)
    return;
  Kinds &= ~Mask;
  // Do we have new kinds to diagnose?
  if (DiagnoseErrors && (DiagnosedKinds & MaskedKinds) != MaskedKinds) {
    // Only diagnose the new kinds.
    std::string Desc =
        describeSanitizeArg(Args, A, MaskedKinds & ~DiagnosedKinds);
    TC.getDriver().Diag(diag::err_drv_unsupported_opt_for_target)
        << Desc << TC.getTriple().str();
    DiagnosedKinds |= MaskedKinds;
  }
}

unsigned SanitizerArgs::filterUnsupportedKinds(const ToolChain &TC,
                                               unsigned Kinds,
                                               const llvm::opt::ArgList &Args,
                                               const llvm::opt::Arg *A,
                                               bool DiagnoseErrors,
                                               unsigned &DiagnosedKinds) {
  bool IsLinux = TC.getTriple().getOS() == llvm::Triple::Linux;
  bool IsX86 = TC.getTriple().getArch() == llvm::Triple::x86;
  bool IsX86_64 = TC.getTriple().getArch() == llvm::Triple::x86_64;
  if (!(IsLinux && IsX86_64)) {
    filterUnsupportedMask(TC, Kinds, Thread | Memory | DataFlow, Args, A,
                          DiagnoseErrors, DiagnosedKinds);
  }
  if (!(IsLinux && (IsX86 || IsX86_64))) {
    filterUnsupportedMask(TC, Kinds, Function, Args, A, DiagnoseErrors,
                          DiagnosedKinds);
  }
  return Kinds;
}

unsigned SanitizerArgs::parse(const Driver &D, const llvm::opt::Arg *A,
                              bool DiagnoseErrors) {
  unsigned Kind = 0;
  for (unsigned I = 0, N = A->getNumValues(); I != N; ++I) {
    if (unsigned K = parse(A->getValue(I)))
      Kind |= K;
    else if (DiagnoseErrors)
      D.Diag(diag::err_drv_unsupported_option_argument)
        << A->getOption().getName() << A->getValue(I);
  }
  return Kind;
}

bool SanitizerArgs::parse(const Driver &D, const llvm::opt::ArgList &Args,
                          const llvm::opt::Arg *A, unsigned &Add,
                          unsigned &Remove, bool DiagnoseErrors) {
  Add = 0;
  Remove = 0;
  const char *DeprecatedReplacement = 0;
  if (A->getOption().matches(options::OPT_faddress_sanitizer)) {
    Add = Address;
    DeprecatedReplacement = "-fsanitize=address";
  } else if (A->getOption().matches(options::OPT_fno_address_sanitizer)) {
    Remove = Address;
    DeprecatedReplacement = "-fno-sanitize=address";
  } else if (A->getOption().matches(options::OPT_fthread_sanitizer)) {
    Add = Thread;
    DeprecatedReplacement = "-fsanitize=thread";
  } else if (A->getOption().matches(options::OPT_fno_thread_sanitizer)) {
    Remove = Thread;
    DeprecatedReplacement = "-fno-sanitize=thread";
  } else if (A->getOption().matches(options::OPT_fcatch_undefined_behavior)) {
    Add = UndefinedTrap;
    DeprecatedReplacement =
      "-fsanitize=undefined-trap -fsanitize-undefined-trap-on-error";
  } else if (A->getOption().matches(options::OPT_fbounds_checking) ||
             A->getOption().matches(options::OPT_fbounds_checking_EQ)) {
    Add = LocalBounds;
    DeprecatedReplacement = "-fsanitize=local-bounds";
  } else if (A->getOption().matches(options::OPT_fsanitize_EQ)) {
    Add = parse(D, A, DiagnoseErrors);
  } else if (A->getOption().matches(options::OPT_fno_sanitize_EQ)) {
    Remove = parse(D, A, DiagnoseErrors);
  } else {
    // Flag is not relevant to sanitizers.
    return false;
  }
  // If this is a deprecated synonym, produce a warning directing users
  // towards the new spelling.
  if (DeprecatedReplacement && DiagnoseErrors)
    D.Diag(diag::warn_drv_deprecated_arg)
      << A->getAsString(Args) << DeprecatedReplacement;
  return true;
}

std::string SanitizerArgs::lastArgumentForKind(const Driver &D,
                                               const llvm::opt::ArgList &Args,
                                               unsigned Kind) {
  for (llvm::opt::ArgList::const_reverse_iterator I = Args.rbegin(),
                                                  E = Args.rend();
       I != E; ++I) {
    unsigned Add, Remove;
    if (parse(D, Args, *I, Add, Remove, false) &&
        (expandGroups(Add) & Kind))
      return describeSanitizeArg(Args, *I, Kind);
    Kind &= ~Remove;
  }
  llvm_unreachable("arg list didn't provide expected value");
}

std::string SanitizerArgs::describeSanitizeArg(const llvm::opt::ArgList &Args,
                                               const llvm::opt::Arg *A,
                                               unsigned Mask) {
  if (!A->getOption().matches(options::OPT_fsanitize_EQ))
    return A->getAsString(Args);

  std::string Sanitizers;
  for (unsigned I = 0, N = A->getNumValues(); I != N; ++I) {
    if (expandGroups(parse(A->getValue(I))) & Mask) {
      if (!Sanitizers.empty())
        Sanitizers += ",";
      Sanitizers += A->getValue(I);
    }
  }

  assert(!Sanitizers.empty() && "arg didn't provide expected value");
  return "-fsanitize=" + Sanitizers;
}

bool SanitizerArgs::getDefaultBlacklistForKind(const Driver &D, unsigned Kind,
                                               std::string &BLPath) {
  const char *BlacklistFile = 0;
  if (Kind & NeedsAsanRt)
    BlacklistFile = "asan_blacklist.txt";
  else if (Kind & NeedsMsanRt)
    BlacklistFile = "msan_blacklist.txt";
  else if (Kind & NeedsTsanRt)
    BlacklistFile = "tsan_blacklist.txt";
  else if (Kind & NeedsDfsanRt)
    BlacklistFile = "dfsan_abilist.txt";

  if (BlacklistFile) {
    SmallString<64> Path(D.ResourceDir);
    llvm::sys::path::append(Path, BlacklistFile);
    BLPath = Path.str();
    return true;
  }
  return false;
}
@


