SemaAccess.cpp 70 KB

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