clang 24.0.0git
CGPointerAuth.cpp
Go to the documentation of this file.
1//===--- CGPointerAuth.cpp - IR generation for pointer authentication -----===//
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 contains common routines relating to the emission of
10// pointer authentication operations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGCXXABI.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
17#include "clang/AST/Attr.h"
20#include "llvm/Analysis/ValueTracking.h"
21#include "llvm/Support/SipHash.h"
22
23using namespace clang;
24using namespace CodeGen;
25
26/// Given a pointer-authentication schema, return a concrete "other"
27/// discriminator for it.
30 switch (Schema.getOtherDiscrimination()) {
32 return nullptr;
33
35 assert(!Type.isNull() && "type not provided for type-discriminated schema");
36 return llvm::ConstantInt::get(
38
40 assert(Decl.getDecl() &&
41 "declaration not provided for decl-discriminated schema");
42 return llvm::ConstantInt::get(IntPtrTy,
44
46 return llvm::ConstantInt::get(IntPtrTy, Schema.getConstantDiscrimination());
47 }
48 llvm_unreachable("bad discrimination kind");
49}
50
55
60
61/// Return the "other" decl-specific discriminator for the given decl.
62uint16_t
64 uint16_t &EntityHash = PtrAuthDiscriminatorHashes[Declaration];
65
66 if (EntityHash == 0) {
67 const auto *ND = cast<NamedDecl>(Declaration.getDecl());
68 if (ND->hasAttr<AsmLabelAttr>() &&
69 ND->getAttr<AsmLabelAttr>()->getLabel().starts_with(
71 // If the declaration comes from LLDB, the asm label has a prefix that
72 // would producing a different discriminator. Compute the real C++ mangled
73 // name instead so the discriminator matches what the original translation
74 // unit used.
75 SmallString<256> Buffer;
76 llvm::raw_svector_ostream Out(Buffer);
78 EntityHash = llvm::getPointerAuthStableSipHash(Out.str());
79 } else {
80 StringRef Name = getMangledName(Declaration);
81 EntityHash = llvm::getPointerAuthStableSipHash(Name);
82 }
83 }
84
85 return EntityHash;
86}
87
88/// Return the abstract pointer authentication schema for a pointer to the given
89/// function type.
91 const auto &Schema = getCodeGenOpts().PointerAuth.FunctionPointers;
92 if (!Schema)
93 return CGPointerAuthInfo();
94
95 assert(!Schema.isAddressDiscriminated() &&
96 "function pointers cannot use address-specific discrimination");
97
98 llvm::Constant *Discriminator = nullptr;
99 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
100 T = T->getPointeeType();
101 if (T->isFunctionType())
102 Discriminator = getPointerAuthOtherDiscriminator(Schema, GlobalDecl(), T);
103
104 return CGPointerAuthInfo(Schema.getKey(), Schema.getAuthenticationMode(),
105 /*IsaPointer=*/false, /*AuthenticatesNull=*/false,
106 Discriminator);
107}
108
109llvm::Value *
111 llvm::Value *Discriminator) {
112 StorageAddress = Builder.CreatePtrToInt(StorageAddress, IntPtrTy);
113 auto Intrinsic = CGM.getIntrinsic(llvm::Intrinsic::ptrauth_blend);
114 return Builder.CreateCall(Intrinsic, {StorageAddress, Discriminator});
115}
116
117/// Emit the concrete pointer authentication informaton for the
118/// given authentication schema.
120 const PointerAuthSchema &Schema, llvm::Value *StorageAddress,
121 GlobalDecl SchemaDecl, QualType SchemaType) {
122 if (!Schema)
123 return CGPointerAuthInfo();
124
125 llvm::Value *Discriminator =
126 CGM.getPointerAuthOtherDiscriminator(Schema, SchemaDecl, SchemaType);
127
128 if (Schema.isAddressDiscriminated()) {
129 assert(StorageAddress &&
130 "address not provided for address-discriminated schema");
131
132 if (Discriminator)
133 Discriminator =
134 EmitPointerAuthBlendDiscriminator(StorageAddress, Discriminator);
135 else
136 Discriminator = Builder.CreatePtrToInt(StorageAddress, IntPtrTy);
137 }
138
139 return CGPointerAuthInfo(Schema.getKey(), Schema.getAuthenticationMode(),
140 Schema.isIsaPointer(),
141 Schema.authenticatesNullValues(), Discriminator);
142}
143
146 Address StorageAddress) {
147 assert(Qual && "don't call this if you don't know that the Qual is present");
148 if (Qual.hasKeyNone())
149 return CGPointerAuthInfo();
150
151 llvm::Value *Discriminator = nullptr;
152 if (unsigned Extra = Qual.getExtraDiscriminator())
153 Discriminator = llvm::ConstantInt::get(IntPtrTy, Extra);
154
155 if (Qual.isAddressDiscriminated()) {
156 assert(StorageAddress.isValid() &&
157 "address discrimination without address");
158 llvm::Value *StoragePtr = StorageAddress.emitRawPointer(*this);
159 if (Discriminator)
160 Discriminator =
161 EmitPointerAuthBlendDiscriminator(StoragePtr, Discriminator);
162 else
163 Discriminator = Builder.CreatePtrToInt(StoragePtr, IntPtrTy);
164 }
165
166 return CGPointerAuthInfo(Qual.getKey(), Qual.getAuthenticationMode(),
168 Discriminator);
169}
170
171/// Return the natural pointer authentication for values of the given
172/// pointee type.
175 if (PointeeType.isNull())
176 return CGPointerAuthInfo();
177
178 // Function pointers use the function-pointer schema by default.
179 if (PointeeType->isFunctionType())
180 return CGM.getFunctionPointerAuthInfo(PointeeType);
181
182 // Normal data pointers never use direct pointer authentication by default.
183 return CGPointerAuthInfo();
184}
185
187 return ::getPointerAuthInfoForPointeeType(*this, T);
188}
189
190/// Return the natural pointer authentication for values of the given
191/// pointer type.
194 PointerType = PointerType.getAtomicUnqualifiedType();
195 assert(PointerType->isSignableType(CGM.getContext()));
196
197 // Block pointers are currently not signed.
199 return CGPointerAuthInfo();
200
201 auto PointeeType = PointerType->getPointeeType();
202
203 if (PointeeType.isNull())
204 return CGPointerAuthInfo();
205
206 return ::getPointerAuthInfoForPointeeType(CGM, PointeeType);
207}
208
210 return ::getPointerAuthInfoForType(*this, T);
211}
212
213static std::pair<llvm::Value *, CGPointerAuthInfo>
215 SourceLocation Loc) {
216 llvm::Value *Value = CGF.EmitLoadOfScalar(LV, Loc);
217 CGPointerAuthInfo AuthInfo;
218 if (PointerAuthQualifier PtrAuth = LV.getQuals().getPointerAuth())
219 AuthInfo = CGF.EmitPointerAuthInfo(PtrAuth, LV.getAddress());
220 else
221 AuthInfo = getPointerAuthInfoForType(CGF.CGM, LV.getType());
222 return {Value, AuthInfo};
223}
224
225/// Retrieve a pointer rvalue and its ptrauth info. When possible, avoid
226/// needlessly resigning the pointer.
227std::pair<llvm::Value *, CGPointerAuthInfo>
230
231 E = E->IgnoreParens();
232 if (const auto *Load = dyn_cast<ImplicitCastExpr>(E)) {
233 if (Load->getCastKind() == CK_LValueToRValue) {
234 E = Load->getSubExpr()->IgnoreParens();
235
236 // We're semantically required to not emit loads of certain DREs naively.
237 if (const auto *RefExpr = dyn_cast<DeclRefExpr>(E)) {
239 // Fold away a use of an intermediate variable.
240 if (!Result.isReference())
241 return {Result.getValue(),
242 getPointerAuthInfoForType(CGM, RefExpr->getType())};
243
244 // Fold away a use of an intermediate reference.
245 LValue LV = Result.getReferenceLValue(*this, RefExpr);
246 return emitLoadOfOrigPointerRValue(*this, LV, RefExpr->getLocation());
247 }
248 }
249
250 // Otherwise, load and use the pointer
252 return emitLoadOfOrigPointerRValue(*this, LV, E->getExprLoc());
253 }
254 }
255
256 // Fallback: just use the normal rules for the type.
257 llvm::Value *Value = EmitScalarExpr(E);
259}
260
261llvm::Value *
263 const Expr *E,
264 Address DestStorageAddress) {
265 assert(DestQualifier);
266 auto [Value, CurAuthInfo] = EmitOrigPointerRValue(E);
267
268 CGPointerAuthInfo DestAuthInfo =
269 EmitPointerAuthInfo(DestQualifier, DestStorageAddress);
270 return emitPointerAuthResign(Value, E->getType(), CurAuthInfo, DestAuthInfo,
272}
273
275 PointerAuthQualifier DestQualifier, llvm::Value *Value,
276 QualType PointerType, Address DestStorageAddress, bool IsKnownNonNull) {
277 assert(DestQualifier);
278
280 CGPointerAuthInfo DestAuthInfo =
281 EmitPointerAuthInfo(DestQualifier, DestStorageAddress);
282 return emitPointerAuthResign(Value, PointerType, CurAuthInfo, DestAuthInfo,
283 IsKnownNonNull);
284}
285
287 PointerAuthQualifier CurQualifier, llvm::Value *Value, QualType PointerType,
288 Address CurStorageAddress, bool IsKnownNonNull) {
289 assert(CurQualifier);
290
291 CGPointerAuthInfo CurAuthInfo =
292 EmitPointerAuthInfo(CurQualifier, CurStorageAddress);
294 return emitPointerAuthResign(Value, PointerType, CurAuthInfo, DestAuthInfo,
295 IsKnownNonNull);
296}
297
298static bool isZeroConstant(const llvm::Value *Value) {
299 if (const auto *CI = dyn_cast<llvm::ConstantInt>(Value))
300 return CI->isZero();
301 return false;
302}
303
304static bool equalAuthPolicies(const CGPointerAuthInfo &Left,
305 const CGPointerAuthInfo &Right) {
306 assert((Left.isSigned() || Right.isSigned()) &&
307 "shouldn't be called if neither is signed");
308 if (Left.isSigned() != Right.isSigned())
309 return false;
310 return Left.getKey() == Right.getKey() &&
311 Left.getAuthenticationMode() == Right.getAuthenticationMode() &&
312 Left.isIsaPointer() == Right.isIsaPointer() &&
313 Left.authenticatesNullValues() == Right.authenticatesNullValues() &&
314 Left.getDiscriminator() == Right.getDiscriminator();
315}
316
317// Return the discriminator or return zero if the discriminator is null.
318static llvm::Value *getDiscriminatorOrZero(const CGPointerAuthInfo &Info,
319 CGBuilderTy &Builder) {
320 llvm::Value *Discriminator = Info.getDiscriminator();
321 return Discriminator ? Discriminator : Builder.getSize(0);
322}
323
324llvm::Value *
326 const CGPointerAuthInfo &CurAuth,
327 const CGPointerAuthInfo &NewAuth) {
328 assert(CurAuth && NewAuth);
329
330 if (CurAuth.getAuthenticationMode() !=
332 NewAuth.getAuthenticationMode() !=
334 llvm::Value *AuthedValue = EmitPointerAuthAuth(CurAuth, Value);
335 return EmitPointerAuthSign(NewAuth, AuthedValue);
336 }
337 // Convert the pointer to intptr_t before signing it.
338 auto *OrigType = Value->getType();
339 Value = Builder.CreatePtrToInt(Value, IntPtrTy);
340
341 auto *CurKey = Builder.getInt32(CurAuth.getKey());
342 auto *NewKey = Builder.getInt32(NewAuth.getKey());
343
344 llvm::Value *CurDiscriminator = getDiscriminatorOrZero(CurAuth, Builder);
345 llvm::Value *NewDiscriminator = getDiscriminatorOrZero(NewAuth, Builder);
346
347 // call i64 @llvm.ptrauth.resign(i64 %pointer,
348 // i32 %curKey, i64 %curDiscriminator,
349 // i32 %newKey, i64 %newDiscriminator)
350 auto *Intrinsic = CGM.getIntrinsic(llvm::Intrinsic::ptrauth_resign);
352 Intrinsic, {Value, CurKey, CurDiscriminator, NewKey, NewDiscriminator});
353
354 // Convert back to the original type.
355 Value = Builder.CreateIntToPtr(Value, OrigType);
356 return Value;
357}
358
360 llvm::Value *Value, QualType Type, const CGPointerAuthInfo &CurAuthInfo,
361 const CGPointerAuthInfo &NewAuthInfo, bool IsKnownNonNull) {
362 // Fast path: if neither schema wants a signature, we're done.
363 if (!CurAuthInfo && !NewAuthInfo)
364 return Value;
365
366 llvm::Value *Null = nullptr;
367 // If the value is obviously null, we're done.
368 if (auto *PointerValue = dyn_cast<llvm::PointerType>(Value->getType())) {
369 Null = CGM.getNullPointer(PointerValue, Type);
370 } else {
371 assert(Value->getType()->isIntegerTy());
372 Null = llvm::ConstantInt::get(IntPtrTy, 0);
373 }
374 if (Value == Null)
375 return Value;
376
377 // If both schemas sign the same way, we're done.
378 if (equalAuthPolicies(CurAuthInfo, NewAuthInfo)) {
379 const llvm::Value *CurD = CurAuthInfo.getDiscriminator();
380 const llvm::Value *NewD = NewAuthInfo.getDiscriminator();
381 if (CurD == NewD)
382 return Value;
383
384 if ((CurD == nullptr && isZeroConstant(NewD)) ||
385 (NewD == nullptr && isZeroConstant(CurD)))
386 return Value;
387 }
388
389 llvm::BasicBlock *InitBB = Builder.GetInsertBlock();
390 llvm::BasicBlock *ResignBB = nullptr, *ContBB = nullptr;
391
392 // Null pointers have to be mapped to null, and the ptrauth_resign
393 // intrinsic doesn't do that.
394 if (!IsKnownNonNull && !llvm::isKnownNonZero(Value, CGM.getDataLayout())) {
395 ContBB = createBasicBlock("resign.cont");
396 ResignBB = createBasicBlock("resign.nonnull");
397
398 auto *IsNonNull = Builder.CreateICmpNE(Value, Null);
399 Builder.CreateCondBr(IsNonNull, ResignBB, ContBB);
400 EmitBlock(ResignBB);
401 }
402
403 // Perform the auth/sign/resign operation.
404 if (!NewAuthInfo)
405 Value = EmitPointerAuthAuth(CurAuthInfo, Value);
406 else if (!CurAuthInfo)
407 Value = EmitPointerAuthSign(NewAuthInfo, Value);
408 else
409 Value = emitPointerAuthResignCall(Value, CurAuthInfo, NewAuthInfo);
410
411 // Clean up with a phi if we branched before.
412 if (ContBB) {
413 EmitBlock(ContBB);
414 auto *Phi = Builder.CreatePHI(Value->getType(), 2);
415 Phi->addIncoming(Null, InitBB);
416 Phi->addIncoming(Value, ResignBB);
417 Value = Phi;
418 }
419
420 return Value;
421}
422
424 Address DestAddress,
425 Address SrcAddress) {
426 assert(Qual);
427 llvm::Value *Value = Builder.CreateLoad(SrcAddress);
428
429 // If we're using address-discrimination, we have to re-sign the value.
430 if (Qual.isAddressDiscriminated()) {
431 CGPointerAuthInfo SrcPtrAuth = EmitPointerAuthInfo(Qual, SrcAddress);
432 CGPointerAuthInfo DestPtrAuth = EmitPointerAuthInfo(Qual, DestAddress);
433 Value = emitPointerAuthResign(Value, T, SrcPtrAuth, DestPtrAuth,
434 /*IsKnownNonNull=*/false);
435 }
436
437 Builder.CreateStore(Value, DestAddress);
438}
439
440llvm::Constant *
442 llvm::Constant *StorageAddress,
443 llvm::ConstantInt *OtherDiscriminator) {
444 llvm::Constant *AddressDiscriminator;
445 if (StorageAddress) {
446 assert(StorageAddress->getType() == DefaultPtrTy);
447 AddressDiscriminator = StorageAddress;
448 } else {
449 AddressDiscriminator = llvm::Constant::getNullValue(DefaultPtrTy);
450 }
451
452 llvm::ConstantInt *IntegerDiscriminator;
453 if (OtherDiscriminator) {
454 assert(OtherDiscriminator->getType() == Int64Ty);
455 IntegerDiscriminator = OtherDiscriminator;
456 } else {
457 IntegerDiscriminator = llvm::ConstantInt::get(Int64Ty, 0);
458 }
459
460 return llvm::ConstantPtrAuth::get(
461 Pointer, llvm::ConstantInt::get(Int32Ty, Key), IntegerDiscriminator,
462 AddressDiscriminator,
463 /*DeactivationSymbol=*/llvm::Constant::getNullValue(DefaultPtrTy));
464}
465
466/// Does a given PointerAuthScheme require us to sign a value
468 auto AuthenticationMode = Schema.getAuthenticationMode();
469 return AuthenticationMode == PointerAuthenticationMode::SignAndStrip ||
470 AuthenticationMode == PointerAuthenticationMode::SignAndAuth;
471}
472
473/// Sign a constant pointer using the given scheme, producing a constant
474/// with the same IR type.
476 llvm::Constant *Pointer, const PointerAuthSchema &Schema,
477 llvm::Constant *StorageAddress, GlobalDecl SchemaDecl,
478 QualType SchemaType) {
479 assert(shouldSignPointer(Schema));
480 llvm::ConstantInt *OtherDiscriminator =
481 getPointerAuthOtherDiscriminator(Schema, SchemaDecl, SchemaType);
482
483 return getConstantSignedPointer(Pointer, Schema.getKey(), StorageAddress,
484 OtherDiscriminator);
485}
486
487llvm::Constant *
489 unsigned Key, llvm::Constant *StorageAddress,
490 llvm::ConstantInt *OtherDiscriminator) {
491 return CGM.getConstantSignedPointer(Pointer, Key, StorageAddress,
492 OtherDiscriminator);
493}
494
495/// If applicable, sign a given constant function pointer with the ABI rules for
496/// functionType.
497llvm::Constant *CodeGenModule::getFunctionPointer(llvm::Constant *Pointer,
499 assert(FunctionType->isFunctionType() ||
502
503 if (auto PointerAuth = getFunctionPointerAuthInfo(FunctionType))
505 Pointer, PointerAuth.getKey(), /*StorageAddress=*/nullptr,
506 cast_or_null<llvm::ConstantInt>(PointerAuth.getDiscriminator()));
507
508 return Pointer;
509}
510
512 llvm::Type *Ty) {
513 const auto *FD = cast<FunctionDecl>(GD.getDecl());
514 QualType FuncType = FD->getType();
515
516 // Annoyingly, K&R functions have prototypes in the clang AST, but
517 // expressions referring to them are unprototyped.
518 if (!FD->hasPrototype())
519 if (const auto *Proto = FuncType->getAs<FunctionProtoType>())
520 FuncType = Context.getFunctionNoProtoType(Proto->getReturnType(),
521 Proto->getExtInfo());
522
523 return getFunctionPointer(getRawFunctionPointer(GD, Ty), FuncType);
524}
525
527 assert(FT->getAs<MemberPointerType>() && "MemberPointerType expected");
529 if (!Schema)
530 return CGPointerAuthInfo();
531
532 assert(!Schema.isAddressDiscriminated() &&
533 "function pointers cannot use address-specific discrimination");
534
535 llvm::ConstantInt *Discriminator =
537 return CGPointerAuthInfo(Schema.getKey(), Schema.getAuthenticationMode(),
538 /* IsIsaPointer */ false,
539 /* AuthenticatesNullValues */ false, Discriminator);
540}
541
542llvm::Constant *CodeGenModule::getMemberFunctionPointer(llvm::Constant *Pointer,
543 QualType FT) {
546 Pointer, PointerAuth.getKey(), nullptr,
547 cast_or_null<llvm::ConstantInt>(PointerAuth.getDiscriminator()));
548
549 if (const auto *MFT = dyn_cast<MemberPointerType>(FT.getTypePtr())) {
550 if (MFT->hasPointeeToCFIUncheckedCalleeFunctionType())
551 Pointer = llvm::NoCFIValue::get(cast<llvm::GlobalValue>(Pointer));
552 }
553
554 return Pointer;
555}
556
558 llvm::Type *Ty) {
559 QualType FT = FD->getType();
560 FT = getContext().getMemberPointerType(FT, /*Qualifier=*/std::nullopt,
561 cast<CXXMethodDecl>(FD)->getParent());
563}
564
565std::optional<PointerAuthQualifier>
566CodeGenModule::computeVTPointerAuthentication(const CXXRecordDecl *ThisClass,
567 bool IsVTTEntry) {
568 auto DefaultAuthentication =
571 if (!DefaultAuthentication)
572 return std::nullopt;
573 const CXXRecordDecl *PrimaryBase =
574 Context.baseForVTableAuthentication(ThisClass);
575 const CXXRecordDecl *TypeDiscriminatorClass =
576 IsVTTEntry ? ThisClass : PrimaryBase;
577
578 unsigned Key = DefaultAuthentication.getKey();
579 bool AddressDiscriminated = DefaultAuthentication.isAddressDiscriminated();
580 auto DefaultDiscrimination = DefaultAuthentication.getOtherDiscrimination();
581 unsigned TypeBasedDiscriminator =
582 Context.getPointerAuthVTablePointerDiscriminator(TypeDiscriminatorClass,
583 IsVTTEntry);
584 unsigned Discriminator;
585 if (DefaultDiscrimination == PointerAuthSchema::Discrimination::Type) {
586 Discriminator = TypeBasedDiscriminator;
587 } else if (DefaultDiscrimination ==
589 Discriminator = DefaultAuthentication.getConstantDiscrimination();
590 } else {
591 assert(DefaultDiscrimination == PointerAuthSchema::Discrimination::None);
592 Discriminator = 0;
593 }
594 auto ExplicitAuthentication =
595 PrimaryBase->getAttr<VTablePointerAuthenticationAttr>();
596
597 // TODO: enable explicit authentication path for VTT vtable entries.
598 if (!IsVTTEntry && ExplicitAuthentication) {
599 auto ExplicitAddressDiscrimination =
600 ExplicitAuthentication->getAddressDiscrimination();
601 auto ExplicitDiscriminator =
602 ExplicitAuthentication->getExtraDiscrimination();
603
604 unsigned ExplicitKey = ExplicitAuthentication->getKey();
605 if (ExplicitKey == VTablePointerAuthenticationAttr::NoKey)
606 return std::nullopt;
607
608 if (ExplicitKey != VTablePointerAuthenticationAttr::DefaultKey) {
609 if (ExplicitKey == VTablePointerAuthenticationAttr::ProcessIndependent)
611 else {
612 assert(ExplicitKey ==
613 VTablePointerAuthenticationAttr::ProcessDependent);
615 }
616 }
617
618 if (ExplicitAddressDiscrimination !=
619 VTablePointerAuthenticationAttr::DefaultAddressDiscrimination)
620 AddressDiscriminated =
621 ExplicitAddressDiscrimination ==
622 VTablePointerAuthenticationAttr::AddressDiscrimination;
623
624 if (ExplicitDiscriminator ==
625 VTablePointerAuthenticationAttr::TypeDiscrimination)
626 Discriminator = TypeBasedDiscriminator;
627 else if (ExplicitDiscriminator ==
628 VTablePointerAuthenticationAttr::CustomDiscrimination)
629 Discriminator = ExplicitAuthentication->getCustomDiscriminationValue();
630 else if (ExplicitDiscriminator ==
631 VTablePointerAuthenticationAttr::NoExtraDiscrimination)
632 Discriminator = 0;
633 }
634 return PointerAuthQualifier::Create(Key, AddressDiscriminated, Discriminator,
636 /* IsIsaPointer */ false,
637 /* AuthenticatesNullValues */ false);
638}
639
640std::optional<PointerAuthQualifier>
642 bool IsVTTEntry) {
643 if (!Record->getDefinition() || !Record->isPolymorphic())
644 return std::nullopt;
645
646 if (IsVTTEntry)
647 return computeVTPointerAuthentication(Record, IsVTTEntry);
648
649 auto Existing = VTablePtrAuthInfos.find(Record);
650 if (Existing != VTablePtrAuthInfos.end())
651 return Existing->getSecond();
652
653 std::optional<PointerAuthQualifier> Authentication =
654 computeVTPointerAuthentication(Record, IsVTTEntry);
655 VTablePtrAuthInfos.insert(std::make_pair(Record, Authentication));
656 return Authentication;
657}
658
659std::optional<CGPointerAuthInfo> CodeGenModule::getVTablePointerAuthInfo(
661 llvm::Value *StorageAddress, bool IsVTTEntry) {
662 auto Authentication = getVTablePointerAuthentication(Record, IsVTTEntry);
663 if (!Authentication)
664 return std::nullopt;
665
666 llvm::Value *Discriminator = nullptr;
667 if (auto ExtraDiscriminator = Authentication->getExtraDiscriminator())
668 Discriminator = llvm::ConstantInt::get(IntPtrTy, ExtraDiscriminator);
669
670 if (Authentication->isAddressDiscriminated()) {
671 assert(StorageAddress &&
672 "address not provided for address-discriminated schema");
673 if (Discriminator)
674 Discriminator =
675 CGF->EmitPointerAuthBlendDiscriminator(StorageAddress, Discriminator);
676 else
677 Discriminator = CGF->Builder.CreatePtrToInt(StorageAddress, IntPtrTy);
678 }
679
680 return CGPointerAuthInfo(Authentication->getKey(),
682 /* IsIsaPointer */ false,
683 /* AuthenticatesNullValues */ false, Discriminator);
684}
685
686llvm::Value *CodeGenFunction::authPointerToPointerCast(llvm::Value *ResultPtr,
687 QualType SourceType,
688 QualType DestType) {
689 CGPointerAuthInfo CurAuthInfo, NewAuthInfo;
690 if (SourceType->isSignableType(getContext()))
691 CurAuthInfo = getPointerAuthInfoForType(CGM, SourceType);
692
693 if (DestType->isSignableType(getContext()))
694 NewAuthInfo = getPointerAuthInfoForType(CGM, DestType);
695
696 if (!CurAuthInfo && !NewAuthInfo)
697 return ResultPtr;
698
699 // If only one side of the cast is a function pointer, then we still need to
700 // resign to handle casts to/from opaque pointers.
701 if (!CurAuthInfo && DestType->isFunctionPointerType())
702 CurAuthInfo = CGM.getFunctionPointerAuthInfo(SourceType);
703
704 if (!NewAuthInfo && SourceType->isFunctionPointerType())
705 NewAuthInfo = CGM.getFunctionPointerAuthInfo(DestType);
706
707 return emitPointerAuthResign(ResultPtr, DestType, CurAuthInfo, NewAuthInfo,
708 /*IsKnownNonNull=*/false);
709}
710
712 QualType SourceType,
713 QualType DestType) {
714 CGPointerAuthInfo CurAuthInfo, NewAuthInfo;
715 if (SourceType->isSignableType(getContext()))
716 CurAuthInfo = getPointerAuthInfoForType(CGM, SourceType);
717
718 if (DestType->isSignableType(getContext()))
719 NewAuthInfo = getPointerAuthInfoForType(CGM, DestType);
720
721 if (!CurAuthInfo && !NewAuthInfo)
722 return Ptr;
723
724 if (!CurAuthInfo && DestType->isFunctionPointerType()) {
725 // When casting a non-signed pointer to a function pointer, just set the
726 // auth info on Ptr to the assumed schema. The pointer will be resigned to
727 // the effective type when used.
728 Ptr.setPointerAuthInfo(CGM.getFunctionPointerAuthInfo(SourceType));
729 return Ptr;
730 }
731
732 if (!NewAuthInfo && SourceType->isFunctionPointerType()) {
733 NewAuthInfo = CGM.getFunctionPointerAuthInfo(DestType);
734 Ptr = Ptr.getResignedAddress(NewAuthInfo, *this);
735 Ptr.setPointerAuthInfo(CGPointerAuthInfo());
736 return Ptr;
737 }
738
739 return Ptr;
740}
741
743 QualType PointeeTy) {
744 CGPointerAuthInfo Info =
745 PointeeTy.isNull() ? CGPointerAuthInfo()
746 : CGM.getPointerAuthInfoForPointeeType(PointeeTy);
747 return Addr.getResignedAddress(Info, *this);
748}
749
751 CodeGenFunction &CGF) const {
752 assert(isValid() && "pointer isn't valid");
754 llvm::Value *Val;
755
756 // Nothing to do if neither the current or the new ptrauth info needs signing.
757 if (!CurInfo.isSigned() && !NewInfo.isSigned())
760
761 assert(ElementType && "Effective type has to be set");
762 assert(!Offset && "unexpected non-null offset");
763
764 // If the current and the new ptrauth infos are the same and the offset is
765 // null, just cast the base pointer to the effective type.
766 if (CurInfo == NewInfo && !hasOffset())
767 Val = getBasePointer();
768 else
769 Val = CGF.emitPointerAuthResign(getBasePointer(), QualType(), CurInfo,
770 NewInfo, isKnownNonNull());
771
772 return Address(Val, getElementType(), getAlignment(), NewInfo,
773 /*Offset=*/nullptr, isKnownNonNull());
774}
775
776llvm::Value *Address::emitRawPointerSlow(CodeGenFunction &CGF) const {
777 return CGF.getAsNaturalPointerTo(*this, QualType());
778}
779
780llvm::Value *LValue::getPointer(CodeGenFunction &CGF) const {
781 assert(isSimple());
782 return emitResignedPointer(getType(), CGF);
783}
784
786 CodeGenFunction &CGF) const {
787 assert(isSimple());
788 return CGF.getAsNaturalAddressOf(Addr, PointeeTy).getBasePointer();
789}
790
791llvm::Value *LValue::emitRawPointer(CodeGenFunction &CGF) const {
792 assert(isSimple());
793 return Addr.isValid() ? Addr.emitRawPointer(CGF) : nullptr;
794}
static std::pair< llvm::Value *, CGPointerAuthInfo > emitLoadOfOrigPointerRValue(CodeGenFunction &CGF, const LValue &LV, SourceLocation Loc)
static bool isZeroConstant(const llvm::Value *Value)
static llvm::Value * getDiscriminatorOrZero(const CGPointerAuthInfo &Info, CGBuilderTy &Builder)
static bool equalAuthPolicies(const CGPointerAuthInfo &Left, const CGPointerAuthInfo &Right)
static CGPointerAuthInfo getPointerAuthInfoForPointeeType(CodeGenModule &CGM, QualType PointeeType)
Return the natural pointer authentication for values of the given pointee type.
static CGPointerAuthInfo getPointerAuthInfoForType(CodeGenModule &CGM, QualType PointerType)
Return the natural pointer authentication for values of the given pointer type.
llvm::MachO::Record Record
Definition MachO.h:31
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
uint16_t getPointerAuthTypeDiscriminator(QualType T)
Return the "other" type-specific discriminator for the given type.
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
PointerAuthOptions PointerAuth
Configuration for pointer-signing.
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition Address.h:128
llvm::Value * getBasePointer() const
Definition Address.h:198
Address(std::nullptr_t)
Definition Address.h:151
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:253
CharUnits getAlignment() const
Definition Address.h:194
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition Address.h:209
bool hasOffset() const
Definition Address.h:244
KnownNonNull_t isKnownNonNull() const
Whether the pointer is known not to be null.
Definition Address.h:233
Address getResignedAddress(const CGPointerAuthInfo &NewInfo, CodeGenFunction &CGF) const
const CGPointerAuthInfo & getPointerAuthInfo() const
Definition Address.h:220
bool isValid() const
Definition Address.h:177
MangleContext & getMangleContext()
Gets the mangle context.
Definition CGCXXABI.h:113
PointerAuthenticationMode getAuthenticationMode() const
llvm::Value * getDiscriminator() const
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::Value * EmitPointerAuthQualify(PointerAuthQualifier Qualifier, llvm::Value *Pointer, QualType ValueType, Address StorageAddress, bool IsKnownNonNull)
llvm::Value * getAsNaturalPointerTo(Address Addr, QualType PointeeType)
llvm::Value * emitPointerAuthResignCall(llvm::Value *Pointer, const CGPointerAuthInfo &CurInfo, const CGPointerAuthInfo &NewInfo)
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
bool isPointerKnownNonNull(const Expr *E)
llvm::Value * EmitPointerAuthUnqualify(PointerAuthQualifier Qualifier, llvm::Value *Pointer, QualType PointerType, Address StorageAddress, bool IsKnownNonNull)
@ TCK_Load
Checking the operand of a load. Must be suitably sized and aligned.
llvm::Value * EmitPointerAuthSign(const CGPointerAuthInfo &Info, llvm::Value *Pointer)
Address getAsNaturalAddressOf(Address Addr, QualType PointeeTy)
CGPointerAuthInfo EmitPointerAuthInfo(const PointerAuthSchema &Schema, llvm::Value *StorageAddress, GlobalDecl SchemaDecl, QualType SchemaType)
Emit the concrete pointer authentication informaton for the given authentication schema.
void EmitPointerAuthCopy(PointerAuthQualifier Qualifier, QualType Type, Address DestField, Address SrcField)
llvm::Value * emitPointerAuthResign(llvm::Value *Pointer, QualType PointerType, const CGPointerAuthInfo &CurAuthInfo, const CGPointerAuthInfo &NewAuthInfo, bool IsKnownNonNull)
llvm::Value * EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, SourceLocation Loc, AlignmentSource Source=AlignmentSource::Type, bool isNontemporal=false)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
llvm::Value * authPointerToPointerCast(llvm::Value *ResultPtr, QualType SourceType, QualType DestType)
LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK)
Same as EmitLValue but additionally we generate checking code to guard against undefined behavior.
Definition CGExpr.cpp:1734
llvm::Value * EmitPointerAuthBlendDiscriminator(llvm::Value *StorageAddress, llvm::Value *Discriminator)
Create the discriminator from the storage address and the entity hash.
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
ConstantEmission tryEmitAsConstant(const DeclRefExpr *RefExpr)
Try to emit a reference to the given value without producing it as an l-value.
Definition CGExpr.cpp:1949
std::pair< llvm::Value *, CGPointerAuthInfo > EmitOrigPointerRValue(const Expr *E)
Retrieve a pointer rvalue and its ptrauth info.
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:659
llvm::Value * EmitPointerAuthAuth(const CGPointerAuthInfo &Info, llvm::Value *Pointer)
This class organizes the cross-function state that is used while generating LLVM code.
std::optional< PointerAuthQualifier > getVTablePointerAuthentication(const CXXRecordDecl *thisClass, bool IsVTTEntry=false)
llvm::Constant * getRawFunctionPointer(GlobalDecl GD, llvm::Type *Ty=nullptr)
Return a function pointer for a reference to the given function.
Definition CGExpr.cpp:3511
llvm::Constant * getFunctionPointer(GlobalDecl GD, llvm::Type *Ty=nullptr)
Return the ABI-correct function pointer value for a reference to the given function.
CGPointerAuthInfo getMemberFunctionPointerAuthInfo(QualType FT)
llvm::ConstantInt * getPointerAuthOtherDiscriminator(const PointerAuthSchema &Schema, GlobalDecl SchemaDecl, QualType SchemaType)
Given a pointer-authentication schema, return a concrete "other" discriminator for it.
CGPointerAuthInfo getPointerAuthInfoForPointeeType(QualType type)
CGPointerAuthInfo getFunctionPointerAuthInfo(QualType T)
Return the abstract pointer authentication schema for a pointer to the given function type.
llvm::Constant * getMemberFunctionPointer(const FunctionDecl *FD, llvm::Type *Ty=nullptr)
uint16_t getPointerAuthDeclDiscriminator(GlobalDecl GD)
Return the "other" decl-specific discriminator for the given decl.
ASTContext & getContext() const
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
std::optional< CGPointerAuthInfo > getVTablePointerAuthInfo(CodeGenFunction *Context, const CXXRecordDecl *Record, llvm::Value *StorageAddress, bool IsVTTEntry=false)
llvm::Constant * getConstantSignedPointer(llvm::Constant *Pointer, const PointerAuthSchema &Schema, llvm::Constant *StorageAddress, GlobalDecl SchemaDecl, QualType SchemaType)
Sign a constant pointer using the given scheme, producing a constant with the same IR type.
bool shouldSignPointer(const PointerAuthSchema &Schema)
Does a given PointerAuthScheme require us to sign a value.
CGPointerAuthInfo getPointerAuthInfoForType(QualType type)
LValue - This represents an lvalue references.
Definition CGValue.h:183
llvm::Value * emitResignedPointer(QualType PointeeTy, CodeGenFunction &CGF) const
bool isSimple() const
Definition CGValue.h:286
llvm::Value * getPointer(CodeGenFunction &CGF) const
QualType getType() const
Definition CGValue.h:303
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
T * getAttr() const
Definition DeclBase.h:582
This represents one expression.
Definition Expr.h:114
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:146
Represents a function declaration or definition.
Definition Decl.h:2082
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5548
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4744
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
const Decl * getDecl() const
Definition GlobalDecl.h:115
virtual void mangleCXXName(GlobalDecl GD, raw_ostream &)=0
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
Pointer-authentication qualifiers.
Definition TypeBase.h:153
static PointerAuthQualifier Create(unsigned Key, bool IsAddressDiscriminated, unsigned ExtraDiscriminator, PointerAuthenticationMode AuthenticationMode, bool IsIsaPointer, bool AuthenticatesNullValues)
Definition TypeBase.h:240
bool authenticatesNullValues() const
Definition TypeBase.h:286
bool isAddressDiscriminated() const
Definition TypeBase.h:266
unsigned getExtraDiscriminator() const
Definition TypeBase.h:271
PointerAuthenticationMode getAuthenticationMode() const
Definition TypeBase.h:276
unsigned getKey() const
Definition TypeBase.h:259
Discrimination getOtherDiscrimination() const
@ None
No additional discrimination.
@ Type
Include a hash of the entity's type.
@ Decl
Include a hash of the entity's identity.
@ Constant
Discriminate using a constant value.
PointerAuthenticationMode getAuthenticationMode() const
uint16_t getConstantDiscrimination() const
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
QualType getPointeeType() const
Definition TypeBase.h:3413
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8578
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
Definition Type.cpp:1841
Encodes a location in the source.
bool isBlockPointerType() const
Definition TypeBase.h:8835
bool isFunctionReferenceType() const
Definition TypeBase.h:8889
bool isSignableType(const ASTContext &Ctx) const
Definition TypeBase.h:8827
bool isFunctionPointerType() const
Definition TypeBase.h:8882
bool isFunctionType() const
Definition TypeBase.h:8811
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
QualType getType() const
Definition Decl.h:725
QualType getType() const
Definition Value.cpp:238
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
Definition CGValue.h:155
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
Definition CGValue.h:146
uint16_t getPointerAuthDeclDiscriminator(CodeGenModule &CGM, GlobalDecl GD)
Return a declaration discriminator for the given global decl.
llvm::Constant * getConstantSignedPointer(CodeGenModule &CGM, llvm::Constant *Pointer, unsigned Key, llvm::Constant *StorageAddress, llvm::ConstantInt *OtherDiscriminator)
Return a signed constant pointer.
uint16_t getPointerAuthTypeDiscriminator(CodeGenModule &CGM, QualType FunctionType)
Return a type discriminator for the given function type.
Top level wrappers for InstallAPI frontend operations.
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
U cast(CodeGen::Address addr)
Definition Address.h:327
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 unsigned
static constexpr llvm::StringLiteral FunctionLabelPrefix
Definition Mangle.h:338
PointerAuthSchema CXXVTablePointers
The ABI for C++ virtual table pointers (the pointer to the table itself) as installed in an actual cl...
PointerAuthSchema CXXVTTVTablePointers
The ABI for C++ virtual table pointers as installed in a VTT.
PointerAuthSchema FunctionPointers
The ABI for C function pointers.
PointerAuthSchema CXXMemberFunctionPointers
The ABI for C++ member function pointers.