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_TRACE_EVENT_HEAP_PROFILER_ALLOCATION_CONTEXT_TRACKER_H_ 6 #define BASE_TRACE_EVENT_HEAP_PROFILER_ALLOCATION_CONTEXT_TRACKER_H_ 7 8 #include <vector> 9 10 #include "base/atomicops.h" 11 #include "base/base_export.h" 12 #include "base/logging.h" 13 #include "base/macros.h" 14 #include "base/trace_event/heap_profiler_allocation_context.h" 15 16 namespace base { 17 namespace trace_event { 18 19 // The allocation context tracker keeps track of thread-local context for heap 20 // profiling. It includes a pseudo stack of trace events. On every allocation 21 // the tracker provides a snapshot of its context in the form of an 22 // |AllocationContext| that is to be stored together with the allocation 23 // details. 24 class BASE_EXPORT AllocationContextTracker { 25 public: 26 // Globally enables capturing allocation context. 27 // TODO(ruuda): Should this be replaced by |EnableCapturing| in the future? 28 // Or at least have something that guards agains enable -> disable -> enable? 29 static void SetCaptureEnabled(bool enabled); 30 31 // Returns whether capturing allocation context is enabled globally. capture_enabled()32 inline static bool capture_enabled() { 33 // A little lag after heap profiling is enabled or disabled is fine, it is 34 // more important that the check is as cheap as possible when capturing is 35 // not enabled, so do not issue a memory barrier in the fast path. 36 if (subtle::NoBarrier_Load(&capture_enabled_) == 0) 37 return false; 38 39 // In the slow path, an acquire load is required to pair with the release 40 // store in |SetCaptureEnabled|. This is to ensure that the TLS slot for 41 // the thread-local allocation context tracker has been initialized if 42 // |capture_enabled| returns true. 43 return subtle::Acquire_Load(&capture_enabled_) != 0; 44 } 45 46 // Pushes a frame onto the thread-local pseudo stack. 47 static void PushPseudoStackFrame(StackFrame frame); 48 49 // Pops a frame from the thread-local pseudo stack. 50 static void PopPseudoStackFrame(StackFrame frame); 51 52 // Returns a snapshot of the current thread-local context. 53 static AllocationContext GetContextSnapshot(); 54 55 ~AllocationContextTracker(); 56 57 private: 58 AllocationContextTracker(); 59 60 static AllocationContextTracker* GetThreadLocalTracker(); 61 62 static subtle::Atomic32 capture_enabled_; 63 64 // The pseudo stack where frames are |TRACE_EVENT| names. 65 std::vector<StackFrame> pseudo_stack_; 66 67 DISALLOW_COPY_AND_ASSIGN(AllocationContextTracker); 68 }; 69 70 } // namespace trace_event 71 } // namespace base 72 73 #endif // BASE_TRACE_EVENT_HEAP_PROFILER_ALLOCATION_CONTEXT_TRACKER_H_ 74