# Copyright 2015 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import("//build/config/cast.gni")
import("//build/config/chrome_build.gni")
import("//build/config/chromeos/args.gni")
import("//build/config/profiling/profiling.gni")
import("//build/toolchain/toolchain.gni")

declare_args() {
  # Compile for Address Sanitizer to find memory bugs.
  is_asan = false

  # Compile for Hardware-Assisted Address Sanitizer to find memory bugs
  # (android/arm64 only).
  # See http://clang.llvm.org/docs/HardwareAssistedAddressSanitizerDesign.html
  is_hwasan = false

  # Compile for Leak Sanitizer to find leaks.
  is_lsan = false

  # Compile for Memory Sanitizer to find uninitialized reads.
  is_msan = false

  # Compile for Thread Sanitizer to find threading bugs.
  is_tsan = false

  # Compile for Undefined Behaviour Sanitizer to find various types of
  # undefined behaviour (excludes vptr checks).
  is_ubsan = false

  # Halt the program if a problem is detected.
  is_ubsan_no_recover = false

  # Track where uninitialized memory originates from. From fastest to slowest:
  # 0 - no tracking, 1 - track only the initial allocation site, 2 - track the
  # chain of stores leading from allocation site to use site.
  msan_track_origins = 2

  # Enables "param-retval" mode, which finds more uses of uninitialized data and
  # reduces code size. Behind a flag as there are a number of previously
  # undetected violations that still need to be fixed.
  # TODO(crbug.com/40240570): Default this to true and remove.
  msan_eager_checks = true

  # TODO(crbug.com/40222690): Enable everywhere.
  msan_check_use_after_dtor = is_linux

  # Use dynamic libraries instrumented by one of the sanitizers instead of the
  # standard system libraries. Set this flag to build the libraries from source.
  use_locally_built_instrumented_libraries = false

  # Compile with Control Flow Integrity to protect virtual calls and casts.
  # See http://clang.llvm.org/docs/ControlFlowIntegrity.html
  #
  # TODO(pcc): Remove this flag if/when CFI is enabled in all official builds.
  is_cfi = is_official_build && is_clang &&
           ((target_os == "linux" && target_cpu == "x64") ||
            (is_chromeos && is_chromeos_device))

  # Enable checks for indirect function calls via a function pointer.
  # TODO(pcc): remove this when we're ready to add these checks by default.
  # https://crbug.com/701919
  use_cfi_icall =
      target_os == "linux" && target_cpu == "x64" && is_official_build

  # Print detailed diagnostics when Control Flow Integrity detects a violation.
  use_cfi_diag = false

  # Let Control Flow Integrity continue execution instead of crashing when
  # printing diagnostics (use_cfi_diag = true).
  use_cfi_recover = false

  # Compile for fuzzing with LLVM LibFuzzer.
  # See http://www.chromium.org/developers/testing/libfuzzer
  use_libfuzzer = false

  # Compile for fuzzing with centipede.
  # See https://github.com/google/centipede
  use_centipede = false

  # Compile for fuzzing with Fuzzilli.
  use_chromium_fuzzilli = false

  # Compile for fuzzing with an external engine (e.g., Grammarinator).
  use_external_fuzzing_engine = false

  # Enables core ubsan security features. Will later be removed once it matches
  # is_ubsan.
  is_ubsan_security = false

  # Helper variable for testing builds with disabled libfuzzer.
  # Not for client use.
  disable_libfuzzer = false

  # Value for -fsanitize-coverage flag. Setting this causes
  # use_sanitizer_coverage to be enabled.
  # This flag is not used for libFuzzer (use_libfuzzer=true). Instead, we use:
  #     -fsanitize=fuzzer-no-link
  # Default value when unset and use_fuzzing_engine=true:
  #     trace-pc-guard
  # Default value when unset and use_sanitizer_coverage=true:
  #     trace-pc-guard,indirect-calls
  sanitizer_coverage_flags = ""

  # A sanitizer coverage allowlist, specifying exactly which
  # files or symbol names should be instrumented, rather than all of them.
  sanitizer_coverage_allowlist = ""

  # A sanitizer coverage ignorelist, specifying which files or symbol names
  # should be excluded from coverage instrumentation (mostly for performance
  # reasons).
  sanitizer_coverage_ignorelist = ""

  # When enabled, only relevant sanitizer defines are set, but compilation
  # happens with no extra flags. This is useful when in component build
  # enabling sanitizers only in some of the components.
  use_sanitizer_configs_without_instrumentation = false

  # When true, seed corpora archives are built.
  archive_seed_corpus = true

  # When true, only builds fuzzer targets that require high end machines to run.
  # Otherwise, builds all the targets.
  # TODO(paulsemel): once we have everything implemented on the recipe side, we
  # can change the behaviour for the false case, and only build the non high-end
  # jobs, so that they do not appear in the zip. As for now, this behaviour
  # ensures nothing breaks.
  high_end_fuzzer_targets = false
}

