chromiumv8embedded-v8

In the chromium source code, why some boundary or type checks use DCHECK


Recently, I was studying chromium and v8 source code, and saw a lot of CHECK or DCHECK. Among them, many DCHECK are checks on parameter types, or bounds on arrays, and DCHECK are closed in the release version.

DCHECK(key->IsName() || key->IsNumber());    // Check for types
DCHECK(desc->is_empty());                    // Check for borderline conditions

Shouldn't it be better to use CHECK for boundary or type checks, which is still working in the release version? Or when choosing to use DCHECK or CHECK, are there any criteria? Because sometimes, the check that should be kept uses DCHECK

it confuses me alot, i don't know whether DCHECK or CHECK should be used


Solution

  • Both CHECK and DCHECK cause a crash when they fail, so they're not intended or suitable for handling situations that are expected to happen. Instead, they're meant to "double-check" or document invariants that are assumed to be guaranteed to be true. That's why most of the time, it's enough to execute these checks in Debug mode, to keep Release-mode binaries smaller and faster. Using Release-mode CHECKs is a rare exception: it mostly serves as an additional layer of defense in complicated code that has had security bugs before. If a CHECK (or DCHECK) is hit in practice, then that's always a bug that should be fixed as soon as it's found.

    The typical pattern is something like:

      if (!condition_holds()) {
        throw_error();
        return;
      }
      helper_function();
      ...
    
    void helper_function() {
      DCHECK(condition_holds());  // Callers have checked, no need to check again.
      ...
    }