• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2022 The Chromium Authors. All rights reserved.
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/raw_ptr_asan_bound_arg_tracker.h"
6 
7 #include "base/allocator/partition_allocator/partition_alloc_buildflags.h"
8 
9 #if BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
10 
11 #include <sanitizer/allocator_interface.h>
12 #include <sanitizer/asan_interface.h>
13 
14 #include "base/memory/raw_ptr_asan_service.h"
15 #include "third_party/abseil-cpp/absl/base/attributes.h"
16 
17 namespace base {
18 
19 namespace {
20 
21 // We use thread-local storage instead of sequence-local storage for consistency
22 // with PendingReport in RawPtrAsanService.
23 ABSL_CONST_INIT thread_local RawPtrAsanBoundArgTracker::ProtectedArgsVector*
24     protected_args = nullptr;
25 
26 }  // namespace
27 
28 // static
GetProtectedArgPtr(uintptr_t ptr)29 uintptr_t RawPtrAsanBoundArgTracker::GetProtectedArgPtr(uintptr_t ptr) {
30   if (!protected_args) {
31     return 0;
32   }
33 
34   for (auto protected_arg_ptr : *protected_args) {
35     uintptr_t allocation_base = 0;
36     size_t allocation_size = 0;
37     __asan_locate_address(reinterpret_cast<void*>(protected_arg_ptr), nullptr,
38                           0, reinterpret_cast<void**>(&allocation_base),
39                           &allocation_size);
40     if (allocation_base <= ptr && ptr < allocation_base + allocation_size) {
41       return allocation_base;
42     }
43   }
44 
45   return 0;
46 }
47 
RawPtrAsanBoundArgTracker()48 RawPtrAsanBoundArgTracker::RawPtrAsanBoundArgTracker()
49     : enabled_(RawPtrAsanService::GetInstance().IsEnabled()) {
50   if (enabled_) {
51     prev_protected_args_ = protected_args;
52     protected_args = &protected_args_;
53   }
54 }
55 
~RawPtrAsanBoundArgTracker()56 RawPtrAsanBoundArgTracker::~RawPtrAsanBoundArgTracker() {
57   if (enabled_) {
58     protected_args = prev_protected_args_;
59   }
60 }
61 
Add(uintptr_t ptr)62 void RawPtrAsanBoundArgTracker::Add(uintptr_t ptr) {
63   if (ptr) {
64     protected_args_->push_back(ptr);
65   }
66 }
67 
68 }  // namespace base
69 
70 #endif  // BUILDFLAG(USE_ASAN_BACKUP_REF_PTR)
71