declare_args() {
  # Enable checks for bad casts: derived cast and unrelated cast.
  # TODO(krasin): remove this, when we're ready to add these checks by default.
  # https://crbug.com/626794
  use_cfi_cast = is_cfi && is_chromeos

  # Compile for Undefined Behaviour Sanitizer's vptr checks.
  is_ubsan_vptr = is_ubsan_security || is_ubsan

  # Use dynamic libraries instrumented by MemorySanitizer (MSan) instead of the
  # standard system libraries. Prebuilt instrumented libraries are required on
  # Linux desktop and linux-chromeos (simulation) test builds to prevent false
  # positives from uninstrumented host system libraries.
  # ChromeOS device builds compile system dependencies with MSan in the target
  # sysroot and do not use these prebuilt Ubuntu libraries.
  use_prebuilt_instrumented_libraries =
      is_msan && current_cpu == "x64" &&
      (is_linux || (is_chromeos && !is_chromeos_device))
}

# Whether we are doing a fuzzer build. Prefer this over "use_libfuzzer" as it
# is engine-agnostic.
use_fuzzing_engine = use_libfuzzer || use_centipede ||
                     use_external_fuzzing_engine || use_chromium_fuzzilli

# Whether any UBSan subset is enabled.
# TODO(crbug.com/40248746): Unify these under a single UBSan option.
is_ubsan_any = is_ubsan || is_ubsan_vptr || is_ubsan_security

declare_args() {
  # Builds fuzztest test executables such that they support the
  # --fuzz= argument, which requires some sanitizer coverage.
  # We want to enable this only when we're *NOT* using a fuzzing
  # engine such as libfuzzer or centipede. It's generally a
  # useful option, but it requires sanitizer coverage, and that
  # could conceivably disrupt normal unit testing workflows, so we'll
  # enable it by default only in sanitizer builds.
  # Also be sure not to enable this on non-Chromium builds where
  # the required //third_party/fuzztest dependency may be absent.
  # TODO(crbug.com/40286621): enable on component builds
  enable_fuzztest_fuzz =
      !(use_libfuzzer || use_centipede || use_external_fuzzing_engine ||
        use_chromium_fuzzilli) &&
      (is_asan || is_hwasan || is_lsan || is_tsan || is_msan || is_ubsan_any) &&
      !is_component_build && is_linux && build_with_chromium

  # Whether FUZZ_TESTs should be registered as gtests in Chromium's mainstream
  # test suites. This will cause the to run for 1 second in normal testing
  # environments such as CI. Within Chromium, we want to do this only on
  # platforms where we have ClusterFuzz support (Windows, Mac, Linux) because
  # we want ClusterFuzz to find the majority of problems rather than CI.
  # This gn arg is typically respected by general-purpose test suite
  # initialization code; targets created specifically for fuzztests alone
  # would not normally be disabled by a setting of 'false' here.
  register_fuzztests_in_test_suites =
      is_linux || is_mac || is_win || use_libfuzzer || use_centipede ||
      use_external_fuzzing_engine
}

declare_args() {
  use_sanitizer_coverage =
      !use_clang_coverage && (use_fuzzing_engine || enable_fuzztest_fuzz ||
                              sanitizer_coverage_flags != "")
}

assert(!is_hwasan || (target_os == "android" && target_cpu == "arm64"),
       "HWASan only supported on Android ARM64 builds.")

if (is_asan && target_os == "android") {
  print(
      "Warning: is_asan is no longer supported on Android. It might work, but you'll probably have better luck with is_hwasan=true (which requires arm64). https://crbug.com/441905843")
}

assert(
    !(enable_fuzztest_fuzz && use_libfuzzer),
    "Can't specify enable_fuzztest_fuzz and use_libfuzzer. When libfuzzer is enabled, fuzztest executables automatically support --fuzz but provide output that's libfuzzer compatible.")

assert(
    !(enable_fuzztest_fuzz && use_centipede),
    "Can't specify enable_fuzztest_fuzz and use_centipede. The same binaries are built in a different mode to add centipede support.")

assert(
    !(enable_fuzztest_fuzz && is_component_build),
    "Can't specify enable_fuzztest_fuzz in component builds; fuzztest doesn't yet support it. Consider using use_libfuzzer=true instead which provides superficially similar functionality.")

# Disable sanitizers for non-target toolchains, and for the toolchain using
# the prebuilt Rust stdlib which has no sanitizer support with it.
if (!is_a_target_toolchain || toolchain_for_rust_host_build_tools) {
  is_asan = false
  is_cfi = false
  is_hwasan = false
  is_lsan = false
  is_msan = false
  is_tsan = false
  is_ubsan = false
  is_ubsan_no_recover = false
  is_ubsan_security = false
  is_ubsan_vptr = false
  is_ubsan_any = false
  msan_track_origins = 0
  sanitizer_coverage_flags = ""
  sanitizer_coverage_allowlist = ""
  sanitizer_coverage_ignorelist = ""
  use_centipede = false
  use_cfi_diag = false
  use_cfi_recover = false
  use_libfuzzer = false
  use_locally_built_instrumented_libraries = false
  use_prebuilt_instrumented_libraries = false
  use_sanitizer_coverage = false
  enable_fuzztest_fuzz = false
} else if (current_cpu != "arm64") {
  is_hwasan = false
}

# Whether we are linking against a sanitizer runtime library. Among other
# things, this changes the default symbol level and other settings in order to
# prepare to create stack traces "live" using the sanitizer runtime.
using_sanitizer = is_asan || is_hwasan || is_lsan || is_tsan || is_msan ||
                  is_ubsan_any || use_sanitizer_coverage || use_cfi_diag

# Whether the current fuzzing engine supports libprotobuf_mutator.
use_fuzzing_engine_with_lpm = use_libfuzzer || use_centipede

# Whether the fuzzing engine supports fuzzers which supply their own
# "main" function.
fuzzing_engine_supports_custom_main =
    use_libfuzzer || use_centipede || use_chromium_fuzzilli ||
    use_external_fuzzing_engine

# Args that are in turn dependent on other args must be in a separate
# declare_args block. User overrides are only applied at the end of a
# declare_args block.
declare_args() {
  # When true, sanitizer warnings will cause test case failures.
  fail_on_san_warnings = using_sanitizer

  # Generates an owners file for each fuzzer test.
  # TODO(crbug.com/40175535): Remove this arg when finding OWNERS is faster.
  generate_fuzzer_owners = use_fuzzing_engine

  # https://crbug.com/1002058: Code coverage works inside the sandbox via the
  # help of several helper IPCs. Unfortunately, the sandbox-only path does not
  # work well for fuzzing builds. Since fuzzing builds already disable the
  # sandbox when dumping coverage, limit the sandbox-only path to non-fuzzing
  # builds.
  # Everything is IPC on Fuchsia, so this workaround for code coverage inside
  # the sandbox does not apply.
  use_clang_profiling_inside_sandbox =
      use_clang_profiling && !use_fuzzing_engine && !is_fuchsia

  # These are set for some non-host toolchains which require running a binary
  # built for the host toolchain with MSan in a non-host toolchain context.
  host_toolchain_is_msan = is_msan && use_prebuilt_instrumented_libraries
  host_toolchain_msan_track_origins = msan_track_origins
}

