SemaAccess.cpp 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946
  1. //===---- SemaAccess.cpp - C++ Access Control -------------------*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file provides Sema routines for C++ access control semantics.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Basic/Specifiers.h"
  13. #include "clang/Sema/SemaInternal.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/CXXInheritance.h"
  16. #include "clang/AST/DeclCXX.h"
  17. #include "clang/AST/DeclFriend.h"
  18. #include "clang/AST/DeclObjC.h"
  19. #include "clang/AST/DependentDiagnostic.h"
  20. #include "clang/AST/ExprCXX.h"
  21. #include "clang/Sema/DelayedDiagnostic.h"
  22. #include "clang/Sema/Initialization.h"
  23. #include "clang/Sema/Lookup.h"
  24. using namespace clang;
  25. using namespace sema;
  26. /// A copy of Sema's enum without AR_delayed.
  27. enum AccessResult {
  28. AR_accessible,
  29. AR_inaccessible,
  30. AR_dependent
  31. };
  32. /// SetMemberAccessSpecifier - Set the access specifier of a member.
  33. /// Returns true on error (when the previous member decl access specifier
  34. /// is different from the new member decl access specifier).
  35. bool Sema::SetMemberAccessSpecifier(NamedDecl *MemberDecl,
  36. NamedDecl *PrevMemberDecl,
  37. AccessSpecifier LexicalAS) {
  38. if (!PrevMemberDecl) {
  39. // Use the lexical access specifier.
  40. MemberDecl->setAccess(LexicalAS);
  41. return false;
  42. }
  43. // C++ [class.access.spec]p3: When a member is redeclared its access
  44. // specifier must be same as its initial declaration.
  45. if (LexicalAS != AS_none && LexicalAS != PrevMemberDecl->getAccess()) {
  46. Diag(MemberDecl->getLocation(),
  47. diag::err_class_redeclared_with_different_access)
  48. << MemberDecl << LexicalAS;
  49. Diag(PrevMemberDecl->getLocation(), diag::note_previous_access_declaration)
  50. << PrevMemberDecl << PrevMemberDecl->getAccess();
  51. MemberDecl->setAccess(LexicalAS);
  52. return true;
  53. }
  54. MemberDecl->setAccess(PrevMemberDecl->getAccess());
  55. return false;
  56. }
  57. static CXXRecordDecl *FindDeclaringClass(NamedDecl *D) {
  58. DeclContext *DC = D->getDeclContext();
  59. // This can only happen at top: enum decls only "publish" their
  60. // immediate members.
  61. if (isa<EnumDecl>(DC))
  62. DC = cast<EnumDecl>(DC)->getDeclContext();
  63. CXXRecordDecl *DeclaringClass = cast<CXXRecordDecl>(DC);
  64. while (DeclaringClass->isAnonymousStructOrUnion())
  65. DeclaringClass = cast<CXXRecordDecl>(DeclaringClass->getDeclContext());
  66. return DeclaringClass;
  67. }
  68. namespace {
  69. struct EffectiveContext {
  70. EffectiveContext() : Inner(nullptr), Dependent(false) {}
  71. explicit EffectiveContext(DeclContext *DC)
  72. : Inner(DC),
  73. Dependent(DC->isDependentContext()) {
  74. // 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 llvm::find(Records, R) != Records.end();
  114. }
  115. /// Retrieves the innermost "useful" context. Can be null if we're
  116. /// doing access-control without privileges.
  117. DeclContext *getInnerContext() const {
  118. return Inner;
  119. }
  120. typedef SmallVectorImpl<CXXRecordDecl*>::const_iterator record_iterator;
  121. DeclContext *Inner;
  122. SmallVector<FunctionDecl*, 4> Functions;
  123. SmallVector<CXXRecordDecl*, 4> Records;
  124. bool Dependent;
  125. };
  126. /// Like sema::AccessedEntity, but kindly lets us scribble all over
  127. /// it.
  128. struct AccessTarget : public AccessedEntity {
  129. AccessTarget(const AccessedEntity &Entity)
  130. : AccessedEntity(Entity) {
  131. initialize();
  132. }
  133. AccessTarget(ASTContext &Context,
  134. MemberNonce _,
  135. CXXRecordDecl *NamingClass,
  136. DeclAccessPair FoundDecl,
  137. QualType BaseObjectType)
  138. : AccessedEntity(Context.getDiagAllocator(), Member, NamingClass,
  139. FoundDecl, BaseObjectType) {
  140. initialize();
  141. }
  142. AccessTarget(ASTContext &Context,
  143. BaseNonce _,
  144. CXXRecordDecl *BaseClass,
  145. CXXRecordDecl *DerivedClass,
  146. AccessSpecifier Access)
  147. : AccessedEntity(Context.getDiagAllocator(), Base, BaseClass, DerivedClass,
  148. Access) {
  149. initialize();
  150. }
  151. bool isInstanceMember() const {
  152. return (isMemberAccess() && getTargetDecl()->isCXXInstanceMember());
  153. }
  154. bool hasInstanceContext() const {
  155. return HasInstanceContext;
  156. }
  157. class SavedInstanceContext {
  158. public:
  159. SavedInstanceContext(SavedInstanceContext &&S)
  160. : Target(S.Target), Has(S.Has) {
  161. S.Target = nullptr;
  162. }
  163. ~SavedInstanceContext() {
  164. if (Target)
  165. Target->HasInstanceContext = Has;
  166. }
  167. private:
  168. friend struct AccessTarget;
  169. explicit SavedInstanceContext(AccessTarget &Target)
  170. : Target(&Target), Has(Target.HasInstanceContext) {}
  171. AccessTarget *Target;
  172. bool Has;
  173. };
  174. SavedInstanceContext saveInstanceContext() {
  175. return SavedInstanceContext(*this);
  176. }
  177. void suppressInstanceContext() {
  178. HasInstanceContext = false;
  179. }
  180. const CXXRecordDecl *resolveInstanceContext(Sema &S) const {
  181. assert(HasInstanceContext);
  182. if (CalculatedInstanceContext)
  183. return InstanceContext;
  184. CalculatedInstanceContext = true;
  185. DeclContext *IC = S.computeDeclContext(getBaseObjectType());
  186. InstanceContext = (IC ? cast<CXXRecordDecl>(IC)->getCanonicalDecl()
  187. : nullptr);
  188. return InstanceContext;
  189. }
  190. const CXXRecordDecl *getDeclaringClass() const {
  191. return DeclaringClass;
  192. }
  193. /// The "effective" naming class is the canonical non-anonymous
  194. /// class containing the actual naming class.
  195. const CXXRecordDecl *getEffectiveNamingClass() const {
  196. const CXXRecordDecl *namingClass = getNamingClass();
  197. while (namingClass->isAnonymousStructOrUnion())
  198. namingClass = cast<CXXRecordDecl>(namingClass->getParent());
  199. return namingClass->getCanonicalDecl();
  200. }
  201. private:
  202. void initialize() {
  203. HasInstanceContext = (isMemberAccess() &&
  204. !getBaseObjectType().isNull() &&
  205. getTargetDecl()->isCXXInstanceMember());
  206. CalculatedInstanceContext = false;
  207. InstanceContext = nullptr;
  208. if (isMemberAccess())
  209. DeclaringClass = FindDeclaringClass(getTargetDecl());
  210. else
  211. DeclaringClass = getBaseClass();
  212. DeclaringClass = DeclaringClass->getCanonicalDecl();
  213. }
  214. bool HasInstanceContext : 1;
  215. mutable bool CalculatedInstanceContext : 1;
  216. mutable const CXXRecordDecl *InstanceContext;
  217. const CXXRecordDecl *DeclaringClass;
  218. };
  219. }
  220. /// Checks whether one class might instantiate to the other.
  221. static bool MightInstantiateTo(const CXXRecordDecl *From,
  222. const CXXRecordDecl *To) {
  223. // Declaration names are always preserved by instantiation.
  224. if (From->getDeclName() != To->getDeclName())
  225. return false;
  226. const DeclContext *FromDC = From->getDeclContext()->getPrimaryContext();
  227. const DeclContext *ToDC = To->getDeclContext()->getPrimaryContext();
  228. if (FromDC == ToDC) return true;
  229. if (FromDC->isFileContext() || ToDC->isFileContext()) return false;
  230. // Be conservative.
  231. return true;
  232. }
  233. /// Checks whether one class is derived from another, inclusively.
  234. /// Properly indicates when it couldn't be determined due to
  235. /// dependence.
  236. ///
  237. /// This should probably be donated to AST or at least Sema.
  238. static AccessResult IsDerivedFromInclusive(const CXXRecordDecl *Derived,
  239. const CXXRecordDecl *Target) {
  240. assert(Derived->getCanonicalDecl() == Derived);
  241. assert(Target->getCanonicalDecl() == Target);
  242. if (Derived == Target) return AR_accessible;
  243. bool CheckDependent = Derived->isDependentContext();
  244. if (CheckDependent && MightInstantiateTo(Derived, Target))
  245. return AR_dependent;
  246. AccessResult OnFailure = AR_inaccessible;
  247. SmallVector<const CXXRecordDecl*, 8> Queue; // actually a stack
  248. while (true) {
  249. if (Derived->isDependentContext() && !Derived->hasDefinition() &&
  250. !Derived->isLambda())
  251. return AR_dependent;
  252. for (const auto &I : Derived->bases()) {
  253. const CXXRecordDecl *RD;
  254. QualType T = I.getType();
  255. if (const RecordType *RT = T->getAs<RecordType>()) {
  256. RD = cast<CXXRecordDecl>(RT->getDecl());
  257. } else if (const InjectedClassNameType *IT
  258. = T->getAs<InjectedClassNameType>()) {
  259. RD = IT->getDecl();
  260. } else {
  261. assert(T->isDependentType() && "non-dependent base wasn't a record?");
  262. OnFailure = AR_dependent;
  263. continue;
  264. }
  265. RD = RD->getCanonicalDecl();
  266. if (RD == Target) return AR_accessible;
  267. if (CheckDependent && MightInstantiateTo(RD, Target))
  268. OnFailure = AR_dependent;
  269. Queue.push_back(RD);
  270. }
  271. if (Queue.empty()) break;
  272. Derived = Queue.pop_back_val();
  273. }
  274. return OnFailure;
  275. }
  276. static bool MightInstantiateTo(Sema &S, DeclContext *Context,
  277. DeclContext *Friend) {
  278. if (Friend == Context)
  279. return true;
  280. assert(!Friend->isDependentContext() &&
  281. "can't handle friends with dependent contexts here");
  282. if (!Context->isDependentContext())
  283. return false;
  284. if (Friend->isFileContext())
  285. return false;
  286. // TODO: this is very conservative
  287. return true;
  288. }
  289. // Asks whether the type in 'context' can ever instantiate to the type
  290. // in 'friend'.
  291. static bool MightInstantiateTo(Sema &S, CanQualType Context, CanQualType Friend) {
  292. if (Friend == Context)
  293. return true;
  294. if (!Friend->isDependentType() && !Context->isDependentType())
  295. return false;
  296. // TODO: this is very conservative.
  297. return true;
  298. }
  299. static bool MightInstantiateTo(Sema &S,
  300. FunctionDecl *Context,
  301. FunctionDecl *Friend) {
  302. if (Context->getDeclName() != Friend->getDeclName())
  303. return false;
  304. if (!MightInstantiateTo(S,
  305. Context->getDeclContext(),
  306. Friend->getDeclContext()))
  307. return false;
  308. CanQual<FunctionProtoType> FriendTy
  309. = S.Context.getCanonicalType(Friend->getType())
  310. ->getAs<FunctionProtoType>();
  311. CanQual<FunctionProtoType> ContextTy
  312. = S.Context.getCanonicalType(Context->getType())
  313. ->getAs<FunctionProtoType>();
  314. // There isn't any way that I know of to add qualifiers
  315. // during instantiation.
  316. if (FriendTy.getQualifiers() != ContextTy.getQualifiers())
  317. return false;
  318. if (FriendTy->getNumParams() != ContextTy->getNumParams())
  319. return false;
  320. if (!MightInstantiateTo(S, ContextTy->getReturnType(),
  321. FriendTy->getReturnType()))
  322. return false;
  323. for (unsigned I = 0, E = FriendTy->getNumParams(); I != E; ++I)
  324. if (!MightInstantiateTo(S, ContextTy->getParamType(I),
  325. FriendTy->getParamType(I)))
  326. return false;
  327. return true;
  328. }
  329. static bool MightInstantiateTo(Sema &S,
  330. FunctionTemplateDecl *Context,
  331. FunctionTemplateDecl *Friend) {
  332. return MightInstantiateTo(S,
  333. Context->getTemplatedDecl(),
  334. Friend->getTemplatedDecl());
  335. }
  336. static AccessResult MatchesFriend(Sema &S,
  337. const EffectiveContext &EC,
  338. const CXXRecordDecl *Friend) {
  339. if (EC.includesClass(Friend))
  340. return AR_accessible;
  341. if (EC.isDependent()) {
  342. for (const CXXRecordDecl *Context : EC.Records) {
  343. if (MightInstantiateTo(Context, Friend))
  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->castAs<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. DeclAccessPair Found,
  1355. const InitializedEntity &Entity,
  1356. bool IsCopyBindingRefToTemp) {
  1357. if (!getLangOpts().AccessControl || Found.getAccess() == 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, Found, Entity, PD);
  1385. }
  1386. /// Checks access to a constructor.
  1387. Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc,
  1388. CXXConstructorDecl *Constructor,
  1389. DeclAccessPair Found,
  1390. const InitializedEntity &Entity,
  1391. const PartialDiagnostic &PD) {
  1392. if (!getLangOpts().AccessControl ||
  1393. Found.getAccess() == 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. //
  1400. // FIXME: If we have a parent, we're initializing the base class subobject
  1401. // in aggregate initialization. It's not clear whether the object class
  1402. // should be the base class or the derived class in that case.
  1403. CXXRecordDecl *ObjectClass;
  1404. if ((Entity.getKind() == InitializedEntity::EK_Base ||
  1405. Entity.getKind() == InitializedEntity::EK_Delegating) &&
  1406. !Entity.getParent()) {
  1407. ObjectClass = cast<CXXConstructorDecl>(CurContext)->getParent();
  1408. } else if (auto *Shadow =
  1409. dyn_cast<ConstructorUsingShadowDecl>(Found.getDecl())) {
  1410. // If we're using an inheriting constructor to construct an object,
  1411. // the object class is the derived class, not the base class.
  1412. ObjectClass = Shadow->getParent();
  1413. } else {
  1414. ObjectClass = NamingClass;
  1415. }
  1416. AccessTarget AccessEntity(
  1417. Context, AccessTarget::Member, NamingClass,
  1418. DeclAccessPair::make(Constructor, Found.getAccess()),
  1419. Context.getTypeDeclType(ObjectClass));
  1420. AccessEntity.setDiag(PD);
  1421. return CheckAccess(*this, UseLoc, AccessEntity);
  1422. }
  1423. /// Checks access to an overloaded operator new or delete.
  1424. Sema::AccessResult Sema::CheckAllocationAccess(SourceLocation OpLoc,
  1425. SourceRange PlacementRange,
  1426. CXXRecordDecl *NamingClass,
  1427. DeclAccessPair Found,
  1428. bool Diagnose) {
  1429. if (!getLangOpts().AccessControl ||
  1430. !NamingClass ||
  1431. Found.getAccess() == AS_public)
  1432. return AR_accessible;
  1433. AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
  1434. QualType());
  1435. if (Diagnose)
  1436. Entity.setDiag(diag::err_access)
  1437. << PlacementRange;
  1438. return CheckAccess(*this, OpLoc, Entity);
  1439. }
  1440. /// Checks access to a member.
  1441. Sema::AccessResult Sema::CheckMemberAccess(SourceLocation UseLoc,
  1442. CXXRecordDecl *NamingClass,
  1443. DeclAccessPair Found) {
  1444. if (!getLangOpts().AccessControl ||
  1445. !NamingClass ||
  1446. Found.getAccess() == AS_public)
  1447. return AR_accessible;
  1448. AccessTarget Entity(Context, AccessTarget::Member, NamingClass,
  1449. Found, QualType());
  1450. return CheckAccess(*this, UseLoc, Entity);
  1451. }
  1452. /// Checks implicit access to a member in a structured binding.
  1453. Sema::AccessResult
  1454. Sema::CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
  1455. CXXRecordDecl *DecomposedClass,
  1456. DeclAccessPair Field) {
  1457. if (!getLangOpts().AccessControl ||
  1458. Field.getAccess() == AS_public)
  1459. return AR_accessible;
  1460. AccessTarget Entity(Context, AccessTarget::Member, DecomposedClass, Field,
  1461. Context.getRecordType(DecomposedClass));
  1462. Entity.setDiag(diag::err_decomp_decl_inaccessible_field);
  1463. return CheckAccess(*this, UseLoc, Entity);
  1464. }
  1465. /// Checks access to an overloaded member operator, including
  1466. /// conversion operators.
  1467. Sema::AccessResult Sema::CheckMemberOperatorAccess(SourceLocation OpLoc,
  1468. Expr *ObjectExpr,
  1469. Expr *ArgExpr,
  1470. DeclAccessPair Found) {
  1471. if (!getLangOpts().AccessControl ||
  1472. Found.getAccess() == AS_public)
  1473. return AR_accessible;
  1474. const RecordType *RT = ObjectExpr->getType()->castAs<RecordType>();
  1475. CXXRecordDecl *NamingClass = cast<CXXRecordDecl>(RT->getDecl());
  1476. AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
  1477. ObjectExpr->getType());
  1478. Entity.setDiag(diag::err_access)
  1479. << ObjectExpr->getSourceRange()
  1480. << (ArgExpr ? ArgExpr->getSourceRange() : SourceRange());
  1481. return CheckAccess(*this, OpLoc, Entity);
  1482. }
  1483. /// Checks access to the target of a friend declaration.
  1484. Sema::AccessResult Sema::CheckFriendAccess(NamedDecl *target) {
  1485. assert(isa<CXXMethodDecl>(target->getAsFunction()));
  1486. // Friendship lookup is a redeclaration lookup, so there's never an
  1487. // inheritance path modifying access.
  1488. AccessSpecifier access = target->getAccess();
  1489. if (!getLangOpts().AccessControl || access == AS_public)
  1490. return AR_accessible;
  1491. CXXMethodDecl *method = cast<CXXMethodDecl>(target->getAsFunction());
  1492. AccessTarget entity(Context, AccessTarget::Member,
  1493. cast<CXXRecordDecl>(target->getDeclContext()),
  1494. DeclAccessPair::make(target, access),
  1495. /*no instance context*/ QualType());
  1496. entity.setDiag(diag::err_access_friend_function)
  1497. << (method->getQualifier() ? method->getQualifierLoc().getSourceRange()
  1498. : method->getNameInfo().getSourceRange());
  1499. // We need to bypass delayed-diagnostics because we might be called
  1500. // while the ParsingDeclarator is active.
  1501. EffectiveContext EC(CurContext);
  1502. switch (CheckEffectiveAccess(*this, EC, target->getLocation(), entity)) {
  1503. case ::AR_accessible: return Sema::AR_accessible;
  1504. case ::AR_inaccessible: return Sema::AR_inaccessible;
  1505. case ::AR_dependent: return Sema::AR_dependent;
  1506. }
  1507. llvm_unreachable("invalid access result");
  1508. }
  1509. Sema::AccessResult Sema::CheckAddressOfMemberAccess(Expr *OvlExpr,
  1510. DeclAccessPair Found) {
  1511. if (!getLangOpts().AccessControl ||
  1512. Found.getAccess() == AS_none ||
  1513. Found.getAccess() == AS_public)
  1514. return AR_accessible;
  1515. OverloadExpr *Ovl = OverloadExpr::find(OvlExpr).Expression;
  1516. CXXRecordDecl *NamingClass = Ovl->getNamingClass();
  1517. AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
  1518. /*no instance context*/ QualType());
  1519. Entity.setDiag(diag::err_access)
  1520. << Ovl->getSourceRange();
  1521. return CheckAccess(*this, Ovl->getNameLoc(), Entity);
  1522. }
  1523. /// Checks access for a hierarchy conversion.
  1524. ///
  1525. /// \param ForceCheck true if this check should be performed even if access
  1526. /// control is disabled; some things rely on this for semantics
  1527. /// \param ForceUnprivileged true if this check should proceed as if the
  1528. /// context had no special privileges
  1529. Sema::AccessResult Sema::CheckBaseClassAccess(SourceLocation AccessLoc,
  1530. QualType Base,
  1531. QualType Derived,
  1532. const CXXBasePath &Path,
  1533. unsigned DiagID,
  1534. bool ForceCheck,
  1535. bool ForceUnprivileged) {
  1536. if (!ForceCheck && !getLangOpts().AccessControl)
  1537. return AR_accessible;
  1538. if (Path.Access == AS_public)
  1539. return AR_accessible;
  1540. CXXRecordDecl *BaseD, *DerivedD;
  1541. BaseD = cast<CXXRecordDecl>(Base->castAs<RecordType>()->getDecl());
  1542. DerivedD = cast<CXXRecordDecl>(Derived->castAs<RecordType>()->getDecl());
  1543. AccessTarget Entity(Context, AccessTarget::Base, BaseD, DerivedD,
  1544. Path.Access);
  1545. if (DiagID)
  1546. Entity.setDiag(DiagID) << Derived << Base;
  1547. if (ForceUnprivileged) {
  1548. switch (CheckEffectiveAccess(*this, EffectiveContext(),
  1549. AccessLoc, Entity)) {
  1550. case ::AR_accessible: return Sema::AR_accessible;
  1551. case ::AR_inaccessible: return Sema::AR_inaccessible;
  1552. case ::AR_dependent: return Sema::AR_dependent;
  1553. }
  1554. llvm_unreachable("unexpected result from CheckEffectiveAccess");
  1555. }
  1556. return CheckAccess(*this, AccessLoc, Entity);
  1557. }
  1558. /// Checks access to all the declarations in the given result set.
  1559. void Sema::CheckLookupAccess(const LookupResult &R) {
  1560. assert(getLangOpts().AccessControl
  1561. && "performing access check without access control");
  1562. assert(R.getNamingClass() && "performing access check without naming class");
  1563. for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
  1564. if (I.getAccess() != AS_public) {
  1565. AccessTarget Entity(Context, AccessedEntity::Member,
  1566. R.getNamingClass(), I.getPair(),
  1567. R.getBaseObjectType());
  1568. Entity.setDiag(diag::err_access);
  1569. CheckAccess(*this, R.getNameLoc(), Entity);
  1570. }
  1571. }
  1572. }
  1573. /// Checks access to Target from the given class. The check will take access
  1574. /// specifiers into account, but no member access expressions and such.
  1575. ///
  1576. /// \param Target the declaration to check if it can be accessed
  1577. /// \param NamingClass the class in which the lookup was started.
  1578. /// \param BaseType type of the left side of member access expression.
  1579. /// \p BaseType and \p NamingClass are used for C++ access control.
  1580. /// Depending on the lookup case, they should be set to the following:
  1581. /// - lhs.target (member access without a qualifier):
  1582. /// \p BaseType and \p NamingClass are both the type of 'lhs'.
  1583. /// - lhs.X::target (member access with a qualifier):
  1584. /// BaseType is the type of 'lhs', NamingClass is 'X'
  1585. /// - X::target (qualified lookup without member access):
  1586. /// BaseType is null, NamingClass is 'X'.
  1587. /// - target (unqualified lookup).
  1588. /// BaseType is null, NamingClass is the parent class of 'target'.
  1589. /// \return true if the Target is accessible from the Class, false otherwise.
  1590. bool Sema::IsSimplyAccessible(NamedDecl *Target, CXXRecordDecl *NamingClass,
  1591. QualType BaseType) {
  1592. // Perform the C++ accessibility checks first.
  1593. if (Target->isCXXClassMember() && NamingClass) {
  1594. if (!getLangOpts().CPlusPlus)
  1595. return false;
  1596. // The unprivileged access is AS_none as we don't know how the member was
  1597. // accessed, which is described by the access in DeclAccessPair.
  1598. // `IsAccessible` will examine the actual access of Target (i.e.
  1599. // Decl->getAccess()) when calculating the access.
  1600. AccessTarget Entity(Context, AccessedEntity::Member, NamingClass,
  1601. DeclAccessPair::make(Target, AS_none), BaseType);
  1602. EffectiveContext EC(CurContext);
  1603. return ::IsAccessible(*this, EC, Entity) != ::AR_inaccessible;
  1604. }
  1605. if (ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(Target)) {
  1606. // @public and @package ivars are always accessible.
  1607. if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Public ||
  1608. Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Package)
  1609. return true;
  1610. // If we are inside a class or category implementation, determine the
  1611. // interface we're in.
  1612. ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
  1613. if (ObjCMethodDecl *MD = getCurMethodDecl())
  1614. ClassOfMethodDecl = MD->getClassInterface();
  1615. else if (FunctionDecl *FD = getCurFunctionDecl()) {
  1616. if (ObjCImplDecl *Impl
  1617. = dyn_cast<ObjCImplDecl>(FD->getLexicalDeclContext())) {
  1618. if (ObjCImplementationDecl *IMPD
  1619. = dyn_cast<ObjCImplementationDecl>(Impl))
  1620. ClassOfMethodDecl = IMPD->getClassInterface();
  1621. else if (ObjCCategoryImplDecl* CatImplClass
  1622. = dyn_cast<ObjCCategoryImplDecl>(Impl))
  1623. ClassOfMethodDecl = CatImplClass->getClassInterface();
  1624. }
  1625. }
  1626. // If we're not in an interface, this ivar is inaccessible.
  1627. if (!ClassOfMethodDecl)
  1628. return false;
  1629. // If we're inside the same interface that owns the ivar, we're fine.
  1630. if (declaresSameEntity(ClassOfMethodDecl, Ivar->getContainingInterface()))
  1631. return true;
  1632. // If the ivar is private, it's inaccessible.
  1633. if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Private)
  1634. return false;
  1635. return Ivar->getContainingInterface()->isSuperClassOf(ClassOfMethodDecl);
  1636. }
  1637. return true;
  1638. }