clang 23.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"
19#include "llvm/Analysis/ValueTracking.h"
20#include "llvm/Support/SipHash.h"
21
22using namespace clang;
23using namespace CodeGen;
24
25/// Given a pointer-authentication schema, return a concrete "other"
26/// discriminator for it.
29 switch (Schema.getOtherDiscrimination()) {
31 return nullptr;
32
34 assert(!Type.isNull() && "type not provided for type-discriminated schema");
35 return llvm::ConstantInt::get(
37
39 assert(Decl.getDecl() &&
40 "declaration not provided for decl-discriminated schema");
41 return llvm::ConstantInt::get(IntPtrTy,
43
45 return llvm::ConstantInt::get(IntPtrTy, Schema.getConstantDiscrimination());
46 }
47 llvm_unreachable("bad discrimination kind");
48}
49
54
59
60/// Return the "other" decl-specific discriminator for the given decl.
61uint16_t
63 uint16_t &EntityHash = PtrAuthDiscriminatorHashes[Declaration];
64
65 if (EntityHash == 0) {
66 const auto *ND = cast<NamedDecl>(Declaration.getDecl());
67 if (ND->hasAttr<AsmLabelAttr>() &&
68 ND->getAttr<AsmLabelAttr>()->getLabel().starts_with(
70 // If the declaration comes from LLDB, the asm label has a prefix that
71 // would producing a different discriminator. Compute the real C++ mangled
72 // name instead so the discriminator matches what the original translation
73 // unit used.
74 SmallString<256> Buffer;
75 llvm::raw_svector_ostream Out(Buffer);
77 EntityHash = llvm::getPointerAuthStableSipHash(Out.str());
78 } else {
79 StringRef Name = getMangledName(Declaration);
80 EntityHash = llvm::getPointerAuthStableSipHash(Name);
81 }
82 }
83
84 return EntityHash;
85}
86
87/// Return the abstract pointer authentication schema for a pointer to the given
88/// function type.
90 const auto &Schema = getCodeGenOpts().PointerAuth.FunctionPointers;
91 if (!Schema)
92 return CGPointerAuthInfo();
93
94 assert(!Schema.isAddressDiscriminated() &&
95 "function pointers cannot use address-specific discrimination");
96
97 llvm::Constant *Discriminator = nullptr;
98 if (T->isFunctionPointerType() || T->isFunctionReferenceType())
99 T = T->getPointeeType();
100 if (T->isFunctionType())
101 Discriminator = getPointerAuthOtherDiscriminator(Schema, GlobalDecl(), T);
102
103 return CGPointerAuthInfo(Schema.getKey(), Schema.getAuthenticationMode(),
104 /*IsaPointer=*/false, /*AuthenticatesNull=*/false,
105 Discriminator);
106}
107
108llvm::Value *
110 llvm::Value *Discriminator) {
111 StorageAddress = Builder.CreatePtrToInt(StorageAddress, IntPtrTy);
112 auto Intrinsic = CGM.getIntrinsic(llvm::Intrinsic::ptrauth_blend);
113 return Builder.CreateCall(Intrinsic, {StorageAddress, Discriminator});
114}
115
116/// Emit the concrete pointer authentication informaton for the
117/// given authentication schema.
119 const PointerAuthSchema &Schema, llvm::Value *StorageAddress,
120 GlobalDecl SchemaDecl, QualType SchemaType) {
121 if (!Schema)
122 return CGPointerAuthInfo();
123
124 llvm::Value *Discriminator =
125 CGM.getPointerAuthOtherDiscriminator(Schema, SchemaDecl, SchemaType);
126
127 if (Schema.isAddressDiscriminated()) {
128 assert(StorageAddress &&
129 "address not provided for address-discriminated schema");
130
131 if (Discriminator)
132 Discriminator =
133 EmitPointerAuthBlendDiscriminator(StorageAddress, Discriminator);
134 else
135 Discriminator = Builder.CreatePtrToInt(StorageAddress, IntPtrTy);
136 }
137
138 return CGPointerAuthInfo(Schema.getKey(), Schema.getAuthenticationMode(),
139 Schema.isIsaPointer(),
140 Schema.authenticatesNullValues(), Discriminator);
141}
142
145 Address StorageAddress) {
146 assert(Qual && "don't call this if you don't know that the Qual is present");
147 if (Qual.hasKeyNone())
148 return CGPointerAuthInfo();
149
150 llvm::Value *Discriminator = nullptr;
151 if (unsigned Extra = Qual.getExtraDiscriminator())
152 Discriminator = llvm::ConstantInt::get(IntPtrTy, Extra);
153
154 if (Qual.isAddressDiscriminated()) {
155 assert(StorageAddress.isValid() &&
156 "address discrimination without address");
157 llvm::Value *StoragePtr = StorageAddress.emitRawPointer(*this);
158 if (Discriminator)
159 Discriminator =
160 EmitPointerAuthBlendDiscriminator(StoragePtr, Discriminator);
161 else
162 Discriminator = Builder.CreatePtrToInt(StoragePtr, IntPtrTy);
163 }
164
165 return CGPointerAuthInfo(Qual.getKey(), Qual.getAuthenticationMode(),
167 Discriminator);
168}
169
170/// Return the natural pointer authentication for values of the given
171/// pointee type.
174 if (PointeeType.isNull())
175 return CGPointerAuthInfo();
176
177 // Function pointers use the function-pointer schema by default.
178 if (PointeeType->isFunctionType())
179 return CGM.getFunctionPointerAuthInfo(PointeeType);
180
181 // Normal data pointers never use direct pointer authentication by default.
182 return CGPointerAuthInfo();
183}
184
186 return ::getPointerAuthInfoForPointeeType(*this, T);
187}
188
189/// Return the natural pointer authentication for values of the given
190/// pointer type.
193 assert(PointerType->isSignableType(CGM.getContext()));
194
195 // Block pointers are currently not signed.
197 return CGPointerAuthInfo();
198
199 auto PointeeType = PointerType->getPointeeType();
200
201 if (PointeeType.isNull())
202 return CGPointerAuthInfo();
203
204 return ::getPointerAuthInfoForPointeeType(CGM, PointeeType);
205}
206
208 return ::getPointerAuthInfoForType(*this, T);
209}
210
211static std::pair<llvm::Value *, CGPointerAuthInfo>
213 SourceLocation Loc) {
214 llvm::Value *Value = CGF.EmitLoadOfScalar(LV, Loc);
215 CGPointerAuthInfo AuthInfo;
216 if (PointerAuthQualifier PtrAuth = LV.getQuals().getPointerAuth())
217 AuthInfo = CGF.EmitPointerAuthInfo(PtrAuth, LV.getAddress());
218 else
219 AuthInfo = getPointerAuthInfoForType(CGF.CGM, LV.getType());
220 return {Value, AuthInfo};
221}
222
223/// Retrieve a pointer rvalue and its ptrauth info. When possible, avoid
224/// needlessly resigning the pointer.
225std::pair<llvm::Value *, CGPointerAuthInfo>
227 assert(E->getType()->isSignableType(getContext()));
228
229 E = E->IgnoreParens();
230 if (const auto *Load = dyn_cast<ImplicitCastExpr>(E)) {
231 if (Load->getCastKind() == CK_LValueToRValue) {
232 E = Load->getSubExpr()->IgnoreParens();
233
234 // We're semantically required to not emit loads of certain DREs naively.
235 if (const auto *RefExpr = dyn_cast<DeclRefExpr>(E)) {
237 // Fold away a use of an intermediate variable.
238 if (!Result.isReference())
239 return {Result.getValue(),
240 getPointerAuthInfoForType(CGM, RefExpr->getType())};
241
242 // Fold away a use of an intermediate reference.
243 LValue LV = Result.getReferenceLValue(*this, RefExpr);
244 return emitLoadOfOrigPointerRValue(*this, LV, RefExpr->getLocation());
245 }
246 }
247
248 // Otherwise, load and use the pointer
250 return emitLoadOfOrigPointerRValue(*this, LV, E->getExprLoc());
251 }
252 }
253
254 // Fallback: just use the normal rules for the type.
255 llvm::Value *Value = EmitScalarExpr(E);
257}
258
259llvm::Value *
261 const Expr *E,
262 Address DestStorageAddress) {
263 assert(DestQualifier);
264 auto [Value, CurAuthInfo] = EmitOrigPointerRValue(E);
265
266 CGPointerAuthInfo DestAuthInfo =
267 EmitPointerAuthInfo(DestQualifier, DestStorageAddress);
268 return emitPointerAuthResign(Value, E->getType(), CurAuthInfo, DestAuthInfo,
270}
271
273 PointerAuthQualifier DestQualifier, llvm::Value *Value,
274 QualType PointerType, Address DestStorageAddress, bool IsKnownNonNull) {
275 assert(DestQualifier);
276
278 CGPointerAuthInfo DestAuthInfo =
279 EmitPointerAuthInfo(DestQualifier, DestStorageAddress);
280 return emitPointerAuthResign(Value, PointerType, CurAuthInfo, DestAuthInfo,
281 IsKnownNonNull);
282}
283
285 PointerAuthQualifier CurQualifier, llvm::Value *Value, QualType PointerType,
286 Address CurStorageAddress, bool IsKnownNonNull) {
287 assert(CurQualifier);
288
289 CGPointerAuthInfo CurAuthInfo =
290 EmitPointerAuthInfo(CurQualifier, CurStorageAddress);
292 return emitPointerAuthResign(Value, PointerType, CurAuthInfo, DestAuthInfo,
293 IsKnownNonNull);
294}
295
296static bool isZeroConstant(const llvm::Value *Value) {
297 if (const auto *CI = dyn_cast<llvm::ConstantInt>(Value))
298 return CI->isZero();
299 return false;
300}
301
302static bool equalAuthPolicies(const CGPointerAuthInfo &Left,
303 const CGPointerAuthInfo &Right) {
304 assert((Left.isSigned() || Right.isSigned()) &&
305 "shouldn't be called if neither is signed");
306 if (Left.isSigned() != Right.isSigned())
307 return false;
308 return Left.getKey() == Right.getKey() &&
309 Left.getAuthenticationMode() == Right.getAuthenticationMode() &&
310 Left.isIsaPointer() == Right.isIsaPointer() &&
311 Left.authenticatesNullValues() == Right.authenticatesNullValues() &&
312 Left.getDiscriminator() == Right.getDiscriminator();
313}
314
315// Return the discriminator or return zero if the discriminator is null.
316static llvm::Value *getDiscriminatorOrZero(const CGPointerAuthInfo &Info,
317 CGBuilderTy &Builder) {
318 llvm::Value *Discriminator = Info.getDiscriminator();
319 return Discriminator ? Discriminator : Builder.getSize(0);
320}
321
322llvm::Value *
324 const CGPointerAuthInfo &CurAuth,
325 const CGPointerAuthInfo &NewAuth) {
326 assert(CurAuth && NewAuth);
327
328 if (CurAuth.getAuthenticationMode() !=
330 NewAuth.getAuthenticationMode() !=
332 llvm::Value *AuthedValue = EmitPointerAuthAuth(CurAuth, Value);
333 return EmitPointerAuthSign(NewAuth, AuthedValue);
334 }
335 // Convert the pointer to intptr_t before signing it.
336 auto *OrigType = Value->getType();
337 Value = Builder.CreatePtrToInt(Value, IntPtrTy);
338
339 auto *CurKey = Builder.getInt32(CurAuth.getKey());
340 auto *NewKey = Builder.getInt32(NewAuth.getKey());
341
342 llvm::Value *CurDiscriminator = getDiscriminatorOrZero(CurAuth, Builder);
343 llvm::Value *NewDiscriminator = getDiscriminatorOrZero(NewAuth, Builder);
344
345 // call i64 @llvm.ptrauth.resign(i64 %pointer,
346 // i32 %curKey, i64 %curDiscriminator,
347 // i32 %newKey, i64 %newDiscriminator)
348 auto *Intrinsic = CGM.getIntrinsic(llvm::Intrinsic::ptrauth_resign);
350 Intrinsic, {Value, CurKey, CurDiscriminator, NewKey, NewDiscriminator});
351
352 // Convert back to the original type.
353 Value = Builder.CreateIntToPtr(Value, OrigType);
354 return Value;
355}
356
358 llvm::Value *Value, QualType Type, const CGPointerAuthInfo &CurAuthInfo,
359 const CGPointerAuthInfo &NewAuthInfo, bool IsKnownNonNull) {
360 // Fast path: if neither schema wants a signature, we're done.
361 if (!CurAuthInfo && !NewAuthInfo)
362 return Value;
363
364 llvm::Value *Null = nullptr;
365 // If the value is obviously null, we're done.
366 if (auto *PointerValue = dyn_cast<llvm::PointerType>(Value->getType())) {
367 Null = CGM.getNullPointer(PointerValue, Type);
368 } else {
369 assert(Value->getType()->isIntegerTy());
370 Null = llvm::ConstantInt::get(IntPtrTy, 0);
371 }
372 if (Value == Null)
373 return Value;
374
375 // If both schemas sign the same way, we're done.
376 if (equalAuthPolicies(CurAuthInfo, NewAuthInfo)) {
377 const llvm::Value *CurD = CurAuthInfo.getDiscriminator();
378 const llvm::Value *NewD = NewAuthInfo.getDiscriminator();
379 if (CurD == NewD)
380 return Value;
381
382 if ((CurD == nullptr && isZeroConstant(NewD)) ||
383 (NewD == nullptr && isZeroConstant(CurD)))
384 return Value;
385 }
386
387 llvm::BasicBlock *InitBB = Builder.GetInsertBlock();
388 llvm::BasicBlock *ResignBB = nullptr, *ContBB = nullptr;
389
390 // Null pointers have to be mapped to null, and the ptrauth_resign
391 // intrinsic doesn't do that.
392 if (!IsKnownNonNull && !llvm::isKnownNonZero(Value, CGM.getDataLayout())) {
393 ContBB = createBasicBlock("resign.cont");
394 ResignBB = createBasicBlock("resign.nonnull");
395
396 auto *IsNonNull = Builder.CreateICmpNE(Value, Null);
397 Builder.CreateCondBr(IsNonNull, ResignBB, ContBB);
398 EmitBlock(ResignBB);
399 }
400
401 // Perform the auth/sign/resign operation.
402 if (!NewAuthInfo)
403 Value = EmitPointerAuthAuth(CurAuthInfo, Value);
404 else if (!CurAuthInfo)
405 Value = EmitPointerAuthSign(NewAuthInfo, Value);
406 else
407 Value = emitPointerAuthResignCall(Value, CurAuthInfo, NewAuthInfo);
408
409 // Clean up with a phi if we branched before.
410 if (ContBB) {
411 EmitBlock(ContBB);
412 auto *Phi = Builder.CreatePHI(Value->getType(), 2);
413 Phi->addIncoming(Null, InitBB);
414 Phi->addIncoming(Value, ResignBB);
415 Value = Phi;
416 }
417
418 return Value;
419}
420
422 Address DestAddress,
423 Address SrcAddress) {
424 assert(Qual);
425 llvm::Value *Value = Builder.CreateLoad(SrcAddress);
426
427 // If we're using address-discrimination, we have to re-sign the value.
428 if (Qual.isAddressDiscriminated()) {
429 CGPointerAuthInfo SrcPtrAuth = EmitPointerAuthInfo(Qual, SrcAddress);
430 CGPointerAuthInfo DestPtrAuth = EmitPointerAuthInfo(Qual, DestAddress);
431 Value = emitPointerAuthResign(Value, T, SrcPtrAuth, DestPtrAuth,
432 /*IsKnownNonNull=*/false);
433 }
434
435 Builder.CreateStore(Value, DestAddress);
436}
437
438llvm::Constant *
440 llvm::Constant *StorageAddress,
441 llvm::ConstantInt *OtherDiscriminator) {
442 llvm::Constant *AddressDiscriminator;
443 if (StorageAddress) {
444 assert(StorageAddress->getType() == DefaultPtrTy);
445 AddressDiscriminator = StorageAddress;
446 } else {
447 AddressDiscriminator = llvm::Constant::getNullValue(DefaultPtrTy);
448 }
449
450 llvm::ConstantInt *IntegerDiscriminator;
451 if (OtherDiscriminator) {
452 assert(OtherDiscriminator->getType() == Int64Ty);
453 IntegerDiscriminator = OtherDiscriminator;
454 } else {
455 IntegerDiscriminator = llvm::ConstantInt::get(Int64Ty, 0);
456 }
457
458 return llvm::ConstantPtrAuth::get(
459 Pointer, llvm::ConstantInt::get(Int32Ty, Key), IntegerDiscriminator,
460 AddressDiscriminator,
461 /*DeactivationSymbol=*/llvm::Constant::getNullValue(DefaultPtrTy));
462}
463
464/// Does a given PointerAuthScheme require us to sign a value
466 auto AuthenticationMode = Schema.getAuthenticationMode();
467 return AuthenticationMode == PointerAuthenticationMode::SignAndStrip ||
468 AuthenticationMode == PointerAuthenticationMode::SignAndAuth;
469}
470
471/// Sign a constant pointer using the given scheme, producing a constant
472/// with the same IR type.
474 llvm::Constant *Pointer, const PointerAuthSchema &Schema,
475 llvm::Constant *StorageAddress, GlobalDecl SchemaDecl,
476 QualType SchemaType) {
477 assert(shouldSignPointer(Schema));
478 llvm::ConstantInt *OtherDiscriminator =
479 getPointerAuthOtherDiscriminator(Schema, SchemaDecl, SchemaType);
480
481 return getConstantSignedPointer(Pointer, Schema.getKey(), StorageAddress,
482 OtherDiscriminator);
483}
484
485llvm::Constant *
487 unsigned Key, llvm::Constant *StorageAddress,
488 llvm::ConstantInt *OtherDiscriminator) {
489 return CGM.getConstantSignedPointer(Pointer, Key, StorageAddress,
490 OtherDiscriminator);
491}
492
493/// If applicable, sign a given constant function pointer with the ABI rules for
494/// functionType.
495llvm::Constant *CodeGenModule::getFunctionPointer(llvm::Constant *Pointer,
497 assert(FunctionType->isFunctionType() ||
500
501 if (auto PointerAuth = getFunctionPointerAuthInfo(FunctionType))
503 Pointer, PointerAuth.getKey(), /*StorageAddress=*/nullptr,
504 cast_or_null<llvm::ConstantInt>(PointerAuth.getDiscriminator()));
505
506 return Pointer;
507}
508
510 llvm::Type *Ty) {
511 const auto *FD = cast<FunctionDecl>(GD.getDecl());
512 QualType FuncType = FD->getType();
513
514 // Annoyingly, K&R functions have prototypes in the clang AST, but
515 // expressions referring to them are unprototyped.
516 if (!FD->hasPrototype())
517 if (const auto *Proto = FuncType->getAs<FunctionProtoType>())
518 FuncType = Context.getFunctionNoProtoType(Proto->getReturnType(),
519 Proto->getExtInfo());
520
521 return getFunctionPointer(getRawFunctionPointer(GD, Ty), FuncType);
522}
523
525 assert(FT->getAs<MemberPointerType>() && "MemberPointerType expected");
527 if (!Schema)
528 return CGPointerAuthInfo();
529
530 assert(!Schema.isAddressDiscriminated() &&
531 "function pointers cannot use address-specific discrimination");
532
533 llvm::ConstantInt *Discriminator =
535 return CGPointerAuthInfo(Schema.getKey(), Schema.getAuthenticationMode(),
536 /* IsIsaPointer */ false,
537 /* AuthenticatesNullValues */ false, Discriminator);
538}
539
540llvm::Constant *CodeGenModule::getMemberFunctionPointer(llvm::Constant *Pointer,
541 QualType FT) {
544 Pointer, PointerAuth.getKey(), nullptr,
545 cast_or_null<llvm::ConstantInt>(PointerAuth.getDiscriminator()));
546
547 if (const auto *MFT = dyn_cast<MemberPointerType>(FT.getTypePtr())) {
548 if (MFT->hasPointeeToCFIUncheckedCalleeFunctionType())
549 Pointer = llvm::NoCFIValue::get(cast<llvm::GlobalValue>(Pointer));
550 }
551
552 return Pointer;
553}
554
556 llvm::Type *Ty) {
557 QualType FT = FD->getType();
558 FT = getContext().getMemberPointerType(FT, /*Qualifier=*/std::nullopt,
559 cast<CXXMethodDecl>(FD)->getParent());
561}
562
563std::optional<PointerAuthQualifier>
564CodeGenModule::computeVTPointerAuthentication(const CXXRecordDecl *ThisClass) {
565 auto DefaultAuthentication = getCodeGenOpts().PointerAuth.CXXVTablePointers;
566 if (!DefaultAuthentication)
567 return std::nullopt;
568 const CXXRecordDecl *PrimaryBase =
569 Context.baseForVTableAuthentication(ThisClass);
570
571 unsigned Key = DefaultAuthentication.getKey();
572 bool AddressDiscriminated = DefaultAuthentication.isAddressDiscriminated();
573 auto DefaultDiscrimination = DefaultAuthentication.getOtherDiscrimination();
574 unsigned TypeBasedDiscriminator =
575 Context.getPointerAuthVTablePointerDiscriminator(PrimaryBase);
576 unsigned Discriminator;
577 if (DefaultDiscrimination == PointerAuthSchema::Discrimination::Type) {
578 Discriminator = TypeBasedDiscriminator;
579 } else if (DefaultDiscrimination ==
581 Discriminator = DefaultAuthentication.getConstantDiscrimination();
582 } else {
583 assert(DefaultDiscrimination == PointerAuthSchema::Discrimination::None);
584 Discriminator = 0;
585 }
586 if (auto ExplicitAuthentication =
587 PrimaryBase->getAttr<VTablePointerAuthenticationAttr>()) {
588 auto ExplicitAddressDiscrimination =
589 ExplicitAuthentication->getAddressDiscrimination();
590 auto ExplicitDiscriminator =
591 ExplicitAuthentication->getExtraDiscrimination();
592
593 unsigned ExplicitKey = ExplicitAuthentication->getKey();
594 if (ExplicitKey == VTablePointerAuthenticationAttr::NoKey)
595 return std::nullopt;
596
597 if (ExplicitKey != VTablePointerAuthenticationAttr::DefaultKey) {
598 if (ExplicitKey == VTablePointerAuthenticationAttr::ProcessIndependent)
600 else {
601 assert(ExplicitKey ==
602 VTablePointerAuthenticationAttr::ProcessDependent);
604 }
605 }
606
607 if (ExplicitAddressDiscrimination !=
608 VTablePointerAuthenticationAttr::DefaultAddressDiscrimination)
609 AddressDiscriminated =
610 ExplicitAddressDiscrimination ==
611 VTablePointerAuthenticationAttr::AddressDiscrimination;
612
613 if (ExplicitDiscriminator ==
614 VTablePointerAuthenticationAttr::TypeDiscrimination)
615 Discriminator = TypeBasedDiscriminator;
616 else if (ExplicitDiscriminator ==
617 VTablePointerAuthenticationAttr::CustomDiscrimination)
618 Discriminator = ExplicitAuthentication->getCustomDiscriminationValue();
619 else if (ExplicitDiscriminator ==
620 VTablePointerAuthenticationAttr::NoExtraDiscrimination)
621 Discriminator = 0;
622 }
623 return PointerAuthQualifier::Create(Key, AddressDiscriminated, Discriminator,
625 /* IsIsaPointer */ false,
626 /* AuthenticatesNullValues */ false);
627}
628
629std::optional<PointerAuthQualifier>
631 if (!Record->getDefinition() || !Record->isPolymorphic())
632 return std::nullopt;
633
634 auto Existing = VTablePtrAuthInfos.find(Record);
635 std::optional<PointerAuthQualifier> Authentication;
636 if (Existing != VTablePtrAuthInfos.end()) {
637 Authentication = Existing->getSecond();
638 } else {
639 Authentication = computeVTPointerAuthentication(Record);
640 VTablePtrAuthInfos.insert(std::make_pair(Record, Authentication));
641 }
642 return Authentication;
643}
644
645std::optional<CGPointerAuthInfo>
647 const CXXRecordDecl *Record,
648 llvm::Value *StorageAddress) {
649 auto Authentication = getVTablePointerAuthentication(Record);
650 if (!Authentication)
651 return std::nullopt;
652
653 llvm::Value *Discriminator = nullptr;
654 if (auto ExtraDiscriminator = Authentication->getExtraDiscriminator())
655 Discriminator = llvm::ConstantInt::get(IntPtrTy, ExtraDiscriminator);
656
657 if (Authentication->isAddressDiscriminated()) {
658 assert(StorageAddress &&
659 "address not provided for address-discriminated schema");
660 if (Discriminator)
661 Discriminator =
662 CGF->EmitPointerAuthBlendDiscriminator(StorageAddress, Discriminator);
663 else
664 Discriminator = CGF->Builder.CreatePtrToInt(StorageAddress, IntPtrTy);
665 }
666
667 return CGPointerAuthInfo(Authentication->getKey(),
669 /* IsIsaPointer */ false,
670 /* AuthenticatesNullValues */ false, Discriminator);
671}
672
673llvm::Value *CodeGenFunction::authPointerToPointerCast(llvm::Value *ResultPtr,
674 QualType SourceType,
675 QualType DestType) {
676 CGPointerAuthInfo CurAuthInfo, NewAuthInfo;
677 if (SourceType->isSignableType(getContext()))
678 CurAuthInfo = getPointerAuthInfoForType(CGM, SourceType);
679
680 if (DestType->isSignableType(getContext()))
681 NewAuthInfo = getPointerAuthInfoForType(CGM, DestType);
682
683 if (!CurAuthInfo && !NewAuthInfo)
684 return ResultPtr;
685
686 // If only one side of the cast is a function pointer, then we still need to
687 // resign to handle casts to/from opaque pointers.
688 if (!CurAuthInfo && DestType->isFunctionPointerType())
689 CurAuthInfo = CGM.getFunctionPointerAuthInfo(SourceType);
690
691 if (!NewAuthInfo && SourceType->isFunctionPointerType())
692 NewAuthInfo = CGM.getFunctionPointerAuthInfo(DestType);
693
694 return emitPointerAuthResign(ResultPtr, DestType, CurAuthInfo, NewAuthInfo,
695 /*IsKnownNonNull=*/false);
696}
697
699 QualType SourceType,
700 QualType DestType) {
701 CGPointerAuthInfo CurAuthInfo, NewAuthInfo;
702 if (SourceType->isSignableType(getContext()))
703 CurAuthInfo = getPointerAuthInfoForType(CGM, SourceType);
704
705 if (DestType->isSignableType(getContext()))
706 NewAuthInfo = getPointerAuthInfoForType(CGM, DestType);
707
708 if (!CurAuthInfo && !NewAuthInfo)
709 return Ptr;
710
711 if (!CurAuthInfo && DestType->isFunctionPointerType()) {
712 // When casting a non-signed pointer to a function pointer, just set the
713 // auth info on Ptr to the assumed schema. The pointer will be resigned to
714 // the effective type when used.
715 Ptr.setPointerAuthInfo(CGM.getFunctionPointerAuthInfo(SourceType));
716 return Ptr;
717 }
718
719 if (!NewAuthInfo && SourceType->isFunctionPointerType()) {
720 NewAuthInfo = CGM.getFunctionPointerAuthInfo(DestType);
721 Ptr = Ptr.getResignedAddress(NewAuthInfo, *this);
723 return Ptr;
724 }
725
726 return Ptr;
727}
728
730 QualType PointeeTy) {
731 CGPointerAuthInfo Info =
732 PointeeTy.isNull() ? CGPointerAuthInfo()
733 : CGM.getPointerAuthInfoForPointeeType(PointeeTy);
734 return Addr.getResignedAddress(Info, *this);
735}
736
738 CodeGenFunction &CGF) const {
739 assert(isValid() && "pointer isn't valid");
741 llvm::Value *Val;
742
743 // Nothing to do if neither the current or the new ptrauth info needs signing.
744 if (!CurInfo.isSigned() && !NewInfo.isSigned())
747
748 assert(ElementType && "Effective type has to be set");
749 assert(!Offset && "unexpected non-null offset");
750
751 // If the current and the new ptrauth infos are the same and the offset is
752 // null, just cast the base pointer to the effective type.
753 if (CurInfo == NewInfo && !hasOffset())
754 Val = getBasePointer();
755 else
756 Val = CGF.emitPointerAuthResign(getBasePointer(), QualType(), CurInfo,
757 NewInfo, isKnownNonNull());
758
759 return Address(Val, getElementType(), getAlignment(), NewInfo,
760 /*Offset=*/nullptr, isKnownNonNull());
761}
762
763llvm::Value *Address::emitRawPointerSlow(CodeGenFunction &CGF) const {
764 return CGF.getAsNaturalPointerTo(*this, QualType());
765}
766
767llvm::Value *LValue::getPointer(CodeGenFunction &CGF) const {
768 assert(isSimple());
769 return emitResignedPointer(getType(), CGF);
770}
771
773 CodeGenFunction &CGF) const {
774 assert(isSimple());
775 return CGF.getAsNaturalAddressOf(Addr, PointeeTy).getBasePointer();
776}
777
778llvm::Value *LValue::emitRawPointer(CodeGenFunction &CGF) const {
779 assert(isSimple());
780 return Addr.isValid() ? Addr.emitRawPointer(CGF) : nullptr;
781}
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
void setPointerAuthInfo(const CGPointerAuthInfo &Info)
Definition Address.h:221
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:1672
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:1934
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:640
llvm::Value * EmitPointerAuthAuth(const CGPointerAuthInfo &Info, llvm::Value *Pointer)
This class organizes the cross-function state that is used while generating LLVM code.
llvm::Constant * getRawFunctionPointer(GlobalDecl GD, llvm::Type *Ty=nullptr)
Return a function pointer for a reference to the given function.
Definition CGExpr.cpp:3449
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)
std::optional< PointerAuthQualifier > getVTablePointerAuthentication(const CXXRecordDecl *thisClass)
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)
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:573
This represents one expression.
Definition Expr.h:112
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3086
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:277
QualType getType() const
Definition Expr.h:144
Represents a function declaration or definition.
Definition Decl.h:2015
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5357
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4553
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
const Decl * getDecl() const
Definition GlobalDecl.h:106
virtual void mangleCXXName(GlobalDecl GD, raw_ostream &)=0
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3703
Pointer-authentication qualifiers.
Definition TypeBase.h:152
static PointerAuthQualifier Create(unsigned Key, bool IsAddressDiscriminated, unsigned ExtraDiscriminator, PointerAuthenticationMode AuthenticationMode, bool IsIsaPointer, bool AuthenticatesNullValues)
Definition TypeBase.h:239
bool authenticatesNullValues() const
Definition TypeBase.h:285
bool isAddressDiscriminated() const
Definition TypeBase.h:265
unsigned getExtraDiscriminator() const
Definition TypeBase.h:270
PointerAuthenticationMode getAuthenticationMode() const
Definition TypeBase.h:275
unsigned getKey() const
Definition TypeBase.h:258
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:3378
QualType getPointeeType() const
Definition TypeBase.h:3388
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8431
Encodes a location in the source.
bool isBlockPointerType() const
Definition TypeBase.h:8688
bool isFunctionReferenceType() const
Definition TypeBase.h:8742
bool isSignableType(const ASTContext &Ctx) const
Definition TypeBase.h:8680
bool isFunctionPointerType() const
Definition TypeBase.h:8735
bool isFunctionType() const
Definition TypeBase.h:8664
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9261
QualType getType() const
Definition Decl.h:723
QualType getType() const
Definition Value.cpp:237
@ 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.
The JSON file list parser is used to communicate input to InstallAPI.
@ Result
The result type of a method or function.
Definition TypeBase.h:905
U cast(CodeGen::Address addr)
Definition Address.h:327
static constexpr llvm::StringLiteral FunctionLabelPrefix
Definition Mangle.h:323
PointerAuthSchema CXXVTablePointers
The ABI for C++ virtual table pointers (the pointer to the table itself) as installed in an actual cl...
PointerAuthSchema FunctionPointers
The ABI for C function pointers.
PointerAuthSchema CXXMemberFunctionPointers
The ABI for C++ member function pointers.