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