blob: 453066a92315a7e411ce60d39c140bc2471ee3f8 [file] [log] [blame]
Jeff Goura3e4ebd2024-01-23 21:04:491// 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
Jeffrey Goure63ec7f2024-08-28 01:12:5311#include "base/bits.h"
Jeff Goura3e4ebd2024-01-23 21:04:4912#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
17namespace base {
Jeff Goura3e4ebd2024-01-23 21:04:4918
Jeffrey Gour6f946aad2024-07-11 16:07:5419#if BUILDFLAG(PROTECTED_MEMORY_ENABLED)
Jeff Goura3e4ebd2024-01-23 21:04:4920namespace {
21
22bool SetMemory(void* start, void* end, DWORD prot) {
23 CHECK(end > start);
Jeffrey Goure63ec7f2024-08-28 01:12:5324 const uintptr_t page_start =
25 bits::AlignDown(reinterpret_cast<uintptr_t>(start), GetPageSize());
Jeff Goura3e4ebd2024-01-23 21:04:4926 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
André Kempe5adc4d5a2024-03-15 12:23:3334namespace internal {
Jeffrey Goure63ec7f2024-08-28 01:12:5335void CheckMemoryReadOnly(const void* ptr) {
36 const uintptr_t page_start =
37 bits::AlignDown(reinterpret_cast<uintptr_t>(ptr), GetPageSize());
Jeff Goura3e4ebd2024-01-23 21:04:4938
39 MEMORY_BASIC_INFORMATION info;
40 SIZE_T result =
41 VirtualQuery(reinterpret_cast<LPCVOID>(page_start), &info, sizeof(info));
André Kempe5adc4d5a2024-03-15 12:23:3342
Jeffrey Goure63ec7f2024-08-28 01:12:5343 CHECK((result > 0U) && (info.Protect == PAGE_READONLY));
Jeff Goura3e4ebd2024-01-23 21:04:4944}
45} // namespace internal
André Kempe5adc4d5a2024-03-15 12:23:3346
47bool AutoWritableMemoryBase::SetMemoryReadWrite(void* start, void* end) {
48 return SetMemory(start, end, PAGE_READWRITE);
49}
50
51bool AutoWritableMemoryBase::SetMemoryReadOnly(void* start, void* end) {
52 return SetMemory(start, end, PAGE_READONLY);
53}
Jeffrey Gour6f946aad2024-07-11 16:07:5454#endif // BUILDFLAG(PROTECTED_MEMORY_ENABLED)
André Kempe5adc4d5a2024-03-15 12:23:3355
Jeff Goura3e4ebd2024-01-23 21:04:4956} // namespace base