SemaAccess.cpp 61 KB

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