1 //===-- StructuredDataDarwinLog.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 "StructuredDataDarwinLog.h"
16 #include "lldb/Breakpoint/StoppointCallbackContext.h"
17 #include "lldb/Core/Debugger.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/PluginManager.h"
20 #include "lldb/Host/OptionParser.h"
21 #include "lldb/Interpreter/CommandInterpreter.h"
22 #include "lldb/Interpreter/CommandObjectMultiword.h"
23 #include "lldb/Interpreter/CommandReturnObject.h"
24 #include "lldb/Interpreter/OptionArgParser.h"
25 #include "lldb/Interpreter/OptionValueProperties.h"
26 #include "lldb/Interpreter/OptionValueString.h"
27 #include "lldb/Interpreter/Property.h"
28 #include "lldb/Target/Process.h"
29 #include "lldb/Target/Target.h"
30 #include "lldb/Target/ThreadPlanCallOnFunctionExit.h"
31 #include "lldb/Utility/Log.h"
32 #include "lldb/Utility/RegularExpression.h"
34 #define DARWIN_LOG_TYPE_VALUE "DarwinLog"
37 using namespace lldb_private;
40 #pragma mark Anonymous Namespace
42 // Anonymous namespace
44 namespace sddarwinlog_private {
45 const uint64_t NANOS_PER_MICRO = 1000;
46 const uint64_t NANOS_PER_MILLI = NANOS_PER_MICRO * 1000;
47 const uint64_t NANOS_PER_SECOND = NANOS_PER_MILLI * 1000;
48 const uint64_t NANOS_PER_MINUTE = NANOS_PER_SECOND * 60;
49 const uint64_t NANOS_PER_HOUR = NANOS_PER_MINUTE * 60;
51 static bool DEFAULT_FILTER_FALLTHROUGH_ACCEPTS = true;
53 /// Global, sticky enable switch. If true, the user has explicitly
54 /// run the enable command. When a process launches or is attached to,
55 /// we will enable DarwinLog if either the settings for auto-enable is
56 /// on, or if the user had explicitly run enable at some point prior
57 /// to the launch/attach.
58 static bool s_is_explicitly_enabled;
61 using EnableOptionsSP = std::shared_ptr<EnableOptions>;
64 std::map<DebuggerWP, EnableOptionsSP, std::owner_less<DebuggerWP>>;
66 static OptionsMap &GetGlobalOptionsMap() {
67 static OptionsMap s_options_map;
71 static std::mutex &GetGlobalOptionsMapLock() {
72 static std::mutex s_options_map_lock;
73 return s_options_map_lock;
76 EnableOptionsSP GetGlobalEnableOptions(const DebuggerSP &debugger_sp) {
78 return EnableOptionsSP();
80 std::lock_guard<std::mutex> locker(GetGlobalOptionsMapLock());
81 OptionsMap &options_map = GetGlobalOptionsMap();
82 DebuggerWP debugger_wp(debugger_sp);
83 auto find_it = options_map.find(debugger_wp);
84 if (find_it != options_map.end())
85 return find_it->second;
87 return EnableOptionsSP();
90 void SetGlobalEnableOptions(const DebuggerSP &debugger_sp,
91 const EnableOptionsSP &options_sp) {
92 std::lock_guard<std::mutex> locker(GetGlobalOptionsMapLock());
93 OptionsMap &options_map = GetGlobalOptionsMap();
94 DebuggerWP debugger_wp(debugger_sp);
95 auto find_it = options_map.find(debugger_wp);
96 if (find_it != options_map.end())
97 find_it->second = options_sp;
99 options_map.insert(std::make_pair(debugger_wp, options_sp));
103 #pragma mark Settings Handling
105 /// Code to handle the StructuredDataDarwinLog settings
107 #define LLDB_PROPERTIES_darwinlog
108 #include "StructuredDataDarwinLogProperties.inc"
111 #define LLDB_PROPERTIES_darwinlog
112 #include "StructuredDataDarwinLogPropertiesEnum.inc"
115 class StructuredDataDarwinLogProperties : public Properties {
117 static ConstString &GetSettingName() {
118 static ConstString g_setting_name("darwin-log");
119 return g_setting_name;
122 StructuredDataDarwinLogProperties() : Properties() {
123 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
124 m_collection_sp->Initialize(g_darwinlog_properties);
127 ~StructuredDataDarwinLogProperties() override {}
129 bool GetEnableOnStartup() const {
130 const uint32_t idx = ePropertyEnableOnStartup;
131 return m_collection_sp->GetPropertyAtIndexAsBoolean(
132 nullptr, idx, g_darwinlog_properties[idx].default_uint_value != 0);
135 llvm::StringRef GetAutoEnableOptions() const {
136 const uint32_t idx = ePropertyAutoEnableOptions;
137 return m_collection_sp->GetPropertyAtIndexAsString(
138 nullptr, idx, g_darwinlog_properties[idx].default_cstr_value);
141 const char *GetLoggingModuleName() const { return "libsystem_trace.dylib"; }
144 using StructuredDataDarwinLogPropertiesSP =
145 std::shared_ptr<StructuredDataDarwinLogProperties>;
147 static const StructuredDataDarwinLogPropertiesSP &GetGlobalProperties() {
148 static StructuredDataDarwinLogPropertiesSP g_settings_sp;
150 g_settings_sp = std::make_shared<StructuredDataDarwinLogProperties>();
151 return g_settings_sp;
154 const char *const s_filter_attributes[] = {
155 "activity", // current activity
156 "activity-chain", // entire activity chain, each level separated by ':'
157 "category", // category of the log message
158 "message", // message contents, fully expanded
159 "subsystem" // subsystem of the log message
161 // Consider implementing this action as it would be cheaper to filter.
162 // "message" requires always formatting the message, which is a waste of
163 // cycles if it ends up being rejected. "format", // format string
164 // used to format message text
167 static ConstString GetDarwinLogTypeName() {
168 static const ConstString s_key_name("DarwinLog");
172 static ConstString GetLogEventType() {
173 static const ConstString s_event_type("log");
178 using FilterRuleSP = std::shared_ptr<FilterRule>;
182 virtual ~FilterRule() {}
184 using OperationCreationFunc =
185 std::function<FilterRuleSP(bool accept, size_t attribute_index,
186 const std::string &op_arg, Status &error)>;
188 static void RegisterOperation(ConstString operation,
189 const OperationCreationFunc &creation_func) {
190 GetCreationFuncMap().insert(std::make_pair(operation, creation_func));
193 static FilterRuleSP CreateRule(bool match_accepts, size_t attribute,
194 ConstString operation,
195 const std::string &op_arg, Status &error) {
196 // Find the creation func for this type of filter rule.
197 auto map = GetCreationFuncMap();
198 auto find_it = map.find(operation);
199 if (find_it == map.end()) {
200 error.SetErrorStringWithFormat("unknown filter operation \""
202 operation.GetCString());
203 return FilterRuleSP();
206 return find_it->second(match_accepts, attribute, op_arg, error);
209 StructuredData::ObjectSP Serialize() const {
210 StructuredData::Dictionary *dict_p = new StructuredData::Dictionary();
212 // Indicate whether this is an accept or reject rule.
213 dict_p->AddBooleanItem("accept", m_accept);
215 // Indicate which attribute of the message this filter references. This can
216 // drop into the rule-specific DoSerialization if we get to the point where
217 // not all FilterRule derived classes work on an attribute. (e.g. logical
218 // and/or and other compound operations).
219 dict_p->AddStringItem("attribute", s_filter_attributes[m_attribute_index]);
221 // Indicate the type of the rule.
222 dict_p->AddStringItem("type", GetOperationType().GetCString());
224 // Let the rule add its own specific details here.
225 DoSerialization(*dict_p);
227 return StructuredData::ObjectSP(dict_p);
230 virtual void Dump(Stream &stream) const = 0;
232 ConstString GetOperationType() const { return m_operation; }
235 FilterRule(bool accept, size_t attribute_index, ConstString operation)
236 : m_accept(accept), m_attribute_index(attribute_index),
237 m_operation(operation) {}
239 virtual void DoSerialization(StructuredData::Dictionary &dict) const = 0;
241 bool GetMatchAccepts() const { return m_accept; }
243 const char *GetFilterAttribute() const {
244 return s_filter_attributes[m_attribute_index];
248 using CreationFuncMap = std::map<ConstString, OperationCreationFunc>;
250 static CreationFuncMap &GetCreationFuncMap() {
251 static CreationFuncMap s_map;
256 const size_t m_attribute_index;
257 const ConstString m_operation;
260 using FilterRules = std::vector<FilterRuleSP>;
262 class RegexFilterRule : public FilterRule {
264 static void RegisterOperation() {
265 FilterRule::RegisterOperation(StaticGetOperation(), CreateOperation);
268 void Dump(Stream &stream) const override {
269 stream.Printf("%s %s regex %s", GetMatchAccepts() ? "accept" : "reject",
270 GetFilterAttribute(), m_regex_text.c_str());
274 void DoSerialization(StructuredData::Dictionary &dict) const override {
275 dict.AddStringItem("regex", m_regex_text);
279 static FilterRuleSP CreateOperation(bool accept, size_t attribute_index,
280 const std::string &op_arg,
282 // We treat the op_arg as a regex. Validate it.
283 if (op_arg.empty()) {
284 error.SetErrorString("regex filter type requires a regex "
286 return FilterRuleSP();
289 // Instantiate the regex so we can report any errors.
290 auto regex = RegularExpression(op_arg);
291 if (llvm::Error err = regex.GetError()) {
292 error.SetErrorString(llvm::toString(std::move(err)));
293 return FilterRuleSP();
296 // We passed all our checks, this appears fine.
298 return FilterRuleSP(new RegexFilterRule(accept, attribute_index, op_arg));
301 static ConstString StaticGetOperation() {
302 static ConstString s_operation("regex");
306 RegexFilterRule(bool accept, size_t attribute_index,
307 const std::string ®ex_text)
308 : FilterRule(accept, attribute_index, StaticGetOperation()),
309 m_regex_text(regex_text) {}
311 const std::string m_regex_text;
314 class ExactMatchFilterRule : public FilterRule {
316 static void RegisterOperation() {
317 FilterRule::RegisterOperation(StaticGetOperation(), CreateOperation);
320 void Dump(Stream &stream) const override {
321 stream.Printf("%s %s match %s", GetMatchAccepts() ? "accept" : "reject",
322 GetFilterAttribute(), m_match_text.c_str());
326 void DoSerialization(StructuredData::Dictionary &dict) const override {
327 dict.AddStringItem("exact_text", m_match_text);
331 static FilterRuleSP CreateOperation(bool accept, size_t attribute_index,
332 const std::string &op_arg,
334 if (op_arg.empty()) {
335 error.SetErrorString("exact match filter type requires an "
336 "argument containing the text that must "
337 "match the specified message attribute.");
338 return FilterRuleSP();
343 new ExactMatchFilterRule(accept, attribute_index, op_arg));
346 static ConstString StaticGetOperation() {
347 static ConstString s_operation("match");
351 ExactMatchFilterRule(bool accept, size_t attribute_index,
352 const std::string &match_text)
353 : FilterRule(accept, attribute_index, StaticGetOperation()),
354 m_match_text(match_text) {}
356 const std::string m_match_text;
359 static void RegisterFilterOperations() {
360 ExactMatchFilterRule::RegisterOperation();
361 RegexFilterRule::RegisterOperation();
364 // =========================================================================
366 // =========================================================================
368 /// Provides the main on-off switch for enabling darwin logging.
370 /// It is valid to run the enable command when logging is already enabled.
371 /// This resets the logging with whatever settings are currently set.
373 static constexpr OptionDefinition g_enable_option_table[] = {
374 // Source stream include/exclude options (the first-level filter). This one
375 // should be made as small as possible as everything that goes through here
376 // must be processed by the process monitor.
377 {LLDB_OPT_SET_ALL, false, "any-process", 'a', OptionParser::eNoArgument,
378 nullptr, {}, 0, eArgTypeNone,
379 "Specifies log messages from other related processes should be "
381 {LLDB_OPT_SET_ALL, false, "debug", 'd', OptionParser::eNoArgument, nullptr,
383 "Specifies debug-level log messages should be included. Specifying"
384 " --debug implies --info."},
385 {LLDB_OPT_SET_ALL, false, "info", 'i', OptionParser::eNoArgument, nullptr,
387 "Specifies info-level log messages should be included."},
388 {LLDB_OPT_SET_ALL, false, "filter", 'f', OptionParser::eRequiredArgument,
389 nullptr, {}, 0, eArgRawInput,
390 // There doesn't appear to be a great way for me to have these multi-line,
391 // formatted tables in help. This looks mostly right but there are extra
392 // linefeeds added at seemingly random spots, and indentation isn't
393 // handled properly on those lines.
394 "Appends a filter rule to the log message filter chain. Multiple "
395 "rules may be added by specifying this option multiple times, "
396 "once per filter rule. Filter rules are processed in the order "
397 "they are specified, with the --no-match-accepts setting used "
398 "for any message that doesn't match one of the rules.\n"
400 " Filter spec format:\n"
402 " --filter \"{action} {attribute} {op}\"\n"
409 " activity | // message's most-derived activity\n"
410 " activity-chain | // message's {parent}:{child} activity\n"
411 " category | // message's category\n"
412 " message | // message's expanded contents\n"
413 " subsystem | // message's subsystem\n"
416 " match {exact-match-text} |\n"
417 " regex {search-regex}\n"
419 "The regex flavor used is the C++ std::regex ECMAScript format. "
420 "Prefer character classes like [[:digit:]] to \\d and the like, as "
421 "getting the backslashes escaped through properly is error-prone."},
422 {LLDB_OPT_SET_ALL, false, "live-stream", 'l',
423 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
424 "Specify whether logging events are live-streamed or buffered. "
425 "True indicates live streaming, false indicates buffered. The "
426 "default is true (live streaming). Live streaming will deliver "
427 "log messages with less delay, but buffered capture mode has less "
428 "of an observer effect."},
429 {LLDB_OPT_SET_ALL, false, "no-match-accepts", 'n',
430 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
431 "Specify whether a log message that doesn't match any filter rule "
432 "is accepted or rejected, where true indicates accept. The "
434 {LLDB_OPT_SET_ALL, false, "echo-to-stderr", 'e',
435 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
436 "Specify whether os_log()/NSLog() messages are echoed to the "
437 "target program's stderr. When DarwinLog is enabled, we shut off "
438 "the mirroring of os_log()/NSLog() to the program's stderr. "
439 "Setting this flag to true will restore the stderr mirroring."
440 "The default is false."},
441 {LLDB_OPT_SET_ALL, false, "broadcast-events", 'b',
442 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
443 "Specify if the plugin should broadcast events. Broadcasting "
444 "log events is a requirement for displaying the log entries in "
445 "LLDB command-line. It is also required if LLDB clients want to "
446 "process log events. The default is true."},
447 // Message formatting options
448 {LLDB_OPT_SET_ALL, false, "timestamp-relative", 'r',
449 OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone,
450 "Include timestamp in the message header when printing a log "
451 "message. The timestamp is relative to the first displayed "
453 {LLDB_OPT_SET_ALL, false, "subsystem", 's', OptionParser::eNoArgument,
454 nullptr, {}, 0, eArgTypeNone,
455 "Include the subsystem in the message header when displaying "
457 {LLDB_OPT_SET_ALL, false, "category", 'c', OptionParser::eNoArgument,
458 nullptr, {}, 0, eArgTypeNone,
459 "Include the category in the message header when displaying "
461 {LLDB_OPT_SET_ALL, false, "activity-chain", 'C', OptionParser::eNoArgument,
462 nullptr, {}, 0, eArgTypeNone,
463 "Include the activity parent-child chain in the message header "
464 "when displaying a log message. The activity hierarchy is "
465 "displayed as {grandparent-activity}:"
466 "{parent-activity}:{activity}[:...]."},
467 {LLDB_OPT_SET_ALL, false, "all-fields", 'A', OptionParser::eNoArgument,
468 nullptr, {}, 0, eArgTypeNone,
469 "Shortcut to specify that all header fields should be displayed."}};
471 class EnableOptions : public Options {
474 : Options(), m_include_debug_level(false), m_include_info_level(false),
475 m_include_any_process(false),
476 m_filter_fall_through_accepts(DEFAULT_FILTER_FALLTHROUGH_ACCEPTS),
477 m_echo_to_stderr(false), m_display_timestamp_relative(false),
478 m_display_subsystem(false), m_display_category(false),
479 m_display_activity_chain(false), m_broadcast_events(true),
480 m_live_stream(true), m_filter_rules() {}
482 void OptionParsingStarting(ExecutionContext *execution_context) override {
483 m_include_debug_level = false;
484 m_include_info_level = false;
485 m_include_any_process = false;
486 m_filter_fall_through_accepts = DEFAULT_FILTER_FALLTHROUGH_ACCEPTS;
487 m_echo_to_stderr = false;
488 m_display_timestamp_relative = false;
489 m_display_subsystem = false;
490 m_display_category = false;
491 m_display_activity_chain = false;
492 m_broadcast_events = true;
493 m_live_stream = true;
494 m_filter_rules.clear();
497 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
498 ExecutionContext *execution_context) override {
501 const int short_option = m_getopt_table[option_idx].val;
502 switch (short_option) {
504 m_include_any_process = true;
508 m_display_timestamp_relative = true;
509 m_display_category = true;
510 m_display_subsystem = true;
511 m_display_activity_chain = true;
516 OptionArgParser::ToBoolean(option_arg, true, nullptr);
520 m_display_category = true;
524 m_display_activity_chain = true;
528 m_include_debug_level = true;
532 m_echo_to_stderr = OptionArgParser::ToBoolean(option_arg, false, nullptr);
536 return ParseFilterRule(option_arg);
539 m_include_info_level = true;
543 m_live_stream = OptionArgParser::ToBoolean(option_arg, false, nullptr);
547 m_filter_fall_through_accepts =
548 OptionArgParser::ToBoolean(option_arg, true, nullptr);
552 m_display_timestamp_relative = true;
556 m_display_subsystem = true;
560 error.SetErrorStringWithFormat("unsupported option '%c'", short_option);
565 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
566 return llvm::makeArrayRef(g_enable_option_table);
569 StructuredData::DictionarySP BuildConfigurationData(bool enabled) {
570 StructuredData::DictionarySP config_sp(new StructuredData::Dictionary());
572 // Set the basic enabled state.
573 config_sp->AddBooleanItem("enabled", enabled);
575 // If we're disabled, there's nothing more to add.
579 // Handle source stream flags.
580 auto source_flags_sp =
581 StructuredData::DictionarySP(new StructuredData::Dictionary());
582 config_sp->AddItem("source-flags", source_flags_sp);
584 source_flags_sp->AddBooleanItem("any-process", m_include_any_process);
585 source_flags_sp->AddBooleanItem("debug-level", m_include_debug_level);
586 // The debug-level flag, if set, implies info-level.
587 source_flags_sp->AddBooleanItem("info-level", m_include_info_level ||
588 m_include_debug_level);
589 source_flags_sp->AddBooleanItem("live-stream", m_live_stream);
591 // Specify default filter rule (the fall-through)
592 config_sp->AddBooleanItem("filter-fall-through-accepts",
593 m_filter_fall_through_accepts);
595 // Handle filter rules
596 if (!m_filter_rules.empty()) {
597 auto json_filter_rules_sp =
598 StructuredData::ArraySP(new StructuredData::Array);
599 config_sp->AddItem("filter-rules", json_filter_rules_sp);
600 for (auto &rule_sp : m_filter_rules) {
603 json_filter_rules_sp->AddItem(rule_sp->Serialize());
609 bool GetIncludeDebugLevel() const { return m_include_debug_level; }
611 bool GetIncludeInfoLevel() const {
612 // Specifying debug level implies info level.
613 return m_include_info_level || m_include_debug_level;
616 const FilterRules &GetFilterRules() const { return m_filter_rules; }
618 bool GetFallthroughAccepts() const { return m_filter_fall_through_accepts; }
620 bool GetEchoToStdErr() const { return m_echo_to_stderr; }
622 bool GetDisplayTimestampRelative() const {
623 return m_display_timestamp_relative;
626 bool GetDisplaySubsystem() const { return m_display_subsystem; }
627 bool GetDisplayCategory() const { return m_display_category; }
628 bool GetDisplayActivityChain() const { return m_display_activity_chain; }
630 bool GetDisplayAnyHeaderFields() const {
631 return m_display_timestamp_relative || m_display_activity_chain ||
632 m_display_subsystem || m_display_category;
635 bool GetBroadcastEvents() const { return m_broadcast_events; }
638 Status ParseFilterRule(llvm::StringRef rule_text) {
641 if (rule_text.empty()) {
642 error.SetErrorString("invalid rule_text");
646 // filter spec format:
648 // {action} {attribute} {op}
663 // match {exact-match-text} |
664 // regex {search-regex}
667 auto action_end_pos = rule_text.find(" ");
668 if (action_end_pos == std::string::npos) {
669 error.SetErrorStringWithFormat("could not parse filter rule "
670 "action from \"%s\"",
671 rule_text.str().c_str());
674 auto action = rule_text.substr(0, action_end_pos);
676 if (action == "accept")
678 else if (action == "reject")
681 error.SetErrorString("filter action must be \"accept\" or \"deny\"");
686 auto attribute_end_pos = rule_text.find(" ", action_end_pos + 1);
687 if (attribute_end_pos == std::string::npos) {
688 error.SetErrorStringWithFormat("could not parse filter rule "
689 "attribute from \"%s\"",
690 rule_text.str().c_str());
693 auto attribute = rule_text.substr(action_end_pos + 1,
694 attribute_end_pos - (action_end_pos + 1));
695 auto attribute_index = MatchAttributeIndex(attribute);
696 if (attribute_index < 0) {
697 error.SetErrorStringWithFormat("filter rule attribute unknown: "
699 attribute.str().c_str());
704 auto operation_end_pos = rule_text.find(" ", attribute_end_pos + 1);
705 auto operation = rule_text.substr(
706 attribute_end_pos + 1, operation_end_pos - (attribute_end_pos + 1));
710 FilterRule::CreateRule(accept, attribute_index, ConstString(operation),
711 rule_text.substr(operation_end_pos + 1), error);
713 if (rule_sp && error.Success())
714 m_filter_rules.push_back(rule_sp);
719 int MatchAttributeIndex(llvm::StringRef attribute_name) const {
720 for (const auto &Item : llvm::enumerate(s_filter_attributes)) {
721 if (attribute_name == Item.value())
725 // We didn't match anything.
729 bool m_include_debug_level;
730 bool m_include_info_level;
731 bool m_include_any_process;
732 bool m_filter_fall_through_accepts;
733 bool m_echo_to_stderr;
734 bool m_display_timestamp_relative;
735 bool m_display_subsystem;
736 bool m_display_category;
737 bool m_display_activity_chain;
738 bool m_broadcast_events;
740 FilterRules m_filter_rules;
743 class EnableCommand : public CommandObjectParsed {
745 EnableCommand(CommandInterpreter &interpreter, bool enable, const char *name,
746 const char *help, const char *syntax)
747 : CommandObjectParsed(interpreter, name, help, syntax), m_enable(enable),
748 m_options_sp(enable ? new EnableOptions() : nullptr) {}
751 void AppendStrictSourcesWarning(CommandReturnObject &result,
752 const char *source_name) {
756 // Check if we're *not* using strict sources. If not, then the user is
757 // going to get debug-level info anyways, probably not what they're
758 // expecting. Unfortunately we can only fix this by adding an env var,
759 // which would have had to have happened already. Thus, a warning is the
760 // best we can do here.
762 stream.Printf("darwin-log source settings specify to exclude "
763 "%s messages, but setting "
764 "'plugin.structured-data.darwin-log."
765 "strict-sources' is disabled. This process will "
766 "automatically have %s messages included. Enable"
767 " the property and relaunch the target binary to have"
768 " these messages excluded.",
769 source_name, source_name);
770 result.AppendWarning(stream.GetString());
773 bool DoExecute(Args &command, CommandReturnObject &result) override {
774 // First off, set the global sticky state of enable/disable based on this
775 // command execution.
776 s_is_explicitly_enabled = m_enable;
778 // Next, if this is an enable, save off the option data. We will need it
779 // later if a process hasn't been launched or attached yet.
781 // Save off enabled configuration so we can apply these parsed options
782 // the next time an attach or launch occurs.
783 DebuggerSP debugger_sp =
784 GetCommandInterpreter().GetDebugger().shared_from_this();
785 SetGlobalEnableOptions(debugger_sp, m_options_sp);
788 // Now check if we have a running process. If so, we should instruct the
789 // process monitor to enable/disable DarwinLog support now.
790 Target &target = GetSelectedOrDummyTarget();
792 // Grab the active process.
793 auto process_sp = target.GetProcessSP();
795 // No active process, so there is nothing more to do right now.
796 result.SetStatus(eReturnStatusSuccessFinishNoResult);
800 // If the process is no longer alive, we can't do this now. We'll catch it
801 // the next time the process is started up.
802 if (!process_sp->IsAlive()) {
803 result.SetStatus(eReturnStatusSuccessFinishNoResult);
807 // Get the plugin for the process.
809 process_sp->GetStructuredDataPlugin(GetDarwinLogTypeName());
810 if (!plugin_sp || (plugin_sp->GetPluginName() !=
811 StructuredDataDarwinLog::GetStaticPluginName())) {
812 result.AppendError("failed to get StructuredDataPlugin for "
814 result.SetStatus(eReturnStatusFailed);
816 StructuredDataDarwinLog &plugin =
817 *static_cast<StructuredDataDarwinLog *>(plugin_sp.get());
820 // Hook up the breakpoint for the process that detects when libtrace has
821 // been sufficiently initialized to really start the os_log stream. This
822 // is insurance to assure us that logging is really enabled. Requesting
823 // that logging be enabled for a process before libtrace is initialized
824 // results in a scenario where no errors occur, but no logging is
825 // captured, either. This step is to eliminate that possibility.
826 plugin.AddInitCompletionHook(*process_sp);
829 // Send configuration to the feature by way of the process. Construct the
830 // options we will use.
831 auto config_sp = m_options_sp->BuildConfigurationData(m_enable);
833 process_sp->ConfigureStructuredData(GetDarwinLogTypeName(), config_sp);
836 if (!error.Success()) {
837 result.AppendError(error.AsCString());
838 result.SetStatus(eReturnStatusFailed);
839 // Our configuration failed, so we're definitely disabled.
840 plugin.SetEnabled(false);
842 result.SetStatus(eReturnStatusSuccessFinishNoResult);
843 // Our configuration succeeded, so we're enabled/disabled per whichever
844 // one this command is setup to do.
845 plugin.SetEnabled(m_enable);
847 return result.Succeeded();
850 Options *GetOptions() override {
851 // We don't have options when this represents disable.
852 return m_enable ? m_options_sp.get() : nullptr;
857 EnableOptionsSP m_options_sp;
860 /// Provides the status command.
861 class StatusCommand : public CommandObjectParsed {
863 StatusCommand(CommandInterpreter &interpreter)
864 : CommandObjectParsed(interpreter, "status",
865 "Show whether Darwin log supported is available"
867 "plugin structured-data darwin-log status") {}
870 bool DoExecute(Args &command, CommandReturnObject &result) override {
871 auto &stream = result.GetOutputStream();
873 // Figure out if we've got a process. If so, we can tell if DarwinLog is
874 // available for that process.
875 Target &target = GetSelectedOrDummyTarget();
876 auto process_sp = target.GetProcessSP();
878 stream.PutCString("Availability: unknown (requires process)\n");
879 stream.PutCString("Enabled: not applicable "
880 "(requires process)\n");
883 process_sp->GetStructuredDataPlugin(GetDarwinLogTypeName());
884 stream.Printf("Availability: %s\n",
885 plugin_sp ? "available" : "unavailable");
886 ConstString plugin_name = StructuredDataDarwinLog::GetStaticPluginName();
888 plugin_sp ? plugin_sp->GetEnabled(plugin_name) : false;
889 stream.Printf("Enabled: %s\n", enabled ? "true" : "false");
892 // Display filter settings.
893 DebuggerSP debugger_sp =
894 GetCommandInterpreter().GetDebugger().shared_from_this();
895 auto options_sp = GetGlobalEnableOptions(debugger_sp);
897 // Nothing more to do.
898 result.SetStatus(eReturnStatusSuccessFinishResult);
902 // Print filter rules
903 stream.PutCString("DarwinLog filter rules:\n");
907 if (options_sp->GetFilterRules().empty()) {
909 stream.PutCString("none\n");
911 // Print each of the filter rules.
913 for (auto rule_sp : options_sp->GetFilterRules()) {
919 stream.Printf("%02d: ", rule_number);
920 rule_sp->Dump(stream);
921 stream.PutChar('\n');
926 // Print no-match handling.
928 stream.Printf("no-match behavior: %s\n",
929 options_sp->GetFallthroughAccepts() ? "accept" : "reject");
931 result.SetStatus(eReturnStatusSuccessFinishResult);
936 /// Provides the darwin-log base command
937 class BaseCommand : public CommandObjectMultiword {
939 BaseCommand(CommandInterpreter &interpreter)
940 : CommandObjectMultiword(interpreter, "plugin structured-data darwin-log",
941 "Commands for configuring Darwin os_log "
945 auto enable_help = "Enable Darwin log collection, or re-enable "
946 "with modified configuration.";
947 auto enable_syntax = "plugin structured-data darwin-log enable";
948 auto enable_cmd_sp = CommandObjectSP(
949 new EnableCommand(interpreter,
951 "enable", enable_help, enable_syntax));
952 LoadSubCommand("enable", enable_cmd_sp);
955 auto disable_help = "Disable Darwin log collection.";
956 auto disable_syntax = "plugin structured-data darwin-log disable";
957 auto disable_cmd_sp = CommandObjectSP(
958 new EnableCommand(interpreter,
960 "disable", disable_help, disable_syntax));
961 LoadSubCommand("disable", disable_cmd_sp);
964 auto status_cmd_sp = CommandObjectSP(new StatusCommand(interpreter));
965 LoadSubCommand("status", status_cmd_sp);
969 EnableOptionsSP ParseAutoEnableOptions(Status &error, Debugger &debugger) {
970 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS);
971 // We are abusing the options data model here so that we can parse options
972 // without requiring the Debugger instance.
974 // We have an empty execution context at this point. We only want to parse
975 // options, and we don't need any context to do this here. In fact, we want
976 // to be able to parse the enable options before having any context.
977 ExecutionContext exe_ctx;
979 EnableOptionsSP options_sp(new EnableOptions());
980 options_sp->NotifyOptionParsingStarting(&exe_ctx);
982 CommandReturnObject result;
984 // Parse the arguments.
985 auto options_property_sp =
986 debugger.GetPropertyValue(nullptr, "plugin.structured-data.darwin-log."
987 "auto-enable-options",
989 if (!error.Success())
990 return EnableOptionsSP();
991 if (!options_property_sp) {
992 error.SetErrorString("failed to find option setting for "
993 "plugin.structured-data.darwin-log.");
994 return EnableOptionsSP();
997 const char *enable_options =
998 options_property_sp->GetAsString()->GetCurrentValue();
999 Args args(enable_options);
1000 if (args.GetArgumentCount() > 0) {
1001 // Eliminate the initial '--' that would be required to set the settings
1002 // that themselves include '-' and/or '--'.
1003 const char *first_arg = args.GetArgumentAtIndex(0);
1004 if (first_arg && (strcmp(first_arg, "--") == 0))
1008 bool require_validation = false;
1009 llvm::Expected<Args> args_or =
1010 options_sp->Parse(args, &exe_ctx, PlatformSP(), require_validation);
1013 log, args_or.takeError(),
1014 "Parsing plugin.structured-data.darwin-log.auto-enable-options value "
1016 return EnableOptionsSP();
1019 if (!options_sp->VerifyOptions(result))
1020 return EnableOptionsSP();
1022 // We successfully parsed and validated the options.
1026 bool RunEnableCommand(CommandInterpreter &interpreter) {
1027 StreamString command_stream;
1029 command_stream << "plugin structured-data darwin-log enable";
1030 auto enable_options = GetGlobalProperties()->GetAutoEnableOptions();
1031 if (!enable_options.empty()) {
1032 command_stream << ' ';
1033 command_stream << enable_options;
1037 CommandReturnObject return_object;
1038 interpreter.HandleCommand(command_stream.GetData(), eLazyBoolNo,
1040 return return_object.Succeeded();
1043 using namespace sddarwinlog_private;
1046 #pragma mark Public static API
1048 // Public static API
1050 void StructuredDataDarwinLog::Initialize() {
1051 RegisterFilterOperations();
1052 PluginManager::RegisterPlugin(
1053 GetStaticPluginName(), "Darwin os_log() and os_activity() support",
1054 &CreateInstance, &DebuggerInitialize, &FilterLaunchInfo);
1057 void StructuredDataDarwinLog::Terminate() {
1058 PluginManager::UnregisterPlugin(&CreateInstance);
1061 ConstString StructuredDataDarwinLog::GetStaticPluginName() {
1062 static ConstString s_plugin_name("darwin-log");
1063 return s_plugin_name;
1067 #pragma mark PluginInterface API
1069 // PluginInterface API
1071 ConstString StructuredDataDarwinLog::GetPluginName() {
1072 return GetStaticPluginName();
1075 uint32_t StructuredDataDarwinLog::GetPluginVersion() { return 1; }
1078 #pragma mark StructuredDataPlugin API
1080 // StructuredDataPlugin API
1082 bool StructuredDataDarwinLog::SupportsStructuredDataType(
1083 ConstString type_name) {
1084 return type_name == GetDarwinLogTypeName();
1087 void StructuredDataDarwinLog::HandleArrivalOfStructuredData(
1088 Process &process, ConstString type_name,
1089 const StructuredData::ObjectSP &object_sp) {
1090 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1092 StreamString json_stream;
1094 object_sp->Dump(json_stream);
1096 json_stream.PutCString("<null>");
1097 LLDB_LOGF(log, "StructuredDataDarwinLog::%s() called with json: %s",
1098 __FUNCTION__, json_stream.GetData());
1101 // Ignore empty structured data.
1104 "StructuredDataDarwinLog::%s() StructuredData object "
1110 // Ignore any data that isn't for us.
1111 if (type_name != GetDarwinLogTypeName()) {
1113 "StructuredDataDarwinLog::%s() StructuredData type "
1114 "expected to be %s but was %s, ignoring",
1115 __FUNCTION__, GetDarwinLogTypeName().AsCString(),
1116 type_name.AsCString());
1120 // Broadcast the structured data event if we have that enabled. This is the
1121 // way that the outside world (all clients) get access to this data. This
1122 // plugin sets policy as to whether we do that.
1123 DebuggerSP debugger_sp = process.GetTarget().GetDebugger().shared_from_this();
1124 auto options_sp = GetGlobalEnableOptions(debugger_sp);
1125 if (options_sp && options_sp->GetBroadcastEvents()) {
1126 LLDB_LOGF(log, "StructuredDataDarwinLog::%s() broadcasting event",
1128 process.BroadcastStructuredData(object_sp, shared_from_this());
1131 // Later, hang on to a configurable amount of these and allow commands to
1132 // inspect, including showing backtraces.
1135 static void SetErrorWithJSON(Status &error, const char *message,
1136 StructuredData::Object &object) {
1138 error.SetErrorString("Internal error: message not set.");
1142 StreamString object_stream;
1143 object.Dump(object_stream);
1144 object_stream.Flush();
1146 error.SetErrorStringWithFormat("%s: %s", message, object_stream.GetData());
1149 Status StructuredDataDarwinLog::GetDescription(
1150 const StructuredData::ObjectSP &object_sp, lldb_private::Stream &stream) {
1154 error.SetErrorString("No structured data.");
1158 // Log message payload objects will be dictionaries.
1159 const StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
1161 SetErrorWithJSON(error, "Structured data should have been a dictionary "
1167 // Validate this is really a message for our plugin.
1168 ConstString type_name;
1169 if (!dictionary->GetValueForKeyAsString("type", type_name)) {
1170 SetErrorWithJSON(error, "Structured data doesn't contain mandatory "
1176 if (type_name != GetDarwinLogTypeName()) {
1177 // This is okay - it simply means the data we received is not a log
1178 // message. We'll just format it as is.
1179 object_sp->Dump(stream);
1183 // DarwinLog dictionaries store their data
1184 // in an array with key name "events".
1185 StructuredData::Array *events = nullptr;
1186 if (!dictionary->GetValueForKeyAsArray("events", events) || !events) {
1187 SetErrorWithJSON(error, "Log structured data is missing mandatory "
1188 "'events' field, expected to be an array",
1194 [&stream, &error, &object_sp, this](StructuredData::Object *object) {
1196 // Invalid. Stop iterating.
1197 SetErrorWithJSON(error, "Log event entry is null", *object_sp);
1201 auto event = object->GetAsDictionary();
1203 // Invalid, stop iterating.
1204 SetErrorWithJSON(error, "Log event is not a dictionary", *object_sp);
1208 // If we haven't already grabbed the first timestamp value, do that
1210 if (!m_recorded_first_timestamp) {
1211 uint64_t timestamp = 0;
1212 if (event->GetValueForKeyAsInteger("timestamp", timestamp)) {
1213 m_first_timestamp_seen = timestamp;
1214 m_recorded_first_timestamp = true;
1218 HandleDisplayOfEvent(*event, stream);
1226 bool StructuredDataDarwinLog::GetEnabled(ConstString type_name) const {
1227 if (type_name == GetStaticPluginName())
1228 return m_is_enabled;
1233 void StructuredDataDarwinLog::SetEnabled(bool enabled) {
1234 m_is_enabled = enabled;
1237 void StructuredDataDarwinLog::ModulesDidLoad(Process &process,
1238 ModuleList &module_list) {
1239 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1240 LLDB_LOGF(log, "StructuredDataDarwinLog::%s called (process uid %u)",
1241 __FUNCTION__, process.GetUniqueID());
1243 // Check if we should enable the darwin log support on startup/attach.
1244 if (!GetGlobalProperties()->GetEnableOnStartup() &&
1245 !s_is_explicitly_enabled) {
1246 // We're neither auto-enabled or explicitly enabled, so we shouldn't try to
1249 "StructuredDataDarwinLog::%s not applicable, we're not "
1250 "enabled (process uid %u)",
1251 __FUNCTION__, process.GetUniqueID());
1255 // If we already added the breakpoint, we've got nothing left to do.
1257 std::lock_guard<std::mutex> locker(m_added_breakpoint_mutex);
1258 if (m_added_breakpoint) {
1260 "StructuredDataDarwinLog::%s process uid %u's "
1261 "post-libtrace-init breakpoint is already set",
1262 __FUNCTION__, process.GetUniqueID());
1267 // The logging support module name, specifies the name of the image name that
1268 // must be loaded into the debugged process before we can try to enable
1270 const char *logging_module_cstr =
1271 GetGlobalProperties()->GetLoggingModuleName();
1272 if (!logging_module_cstr || (logging_module_cstr[0] == 0)) {
1273 // We need this. Bail.
1275 "StructuredDataDarwinLog::%s no logging module name "
1276 "specified, we don't know where to set a breakpoint "
1278 __FUNCTION__, process.GetUniqueID());
1282 const ConstString logging_module_name = ConstString(logging_module_cstr);
1284 // We need to see libtrace in the list of modules before we can enable
1285 // tracing for the target process.
1286 bool found_logging_support_module = false;
1287 for (size_t i = 0; i < module_list.GetSize(); ++i) {
1288 auto module_sp = module_list.GetModuleAtIndex(i);
1292 auto &file_spec = module_sp->GetFileSpec();
1293 found_logging_support_module =
1294 (file_spec.GetLastPathComponent() == logging_module_name);
1295 if (found_logging_support_module)
1299 if (!found_logging_support_module) {
1301 "StructuredDataDarwinLog::%s logging module %s "
1302 "has not yet been loaded, can't set a breakpoint "
1303 "yet (process uid %u)",
1304 __FUNCTION__, logging_module_name.AsCString(),
1305 process.GetUniqueID());
1309 // Time to enqueue the breakpoint so we can wait for logging support to be
1310 // initialized before we try to tap the libtrace stream.
1311 AddInitCompletionHook(process);
1313 "StructuredDataDarwinLog::%s post-init hook breakpoint "
1314 "set for logging module %s (process uid %u)",
1315 __FUNCTION__, logging_module_name.AsCString(),
1316 process.GetUniqueID());
1318 // We need to try the enable here as well, which will succeed in the event
1319 // that we're attaching to (rather than launching) the process and the
1320 // process is already past initialization time. In that case, the completion
1321 // breakpoint will never get hit and therefore won't start that way. It
1322 // doesn't hurt much beyond a bit of bandwidth if we end up doing this twice.
1323 // It hurts much more if we don't get the logging enabled when the user
1328 // public destructor
1330 StructuredDataDarwinLog::~StructuredDataDarwinLog() {
1331 if (m_breakpoint_id != LLDB_INVALID_BREAK_ID) {
1332 ProcessSP process_sp(GetProcess());
1334 process_sp->GetTarget().RemoveBreakpointByID(m_breakpoint_id);
1335 m_breakpoint_id = LLDB_INVALID_BREAK_ID;
1341 #pragma mark Private instance methods
1343 // Private constructors
1345 StructuredDataDarwinLog::StructuredDataDarwinLog(const ProcessWP &process_wp)
1346 : StructuredDataPlugin(process_wp), m_recorded_first_timestamp(false),
1347 m_first_timestamp_seen(0), m_is_enabled(false),
1348 m_added_breakpoint_mutex(), m_added_breakpoint(),
1349 m_breakpoint_id(LLDB_INVALID_BREAK_ID) {}
1351 // Private static methods
1353 StructuredDataPluginSP
1354 StructuredDataDarwinLog::CreateInstance(Process &process) {
1355 // Currently only Apple targets support the os_log/os_activity protocol.
1356 if (process.GetTarget().GetArchitecture().GetTriple().getVendor() ==
1357 llvm::Triple::VendorType::Apple) {
1358 auto process_wp = ProcessWP(process.shared_from_this());
1359 return StructuredDataPluginSP(new StructuredDataDarwinLog(process_wp));
1361 return StructuredDataPluginSP();
1365 void StructuredDataDarwinLog::DebuggerInitialize(Debugger &debugger) {
1366 // Setup parent class first.
1367 StructuredDataPlugin::InitializeBasePluginForDebugger(debugger);
1369 // Get parent command.
1370 auto &interpreter = debugger.GetCommandInterpreter();
1371 llvm::StringRef parent_command_text = "plugin structured-data";
1372 auto parent_command =
1373 interpreter.GetCommandObjectForCommand(parent_command_text);
1374 if (!parent_command) {
1375 // Ut oh, parent failed to create parent command.
1380 auto command_name = "darwin-log";
1381 auto command_sp = CommandObjectSP(new BaseCommand(interpreter));
1382 bool result = parent_command->LoadSubCommand(command_name, command_sp);
1384 // TODO log it once we setup structured data logging
1387 if (!PluginManager::GetSettingForPlatformPlugin(
1388 debugger, StructuredDataDarwinLogProperties::GetSettingName())) {
1389 const bool is_global_setting = true;
1390 PluginManager::CreateSettingForStructuredDataPlugin(
1391 debugger, GetGlobalProperties()->GetValueProperties(),
1392 ConstString("Properties for the darwin-log"
1398 Status StructuredDataDarwinLog::FilterLaunchInfo(ProcessLaunchInfo &launch_info,
1402 // If we're not debugging this launched process, there's nothing for us to do
1404 if (!launch_info.GetFlags().AnySet(eLaunchFlagDebug))
1407 // Darwin os_log() support automatically adds debug-level and info-level
1408 // messages when a debugger is attached to a process. However, with
1409 // integrated support for debugging built into the command-line LLDB, the
1410 // user may specifically set to *not* include debug-level and info-level
1411 // content. When the user is using the integrated log support, we want to
1412 // put the kabosh on that automatic adding of info and debug level. This is
1413 // done by adding an environment variable to the process on launch. (This
1414 // also means it is not possible to suppress this behavior if attaching to an
1415 // already-running app).
1416 // Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
1418 // If the target architecture is not one that supports DarwinLog, we have
1419 // nothing to do here.
1420 auto &triple = target ? target->GetArchitecture().GetTriple()
1421 : launch_info.GetArchitecture().GetTriple();
1422 if (triple.getVendor() != llvm::Triple::Apple) {
1426 // If DarwinLog is not enabled (either by explicit user command or via the
1427 // auto-enable option), then we have nothing to do.
1428 if (!GetGlobalProperties()->GetEnableOnStartup() &&
1429 !s_is_explicitly_enabled) {
1430 // Nothing to do, DarwinLog is not enabled.
1434 // If we don't have parsed configuration info, that implies we have enable-
1435 // on-startup set up, but we haven't yet attempted to run the enable command.
1437 // We really can't do this without a target. We need to be able to get to
1438 // the debugger to get the proper options to do this right.
1440 error.SetErrorString("requires a target to auto-enable DarwinLog.");
1444 DebuggerSP debugger_sp = target->GetDebugger().shared_from_this();
1445 auto options_sp = GetGlobalEnableOptions(debugger_sp);
1446 if (!options_sp && debugger_sp) {
1447 options_sp = ParseAutoEnableOptions(error, *debugger_sp.get());
1448 if (!options_sp || !error.Success())
1451 // We already parsed the options, save them now so we don't generate them
1452 // again until the user runs the command manually.
1453 SetGlobalEnableOptions(debugger_sp, options_sp);
1456 if (!options_sp->GetEchoToStdErr()) {
1457 // The user doesn't want to see os_log/NSLog messages echo to stderr. That
1458 // mechanism is entirely separate from the DarwinLog support. By default we
1459 // don't want to get it via stderr, because that would be in duplicate of
1460 // the explicit log support here.
1462 // Here we need to strip out any OS_ACTIVITY_DT_MODE setting to prevent
1463 // echoing of os_log()/NSLog() to stderr in the target program.
1464 launch_info.GetEnvironment().erase("OS_ACTIVITY_DT_MODE");
1466 // We will also set the env var that tells any downstream launcher from
1467 // adding OS_ACTIVITY_DT_MODE.
1468 launch_info.GetEnvironment()["IDE_DISABLED_OS_ACTIVITY_DT_MODE"] = "1";
1471 // Set the OS_ACTIVITY_MODE env var appropriately to enable/disable debug and
1472 // info level messages.
1473 const char *env_var_value;
1474 if (options_sp->GetIncludeDebugLevel())
1475 env_var_value = "debug";
1476 else if (options_sp->GetIncludeInfoLevel())
1477 env_var_value = "info";
1479 env_var_value = "default";
1481 launch_info.GetEnvironment()["OS_ACTIVITY_MODE"] = env_var_value;
1486 bool StructuredDataDarwinLog::InitCompletionHookCallback(
1487 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
1488 lldb::user_id_t break_loc_id) {
1489 // We hit the init function. We now want to enqueue our new thread plan,
1490 // which will in turn enqueue a StepOut thread plan. When the StepOut
1491 // finishes and control returns to our new thread plan, that is the time when
1492 // we can execute our logic to enable the logging support.
1494 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1495 LLDB_LOGF(log, "StructuredDataDarwinLog::%s() called", __FUNCTION__);
1497 // Get the current thread.
1500 "StructuredDataDarwinLog::%s() warning: no context, "
1506 // Get the plugin from the process.
1507 auto process_sp = context->exe_ctx_ref.GetProcessSP();
1510 "StructuredDataDarwinLog::%s() warning: invalid "
1511 "process in context, ignoring",
1515 LLDB_LOGF(log, "StructuredDataDarwinLog::%s() call is for process uid %d",
1516 __FUNCTION__, process_sp->GetUniqueID());
1518 auto plugin_sp = process_sp->GetStructuredDataPlugin(GetDarwinLogTypeName());
1521 "StructuredDataDarwinLog::%s() warning: no plugin for "
1522 "feature %s in process uid %u",
1523 __FUNCTION__, GetDarwinLogTypeName().AsCString(),
1524 process_sp->GetUniqueID());
1528 // Create the callback for when the thread plan completes.
1529 bool called_enable_method = false;
1530 const auto process_uid = process_sp->GetUniqueID();
1532 std::weak_ptr<StructuredDataPlugin> plugin_wp(plugin_sp);
1533 ThreadPlanCallOnFunctionExit::Callback callback =
1534 [plugin_wp, &called_enable_method, log, process_uid]() {
1536 "StructuredDataDarwinLog::post-init callback: "
1537 "called (process uid %u)",
1540 auto strong_plugin_sp = plugin_wp.lock();
1541 if (!strong_plugin_sp) {
1543 "StructuredDataDarwinLog::post-init callback: "
1544 "plugin no longer exists, ignoring (process "
1549 // Make sure we only call it once, just in case the thread plan hits
1550 // the breakpoint twice.
1551 if (!called_enable_method) {
1553 "StructuredDataDarwinLog::post-init callback: "
1554 "calling EnableNow() (process uid %u)",
1556 static_cast<StructuredDataDarwinLog *>(strong_plugin_sp.get())
1558 called_enable_method = true;
1560 // Our breakpoint was hit more than once. Unexpected but no harm
1563 "StructuredDataDarwinLog::post-init callback: "
1564 "skipping EnableNow(), already called by "
1565 "callback [we hit this more than once] "
1571 // Grab the current thread.
1572 auto thread_sp = context->exe_ctx_ref.GetThreadSP();
1575 "StructuredDataDarwinLog::%s() warning: failed to "
1576 "retrieve the current thread from the execution "
1577 "context, nowhere to run the thread plan (process uid "
1579 __FUNCTION__, process_sp->GetUniqueID());
1583 // Queue the thread plan.
1584 auto thread_plan_sp =
1585 ThreadPlanSP(new ThreadPlanCallOnFunctionExit(*thread_sp, callback));
1586 const bool abort_other_plans = false;
1587 thread_sp->QueueThreadPlan(thread_plan_sp, abort_other_plans);
1589 "StructuredDataDarwinLog::%s() queuing thread plan on "
1590 "trace library init method entry (process uid %u)",
1591 __FUNCTION__, process_sp->GetUniqueID());
1593 // We return false here to indicate that it isn't a public stop.
1597 void StructuredDataDarwinLog::AddInitCompletionHook(Process &process) {
1598 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1599 LLDB_LOGF(log, "StructuredDataDarwinLog::%s() called (process uid %u)",
1600 __FUNCTION__, process.GetUniqueID());
1602 // Make sure we haven't already done this.
1604 std::lock_guard<std::mutex> locker(m_added_breakpoint_mutex);
1605 if (m_added_breakpoint) {
1607 "StructuredDataDarwinLog::%s() ignoring request, "
1608 "breakpoint already set (process uid %u)",
1609 __FUNCTION__, process.GetUniqueID());
1613 // We're about to do this, don't let anybody else try to do it.
1614 m_added_breakpoint = true;
1617 // Set a breakpoint for the process that will kick in when libtrace has
1618 // finished its initialization.
1619 Target &target = process.GetTarget();
1621 // Build up the module list.
1622 FileSpecList module_spec_list;
1623 auto module_file_spec =
1624 FileSpec(GetGlobalProperties()->GetLoggingModuleName());
1625 module_spec_list.Append(module_file_spec);
1627 // We aren't specifying a source file set.
1628 FileSpecList *source_spec_list = nullptr;
1630 const char *func_name = "_libtrace_init";
1631 const lldb::addr_t offset = 0;
1632 const LazyBool skip_prologue = eLazyBoolCalculate;
1633 // This is an internal breakpoint - the user shouldn't see it.
1634 const bool internal = true;
1635 const bool hardware = false;
1637 auto breakpoint_sp = target.CreateBreakpoint(
1638 &module_spec_list, source_spec_list, func_name, eFunctionNameTypeFull,
1639 eLanguageTypeC, offset, skip_prologue, internal, hardware);
1640 if (!breakpoint_sp) {
1643 "StructuredDataDarwinLog::%s() failed to set "
1644 "breakpoint in module %s, function %s (process uid %u)",
1645 __FUNCTION__, GetGlobalProperties()->GetLoggingModuleName(),
1646 func_name, process.GetUniqueID());
1650 // Set our callback.
1651 breakpoint_sp->SetCallback(InitCompletionHookCallback, nullptr);
1652 m_breakpoint_id = breakpoint_sp->GetID();
1654 "StructuredDataDarwinLog::%s() breakpoint set in module %s,"
1655 "function %s (process uid %u)",
1656 __FUNCTION__, GetGlobalProperties()->GetLoggingModuleName(),
1657 func_name, process.GetUniqueID());
1660 void StructuredDataDarwinLog::DumpTimestamp(Stream &stream,
1661 uint64_t timestamp) {
1662 const uint64_t delta_nanos = timestamp - m_first_timestamp_seen;
1664 const uint64_t hours = delta_nanos / NANOS_PER_HOUR;
1665 uint64_t nanos_remaining = delta_nanos % NANOS_PER_HOUR;
1667 const uint64_t minutes = nanos_remaining / NANOS_PER_MINUTE;
1668 nanos_remaining = nanos_remaining % NANOS_PER_MINUTE;
1670 const uint64_t seconds = nanos_remaining / NANOS_PER_SECOND;
1671 nanos_remaining = nanos_remaining % NANOS_PER_SECOND;
1673 stream.Printf("%02" PRIu64 ":%02" PRIu64 ":%02" PRIu64 ".%09" PRIu64, hours,
1674 minutes, seconds, nanos_remaining);
1678 StructuredDataDarwinLog::DumpHeader(Stream &output_stream,
1679 const StructuredData::Dictionary &event) {
1680 StreamString stream;
1682 ProcessSP process_sp = GetProcess();
1688 DebuggerSP debugger_sp =
1689 process_sp->GetTarget().GetDebugger().shared_from_this();
1695 auto options_sp = GetGlobalEnableOptions(debugger_sp);
1701 // Check if we should even display a header.
1702 if (!options_sp->GetDisplayAnyHeaderFields())
1705 stream.PutChar('[');
1707 int header_count = 0;
1708 if (options_sp->GetDisplayTimestampRelative()) {
1709 uint64_t timestamp = 0;
1710 if (event.GetValueForKeyAsInteger("timestamp", timestamp)) {
1711 DumpTimestamp(stream, timestamp);
1716 if (options_sp->GetDisplayActivityChain()) {
1717 llvm::StringRef activity_chain;
1718 if (event.GetValueForKeyAsString("activity-chain", activity_chain) &&
1719 !activity_chain.empty()) {
1720 if (header_count > 0)
1721 stream.PutChar(',');
1723 // Display the activity chain, from parent-most to child-most activity,
1724 // separated by a colon (:).
1725 stream.PutCString("activity-chain=");
1726 stream.PutCString(activity_chain);
1731 if (options_sp->GetDisplaySubsystem()) {
1732 llvm::StringRef subsystem;
1733 if (event.GetValueForKeyAsString("subsystem", subsystem) &&
1734 !subsystem.empty()) {
1735 if (header_count > 0)
1736 stream.PutChar(',');
1737 stream.PutCString("subsystem=");
1738 stream.PutCString(subsystem);
1743 if (options_sp->GetDisplayCategory()) {
1744 llvm::StringRef category;
1745 if (event.GetValueForKeyAsString("category", category) &&
1746 !category.empty()) {
1747 if (header_count > 0)
1748 stream.PutChar(',');
1749 stream.PutCString("category=");
1750 stream.PutCString(category);
1754 stream.PutCString("] ");
1756 output_stream.PutCString(stream.GetString());
1758 return stream.GetSize();
1761 size_t StructuredDataDarwinLog::HandleDisplayOfEvent(
1762 const StructuredData::Dictionary &event, Stream &stream) {
1763 // Check the type of the event.
1764 ConstString event_type;
1765 if (!event.GetValueForKeyAsString("type", event_type)) {
1766 // Hmm, we expected to get events that describe what they are. Continue
1771 if (event_type != GetLogEventType())
1774 size_t total_bytes = 0;
1776 // Grab the message content.
1777 llvm::StringRef message;
1778 if (!event.GetValueForKeyAsString("message", message))
1781 // Display the log entry.
1782 const auto len = message.size();
1784 total_bytes += DumpHeader(stream, event);
1786 stream.Write(message.data(), len);
1789 // Add an end of line.
1790 stream.PutChar('\n');
1791 total_bytes += sizeof(char);
1796 void StructuredDataDarwinLog::EnableNow() {
1797 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1798 LLDB_LOGF(log, "StructuredDataDarwinLog::%s() called", __FUNCTION__);
1800 // Run the enable command.
1801 auto process_sp = GetProcess();
1805 "StructuredDataDarwinLog::%s() warning: failed to get "
1806 "valid process, skipping",
1810 LLDB_LOGF(log, "StructuredDataDarwinLog::%s() call is for process uid %u",
1811 __FUNCTION__, process_sp->GetUniqueID());
1813 // If we have configuration data, we can directly enable it now. Otherwise,
1814 // we need to run through the command interpreter to parse the auto-run
1815 // options (which is the only way we get here without having already-parsed
1816 // configuration data).
1817 DebuggerSP debugger_sp =
1818 process_sp->GetTarget().GetDebugger().shared_from_this();
1821 "StructuredDataDarwinLog::%s() warning: failed to get "
1822 "debugger shared pointer, skipping (process uid %u)",
1823 __FUNCTION__, process_sp->GetUniqueID());
1827 auto options_sp = GetGlobalEnableOptions(debugger_sp);
1829 // We haven't run the enable command yet. Just do that now, it'll take
1830 // care of the rest.
1831 auto &interpreter = debugger_sp->GetCommandInterpreter();
1832 const bool success = RunEnableCommand(interpreter);
1836 "StructuredDataDarwinLog::%s() ran enable command "
1837 "successfully for (process uid %u)",
1838 __FUNCTION__, process_sp->GetUniqueID());
1841 "StructuredDataDarwinLog::%s() error: running "
1842 "enable command failed (process uid %u)",
1843 __FUNCTION__, process_sp->GetUniqueID());
1845 // Report failures to the debugger error stream.
1846 auto error_stream_sp = debugger_sp->GetAsyncErrorStream();
1847 if (error_stream_sp) {
1848 error_stream_sp->Printf("failed to configure DarwinLog "
1850 error_stream_sp->Flush();
1855 // We've previously been enabled. We will re-enable now with the previously
1856 // specified options.
1857 auto config_sp = options_sp->BuildConfigurationData(true);
1860 "StructuredDataDarwinLog::%s() warning: failed to "
1861 "build configuration data for enable options, skipping "
1863 __FUNCTION__, process_sp->GetUniqueID());
1867 // We can run it directly.
1868 // Send configuration to the feature by way of the process.
1869 const Status error =
1870 process_sp->ConfigureStructuredData(GetDarwinLogTypeName(), config_sp);
1873 if (!error.Success()) {
1875 "StructuredDataDarwinLog::%s() "
1876 "ConfigureStructuredData() call failed "
1877 "(process uid %u): %s",
1878 __FUNCTION__, process_sp->GetUniqueID(), error.AsCString());
1879 auto error_stream_sp = debugger_sp->GetAsyncErrorStream();
1880 if (error_stream_sp) {
1881 error_stream_sp->Printf("failed to configure DarwinLog "
1884 error_stream_sp->Flush();
1886 m_is_enabled = false;
1888 m_is_enabled = true;
1890 "StructuredDataDarwinLog::%s() success via direct "
1891 "configuration (process uid %u)",
1892 __FUNCTION__, process_sp->GetUniqueID());