1 // Copyright 2019 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 <inttypes.h> 6 #include <sys/mman.h> 7 8 #include "base/memory/madv_free_discardable_memory_allocator_posix.h" 9 #include "base/process/process_metrics.h" 10 #include "base/strings/string_number_conversions.h" 11 #include "base/strings/stringprintf.h" 12 #include "base/threading/thread_task_runner_handle.h" 13 #include "base/tracing_buildflags.h" 14 15 #if BUILDFLAG(ENABLE_BASE_TRACING) 16 #include "base/trace_event/memory_dump_manager.h" // no-presubmit-check 17 #endif // BUILDFLAG(ENABLE_BASE_TRACING) 18 19 namespace base { 20 21 MadvFreeDiscardableMemoryAllocatorPosix:: MadvFreeDiscardableMemoryAllocatorPosix()22 MadvFreeDiscardableMemoryAllocatorPosix() { 23 #if BUILDFLAG(ENABLE_BASE_TRACING) 24 // Don't register dump provider if ThreadTaskRunnerHandle is not set, such as 25 // in tests and Android Webview. 26 if (base::ThreadTaskRunnerHandle::IsSet()) { 27 trace_event::MemoryDumpManager::GetInstance()->RegisterDumpProvider( 28 this, "MadvFreeDiscardableMemoryAllocator", 29 ThreadTaskRunnerHandle::Get()); 30 } 31 #endif // BUILDFLAG(ENABLE_BASE_TRACING) 32 } 33 34 MadvFreeDiscardableMemoryAllocatorPosix:: ~MadvFreeDiscardableMemoryAllocatorPosix()35 ~MadvFreeDiscardableMemoryAllocatorPosix() { 36 #if BUILDFLAG(ENABLE_BASE_TRACING) 37 trace_event::MemoryDumpManager::GetInstance()->UnregisterDumpProvider(this); 38 #endif // BUILDFLAG(ENABLE_BASE_TRACING) 39 } 40 41 std::unique_ptr<DiscardableMemory> AllocateLockedDiscardableMemory(size_t size)42MadvFreeDiscardableMemoryAllocatorPosix::AllocateLockedDiscardableMemory( 43 size_t size) { 44 return std::make_unique<MadvFreeDiscardableMemoryPosix>(size, 45 &bytes_allocated_); 46 } 47 GetBytesAllocated() const48size_t MadvFreeDiscardableMemoryAllocatorPosix::GetBytesAllocated() const { 49 return bytes_allocated_; 50 } 51 OnMemoryDump(const trace_event::MemoryDumpArgs & args,trace_event::ProcessMemoryDump * pmd)52bool MadvFreeDiscardableMemoryAllocatorPosix::OnMemoryDump( 53 const trace_event::MemoryDumpArgs& args, 54 trace_event::ProcessMemoryDump* pmd) { 55 #if BUILDFLAG(ENABLE_BASE_TRACING) 56 if (args.level_of_detail != 57 base::trace_event::MemoryDumpLevelOfDetail::BACKGROUND) { 58 return true; 59 } 60 61 base::trace_event::MemoryAllocatorDump* total_dump = 62 pmd->CreateAllocatorDump("discardable/madv_free_allocated"); 63 total_dump->AddScalar(base::trace_event::MemoryAllocatorDump::kNameSize, 64 base::trace_event::MemoryAllocatorDump::kUnitsBytes, 65 GetBytesAllocated()); 66 return true; 67 #else // BUILDFLAG(ENABLE_BASE_TRACING) 68 return false; 69 #endif // BUILDFLAG(ENABLE_BASE_TRACING) 70 } 71 72 } // namespace base 73