1 // Copyright 2023 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_THREAD_ISOLATION_H_
6 #define PARTITION_ALLOC_THREAD_ISOLATION_THREAD_ISOLATION_H_
7 
8 #include "partition_alloc/partition_alloc_buildflags.h"
9 
10 #if BUILDFLAG(ENABLE_THREAD_ISOLATION)
11 
12 #include <cstddef>
13 #include <cstdint>
14 
15 #include "partition_alloc/partition_alloc_base/component_export.h"
16 #include "partition_alloc/partition_alloc_base/debug/debugging_buildflags.h"
17 
18 #if BUILDFLAG(ENABLE_PKEYS)
19 #include "partition_alloc/thread_isolation/pkey.h"
20 #endif
21 
22 #if !BUILDFLAG(HAS_64_BIT_POINTERS)
23 #error "thread isolation support requires 64 bit pointers"
24 #endif
25 
26 namespace partition_alloc {
27 
28 struct ThreadIsolationOption {
29   constexpr ThreadIsolationOption() = default;
ThreadIsolationOptionThreadIsolationOption30   explicit ThreadIsolationOption(bool enabled) : enabled(enabled) {}
31 
32 #if BUILDFLAG(ENABLE_PKEYS)
ThreadIsolationOptionThreadIsolationOption33   explicit ThreadIsolationOption(int pkey) : pkey(pkey) {
34     enabled = pkey != internal::kInvalidPkey;
35   }
36   int pkey = -1;
37 #endif  // BUILDFLAG(ENABLE_PKEYS)
38 
39   bool enabled = false;
40 
41   bool operator==(const ThreadIsolationOption& other) const {
42 #if BUILDFLAG(ENABLE_PKEYS)
43     if (pkey != other.pkey) {
44       return false;
45     }
46 #endif  // BUILDFLAG(ENABLE_PKEYS)
47     return enabled == other.enabled;
48   }
49 };
50 
51 }  // namespace partition_alloc
52 
53 namespace partition_alloc::internal {
54 
55 #if BUILDFLAG(PA_DCHECK_IS_ON)
56 
57 struct PA_THREAD_ISOLATED_ALIGN ThreadIsolationSettings {
58   bool enabled = false;
59   static ThreadIsolationSettings settings PA_CONSTINIT;
60 };
61 
62 #if BUILDFLAG(ENABLE_PKEYS)
63 
64 using LiftThreadIsolationScope = LiftPkeyRestrictionsScope;
65 
66 #endif  // BUILDFLAG(ENABLE_PKEYS)
67 #endif  // BUILDFLAG(PA_DCHECK_IS_ON)
68 
69 void WriteProtectThreadIsolatedGlobals(ThreadIsolationOption thread_isolation);
70 void UnprotectThreadIsolatedGlobals();
71 [[nodiscard]] int MprotectWithThreadIsolation(
72     void* addr,
73     size_t len,
74     int prot,
75     ThreadIsolationOption thread_isolation);
76 
77 }  // namespace partition_alloc::internal
78 
79 #endif  // BUILDFLAG(ENABLE_THREAD_ISOLATION)
80 
81 #endif  // PARTITION_ALLOC_THREAD_ISOLATION_THREAD_ISOLATION_H_
82