xref: /aosp_15_r20/external/cronet/base/memory/protected_memory_win.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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/memory/page_size.h"
12 #include "base/process/process_metrics.h"
13 #include "base/synchronization/lock.h"
14 #include "build/build_config.h"
15 
16 namespace base {
17 
18 namespace {
19 
SetMemory(void * start,void * end,DWORD prot)20 bool SetMemory(void* start, void* end, DWORD prot) {
21   CHECK(end > start);
22   const uintptr_t page_mask = ~(base::GetPageSize() - 1);
23   const uintptr_t page_start = reinterpret_cast<uintptr_t>(start) & page_mask;
24   DWORD old_prot;
25   return VirtualProtect(reinterpret_cast<void*>(page_start),
26                         reinterpret_cast<uintptr_t>(end) - page_start, prot,
27                         &old_prot) != 0;
28 }
29 
30 }  // namespace
31 
32 namespace internal {
IsMemoryReadOnly(const void * ptr)33 bool IsMemoryReadOnly(const void* ptr) {
34   const uintptr_t page_mask = ~(base::GetPageSize() - 1);
35   const uintptr_t page_start = reinterpret_cast<uintptr_t>(ptr) & page_mask;
36 
37   MEMORY_BASIC_INFORMATION info;
38   SIZE_T result =
39       VirtualQuery(reinterpret_cast<LPCVOID>(page_start), &info, sizeof(info));
40 
41   return (result > 0U) && (info.Protect == PAGE_READONLY);
42 }
43 }  // namespace internal
44 
SetMemoryReadWrite(void * start,void * end)45 bool AutoWritableMemoryBase::SetMemoryReadWrite(void* start, void* end) {
46   return SetMemory(start, end, PAGE_READWRITE);
47 }
48 
SetMemoryReadOnly(void * start,void * end)49 bool AutoWritableMemoryBase::SetMemoryReadOnly(void* start, void* end) {
50   return SetMemory(start, end, PAGE_READONLY);
51 }
52 
53 }  // namespace base
54