1 // Copyright 2022 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef PARTITION_ALLOC_THREAD_ISOLATION_PKEY_H_
6 #define PARTITION_ALLOC_THREAD_ISOLATION_PKEY_H_
7 
8 #include "partition_alloc/partition_alloc_buildflags.h"
9 
10 #if BUILDFLAG(ENABLE_PKEYS)
11 
12 #include "partition_alloc/partition_alloc_base/component_export.h"
13 #include "partition_alloc/partition_alloc_base/debug/debugging_buildflags.h"
14 #include "partition_alloc/thread_isolation/alignment.h"
15 
16 #include <cstddef>
17 #include <cstdint>
18 
19 namespace partition_alloc::internal {
20 
21 constexpr int kDefaultPkey = 0;
22 constexpr int kInvalidPkey = -1;
23 
24 // Check if the CPU supports pkeys.
25 bool CPUHasPkeySupport();
26 
27 // A wrapper around the pkey_mprotect syscall.
28 [[nodiscard]] int PkeyMprotect(void* addr, size_t len, int prot, int pkey);
29 
30 void TagMemoryWithPkey(int pkey, void* address, size_t size);
31 
32 int PkeyAlloc(int access_rights);
33 
34 void PkeyFree(int pkey);
35 
36 // Read the pkru register (the current pkey state).
37 uint32_t Rdpkru();
38 
39 // Write the pkru register (the current pkey state).
40 void Wrpkru(uint32_t pkru);
41 
42 #if BUILDFLAG(PA_DCHECK_IS_ON)
43 
PA_COMPONENT_EXPORT(PARTITION_ALLOC)44 class PA_COMPONENT_EXPORT(PARTITION_ALLOC) LiftPkeyRestrictionsScope {
45  public:
46   static constexpr uint32_t kDefaultPkeyValue = 0x55555554;
47   static constexpr uint32_t kAllowAllPkeyValue = 0x0;
48 
49   LiftPkeyRestrictionsScope();
50   ~LiftPkeyRestrictionsScope();
51 
52  private:
53   uint32_t saved_pkey_value_;
54 };
55 
56 #endif  // BUILDFLAG(PA_DCHECK_IS_ON)
57 
58 }  // namespace partition_alloc::internal
59 
60 #endif  // BUILDFLAG(ENABLE_PKEYS)
61 
62 #endif  // PARTITION_ALLOC_THREAD_ISOLATION_PKEY_H_
63