1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "FindBadConstructsConsumer.h"
7 #include "clang/Frontend/CompilerInstance.h"
8 #include "clang/Lex/Lexer.h"
9 #include "llvm/Support/raw_ostream.h"
11 using namespace clang;
13 namespace chrome_checker {
17 const char kMethodRequiresOverride[] =
18 "[chromium-style] Overriding method must be marked with OVERRIDE.";
19 const char kMethodRequiresVirtual[] =
20 "[chromium-style] Overriding method must have \"virtual\" keyword.";
21 const char kNoExplicitDtor[] =
22 "[chromium-style] Classes that are ref-counted should have explicit "
23 "destructors that are declared protected or private.";
24 const char kPublicDtor[] =
25 "[chromium-style] Classes that are ref-counted should have "
26 "destructors that are declared protected or private.";
27 const char kProtectedNonVirtualDtor[] =
28 "[chromium-style] Classes that are ref-counted and have non-private "
29 "destructors should declare their destructor virtual.";
30 const char kWeakPtrFactoryOrder[] =
31 "[chromium-style] WeakPtrFactory members which refer to their outer class "
32 "must be the last member in the outer class definition.";
33 const char kBadLastEnumValue[] =
34 "[chromium-style] _LAST/Last constants of enum types must have the maximal "
35 "value for any constant of that type.";
36 const char kNoteInheritance[] = "[chromium-style] %0 inherits from %1 here";
37 const char kNoteImplicitDtor[] =
38 "[chromium-style] No explicit destructor for %0 defined";
39 const char kNotePublicDtor[] =
40 "[chromium-style] Public destructor declared here";
41 const char kNoteProtectedNonVirtualDtor[] =
42 "[chromium-style] Protected non-virtual destructor declared here";
44 bool TypeHasNonTrivialDtor(const Type* type) {
45 if (const CXXRecordDecl* cxx_r = type->getPointeeCXXRecordDecl())
46 return !cxx_r->hasTrivialDestructor();
51 // Returns the underlying Type for |type| by expanding typedefs and removing
52 // any namespace qualifiers. This is similar to desugaring, except that for
53 // ElaboratedTypes, desugar will unwrap too much.
54 const Type* UnwrapType(const Type* type) {
55 if (const ElaboratedType* elaborated = dyn_cast<ElaboratedType>(type))
56 return UnwrapType(elaborated->getNamedType().getTypePtr());
57 if (const TypedefType* typedefed = dyn_cast<TypedefType>(type))
58 return UnwrapType(typedefed->desugar().getTypePtr());
64 FindBadConstructsConsumer::FindBadConstructsConsumer(CompilerInstance& instance,
65 const Options& options)
66 : ChromeClassTester(instance), options_(options) {
67 // Register warning/error messages.
68 diag_method_requires_override_ =
69 diagnostic().getCustomDiagID(getErrorLevel(), kMethodRequiresOverride);
70 diag_method_requires_virtual_ =
71 diagnostic().getCustomDiagID(getErrorLevel(), kMethodRequiresVirtual);
72 diag_no_explicit_dtor_ =
73 diagnostic().getCustomDiagID(getErrorLevel(), kNoExplicitDtor);
75 diagnostic().getCustomDiagID(getErrorLevel(), kPublicDtor);
76 diag_protected_non_virtual_dtor_ =
77 diagnostic().getCustomDiagID(getErrorLevel(), kProtectedNonVirtualDtor);
78 diag_weak_ptr_factory_order_ =
79 diagnostic().getCustomDiagID(getErrorLevel(), kWeakPtrFactoryOrder);
80 diag_bad_enum_last_value_ =
81 diagnostic().getCustomDiagID(getErrorLevel(), kBadLastEnumValue);
83 // Registers notes to make it easier to interpret warnings.
84 diag_note_inheritance_ =
85 diagnostic().getCustomDiagID(DiagnosticsEngine::Note, kNoteInheritance);
86 diag_note_implicit_dtor_ =
87 diagnostic().getCustomDiagID(DiagnosticsEngine::Note, kNoteImplicitDtor);
88 diag_note_public_dtor_ =
89 diagnostic().getCustomDiagID(DiagnosticsEngine::Note, kNotePublicDtor);
90 diag_note_protected_non_virtual_dtor_ = diagnostic().getCustomDiagID(
91 DiagnosticsEngine::Note, kNoteProtectedNonVirtualDtor);
94 void FindBadConstructsConsumer::CheckChromeClass(SourceLocation record_location,
95 CXXRecordDecl* record) {
96 bool implementation_file = InImplementationFile(record_location);
98 if (!implementation_file) {
99 // Only check for "heavy" constructors/destructors in header files;
100 // within implementation files, there is no performance cost.
101 CheckCtorDtorWeight(record_location, record);
104 if (!implementation_file || options_.check_virtuals_in_implementations) {
105 bool warn_on_inline_bodies = !implementation_file;
107 // Check that all virtual methods are marked accordingly with both
108 // virtual and OVERRIDE.
109 CheckVirtualMethods(record_location, record, warn_on_inline_bodies);
112 CheckRefCountedDtors(record_location, record);
114 if (options_.check_weak_ptr_factory_order)
115 CheckWeakPtrFactoryMembers(record_location, record);
118 void FindBadConstructsConsumer::CheckChromeEnum(SourceLocation enum_location,
119 EnumDecl* enum_decl) {
120 if (!options_.check_enum_last_value)
123 bool got_one = false;
124 bool is_signed = false;
125 llvm::APSInt max_so_far;
126 EnumDecl::enumerator_iterator iter;
127 for (iter = enum_decl->enumerator_begin();
128 iter != enum_decl->enumerator_end();
130 llvm::APSInt current_value = iter->getInitVal();
132 max_so_far = current_value;
133 is_signed = current_value.isSigned();
136 if (is_signed != current_value.isSigned()) {
137 // This only happens in some cases when compiling C (not C++) files,
138 // so it is OK to bail out here.
141 if (current_value > max_so_far)
142 max_so_far = current_value;
145 for (iter = enum_decl->enumerator_begin();
146 iter != enum_decl->enumerator_end();
148 std::string name = iter->getNameAsString();
149 if (((name.size() > 4 && name.compare(name.size() - 4, 4, "Last") == 0) ||
150 (name.size() > 5 && name.compare(name.size() - 5, 5, "_LAST") == 0)) &&
151 iter->getInitVal() < max_so_far) {
152 diagnostic().Report(iter->getLocation(), diag_bad_enum_last_value_);
157 void FindBadConstructsConsumer::CheckCtorDtorWeight(
158 SourceLocation record_location,
159 CXXRecordDecl* record) {
160 // We don't handle anonymous structs. If this record doesn't have a
161 // name, it's of the form:
166 if (record->getIdentifier() == NULL)
169 // Count the number of templated base classes as a feature of whether the
170 // destructor can be inlined.
171 int templated_base_classes = 0;
172 for (CXXRecordDecl::base_class_const_iterator it = record->bases_begin();
173 it != record->bases_end();
175 if (it->getTypeSourceInfo()->getTypeLoc().getTypeLocClass() ==
176 TypeLoc::TemplateSpecialization) {
177 ++templated_base_classes;
181 // Count the number of trivial and non-trivial member variables.
182 int trivial_member = 0;
183 int non_trivial_member = 0;
184 int templated_non_trivial_member = 0;
185 for (RecordDecl::field_iterator it = record->field_begin();
186 it != record->field_end();
188 CountType(it->getType().getTypePtr(),
191 &templated_non_trivial_member);
194 // Check to see if we need to ban inlined/synthesized constructors. Note
195 // that the cutoffs here are kind of arbitrary. Scores over 10 break.
197 // Deriving from a templated base class shouldn't be enough to trigger
198 // the ctor warning, but if you do *anything* else, it should.
200 // TODO(erg): This is motivated by templated base classes that don't have
201 // any data members. Somehow detect when templated base classes have data
202 // members and treat them differently.
203 dtor_score += templated_base_classes * 9;
204 // Instantiating a template is an insta-hit.
205 dtor_score += templated_non_trivial_member * 10;
206 // The fourth normal class member should trigger the warning.
207 dtor_score += non_trivial_member * 3;
209 int ctor_score = dtor_score;
210 // You should be able to have 9 ints before we warn you.
211 ctor_score += trivial_member;
213 if (ctor_score >= 10) {
214 if (!record->hasUserDeclaredConstructor()) {
215 emitWarning(record_location,
216 "Complex class/struct needs an explicit out-of-line "
219 // Iterate across all the constructors in this file and yell if we
220 // find one that tries to be inline.
221 for (CXXRecordDecl::ctor_iterator it = record->ctor_begin();
222 it != record->ctor_end();
224 if (it->hasInlineBody()) {
225 if (it->isCopyConstructor() &&
226 !record->hasUserDeclaredCopyConstructor()) {
227 emitWarning(record_location,
228 "Complex class/struct needs an explicit out-of-line "
229 "copy constructor.");
231 emitWarning(it->getInnerLocStart(),
232 "Complex constructor has an inlined body.");
239 // The destructor side is equivalent except that we don't check for
240 // trivial members; 20 ints don't need a destructor.
241 if (dtor_score >= 10 && !record->hasTrivialDestructor()) {
242 if (!record->hasUserDeclaredDestructor()) {
243 emitWarning(record_location,
244 "Complex class/struct needs an explicit out-of-line "
246 } else if (CXXDestructorDecl* dtor = record->getDestructor()) {
247 if (dtor->hasInlineBody()) {
248 emitWarning(dtor->getInnerLocStart(),
249 "Complex destructor has an inline body.");
255 void FindBadConstructsConsumer::CheckVirtualMethod(const CXXMethodDecl* method,
256 bool warn_on_inline_bodies) {
257 if (!method->isVirtual())
260 if (!method->isVirtualAsWritten()) {
261 SourceLocation loc = method->getTypeSpecStartLoc();
262 if (isa<CXXDestructorDecl>(method))
263 loc = method->getInnerLocStart();
264 SourceManager& manager = instance().getSourceManager();
265 FullSourceLoc full_loc(loc, manager);
266 SourceLocation spelling_loc = manager.getSpellingLoc(loc);
267 diagnostic().Report(full_loc, diag_method_requires_virtual_)
268 << FixItHint::CreateInsertion(spelling_loc, "virtual ");
271 // Virtual methods should not have inline definitions beyond "{}". This
272 // only matters for header files.
273 if (warn_on_inline_bodies && method->hasBody() && method->hasInlineBody()) {
274 if (CompoundStmt* cs = dyn_cast<CompoundStmt>(method->getBody())) {
276 emitWarning(cs->getLBracLoc(),
277 "virtual methods with non-empty bodies shouldn't be "
284 bool FindBadConstructsConsumer::InTestingNamespace(const Decl* record) {
285 return GetNamespace(record).find("testing") != std::string::npos;
288 bool FindBadConstructsConsumer::IsMethodInBannedOrTestingNamespace(
289 const CXXMethodDecl* method) {
290 if (InBannedNamespace(method))
292 for (CXXMethodDecl::method_iterator i = method->begin_overridden_methods();
293 i != method->end_overridden_methods();
295 const CXXMethodDecl* overridden = *i;
296 if (IsMethodInBannedOrTestingNamespace(overridden) ||
297 InTestingNamespace(overridden)) {
305 void FindBadConstructsConsumer::CheckOverriddenMethod(
306 const CXXMethodDecl* method) {
307 if (!method->size_overridden_methods() || method->getAttr<OverrideAttr>())
310 if (isa<CXXDestructorDecl>(method) || method->isPure())
313 if (IsMethodInBannedOrTestingNamespace(method))
316 SourceManager& manager = instance().getSourceManager();
317 SourceRange type_info_range =
318 method->getTypeSourceInfo()->getTypeLoc().getSourceRange();
319 FullSourceLoc loc(type_info_range.getBegin(), manager);
321 // Build the FixIt insertion point after the end of the method definition,
322 // including any const-qualifiers and attributes, and before the opening
323 // of the l-curly-brace (if inline) or the semi-color (if a declaration).
324 SourceLocation spelling_end =
325 manager.getSpellingLoc(type_info_range.getEnd());
326 if (spelling_end.isValid()) {
327 SourceLocation token_end =
328 Lexer::getLocForEndOfToken(spelling_end, 0, manager, LangOptions());
329 diagnostic().Report(token_end, diag_method_requires_override_)
330 << FixItHint::CreateInsertion(token_end, " OVERRIDE");
332 diagnostic().Report(loc, diag_method_requires_override_);
336 // Makes sure there is a "virtual" keyword on virtual methods.
338 // Gmock objects trigger these for each MOCK_BLAH() macro used. So we have a
339 // trick to get around that. If a class has member variables whose types are
340 // in the "testing" namespace (which is how gmock works behind the scenes),
341 // there's a really high chance we won't care about these errors
342 void FindBadConstructsConsumer::CheckVirtualMethods(
343 SourceLocation record_location,
344 CXXRecordDecl* record,
345 bool warn_on_inline_bodies) {
346 for (CXXRecordDecl::field_iterator it = record->field_begin();
347 it != record->field_end();
349 CXXRecordDecl* record_type = it->getTypeSourceInfo()
352 ->getAsCXXRecordDecl();
354 if (InTestingNamespace(record_type)) {
360 for (CXXRecordDecl::method_iterator it = record->method_begin();
361 it != record->method_end();
363 if (it->isCopyAssignmentOperator() || isa<CXXConstructorDecl>(*it)) {
364 // Ignore constructors and assignment operators.
365 } else if (isa<CXXDestructorDecl>(*it) &&
366 !record->hasUserDeclaredDestructor()) {
367 // Ignore non-user-declared destructors.
369 CheckVirtualMethod(*it, warn_on_inline_bodies);
370 CheckOverriddenMethod(*it);
375 void FindBadConstructsConsumer::CountType(const Type* type,
377 int* non_trivial_member,
378 int* templated_non_trivial_member) {
379 switch (type->getTypeClass()) {
381 // Simplifying; the whole class isn't trivial if the dtor is, but
382 // we use this as a signal about complexity.
383 if (TypeHasNonTrivialDtor(type))
386 (*non_trivial_member)++;
389 case Type::TemplateSpecialization: {
391 dyn_cast<TemplateSpecializationType>(type)->getTemplateName();
392 bool whitelisted_template = false;
394 // HACK: I'm at a loss about how to get the syntax checker to get
395 // whether a template is exterened or not. For the first pass here,
396 // just do retarded string comparisons.
397 if (TemplateDecl* decl = name.getAsTemplateDecl()) {
398 std::string base_name = decl->getNameAsString();
399 if (base_name == "basic_string")
400 whitelisted_template = true;
403 if (whitelisted_template)
404 (*non_trivial_member)++;
406 (*templated_non_trivial_member)++;
409 case Type::Elaborated: {
410 CountType(dyn_cast<ElaboratedType>(type)->getNamedType().getTypePtr(),
413 templated_non_trivial_member);
416 case Type::Typedef: {
417 while (const TypedefType* TT = dyn_cast<TypedefType>(type)) {
418 type = TT->getDecl()->getUnderlyingType().getTypePtr();
423 templated_non_trivial_member);
427 // Stupid assumption: anything we see that isn't the above is one of
428 // the 20 integer types.
435 // Check |record| for issues that are problematic for ref-counted types.
436 // Note that |record| may not be a ref-counted type, but a base class for
438 // If there are issues, update |loc| with the SourceLocation of the issue
439 // and returns appropriately, or returns None if there are no issues.
440 FindBadConstructsConsumer::RefcountIssue
441 FindBadConstructsConsumer::CheckRecordForRefcountIssue(
442 const CXXRecordDecl* record,
443 SourceLocation& loc) {
444 if (!record->hasUserDeclaredDestructor()) {
445 loc = record->getLocation();
446 return ImplicitDestructor;
449 if (CXXDestructorDecl* dtor = record->getDestructor()) {
450 if (dtor->getAccess() == AS_public) {
451 loc = dtor->getInnerLocStart();
452 return PublicDestructor;
459 // Adds either a warning or error, based on the current handling of
461 DiagnosticsEngine::Level FindBadConstructsConsumer::getErrorLevel() {
462 return diagnostic().getWarningsAsErrors() ? DiagnosticsEngine::Error
463 : DiagnosticsEngine::Warning;
466 // Returns true if |base| specifies one of the Chromium reference counted
467 // classes (base::RefCounted / base::RefCountedThreadSafe).
468 bool FindBadConstructsConsumer::IsRefCountedCallback(
469 const CXXBaseSpecifier* base,
472 FindBadConstructsConsumer* self =
473 static_cast<FindBadConstructsConsumer*>(user_data);
475 const TemplateSpecializationType* base_type =
476 dyn_cast<TemplateSpecializationType>(
477 UnwrapType(base->getType().getTypePtr()));
479 // Base-most definition is not a template, so this cannot derive from
480 // base::RefCounted. However, it may still be possible to use with a
481 // scoped_refptr<> and support ref-counting, so this is not a perfect
482 // guarantee of safety.
486 TemplateName name = base_type->getTemplateName();
487 if (TemplateDecl* decl = name.getAsTemplateDecl()) {
488 std::string base_name = decl->getNameAsString();
490 // Check for both base::RefCounted and base::RefCountedThreadSafe.
491 if (base_name.compare(0, 10, "RefCounted") == 0 &&
492 self->GetNamespace(decl) == "base") {
500 // Returns true if |base| specifies a class that has a public destructor,
501 // either explicitly or implicitly.
502 bool FindBadConstructsConsumer::HasPublicDtorCallback(
503 const CXXBaseSpecifier* base,
506 // Only examine paths that have public inheritance, as they are the
507 // only ones which will result in the destructor potentially being
508 // exposed. This check is largely redundant, as Chromium code should be
509 // exclusively using public inheritance.
510 if (path.Access != AS_public)
513 CXXRecordDecl* record =
514 dyn_cast<CXXRecordDecl>(base->getType()->getAs<RecordType>()->getDecl());
515 SourceLocation unused;
516 return None != CheckRecordForRefcountIssue(record, unused);
519 // Outputs a C++ inheritance chain as a diagnostic aid.
520 void FindBadConstructsConsumer::PrintInheritanceChain(const CXXBasePath& path) {
521 for (CXXBasePath::const_iterator it = path.begin(); it != path.end(); ++it) {
522 diagnostic().Report(it->Base->getLocStart(), diag_note_inheritance_)
523 << it->Class << it->Base->getType();
527 unsigned FindBadConstructsConsumer::DiagnosticForIssue(RefcountIssue issue) {
529 case ImplicitDestructor:
530 return diag_no_explicit_dtor_;
531 case PublicDestructor:
532 return diag_public_dtor_;
534 assert(false && "Do not call DiagnosticForIssue with issue None");
541 // Check |record| to determine if it has any problematic refcounting
542 // issues and, if so, print them as warnings/errors based on the current
543 // value of getErrorLevel().
545 // If |record| is a C++ class, and if it inherits from one of the Chromium
546 // ref-counting classes (base::RefCounted / base::RefCountedThreadSafe),
547 // ensure that there are no public destructors in the class hierarchy. This
548 // is to guard against accidentally stack-allocating a RefCounted class or
549 // sticking it in a non-ref-counted container (like scoped_ptr<>).
550 void FindBadConstructsConsumer::CheckRefCountedDtors(
551 SourceLocation record_location,
552 CXXRecordDecl* record) {
553 // Skip anonymous structs.
554 if (record->getIdentifier() == NULL)
557 // Determine if the current type is even ref-counted.
558 CXXBasePaths refcounted_path;
559 if (!record->lookupInBases(&FindBadConstructsConsumer::IsRefCountedCallback,
562 return; // Class does not derive from a ref-counted base class.
565 // Easy check: Check to see if the current type is problematic.
567 RefcountIssue issue = CheckRecordForRefcountIssue(record, loc);
569 diagnostic().Report(loc, DiagnosticForIssue(issue));
570 PrintInheritanceChain(refcounted_path.front());
573 if (CXXDestructorDecl* dtor =
574 refcounted_path.begin()->back().Class->getDestructor()) {
575 if (dtor->getAccess() == AS_protected && !dtor->isVirtual()) {
576 loc = dtor->getInnerLocStart();
577 diagnostic().Report(loc, diag_protected_non_virtual_dtor_);
582 // Long check: Check all possible base classes for problematic
583 // destructors. This checks for situations involving multiple
584 // inheritance, where the ref-counted class may be implementing an
585 // interface that has a public or implicit destructor.
587 // struct SomeInterface {
588 // virtual void DoFoo();
591 // struct RefCountedInterface
592 // : public base::RefCounted<RefCountedInterface>,
593 // public SomeInterface {
595 // friend class base::Refcounted<RefCountedInterface>;
596 // virtual ~RefCountedInterface() {}
599 // While RefCountedInterface is "safe", in that its destructor is
600 // private, it's possible to do the following "unsafe" code:
601 // scoped_refptr<RefCountedInterface> some_class(
602 // new RefCountedInterface);
603 // // Calls SomeInterface::~SomeInterface(), which is unsafe.
604 // delete static_cast<SomeInterface*>(some_class.get());
605 if (!options_.check_base_classes)
608 // Find all public destructors. This will record the class hierarchy
609 // that leads to the public destructor in |dtor_paths|.
610 CXXBasePaths dtor_paths;
611 if (!record->lookupInBases(&FindBadConstructsConsumer::HasPublicDtorCallback,
617 for (CXXBasePaths::const_paths_iterator it = dtor_paths.begin();
618 it != dtor_paths.end();
620 // The record with the problem will always be the last record
621 // in the path, since it is the record that stopped the search.
622 const CXXRecordDecl* problem_record = dyn_cast<CXXRecordDecl>(
623 it->back().Base->getType()->getAs<RecordType>()->getDecl());
625 issue = CheckRecordForRefcountIssue(problem_record, loc);
627 if (issue == ImplicitDestructor) {
628 diagnostic().Report(record_location, diag_no_explicit_dtor_);
629 PrintInheritanceChain(refcounted_path.front());
630 diagnostic().Report(loc, diag_note_implicit_dtor_) << problem_record;
631 PrintInheritanceChain(*it);
632 } else if (issue == PublicDestructor) {
633 diagnostic().Report(record_location, diag_public_dtor_);
634 PrintInheritanceChain(refcounted_path.front());
635 diagnostic().Report(loc, diag_note_public_dtor_);
636 PrintInheritanceChain(*it);
641 // Check for any problems with WeakPtrFactory class members. This currently
642 // only checks that any WeakPtrFactory<T> member of T appears as the last
643 // data member in T. We could consider checking for bad uses of
644 // WeakPtrFactory to refer to other data members, but that would require
645 // looking at the initializer list in constructors to see what the factory
647 // Note, if we later add other unrelated checks of data members, we should
648 // consider collapsing them in to one loop to avoid iterating over the data
649 // members more than once.
650 void FindBadConstructsConsumer::CheckWeakPtrFactoryMembers(
651 SourceLocation record_location,
652 CXXRecordDecl* record) {
653 // Skip anonymous structs.
654 if (record->getIdentifier() == NULL)
657 // Iterate through members of the class.
658 RecordDecl::field_iterator iter(record->field_begin()),
659 the_end(record->field_end());
660 SourceLocation weak_ptr_factory_location; // Invalid initially.
661 for (; iter != the_end; ++iter) {
662 // If we enter the loop but have already seen a matching WeakPtrFactory,
663 // it means there is at least one member after the factory.
664 if (weak_ptr_factory_location.isValid()) {
665 diagnostic().Report(weak_ptr_factory_location,
666 diag_weak_ptr_factory_order_);
668 const TemplateSpecializationType* template_spec_type =
669 iter->getType().getTypePtr()->getAs<TemplateSpecializationType>();
670 if (template_spec_type) {
671 const TemplateDecl* template_decl =
672 template_spec_type->getTemplateName().getAsTemplateDecl();
673 if (template_decl && template_spec_type->getNumArgs() >= 1) {
674 if (template_decl->getNameAsString().compare("WeakPtrFactory") == 0 &&
675 GetNamespace(template_decl) == "base") {
676 const TemplateArgument& arg = template_spec_type->getArg(0);
677 if (arg.getAsType().getTypePtr()->getAsCXXRecordDecl() ==
678 record->getTypeForDecl()->getAsCXXRecordDecl()) {
679 weak_ptr_factory_location = iter->getLocation();
687 } // namespace chrome_checker