if (sanitizer_coverage_flags == "") {
  if (enable_fuzztest_fuzz) {
    # ./fuzztest_executable --fuzz=
    # requires only this single type of coverage
    sanitizer_coverage_flags = "inline-8bit-counters"
  } else if (use_fuzzing_engine) {
    sanitizer_coverage_flags = "trace-pc-guard"
    if (use_centipede) {
      # Centipede's minimal flags are listed in
      # //third_party/fuzztest/src/centipede/clang-flags.txt. But, for users
      # like Chromium using an up-to-date clang, we can also enable extra
      # optional types of coverage which may make Centipede more effective. This
      # list is not currently documented and has been derived from discussion
      # with centipede creators (though one is warned about at
      # https://github.com/google/centipede/blob/main/centipede_callbacks.cc#L68)
      sanitizer_coverage_flags =
          sanitizer_coverage_flags + ",pc-table,trace-cmp,control-flow"
    }
  } else if (use_sanitizer_coverage) {
    sanitizer_coverage_flags = "trace-pc-guard,indirect-calls"
  }
}

assert(!using_sanitizer || is_clang,
       "Sanitizers (is_*san) require setting is_clang = true in 'gn args'")

assert(!is_cfi || is_clang,
       "is_cfi requires setting is_clang = true in 'gn args'")

prebuilt_instrumented_libraries_available =
    use_prebuilt_instrumented_libraries &&
    (msan_track_origins == 0 || msan_track_origins == 2)

if (use_fuzzing_engine && (is_linux || is_chromeos)) {
  if (is_asan) {
    # We do leak checking when fuzzing with ASan on Linux. Set is_lsan for code
    # that relies on LEAK_SANITIZER define to avoid false positives.
    is_lsan = true
  }
}

# MSan only links Chrome properly in release builds (brettw -- 9/1/2015). The
# same is possibly true for the other non-ASan sanitizers. But regardless of
# whether it links, one would normally never run a sanitizer in debug mode.
# Running in debug mode probably indicates you forgot to set the "is_debug =
# false" flag in the build args. ASan seems to run fine in debug mode.
#
# If you find a use-case where you want to compile a sanitizer in debug mode
# and have verified it works, ask brettw and we can consider removing it from
# this condition. We may also be able to find another way to enable your case
# without having people accidentally get broken builds by compiling an
# unsupported or unadvisable configurations.
#
# For one-off testing, just comment this assertion out.
assert(!is_debug || !(is_msan || is_ubsan || is_ubsan_vptr),
       "Sanitizers should generally be used in release (set is_debug=false).")

assert(!is_msan || ((is_linux || is_chromeos) && current_cpu == "x64"),
       "MSan currently only works on 64-bit Linux and ChromeOS builds.")

assert(!is_lsan || is_asan, "is_lsan = true requires is_asan = true also.")

# ASAN build on Windows is not working in debug mode. Intercepting memory
# allocation functions is hard on Windows and not yet implemented in LLVM.
assert(!is_win || !is_debug || !is_asan,
       "ASan on Windows doesn't work in debug (set is_debug=false).")

# libFuzzer targets can fail to build or behave incorrectly when built without
# ASAN on Windows.
assert(!is_win || !use_libfuzzer || is_asan,
       "use_libfuzzer on Windows requires setting is_asan = true")

# Make sure that if we recover on detection (i.e. not crash), diagnostics are
# printed.
assert(!use_cfi_recover || use_cfi_diag,
       "Only use CFI recovery together with diagnostics.")

# TODO(crbug.com/40534102): the use_sanitizer_coverage arg is currently
# not supported by the Chromium mac_clang_x64 toolchain on iOS distribution.
# The coverage works with iOS toolchain but it is broken when the mac
# toolchain is used as a secondary one on iOS distribution. E.g., it should be
# possible to build the "net" target for iOS with the sanitizer coverage
# enabled.
assert(
    !(use_sanitizer_coverage && is_mac && target_os == "ios"),
    "crbug.com/753445: use_sanitizer_coverage=true is not supported by the " +
        "Chromium mac_clang_x64 toolchain on iOS distribution. Please set " +
        "the argument value to false.")

