-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathGenPointerAuth.cpp
775 lines (675 loc) · 29.6 KB
/
GenPointerAuth.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
//===--- GenPointerAuth.cpp - IRGen for pointer authentication ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements general support for pointer authentication in Swift.
//
//===----------------------------------------------------------------------===//
#include "GenPointerAuth.h"
#include "Callee.h"
#include "ConstantBuilder.h"
#include "GenType.h"
#include "IRGenFunction.h"
#include "IRGenMangler.h"
#include "IRGenModule.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/Basic/Assertions.h"
#include "swift/SIL/TypeLowering.h"
#include "clang/CodeGen/CodeGenABITypes.h"
#include "llvm/ADT/APInt.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
using namespace irgen;
/**************************** INTRINSIC OPERATIONS ****************************/
/// Return the key and discriminator value for the given auth info,
/// as demanded by the ptrauth intrinsics.
static std::pair<llvm::Constant*, llvm::Value*>
getPointerAuthPair(IRGenFunction &IGF, const PointerAuthInfo &authInfo) {
auto key = llvm::ConstantInt::get(IGF.IGM.Int32Ty, authInfo.getKey());
llvm::Value *discriminator = authInfo.getDiscriminator();
if (discriminator->getType()->isPointerTy()) {
discriminator = IGF.Builder.CreatePtrToInt(discriminator, IGF.IGM.Int64Ty);
}
return { key, discriminator };
}
llvm::Value *irgen::emitPointerAuthBlend(IRGenFunction &IGF,
llvm::Value *address,
llvm::Value *other) {
address = IGF.Builder.CreatePtrToInt(address, IGF.IGM.Int64Ty);
return IGF.Builder.CreateIntrinsicCall(llvm::Intrinsic::ptrauth_blend,
{address, other});
}
llvm::Value *irgen::emitPointerAuthStrip(IRGenFunction &IGF,
llvm::Value *fnPtr,
unsigned Key) {
auto fnVal = IGF.Builder.CreatePtrToInt(fnPtr, IGF.IGM.Int64Ty);
auto keyArg = llvm::ConstantInt::get(IGF.IGM.Int32Ty, Key);
auto strippedPtr = IGF.Builder.CreateIntrinsicCall(
llvm::Intrinsic::ptrauth_strip, {fnVal, keyArg});
return IGF.Builder.CreateIntToPtr(strippedPtr, fnPtr->getType());
}
FunctionPointer irgen::emitPointerAuthResign(IRGenFunction &IGF,
const FunctionPointer &fn,
const PointerAuthInfo &newAuthInfo) {
llvm::Value *fnPtr = emitPointerAuthResign(IGF, fn.getRawPointer(),
fn.getAuthInfo(), newAuthInfo);
return FunctionPointer::createSigned(fn.getKind(), fnPtr, newAuthInfo,
fn.getSignature());
}
llvm::Value *irgen::emitPointerAuthResign(IRGenFunction &IGF,
llvm::Value *fnPtr,
const PointerAuthInfo &oldAuthInfo,
const PointerAuthInfo &newAuthInfo) {
// If the signatures match, there's nothing to do.
if (oldAuthInfo == newAuthInfo)
return fnPtr;
// If the pointer is not currently signed, sign it.
if (!oldAuthInfo.isSigned()) {
return emitPointerAuthSign(IGF, fnPtr, newAuthInfo);
}
// If the pointer is not supposed to be signed, auth it.
if (!newAuthInfo.isSigned()) {
return emitPointerAuthAuth(IGF, fnPtr, oldAuthInfo);
}
// Otherwise, auth and resign it.
auto origTy = fnPtr->getType();
fnPtr = IGF.Builder.CreatePtrToInt(fnPtr, IGF.IGM.Int64Ty);
auto oldPair = getPointerAuthPair(IGF, oldAuthInfo);
auto newPair = getPointerAuthPair(IGF, newAuthInfo);
llvm::Value *args[] = {
fnPtr, oldPair.first, oldPair.second, newPair.first, newPair.second
};
fnPtr =
IGF.Builder.CreateIntrinsicCall(llvm::Intrinsic::ptrauth_resign, args);
return IGF.Builder.CreateIntToPtr(fnPtr, origTy);
}
llvm::Value *irgen::emitPointerAuthAuth(IRGenFunction &IGF, llvm::Value *fnPtr,
const PointerAuthInfo &oldAuthInfo) {
auto origTy = fnPtr->getType();
fnPtr = IGF.Builder.CreatePtrToInt(fnPtr, IGF.IGM.Int64Ty);
auto oldPair = getPointerAuthPair(IGF, oldAuthInfo);
llvm::Value *args[] = {
fnPtr, oldPair.first, oldPair.second
};
fnPtr = IGF.Builder.CreateIntrinsicCall(llvm::Intrinsic::ptrauth_auth, args);
return IGF.Builder.CreateIntToPtr(fnPtr, origTy);
}
llvm::Value *irgen::emitPointerAuthSign(IRGenFunction &IGF, llvm::Value *fnPtr,
const PointerAuthInfo &newAuthInfo) {
if (!newAuthInfo.isSigned())
return fnPtr;
// Special-case constants.
if (auto constantFnPtr = dyn_cast<llvm::Constant>(fnPtr)) {
if (auto constantDiscriminator =
dyn_cast<llvm::Constant>(newAuthInfo.getDiscriminator())) {
llvm::Constant *address = nullptr;
llvm::ConstantInt *other = nullptr;
if (constantDiscriminator->getType()->isPointerTy()) {
address = constantDiscriminator;
} else if (auto otherDiscriminator =
dyn_cast<llvm::ConstantInt>(constantDiscriminator)) {
other = otherDiscriminator;
}
return IGF.IGM.getConstantSignedPointer(constantFnPtr,
newAuthInfo.getKey(),
address, other);
}
}
auto origTy = fnPtr->getType();
fnPtr = IGF.Builder.CreatePtrToInt(fnPtr, IGF.IGM.Int64Ty);
auto newPair = getPointerAuthPair(IGF, newAuthInfo);
llvm::Value *args[] = {
fnPtr, newPair.first, newPair.second
};
fnPtr = IGF.Builder.CreateIntrinsicCall(llvm::Intrinsic::ptrauth_sign, args);
return IGF.Builder.CreateIntToPtr(fnPtr, origTy);
}
/******************************* DISCRIMINATORS *******************************/
struct IRGenModule::PointerAuthCachesType {
llvm::DenseMap<SILDeclRef, llvm::ConstantInt*> Decls;
llvm::DenseMap<CanType, llvm::ConstantInt*> Types;
llvm::DenseMap<CanType, llvm::ConstantInt*> YieldTypes;
llvm::DenseMap<AssociatedType, llvm::ConstantInt*> AssociatedTypes;
llvm::DenseMap<AssociatedConformance, llvm::ConstantInt*> AssociatedConformances;
};
IRGenModule::PointerAuthCachesType &IRGenModule::getPointerAuthCaches() {
if (!PointerAuthCaches)
PointerAuthCaches = new PointerAuthCachesType();
return *PointerAuthCaches;
}
void IRGenModule::destroyPointerAuthCaches() {
delete PointerAuthCaches;
}
static const PointerAuthSchema &getFunctionPointerSchema(IRGenModule &IGM,
CanSILFunctionType fnType) {
auto &options = IGM.getOptions().PointerAuth;
switch (fnType->getRepresentation()) {
case SILFunctionTypeRepresentation::CXXMethod:
case SILFunctionTypeRepresentation::CFunctionPointer:
return options.FunctionPointers;
case SILFunctionTypeRepresentation::Thin:
case SILFunctionTypeRepresentation::Thick:
case SILFunctionTypeRepresentation::Method:
case SILFunctionTypeRepresentation::WitnessMethod:
case SILFunctionTypeRepresentation::Closure:
case SILFunctionTypeRepresentation::KeyPathAccessorGetter:
case SILFunctionTypeRepresentation::KeyPathAccessorSetter:
case SILFunctionTypeRepresentation::KeyPathAccessorEquals:
case SILFunctionTypeRepresentation::KeyPathAccessorHash:
if (fnType->isAsync()) {
return options.AsyncSwiftFunctionPointers;
} else if (fnType->isCalleeAllocatedCoroutine()) {
return options.CoroSwiftFunctionPointers;
}
return options.SwiftFunctionPointers;
case SILFunctionTypeRepresentation::ObjCMethod:
case SILFunctionTypeRepresentation::Block:
llvm_unreachable("not just a function pointer");
}
llvm_unreachable("bad representation");
}
PointerAuthInfo PointerAuthInfo::forFunctionPointer(IRGenModule &IGM,
CanSILFunctionType fnType) {
auto &schema = getFunctionPointerSchema(IGM, fnType);
// If the target doesn't sign function pointers, we're done.
if (!schema) return PointerAuthInfo();
assert(!schema.isAddressDiscriminated() &&
"function pointer cannot be address-discriminated");
auto discriminator = getOtherDiscriminator(IGM, schema, fnType);
return PointerAuthInfo(schema.getKey(), discriminator);
}
PointerAuthInfo PointerAuthInfo::emit(IRGenFunction &IGF,
const PointerAuthSchema &schema,
llvm::Value *storageAddress,
const PointerAuthEntity &entity) {
if (!schema) return PointerAuthInfo();
unsigned key = schema.getKey();
// Produce the 'other' discriminator.
auto otherDiscriminator = getOtherDiscriminator(IGF.IGM, schema, entity);
llvm::Value *discriminator = otherDiscriminator;
// Factor in the address.
if (schema.isAddressDiscriminated()) {
assert(storageAddress &&
"no storage address for address-discriminated schema");
if (!otherDiscriminator->isZero()) {
discriminator = emitPointerAuthBlend(IGF, storageAddress, discriminator);
} else {
discriminator =
IGF.Builder.CreatePtrToInt(storageAddress, IGF.IGM.Int64Ty);
}
}
return PointerAuthInfo(key, discriminator);
}
PointerAuthInfo
PointerAuthInfo::emit(IRGenFunction &IGF,
clang::PointerAuthQualifier pointerAuthQual,
llvm::Value *storageAddress) {
unsigned key = pointerAuthQual.getKey();
// Produce the 'other' discriminator.
auto otherDiscriminator = pointerAuthQual.getExtraDiscriminator();
llvm::Value *discriminator =
llvm::ConstantInt::get(IGF.IGM.Int64Ty, otherDiscriminator);
// Factor in the address.
if (pointerAuthQual.isAddressDiscriminated()) {
assert(storageAddress &&
"no storage address for address-discriminated schema");
if (otherDiscriminator != 0) {
discriminator = emitPointerAuthBlend(IGF, storageAddress, discriminator);
} else {
discriminator =
IGF.Builder.CreatePtrToInt(storageAddress, IGF.IGM.Int64Ty);
}
}
return PointerAuthInfo(key, discriminator);
}
PointerAuthInfo PointerAuthInfo::emit(IRGenFunction &IGF,
const PointerAuthSchema &schema,
llvm::Value *storageAddress,
llvm::ConstantInt *otherDiscriminator) {
if (!schema)
return PointerAuthInfo();
unsigned key = schema.getKey();
llvm::Value *discriminator = otherDiscriminator;
// Factor in the address.
if (schema.isAddressDiscriminated()) {
assert(storageAddress &&
"no storage address for address-discriminated schema");
if (!otherDiscriminator->isZero()) {
discriminator = emitPointerAuthBlend(IGF, storageAddress, discriminator);
} else {
discriminator =
IGF.Builder.CreatePtrToInt(storageAddress, IGF.IGM.Int64Ty);
}
}
return PointerAuthInfo(key, discriminator);
}
llvm::ConstantInt *
PointerAuthInfo::getOtherDiscriminator(IRGenModule &IGM,
const PointerAuthSchema &schema,
const PointerAuthEntity &entity) {
assert(schema);
switch (schema.getOtherDiscrimination()) {
case PointerAuthSchema::Discrimination::None:
return llvm::ConstantInt::get(IGM.Int64Ty, 0);
case PointerAuthSchema::Discrimination::Decl:
return entity.getDeclDiscriminator(IGM);
case PointerAuthSchema::Discrimination::Type:
return entity.getTypeDiscriminator(IGM);
case PointerAuthSchema::Discrimination::Constant:
return llvm::ConstantInt::get(IGM.Int64Ty,
schema.getConstantDiscrimination());
}
llvm_unreachable("bad kind");
}
static llvm::ConstantInt *getDiscriminatorForHash(IRGenModule &IGM,
uint64_t rawHash) {
uint16_t reducedHash = (rawHash % 0xFFFF) + 1;
return llvm::ConstantInt::get(IGM.Int64Ty, reducedHash);
}
static llvm::ConstantInt *getDiscriminatorForString(IRGenModule &IGM,
StringRef string) {
uint64_t rawHash = clang::CodeGen::computeStableStringHash(string);
return getDiscriminatorForHash(IGM, rawHash);
}
static std::string mangle(AssociatedType association) {
return IRGenMangler(association.getAssociation()->getASTContext())
.mangleAssociatedTypeAccessFunctionDiscriminator(association);
}
static std::string mangle(const AssociatedConformance &association) {
return IRGenMangler(association.getAssociatedRequirement()->getASTContext())
.mangleAssociatedTypeWitnessTableAccessFunctionDiscriminator(association);
}
llvm::ConstantInt *
PointerAuthEntity::getDeclDiscriminator(IRGenModule &IGM) const {
switch (StoredKind) {
case Kind::None:
case Kind::CanSILFunctionType:
case Kind::CoroutineYieldTypes:
llvm_unreachable("no declaration for schema using decl discrimination");
case Kind::Special: {
auto getSpecialDiscriminator = [](Special special) -> uint16_t {
switch (special) {
case Special::HeapDestructor:
return SpecialPointerAuthDiscriminators::HeapDestructor;
case Special::TypeDescriptor:
case Special::TypeDescriptorAsArgument:
return SpecialPointerAuthDiscriminators::TypeDescriptor;
case Special::ProtocolConformanceDescriptor:
case Special::ProtocolConformanceDescriptorAsArgument:
return SpecialPointerAuthDiscriminators::ProtocolConformanceDescriptor;
case Special::ProtocolDescriptorAsArgument:
return SpecialPointerAuthDiscriminators::ProtocolDescriptor;
case Special::OpaqueTypeDescriptorAsArgument:
return SpecialPointerAuthDiscriminators::OpaqueTypeDescriptor;
case Special::ContextDescriptorAsArgument:
return SpecialPointerAuthDiscriminators::ContextDescriptor;
case Special::PartialApplyCapture:
return PointerAuthDiscriminator_PartialApplyCapture;
case Special::KeyPathDestroy:
return SpecialPointerAuthDiscriminators::KeyPathDestroy;
case Special::KeyPathCopy:
return SpecialPointerAuthDiscriminators::KeyPathCopy;
case Special::KeyPathEquals:
return SpecialPointerAuthDiscriminators::KeyPathEquals;
case Special::KeyPathHash:
return SpecialPointerAuthDiscriminators::KeyPathHash;
case Special::KeyPathGetter:
return SpecialPointerAuthDiscriminators::KeyPathGetter;
case Special::KeyPathNonmutatingSetter:
return SpecialPointerAuthDiscriminators::KeyPathNonmutatingSetter;
case Special::KeyPathMutatingSetter:
return SpecialPointerAuthDiscriminators::KeyPathMutatingSetter;
case Special::KeyPathGetLayout:
return SpecialPointerAuthDiscriminators::KeyPathGetLayout;
case Special::KeyPathInitializer:
return SpecialPointerAuthDiscriminators::KeyPathInitializer;
case Special::KeyPathMetadataAccessor:
return SpecialPointerAuthDiscriminators::KeyPathMetadataAccessor;
case Special::DynamicReplacementKey:
return SpecialPointerAuthDiscriminators::DynamicReplacementKey;
case Special::TypeLayoutString:
return SpecialPointerAuthDiscriminators::TypeLayoutString;
case Special::BlockCopyHelper:
case Special::BlockDisposeHelper:
llvm_unreachable("no known discriminator for these foreign entities");
}
llvm_unreachable("bad kind");
};
auto specialKind = Storage.get<Special>(StoredKind);
return llvm::ConstantInt::get(IGM.Int64Ty,
getSpecialDiscriminator(specialKind));
}
case Kind::ValueWitness: {
auto getValueWitnessDiscriminator = [](ValueWitness witness) -> uint16_t {
switch (witness) {
#define WANT_ALL_VALUE_WITNESSES
#define DATA_VALUE_WITNESS(LOWER, UPPER, TYPE)
#define FUNCTION_VALUE_WITNESS(LOWER, ID, RET, PARAMS) \
case ValueWitness::ID: return SpecialPointerAuthDiscriminators::ID;
#include "swift/ABI/ValueWitness.def"
case ValueWitness::Size:
case ValueWitness::Flags:
case ValueWitness::Stride:
case ValueWitness::ExtraInhabitantCount:
llvm_unreachable("not a function value witness");
}
llvm_unreachable("bad kind");
};
auto witness = Storage.get<ValueWitness>(StoredKind);
return llvm::ConstantInt::get(IGM.Int64Ty,
getValueWitnessDiscriminator(witness));
}
case Kind::AssociatedType: {
auto association = Storage.get<AssociatedType>(StoredKind);
llvm::ConstantInt *&cache =
IGM.getPointerAuthCaches().AssociatedTypes[association];
if (cache) return cache;
auto mangling = mangle(association);
cache = getDiscriminatorForString(IGM, mangling);
return cache;
}
case Kind::AssociatedConformance: {
auto conformance = Storage.get<AssociatedConformance>(StoredKind);
llvm::ConstantInt *&cache =
IGM.getPointerAuthCaches().AssociatedConformances[conformance];
if (cache) return cache;
auto mangling = mangle(conformance);
cache = getDiscriminatorForString(IGM, mangling);
return cache;
}
case Kind::SILDeclRef: {
auto constant = Storage.get<SILDeclRef>(StoredKind);
llvm::ConstantInt *&cache = IGM.getPointerAuthCaches().Decls[constant];
if (cache) return cache;
// Getting the discriminator for a foreign SILDeclRef just means
// converting it to a foreign declaration and asking Clang IRGen
// for the corresponding discriminator, but that's not completely
// trivial.
assert(!constant.isForeign &&
"discriminator for foreign declaration not supported yet!");
auto mangling = constant.mangle();
cache = getDiscriminatorForString(IGM, mangling);
return cache;
}
case Kind::SILFunction: {
auto fn = Storage.get<SILFunction*>(StoredKind);
return getDiscriminatorForString(IGM, fn->getName());
}
}
llvm_unreachable("bad kind");
}
static void hashStringForFunctionType(IRGenModule &IGM, CanSILFunctionType type,
raw_ostream &Out,
GenericEnvironment *genericEnv);
static void hashStringForType(IRGenModule &IGM, CanType Ty, raw_ostream &Out,
GenericEnvironment *genericEnv) {
if (Ty->isAnyClassReferenceType()) {
// Any class type has to be hashed opaquely.
Out << "-class";
} else if (isa<AnyMetatypeType>(Ty)) {
// Any metatype has to be hashed opaquely.
Out << "-metatype";
} else if (auto UnwrappedTy = Ty->getOptionalObjectType()) {
if (UnwrappedTy->isBridgeableObjectType()) {
// Optional<T> is compatible with T when T is class-based.
hashStringForType(IGM, UnwrappedTy->getCanonicalType(), Out, genericEnv);
} else if (UnwrappedTy->is<MetatypeType>()) {
// Optional<T> is compatible with T when T is a metatype.
hashStringForType(IGM, UnwrappedTy->getCanonicalType(), Out, genericEnv);
} else {
// Optional<T> is direct if and only if T is.
Out << "Optional<";
hashStringForType(IGM, UnwrappedTy->getCanonicalType(), Out, genericEnv);
Out << ">";
}
} else if (auto ETy = dyn_cast<ExistentialType>(Ty)) {
// Look through existential types
hashStringForType(IGM, ETy->getConstraintType()->getCanonicalType(),
Out, genericEnv);
} else if (auto GTy = dyn_cast<AnyGenericType>(Ty)) {
// For generic and non-generic value types, use the mangled declaration
// name, and ignore all generic arguments.
NominalTypeDecl *nominal = cast<NominalTypeDecl>(GTy->getDecl());
Out << Mangle::ASTMangler(IGM.Context).mangleNominalType(nominal);
} else if (auto FTy = dyn_cast<SILFunctionType>(Ty)) {
Out << "(";
hashStringForFunctionType(IGM, FTy, Out, genericEnv);
Out << ")";
} else {
Out << "-";
}
}
template <class T>
static void hashStringForList(IRGenModule &IGM, const ArrayRef<T> &list,
raw_ostream &Out, GenericEnvironment *genericEnv,
const SILFunctionType *fnType) {
for (auto paramOrRetVal : list) {
if (paramOrRetVal.isFormalIndirect()) {
// Indirect params and return values have to be opaque.
Out << "-indirect";
} else {
CanType Ty = paramOrRetVal.getArgumentType(
IGM.getSILModule(), fnType, IGM.getMaximalTypeExpansionContext());
if (Ty->hasTypeParameter())
Ty = genericEnv->mapTypeIntoContext(Ty)->getCanonicalType();
hashStringForType(IGM, Ty, Out, genericEnv);
}
Out << ":";
}
}
static void hashStringForList(IRGenModule &IGM,
const ArrayRef<SILResultInfo> &list,
raw_ostream &Out, GenericEnvironment *genericEnv,
const SILFunctionType *fnType) {
for (auto paramOrRetVal : list) {
if (paramOrRetVal.isFormalIndirect()) {
// Indirect params and return values have to be opaque.
Out << "-indirect";
} else {
CanType Ty = paramOrRetVal.getReturnValueType(
IGM.getSILModule(), fnType, IGM.getMaximalTypeExpansionContext());
if (Ty->hasTypeParameter())
Ty = genericEnv->mapTypeIntoContext(Ty)->getCanonicalType();
hashStringForType(IGM, Ty, Out, genericEnv);
}
Out << ":";
}
}
static void hashStringForFunctionType(IRGenModule &IGM, CanSILFunctionType type,
raw_ostream &Out,
GenericEnvironment *genericEnv) {
Out << (type->isCoroutine() ? "coroutine" : "function") << ":";
Out << type->getNumParameters() << ":";
hashStringForList(IGM, type->getParameters(), Out, genericEnv, type);
Out << type->getNumResults() << ":";
hashStringForList(IGM, type->getResults(), Out, genericEnv, type);
if (type->isCoroutine()) {
Out << type->getNumYields() << ":";
hashStringForList(IGM, type->getYields(), Out, genericEnv, type);
}
}
static uint64_t getTypeHash(IRGenModule &IGM, CanSILFunctionType type) {
// The hash we need to do here ignores:
// - thickness, so that we can promote thin-to-thick without rehashing;
// - error results, so that we can promote nonthrowing-to-throwing
// without rehashing;
// - isolation, so that global actor annotations can change in the SDK
// without breaking compatibility and so that we can erase it to
// nonisolated without rehashing;
// - types of indirect arguments/retvals, so they can be substituted freely;
// - types of class arguments/retvals
// - types of metatype arguments/retvals
// See isABICompatibleWith and areABICompatibleParamsOrReturns in
// SILFunctionType.cpp.
SmallString<32> Buffer;
llvm::raw_svector_ostream Out(Buffer);
auto genericSig = type->getInvocationGenericSignature();
hashStringForFunctionType(
IGM, type, Out,
genericSig.getCanonicalSignature().getGenericEnvironment());
return clang::CodeGen::computeStableStringHash(Out.str());
}
static uint64_t getYieldTypesHash(IRGenModule &IGM, CanSILFunctionType type) {
SmallString<32> buffer;
llvm::raw_svector_ostream out(buffer);
auto genericSig = type->getInvocationGenericSignature();
auto *genericEnv = genericSig.getCanonicalSignature().getGenericEnvironment();
out << [&]() -> StringRef {
switch (type->getCoroutineKind()) {
case SILCoroutineKind::YieldMany: return "yield_many:";
case SILCoroutineKind::YieldOnce: return "yield_once:";
case SILCoroutineKind::YieldOnce2:
return "yield_once_2:";
case SILCoroutineKind::None: llvm_unreachable("not a coroutine");
}
llvm_unreachable("bad coroutine kind");
}();
out << type->getNumYields() << ":";
for (auto yield: type->getYields()) {
// We can't mangle types on inout and indirect yields because they're
// abstractable.
if (yield.isIndirectInOut()) {
out << "inout";
} else if (yield.isFormalIndirect()) {
out << "indirect";
} else {
CanType Ty = yield.getArgumentType(IGM.getSILModule(), type,
IGM.getMaximalTypeExpansionContext());
if (Ty->hasTypeParameter())
Ty = genericEnv->mapTypeIntoContext(Ty)->getCanonicalType();
hashStringForType(IGM, Ty, out, genericEnv);
}
out << ":";
}
return clang::CodeGen::computeStableStringHash(out.str());
}
llvm::ConstantInt *
PointerAuthEntity::getTypeDiscriminator(IRGenModule &IGM) const {
auto getTypeDiscriminator = [&](CanSILFunctionType fnType) {
switch (fnType->getRepresentation()) {
// Swift function types are type-discriminated.
case SILFunctionTypeRepresentation::Thick:
case SILFunctionTypeRepresentation::Thin:
case SILFunctionTypeRepresentation::Method:
case SILFunctionTypeRepresentation::WitnessMethod:
case SILFunctionTypeRepresentation::Closure:
case SILFunctionTypeRepresentation::KeyPathAccessorGetter:
case SILFunctionTypeRepresentation::KeyPathAccessorSetter:
case SILFunctionTypeRepresentation::KeyPathAccessorEquals:
case SILFunctionTypeRepresentation::KeyPathAccessorHash: {
llvm::ConstantInt *&cache = IGM.getPointerAuthCaches().Types[fnType];
if (cache) return cache;
auto hash = getTypeHash(IGM, fnType);
cache = getDiscriminatorForHash(IGM, hash);
return cache;
}
// C function pointers are undiscriminated.
case SILFunctionTypeRepresentation::CXXMethod:
case SILFunctionTypeRepresentation::CFunctionPointer:
return llvm::ConstantInt::get(IGM.Int64Ty, 0);
case SILFunctionTypeRepresentation::ObjCMethod:
case SILFunctionTypeRepresentation::Block: {
llvm_unreachable("not type discriminated");
}
}
llvm_unreachable("invalid representation");
};
auto getCoroutineYieldTypesDiscriminator = [&](CanSILFunctionType fnType) {
llvm::ConstantInt *&cache = IGM.getPointerAuthCaches().Types[fnType];
if (cache) return cache;
auto hash = getYieldTypesHash(IGM, fnType);
cache = getDiscriminatorForHash(IGM, hash);
return cache;
};
switch (StoredKind) {
case Kind::None:
case Kind::Special:
case Kind::ValueWitness:
case Kind::AssociatedType:
case Kind::AssociatedConformance:
case Kind::SILFunction:
llvm_unreachable("no type for schema using type discrimination");
case Kind::CoroutineYieldTypes: {
auto fnType = Storage.get<CanSILFunctionType>(StoredKind);
return getCoroutineYieldTypesDiscriminator(fnType);
}
case Kind::CanSILFunctionType: {
auto fnType = Storage.get<CanSILFunctionType>(StoredKind);
return getTypeDiscriminator(fnType);
}
case Kind::SILDeclRef: {
SILDeclRef decl = Storage.get<SILDeclRef>(StoredKind);
auto fnType = IGM.getSILTypes().getConstantFunctionType(
TypeExpansionContext::minimal(), decl);
return getTypeDiscriminator(fnType);
}
}
llvm_unreachable("bad kind");
}
llvm::Constant *
IRGenModule::getConstantSignedFunctionPointer(llvm::Constant *fn,
CanSILFunctionType fnType) {
if (auto &schema = getFunctionPointerSchema(*this, fnType)) {
return getConstantSignedPointer(fn, schema, fnType, nullptr);
}
return fn;
}
llvm::Constant *
IRGenModule::getConstantSignedCFunctionPointer(llvm::Constant *fn) {
if (auto &schema = getOptions().PointerAuth.FunctionPointers) {
assert(!schema.hasOtherDiscrimination());
return getConstantSignedPointer(fn, schema, PointerAuthEntity(), nullptr);
}
return fn;
}
llvm::Constant *
IRGenModule::getConstantSignedPointer(llvm::Constant *pointer, unsigned key,
llvm::Constant *storageAddress,
llvm::ConstantInt *otherDiscriminator) {
return clang::CodeGen::getConstantSignedPointer(getClangCGM(), pointer, key,
storageAddress,
otherDiscriminator);
}
llvm::Constant *IRGenModule::getConstantSignedPointer(llvm::Constant *pointer,
const PointerAuthSchema &schema,
const PointerAuthEntity &entity,
llvm::Constant *storageAddress) {
// If the schema doesn't sign pointers, do nothing.
if (!schema)
return pointer;
auto otherDiscriminator =
PointerAuthInfo::getOtherDiscriminator(*this, schema, entity);
return getConstantSignedPointer(pointer, schema.getKey(), storageAddress,
otherDiscriminator);
}
void ConstantAggregateBuilderBase::addSignedPointer(llvm::Constant *pointer,
const PointerAuthSchema &schema,
const PointerAuthEntity &entity) {
// If the schema doesn't sign pointers, do nothing.
if (!schema)
return add(pointer);
auto otherDiscriminator =
PointerAuthInfo::getOtherDiscriminator(IGM(), schema, entity);
addSignedPointer(pointer, schema.getKey(), schema.isAddressDiscriminated(),
otherDiscriminator);
}
void ConstantAggregateBuilderBase::addSignedPointer(llvm::Constant *pointer,
const PointerAuthSchema &schema,
uint16_t otherDiscriminator) {
// If the schema doesn't sign pointers, do nothing.
if (!schema)
return add(pointer);
addSignedPointer(pointer, schema.getKey(), schema.isAddressDiscriminated(),
llvm::ConstantInt::get(IGM().Int64Ty, otherDiscriminator));
}
llvm::ConstantInt* IRGenFunction::getMallocTypeId() {
return getDiscriminatorForString(IGM, CurFn->getName());
}