Skip to content

Commit ecea44f

Browse files
committed
[clang][ptrauth] Add support for querying the ptrauth schema of a type
This adds a number of builtins to query the ptrauth schema of an arbitrary type in a way that can be fed into other ptrauth qualifiers.
1 parent cf9b4d1 commit ecea44f

File tree

17 files changed

+518
-5
lines changed

17 files changed

+518
-5
lines changed

clang/docs/PointerAuthentication.rst

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -499,6 +499,24 @@ type. Implementations are not required to make all bits of the result equally
499499
significant; in particular, some implementations are known to not leave
500500
meaningful data in the low bits.
501501

502+
``__ptrauth type queries``
503+
^^^^^^^^^^^^^^^^^^^^^^^^^^
504+
505+
There are a number of builtins that can be used to query the ptrauth qualifier
506+
parameters of a type, including those configured implicitly. These are:
507+
508+
.. code-block:: c
509+
__builtin_ptrauth_has_authentication(type)
510+
__builtin_ptrauth_schema_key(type)
511+
__builtin_ptrauth_schema_is_address_discriminated(type)
512+
__builtin_ptrauth_schema_extra_discriminator(type)
513+
__builtin_ptrauth_schema_options(type)
514+
515+
All these builtins are compile time constants. The schema queries are only valid
516+
on types that have some form of pointer authentication, including implicit
517+
authentication as is present of function pointers. Each schema query returns a
518+
value of the appropriate type for the relevant parameter to the __ptrauth
519+
qualifier.
502520

503521

504522
Alternative Implementations

