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_TRACE_EVENT_PROCESS_MEMORY_DUMP_H_ 6 #define BASE_TRACE_EVENT_PROCESS_MEMORY_DUMP_H_ 7 8 #include <stddef.h> 9 10 #include <map> 11 #include <optional> 12 #include <unordered_map> 13 #include <vector> 14 15 #include "base/base_export.h" 16 #include "base/gtest_prod_util.h" 17 #include "base/trace_event/heap_profiler_allocation_context.h" 18 #include "base/trace_event/memory_allocator_dump.h" 19 #include "base/trace_event/memory_allocator_dump_guid.h" 20 #include "base/trace_event/memory_dump_request_args.h" 21 #include "build/build_config.h" 22 23 // Define COUNT_RESIDENT_BYTES_SUPPORTED if platform supports counting of the 24 // resident memory. 25 #if !BUILDFLAG(IS_NACL) 26 #define COUNT_RESIDENT_BYTES_SUPPORTED 27 #endif 28 29 namespace perfetto { 30 namespace protos { 31 namespace pbzero { 32 class MemoryTrackerSnapshot; 33 } 34 } // namespace protos 35 } // namespace perfetto 36 37 namespace base { 38 39 class UnguessableToken; 40 41 namespace trace_event { 42 43 class TraceEventMemoryOverhead; 44 class TracedValue; 45 46 // ProcessMemoryDump is as a strongly typed container which holds the dumps 47 // produced by the MemoryDumpProvider(s) for a specific process. 48 class BASE_EXPORT ProcessMemoryDump { 49 public: 50 struct BASE_EXPORT MemoryAllocatorDumpEdge { 51 friend bool operator==(const MemoryAllocatorDumpEdge&, 52 const MemoryAllocatorDumpEdge&) = default; 53 54 MemoryAllocatorDumpGuid source; 55 MemoryAllocatorDumpGuid target; 56 int importance = 0; 57 bool overridable = false; 58 }; 59 60 // Maps allocator dumps absolute names (allocator_name/heap/subheap) to 61 // MemoryAllocatorDump instances. 62 using AllocatorDumpsMap = 63 std::map<std::string, std::unique_ptr<MemoryAllocatorDump>>; 64 65 // Stores allocator dump edges indexed by source allocator dump GUID. 66 using AllocatorDumpEdgesMap = 67 std::map<MemoryAllocatorDumpGuid, MemoryAllocatorDumpEdge>; 68 69 #if defined(COUNT_RESIDENT_BYTES_SUPPORTED) 70 // Returns the number of bytes in a kernel memory page. Some platforms may 71 // have a different value for kernel page sizes from user page sizes. It is 72 // important to use kernel memory page sizes for resident bytes calculation. 73 // In most cases, the two are the same. 74 static size_t GetSystemPageSize(); 75 76 // Returns the total bytes resident for a virtual address range, with given 77 // |start_address| and |mapped_size|. |mapped_size| is specified in bytes. The 78 // value returned is valid only if the given range is currently mmapped by the 79 // process. The |start_address| must be page-aligned. 80 static std::optional<size_t> CountResidentBytes(void* start_address, 81 size_t mapped_size); 82 83 // The same as above, but the given mapped range should belong to the 84 // shared_memory's mapped region. 85 static std::optional<size_t> CountResidentBytesInSharedMemory( 86 void* start_address, 87 size_t mapped_size); 88 #endif 89 90 explicit ProcessMemoryDump(const MemoryDumpArgs& dump_args); 91 ProcessMemoryDump(ProcessMemoryDump&&); 92 93 ProcessMemoryDump(const ProcessMemoryDump&) = delete; 94 ProcessMemoryDump& operator=(const ProcessMemoryDump&) = delete; 95 96 ~ProcessMemoryDump(); 97 98 ProcessMemoryDump& operator=(ProcessMemoryDump&&); 99 100 // Creates a new MemoryAllocatorDump with the given name and returns the 101 // empty object back to the caller. 102 // Arguments: 103 // absolute_name: a name that uniquely identifies allocator dumps produced 104 // by this provider. It is possible to specify nesting by using a 105 // path-like string (e.g., v8/isolate1/heap1, v8/isolate1/heap2). 106 // Leading or trailing slashes are not allowed. 107 // guid: an optional identifier, unique among all processes within the 108 // scope of a global dump. This is only relevant when using 109 // AddOwnershipEdge() to express memory sharing. If omitted, 110 // it will be automatically generated. 111 // ProcessMemoryDump handles the memory ownership of its MemoryAllocatorDumps. 112 MemoryAllocatorDump* CreateAllocatorDump(const std::string& absolute_name); 113 MemoryAllocatorDump* CreateAllocatorDump(const std::string& absolute_name, 114 const MemoryAllocatorDumpGuid& guid); 115 116 // Looks up a MemoryAllocatorDump given its allocator and heap names, or 117 // nullptr if not found. 118 MemoryAllocatorDump* GetAllocatorDump(const std::string& absolute_name) const; 119 120 // Do NOT use this method. All dump providers should use 121 // CreateAllocatorDump(). Tries to create a new MemoryAllocatorDump only if it 122 // doesn't already exist. Creating multiple dumps with same name using 123 // GetOrCreateAllocatorDump() would override the existing scalars in MAD and 124 // cause misreporting. This method is used only in rare cases multiple 125 // components create allocator dumps with same name and only one of them adds 126 // size. 127 MemoryAllocatorDump* GetOrCreateAllocatorDump( 128 const std::string& absolute_name); 129 130 // Creates a shared MemoryAllocatorDump, to express cross-process sharing. 131 // Shared allocator dumps are allowed to have duplicate guids within the 132 // global scope, in order to reference the same dump from multiple processes. 133 // See the design doc goo.gl/keU6Bf for reference usage patterns. 134 MemoryAllocatorDump* CreateSharedGlobalAllocatorDump( 135 const MemoryAllocatorDumpGuid& guid); 136 137 // Creates a shared MemoryAllocatorDump as CreateSharedGlobalAllocatorDump, 138 // but with a WEAK flag. A weak dump will be discarded unless a non-weak dump 139 // is created using CreateSharedGlobalAllocatorDump by at least one process. 140 // The WEAK flag does not apply if a non-weak dump with the same GUID already 141 // exists or is created later. All owners and children of the discarded dump 142 // will also be discarded transitively. 143 MemoryAllocatorDump* CreateWeakSharedGlobalAllocatorDump( 144 const MemoryAllocatorDumpGuid& guid); 145 146 // Looks up a shared MemoryAllocatorDump given its guid. 147 MemoryAllocatorDump* GetSharedGlobalAllocatorDump( 148 const MemoryAllocatorDumpGuid& guid) const; 149 150 // Returns the map of the MemoryAllocatorDumps added to this dump. allocator_dumps()151 const AllocatorDumpsMap& allocator_dumps() const { return allocator_dumps_; } 152 mutable_allocator_dumps_for_serialization()153 AllocatorDumpsMap* mutable_allocator_dumps_for_serialization() const { 154 // Mojo takes a const input argument even for move-only types that can be 155 // mutate while serializing (like this one). Hence the const_cast. 156 return const_cast<AllocatorDumpsMap*>(&allocator_dumps_); 157 } 158 void SetAllocatorDumpsForSerialization( 159 std::vector<std::unique_ptr<MemoryAllocatorDump>>); 160 161 // Only for mojo serialization. 162 std::vector<MemoryAllocatorDumpEdge> GetAllEdgesForSerialization() const; 163 void SetAllEdgesForSerialization(const std::vector<MemoryAllocatorDumpEdge>&); 164 165 // Dumps heap usage with |allocator_name|. 166 void DumpHeapUsage( 167 const std::unordered_map<base::trace_event::AllocationContext, 168 base::trace_event::AllocationMetrics>& 169 metrics_by_context, 170 base::trace_event::TraceEventMemoryOverhead& overhead, 171 const char* allocator_name); 172 173 // Adds an ownership relationship between two MemoryAllocatorDump(s) with the 174 // semantics: |source| owns |target|, and has the effect of attributing 175 // the memory usage of |target| to |source|. |importance| is optional and 176 // relevant only for the cases of co-ownership, where it acts as a z-index: 177 // the owner with the highest importance will be attributed |target|'s memory. 178 // If an edge is present, its importance will not be updated unless 179 // |importance| is larger. 180 void AddOwnershipEdge(const MemoryAllocatorDumpGuid& source, 181 const MemoryAllocatorDumpGuid& target, 182 int importance); 183 void AddOwnershipEdge(const MemoryAllocatorDumpGuid& source, 184 const MemoryAllocatorDumpGuid& target); 185 186 // Adds edges that can be overriden by a later or earlier call to 187 // AddOwnershipEdge() with the same source and target with a different 188 // |importance| value. 189 void AddOverridableOwnershipEdge(const MemoryAllocatorDumpGuid& source, 190 const MemoryAllocatorDumpGuid& target, 191 int importance); 192 193 // Creates ownership edges for shared memory. Handles the case of cross 194 // process sharing and importance of ownership for the case with and without 195 // the shared memory dump provider. This handles both shared memory from both 196 // legacy base::SharedMemory as well as current base::SharedMemoryMapping. The 197 // weak version creates a weak global dump. 198 // |client_local_dump_guid| The guid of the local dump created by the client 199 // of base::SharedMemory. 200 // |shared_memory_guid| The ID of the shared memory that is assigned globally, 201 // used to create global dump edges in the new model. 202 // |importance| Importance of the global dump edges to say if the current 203 // process owns the memory segment. 204 void CreateSharedMemoryOwnershipEdge( 205 const MemoryAllocatorDumpGuid& client_local_dump_guid, 206 const UnguessableToken& shared_memory_guid, 207 int importance); 208 void CreateWeakSharedMemoryOwnershipEdge( 209 const MemoryAllocatorDumpGuid& client_local_dump_guid, 210 const UnguessableToken& shared_memory_guid, 211 int importance); 212 allocator_dumps_edges()213 const AllocatorDumpEdgesMap& allocator_dumps_edges() const { 214 return allocator_dumps_edges_; 215 } 216 217 // Utility method to add a suballocation relationship with the following 218 // semantics: |source| is suballocated from |target_node_name|. 219 // This creates a child node of |target_node_name| and adds an ownership edge 220 // between |source| and the new child node. As a result, the UI will not 221 // account the memory of |source| in the target node. 222 void AddSuballocation(const MemoryAllocatorDumpGuid& source, 223 const std::string& target_node_name); 224 225 // Removes all the MemoryAllocatorDump(s) contained in this instance. This 226 // ProcessMemoryDump can be safely reused as if it was new once this returns. 227 void Clear(); 228 229 // Merges all MemoryAllocatorDump(s) contained in |other| inside this 230 // ProcessMemoryDump, transferring their ownership to this instance. 231 // |other| will be an empty ProcessMemoryDump after this method returns. 232 // This is to allow dump providers to pre-populate ProcessMemoryDump instances 233 // and later move their contents into the ProcessMemoryDump passed as argument 234 // of the MemoryDumpProvider::OnMemoryDump(ProcessMemoryDump*) callback. 235 void TakeAllDumpsFrom(ProcessMemoryDump* other); 236 237 // Populate the traced value with information about the memory allocator 238 // dumps. 239 void SerializeAllocatorDumpsInto(TracedValue* value) const; 240 241 void SerializeAllocatorDumpsInto( 242 perfetto::protos::pbzero::MemoryTrackerSnapshot* memory_snapshot, 243 const base::ProcessId pid) const; 244 dump_args()245 const MemoryDumpArgs& dump_args() const { return dump_args_; } 246 247 private: 248 FRIEND_TEST_ALL_PREFIXES(ProcessMemoryDumpTest, BackgroundModeTest); 249 FRIEND_TEST_ALL_PREFIXES(ProcessMemoryDumpTest, SharedMemoryOwnershipTest); 250 FRIEND_TEST_ALL_PREFIXES(ProcessMemoryDumpTest, GuidsTest); 251 252 MemoryAllocatorDump* AddAllocatorDumpInternal( 253 std::unique_ptr<MemoryAllocatorDump> mad); 254 255 // A per-process token, valid throughout all the lifetime of the current 256 // process, used to disambiguate dumps with the same name generated in 257 // different processes. process_token()258 const UnguessableToken& process_token() const { return process_token_; } set_process_token_for_testing(UnguessableToken token)259 void set_process_token_for_testing(UnguessableToken token) { 260 process_token_ = token; 261 } 262 263 // Returns the Guid of the dump for the given |absolute_name| for 264 // for the given process' token. |process_token| is used to disambiguate GUIDs 265 // derived from the same name under different processes. 266 MemoryAllocatorDumpGuid GetDumpId(const std::string& absolute_name); 267 268 void CreateSharedMemoryOwnershipEdgeInternal( 269 const MemoryAllocatorDumpGuid& client_local_dump_guid, 270 const UnguessableToken& shared_memory_guid, 271 int importance, 272 bool is_weak); 273 274 MemoryAllocatorDump* GetBlackHoleMad(const std::string& absolute_name); 275 276 UnguessableToken process_token_; 277 AllocatorDumpsMap allocator_dumps_; 278 279 // Keeps track of relationships between MemoryAllocatorDump(s). 280 AllocatorDumpEdgesMap allocator_dumps_edges_; 281 282 // Level of detail of the current dump. 283 MemoryDumpArgs dump_args_; 284 285 // This allocator dump is returned when an invalid dump is created in 286 // background mode. The attributes of the dump are ignored and not added to 287 // the trace. 288 std::unique_ptr<MemoryAllocatorDump> black_hole_mad_; 289 290 // When set to true, the DCHECK(s) for invalid dump creations on the 291 // background mode are disabled for testing. 292 static bool is_black_hole_non_fatal_for_testing_; 293 }; 294 295 } // namespace trace_event 296 } // namespace base 297 298 #endif // BASE_TRACE_EVENT_PROCESS_MEMORY_DUMP_H_ 299