SemaAccess.cpp 68 KB

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