SemaAccess.cpp 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965
  1. //===---- SemaAccess.cpp - C++ Access Control -------------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file provides Sema routines for C++ access control semantics.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Basic/Specifiers.h"
  13. #include "clang/Sema/SemaInternal.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/CXXInheritance.h"
  16. #include "clang/AST/DeclCXX.h"
  17. #include "clang/AST/DeclFriend.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "clang/AST/DependentDiagnostic.h"
  20. #include "clang/AST/ExprCXX.h"
  21. #include "clang/Sema/DelayedDiagnostic.h"
  22. #include "clang/Sema/Initialization.h"
  23. #include "clang/Sema/Lookup.h"
  24. using namespace clang;
  25. using namespace sema;
  26. /// A copy of Sema's enum without AR_delayed.
  27. enum AccessResult {
  28. AR_accessible,
  29. AR_inaccessible,
  30. AR_dependent
  31. };
  32. /// SetMemberAccessSpecifier - Set the access specifier of a member.
  33. /// Returns true on error (when the previous member decl access specifier
  34. /// is different from the new member decl access specifier).
  35. bool Sema::SetMemberAccessSpecifier(NamedDecl *MemberDecl,
  36. NamedDecl *PrevMemberDecl,
  37. AccessSpecifier LexicalAS) {
  38. if (!PrevMemberDecl) {
  39. // Use the lexical access specifier.
  40. MemberDecl->setAccess(LexicalAS);
  41. return false;
  42. }
  43. // C++ [class.access.spec]p3: When a member is redeclared its access
  44. // specifier must be same as its initial declaration.
  45. if (LexicalAS != AS_none && LexicalAS != PrevMemberDecl->getAccess()) {
  46. Diag(MemberDecl->getLocation(),
  47. diag::err_class_redeclared_with_different_access)
  48. << MemberDecl << LexicalAS;
  49. Diag(PrevMemberDecl->getLocation(), diag::note_previous_access_declaration)
  50. << PrevMemberDecl << PrevMemberDecl->getAccess();
  51. MemberDecl->setAccess(LexicalAS);
  52. return true;
  53. }
  54. MemberDecl->setAccess(PrevMemberDecl->getAccess());
  55. return false;
  56. }
  57. static CXXRecordDecl *FindDeclaringClass(NamedDecl *D) {
  58. DeclContext *DC = D->getDeclContext();
  59. // This can only happen at top: enum decls only "publish" their
  60. // immediate members.
  61. if (isa<EnumDecl>(DC))
  62. DC = cast<EnumDecl>(DC)->getDeclContext();
  63. CXXRecordDecl *DeclaringClass = cast<CXXRecordDecl>(DC);
  64. while (DeclaringClass->isAnonymousStructOrUnion())
  65. DeclaringClass = cast<CXXRecordDecl>(DeclaringClass->getDeclContext());
  66. return DeclaringClass;
  67. }
  68. namespace {
  69. struct EffectiveContext {
  70. EffectiveContext() : Inner(nullptr), Dependent(false) {}
  71. explicit EffectiveContext(DeclContext *DC)
  72. : Inner(DC),
  73. Dependent(DC->isDependentContext()) {
  74. // An implicit deduction guide is semantically in the context enclosing the
  75. // class template, but for access purposes behaves like the constructor
  76. // from which it was produced.
  77. if (auto *DGD = dyn_cast<CXXDeductionGuideDecl>(DC)) {
  78. if (DGD->isImplicit()) {
  79. DC = DGD->getCorrespondingConstructor();
  80. if (!DC) {
  81. // The copy deduction candidate doesn't have a corresponding
  82. // constructor.
  83. DC = cast<DeclContext>(DGD->getDeducedTemplate()->getTemplatedDecl());
  84. }
  85. }
  86. }
  87. // C++11 [class.access.nest]p1:
  88. // A nested class is a member and as such has the same access
  89. // rights as any other member.
  90. // C++11 [class.access]p2:
  91. // A member of a class can also access all the names to which
  92. // the class has access. A local class of a member function
  93. // may access the same names that the member function itself
  94. // may access.
  95. // This almost implies that the privileges of nesting are transitive.
  96. // Technically it says nothing about the local classes of non-member
  97. // functions (which can gain privileges through friendship), but we
  98. // take that as an oversight.
  99. while (true) {
  100. // We want to add canonical declarations to the EC lists for
  101. // simplicity of checking, but we need to walk up through the
  102. // actual current DC chain. Otherwise, something like a local
  103. // extern or friend which happens to be the canonical
  104. // declaration will really mess us up.
  105. if (isa<CXXRecordDecl>(DC)) {
  106. CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
  107. Records.push_back(Record->getCanonicalDecl());
  108. DC = Record->getDeclContext();
  109. } else if (isa<FunctionDecl>(DC)) {
  110. FunctionDecl *Function = cast<FunctionDecl>(DC);
  111. Functions.push_back(Function->getCanonicalDecl());
  112. if (Function->getFriendObjectKind())
  113. DC = Function->getLexicalDeclContext();
  114. else
  115. DC = Function->getDeclContext();
  116. } else if (DC->isFileContext()) {
  117. break;
  118. } else {
  119. DC = DC->getParent();
  120. }
  121. }
  122. }
  123. bool isDependent() const { return Dependent; }
  124. bool includesClass(const CXXRecordDecl *R) const {
  125. R = R->getCanonicalDecl();
  126. return llvm::is_contained(Records, R);
  127. }
  128. /// Retrieves the innermost "useful" context. Can be null if we're
  129. /// doing access-control without privileges.
  130. DeclContext *getInnerContext() const {
  131. return Inner;
  132. }
  133. typedef SmallVectorImpl<CXXRecordDecl*>::const_iterator record_iterator;
  134. DeclContext *Inner;
  135. SmallVector<FunctionDecl*, 4> Functions;
  136. SmallVector<CXXRecordDecl*, 4> Records;
  137. bool Dependent;
  138. };
  139. /// Like sema::AccessedEntity, but kindly lets us scribble all over
  140. /// it.
  141. struct AccessTarget : public AccessedEntity {
  142. AccessTarget(const AccessedEntity &Entity)
  143. : AccessedEntity(Entity) {
  144. initialize();
  145. }
  146. AccessTarget(ASTContext &Context,
  147. MemberNonce _,
  148. CXXRecordDecl *NamingClass,
  149. DeclAccessPair FoundDecl,
  150. QualType BaseObjectType)
  151. : AccessedEntity(Context.getDiagAllocator(), Member, NamingClass,
  152. FoundDecl, BaseObjectType) {
  153. initialize();
  154. }
  155. AccessTarget(ASTContext &Context,
  156. BaseNonce _,
  157. CXXRecordDecl *BaseClass,
  158. CXXRecordDecl *DerivedClass,
  159. AccessSpecifier Access)
  160. : AccessedEntity(Context.getDiagAllocator(), Base, BaseClass, DerivedClass,
  161. Access) {
  162. initialize();
  163. }
  164. bool isInstanceMember() const {
  165. return (isMemberAccess() && getTargetDecl()->isCXXInstanceMember());
  166. }
  167. bool hasInstanceContext() const {
  168. return HasInstanceContext;
  169. }
  170. class SavedInstanceContext {
  171. public:
  172. SavedInstanceContext(SavedInstanceContext &&S)
  173. : Target(S.Target), Has(S.Has) {
  174. S.Target = nullptr;
  175. }
  176. ~SavedInstanceContext() {
  177. if (Target)
  178. Target->HasInstanceContext = Has;
  179. }
  180. private:
  181. friend struct AccessTarget;
  182. explicit SavedInstanceContext(AccessTarget &Target)
  183. : Target(&Target), Has(Target.HasInstanceContext) {}
  184. AccessTarget *Target;
  185. bool Has;
  186. };
  187. SavedInstanceContext saveInstanceContext() {
  188. return SavedInstanceContext(*this);
  189. }
  190. void suppressInstanceContext() {
  191. HasInstanceContext = false;
  192. }
  193. const CXXRecordDecl *resolveInstanceContext(Sema &S) const {
  194. assert(HasInstanceContext);
  195. if (CalculatedInstanceContext)
  196. return InstanceContext;
  197. CalculatedInstanceContext = true;
  198. DeclContext *IC = S.computeDeclContext(getBaseObjectType());
  199. InstanceContext = (IC ? cast<CXXRecordDecl>(IC)->getCanonicalDecl()
  200. : nullptr);
  201. return InstanceContext;
  202. }
  203. const CXXRecordDecl *getDeclaringClass() const {
  204. return DeclaringClass;
  205. }
  206. /// The "effective" naming class is the canonical non-anonymous
  207. /// class containing the actual naming class.
  208. const CXXRecordDecl *getEffectiveNamingClass() const {
  209. const CXXRecordDecl *namingClass = getNamingClass();
  210. while (namingClass->isAnonymousStructOrUnion())
  211. namingClass = cast<CXXRecordDecl>(namingClass->getParent());
  212. return namingClass->getCanonicalDecl();
  213. }
  214. private:
  215. void initialize() {
  216. HasInstanceContext = (isMemberAccess() &&
  217. !getBaseObjectType().isNull() &&
  218. getTargetDecl()->isCXXInstanceMember());
  219. CalculatedInstanceContext = false;
  220. InstanceContext = nullptr;
  221. if (isMemberAccess())
  222. DeclaringClass = FindDeclaringClass(getTargetDecl());
  223. else
  224. DeclaringClass = getBaseClass();
  225. DeclaringClass = DeclaringClass->getCanonicalDecl();
  226. }
  227. bool HasInstanceContext : 1;
  228. mutable bool CalculatedInstanceContext : 1;
  229. mutable const CXXRecordDecl *InstanceContext;
  230. const CXXRecordDecl *DeclaringClass;
  231. };
  232. }
  233. /// Checks whether one class might instantiate to the other.
  234. static bool MightInstantiateTo(const CXXRecordDecl *From,
  235. const CXXRecordDecl *To) {
  236. // Declaration names are always preserved by instantiation.
  237. if (From->getDeclName() != To->getDeclName())
  238. return false;
  239. const DeclContext *FromDC = From->getDeclContext()->getPrimaryContext();
  240. const DeclContext *ToDC = To->getDeclContext()->getPrimaryContext();
  241. if (FromDC == ToDC) return true;
  242. if (FromDC->isFileContext() || ToDC->isFileContext()) return false;
  243. // Be conservative.
  244. return true;
  245. }
  246. /// Checks whether one class is derived from another, inclusively.
  247. /// Properly indicates when it couldn't be determined due to
  248. /// dependence.
  249. ///
  250. /// This should probably be donated to AST or at least Sema.
  251. static AccessResult IsDerivedFromInclusive(const CXXRecordDecl *Derived,
  252. const CXXRecordDecl *Target) {
  253. assert(Derived->getCanonicalDecl() == Derived);
  254. assert(Target->getCanonicalDecl() == Target);
  255. if (Derived == Target) return AR_accessible;
  256. bool CheckDependent = Derived->isDependentContext();
  257. if (CheckDependent && MightInstantiateTo(Derived, Target))
  258. return AR_dependent;
  259. AccessResult OnFailure = AR_inaccessible;
  260. SmallVector<const CXXRecordDecl*, 8> Queue; // actually a stack
  261. while (true) {
  262. if (Derived->isDependentContext() && !Derived->hasDefinition() &&
  263. !Derived->isLambda())
  264. return AR_dependent;
  265. for (const auto &I : Derived->bases()) {
  266. const CXXRecordDecl *RD;
  267. QualType T = I.getType();
  268. if (const RecordType *RT = T->getAs<RecordType>()) {
  269. RD = cast<CXXRecordDecl>(RT->getDecl());
  270. } else if (const InjectedClassNameType *IT
  271. = T->getAs<InjectedClassNameType>()) {
  272. RD = IT->getDecl();
  273. } else {
  274. assert(T->isDependentType() && "non-dependent base wasn't a record?");
  275. OnFailure = AR_dependent;
  276. continue;
  277. }
  278. RD = RD->getCanonicalDecl();
  279. if (RD == Target) return AR_accessible;
  280. if (CheckDependent && MightInstantiateTo(RD, Target))
  281. OnFailure = AR_dependent;
  282. Queue.push_back(RD);
  283. }
  284. if (Queue.empty()) break;
  285. Derived = Queue.pop_back_val();
  286. }
  287. return OnFailure;
  288. }
  289. static bool MightInstantiateTo(Sema &S, DeclContext *Context,
  290. DeclContext *Friend) {
  291. if (Friend == Context)
  292. return true;
  293. assert(!Friend->isDependentContext() &&
  294. "can't handle friends with dependent contexts here");
  295. if (!Context->isDependentContext())
  296. return false;
  297. if (Friend->isFileContext())
  298. return false;
  299. // TODO: this is very conservative
  300. return true;
  301. }
  302. // Asks whether the type in 'context' can ever instantiate to the type
  303. // in 'friend'.
  304. static bool MightInstantiateTo(Sema &S, CanQualType Context, CanQualType Friend) {
  305. if (Friend == Context)
  306. return true;
  307. if (!Friend->isDependentType() && !Context->isDependentType())
  308. return false;
  309. // TODO: this is very conservative.
  310. return true;
  311. }
  312. static bool MightInstantiateTo(Sema &S,
  313. FunctionDecl *Context,
  314. FunctionDecl *Friend) {
  315. if (Context->getDeclName() != Friend->getDeclName())
  316. return false;
  317. if (!MightInstantiateTo(S,
  318. Context->getDeclContext(),
  319. Friend->getDeclContext()))
  320. return false;
  321. CanQual<FunctionProtoType> FriendTy
  322. = S.Context.getCanonicalType(Friend->getType())
  323. ->getAs<FunctionProtoType>();
  324. CanQual<FunctionProtoType> ContextTy
  325. = S.Context.getCanonicalType(Context->getType())
  326. ->getAs<FunctionProtoType>();
  327. // There isn't any way that I know of to add qualifiers
  328. // during instantiation.
  329. if (FriendTy.getQualifiers() != ContextTy.getQualifiers())
  330. return false;
  331. if (FriendTy->getNumParams() != ContextTy->getNumParams())
  332. return false;
  333. if (!MightInstantiateTo(S, ContextTy->getReturnType(),
  334. FriendTy->getReturnType()))
  335. return false;
  336. for (unsigned I = 0, E = FriendTy->getNumParams(); I != E; ++I)
  337. if (!MightInstantiateTo(S, ContextTy->getParamType(I),
  338. FriendTy->getParamType(I)))
  339. return false;
  340. return true;
  341. }
  342. static bool MightInstantiateTo(Sema &S,
  343. FunctionTemplateDecl *Context,
  344. FunctionTemplateDecl *Friend) {
  345. return MightInstantiateTo(S,
  346. Context->getTemplatedDecl(),
  347. Friend->getTemplatedDecl());
  348. }
  349. static AccessResult MatchesFriend(Sema &S,
  350. const EffectiveContext &EC,
  351. const CXXRecordDecl *Friend) {
  352. if (EC.includesClass(Friend))
  353. return AR_accessible;
  354. if (EC.isDependent()) {
  355. for (const CXXRecordDecl *Context : EC.Records) {
  356. if (MightInstantiateTo(Context, Friend))
  357. return AR_dependent;
  358. }
  359. }
  360. return AR_inaccessible;
  361. }
  362. static AccessResult MatchesFriend(Sema &S,
  363. const EffectiveContext &EC,
  364. CanQualType Friend) {
  365. if (const RecordType *RT = Friend->getAs<RecordType>())
  366. return MatchesFriend(S, EC, cast<CXXRecordDecl>(RT->getDecl()));
  367. // TODO: we can do better than this
  368. if (Friend->isDependentType())
  369. return AR_dependent;
  370. return AR_inaccessible;
  371. }
  372. /// Determines whether the given friend class template matches
  373. /// anything in the effective context.
  374. static AccessResult MatchesFriend(Sema &S,
  375. const EffectiveContext &EC,
  376. ClassTemplateDecl *Friend) {
  377. AccessResult OnFailure = AR_inaccessible;
  378. // Check whether the friend is the template of a class in the
  379. // context chain.
  380. for (SmallVectorImpl<CXXRecordDecl*>::const_iterator
  381. I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
  382. CXXRecordDecl *Record = *I;
  383. // Figure out whether the current class has a template:
  384. ClassTemplateDecl *CTD;
  385. // A specialization of the template...
  386. if (isa<ClassTemplateSpecializationDecl>(Record)) {
  387. CTD = cast<ClassTemplateSpecializationDecl>(Record)
  388. ->getSpecializedTemplate();
  389. // ... or the template pattern itself.
  390. } else {
  391. CTD = Record->getDescribedClassTemplate();
  392. if (!CTD) continue;
  393. }
  394. // It's a match.
  395. if (Friend == CTD->getCanonicalDecl())
  396. return AR_accessible;
  397. // If the context isn't dependent, it can't be a dependent match.
  398. if (!EC.isDependent())
  399. continue;
  400. // If the template names don't match, it can't be a dependent
  401. // match.
  402. if (CTD->getDeclName() != Friend->getDeclName())
  403. continue;
  404. // If the class's context can't instantiate to the friend's
  405. // context, it can't be a dependent match.
  406. if (!MightInstantiateTo(S, CTD->getDeclContext(),
  407. Friend->getDeclContext()))
  408. continue;
  409. // Otherwise, it's a dependent match.
  410. OnFailure = AR_dependent;
  411. }
  412. return OnFailure;
  413. }
  414. /// Determines whether the given friend function matches anything in
  415. /// the effective context.
  416. static AccessResult MatchesFriend(Sema &S,
  417. const EffectiveContext &EC,
  418. FunctionDecl *Friend) {
  419. AccessResult OnFailure = AR_inaccessible;
  420. for (SmallVectorImpl<FunctionDecl*>::const_iterator
  421. I = EC.Functions.begin(), E = EC.Functions.end(); I != E; ++I) {
  422. if (Friend == *I)
  423. return AR_accessible;
  424. if (EC.isDependent() && MightInstantiateTo(S, *I, Friend))
  425. OnFailure = AR_dependent;
  426. }
  427. return OnFailure;
  428. }
  429. /// Determines whether the given friend function template matches
  430. /// anything in the effective context.
  431. static AccessResult MatchesFriend(Sema &S,
  432. const EffectiveContext &EC,
  433. FunctionTemplateDecl *Friend) {
  434. if (EC.Functions.empty()) return AR_inaccessible;
  435. AccessResult OnFailure = AR_inaccessible;
  436. for (SmallVectorImpl<FunctionDecl*>::const_iterator
  437. I = EC.Functions.begin(), E = EC.Functions.end(); I != E; ++I) {
  438. FunctionTemplateDecl *FTD = (*I)->getPrimaryTemplate();
  439. if (!FTD)
  440. FTD = (*I)->getDescribedFunctionTemplate();
  441. if (!FTD)
  442. continue;
  443. FTD = FTD->getCanonicalDecl();
  444. if (Friend == FTD)
  445. return AR_accessible;
  446. if (EC.isDependent() && MightInstantiateTo(S, FTD, Friend))
  447. OnFailure = AR_dependent;
  448. }
  449. return OnFailure;
  450. }
  451. /// Determines whether the given friend declaration matches anything
  452. /// in the effective context.
  453. static AccessResult MatchesFriend(Sema &S,
  454. const EffectiveContext &EC,
  455. FriendDecl *FriendD) {
  456. // Whitelist accesses if there's an invalid or unsupported friend
  457. // declaration.
  458. if (FriendD->isInvalidDecl() || FriendD->isUnsupportedFriend())
  459. return AR_accessible;
  460. if (TypeSourceInfo *T = FriendD->getFriendType())
  461. return MatchesFriend(S, EC, T->getType()->getCanonicalTypeUnqualified());
  462. NamedDecl *Friend
  463. = cast<NamedDecl>(FriendD->getFriendDecl()->getCanonicalDecl());
  464. // FIXME: declarations with dependent or templated scope.
  465. if (isa<ClassTemplateDecl>(Friend))
  466. return MatchesFriend(S, EC, cast<ClassTemplateDecl>(Friend));
  467. if (isa<FunctionTemplateDecl>(Friend))
  468. return MatchesFriend(S, EC, cast<FunctionTemplateDecl>(Friend));
  469. if (isa<CXXRecordDecl>(Friend))
  470. return MatchesFriend(S, EC, cast<CXXRecordDecl>(Friend));
  471. assert(isa<FunctionDecl>(Friend) && "unknown friend decl kind");
  472. return MatchesFriend(S, EC, cast<FunctionDecl>(Friend));
  473. }
  474. static AccessResult GetFriendKind(Sema &S,
  475. const EffectiveContext &EC,
  476. const CXXRecordDecl *Class) {
  477. AccessResult OnFailure = AR_inaccessible;
  478. // Okay, check friends.
  479. for (auto *Friend : Class->friends()) {
  480. switch (MatchesFriend(S, EC, Friend)) {
  481. case AR_accessible:
  482. return AR_accessible;
  483. case AR_inaccessible:
  484. continue;
  485. case AR_dependent:
  486. OnFailure = AR_dependent;
  487. break;
  488. }
  489. }
  490. // That's it, give up.
  491. return OnFailure;
  492. }
  493. namespace {
  494. /// A helper class for checking for a friend which will grant access
  495. /// to a protected instance member.
  496. struct ProtectedFriendContext {
  497. Sema &S;
  498. const EffectiveContext &EC;
  499. const CXXRecordDecl *NamingClass;
  500. bool CheckDependent;
  501. bool EverDependent;
  502. /// The path down to the current base class.
  503. SmallVector<const CXXRecordDecl*, 20> CurPath;
  504. ProtectedFriendContext(Sema &S, const EffectiveContext &EC,
  505. const CXXRecordDecl *InstanceContext,
  506. const CXXRecordDecl *NamingClass)
  507. : S(S), EC(EC), NamingClass(NamingClass),
  508. CheckDependent(InstanceContext->isDependentContext() ||
  509. NamingClass->isDependentContext()),
  510. EverDependent(false) {}
  511. /// Check classes in the current path for friendship, starting at
  512. /// the given index.
  513. bool checkFriendshipAlongPath(unsigned I) {
  514. assert(I < CurPath.size());
  515. for (unsigned E = CurPath.size(); I != E; ++I) {
  516. switch (GetFriendKind(S, EC, CurPath[I])) {
  517. case AR_accessible: return true;
  518. case AR_inaccessible: continue;
  519. case AR_dependent: EverDependent = true; continue;
  520. }
  521. }
  522. return false;
  523. }
  524. /// Perform a search starting at the given class.
  525. ///
  526. /// PrivateDepth is the index of the last (least derived) class
  527. /// along the current path such that a notional public member of
  528. /// the final class in the path would have access in that class.
  529. bool findFriendship(const CXXRecordDecl *Cur, unsigned PrivateDepth) {
  530. // If we ever reach the naming class, check the current path for
  531. // friendship. We can also stop recursing because we obviously
  532. // won't find the naming class there again.
  533. if (Cur == NamingClass)
  534. return checkFriendshipAlongPath(PrivateDepth);
  535. if (CheckDependent && MightInstantiateTo(Cur, NamingClass))
  536. EverDependent = true;
  537. // Recurse into the base classes.
  538. for (const auto &I : Cur->bases()) {
  539. // If this is private inheritance, then a public member of the
  540. // base will not have any access in classes derived from Cur.
  541. unsigned BasePrivateDepth = PrivateDepth;
  542. if (I.getAccessSpecifier() == AS_private)
  543. BasePrivateDepth = CurPath.size() - 1;
  544. const CXXRecordDecl *RD;
  545. QualType T = I.getType();
  546. if (const RecordType *RT = T->getAs<RecordType>()) {
  547. RD = cast<CXXRecordDecl>(RT->getDecl());
  548. } else if (const InjectedClassNameType *IT
  549. = T->getAs<InjectedClassNameType>()) {
  550. RD = IT->getDecl();
  551. } else {
  552. assert(T->isDependentType() && "non-dependent base wasn't a record?");
  553. EverDependent = true;
  554. continue;
  555. }
  556. // Recurse. We don't need to clean up if this returns true.
  557. CurPath.push_back(RD);
  558. if (findFriendship(RD->getCanonicalDecl(), BasePrivateDepth))
  559. return true;
  560. CurPath.pop_back();
  561. }
  562. return false;
  563. }
  564. bool findFriendship(const CXXRecordDecl *Cur) {
  565. assert(CurPath.empty());
  566. CurPath.push_back(Cur);
  567. return findFriendship(Cur, 0);
  568. }
  569. };
  570. }
  571. /// Search for a class P that EC is a friend of, under the constraint
  572. /// InstanceContext <= P
  573. /// if InstanceContext exists, or else
  574. /// NamingClass <= P
  575. /// and with the additional restriction that a protected member of
  576. /// NamingClass would have some natural access in P, which implicitly
  577. /// imposes the constraint that P <= NamingClass.
  578. ///
  579. /// This isn't quite the condition laid out in the standard.
  580. /// Instead of saying that a notional protected member of NamingClass
  581. /// would have to have some natural access in P, it says the actual
  582. /// target has to have some natural access in P, which opens up the
  583. /// possibility that the target (which is not necessarily a member
  584. /// of NamingClass) might be more accessible along some path not
  585. /// passing through it. That's really a bad idea, though, because it
  586. /// introduces two problems:
  587. /// - Most importantly, it breaks encapsulation because you can
  588. /// access a forbidden base class's members by directly subclassing
  589. /// it elsewhere.
  590. /// - It also makes access substantially harder to compute because it
  591. /// breaks the hill-climbing algorithm: knowing that the target is
  592. /// accessible in some base class would no longer let you change
  593. /// the question solely to whether the base class is accessible,
  594. /// because the original target might have been more accessible
  595. /// because of crazy subclassing.
  596. /// So we don't implement that.
  597. static AccessResult GetProtectedFriendKind(Sema &S, const EffectiveContext &EC,
  598. const CXXRecordDecl *InstanceContext,
  599. const CXXRecordDecl *NamingClass) {
  600. assert(InstanceContext == nullptr ||
  601. InstanceContext->getCanonicalDecl() == InstanceContext);
  602. assert(NamingClass->getCanonicalDecl() == NamingClass);
  603. // If we don't have an instance context, our constraints give us
  604. // that NamingClass <= P <= NamingClass, i.e. P == NamingClass.
  605. // This is just the usual friendship check.
  606. if (!InstanceContext) return GetFriendKind(S, EC, NamingClass);
  607. ProtectedFriendContext PRC(S, EC, InstanceContext, NamingClass);
  608. if (PRC.findFriendship(InstanceContext)) return AR_accessible;
  609. if (PRC.EverDependent) return AR_dependent;
  610. return AR_inaccessible;
  611. }
  612. static AccessResult HasAccess(Sema &S,
  613. const EffectiveContext &EC,
  614. const CXXRecordDecl *NamingClass,
  615. AccessSpecifier Access,
  616. const AccessTarget &Target) {
  617. assert(NamingClass->getCanonicalDecl() == NamingClass &&
  618. "declaration should be canonicalized before being passed here");
  619. if (Access == AS_public) return AR_accessible;
  620. assert(Access == AS_private || Access == AS_protected);
  621. AccessResult OnFailure = AR_inaccessible;
  622. for (EffectiveContext::record_iterator
  623. I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
  624. // All the declarations in EC have been canonicalized, so pointer
  625. // equality from this point on will work fine.
  626. const CXXRecordDecl *ECRecord = *I;
  627. // [B2] and [M2]
  628. if (Access == AS_private) {
  629. if (ECRecord == NamingClass)
  630. return AR_accessible;
  631. if (EC.isDependent() && MightInstantiateTo(ECRecord, NamingClass))
  632. OnFailure = AR_dependent;
  633. // [B3] and [M3]
  634. } else {
  635. assert(Access == AS_protected);
  636. switch (IsDerivedFromInclusive(ECRecord, NamingClass)) {
  637. case AR_accessible: break;
  638. case AR_inaccessible: continue;
  639. case AR_dependent: OnFailure = AR_dependent; continue;
  640. }
  641. // C++ [class.protected]p1:
  642. // An additional access check beyond those described earlier in
  643. // [class.access] is applied when a non-static data member or
  644. // non-static member function is a protected member of its naming
  645. // class. As described earlier, access to a protected member is
  646. // granted because the reference occurs in a friend or member of
  647. // some class C. If the access is to form a pointer to member,
  648. // the nested-name-specifier shall name C or a class derived from
  649. // C. All other accesses involve a (possibly implicit) object
  650. // expression. In this case, the class of the object expression
  651. // shall be C or a class derived from C.
  652. //
  653. // We interpret this as a restriction on [M3].
  654. // In this part of the code, 'C' is just our context class ECRecord.
  655. // These rules are different if we don't have an instance context.
  656. if (!Target.hasInstanceContext()) {
  657. // If it's not an instance member, these restrictions don't apply.
  658. if (!Target.isInstanceMember()) return AR_accessible;
  659. // If it's an instance member, use the pointer-to-member rule
  660. // that the naming class has to be derived from the effective
  661. // context.
  662. // Emulate a MSVC bug where the creation of pointer-to-member
  663. // to protected member of base class is allowed but only from
  664. // static member functions.
  665. if (S.getLangOpts().MSVCCompat && !EC.Functions.empty())
  666. if (CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(EC.Functions.front()))
  667. if (MD->isStatic()) return AR_accessible;
  668. // Despite the standard's confident wording, there is a case
  669. // where you can have an instance member that's neither in a
  670. // pointer-to-member expression nor in a member access: when
  671. // it names a field in an unevaluated context that can't be an
  672. // implicit member. Pending clarification, we just apply the
  673. // same naming-class restriction here.
  674. // FIXME: we're probably not correctly adding the
  675. // protected-member restriction when we retroactively convert
  676. // an expression to being evaluated.
  677. // We know that ECRecord derives from NamingClass. The
  678. // restriction says to check whether NamingClass derives from
  679. // ECRecord, but that's not really necessary: two distinct
  680. // classes can't be recursively derived from each other. So
  681. // along this path, we just need to check whether the classes
  682. // are equal.
  683. if (NamingClass == ECRecord) return AR_accessible;
  684. // Otherwise, this context class tells us nothing; on to the next.
  685. continue;
  686. }
  687. assert(Target.isInstanceMember());
  688. const CXXRecordDecl *InstanceContext = Target.resolveInstanceContext(S);
  689. if (!InstanceContext) {
  690. OnFailure = AR_dependent;
  691. continue;
  692. }
  693. switch (IsDerivedFromInclusive(InstanceContext, ECRecord)) {
  694. case AR_accessible: return AR_accessible;
  695. case AR_inaccessible: continue;
  696. case AR_dependent: OnFailure = AR_dependent; continue;
  697. }
  698. }
  699. }
  700. // [M3] and [B3] say that, if the target is protected in N, we grant
  701. // access if the access occurs in a friend or member of some class P
  702. // that's a subclass of N and where the target has some natural
  703. // access in P. The 'member' aspect is easy to handle because P
  704. // would necessarily be one of the effective-context records, and we
  705. // address that above. The 'friend' aspect is completely ridiculous
  706. // to implement because there are no restrictions at all on P
  707. // *unless* the [class.protected] restriction applies. If it does,
  708. // however, we should ignore whether the naming class is a friend,
  709. // and instead rely on whether any potential P is a friend.
  710. if (Access == AS_protected && Target.isInstanceMember()) {
  711. // Compute the instance context if possible.
  712. const CXXRecordDecl *InstanceContext = nullptr;
  713. if (Target.hasInstanceContext()) {
  714. InstanceContext = Target.resolveInstanceContext(S);
  715. if (!InstanceContext) return AR_dependent;
  716. }
  717. switch (GetProtectedFriendKind(S, EC, InstanceContext, NamingClass)) {
  718. case AR_accessible: return AR_accessible;
  719. case AR_inaccessible: return OnFailure;
  720. case AR_dependent: return AR_dependent;
  721. }
  722. llvm_unreachable("impossible friendship kind");
  723. }
  724. switch (GetFriendKind(S, EC, NamingClass)) {
  725. case AR_accessible: return AR_accessible;
  726. case AR_inaccessible: return OnFailure;
  727. case AR_dependent: return AR_dependent;
  728. }
  729. // Silence bogus warnings
  730. llvm_unreachable("impossible friendship kind");
  731. }
  732. /// Finds the best path from the naming class to the declaring class,
  733. /// taking friend declarations into account.
  734. ///
  735. /// C++0x [class.access.base]p5:
  736. /// A member m is accessible at the point R when named in class N if
  737. /// [M1] m as a member of N is public, or
  738. /// [M2] m as a member of N is private, and R occurs in a member or
  739. /// friend of class N, or
  740. /// [M3] m as a member of N is protected, and R occurs in a member or
  741. /// friend of class N, or in a member or friend of a class P
  742. /// derived from N, where m as a member of P is public, private,
  743. /// or protected, or
  744. /// [M4] there exists a base class B of N that is accessible at R, and
  745. /// m is accessible at R when named in class B.
  746. ///
  747. /// C++0x [class.access.base]p4:
  748. /// A base class B of N is accessible at R, if
  749. /// [B1] an invented public member of B would be a public member of N, or
  750. /// [B2] R occurs in a member or friend of class N, and an invented public
  751. /// member of B would be a private or protected member of N, or
  752. /// [B3] R occurs in a member or friend of a class P derived from N, and an
  753. /// invented public member of B would be a private or protected member
  754. /// of P, or
  755. /// [B4] there exists a class S such that B is a base class of S accessible
  756. /// at R and S is a base class of N accessible at R.
  757. ///
  758. /// Along a single inheritance path we can restate both of these
  759. /// iteratively:
  760. ///
  761. /// First, we note that M1-4 are equivalent to B1-4 if the member is
  762. /// treated as a notional base of its declaring class with inheritance
  763. /// access equivalent to the member's access. Therefore we need only
  764. /// ask whether a class B is accessible from a class N in context R.
  765. ///
  766. /// Let B_1 .. B_n be the inheritance path in question (i.e. where
  767. /// B_1 = N, B_n = B, and for all i, B_{i+1} is a direct base class of
  768. /// B_i). For i in 1..n, we will calculate ACAB(i), the access to the
  769. /// closest accessible base in the path:
  770. /// Access(a, b) = (* access on the base specifier from a to b *)
  771. /// Merge(a, forbidden) = forbidden
  772. /// Merge(a, private) = forbidden
  773. /// Merge(a, b) = min(a,b)
  774. /// Accessible(c, forbidden) = false
  775. /// Accessible(c, private) = (R is c) || IsFriend(c, R)
  776. /// Accessible(c, protected) = (R derived from c) || IsFriend(c, R)
  777. /// Accessible(c, public) = true
  778. /// ACAB(n) = public
  779. /// ACAB(i) =
  780. /// let AccessToBase = Merge(Access(B_i, B_{i+1}), ACAB(i+1)) in
  781. /// if Accessible(B_i, AccessToBase) then public else AccessToBase
  782. ///
  783. /// B is an accessible base of N at R iff ACAB(1) = public.
  784. ///
  785. /// \param FinalAccess the access of the "final step", or AS_public if
  786. /// there is no final step.
  787. /// \return null if friendship is dependent
  788. static CXXBasePath *FindBestPath(Sema &S,
  789. const EffectiveContext &EC,
  790. AccessTarget &Target,
  791. AccessSpecifier FinalAccess,
  792. CXXBasePaths &Paths) {
  793. // Derive the paths to the desired base.
  794. const CXXRecordDecl *Derived = Target.getNamingClass();
  795. const CXXRecordDecl *Base = Target.getDeclaringClass();
  796. // FIXME: fail correctly when there are dependent paths.
  797. bool isDerived = Derived->isDerivedFrom(const_cast<CXXRecordDecl*>(Base),
  798. Paths);
  799. assert(isDerived && "derived class not actually derived from base");
  800. (void) isDerived;
  801. CXXBasePath *BestPath = nullptr;
  802. assert(FinalAccess != AS_none && "forbidden access after declaring class");
  803. bool AnyDependent = false;
  804. // Derive the friend-modified access along each path.
  805. for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
  806. PI != PE; ++PI) {
  807. AccessTarget::SavedInstanceContext _ = Target.saveInstanceContext();
  808. // Walk through the path backwards.
  809. AccessSpecifier PathAccess = FinalAccess;
  810. CXXBasePath::iterator I = PI->end(), E = PI->begin();
  811. while (I != E) {
  812. --I;
  813. assert(PathAccess != AS_none);
  814. // If the declaration is a private member of a base class, there
  815. // is no level of friendship in derived classes that can make it
  816. // accessible.
  817. if (PathAccess == AS_private) {
  818. PathAccess = AS_none;
  819. break;
  820. }
  821. const CXXRecordDecl *NC = I->Class->getCanonicalDecl();
  822. AccessSpecifier BaseAccess = I->Base->getAccessSpecifier();
  823. PathAccess = std::max(PathAccess, BaseAccess);
  824. switch (HasAccess(S, EC, NC, PathAccess, Target)) {
  825. case AR_inaccessible: break;
  826. case AR_accessible:
  827. PathAccess = AS_public;
  828. // Future tests are not against members and so do not have
  829. // instance context.
  830. Target.suppressInstanceContext();
  831. break;
  832. case AR_dependent:
  833. AnyDependent = true;
  834. goto Next;
  835. }
  836. }
  837. // Note that we modify the path's Access field to the
  838. // friend-modified access.
  839. if (BestPath == nullptr || PathAccess < BestPath->Access) {
  840. BestPath = &*PI;
  841. BestPath->Access = PathAccess;
  842. // Short-circuit if we found a public path.
  843. if (BestPath->Access == AS_public)
  844. return BestPath;
  845. }
  846. Next: ;
  847. }
  848. assert((!BestPath || BestPath->Access != AS_public) &&
  849. "fell out of loop with public path");
  850. // We didn't find a public path, but at least one path was subject
  851. // to dependent friendship, so delay the check.
  852. if (AnyDependent)
  853. return nullptr;
  854. return BestPath;
  855. }
  856. /// Given that an entity has protected natural access, check whether
  857. /// access might be denied because of the protected member access
  858. /// restriction.
  859. ///
  860. /// \return true if a note was emitted
  861. static bool TryDiagnoseProtectedAccess(Sema &S, const EffectiveContext &EC,
  862. AccessTarget &Target) {
  863. // Only applies to instance accesses.
  864. if (!Target.isInstanceMember())
  865. return false;
  866. assert(Target.isMemberAccess());
  867. const CXXRecordDecl *NamingClass = Target.getEffectiveNamingClass();
  868. for (EffectiveContext::record_iterator
  869. I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
  870. const CXXRecordDecl *ECRecord = *I;
  871. switch (IsDerivedFromInclusive(ECRecord, NamingClass)) {
  872. case AR_accessible: break;
  873. case AR_inaccessible: continue;
  874. case AR_dependent: continue;
  875. }
  876. // The effective context is a subclass of the declaring class.
  877. // Check whether the [class.protected] restriction is limiting
  878. // access.
  879. // To get this exactly right, this might need to be checked more
  880. // holistically; it's not necessarily the case that gaining
  881. // access here would grant us access overall.
  882. NamedDecl *D = Target.getTargetDecl();
  883. // If we don't have an instance context, [class.protected] says the
  884. // naming class has to equal the context class.
  885. if (!Target.hasInstanceContext()) {
  886. // If it does, the restriction doesn't apply.
  887. if (NamingClass == ECRecord) continue;
  888. // TODO: it would be great to have a fixit here, since this is
  889. // such an obvious error.
  890. S.Diag(D->getLocation(), diag::note_access_protected_restricted_noobject)
  891. << S.Context.getTypeDeclType(ECRecord);
  892. return true;
  893. }
  894. const CXXRecordDecl *InstanceContext = Target.resolveInstanceContext(S);
  895. assert(InstanceContext && "diagnosing dependent access");
  896. switch (IsDerivedFromInclusive(InstanceContext, ECRecord)) {
  897. case AR_accessible: continue;
  898. case AR_dependent: continue;
  899. case AR_inaccessible:
  900. break;
  901. }
  902. // Okay, the restriction seems to be what's limiting us.
  903. // Use a special diagnostic for constructors and destructors.
  904. if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D) ||
  905. (isa<FunctionTemplateDecl>(D) &&
  906. isa<CXXConstructorDecl>(
  907. cast<FunctionTemplateDecl>(D)->getTemplatedDecl()))) {
  908. return S.Diag(D->getLocation(),
  909. diag::note_access_protected_restricted_ctordtor)
  910. << isa<CXXDestructorDecl>(D->getAsFunction());
  911. }
  912. // Otherwise, use the generic diagnostic.
  913. return S.Diag(D->getLocation(),
  914. diag::note_access_protected_restricted_object)
  915. << S.Context.getTypeDeclType(ECRecord);
  916. }
  917. return false;
  918. }
  919. /// We are unable to access a given declaration due to its direct
  920. /// access control; diagnose that.
  921. static void diagnoseBadDirectAccess(Sema &S,
  922. const EffectiveContext &EC,
  923. AccessTarget &entity) {
  924. assert(entity.isMemberAccess());
  925. NamedDecl *D = entity.getTargetDecl();
  926. if (D->getAccess() == AS_protected &&
  927. TryDiagnoseProtectedAccess(S, EC, entity))
  928. return;
  929. // Find an original declaration.
  930. while (D->isOutOfLine()) {
  931. NamedDecl *PrevDecl = nullptr;
  932. if (VarDecl *VD = dyn_cast<VarDecl>(D))
  933. PrevDecl = VD->getPreviousDecl();
  934. else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  935. PrevDecl = FD->getPreviousDecl();
  936. else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(D))
  937. PrevDecl = TND->getPreviousDecl();
  938. else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
  939. if (isa<RecordDecl>(D) && cast<RecordDecl>(D)->isInjectedClassName())
  940. break;
  941. PrevDecl = TD->getPreviousDecl();
  942. }
  943. if (!PrevDecl) break;
  944. D = PrevDecl;
  945. }
  946. CXXRecordDecl *DeclaringClass = FindDeclaringClass(D);
  947. Decl *ImmediateChild;
  948. if (D->getDeclContext() == DeclaringClass)
  949. ImmediateChild = D;
  950. else {
  951. DeclContext *DC = D->getDeclContext();
  952. while (DC->getParent() != DeclaringClass)
  953. DC = DC->getParent();
  954. ImmediateChild = cast<Decl>(DC);
  955. }
  956. // Check whether there's an AccessSpecDecl preceding this in the
  957. // chain of the DeclContext.
  958. bool isImplicit = true;
  959. for (const auto *I : DeclaringClass->decls()) {
  960. if (I == ImmediateChild) break;
  961. if (isa<AccessSpecDecl>(I)) {
  962. isImplicit = false;
  963. break;
  964. }
  965. }
  966. S.Diag(D->getLocation(), diag::note_access_natural)
  967. << (unsigned) (D->getAccess() == AS_protected)
  968. << isImplicit;
  969. }
  970. /// Diagnose the path which caused the given declaration or base class
  971. /// to become inaccessible.
  972. static void DiagnoseAccessPath(Sema &S,
  973. const EffectiveContext &EC,
  974. AccessTarget &entity) {
  975. // Save the instance context to preserve invariants.
  976. AccessTarget::SavedInstanceContext _ = entity.saveInstanceContext();
  977. // This basically repeats the main algorithm but keeps some more
  978. // information.
  979. // The natural access so far.
  980. AccessSpecifier accessSoFar = AS_public;
  981. // Check whether we have special rights to the declaring class.
  982. if (entity.isMemberAccess()) {
  983. NamedDecl *D = entity.getTargetDecl();
  984. accessSoFar = D->getAccess();
  985. const CXXRecordDecl *declaringClass = entity.getDeclaringClass();
  986. switch (HasAccess(S, EC, declaringClass, accessSoFar, entity)) {
  987. // If the declaration is accessible when named in its declaring
  988. // class, then we must be constrained by the path.
  989. case AR_accessible:
  990. accessSoFar = AS_public;
  991. entity.suppressInstanceContext();
  992. break;
  993. case AR_inaccessible:
  994. if (accessSoFar == AS_private ||
  995. declaringClass == entity.getEffectiveNamingClass())
  996. return diagnoseBadDirectAccess(S, EC, entity);
  997. break;
  998. case AR_dependent:
  999. llvm_unreachable("cannot diagnose dependent access");
  1000. }
  1001. }
  1002. CXXBasePaths paths;
  1003. CXXBasePath &path = *FindBestPath(S, EC, entity, accessSoFar, paths);
  1004. assert(path.Access != AS_public);
  1005. CXXBasePath::iterator i = path.end(), e = path.begin();
  1006. CXXBasePath::iterator constrainingBase = i;
  1007. while (i != e) {
  1008. --i;
  1009. assert(accessSoFar != AS_none && accessSoFar != AS_private);
  1010. // Is the entity accessible when named in the deriving class, as
  1011. // modified by the base specifier?
  1012. const CXXRecordDecl *derivingClass = i->Class->getCanonicalDecl();
  1013. const CXXBaseSpecifier *base = i->Base;
  1014. // If the access to this base is worse than the access we have to
  1015. // the declaration, remember it.
  1016. AccessSpecifier baseAccess = base->getAccessSpecifier();
  1017. if (baseAccess > accessSoFar) {
  1018. constrainingBase = i;
  1019. accessSoFar = baseAccess;
  1020. }
  1021. switch (HasAccess(S, EC, derivingClass, accessSoFar, entity)) {
  1022. case AR_inaccessible: break;
  1023. case AR_accessible:
  1024. accessSoFar = AS_public;
  1025. entity.suppressInstanceContext();
  1026. constrainingBase = nullptr;
  1027. break;
  1028. case AR_dependent:
  1029. llvm_unreachable("cannot diagnose dependent access");
  1030. }
  1031. // If this was private inheritance, but we don't have access to
  1032. // the deriving class, we're done.
  1033. if (accessSoFar == AS_private) {
  1034. assert(baseAccess == AS_private);
  1035. assert(constrainingBase == i);
  1036. break;
  1037. }
  1038. }
  1039. // If we don't have a constraining base, the access failure must be
  1040. // due to the original declaration.
  1041. if (constrainingBase == path.end())
  1042. return diagnoseBadDirectAccess(S, EC, entity);
  1043. // We're constrained by inheritance, but we want to say
  1044. // "declared private here" if we're diagnosing a hierarchy
  1045. // conversion and this is the final step.
  1046. unsigned diagnostic;
  1047. if (entity.isMemberAccess() ||
  1048. constrainingBase + 1 != path.end()) {
  1049. diagnostic = diag::note_access_constrained_by_path;
  1050. } else {
  1051. diagnostic = diag::note_access_natural;
  1052. }
  1053. const CXXBaseSpecifier *base = constrainingBase->Base;
  1054. S.Diag(base->getSourceRange().getBegin(), diagnostic)
  1055. << base->getSourceRange()
  1056. << (base->getAccessSpecifier() == AS_protected)
  1057. << (base->getAccessSpecifierAsWritten() == AS_none);
  1058. if (entity.isMemberAccess())
  1059. S.Diag(entity.getTargetDecl()->getLocation(),
  1060. diag::note_member_declared_at);
  1061. }
  1062. static void DiagnoseBadAccess(Sema &S, SourceLocation Loc,
  1063. const EffectiveContext &EC,
  1064. AccessTarget &Entity) {
  1065. const CXXRecordDecl *NamingClass = Entity.getNamingClass();
  1066. const CXXRecordDecl *DeclaringClass = Entity.getDeclaringClass();
  1067. NamedDecl *D = (Entity.isMemberAccess() ? Entity.getTargetDecl() : nullptr);
  1068. S.Diag(Loc, Entity.getDiag())
  1069. << (Entity.getAccess() == AS_protected)
  1070. << (D ? D->getDeclName() : DeclarationName())
  1071. << S.Context.getTypeDeclType(NamingClass)
  1072. << S.Context.getTypeDeclType(DeclaringClass);
  1073. DiagnoseAccessPath(S, EC, Entity);
  1074. }
  1075. /// MSVC has a bug where if during an using declaration name lookup,
  1076. /// the declaration found is unaccessible (private) and that declaration
  1077. /// was bring into scope via another using declaration whose target
  1078. /// declaration is accessible (public) then no error is generated.
  1079. /// Example:
  1080. /// class A {
  1081. /// public:
  1082. /// int f();
  1083. /// };
  1084. /// class B : public A {
  1085. /// private:
  1086. /// using A::f;
  1087. /// };
  1088. /// class C : public B {
  1089. /// private:
  1090. /// using B::f;
  1091. /// };
  1092. ///
  1093. /// Here, B::f is private so this should fail in Standard C++, but
  1094. /// because B::f refers to A::f which is public MSVC accepts it.
  1095. static bool IsMicrosoftUsingDeclarationAccessBug(Sema& S,
  1096. SourceLocation AccessLoc,
  1097. AccessTarget &Entity) {
  1098. if (UsingShadowDecl *Shadow =
  1099. dyn_cast<UsingShadowDecl>(Entity.getTargetDecl()))
  1100. if (UsingDecl *UD = dyn_cast<UsingDecl>(Shadow->getIntroducer())) {
  1101. const NamedDecl *OrigDecl = Entity.getTargetDecl()->getUnderlyingDecl();
  1102. if (Entity.getTargetDecl()->getAccess() == AS_private &&
  1103. (OrigDecl->getAccess() == AS_public ||
  1104. OrigDecl->getAccess() == AS_protected)) {
  1105. S.Diag(AccessLoc, diag::ext_ms_using_declaration_inaccessible)
  1106. << UD->getQualifiedNameAsString()
  1107. << OrigDecl->getQualifiedNameAsString();
  1108. return true;
  1109. }
  1110. }
  1111. return false;
  1112. }
  1113. /// Determines whether the accessed entity is accessible. Public members
  1114. /// have been weeded out by this point.
  1115. static AccessResult IsAccessible(Sema &S,
  1116. const EffectiveContext &EC,
  1117. AccessTarget &Entity) {
  1118. // Determine the actual naming class.
  1119. const CXXRecordDecl *NamingClass = Entity.getEffectiveNamingClass();
  1120. AccessSpecifier UnprivilegedAccess = Entity.getAccess();
  1121. assert(UnprivilegedAccess != AS_public && "public access not weeded out");
  1122. // Before we try to recalculate access paths, try to white-list
  1123. // accesses which just trade in on the final step, i.e. accesses
  1124. // which don't require [M4] or [B4]. These are by far the most
  1125. // common forms of privileged access.
  1126. if (UnprivilegedAccess != AS_none) {
  1127. switch (HasAccess(S, EC, NamingClass, UnprivilegedAccess, Entity)) {
  1128. case AR_dependent:
  1129. // This is actually an interesting policy decision. We don't
  1130. // *have* to delay immediately here: we can do the full access
  1131. // calculation in the hope that friendship on some intermediate
  1132. // class will make the declaration accessible non-dependently.
  1133. // But that's not cheap, and odds are very good (note: assertion
  1134. // made without data) that the friend declaration will determine
  1135. // access.
  1136. return AR_dependent;
  1137. case AR_accessible: return AR_accessible;
  1138. case AR_inaccessible: break;
  1139. }
  1140. }
  1141. AccessTarget::SavedInstanceContext _ = Entity.saveInstanceContext();
  1142. // We lower member accesses to base accesses by pretending that the
  1143. // member is a base class of its declaring class.
  1144. AccessSpecifier FinalAccess;
  1145. if (Entity.isMemberAccess()) {
  1146. // Determine if the declaration is accessible from EC when named
  1147. // in its declaring class.
  1148. NamedDecl *Target = Entity.getTargetDecl();
  1149. const CXXRecordDecl *DeclaringClass = Entity.getDeclaringClass();
  1150. FinalAccess = Target->getAccess();
  1151. switch (HasAccess(S, EC, DeclaringClass, FinalAccess, Entity)) {
  1152. case AR_accessible:
  1153. // Target is accessible at EC when named in its declaring class.
  1154. // We can now hill-climb and simply check whether the declaring
  1155. // class is accessible as a base of the naming class. This is
  1156. // equivalent to checking the access of a notional public
  1157. // member with no instance context.
  1158. FinalAccess = AS_public;
  1159. Entity.suppressInstanceContext();
  1160. break;
  1161. case AR_inaccessible: break;
  1162. case AR_dependent: return AR_dependent; // see above
  1163. }
  1164. if (DeclaringClass == NamingClass)
  1165. return (FinalAccess == AS_public ? AR_accessible : AR_inaccessible);
  1166. } else {
  1167. FinalAccess = AS_public;
  1168. }
  1169. assert(Entity.getDeclaringClass() != NamingClass);
  1170. // Append the declaration's access if applicable.
  1171. CXXBasePaths Paths;
  1172. CXXBasePath *Path = FindBestPath(S, EC, Entity, FinalAccess, Paths);
  1173. if (!Path)
  1174. return AR_dependent;
  1175. assert(Path->Access <= UnprivilegedAccess &&
  1176. "access along best path worse than direct?");
  1177. if (Path->Access == AS_public)
  1178. return AR_accessible;
  1179. return AR_inaccessible;
  1180. }
  1181. static void DelayDependentAccess(Sema &S,
  1182. const EffectiveContext &EC,
  1183. SourceLocation Loc,
  1184. const AccessTarget &Entity) {
  1185. assert(EC.isDependent() && "delaying non-dependent access");
  1186. DeclContext *DC = EC.getInnerContext();
  1187. assert(DC->isDependentContext() && "delaying non-dependent access");
  1188. DependentDiagnostic::Create(S.Context, DC, DependentDiagnostic::Access,
  1189. Loc,
  1190. Entity.isMemberAccess(),
  1191. Entity.getAccess(),
  1192. Entity.getTargetDecl(),
  1193. Entity.getNamingClass(),
  1194. Entity.getBaseObjectType(),
  1195. Entity.getDiag());
  1196. }
  1197. /// Checks access to an entity from the given effective context.
  1198. static AccessResult CheckEffectiveAccess(Sema &S,
  1199. const EffectiveContext &EC,
  1200. SourceLocation Loc,
  1201. AccessTarget &Entity) {
  1202. assert(Entity.getAccess() != AS_public && "called for public access!");
  1203. switch (IsAccessible(S, EC, Entity)) {
  1204. case AR_dependent:
  1205. DelayDependentAccess(S, EC, Loc, Entity);
  1206. return AR_dependent;
  1207. case AR_inaccessible:
  1208. if (S.getLangOpts().MSVCCompat &&
  1209. IsMicrosoftUsingDeclarationAccessBug(S, Loc, Entity))
  1210. return AR_accessible;
  1211. if (!Entity.isQuiet())
  1212. DiagnoseBadAccess(S, Loc, EC, Entity);
  1213. return AR_inaccessible;
  1214. case AR_accessible:
  1215. return AR_accessible;
  1216. }
  1217. // silence unnecessary warning
  1218. llvm_unreachable("invalid access result");
  1219. }
  1220. static Sema::AccessResult CheckAccess(Sema &S, SourceLocation Loc,
  1221. AccessTarget &Entity) {
  1222. // If the access path is public, it's accessible everywhere.
  1223. if (Entity.getAccess() == AS_public)
  1224. return Sema::AR_accessible;
  1225. // If we're currently parsing a declaration, we may need to delay
  1226. // access control checking, because our effective context might be
  1227. // different based on what the declaration comes out as.
  1228. //
  1229. // For example, we might be parsing a declaration with a scope
  1230. // specifier, like this:
  1231. // A::private_type A::foo() { ... }
  1232. //
  1233. // Or we might be parsing something that will turn out to be a friend:
  1234. // void foo(A::private_type);
  1235. // void B::foo(A::private_type);
  1236. if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
  1237. S.DelayedDiagnostics.add(DelayedDiagnostic::makeAccess(Loc, Entity));
  1238. return Sema::AR_delayed;
  1239. }
  1240. EffectiveContext EC(S.CurContext);
  1241. switch (CheckEffectiveAccess(S, EC, Loc, Entity)) {
  1242. case AR_accessible: return Sema::AR_accessible;
  1243. case AR_inaccessible: return Sema::AR_inaccessible;
  1244. case AR_dependent: return Sema::AR_dependent;
  1245. }
  1246. llvm_unreachable("invalid access result");
  1247. }
  1248. void Sema::HandleDelayedAccessCheck(DelayedDiagnostic &DD, Decl *D) {
  1249. // Access control for names used in the declarations of functions
  1250. // and function templates should normally be evaluated in the context
  1251. // of the declaration, just in case it's a friend of something.
  1252. // However, this does not apply to local extern declarations.
  1253. DeclContext *DC = D->getDeclContext();
  1254. if (D->isLocalExternDecl()) {
  1255. DC = D->getLexicalDeclContext();
  1256. } else if (FunctionDecl *FN = dyn_cast<FunctionDecl>(D)) {
  1257. DC = FN;
  1258. } else if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
  1259. if (isa<DeclContext>(TD->getTemplatedDecl()))
  1260. DC = cast<DeclContext>(TD->getTemplatedDecl());
  1261. }
  1262. EffectiveContext EC(DC);
  1263. AccessTarget Target(DD.getAccessData());
  1264. if (CheckEffectiveAccess(*this, EC, DD.Loc, Target) == ::AR_inaccessible)
  1265. DD.Triggered = true;
  1266. }
  1267. void Sema::HandleDependentAccessCheck(const DependentDiagnostic &DD,
  1268. const MultiLevelTemplateArgumentList &TemplateArgs) {
  1269. SourceLocation Loc = DD.getAccessLoc();
  1270. AccessSpecifier Access = DD.getAccess();
  1271. Decl *NamingD = FindInstantiatedDecl(Loc, DD.getAccessNamingClass(),
  1272. TemplateArgs);
  1273. if (!NamingD) return;
  1274. Decl *TargetD = FindInstantiatedDecl(Loc, DD.getAccessTarget(),
  1275. TemplateArgs);
  1276. if (!TargetD) return;
  1277. if (DD.isAccessToMember()) {
  1278. CXXRecordDecl *NamingClass = cast<CXXRecordDecl>(NamingD);
  1279. NamedDecl *TargetDecl = cast<NamedDecl>(TargetD);
  1280. QualType BaseObjectType = DD.getAccessBaseObjectType();
  1281. if (!BaseObjectType.isNull()) {
  1282. BaseObjectType = SubstType(BaseObjectType, TemplateArgs, Loc,
  1283. DeclarationName());
  1284. if (BaseObjectType.isNull()) return;
  1285. }
  1286. AccessTarget Entity(Context,
  1287. AccessTarget::Member,
  1288. NamingClass,
  1289. DeclAccessPair::make(TargetDecl, Access),
  1290. BaseObjectType);
  1291. Entity.setDiag(DD.getDiagnostic());
  1292. CheckAccess(*this, Loc, Entity);
  1293. } else {
  1294. AccessTarget Entity(Context,
  1295. AccessTarget::Base,
  1296. cast<CXXRecordDecl>(TargetD),
  1297. cast<CXXRecordDecl>(NamingD),
  1298. Access);
  1299. Entity.setDiag(DD.getDiagnostic());
  1300. CheckAccess(*this, Loc, Entity);
  1301. }
  1302. }
  1303. Sema::AccessResult Sema::CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
  1304. DeclAccessPair Found) {
  1305. if (!getLangOpts().AccessControl ||
  1306. !E->getNamingClass() ||
  1307. Found.getAccess() == AS_public)
  1308. return AR_accessible;
  1309. AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(),
  1310. Found, QualType());
  1311. Entity.setDiag(diag::err_access) << E->getSourceRange();
  1312. return CheckAccess(*this, E->getNameLoc(), Entity);
  1313. }
  1314. /// Perform access-control checking on a previously-unresolved member
  1315. /// access which has now been resolved to a member.
  1316. Sema::AccessResult Sema::CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
  1317. DeclAccessPair Found) {
  1318. if (!getLangOpts().AccessControl ||
  1319. Found.getAccess() == AS_public)
  1320. return AR_accessible;
  1321. QualType BaseType = E->getBaseType();
  1322. if (E->isArrow())
  1323. BaseType = BaseType->castAs<PointerType>()->getPointeeType();
  1324. AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(),
  1325. Found, BaseType);
  1326. Entity.setDiag(diag::err_access) << E->getSourceRange();
  1327. return CheckAccess(*this, E->getMemberLoc(), Entity);
  1328. }
  1329. /// Is the given member accessible for the purposes of deciding whether to
  1330. /// define a special member function as deleted?
  1331. bool Sema::isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
  1332. DeclAccessPair Found,
  1333. QualType ObjectType,
  1334. SourceLocation Loc,
  1335. const PartialDiagnostic &Diag) {
  1336. // Fast path.
  1337. if (Found.getAccess() == AS_public || !getLangOpts().AccessControl)
  1338. return true;
  1339. AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
  1340. ObjectType);
  1341. // Suppress diagnostics.
  1342. Entity.setDiag(Diag);
  1343. switch (CheckAccess(*this, Loc, Entity)) {
  1344. case AR_accessible: return true;
  1345. case AR_inaccessible: return false;
  1346. case AR_dependent: llvm_unreachable("dependent for =delete computation");
  1347. case AR_delayed: llvm_unreachable("cannot delay =delete computation");
  1348. }
  1349. llvm_unreachable("bad access result");
  1350. }
  1351. Sema::AccessResult Sema::CheckDestructorAccess(SourceLocation Loc,
  1352. CXXDestructorDecl *Dtor,
  1353. const PartialDiagnostic &PDiag,
  1354. QualType ObjectTy) {
  1355. if (!getLangOpts().AccessControl)
  1356. return AR_accessible;
  1357. // There's never a path involved when checking implicit destructor access.
  1358. AccessSpecifier Access = Dtor->getAccess();
  1359. if (Access == AS_public)
  1360. return AR_accessible;
  1361. CXXRecordDecl *NamingClass = Dtor->getParent();
  1362. if (ObjectTy.isNull()) ObjectTy = Context.getTypeDeclType(NamingClass);
  1363. AccessTarget Entity(Context, AccessTarget::Member, NamingClass,
  1364. DeclAccessPair::make(Dtor, Access),
  1365. ObjectTy);
  1366. Entity.setDiag(PDiag); // TODO: avoid copy
  1367. return CheckAccess(*this, Loc, Entity);
  1368. }
  1369. /// Checks access to a constructor.
  1370. Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc,
  1371. CXXConstructorDecl *Constructor,
  1372. DeclAccessPair Found,
  1373. const InitializedEntity &Entity,
  1374. bool IsCopyBindingRefToTemp) {
  1375. if (!getLangOpts().AccessControl || Found.getAccess() == AS_public)
  1376. return AR_accessible;
  1377. PartialDiagnostic PD(PDiag());
  1378. switch (Entity.getKind()) {
  1379. default:
  1380. PD = PDiag(IsCopyBindingRefToTemp
  1381. ? diag::ext_rvalue_to_reference_access_ctor
  1382. : diag::err_access_ctor);
  1383. break;
  1384. case InitializedEntity::EK_Base:
  1385. PD = PDiag(diag::err_access_base_ctor);
  1386. PD << Entity.isInheritedVirtualBase()
  1387. << Entity.getBaseSpecifier()->getType() << getSpecialMember(Constructor);
  1388. break;
  1389. case InitializedEntity::EK_Member: {
  1390. const FieldDecl *Field = cast<FieldDecl>(Entity.getDecl());
  1391. PD = PDiag(diag::err_access_field_ctor);
  1392. PD << Field->getType() << getSpecialMember(Constructor);
  1393. break;
  1394. }
  1395. case InitializedEntity::EK_LambdaCapture: {
  1396. StringRef VarName = Entity.getCapturedVarName();
  1397. PD = PDiag(diag::err_access_lambda_capture);
  1398. PD << VarName << Entity.getType() << getSpecialMember(Constructor);
  1399. break;
  1400. }
  1401. }
  1402. return CheckConstructorAccess(UseLoc, Constructor, Found, Entity, PD);
  1403. }
  1404. /// Checks access to a constructor.
  1405. Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc,
  1406. CXXConstructorDecl *Constructor,
  1407. DeclAccessPair Found,
  1408. const InitializedEntity &Entity,
  1409. const PartialDiagnostic &PD) {
  1410. if (!getLangOpts().AccessControl ||
  1411. Found.getAccess() == AS_public)
  1412. return AR_accessible;
  1413. CXXRecordDecl *NamingClass = Constructor->getParent();
  1414. // Initializing a base sub-object is an instance method call on an
  1415. // object of the derived class. Otherwise, we have an instance method
  1416. // call on an object of the constructed type.
  1417. //
  1418. // FIXME: If we have a parent, we're initializing the base class subobject
  1419. // in aggregate initialization. It's not clear whether the object class
  1420. // should be the base class or the derived class in that case.
  1421. CXXRecordDecl *ObjectClass;
  1422. if ((Entity.getKind() == InitializedEntity::EK_Base ||
  1423. Entity.getKind() == InitializedEntity::EK_Delegating) &&
  1424. !Entity.getParent()) {
  1425. ObjectClass = cast<CXXConstructorDecl>(CurContext)->getParent();
  1426. } else if (auto *Shadow =
  1427. dyn_cast<ConstructorUsingShadowDecl>(Found.getDecl())) {
  1428. // If we're using an inheriting constructor to construct an object,
  1429. // the object class is the derived class, not the base class.
  1430. ObjectClass = Shadow->getParent();
  1431. } else {
  1432. ObjectClass = NamingClass;
  1433. }
  1434. AccessTarget AccessEntity(
  1435. Context, AccessTarget::Member, NamingClass,
  1436. DeclAccessPair::make(Constructor, Found.getAccess()),
  1437. Context.getTypeDeclType(ObjectClass));
  1438. AccessEntity.setDiag(PD);
  1439. return CheckAccess(*this, UseLoc, AccessEntity);
  1440. }
  1441. /// Checks access to an overloaded operator new or delete.
  1442. Sema::AccessResult Sema::CheckAllocationAccess(SourceLocation OpLoc,
  1443. SourceRange PlacementRange,
  1444. CXXRecordDecl *NamingClass,
  1445. DeclAccessPair Found,
  1446. bool Diagnose) {
  1447. if (!getLangOpts().AccessControl ||
  1448. !NamingClass ||
  1449. Found.getAccess() == AS_public)
  1450. return AR_accessible;
  1451. AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
  1452. QualType());
  1453. if (Diagnose)
  1454. Entity.setDiag(diag::err_access)
  1455. << PlacementRange;
  1456. return CheckAccess(*this, OpLoc, Entity);
  1457. }
  1458. /// Checks access to a member.
  1459. Sema::AccessResult Sema::CheckMemberAccess(SourceLocation UseLoc,
  1460. CXXRecordDecl *NamingClass,
  1461. DeclAccessPair Found) {
  1462. if (!getLangOpts().AccessControl ||
  1463. !NamingClass ||
  1464. Found.getAccess() == AS_public)
  1465. return AR_accessible;
  1466. AccessTarget Entity(Context, AccessTarget::Member, NamingClass,
  1467. Found, QualType());
  1468. return CheckAccess(*this, UseLoc, Entity);
  1469. }
  1470. /// Checks implicit access to a member in a structured binding.
  1471. Sema::AccessResult
  1472. Sema::CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
  1473. CXXRecordDecl *DecomposedClass,
  1474. DeclAccessPair Field) {
  1475. if (!getLangOpts().AccessControl ||
  1476. Field.getAccess() == AS_public)
  1477. return AR_accessible;
  1478. AccessTarget Entity(Context, AccessTarget::Member, DecomposedClass, Field,
  1479. Context.getRecordType(DecomposedClass));
  1480. Entity.setDiag(diag::err_decomp_decl_inaccessible_field);
  1481. return CheckAccess(*this, UseLoc, Entity);
  1482. }
  1483. /// Checks access to an overloaded member operator, including
  1484. /// conversion operators.
  1485. Sema::AccessResult Sema::CheckMemberOperatorAccess(SourceLocation OpLoc,
  1486. Expr *ObjectExpr,
  1487. Expr *ArgExpr,
  1488. DeclAccessPair Found) {
  1489. if (!getLangOpts().AccessControl ||
  1490. Found.getAccess() == AS_public)
  1491. return AR_accessible;
  1492. const RecordType *RT = ObjectExpr->getType()->castAs<RecordType>();
  1493. CXXRecordDecl *NamingClass = cast<CXXRecordDecl>(RT->getDecl());
  1494. AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
  1495. ObjectExpr->getType());
  1496. Entity.setDiag(diag::err_access)
  1497. << ObjectExpr->getSourceRange()
  1498. << (ArgExpr ? ArgExpr->getSourceRange() : SourceRange());
  1499. return CheckAccess(*this, OpLoc, Entity);
  1500. }
  1501. /// Checks access to the target of a friend declaration.
  1502. Sema::AccessResult Sema::CheckFriendAccess(NamedDecl *target) {
  1503. assert(isa<CXXMethodDecl>(target->getAsFunction()));
  1504. // Friendship lookup is a redeclaration lookup, so there's never an
  1505. // inheritance path modifying access.
  1506. AccessSpecifier access = target->getAccess();
  1507. if (!getLangOpts().AccessControl || access == AS_public)
  1508. return AR_accessible;
  1509. CXXMethodDecl *method = cast<CXXMethodDecl>(target->getAsFunction());
  1510. AccessTarget entity(Context, AccessTarget::Member,
  1511. cast<CXXRecordDecl>(target->getDeclContext()),
  1512. DeclAccessPair::make(target, access),
  1513. /*no instance context*/ QualType());
  1514. entity.setDiag(diag::err_access_friend_function)
  1515. << (method->getQualifier() ? method->getQualifierLoc().getSourceRange()
  1516. : method->getNameInfo().getSourceRange());
  1517. // We need to bypass delayed-diagnostics because we might be called
  1518. // while the ParsingDeclarator is active.
  1519. EffectiveContext EC(CurContext);
  1520. switch (CheckEffectiveAccess(*this, EC, target->getLocation(), entity)) {
  1521. case ::AR_accessible: return Sema::AR_accessible;
  1522. case ::AR_inaccessible: return Sema::AR_inaccessible;
  1523. case ::AR_dependent: return Sema::AR_dependent;
  1524. }
  1525. llvm_unreachable("invalid access result");
  1526. }
  1527. Sema::AccessResult Sema::CheckAddressOfMemberAccess(Expr *OvlExpr,
  1528. DeclAccessPair Found) {
  1529. if (!getLangOpts().AccessControl ||
  1530. Found.getAccess() == AS_none ||
  1531. Found.getAccess() == AS_public)
  1532. return AR_accessible;
  1533. OverloadExpr *Ovl = OverloadExpr::find(OvlExpr).Expression;
  1534. CXXRecordDecl *NamingClass = Ovl->getNamingClass();
  1535. AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
  1536. /*no instance context*/ QualType());
  1537. Entity.setDiag(diag::err_access)
  1538. << Ovl->getSourceRange();
  1539. return CheckAccess(*this, Ovl->getNameLoc(), Entity);
  1540. }
  1541. /// Checks access for a hierarchy conversion.
  1542. ///
  1543. /// \param ForceCheck true if this check should be performed even if access
  1544. /// control is disabled; some things rely on this for semantics
  1545. /// \param ForceUnprivileged true if this check should proceed as if the
  1546. /// context had no special privileges
  1547. Sema::AccessResult Sema::CheckBaseClassAccess(SourceLocation AccessLoc,
  1548. QualType Base,
  1549. QualType Derived,
  1550. const CXXBasePath &Path,
  1551. unsigned DiagID,
  1552. bool ForceCheck,
  1553. bool ForceUnprivileged) {
  1554. if (!ForceCheck && !getLangOpts().AccessControl)
  1555. return AR_accessible;
  1556. if (Path.Access == AS_public)
  1557. return AR_accessible;
  1558. CXXRecordDecl *BaseD, *DerivedD;
  1559. BaseD = cast<CXXRecordDecl>(Base->castAs<RecordType>()->getDecl());
  1560. DerivedD = cast<CXXRecordDecl>(Derived->castAs<RecordType>()->getDecl());
  1561. AccessTarget Entity(Context, AccessTarget::Base, BaseD, DerivedD,
  1562. Path.Access);
  1563. if (DiagID)
  1564. Entity.setDiag(DiagID) << Derived << Base;
  1565. if (ForceUnprivileged) {
  1566. switch (CheckEffectiveAccess(*this, EffectiveContext(),
  1567. AccessLoc, Entity)) {
  1568. case ::AR_accessible: return Sema::AR_accessible;
  1569. case ::AR_inaccessible: return Sema::AR_inaccessible;
  1570. case ::AR_dependent: return Sema::AR_dependent;
  1571. }
  1572. llvm_unreachable("unexpected result from CheckEffectiveAccess");
  1573. }
  1574. return CheckAccess(*this, AccessLoc, Entity);
  1575. }
  1576. /// Checks access to all the declarations in the given result set.
  1577. void Sema::CheckLookupAccess(const LookupResult &R) {
  1578. assert(getLangOpts().AccessControl
  1579. && "performing access check without access control");
  1580. assert(R.getNamingClass() && "performing access check without naming class");
  1581. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  1582. if (I.getAccess() != AS_public) {
  1583. AccessTarget Entity(Context, AccessedEntity::Member,
  1584. R.getNamingClass(), I.getPair(),
  1585. R.getBaseObjectType());
  1586. Entity.setDiag(diag::err_access);
  1587. CheckAccess(*this, R.getNameLoc(), Entity);
  1588. }
  1589. }
  1590. }
  1591. /// Checks access to Target from the given class. The check will take access
  1592. /// specifiers into account, but no member access expressions and such.
  1593. ///
  1594. /// \param Target the declaration to check if it can be accessed
  1595. /// \param NamingClass the class in which the lookup was started.
  1596. /// \param BaseType type of the left side of member access expression.
  1597. /// \p BaseType and \p NamingClass are used for C++ access control.
  1598. /// Depending on the lookup case, they should be set to the following:
  1599. /// - lhs.target (member access without a qualifier):
  1600. /// \p BaseType and \p NamingClass are both the type of 'lhs'.
  1601. /// - lhs.X::target (member access with a qualifier):
  1602. /// BaseType is the type of 'lhs', NamingClass is 'X'
  1603. /// - X::target (qualified lookup without member access):
  1604. /// BaseType is null, NamingClass is 'X'.
  1605. /// - target (unqualified lookup).
  1606. /// BaseType is null, NamingClass is the parent class of 'target'.
  1607. /// \return true if the Target is accessible from the Class, false otherwise.
  1608. bool Sema::IsSimplyAccessible(NamedDecl *Target, CXXRecordDecl *NamingClass,
  1609. QualType BaseType) {
  1610. // Perform the C++ accessibility checks first.
  1611. if (Target->isCXXClassMember() && NamingClass) {
  1612. if (!getLangOpts().CPlusPlus)
  1613. return false;
  1614. // The unprivileged access is AS_none as we don't know how the member was
  1615. // accessed, which is described by the access in DeclAccessPair.
  1616. // `IsAccessible` will examine the actual access of Target (i.e.
  1617. // Decl->getAccess()) when calculating the access.
  1618. AccessTarget Entity(Context, AccessedEntity::Member, NamingClass,
  1619. DeclAccessPair::make(Target, AS_none), BaseType);
  1620. EffectiveContext EC(CurContext);
  1621. return ::IsAccessible(*this, EC, Entity) != ::AR_inaccessible;
  1622. }
  1623. if (ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(Target)) {
  1624. // @public and @package ivars are always accessible.
  1625. if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Public ||
  1626. Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Package)
  1627. return true;
  1628. // If we are inside a class or category implementation, determine the
  1629. // interface we're in.
  1630. ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
  1631. if (ObjCMethodDecl *MD = getCurMethodDecl())
  1632. ClassOfMethodDecl = MD->getClassInterface();
  1633. else if (FunctionDecl *FD = getCurFunctionDecl()) {
  1634. if (ObjCImplDecl *Impl
  1635. = dyn_cast<ObjCImplDecl>(FD->getLexicalDeclContext())) {
  1636. if (ObjCImplementationDecl *IMPD
  1637. = dyn_cast<ObjCImplementationDecl>(Impl))
  1638. ClassOfMethodDecl = IMPD->getClassInterface();
  1639. else if (ObjCCategoryImplDecl* CatImplClass
  1640. = dyn_cast<ObjCCategoryImplDecl>(Impl))
  1641. ClassOfMethodDecl = CatImplClass->getClassInterface();
  1642. }
  1643. }
  1644. // If we're not in an interface, this ivar is inaccessible.
  1645. if (!ClassOfMethodDecl)
  1646. return false;
  1647. // If we're inside the same interface that owns the ivar, we're fine.
  1648. if (declaresSameEntity(ClassOfMethodDecl, Ivar->getContainingInterface()))
  1649. return true;
  1650. // If the ivar is private, it's inaccessible.
  1651. if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Private)
  1652. return false;
  1653. return Ivar->getContainingInterface()->isSuperClassOf(ClassOfMethodDecl);
  1654. }
  1655. return true;
  1656. }