Open Bug 2020856 Opened 8 months ago Updated 8 months ago

`mozilla-implicit-constructor` fires false positives for constructors annotated with `MOZ_IMPLICIT` in clang-tidy mode

Categories

(Developer Infrastructure :: Source Code Analysis, enhancement)

enhancement

Tracking

(Not tracked)

People

(Reporter: chunmin, Unassigned)

References

Details

Attachments

(1 file)

The following issue was detected by my Claude. TBH, my knowledge for clang plugin is insufficient to judge if this is true, but I do see there are several errors/warning like below when running ./mach static-analysis check dom/media/platforms/ffmpeg/FFmpegVideoEncoder.cpp

 4:04.21   405 |   MOZ_IMPLICIT Maybe(const Maybe<U>& aOther) {
 4:04.21       |                ^
 4:04.21       |                explicit

...

 4:04.21   123 |   MOZ_IMPLICIT RefPtr(already_AddRefed<I>&& aSmartPtr)
 4:04.21       |                ^
 4:04.21 /home/cm/Work/fix-static-analysis/obj-x86_64-pc-linux-gnu/dist/include/mozilla/RefPtr.h:123:16: note: consider adding the explicit keyword to the constructor
 4:04.21   123 |   MOZ_IMPLICIT RefPtr(already_AddRefed<I>&& aSmartPtr)
 4:04.21       |                ^
 4:04.21       |                explicit
 4:04.21 Warning: mozilla-implicit-constructor in mfbt/RefPtr.h: bad implicit conversion constructor for 'RefPtr'

...


mozilla-implicit-constructor fires false positives for constructors annotated with MOZ_IMPLICIT in clang-tidy mode. Affected types include RefPtr, nsCOMPtr, Span, nsTArray, StaticString, Handle, TimeRanges, and others.

Steps to Reproduce

Run ./mach static-analysis check on any file that transitively includes one of the affected headers. For example:

./mach static-analysis check dom/media/platforms/ffmpeg/FFmpegVideoEncoder.cpp

Expected Behavior

No errors for constructors already annotated with MOZ_IMPLICIT.

Actual Behavior

Errors of the form:

error: bad implicit conversion constructor for 'RefPtr' [mozilla-implicit-constructor]
  MOZ_IMPLICIT RefPtr(already_AddRefed<I>&& aSmartPtr)
               ^
note: consider adding the explicit keyword to the constructor

The same fires for Span, nsCOMPtr, nsTArray, StaticString, Handle, TimeRanges, etc.

Root Cause

Background: how GetAttributes works

The Mozilla clang plugin stores custom annotations (moz_implicit, moz_stack_class, moz_can_run_script, etc.) as __attribute__((annotate("..."))) on AST nodes. Because these annotations must be stripped before code generation, the plugin runs a pre-pass (CustomAttributesMatcher) that walks every decl, reads all annotations into an in-memory AttributesCache map (DenseMap<const Decl*, CustomAttributesSet>), and strips the AnnotateAttr nodes from the AST. Subsequent calls to GetAttributes(D) just do a cache lookup by Decl* pointer.

In clang-tidy mode (#ifdef CLANG_TIDY), this pre-pass does not run. Attributes are cached lazily on the first call to GetAttributes. This is where the bug lives.

Why template class constructors are affected

When a class template defines a constructor with MOZ_IMPLICIT:

template <typename T>
class RefPtr {
    MOZ_IMPLICIT RefPtr(already_AddRefed<T>&& ptr) { ... }
};

Clang creates one CXXConstructorDecl node for the template definition (CtorDef). When the compiler instantiates RefPtr<nsIRunnable>, it creates a new, separate CXXConstructorDecl node for the instantiation (CtorInst). These are different pointer values in the AST. Critically, MOZ_IMPLICIT — and thus the AnnotateAttr — is only on CtorDef. Clang does not propagate annotations from a template definition to its instantiations.

So in clang-tidy mode, when the ExplicitImplicitChecker matcher fires for CtorInst:

  1. isMarkedImplicit() calls GetAttributes(CtorInst)
  2. CtorInst->hasAttr<AnnotateAttr>() → false (annotation is on CtorDef, not CtorInst)
  3. AttributesCache.find(CtorInst) → not found (no pre-pass has run; CtorInst has never been cached)
  4. Returns empty → has_moz_implicit = false
  5. isMarkedImplicit() returns false → false positive

Why concrete classes like TimeRanges can also be affected

Even for a non-template class, GetAttributes can return empty if the Decl* pointer seen by the matcher differs from the pointer under which annotations were previously cached. This can happen when a constructor is encountered through a redeclaration or a different canonical form of the same decl (for example, when the parent class is a template specialization and clang creates multiple AST representations during instantiation). The compile_commands.json for a single .cpp file can contain many entries compiled with different defines; run-clang-tidy runs all of them in parallel, and the deduplicated output includes any location flagged by any single run.

Proposed Fix

GetAttributes in build/clang-plugin/CustomAttributes.cpp should fall back to related decls when a direct cache miss occurs:

  1. Canonical decl fallback: if D->getCanonicalDecl() != D, retry with the canonical decl. This handles redeclarations where the annotation was cached under a different pointer for the same logical declaration.

  2. Template instantiation pattern fallback: for a FunctionDecl that is a template instantiation, FD->getTemplateInstantiationPattern() returns the template definition. The annotation lives there. Recursively calling GetAttributes on the pattern finds it.

  } else {
    auto attributes = AttributesCache.find(D);
    if (attributes != AttributesCache.end()) {
      attrs = attributes->second;
    } else {
      const Decl *Canonical = D->getCanonicalDecl();
      if (Canonical != D) {
        attrs = GetAttributes(Canonical);
      } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
        if (const FunctionDecl *Pattern =
                FD->getTemplateInstantiationPattern()) {
          attrs = GetAttributes(Pattern);
        }
      }
    }
  }

Fixing GetAttributes is the right location because it is the single source of truth for all attribute lookups across the entire plugin. This automatically corrects isMarkedImplicit(), hasCanRunScriptAnnotation(), and every other attribute check without needing to modify individual checkers.

suggested fix by Claude

See Also: → 2020854
You need to log in before you can comment on or make changes to this bug.

Attachment

General

Created:
Updated:
Size: