1 //===---------------------SharingPtr.cpp ------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "lldb/Utility/SharingPtr.h"
11 #if defined(ENABLE_SP_LOGGING)
13 // If ENABLE_SP_LOGGING is defined, then log all shared pointer assignments and
14 // allow them to be queried using a pointer by a call to:
18 #include "llvm/ADT/STLExtras.h"
36 std::vector<void *> m_frames;
39 Backtrace::Backtrace() : m_frames() {}
41 Backtrace::~Backtrace() {}
43 void Backtrace::GetFrames() {
45 const int count = ::backtrace(frames, llvm::array_lengthof(frames));
47 m_frames.assign(frames + 2, frames + (count - 2));
50 void Backtrace::Dump() const {
51 if (!m_frames.empty())
52 ::backtrace_symbols_fd(m_frames.data(), m_frames.size(), STDOUT_FILENO);
53 write(STDOUT_FILENO, "\n\n", 2);
56 extern "C" void track_sp(void *sp_this, void *ptr, long use_count) {
57 typedef std::pair<void *, Backtrace> PtrBacktracePair;
58 typedef std::map<void *, PtrBacktracePair> PtrToBacktraceMap;
59 static std::mutex g_mutex;
60 std::lock_guard<std::mutex> guard(g_mutex);
61 static PtrToBacktraceMap g_map;
64 printf("sp(%p) -> %p %lu\n", sp_this, ptr, use_count);
69 g_map[sp_this] = std::make_pair(ptr, bt);
75 printf("Searching for shared pointers that are tracking %p: ", ptr);
77 printf("Dump all live shared pointres: ");
80 PtrToBacktraceMap::iterator pos, end = g_map.end();
81 for (pos = g_map.begin(); pos != end; ++pos) {
82 if (ptr == NULL || pos->second.first == ptr) {
84 printf("\nsp(%p): %p\n", pos->first, pos->second.first);
85 pos->second.second.Dump();
93 // Put dump_sp_refs in the lldb namespace to it gets through our exports lists
94 // filter in the LLDB.framework or lldb.so
97 void dump_sp_refs(void *ptr) {
98 // Use a specially crafted call to "track_sp" which will dump info on all
99 // live shared pointers that reference "ptr"
100 track_sp(NULL, ptr, 0);
106 namespace lldb_private {
110 shared_count::~shared_count() {}
112 void shared_count::add_shared() {
114 _InterlockedIncrement(&shared_owners_);
120 void shared_count::release_shared() {
122 if (_InterlockedDecrement(&shared_owners_) == -1)
124 if (--shared_owners_ == -1)