declare_args() {
  # Skip instrumentation of standard library types and containers, and absl.
  # This is currently an experiment to evaluate performance improvements, see
  # https://crbug.com/476343968.
  sanitizer_coverage_skip_stdlib_and_absl = false
}

if (use_sanitizer_coverage && sanitizer_coverage_skip_stdlib_and_absl &&
    sanitizer_coverage_ignorelist == "") {
  sanitizer_coverage_ignorelist =
      "//build/config/sanitizers/ignorelist_stdlib_and_absl.txt"
}

assert(
    sanitizer_coverage_allowlist == "" || use_sanitizer_coverage,
    "Can't specify a sanitizer coverage allowlist without using sanitizer coverage.")

assert(
    sanitizer_coverage_ignorelist == "" || use_sanitizer_coverage,
    "Can't specify a sanitizer coverage ignorelist without using sanitizer coverage.")

# Use these lists of configs to disable instrumenting code that is part of a
# fuzzer, but which isn't being targeted (such as libprotobuf-mutator, *.pb.cc
# and libprotobuf when they are built as part of a proto fuzzer). Adding or
# removing these lists does not have any effect if use_fuzzing_engine is false.
not_fuzzed_remove_configs = []
not_fuzzed_add_configs = []

# It is usually OK to compile only certain parts of a binary with ASan. Usually,
# but not always :)
# The `needs_asan` variant can be used in such cases: it disables coverage and
# instrumentation to the extent possible, but leaves ASan enabled.
not_fuzzed_needs_asan_add_configs = []

if (use_fuzzing_engine) {
  # Remove coverage and sanitizer flags for "not fuzzed" targets.
  # Some might be added back via the "not_fuzzed*_add_configs" lists.
  not_fuzzed_remove_configs += [
    "//build/config/coverage:default_coverage",
    "//build/config/sanitizers:default_sanitizer_flags",
  ]

  # Always add the `not_fuzzed` config for "not fuzzed" targets, and explicitly
  # add sanitizer ldflags which are needed to link even partially-sanitized
  # binaries. Depending on asan / msan the ldflags might already be included
  # via the default_sanitizer_flags_but_coverage config, but it's fine to add
  # it explicitly here.
  not_fuzzed_add_configs += [
    "//build/config/sanitizers:not_fuzzed",
    "//build/config/sanitizers:default_sanitizer_ldflags",
  ]

  # If we are using MSan: Add back sanitizer instrumentation except for coverage
  # since binaries cannot be partially instrumented with MSan.
  if (is_msan) {
    not_fuzzed_add_configs +=
        [ "//build/config/sanitizers:default_sanitizer_flags_but_coverage" ]
  }

  not_fuzzed_needs_asan_add_configs = not_fuzzed_add_configs

  # For selected targets which need ASan instrumentation, do also add back
  # sanitizer flags except for coverage.
  if (is_asan && !is_msan) {
    not_fuzzed_needs_asan_add_configs +=
        [ "//build/config/sanitizers:default_sanitizer_flags_but_coverage" ]
  }

  if (is_asan && !is_msan) {
    assert(not_fuzzed_add_configs != not_fuzzed_needs_asan_add_configs)
  } else {
    assert(not_fuzzed_add_configs == not_fuzzed_needs_asan_add_configs)
  }
}

# Options common to different fuzzer engines.
# Engine should be compiled without coverage (infinite loop in trace_cmp).
fuzzing_engine_remove_configs = [
  "//build/config/coverage:default_coverage",
  "//build/config/sanitizers:default_sanitizer_flags",
]

