OLD | NEW |
(Empty) | |
| 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. |
| 4 |
| 5 #include "FindBadConstructsConsumer.h" |
| 6 |
| 7 #include "clang/Frontend/CompilerInstance.h" |
| 8 #include "clang/Lex/Lexer.h" |
| 9 #include "llvm/Support/raw_ostream.h" |
| 10 |
| 11 using namespace clang; |
| 12 |
| 13 namespace chrome_checker { |
| 14 |
| 15 namespace { |
| 16 |
| 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"; |
| 43 |
| 44 bool TypeHasNonTrivialDtor(const Type* type) { |
| 45 if (const CXXRecordDecl* cxx_r = type->getPointeeCXXRecordDecl()) |
| 46 return !cxx_r->hasTrivialDestructor(); |
| 47 |
| 48 return false; |
| 49 } |
| 50 |
| 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()); |
| 59 return type; |
| 60 } |
| 61 |
| 62 } // namespace |
| 63 |
| 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); |
| 74 diag_public_dtor_ = |
| 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); |
| 82 |
| 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); |
| 92 } |
| 93 |
| 94 void FindBadConstructsConsumer::CheckChromeClass(SourceLocation record_location, |
| 95 CXXRecordDecl* record) { |
| 96 bool implementation_file = InImplementationFile(record_location); |
| 97 |
| 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); |
| 102 } |
| 103 |
| 104 if (!implementation_file || options_.check_virtuals_in_implementations) { |
| 105 bool warn_on_inline_bodies = !implementation_file; |
| 106 |
| 107 // Check that all virtual methods are marked accordingly with both |
| 108 // virtual and OVERRIDE. |
| 109 CheckVirtualMethods(record_location, record, warn_on_inline_bodies); |
| 110 } |
| 111 |
| 112 CheckRefCountedDtors(record_location, record); |
| 113 |
| 114 if (options_.check_weak_ptr_factory_order) |
| 115 CheckWeakPtrFactoryMembers(record_location, record); |
| 116 } |
| 117 |
| 118 void FindBadConstructsConsumer::CheckChromeEnum(SourceLocation enum_location, |
| 119 EnumDecl* enum_decl) { |
| 120 if (!options_.check_enum_last_value) |
| 121 return; |
| 122 |
| 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(); |
| 129 ++iter) { |
| 130 llvm::APSInt current_value = iter->getInitVal(); |
| 131 if (!got_one) { |
| 132 max_so_far = current_value; |
| 133 is_signed = current_value.isSigned(); |
| 134 got_one = true; |
| 135 } else { |
| 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. |
| 139 return; |
| 140 } |
| 141 if (current_value > max_so_far) |
| 142 max_so_far = current_value; |
| 143 } |
| 144 } |
| 145 for (iter = enum_decl->enumerator_begin(); |
| 146 iter != enum_decl->enumerator_end(); |
| 147 ++iter) { |
| 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_); |
| 153 } |
| 154 } |
| 155 } |
| 156 |
| 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: |
| 162 // |
| 163 // struct { |
| 164 // ... |
| 165 // } name_; |
| 166 if (record->getIdentifier() == NULL) |
| 167 return; |
| 168 |
| 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(); |
| 174 ++it) { |
| 175 if (it->getTypeSourceInfo()->getTypeLoc().getTypeLocClass() == |
| 176 TypeLoc::TemplateSpecialization) { |
| 177 ++templated_base_classes; |
| 178 } |
| 179 } |
| 180 |
| 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(); |
| 187 ++it) { |
| 188 CountType(it->getType().getTypePtr(), |
| 189 &trivial_member, |
| 190 &non_trivial_member, |
| 191 &templated_non_trivial_member); |
| 192 } |
| 193 |
| 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. |
| 196 int dtor_score = 0; |
| 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. |
| 199 // |
| 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; |
| 208 |
| 209 int ctor_score = dtor_score; |
| 210 // You should be able to have 9 ints before we warn you. |
| 211 ctor_score += trivial_member; |
| 212 |
| 213 if (ctor_score >= 10) { |
| 214 if (!record->hasUserDeclaredConstructor()) { |
| 215 emitWarning(record_location, |
| 216 "Complex class/struct needs an explicit out-of-line " |
| 217 "constructor."); |
| 218 } else { |
| 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(); |
| 223 ++it) { |
| 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."); |
| 230 } else { |
| 231 emitWarning(it->getInnerLocStart(), |
| 232 "Complex constructor has an inlined body."); |
| 233 } |
| 234 } |
| 235 } |
| 236 } |
| 237 } |
| 238 |
| 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 " |
| 245 "destructor."); |
| 246 } else if (CXXDestructorDecl* dtor = record->getDestructor()) { |
| 247 if (dtor->hasInlineBody()) { |
| 248 emitWarning(dtor->getInnerLocStart(), |
| 249 "Complex destructor has an inline body."); |
| 250 } |
| 251 } |
| 252 } |
| 253 } |
| 254 |
| 255 void FindBadConstructsConsumer::CheckVirtualMethod(const CXXMethodDecl* method, |
| 256 bool warn_on_inline_bodies) { |
| 257 if (!method->isVirtual()) |
| 258 return; |
| 259 |
| 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 "); |
| 269 } |
| 270 |
| 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())) { |
| 275 if (cs->size()) { |
| 276 emitWarning(cs->getLBracLoc(), |
| 277 "virtual methods with non-empty bodies shouldn't be " |
| 278 "declared inline."); |
| 279 } |
| 280 } |
| 281 } |
| 282 } |
| 283 |
| 284 bool FindBadConstructsConsumer::InTestingNamespace(const Decl* record) { |
| 285 return GetNamespace(record).find("testing") != std::string::npos; |
| 286 } |
| 287 |
| 288 bool FindBadConstructsConsumer::IsMethodInBannedOrTestingNamespace( |
| 289 const CXXMethodDecl* method) { |
| 290 if (InBannedNamespace(method)) |
| 291 return true; |
| 292 for (CXXMethodDecl::method_iterator i = method->begin_overridden_methods(); |
| 293 i != method->end_overridden_methods(); |
| 294 ++i) { |
| 295 const CXXMethodDecl* overridden = *i; |
| 296 if (IsMethodInBannedOrTestingNamespace(overridden) || |
| 297 InTestingNamespace(overridden)) { |
| 298 return true; |
| 299 } |
| 300 } |
| 301 |
| 302 return false; |
| 303 } |
| 304 |
| 305 void FindBadConstructsConsumer::CheckOverriddenMethod( |
| 306 const CXXMethodDecl* method) { |
| 307 if (!method->size_overridden_methods() || method->getAttr<OverrideAttr>()) |
| 308 return; |
| 309 |
| 310 if (isa<CXXDestructorDecl>(method) || method->isPure()) |
| 311 return; |
| 312 |
| 313 if (IsMethodInBannedOrTestingNamespace(method)) |
| 314 return; |
| 315 |
| 316 SourceManager& manager = instance().getSourceManager(); |
| 317 SourceRange type_info_range = |
| 318 method->getTypeSourceInfo()->getTypeLoc().getSourceRange(); |
| 319 FullSourceLoc loc(type_info_range.getBegin(), manager); |
| 320 |
| 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"); |
| 331 } else { |
| 332 diagnostic().Report(loc, diag_method_requires_override_); |
| 333 } |
| 334 } |
| 335 |
| 336 // Makes sure there is a "virtual" keyword on virtual methods. |
| 337 // |
| 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(); |
| 348 ++it) { |
| 349 CXXRecordDecl* record_type = it->getTypeSourceInfo() |
| 350 ->getTypeLoc() |
| 351 .getTypePtr() |
| 352 ->getAsCXXRecordDecl(); |
| 353 if (record_type) { |
| 354 if (InTestingNamespace(record_type)) { |
| 355 return; |
| 356 } |
| 357 } |
| 358 } |
| 359 |
| 360 for (CXXRecordDecl::method_iterator it = record->method_begin(); |
| 361 it != record->method_end(); |
| 362 ++it) { |
| 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. |
| 368 } else { |
| 369 CheckVirtualMethod(*it, warn_on_inline_bodies); |
| 370 CheckOverriddenMethod(*it); |
| 371 } |
| 372 } |
| 373 } |
| 374 |
| 375 void FindBadConstructsConsumer::CountType(const Type* type, |
| 376 int* trivial_member, |
| 377 int* non_trivial_member, |
| 378 int* templated_non_trivial_member) { |
| 379 switch (type->getTypeClass()) { |
| 380 case Type::Record: { |
| 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)) |
| 384 (*trivial_member)++; |
| 385 else |
| 386 (*non_trivial_member)++; |
| 387 break; |
| 388 } |
| 389 case Type::TemplateSpecialization: { |
| 390 TemplateName name = |
| 391 dyn_cast<TemplateSpecializationType>(type)->getTemplateName(); |
| 392 bool whitelisted_template = false; |
| 393 |
| 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; |
| 401 } |
| 402 |
| 403 if (whitelisted_template) |
| 404 (*non_trivial_member)++; |
| 405 else |
| 406 (*templated_non_trivial_member)++; |
| 407 break; |
| 408 } |
| 409 case Type::Elaborated: { |
| 410 CountType(dyn_cast<ElaboratedType>(type)->getNamedType().getTypePtr(), |
| 411 trivial_member, |
| 412 non_trivial_member, |
| 413 templated_non_trivial_member); |
| 414 break; |
| 415 } |
| 416 case Type::Typedef: { |
| 417 while (const TypedefType* TT = dyn_cast<TypedefType>(type)) { |
| 418 type = TT->getDecl()->getUnderlyingType().getTypePtr(); |
| 419 } |
| 420 CountType(type, |
| 421 trivial_member, |
| 422 non_trivial_member, |
| 423 templated_non_trivial_member); |
| 424 break; |
| 425 } |
| 426 default: { |
| 427 // Stupid assumption: anything we see that isn't the above is one of |
| 428 // the 20 integer types. |
| 429 (*trivial_member)++; |
| 430 break; |
| 431 } |
| 432 } |
| 433 } |
| 434 |
| 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 |
| 437 // a type that is. |
| 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; |
| 447 } |
| 448 |
| 449 if (CXXDestructorDecl* dtor = record->getDestructor()) { |
| 450 if (dtor->getAccess() == AS_public) { |
| 451 loc = dtor->getInnerLocStart(); |
| 452 return PublicDestructor; |
| 453 } |
| 454 } |
| 455 |
| 456 return None; |
| 457 } |
| 458 |
| 459 // Adds either a warning or error, based on the current handling of |
| 460 // -Werror. |
| 461 DiagnosticsEngine::Level FindBadConstructsConsumer::getErrorLevel() { |
| 462 return diagnostic().getWarningsAsErrors() ? DiagnosticsEngine::Error |
| 463 : DiagnosticsEngine::Warning; |
| 464 } |
| 465 |
| 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, |
| 470 CXXBasePath& path, |
| 471 void* user_data) { |
| 472 FindBadConstructsConsumer* self = |
| 473 static_cast<FindBadConstructsConsumer*>(user_data); |
| 474 |
| 475 const TemplateSpecializationType* base_type = |
| 476 dyn_cast<TemplateSpecializationType>( |
| 477 UnwrapType(base->getType().getTypePtr())); |
| 478 if (!base_type) { |
| 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. |
| 483 return false; |
| 484 } |
| 485 |
| 486 TemplateName name = base_type->getTemplateName(); |
| 487 if (TemplateDecl* decl = name.getAsTemplateDecl()) { |
| 488 std::string base_name = decl->getNameAsString(); |
| 489 |
| 490 // Check for both base::RefCounted and base::RefCountedThreadSafe. |
| 491 if (base_name.compare(0, 10, "RefCounted") == 0 && |
| 492 self->GetNamespace(decl) == "base") { |
| 493 return true; |
| 494 } |
| 495 } |
| 496 |
| 497 return false; |
| 498 } |
| 499 |
| 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, |
| 504 CXXBasePath& path, |
| 505 void* user_data) { |
| 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) |
| 511 return false; |
| 512 |
| 513 CXXRecordDecl* record = |
| 514 dyn_cast<CXXRecordDecl>(base->getType()->getAs<RecordType>()->getDecl()); |
| 515 SourceLocation unused; |
| 516 return None != CheckRecordForRefcountIssue(record, unused); |
| 517 } |
| 518 |
| 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(); |
| 524 } |
| 525 } |
| 526 |
| 527 unsigned FindBadConstructsConsumer::DiagnosticForIssue(RefcountIssue issue) { |
| 528 switch (issue) { |
| 529 case ImplicitDestructor: |
| 530 return diag_no_explicit_dtor_; |
| 531 case PublicDestructor: |
| 532 return diag_public_dtor_; |
| 533 case None: |
| 534 assert(false && "Do not call DiagnosticForIssue with issue None"); |
| 535 return 0; |
| 536 } |
| 537 assert(false); |
| 538 return 0; |
| 539 } |
| 540 |
| 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(). |
| 544 // |
| 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) |
| 555 return; |
| 556 |
| 557 // Determine if the current type is even ref-counted. |
| 558 CXXBasePaths refcounted_path; |
| 559 if (!record->lookupInBases(&FindBadConstructsConsumer::IsRefCountedCallback, |
| 560 this, |
| 561 refcounted_path)) { |
| 562 return; // Class does not derive from a ref-counted base class. |
| 563 } |
| 564 |
| 565 // Easy check: Check to see if the current type is problematic. |
| 566 SourceLocation loc; |
| 567 RefcountIssue issue = CheckRecordForRefcountIssue(record, loc); |
| 568 if (issue != None) { |
| 569 diagnostic().Report(loc, DiagnosticForIssue(issue)); |
| 570 PrintInheritanceChain(refcounted_path.front()); |
| 571 return; |
| 572 } |
| 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_); |
| 578 return; |
| 579 } |
| 580 } |
| 581 |
| 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. |
| 586 // |
| 587 // struct SomeInterface { |
| 588 // virtual void DoFoo(); |
| 589 // }; |
| 590 // |
| 591 // struct RefCountedInterface |
| 592 // : public base::RefCounted<RefCountedInterface>, |
| 593 // public SomeInterface { |
| 594 // private: |
| 595 // friend class base::Refcounted<RefCountedInterface>; |
| 596 // virtual ~RefCountedInterface() {} |
| 597 // }; |
| 598 // |
| 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) |
| 606 return; |
| 607 |
| 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, |
| 612 this, |
| 613 dtor_paths)) { |
| 614 return; |
| 615 } |
| 616 |
| 617 for (CXXBasePaths::const_paths_iterator it = dtor_paths.begin(); |
| 618 it != dtor_paths.end(); |
| 619 ++it) { |
| 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()); |
| 624 |
| 625 issue = CheckRecordForRefcountIssue(problem_record, loc); |
| 626 |
| 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); |
| 637 } |
| 638 } |
| 639 } |
| 640 |
| 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 |
| 646 // points to. |
| 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) |
| 655 return; |
| 656 |
| 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_); |
| 667 } |
| 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(); |
| 680 } |
| 681 } |
| 682 } |
| 683 } |
| 684 } |
| 685 } |
| 686 |
| 687 } // namespace chrome_checker |
OLD | NEW |