clang/include/clang/AST/ASTContext.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1358,6 +1358,11 @@ class ASTContext : public RefCountedBase<ASTContext> {
13581358
/// Return the "other" type-specific discriminator for the given type.
13591359
uint16_t getPointerAuthTypeDiscriminator(QualType T);
13601360

1361+
/// Produces the canonical "options" string for the given PointerAuthQualifier
1362+
/// such that using it explicitly in a __ptrauth qualifier would result in as
1363+
/// identical configuration
1364+
std::string getPointerAuthOptionsString(const PointerAuthQualifier &PAQ);
1365+
13611366
/// Apply Objective-C protocol qualifiers to the given type.
13621367
/// \param allowOnPointerType specifies if we can apply protocol
13631368
/// qualifiers on ObjCObjectPointerType. It can be set to true when
@@ -1696,6 +1701,13 @@ class ASTContext : public RefCountedBase<ASTContext> {
16961701

16971702
QualType adjustStringLiteralBaseType(QualType StrLTy) const;
16981703

1704+
/// Synthesizes a PointerAuthQualifier representing the actual authentication
1705+
/// policy for the given type. This may be either the schema specified
1706+
/// explicitly via the __ptrauth qualified in the source, or the implicit
1707+
/// schema associated with function pointers and similar.
1708+
std::optional<PointerAuthQualifier>
1709+
getExplicitOrImplicitPointerAuth(QualType T);
1710+
16991711
private:
17001712
/// Return a normal function type with a typed argument list.
17011713
QualType getFunctionTypeInternal(QualType ResultTy, ArrayRef<QualType> Args,

clang/include/clang/Basic/DiagnosticSemaKinds.td

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1039,6 +1039,8 @@ def err_ptrauth_address_discrimination_invalid : Error<
10391039
"invalid address discrimination flag '%0'; '__ptrauth' requires '0' or '1'">;
10401040
def err_ptrauth_extra_discriminator_invalid : Error<
10411041
"invalid extra discriminator flag '%0'; '__ptrauth' requires a value between '0' and '%1'">;
1042+
def err_ptrauth_query_type_has_no_pointer_authentication
1043+
: Error<"argument to %0 parameter is not an authenticated value">;
10421044

10431045
/// main()
10441046
// static main() is not an error in C, just in C++.

clang/include/clang/Basic/LangOptions.def

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,7 @@ LANGOPT(PointerAuthInitFiniAddressDiscrimination, 1, 0,
177177
"incorporate address discrimination in authenticated function pointers in init/fini arrays")
178178
LANGOPT(PointerAuthELFGOT, 1, 0, "authenticate pointers from GOT")
179179
LANGOPT(AArch64JumpTableHardening, 1, 0, "use hardened lowering for jump-table dispatch")
180+
LANGOPT(PointerAuthFunctionKey, 16, 0, "authentication key for function pointers")
180181

181182
LANGOPT(DoubleSquareBracketAttributes, 1, 0, "'[[]]' attributes extension for all language standard modes")
182183
LANGOPT(ExperimentalLateParseAttributes, 1, 0, "experimental late parsing of attributes")

clang/include/clang/Basic/LangOptions.h

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,17 @@ enum class PointerAuthenticationMode : unsigned {
6565
SignAndAuth
6666
};
6767

68+
static constexpr llvm::StringLiteral PointerAuthenticationOptionStrip = "strip";
69+
static constexpr llvm::StringLiteral PointerAuthenticationOptionSignAndStrip =
70+
"sign-and-strip";
71+
static constexpr llvm::StringLiteral PointerAuthenticationOptionSignAndAuth =
72+
"sign-and-auth";
73+
static constexpr llvm::StringLiteral PointerAuthenticationOptionIsaPointer =
74+
"isa-pointer";
75+
static constexpr llvm::StringLiteral
76+
PointerAuthenticationOptionAuthenticatesNullValues =
77+
"authenticates-null-values";
78+
6879
/// Bitfields of LangOptions, split out from LangOptions in order to ensure that
6980
/// this large collection of bitfields is a trivial class type.
7081
class LangOptionsBase {

clang/include/clang/Basic/TokenKinds.def

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -605,6 +605,11 @@ KEYWORD(__private_extern__ , KEYALL)
605605
KEYWORD(__module_private__ , KEYALL)
606606

607607
UNARY_EXPR_OR_TYPE_TRAIT(__builtin_ptrauth_type_discriminator, PtrAuthTypeDiscriminator, KEYALL)
608+
UNARY_EXPR_OR_TYPE_TRAIT(__builtin_ptrauth_has_authentication, PtrAuthHasAuthentication, KEYALL)
609+
UNARY_EXPR_OR_TYPE_TRAIT(__builtin_ptrauth_schema_key, PtrAuthSchemaKey, KEYALL)
610+
UNARY_EXPR_OR_TYPE_TRAIT(__builtin_ptrauth_schema_is_address_discriminated, PtrAuthSchemaIsAddressDiscriminated, KEYALL)
611+
UNARY_EXPR_OR_TYPE_TRAIT(__builtin_ptrauth_schema_extra_discriminator, PtrAuthSchemaExtraDiscriminator, KEYALL)
612+
UNARY_EXPR_OR_TYPE_TRAIT(__builtin_ptrauth_schema_options, PtrAuthSchemaOptions, KEYALL)
608613

609614
// Extension that will be enabled for Microsoft, Borland and PS4, but can be
610615
// disabled via '-fno-declspec'.

clang/include/clang/Parse/Parser.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3981,7 +3981,9 @@ class Parser : public CodeCompletionHandler {
39813981
ExprResult ParseArrayTypeTrait();
39823982
ExprResult ParseExpressionTrait();
39833983

3984+
ExprResult ParseBuiltinUnaryExprOrTypeTrait(UnaryExprOrTypeTrait ExprKind);
39843985
ExprResult ParseBuiltinPtrauthTypeDiscriminator();
3986+
ExprResult ParseBuiltinPtrauthQuery(tok::TokenKind Token);
39853987

39863988
//===--------------------------------------------------------------------===//
39873989
// Preprocessor code-completion pass-through

clang/lib/AST/ASTContext.cpp

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@
9696
#include <map>
9797
#include <memory>
9898
#include <optional>
99+
#include <sstream>
99100
#include <string>
100101
#include <tuple>
101102
#include <utility>
@@ -9619,6 +9620,65 @@ ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
96199620
return ObjCProtocolClassDecl;
96209621
}
96219622

9623+
std::optional<PointerAuthQualifier>
9624+
ASTContext::getExplicitOrImplicitPointerAuth(QualType T) {
9625+
auto ExplicitQualifier = T.getPointerAuth();
9626+
if (ExplicitQualifier.isPresent())
9627+
return ExplicitQualifier;
9628+
if (T->isDependentType()) {
9629+
return std::nullopt;
9630+
}
9631+
// FIXME: The more we expand pointer auth support, the more it becomes clear
9632+
// the codegen option's PointerAuth info belongs in LangOpts
9633+
if (!LangOpts.PointerAuthCalls)
9634+
return PointerAuthQualifier();
9635+
if (T->isFunctionPointerType() || T->isFunctionReferenceType())
9636+
T = T->getPointeeType();
9637+
if (!T->isFunctionType())
9638+
return PointerAuthQualifier();
9639+
int ExtraDiscriminator = 0;
9640+
if (LangOpts.PointerAuthFunctionTypeDiscrimination) {
9641+
ExtraDiscriminator = getPointerAuthTypeDiscriminator(T);
9642+
}
9643+
return PointerAuthQualifier::Create(
9644+
LangOpts.PointerAuthFunctionKey, false, ExtraDiscriminator,
9645+
PointerAuthenticationMode::SignAndAuth,
9646+
/*isIsaPointer=*/false, /*authenticatesNullValues=*/false);
9647+
}
9648+
9649+
std::string
9650+
ASTContext::getPointerAuthOptionsString(const PointerAuthQualifier &PAQ) {
9651+
llvm::SmallVector<llvm::StringLiteral, 4> Options;
9652+
switch (PAQ.getAuthenticationMode()) {
9653+
case PointerAuthenticationMode::Strip:
9654+
Options.push_back(PointerAuthenticationOptionStrip);
9655+
break;
9656+
case PointerAuthenticationMode::SignAndStrip:
9657+
Options.push_back(PointerAuthenticationOptionSignAndStrip);
9658+
break;
9659+
case PointerAuthenticationMode::SignAndAuth:
9660+
// Just default to not listing this explicitly
9661+
break;
9662+
default:
9663+
llvm_unreachable("Invalid authentication mode");
9664+
}
9665+
if (PAQ.isIsaPointer())
9666+
Options.push_back(PointerAuthenticationOptionIsaPointer);
9667+
if (PAQ.authenticatesNullValues())
9668+
Options.push_back(PointerAuthenticationOptionAuthenticatesNullValues);
9669+
if (Options.empty())
9670+
return std::string();
9671+
if (Options.size() == 1)
9672+
return Options[0].str();
9673+
std::ostringstream Buffer;
9674+
Buffer << Options[0].str();
9675+
for (unsigned i = 1; i < Options.size(); i++) {
9676+
Buffer << ',';
9677+
Buffer << Options[i].str();
9678+
}
9679+
return Buffer.str();
9680+
}
9681+
96229682
//===----------------------------------------------------------------------===//
96239683
// __builtin_va_list Construction Functions
96249684
//===----------------------------------------------------------------------===//

clang/lib/AST/ExprConstant.cpp

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9561,6 +9561,41 @@ class PointerExprEvaluator
95619561
return true;
95629562
}
95639563

9564+
bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E) {
9565+
// This is the only UETT we evaluate here.
9566+
assert(E->getKind() == UETT_PtrAuthSchemaOptions &&
9567+
"Unknown UnaryExprOrTypeTraitExpr");
9568+
9569+
// Note for review: there are other UETTs down the road
9570+
// that make a switch make sense, but for now this is the only
9571+
// one should this just be an
9572+
// if (E->getKind() != UETT_PtrAuthSchemaOptions)
9573+
// return false;
9574+
ASTContext &Ctx = Info.Ctx;
9575+
switch (E->getKind()) {
9576+
case UETT_PtrAuthSchemaOptions: {
9577+
auto ArgumentType = E->getArgumentType();
9578+
auto Qualifier = Ctx.getExplicitOrImplicitPointerAuth(ArgumentType);
9579+
if (!Qualifier)
9580+
return false;
9581+
if (!Qualifier->isPresent())
9582+
return false;
9583+
auto OptionsString = Ctx.getPointerAuthOptionsString(*Qualifier);
9584+
QualType StrTy =
9585+
Ctx.getStringLiteralArrayType(Ctx.CharTy, OptionsString.length());
9586+
StringLiteral *OptionsLit =
9587+
StringLiteral::Create(Ctx, OptionsString, StringLiteralKind::Ordinary,
9588+
/*Pascal=*/false, StrTy, SourceLocation());
9589+
APValue OptionsVal(OptionsLit, CharUnits::Zero(),
9590+
{APValue::LValuePathEntry::ArrayIndex(0)},
9591+
/*OnePastTheEnd=*/false);
9592+
return Success(OptionsVal, E);
9593+
}
9594+
default:
9595+
return false;
9596+
}
9597+
}
9598+
95649599
bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
95659600
std::string ResultStr = E->ComputeName(Info.Ctx);
95669601

@@ -14878,6 +14913,43 @@ bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1487814913
return Success(
1487914914
Info.Ctx.getPointerAuthTypeDiscriminator(E->getArgumentType()), E);
1488014915
}
14916+
case UETT_PtrAuthHasAuthentication: {
14917+
auto ArgumentType = E->getArgumentType();
14918+
auto Qualifier = Info.Ctx.getExplicitOrImplicitPointerAuth(ArgumentType);
14919+
if (!Qualifier)
14920+
return false;
14921+
return Success(Qualifier->isPresent(), E);
14922+
}
14923+
case UETT_PtrAuthSchemaKey: {
14924+
auto ArgumentType = E->getArgumentType();
14925+
auto Qualifier = Info.Ctx.getExplicitOrImplicitPointerAuth(ArgumentType);
14926+
if (!Qualifier)
14927+
return false;
14928+
if (!Qualifier->isPresent())
14929+
return false;
14930+
return Success(Qualifier->getKey(), E);
14931+
}
14932+
case UETT_PtrAuthSchemaIsAddressDiscriminated: {
14933+
auto ArgumentType = E->getArgumentType();
14934+
auto Qualifier = Info.Ctx.getExplicitOrImplicitPointerAuth(ArgumentType);
14935+
if (!Qualifier)
14936+
return false;
14937+
if (!Qualifier->isPresent())
14938+
return false;
14939+
return Success(Qualifier->isAddressDiscriminated(), E);
14940+
}
14941+
case UETT_PtrAuthSchemaExtraDiscriminator: {
14942+
auto ArgumentType = E->getArgumentType();
14943+
auto Qualifier = Info.Ctx.getExplicitOrImplicitPointerAuth(ArgumentType);
14944+
if (!Qualifier)
14945+
return false;
14946+
if (!Qualifier->isPresent())
14947+
return false;
14948+
return Success(Qualifier->getExtraDiscriminator(), E);
14949+
}
14950+
case UETT_PtrAuthSchemaOptions:
14951+
llvm_unreachable(
14952+
"UETT_PtrAuthSchemaOptions should be evaluated as a pointer");
1488114953
case UETT_VecStep: {
1488214954
QualType Ty = E->getTypeOfArgument();
1488314955

clang/lib/AST/ItaniumMangle.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5426,6 +5426,14 @@ void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity,
54265426
Diags.Report(E->getExprLoc(), DiagID) << getTraitSpelling(SAE->getKind());
54275427
return;
54285428
}
5429+
case UETT_PtrAuthHasAuthentication:
5430+
case UETT_PtrAuthSchemaKey:
5431+
case UETT_PtrAuthSchemaIsAddressDiscriminated:
5432+
case UETT_PtrAuthSchemaExtraDiscriminator:
5433+
case UETT_PtrAuthSchemaOptions: {
5434+
MangleExtensionBuiltin(SAE);
5435+
break;
5436+
}
54295437
}
54305438
break;
54315439
}

0 commit comments

Comments
 (0)