1 //===-- Statistics.cpp ----------------------------------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "lldb/Target/Statistics.h"
10 
11 #include "lldb/Core/Debugger.h"
12 #include "lldb/Core/Module.h"
13 #include "lldb/Symbol/SymbolFile.h"
14 #include "lldb/Target/Process.h"
15 #include "lldb/Target/Target.h"
16 #include "lldb/Target/UnixSignals.h"
17 
18 using namespace lldb;
19 using namespace lldb_private;
20 using namespace llvm;
21 
22 static void EmplaceSafeString(llvm::json::Object &obj, llvm::StringRef key,
23                               const std::string &str) {
24   if (str.empty())
25     return;
26   if (LLVM_LIKELY(llvm::json::isUTF8(str)))
27     obj.try_emplace(key, str);
28   else
29     obj.try_emplace(key, llvm::json::fixUTF8(str));
30 }
31 
32 json::Value StatsSuccessFail::ToJSON() const {
33   return json::Object{{"successes", successes}, {"failures", failures}};
34 }
35 
36 static double elapsed(const StatsTimepoint &start, const StatsTimepoint &end) {
37   StatsDuration::Duration elapsed =
38       end.time_since_epoch() - start.time_since_epoch();
39   return elapsed.count();
40 }
41 
42 void TargetStats::CollectStats(Target &target) {
43   m_module_identifiers.clear();
44   for (ModuleSP module_sp : target.GetImages().Modules())
45     m_module_identifiers.emplace_back((intptr_t)module_sp.get());
46 }
47 
48 json::Value ModuleStats::ToJSON() const {
49   json::Object module;
50   EmplaceSafeString(module, "path", path);
51   EmplaceSafeString(module, "uuid", uuid);
52   EmplaceSafeString(module, "triple", triple);
53   module.try_emplace("identifier", identifier);
54   module.try_emplace("symbolTableParseTime", symtab_parse_time);
55   module.try_emplace("symbolTableIndexTime", symtab_index_time);
56   module.try_emplace("symbolTableLoadedFromCache", symtab_loaded_from_cache);
57   module.try_emplace("symbolTableSavedToCache", symtab_saved_to_cache);
58   module.try_emplace("debugInfoParseTime", debug_parse_time);
59   module.try_emplace("debugInfoIndexTime", debug_index_time);
60   module.try_emplace("debugInfoByteSize", (int64_t)debug_info_size);
61   module.try_emplace("debugInfoIndexLoadedFromCache",
62                      debug_info_index_loaded_from_cache);
63   module.try_emplace("debugInfoIndexSavedToCache",
64                      debug_info_index_saved_to_cache);
65   if (!symfile_path.empty())
66     module.try_emplace("symbolFilePath", symfile_path);
67 
68   if (!symfile_modules.empty()) {
69     json::Array symfile_ids;
70     for (const auto symfile_id: symfile_modules)
71       symfile_ids.emplace_back(symfile_id);
72     module.try_emplace("symbolFileModuleIdentifiers", std::move(symfile_ids));
73   }
74   return module;
75 }
76 
77 llvm::json::Value ConstStringStats::ToJSON() const {
78   json::Object obj;
79   obj.try_emplace<int64_t>("bytesTotal", stats.GetBytesTotal());
80   obj.try_emplace<int64_t>("bytesUsed", stats.GetBytesUsed());
81   obj.try_emplace<int64_t>("bytesUnused", stats.GetBytesUnused());
82   return obj;
83 }
84 
85 json::Value TargetStats::ToJSON(Target &target) {
86   CollectStats(target);
87 
88   json::Array json_module_uuid_array;
89   for (auto module_identifier : m_module_identifiers)
90     json_module_uuid_array.emplace_back(module_identifier);
91 
92   json::Object target_metrics_json{
93       {m_expr_eval.name, m_expr_eval.ToJSON()},
94       {m_frame_var.name, m_frame_var.ToJSON()},
95       {"moduleIdentifiers", std::move(json_module_uuid_array)}};
96 
97   if (m_launch_or_attach_time && m_first_private_stop_time) {
98     double elapsed_time =
99         elapsed(*m_launch_or_attach_time, *m_first_private_stop_time);
100     target_metrics_json.try_emplace("launchOrAttachTime", elapsed_time);
101   }
102   if (m_launch_or_attach_time && m_first_public_stop_time) {
103     double elapsed_time =
104         elapsed(*m_launch_or_attach_time, *m_first_public_stop_time);
105     target_metrics_json.try_emplace("firstStopTime", elapsed_time);
106   }
107   target_metrics_json.try_emplace("targetCreateTime",
108                                   m_create_time.get().count());
109 
110   json::Array breakpoints_array;
111   double totalBreakpointResolveTime = 0.0;
112   // Rport both the normal breakpoint list and the internal breakpoint list.
113   for (int i = 0; i < 2; ++i) {
114     BreakpointList &breakpoints = target.GetBreakpointList(i == 1);
115     std::unique_lock<std::recursive_mutex> lock;
116     breakpoints.GetListMutex(lock);
117     size_t num_breakpoints = breakpoints.GetSize();
118     for (size_t i = 0; i < num_breakpoints; i++) {
119       Breakpoint *bp = breakpoints.GetBreakpointAtIndex(i).get();
120       breakpoints_array.push_back(bp->GetStatistics());
121       totalBreakpointResolveTime += bp->GetResolveTime().count();
122     }
123   }
124 
125   ProcessSP process_sp = target.GetProcessSP();
126   if (process_sp) {
127     UnixSignalsSP unix_signals_sp = process_sp->GetUnixSignals();
128     if (unix_signals_sp)
129       target_metrics_json.try_emplace("signals",
130                                       unix_signals_sp->GetHitCountStatistics());
131     uint32_t stop_id = process_sp->GetStopID();
132     target_metrics_json.try_emplace("stopCount", stop_id);
133   }
134   target_metrics_json.try_emplace("breakpoints", std::move(breakpoints_array));
135   target_metrics_json.try_emplace("totalBreakpointResolveTime",
136                                   totalBreakpointResolveTime);
137 
138   return target_metrics_json;
139 }
140 
141 void TargetStats::SetLaunchOrAttachTime() {
142   m_launch_or_attach_time = StatsClock::now();
143   m_first_private_stop_time = llvm::None;
144 }
145 
146 void TargetStats::SetFirstPrivateStopTime() {
147   // Launching and attaching has many paths depending on if synchronous mode
148   // was used or if we are stopping at the entry point or not. Only set the
149   // first stop time if it hasn't already been set.
150   if (!m_first_private_stop_time)
151     m_first_private_stop_time = StatsClock::now();
152 }
153 
154 void TargetStats::SetFirstPublicStopTime() {
155   // Launching and attaching has many paths depending on if synchronous mode
156   // was used or if we are stopping at the entry point or not. Only set the
157   // first stop time if it hasn't already been set.
158   if (!m_first_public_stop_time)
159     m_first_public_stop_time = StatsClock::now();
160 }
161 
162 bool DebuggerStats::g_collecting_stats = false;
163 
164 llvm::json::Value DebuggerStats::ReportStatistics(Debugger &debugger,
165                                                   Target *target) {
166   json::Array json_targets;
167   json::Array json_modules;
168   double symtab_parse_time = 0.0;
169   double symtab_index_time = 0.0;
170   double debug_parse_time = 0.0;
171   double debug_index_time = 0.0;
172   uint32_t symtabs_loaded = 0;
173   uint32_t symtabs_saved = 0;
174   uint32_t debug_index_loaded = 0;
175   uint32_t debug_index_saved = 0;
176   uint64_t debug_info_size = 0;
177   if (target) {
178     json_targets.emplace_back(target->ReportStatistics());
179   } else {
180     for (const auto &target : debugger.GetTargetList().Targets())
181       json_targets.emplace_back(target->ReportStatistics());
182   }
183   std::vector<ModuleStats> modules;
184   std::lock_guard<std::recursive_mutex> guard(
185       Module::GetAllocationModuleCollectionMutex());
186   const size_t num_modules = Module::GetNumberAllocatedModules();
187   for (size_t image_idx = 0; image_idx < num_modules; ++image_idx) {
188     Module *module = Module::GetAllocatedModuleAtIndex(image_idx);
189     ModuleStats module_stat;
190     module_stat.identifier = (intptr_t)module;
191     module_stat.path = module->GetFileSpec().GetPath();
192     if (ConstString object_name = module->GetObjectName()) {
193       module_stat.path.append(1, '(');
194       module_stat.path.append(object_name.GetStringRef().str());
195       module_stat.path.append(1, ')');
196     }
197     module_stat.uuid = module->GetUUID().GetAsString();
198     module_stat.triple = module->GetArchitecture().GetTriple().str();
199     module_stat.symtab_parse_time = module->GetSymtabParseTime().get().count();
200     module_stat.symtab_index_time = module->GetSymtabIndexTime().get().count();
201     Symtab *symtab = module->GetSymtab();
202     if (symtab) {
203       module_stat.symtab_loaded_from_cache = symtab->GetWasLoadedFromCache();
204       if (module_stat.symtab_loaded_from_cache)
205         ++symtabs_loaded;
206       module_stat.symtab_saved_to_cache = symtab->GetWasSavedToCache();
207       if (module_stat.symtab_saved_to_cache)
208         ++symtabs_saved;
209     }
210     SymbolFile *sym_file = module->GetSymbolFile();
211     if (sym_file) {
212 
213       if (sym_file->GetObjectFile() != module->GetObjectFile())
214         module_stat.symfile_path =
215             sym_file->GetObjectFile()->GetFileSpec().GetPath();
216       module_stat.debug_index_time = sym_file->GetDebugInfoIndexTime().count();
217       module_stat.debug_parse_time = sym_file->GetDebugInfoParseTime().count();
218       module_stat.debug_info_size = sym_file->GetDebugInfoSize();
219       module_stat.debug_info_index_loaded_from_cache =
220           sym_file->GetDebugInfoIndexWasLoadedFromCache();
221       if (module_stat.debug_info_index_loaded_from_cache)
222         ++debug_index_loaded;
223       module_stat.debug_info_index_saved_to_cache =
224           sym_file->GetDebugInfoIndexWasSavedToCache();
225       if (module_stat.debug_info_index_saved_to_cache)
226         ++debug_index_saved;
227       ModuleList symbol_modules = sym_file->GetDebugInfoModules();
228       for (const auto &symbol_module: symbol_modules.Modules())
229         module_stat.symfile_modules.push_back((intptr_t)symbol_module.get());
230     }
231     symtab_parse_time += module_stat.symtab_parse_time;
232     symtab_index_time += module_stat.symtab_index_time;
233     debug_parse_time += module_stat.debug_parse_time;
234     debug_index_time += module_stat.debug_index_time;
235     debug_info_size += module_stat.debug_info_size;
236     json_modules.emplace_back(module_stat.ToJSON());
237   }
238 
239   ConstStringStats const_string_stats;
240   json::Object json_memory{
241       {"strings", const_string_stats.ToJSON()},
242   };
243 
244   json::Object global_stats{
245       {"targets", std::move(json_targets)},
246       {"modules", std::move(json_modules)},
247       {"memory", std::move(json_memory)},
248       {"totalSymbolTableParseTime", symtab_parse_time},
249       {"totalSymbolTableIndexTime", symtab_index_time},
250       {"totalSymbolTablesLoadedFromCache", symtabs_loaded},
251       {"totalSymbolTablesSavedToCache", symtabs_saved},
252       {"totalDebugInfoParseTime", debug_parse_time},
253       {"totalDebugInfoIndexTime", debug_index_time},
254       {"totalDebugInfoIndexLoadedFromCache", debug_index_loaded},
255       {"totalDebugInfoIndexSavedToCache", debug_index_saved},
256       {"totalDebugInfoByteSize", debug_info_size},
257   };
258   return std::move(global_stats);
259 }
260