1 // Copyright 2015 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 #ifndef BASE_MEMORY_DISCARDABLE_MEMORY_ALLOCATOR_H_ 6 #define BASE_MEMORY_DISCARDABLE_MEMORY_ALLOCATOR_H_ 7 8 #include <stddef.h> 9 10 #include <memory> 11 12 #include "base/base_export.h" 13 #include "base/callback.h" 14 #include "base/macros.h" 15 #include "base/memory/discardable_memory.h" 16 17 namespace base { 18 class DiscardableMemory; 19 20 // An allocator which creates and manages DiscardableMemory. The allocator 21 // itself should be created via CreateDiscardableMemoryAllocator, which 22 // selects an appropriate implementation depending on platform support. 23 class BASE_EXPORT DiscardableMemoryAllocator { 24 public: 25 DiscardableMemoryAllocator() = default; 26 virtual ~DiscardableMemoryAllocator() = default; 27 28 // Returns the allocator instance. 29 static DiscardableMemoryAllocator* GetInstance(); 30 31 // Sets the allocator instance. Can only be called once, e.g. on startup. 32 // Ownership of |instance| remains with the caller. 33 static void SetInstance(DiscardableMemoryAllocator* allocator); 34 35 // Creates an initially-locked instance of discardable memory. 36 // If the platform supports Android ashmem or madvise(MADV_FREE), 37 // platform-specific techniques will be used to discard memory under pressure. 38 // Otherwise, discardable memory is emulated and manually discarded 39 // heuristicly (via memory pressure notifications). 40 virtual std::unique_ptr<DiscardableMemory> AllocateLockedDiscardableMemory( 41 size_t size) = 0; 42 43 // Allocates discardable memory the same way |AllocateLockedDiscardableMemory| 44 // does. In case of failure, calls |on_no_memory| and retries once. As a 45 // consequence, |on_no_memory| should free some memory, and importantly, 46 // address space as well. 47 // 48 // In case of allocation failure after retry, terminates the process with 49 // an Out Of Memory status (for triage in crash reports). 50 // 51 // As a consequence, does *not* return nullptr. 52 std::unique_ptr<DiscardableMemory> 53 AllocateLockedDiscardableMemoryWithRetryOrDie(size_t size, 54 OnceClosure on_no_memory); 55 56 // Gets the total number of bytes allocated by this allocator which have not 57 // been discarded. 58 virtual size_t GetBytesAllocated() const = 0; 59 60 // Release any memory used in the implementation of discardable memory that is 61 // not immediately being used. 62 virtual void ReleaseFreeMemory() = 0; 63 64 private: 65 DISALLOW_COPY_AND_ASSIGN(DiscardableMemoryAllocator); 66 }; 67 68 } // namespace base 69 70 #endif // BASE_MEMORY_DISCARDABLE_MEMORY_ALLOCATOR_H_ 71