# Add any sanitizer flags back. In MSAN builds, instrumenting libfuzzer with
# MSAN is necessary since all parts of the binary need to be instrumented for it
# to work. ASAN builds are more subtle: libfuzzer depends on features from the
# C++ STL. If it were not instrumented, templates would be insantiated without
# ASAN from libfuzzer and with ASAN in other TUs. The linker might merge
# instrumented template instantiations with non-instrumented ones (which could
# have a different ABI) in the final binary, which is problematic for TUs
# expecting one particular ABI (https://crbug.com/915422). The other sanitizers
# are added back for the same reason.
fuzzing_engine_add_configs =
    [ "//build/config/sanitizers:default_sanitizer_flags_but_coverage" ]

# Expose clang_rt dynamic lib name to the dependents that need it as an input
# when running an exeutable.
if ((is_apple || is_win) && (is_asan || is_ubsan_any)) {
  if (is_mac || (is_ios && target_environment == "catalyst")) {
    if (is_asan) {
      clang_rt_dso_path = "darwin/libclang_rt.asan_osx_dynamic.dylib"
    } else {
      assert(is_ubsan_any)
      clang_rt_dso_path = "darwin/libclang_rt.ubsan_osx_dynamic.dylib"
    }
  } else if (is_ios) {
    if (is_asan) {
      if (target_environment == "simulator") {
        clang_rt_dso_path = "darwin/libclang_rt.asan_iossim_dynamic.dylib"
      } else {
        clang_rt_dso_path = "darwin/libclang_rt.asan_ios_dynamic.dylib"
      }
    } else {
      assert(is_ubsan_any)
      clang_rt_dso_path = "darwin/libclang_rt.ubsan_iossim_dynamic.dylib"
    }
  } else if (is_win && current_cpu == "x64") {
    if (is_asan) {
      clang_rt_dso_path = "windows/clang_rt.asan_dynamic-x86_64.dll"
    } else {
      assert(is_ubsan_any)
      clang_rt_dso_path = "windows/clang_rt.ubsan_dynamic-x86_64.dll"
    }
  }

  clang_rt_dso = get_path_info(clang_rt_dso_path, "file")
}

# Adds hardening by way of UBSan instrumentation. No handling is
# provided: your target will crash when the undefined behavior is
# detected.
#
# It is a Chromium convention that GN target names use underscores. This
# template should be instantiated with a `foo_bar`, and the hyphenated
# `foo-bar` should be passed via the `sanitizer` argument.
#
# This takes three arguments:
# *   [required] `sanitizer`, which corresponds to the hyphenated
#     sanitizer name passed to `-fsanitize=`.
# *   [optional] `condition`, which gates the sanitizer in addition to
#     the two built-in conditions above.
# *   [optional] `cflags`, should you want any extra ones.
template("ubsan_hardening") {
  config("sanitize_${target_name}") {
    # When the config isn't activated (e.g. `is_ubsan = true`), the
    # `sanitizer` and `cflags` args will never be evaluated and GN will
    # error out. Mark them potentially unused to suppress this.
    not_needed(invoker,
               [
                 "sanitizer",
                 "cflags",
               ])

    # The target sanitizer is built when
    # *   the build is not already UBSan, which should be a superset of
    #     any single sanitizer we could use here,
    # *   the build is not for Wasm, which doesn't recognize any of
    #     these sanitizer flags (see https://crrev.com/c/7911761), and
    # *   the build is Clang, which provides the UBSan instrumentation.
    _condition = !is_ubsan && !is_wasm && is_clang
    if (defined(invoker.condition)) {
      _condition = invoker.condition && _condition
    }

    if (_condition) {
      cflags = [
        "-fsanitize=${invoker.sanitizer}",
        "-fsanitize-trap=${invoker.sanitizer}",

        # Prevents `__has_feature(undefined_behavior_sanitizer)`
        # from evaluating true. Configs defined here are intended to
        # be usable even in release builds, i.e. as widely as possible.
        # It's important not to have full-on UBSan workarounds activate
        # just because we built support for a specific sanitizer.
        "-fsanitize-ignore-for-ubsan-feature=${invoker.sanitizer}",
      ]
      if (defined(invoker.cflags)) {
        cflags += invoker.cflags
      }
    }
  }
}
