• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2024 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 #include "base/memory/protected_memory.h"
6 
7 #include <windows.h>
8 
9 #include <stdint.h>
10 
11 #include "base/bits.h"
12 #include "base/memory/page_size.h"
13 #include "base/process/process_metrics.h"
14 #include "base/synchronization/lock.h"
15 #include "build/build_config.h"
16 
17 namespace base {
18 
19 #if BUILDFLAG(PROTECTED_MEMORY_ENABLED)
20 namespace {
21 
SetMemory(void * start,void * end,DWORD prot)22 bool SetMemory(void* start, void* end, DWORD prot) {
23   CHECK(end > start);
24   const uintptr_t page_start =
25       bits::AlignDown(reinterpret_cast<uintptr_t>(start), GetPageSize());
26   DWORD old_prot;
27   return VirtualProtect(reinterpret_cast<void*>(page_start),
28                         reinterpret_cast<uintptr_t>(end) - page_start, prot,
29                         &old_prot) != 0;
30 }
31 
32 }  // namespace
33 
34 namespace internal {
CheckMemoryReadOnly(const void * ptr)35 void CheckMemoryReadOnly(const void* ptr) {
36   const uintptr_t page_start =
37       bits::AlignDown(reinterpret_cast<uintptr_t>(ptr), GetPageSize());
38 
39   MEMORY_BASIC_INFORMATION info;
40   SIZE_T result =
41       VirtualQuery(reinterpret_cast<LPCVOID>(page_start), &info, sizeof(info));
42 
43   CHECK((result > 0U) && (info.Protect == PAGE_READONLY));
44 }
45 }  // namespace internal
46 
SetMemoryReadWrite(void * start,void * end)47 bool AutoWritableMemoryBase::SetMemoryReadWrite(void* start, void* end) {
48   return SetMemory(start, end, PAGE_READWRITE);
49 }
50 
SetMemoryReadOnly(void * start,void * end)51 bool AutoWritableMemoryBase::SetMemoryReadOnly(void* start, void* end) {
52   return SetMemory(start, end, PAGE_READONLY);
53 }
54 #endif  // BUILDFLAG(PROTECTED_MEMORY_ENABLED)
55 
56 }  // namespace base
57