1 //===-- StructuredDataDarwinLog.cpp -----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "StructuredDataDarwinLog.h"
18 #include "lldb/Breakpoint/StoppointCallbackContext.h"
19 #include "lldb/Core/Debugger.h"
20 #include "lldb/Core/Module.h"
21 #include "lldb/Core/PluginManager.h"
22 #include "lldb/Host/OptionParser.h"
23 #include "lldb/Interpreter/CommandInterpreter.h"
24 #include "lldb/Interpreter/CommandObjectMultiword.h"
25 #include "lldb/Interpreter/CommandReturnObject.h"
26 #include "lldb/Interpreter/OptionArgParser.h"
27 #include "lldb/Interpreter/OptionValueProperties.h"
28 #include "lldb/Interpreter/OptionValueString.h"
29 #include "lldb/Interpreter/Property.h"
30 #include "lldb/Target/Process.h"
31 #include "lldb/Target/Target.h"
32 #include "lldb/Target/ThreadPlanCallOnFunctionExit.h"
33 #include "lldb/Utility/Log.h"
34 #include "lldb/Utility/RegularExpression.h"
36 #define DARWIN_LOG_TYPE_VALUE "DarwinLog"
39 using namespace lldb_private;
42 #pragma mark Anonymous Namespace
44 // -----------------------------------------------------------------------------
45 // Anonymous namespace
46 // -----------------------------------------------------------------------------
48 namespace sddarwinlog_private {
49 const uint64_t NANOS_PER_MICRO = 1000;
50 const uint64_t NANOS_PER_MILLI = NANOS_PER_MICRO * 1000;
51 const uint64_t NANOS_PER_SECOND = NANOS_PER_MILLI * 1000;
52 const uint64_t NANOS_PER_MINUTE = NANOS_PER_SECOND * 60;
53 const uint64_t NANOS_PER_HOUR = NANOS_PER_MINUTE * 60;
55 static bool DEFAULT_FILTER_FALLTHROUGH_ACCEPTS = true;
57 //------------------------------------------------------------------
58 /// Global, sticky enable switch. If true, the user has explicitly
59 /// run the enable command. When a process launches or is attached to,
60 /// we will enable DarwinLog if either the settings for auto-enable is
61 /// on, or if the user had explicitly run enable at some point prior
62 /// to the launch/attach.
63 //------------------------------------------------------------------
64 static bool s_is_explicitly_enabled;
67 using EnableOptionsSP = std::shared_ptr<EnableOptions>;
70 std::map<DebuggerWP, EnableOptionsSP, std::owner_less<DebuggerWP>>;
72 static OptionsMap &GetGlobalOptionsMap() {
73 static OptionsMap s_options_map;
77 static std::mutex &GetGlobalOptionsMapLock() {
78 static std::mutex s_options_map_lock;
79 return s_options_map_lock;
82 EnableOptionsSP GetGlobalEnableOptions(const DebuggerSP &debugger_sp) {
84 return EnableOptionsSP();
86 std::lock_guard<std::mutex> locker(GetGlobalOptionsMapLock());
87 OptionsMap &options_map = GetGlobalOptionsMap();
88 DebuggerWP debugger_wp(debugger_sp);
89 auto find_it = options_map.find(debugger_wp);
90 if (find_it != options_map.end())
91 return find_it->second;
93 return EnableOptionsSP();
96 void SetGlobalEnableOptions(const DebuggerSP &debugger_sp,
97 const EnableOptionsSP &options_sp) {
98 std::lock_guard<std::mutex> locker(GetGlobalOptionsMapLock());
99 OptionsMap &options_map = GetGlobalOptionsMap();
100 DebuggerWP debugger_wp(debugger_sp);
101 auto find_it = options_map.find(debugger_wp);
102 if (find_it != options_map.end())
103 find_it->second = options_sp;
105 options_map.insert(std::make_pair(debugger_wp, options_sp));
109 #pragma mark Settings Handling
111 //------------------------------------------------------------------
112 /// Code to handle the StructuredDataDarwinLog settings
113 //------------------------------------------------------------------
115 static constexpr PropertyDefinition g_properties[] = {
117 "enable-on-startup", // name
118 OptionValue::eTypeBoolean, // type
120 false, // default uint value
121 nullptr, // default cstring value
123 "Enable Darwin os_log collection when debugged process is launched "
124 "or attached." // description
127 "auto-enable-options", // name
128 OptionValue::eTypeString, // type
130 0, // default uint value
131 "", // default cstring value
133 "Specify the options to 'plugin structured-data darwin-log enable' "
134 "that should be applied when automatically enabling logging on "
135 "startup/attach." // description
138 enum { ePropertyEnableOnStartup = 0, ePropertyAutoEnableOptions = 1 };
140 class StructuredDataDarwinLogProperties : public Properties {
142 static ConstString &GetSettingName() {
143 static ConstString g_setting_name("darwin-log");
144 return g_setting_name;
147 StructuredDataDarwinLogProperties() : Properties() {
148 m_collection_sp.reset(new OptionValueProperties(GetSettingName()));
149 m_collection_sp->Initialize(g_properties);
152 virtual ~StructuredDataDarwinLogProperties() {}
154 bool GetEnableOnStartup() const {
155 const uint32_t idx = ePropertyEnableOnStartup;
156 return m_collection_sp->GetPropertyAtIndexAsBoolean(
157 nullptr, idx, g_properties[idx].default_uint_value != 0);
160 llvm::StringRef GetAutoEnableOptions() const {
161 const uint32_t idx = ePropertyAutoEnableOptions;
162 return m_collection_sp->GetPropertyAtIndexAsString(
163 nullptr, idx, g_properties[idx].default_cstr_value);
166 const char *GetLoggingModuleName() const { return "libsystem_trace.dylib"; }
169 using StructuredDataDarwinLogPropertiesSP =
170 std::shared_ptr<StructuredDataDarwinLogProperties>;
172 static const StructuredDataDarwinLogPropertiesSP &GetGlobalProperties() {
173 static StructuredDataDarwinLogPropertiesSP g_settings_sp;
175 g_settings_sp.reset(new StructuredDataDarwinLogProperties());
176 return g_settings_sp;
179 const char *const s_filter_attributes[] = {
180 "activity", // current activity
181 "activity-chain", // entire activity chain, each level separated by ':'
182 "category", // category of the log message
183 "message", // message contents, fully expanded
184 "subsystem" // subsystem of the log message
186 // Consider implementing this action as it would be cheaper to filter.
187 // "message" requires always formatting the message, which is a waste of
188 // cycles if it ends up being rejected. "format", // format string
189 // used to format message text
192 static const ConstString &GetDarwinLogTypeName() {
193 static const ConstString s_key_name("DarwinLog");
197 static const ConstString &GetLogEventType() {
198 static const ConstString s_event_type("log");
203 using FilterRuleSP = std::shared_ptr<FilterRule>;
207 virtual ~FilterRule() {}
209 using OperationCreationFunc =
210 std::function<FilterRuleSP(bool accept, size_t attribute_index,
211 const std::string &op_arg, Status &error)>;
213 static void RegisterOperation(const ConstString &operation,
214 const OperationCreationFunc &creation_func) {
215 GetCreationFuncMap().insert(std::make_pair(operation, creation_func));
218 static FilterRuleSP CreateRule(bool match_accepts, size_t attribute,
219 const ConstString &operation,
220 const std::string &op_arg, Status &error) {
221 // Find the creation func for this type of filter rule.
222 auto map = GetCreationFuncMap();
223 auto find_it = map.find(operation);
224 if (find_it == map.end()) {
225 error.SetErrorStringWithFormat("unknown filter operation \""
227 operation.GetCString());
228 return FilterRuleSP();
231 return find_it->second(match_accepts, attribute, op_arg, error);
234 StructuredData::ObjectSP Serialize() const {
235 StructuredData::Dictionary *dict_p = new StructuredData::Dictionary();
237 // Indicate whether this is an accept or reject rule.
238 dict_p->AddBooleanItem("accept", m_accept);
240 // Indicate which attribute of the message this filter references. This can
241 // drop into the rule-specific DoSerialization if we get to the point where
242 // not all FilterRule derived classes work on an attribute. (e.g. logical
243 // and/or and other compound operations).
244 dict_p->AddStringItem("attribute", s_filter_attributes[m_attribute_index]);
246 // Indicate the type of the rule.
247 dict_p->AddStringItem("type", GetOperationType().GetCString());
249 // Let the rule add its own specific details here.
250 DoSerialization(*dict_p);
252 return StructuredData::ObjectSP(dict_p);
255 virtual void Dump(Stream &stream) const = 0;
257 const ConstString &GetOperationType() const { return m_operation; }
260 FilterRule(bool accept, size_t attribute_index, const ConstString &operation)
261 : m_accept(accept), m_attribute_index(attribute_index),
262 m_operation(operation) {}
264 virtual void DoSerialization(StructuredData::Dictionary &dict) const = 0;
266 bool GetMatchAccepts() const { return m_accept; }
268 const char *GetFilterAttribute() const {
269 return s_filter_attributes[m_attribute_index];
273 using CreationFuncMap = std::map<ConstString, OperationCreationFunc>;
275 static CreationFuncMap &GetCreationFuncMap() {
276 static CreationFuncMap s_map;
281 const size_t m_attribute_index;
282 const ConstString m_operation;
285 using FilterRules = std::vector<FilterRuleSP>;
287 class RegexFilterRule : public FilterRule {
289 static void RegisterOperation() {
290 FilterRule::RegisterOperation(StaticGetOperation(), CreateOperation);
293 void Dump(Stream &stream) const override {
294 stream.Printf("%s %s regex %s", GetMatchAccepts() ? "accept" : "reject",
295 GetFilterAttribute(), m_regex_text.c_str());
299 void DoSerialization(StructuredData::Dictionary &dict) const override {
300 dict.AddStringItem("regex", m_regex_text);
304 static FilterRuleSP CreateOperation(bool accept, size_t attribute_index,
305 const std::string &op_arg,
307 // We treat the op_arg as a regex. Validate it.
308 if (op_arg.empty()) {
309 error.SetErrorString("regex filter type requires a regex "
311 return FilterRuleSP();
314 // Instantiate the regex so we can report any errors.
315 auto regex = RegularExpression(op_arg);
316 if (!regex.IsValid()) {
317 char error_text[256];
318 error_text[0] = '\0';
319 regex.GetErrorAsCString(error_text, sizeof(error_text));
320 error.SetErrorString(error_text);
321 return FilterRuleSP();
324 // We passed all our checks, this appears fine.
326 return FilterRuleSP(new RegexFilterRule(accept, attribute_index, op_arg));
329 static const ConstString &StaticGetOperation() {
330 static ConstString s_operation("regex");
334 RegexFilterRule(bool accept, size_t attribute_index,
335 const std::string ®ex_text)
336 : FilterRule(accept, attribute_index, StaticGetOperation()),
337 m_regex_text(regex_text) {}
339 const std::string m_regex_text;
342 class ExactMatchFilterRule : public FilterRule {
344 static void RegisterOperation() {
345 FilterRule::RegisterOperation(StaticGetOperation(), CreateOperation);
348 void Dump(Stream &stream) const override {
349 stream.Printf("%s %s match %s", GetMatchAccepts() ? "accept" : "reject",
350 GetFilterAttribute(), m_match_text.c_str());
354 void DoSerialization(StructuredData::Dictionary &dict) const override {
355 dict.AddStringItem("exact_text", m_match_text);
359 static FilterRuleSP CreateOperation(bool accept, size_t attribute_index,
360 const std::string &op_arg,
362 if (op_arg.empty()) {
363 error.SetErrorString("exact match filter type requires an "
364 "argument containing the text that must "
365 "match the specified message attribute.");
366 return FilterRuleSP();
371 new ExactMatchFilterRule(accept, attribute_index, op_arg));
374 static const ConstString &StaticGetOperation() {
375 static ConstString s_operation("match");
379 ExactMatchFilterRule(bool accept, size_t attribute_index,
380 const std::string &match_text)
381 : FilterRule(accept, attribute_index, StaticGetOperation()),
382 m_match_text(match_text) {}
384 const std::string m_match_text;
387 static void RegisterFilterOperations() {
388 ExactMatchFilterRule::RegisterOperation();
389 RegexFilterRule::RegisterOperation();
392 // =========================================================================
394 // =========================================================================
396 // -------------------------------------------------------------------------
397 /// Provides the main on-off switch for enabling darwin logging.
399 /// It is valid to run the enable command when logging is already enabled.
400 /// This resets the logging with whatever settings are currently set.
401 // -------------------------------------------------------------------------
403 static constexpr OptionDefinition g_enable_option_table[] = {
404 // Source stream include/exclude options (the first-level filter). This one
405 // should be made as small as possible as everything that goes through here
406 // must be processed by the process monitor.
407 {LLDB_OPT_SET_ALL, false, "any-process", 'a', OptionParser::eNoArgument,
408 nullptr, {}, 0, eArgTypeNone,
409 "Specifies log messages from other related processes should be "
411 {LLDB_OPT_SET_ALL, false, "debug", 'd', OptionParser::eNoArgument, nullptr,
413 "Specifies debug-level log messages should be included. Specifying"
414 " --debug implies --info."},
415 {LLDB_OPT_SET_ALL, false, "info", 'i', OptionParser::eNoArgument, nullptr,
417 "Specifies info-level log messages should be included."},
418 {LLDB_OPT_SET_ALL, false, "filter", 'f', OptionParser::eRequiredArgument,
419 nullptr, {}, 0, eArgRawInput,
420 // There doesn't appear to be a great way for me to have these multi-line,
421 // formatted tables in help. This looks mostly right but there are extra
422 // linefeeds added at seemingly random spots, and indentation isn't
423 // handled properly on those lines.
424 "Appends a filter rule to the log message filter chain. Multiple "
425 "rules may be added by specifying this option multiple times, "
426 "once per filter rule. Filter rules are processed in the order "
427 "they are specified, with the --no-match-accepts setting used "
428 "for any message that doesn't match one of the rules.\n"
430 " Filter spec format:\n"
432 " --filter \"{action} {attribute} {op}\"\n"
439 " activity | // message's most-derived activity\n"
440 " activity-chain | // message's {parent}:{child} activity\n"
441 " category | // message's category\n"
442 " message | // message's expanded contents\n"
443 " subsystem | // message's subsystem\n"
446 " match {exact-match-text} |\n"
447 " regex {search-regex}\n"
449 "The regex flavor used is the C++ std::regex ECMAScript format. "
450 "Prefer character classes like [[:digit:]] to \\d and the like, as "
451 "getting the backslashes escaped through properly is error-prone."},
452 {LLDB_OPT_SET_ALL, false, "live-stream", 'l',
453 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
454 "Specify whether logging events are live-streamed or buffered. "
455 "True indicates live streaming, false indicates buffered. The "
456 "default is true (live streaming). Live streaming will deliver "
457 "log messages with less delay, but buffered capture mode has less "
458 "of an observer effect."},
459 {LLDB_OPT_SET_ALL, false, "no-match-accepts", 'n',
460 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
461 "Specify whether a log message that doesn't match any filter rule "
462 "is accepted or rejected, where true indicates accept. The "
464 {LLDB_OPT_SET_ALL, false, "echo-to-stderr", 'e',
465 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
466 "Specify whether os_log()/NSLog() messages are echoed to the "
467 "target program's stderr. When DarwinLog is enabled, we shut off "
468 "the mirroring of os_log()/NSLog() to the program's stderr. "
469 "Setting this flag to true will restore the stderr mirroring."
470 "The default is false."},
471 {LLDB_OPT_SET_ALL, false, "broadcast-events", 'b',
472 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeBoolean,
473 "Specify if the plugin should broadcast events. Broadcasting "
474 "log events is a requirement for displaying the log entries in "
475 "LLDB command-line. It is also required if LLDB clients want to "
476 "process log events. The default is true."},
477 // Message formatting options
478 {LLDB_OPT_SET_ALL, false, "timestamp-relative", 'r',
479 OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone,
480 "Include timestamp in the message header when printing a log "
481 "message. The timestamp is relative to the first displayed "
483 {LLDB_OPT_SET_ALL, false, "subsystem", 's', OptionParser::eNoArgument,
484 nullptr, {}, 0, eArgTypeNone,
485 "Include the subsystem in the message header when displaying "
487 {LLDB_OPT_SET_ALL, false, "category", 'c', OptionParser::eNoArgument,
488 nullptr, {}, 0, eArgTypeNone,
489 "Include the category in the message header when displaying "
491 {LLDB_OPT_SET_ALL, false, "activity-chain", 'C', OptionParser::eNoArgument,
492 nullptr, {}, 0, eArgTypeNone,
493 "Include the activity parent-child chain in the message header "
494 "when displaying a log message. The activity hierarchy is "
495 "displayed as {grandparent-activity}:"
496 "{parent-activity}:{activity}[:...]."},
497 {LLDB_OPT_SET_ALL, false, "all-fields", 'A', OptionParser::eNoArgument,
498 nullptr, {}, 0, eArgTypeNone,
499 "Shortcut to specify that all header fields should be displayed."}};
501 class EnableOptions : public Options {
504 : Options(), m_include_debug_level(false), m_include_info_level(false),
505 m_include_any_process(false),
506 m_filter_fall_through_accepts(DEFAULT_FILTER_FALLTHROUGH_ACCEPTS),
507 m_echo_to_stderr(false), m_display_timestamp_relative(false),
508 m_display_subsystem(false), m_display_category(false),
509 m_display_activity_chain(false), m_broadcast_events(true),
510 m_live_stream(true), m_filter_rules() {}
512 void OptionParsingStarting(ExecutionContext *execution_context) override {
513 m_include_debug_level = false;
514 m_include_info_level = false;
515 m_include_any_process = false;
516 m_filter_fall_through_accepts = DEFAULT_FILTER_FALLTHROUGH_ACCEPTS;
517 m_echo_to_stderr = false;
518 m_display_timestamp_relative = false;
519 m_display_subsystem = false;
520 m_display_category = false;
521 m_display_activity_chain = false;
522 m_broadcast_events = true;
523 m_live_stream = true;
524 m_filter_rules.clear();
527 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
528 ExecutionContext *execution_context) override {
531 const int short_option = m_getopt_table[option_idx].val;
532 switch (short_option) {
534 m_include_any_process = true;
538 m_display_timestamp_relative = true;
539 m_display_category = true;
540 m_display_subsystem = true;
541 m_display_activity_chain = true;
546 OptionArgParser::ToBoolean(option_arg, true, nullptr);
550 m_display_category = true;
554 m_display_activity_chain = true;
558 m_include_debug_level = true;
562 m_echo_to_stderr = OptionArgParser::ToBoolean(option_arg, false, nullptr);
566 return ParseFilterRule(option_arg);
569 m_include_info_level = true;
573 m_live_stream = OptionArgParser::ToBoolean(option_arg, false, nullptr);
577 m_filter_fall_through_accepts =
578 OptionArgParser::ToBoolean(option_arg, true, nullptr);
582 m_display_timestamp_relative = true;
586 m_display_subsystem = true;
590 error.SetErrorStringWithFormat("unsupported option '%c'", short_option);
595 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
596 return llvm::makeArrayRef(g_enable_option_table);
599 StructuredData::DictionarySP BuildConfigurationData(bool enabled) {
600 StructuredData::DictionarySP config_sp(new StructuredData::Dictionary());
602 // Set the basic enabled state.
603 config_sp->AddBooleanItem("enabled", enabled);
605 // If we're disabled, there's nothing more to add.
609 // Handle source stream flags.
610 auto source_flags_sp =
611 StructuredData::DictionarySP(new StructuredData::Dictionary());
612 config_sp->AddItem("source-flags", source_flags_sp);
614 source_flags_sp->AddBooleanItem("any-process", m_include_any_process);
615 source_flags_sp->AddBooleanItem("debug-level", m_include_debug_level);
616 // The debug-level flag, if set, implies info-level.
617 source_flags_sp->AddBooleanItem("info-level", m_include_info_level ||
618 m_include_debug_level);
619 source_flags_sp->AddBooleanItem("live-stream", m_live_stream);
621 // Specify default filter rule (the fall-through)
622 config_sp->AddBooleanItem("filter-fall-through-accepts",
623 m_filter_fall_through_accepts);
625 // Handle filter rules
626 if (!m_filter_rules.empty()) {
627 auto json_filter_rules_sp =
628 StructuredData::ArraySP(new StructuredData::Array);
629 config_sp->AddItem("filter-rules", json_filter_rules_sp);
630 for (auto &rule_sp : m_filter_rules) {
633 json_filter_rules_sp->AddItem(rule_sp->Serialize());
639 bool GetIncludeDebugLevel() const { return m_include_debug_level; }
641 bool GetIncludeInfoLevel() const {
642 // Specifying debug level implies info level.
643 return m_include_info_level || m_include_debug_level;
646 const FilterRules &GetFilterRules() const { return m_filter_rules; }
648 bool GetFallthroughAccepts() const { return m_filter_fall_through_accepts; }
650 bool GetEchoToStdErr() const { return m_echo_to_stderr; }
652 bool GetDisplayTimestampRelative() const {
653 return m_display_timestamp_relative;
656 bool GetDisplaySubsystem() const { return m_display_subsystem; }
657 bool GetDisplayCategory() const { return m_display_category; }
658 bool GetDisplayActivityChain() const { return m_display_activity_chain; }
660 bool GetDisplayAnyHeaderFields() const {
661 return m_display_timestamp_relative || m_display_activity_chain ||
662 m_display_subsystem || m_display_category;
665 bool GetBroadcastEvents() const { return m_broadcast_events; }
668 Status ParseFilterRule(llvm::StringRef rule_text) {
671 if (rule_text.empty()) {
672 error.SetErrorString("invalid rule_text");
676 // filter spec format:
678 // {action} {attribute} {op}
693 // match {exact-match-text} |
694 // regex {search-regex}
697 auto action_end_pos = rule_text.find(" ");
698 if (action_end_pos == std::string::npos) {
699 error.SetErrorStringWithFormat("could not parse filter rule "
700 "action from \"%s\"",
701 rule_text.str().c_str());
704 auto action = rule_text.substr(0, action_end_pos);
706 if (action == "accept")
708 else if (action == "reject")
711 error.SetErrorString("filter action must be \"accept\" or \"deny\"");
716 auto attribute_end_pos = rule_text.find(" ", action_end_pos + 1);
717 if (attribute_end_pos == std::string::npos) {
718 error.SetErrorStringWithFormat("could not parse filter rule "
719 "attribute from \"%s\"",
720 rule_text.str().c_str());
723 auto attribute = rule_text.substr(action_end_pos + 1,
724 attribute_end_pos - (action_end_pos + 1));
725 auto attribute_index = MatchAttributeIndex(attribute);
726 if (attribute_index < 0) {
727 error.SetErrorStringWithFormat("filter rule attribute unknown: "
729 attribute.str().c_str());
734 auto operation_end_pos = rule_text.find(" ", attribute_end_pos + 1);
735 auto operation = rule_text.substr(
736 attribute_end_pos + 1, operation_end_pos - (attribute_end_pos + 1));
740 FilterRule::CreateRule(accept, attribute_index, ConstString(operation),
741 rule_text.substr(operation_end_pos + 1), error);
743 if (rule_sp && error.Success())
744 m_filter_rules.push_back(rule_sp);
749 int MatchAttributeIndex(llvm::StringRef attribute_name) const {
750 for (const auto &Item : llvm::enumerate(s_filter_attributes)) {
751 if (attribute_name == Item.value())
755 // We didn't match anything.
759 bool m_include_debug_level;
760 bool m_include_info_level;
761 bool m_include_any_process;
762 bool m_filter_fall_through_accepts;
763 bool m_echo_to_stderr;
764 bool m_display_timestamp_relative;
765 bool m_display_subsystem;
766 bool m_display_category;
767 bool m_display_activity_chain;
768 bool m_broadcast_events;
770 FilterRules m_filter_rules;
773 class EnableCommand : public CommandObjectParsed {
775 EnableCommand(CommandInterpreter &interpreter, bool enable, const char *name,
776 const char *help, const char *syntax)
777 : CommandObjectParsed(interpreter, name, help, syntax), m_enable(enable),
778 m_options_sp(enable ? new EnableOptions() : nullptr) {}
781 void AppendStrictSourcesWarning(CommandReturnObject &result,
782 const char *source_name) {
786 // Check if we're *not* using strict sources. If not, then the user is
787 // going to get debug-level info anyways, probably not what they're
788 // expecting. Unfortunately we can only fix this by adding an env var,
789 // which would have had to have happened already. Thus, a warning is the
790 // best we can do here.
792 stream.Printf("darwin-log source settings specify to exclude "
793 "%s messages, but setting "
794 "'plugin.structured-data.darwin-log."
795 "strict-sources' is disabled. This process will "
796 "automatically have %s messages included. Enable"
797 " the property and relaunch the target binary to have"
798 " these messages excluded.",
799 source_name, source_name);
800 result.AppendWarning(stream.GetString());
803 bool DoExecute(Args &command, CommandReturnObject &result) override {
804 // First off, set the global sticky state of enable/disable based on this
805 // command execution.
806 s_is_explicitly_enabled = m_enable;
808 // Next, if this is an enable, save off the option data. We will need it
809 // later if a process hasn't been launched or attached yet.
811 // Save off enabled configuration so we can apply these parsed options
812 // the next time an attach or launch occurs.
813 DebuggerSP debugger_sp =
814 GetCommandInterpreter().GetDebugger().shared_from_this();
815 SetGlobalEnableOptions(debugger_sp, m_options_sp);
818 // Now check if we have a running process. If so, we should instruct the
819 // process monitor to enable/disable DarwinLog support now.
820 Target *target = GetSelectedOrDummyTarget();
822 // No target, so there is nothing more to do right now.
823 result.SetStatus(eReturnStatusSuccessFinishNoResult);
827 // Grab the active process.
828 auto process_sp = target->GetProcessSP();
830 // No active process, so there is nothing more to do right now.
831 result.SetStatus(eReturnStatusSuccessFinishNoResult);
835 // If the process is no longer alive, we can't do this now. We'll catch it
836 // the next time the process is started up.
837 if (!process_sp->IsAlive()) {
838 result.SetStatus(eReturnStatusSuccessFinishNoResult);
842 // Get the plugin for the process.
844 process_sp->GetStructuredDataPlugin(GetDarwinLogTypeName());
845 if (!plugin_sp || (plugin_sp->GetPluginName() !=
846 StructuredDataDarwinLog::GetStaticPluginName())) {
847 result.AppendError("failed to get StructuredDataPlugin for "
849 result.SetStatus(eReturnStatusFailed);
851 StructuredDataDarwinLog &plugin =
852 *static_cast<StructuredDataDarwinLog *>(plugin_sp.get());
855 // Hook up the breakpoint for the process that detects when libtrace has
856 // been sufficiently initialized to really start the os_log stream. This
857 // is insurance to assure us that logging is really enabled. Requesting
858 // that logging be enabled for a process before libtrace is initialized
859 // results in a scenario where no errors occur, but no logging is
860 // captured, either. This step is to eliminate that possibility.
861 plugin.AddInitCompletionHook(*process_sp.get());
864 // Send configuration to the feature by way of the process. Construct the
865 // options we will use.
866 auto config_sp = m_options_sp->BuildConfigurationData(m_enable);
868 process_sp->ConfigureStructuredData(GetDarwinLogTypeName(), config_sp);
871 if (!error.Success()) {
872 result.AppendError(error.AsCString());
873 result.SetStatus(eReturnStatusFailed);
874 // Our configuration failed, so we're definitely disabled.
875 plugin.SetEnabled(false);
877 result.SetStatus(eReturnStatusSuccessFinishNoResult);
878 // Our configuration succeeded, so we're enabled/disabled per whichever
879 // one this command is setup to do.
880 plugin.SetEnabled(m_enable);
882 return result.Succeeded();
885 Options *GetOptions() override {
886 // We don't have options when this represents disable.
887 return m_enable ? m_options_sp.get() : nullptr;
892 EnableOptionsSP m_options_sp;
895 // -------------------------------------------------------------------------
896 /// Provides the status command.
897 // -------------------------------------------------------------------------
898 class StatusCommand : public CommandObjectParsed {
900 StatusCommand(CommandInterpreter &interpreter)
901 : CommandObjectParsed(interpreter, "status",
902 "Show whether Darwin log supported is available"
904 "plugin structured-data darwin-log status") {}
907 bool DoExecute(Args &command, CommandReturnObject &result) override {
908 auto &stream = result.GetOutputStream();
910 // Figure out if we've got a process. If so, we can tell if DarwinLog is
911 // available for that process.
912 Target *target = GetSelectedOrDummyTarget();
913 auto process_sp = target ? target->GetProcessSP() : ProcessSP();
914 if (!target || !process_sp) {
915 stream.PutCString("Availability: unknown (requires process)\n");
916 stream.PutCString("Enabled: not applicable "
917 "(requires process)\n");
920 process_sp->GetStructuredDataPlugin(GetDarwinLogTypeName());
921 stream.Printf("Availability: %s\n",
922 plugin_sp ? "available" : "unavailable");
923 auto &plugin_name = StructuredDataDarwinLog::GetStaticPluginName();
925 plugin_sp ? plugin_sp->GetEnabled(plugin_name) : false;
926 stream.Printf("Enabled: %s\n", enabled ? "true" : "false");
929 // Display filter settings.
930 DebuggerSP debugger_sp =
931 GetCommandInterpreter().GetDebugger().shared_from_this();
932 auto options_sp = GetGlobalEnableOptions(debugger_sp);
934 // Nothing more to do.
935 result.SetStatus(eReturnStatusSuccessFinishResult);
939 // Print filter rules
940 stream.PutCString("DarwinLog filter rules:\n");
944 if (options_sp->GetFilterRules().empty()) {
946 stream.PutCString("none\n");
948 // Print each of the filter rules.
950 for (auto rule_sp : options_sp->GetFilterRules()) {
956 stream.Printf("%02d: ", rule_number);
957 rule_sp->Dump(stream);
958 stream.PutChar('\n');
963 // Print no-match handling.
965 stream.Printf("no-match behavior: %s\n",
966 options_sp->GetFallthroughAccepts() ? "accept" : "reject");
968 result.SetStatus(eReturnStatusSuccessFinishResult);
973 // -------------------------------------------------------------------------
974 /// Provides the darwin-log base command
975 // -------------------------------------------------------------------------
976 class BaseCommand : public CommandObjectMultiword {
978 BaseCommand(CommandInterpreter &interpreter)
979 : CommandObjectMultiword(interpreter, "plugin structured-data darwin-log",
980 "Commands for configuring Darwin os_log "
984 auto enable_help = "Enable Darwin log collection, or re-enable "
985 "with modified configuration.";
986 auto enable_syntax = "plugin structured-data darwin-log enable";
987 auto enable_cmd_sp = CommandObjectSP(
988 new EnableCommand(interpreter,
990 "enable", enable_help, enable_syntax));
991 LoadSubCommand("enable", enable_cmd_sp);
994 auto disable_help = "Disable Darwin log collection.";
995 auto disable_syntax = "plugin structured-data darwin-log disable";
996 auto disable_cmd_sp = CommandObjectSP(
997 new EnableCommand(interpreter,
999 "disable", disable_help, disable_syntax));
1000 LoadSubCommand("disable", disable_cmd_sp);
1003 auto status_cmd_sp = CommandObjectSP(new StatusCommand(interpreter));
1004 LoadSubCommand("status", status_cmd_sp);
1008 EnableOptionsSP ParseAutoEnableOptions(Status &error, Debugger &debugger) {
1009 Log *log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS);
1010 // We are abusing the options data model here so that we can parse options
1011 // without requiring the Debugger instance.
1013 // We have an empty execution context at this point. We only want to parse
1014 // options, and we don't need any context to do this here. In fact, we want
1015 // to be able to parse the enable options before having any context.
1016 ExecutionContext exe_ctx;
1018 EnableOptionsSP options_sp(new EnableOptions());
1019 options_sp->NotifyOptionParsingStarting(&exe_ctx);
1021 CommandReturnObject result;
1023 // Parse the arguments.
1024 auto options_property_sp =
1025 debugger.GetPropertyValue(nullptr, "plugin.structured-data.darwin-log."
1026 "auto-enable-options",
1028 if (!error.Success())
1029 return EnableOptionsSP();
1030 if (!options_property_sp) {
1031 error.SetErrorString("failed to find option setting for "
1032 "plugin.structured-data.darwin-log.");
1033 return EnableOptionsSP();
1036 const char *enable_options =
1037 options_property_sp->GetAsString()->GetCurrentValue();
1038 Args args(enable_options);
1039 if (args.GetArgumentCount() > 0) {
1040 // Eliminate the initial '--' that would be required to set the settings
1041 // that themselves include '-' and/or '--'.
1042 const char *first_arg = args.GetArgumentAtIndex(0);
1043 if (first_arg && (strcmp(first_arg, "--") == 0))
1047 bool require_validation = false;
1048 llvm::Expected<Args> args_or =
1049 options_sp->Parse(args, &exe_ctx, PlatformSP(), require_validation);
1052 log, args_or.takeError(),
1053 "Parsing plugin.structured-data.darwin-log.auto-enable-options value "
1055 return EnableOptionsSP();
1058 if (!options_sp->VerifyOptions(result))
1059 return EnableOptionsSP();
1061 // We successfully parsed and validated the options.
1065 bool RunEnableCommand(CommandInterpreter &interpreter) {
1066 StreamString command_stream;
1068 command_stream << "plugin structured-data darwin-log enable";
1069 auto enable_options = GetGlobalProperties()->GetAutoEnableOptions();
1070 if (!enable_options.empty()) {
1071 command_stream << ' ';
1072 command_stream << enable_options;
1076 CommandReturnObject return_object;
1077 interpreter.HandleCommand(command_stream.GetData(), eLazyBoolNo,
1079 return return_object.Succeeded();
1082 using namespace sddarwinlog_private;
1085 #pragma mark Public static API
1087 // -----------------------------------------------------------------------------
1088 // Public static API
1089 // -----------------------------------------------------------------------------
1091 void StructuredDataDarwinLog::Initialize() {
1092 RegisterFilterOperations();
1093 PluginManager::RegisterPlugin(
1094 GetStaticPluginName(), "Darwin os_log() and os_activity() support",
1095 &CreateInstance, &DebuggerInitialize, &FilterLaunchInfo);
1098 void StructuredDataDarwinLog::Terminate() {
1099 PluginManager::UnregisterPlugin(&CreateInstance);
1102 const ConstString &StructuredDataDarwinLog::GetStaticPluginName() {
1103 static ConstString s_plugin_name("darwin-log");
1104 return s_plugin_name;
1108 #pragma mark PluginInterface API
1110 // -----------------------------------------------------------------------------
1111 // PluginInterface API
1112 // -----------------------------------------------------------------------------
1114 ConstString StructuredDataDarwinLog::GetPluginName() {
1115 return GetStaticPluginName();
1118 uint32_t StructuredDataDarwinLog::GetPluginVersion() { return 1; }
1121 #pragma mark StructuredDataPlugin API
1123 // -----------------------------------------------------------------------------
1124 // StructuredDataPlugin API
1125 // -----------------------------------------------------------------------------
1127 bool StructuredDataDarwinLog::SupportsStructuredDataType(
1128 const ConstString &type_name) {
1129 return type_name == GetDarwinLogTypeName();
1132 void StructuredDataDarwinLog::HandleArrivalOfStructuredData(
1133 Process &process, const ConstString &type_name,
1134 const StructuredData::ObjectSP &object_sp) {
1135 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1137 StreamString json_stream;
1139 object_sp->Dump(json_stream);
1141 json_stream.PutCString("<null>");
1142 log->Printf("StructuredDataDarwinLog::%s() called with json: %s",
1143 __FUNCTION__, json_stream.GetData());
1146 // Ignore empty structured data.
1149 log->Printf("StructuredDataDarwinLog::%s() StructuredData object "
1155 // Ignore any data that isn't for us.
1156 if (type_name != GetDarwinLogTypeName()) {
1158 log->Printf("StructuredDataDarwinLog::%s() StructuredData type "
1159 "expected to be %s but was %s, ignoring",
1160 __FUNCTION__, GetDarwinLogTypeName().AsCString(),
1161 type_name.AsCString());
1165 // Broadcast the structured data event if we have that enabled. This is the
1166 // way that the outside world (all clients) get access to this data. This
1167 // plugin sets policy as to whether we do that.
1168 DebuggerSP debugger_sp = process.GetTarget().GetDebugger().shared_from_this();
1169 auto options_sp = GetGlobalEnableOptions(debugger_sp);
1170 if (options_sp && options_sp->GetBroadcastEvents()) {
1172 log->Printf("StructuredDataDarwinLog::%s() broadcasting event",
1174 process.BroadcastStructuredData(object_sp, shared_from_this());
1177 // Later, hang on to a configurable amount of these and allow commands to
1178 // inspect, including showing backtraces.
1181 static void SetErrorWithJSON(Status &error, const char *message,
1182 StructuredData::Object &object) {
1184 error.SetErrorString("Internal error: message not set.");
1188 StreamString object_stream;
1189 object.Dump(object_stream);
1190 object_stream.Flush();
1192 error.SetErrorStringWithFormat("%s: %s", message, object_stream.GetData());
1195 Status StructuredDataDarwinLog::GetDescription(
1196 const StructuredData::ObjectSP &object_sp, lldb_private::Stream &stream) {
1200 error.SetErrorString("No structured data.");
1204 // Log message payload objects will be dictionaries.
1205 const StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
1207 SetErrorWithJSON(error, "Structured data should have been a dictionary "
1213 // Validate this is really a message for our plugin.
1214 ConstString type_name;
1215 if (!dictionary->GetValueForKeyAsString("type", type_name)) {
1216 SetErrorWithJSON(error, "Structured data doesn't contain mandatory "
1222 if (type_name != GetDarwinLogTypeName()) {
1223 // This is okay - it simply means the data we received is not a log
1224 // message. We'll just format it as is.
1225 object_sp->Dump(stream);
1229 // DarwinLog dictionaries store their data
1230 // in an array with key name "events".
1231 StructuredData::Array *events = nullptr;
1232 if (!dictionary->GetValueForKeyAsArray("events", events) || !events) {
1233 SetErrorWithJSON(error, "Log structured data is missing mandatory "
1234 "'events' field, expected to be an array",
1240 [&stream, &error, &object_sp, this](StructuredData::Object *object) {
1242 // Invalid. Stop iterating.
1243 SetErrorWithJSON(error, "Log event entry is null", *object_sp);
1247 auto event = object->GetAsDictionary();
1249 // Invalid, stop iterating.
1250 SetErrorWithJSON(error, "Log event is not a dictionary", *object_sp);
1254 // If we haven't already grabbed the first timestamp value, do that
1256 if (!m_recorded_first_timestamp) {
1257 uint64_t timestamp = 0;
1258 if (event->GetValueForKeyAsInteger("timestamp", timestamp)) {
1259 m_first_timestamp_seen = timestamp;
1260 m_recorded_first_timestamp = true;
1264 HandleDisplayOfEvent(*event, stream);
1272 bool StructuredDataDarwinLog::GetEnabled(const ConstString &type_name) const {
1273 if (type_name == GetStaticPluginName())
1274 return m_is_enabled;
1279 void StructuredDataDarwinLog::SetEnabled(bool enabled) {
1280 m_is_enabled = enabled;
1283 void StructuredDataDarwinLog::ModulesDidLoad(Process &process,
1284 ModuleList &module_list) {
1285 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1287 log->Printf("StructuredDataDarwinLog::%s called (process uid %u)",
1288 __FUNCTION__, process.GetUniqueID());
1290 // Check if we should enable the darwin log support on startup/attach.
1291 if (!GetGlobalProperties()->GetEnableOnStartup() &&
1292 !s_is_explicitly_enabled) {
1293 // We're neither auto-enabled or explicitly enabled, so we shouldn't try to
1296 log->Printf("StructuredDataDarwinLog::%s not applicable, we're not "
1297 "enabled (process uid %u)",
1298 __FUNCTION__, process.GetUniqueID());
1302 // If we already added the breakpoint, we've got nothing left to do.
1304 std::lock_guard<std::mutex> locker(m_added_breakpoint_mutex);
1305 if (m_added_breakpoint) {
1307 log->Printf("StructuredDataDarwinLog::%s process uid %u's "
1308 "post-libtrace-init breakpoint is already set",
1309 __FUNCTION__, process.GetUniqueID());
1314 // The logging support module name, specifies the name of the image name that
1315 // must be loaded into the debugged process before we can try to enable
1317 const char *logging_module_cstr =
1318 GetGlobalProperties()->GetLoggingModuleName();
1319 if (!logging_module_cstr || (logging_module_cstr[0] == 0)) {
1320 // We need this. Bail.
1322 log->Printf("StructuredDataDarwinLog::%s no logging module name "
1323 "specified, we don't know where to set a breakpoint "
1325 __FUNCTION__, process.GetUniqueID());
1329 const ConstString logging_module_name = ConstString(logging_module_cstr);
1331 // We need to see libtrace in the list of modules before we can enable
1332 // tracing for the target process.
1333 bool found_logging_support_module = false;
1334 for (size_t i = 0; i < module_list.GetSize(); ++i) {
1335 auto module_sp = module_list.GetModuleAtIndex(i);
1339 auto &file_spec = module_sp->GetFileSpec();
1340 found_logging_support_module =
1341 (file_spec.GetLastPathComponent() == logging_module_name);
1342 if (found_logging_support_module)
1346 if (!found_logging_support_module) {
1348 log->Printf("StructuredDataDarwinLog::%s logging module %s "
1349 "has not yet been loaded, can't set a breakpoint "
1350 "yet (process uid %u)",
1351 __FUNCTION__, logging_module_name.AsCString(),
1352 process.GetUniqueID());
1356 // Time to enqueue the breakpoint so we can wait for logging support to be
1357 // initialized before we try to tap the libtrace stream.
1358 AddInitCompletionHook(process);
1360 log->Printf("StructuredDataDarwinLog::%s post-init hook breakpoint "
1361 "set for logging module %s (process uid %u)",
1362 __FUNCTION__, logging_module_name.AsCString(),
1363 process.GetUniqueID());
1365 // We need to try the enable here as well, which will succeed in the event
1366 // that we're attaching to (rather than launching) the process and the
1367 // process is already past initialization time. In that case, the completion
1368 // breakpoint will never get hit and therefore won't start that way. It
1369 // doesn't hurt much beyond a bit of bandwidth if we end up doing this twice.
1370 // It hurts much more if we don't get the logging enabled when the user
1375 // -----------------------------------------------------------------------------
1376 // public destructor
1377 // -----------------------------------------------------------------------------
1379 StructuredDataDarwinLog::~StructuredDataDarwinLog() {
1380 if (m_breakpoint_id != LLDB_INVALID_BREAK_ID) {
1381 ProcessSP process_sp(GetProcess());
1383 process_sp->GetTarget().RemoveBreakpointByID(m_breakpoint_id);
1384 m_breakpoint_id = LLDB_INVALID_BREAK_ID;
1390 #pragma mark Private instance methods
1392 // -----------------------------------------------------------------------------
1393 // Private constructors
1394 // -----------------------------------------------------------------------------
1396 StructuredDataDarwinLog::StructuredDataDarwinLog(const ProcessWP &process_wp)
1397 : StructuredDataPlugin(process_wp), m_recorded_first_timestamp(false),
1398 m_first_timestamp_seen(0), m_is_enabled(false),
1399 m_added_breakpoint_mutex(), m_added_breakpoint(),
1400 m_breakpoint_id(LLDB_INVALID_BREAK_ID) {}
1402 // -----------------------------------------------------------------------------
1403 // Private static methods
1404 // -----------------------------------------------------------------------------
1406 StructuredDataPluginSP
1407 StructuredDataDarwinLog::CreateInstance(Process &process) {
1408 // Currently only Apple targets support the os_log/os_activity protocol.
1409 if (process.GetTarget().GetArchitecture().GetTriple().getVendor() ==
1410 llvm::Triple::VendorType::Apple) {
1411 auto process_wp = ProcessWP(process.shared_from_this());
1412 return StructuredDataPluginSP(new StructuredDataDarwinLog(process_wp));
1414 return StructuredDataPluginSP();
1418 void StructuredDataDarwinLog::DebuggerInitialize(Debugger &debugger) {
1419 // Setup parent class first.
1420 StructuredDataPlugin::InitializeBasePluginForDebugger(debugger);
1422 // Get parent command.
1423 auto &interpreter = debugger.GetCommandInterpreter();
1424 llvm::StringRef parent_command_text = "plugin structured-data";
1425 auto parent_command =
1426 interpreter.GetCommandObjectForCommand(parent_command_text);
1427 if (!parent_command) {
1428 // Ut oh, parent failed to create parent command.
1433 auto command_name = "darwin-log";
1434 auto command_sp = CommandObjectSP(new BaseCommand(interpreter));
1435 bool result = parent_command->LoadSubCommand(command_name, command_sp);
1437 // TODO log it once we setup structured data logging
1440 if (!PluginManager::GetSettingForPlatformPlugin(
1441 debugger, StructuredDataDarwinLogProperties::GetSettingName())) {
1442 const bool is_global_setting = true;
1443 PluginManager::CreateSettingForStructuredDataPlugin(
1444 debugger, GetGlobalProperties()->GetValueProperties(),
1445 ConstString("Properties for the darwin-log"
1451 Status StructuredDataDarwinLog::FilterLaunchInfo(ProcessLaunchInfo &launch_info,
1455 // If we're not debugging this launched process, there's nothing for us to do
1457 if (!launch_info.GetFlags().AnySet(eLaunchFlagDebug))
1460 // Darwin os_log() support automatically adds debug-level and info-level
1461 // messages when a debugger is attached to a process. However, with
1462 // integrated support for debugging built into the command-line LLDB, the
1463 // user may specifically set to *not* include debug-level and info-level
1464 // content. When the user is using the integrated log support, we want to
1465 // put the kabosh on that automatic adding of info and debug level. This is
1466 // done by adding an environment variable to the process on launch. (This
1467 // also means it is not possible to suppress this behavior if attaching to an
1468 // already-running app).
1469 // Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
1471 // If the target architecture is not one that supports DarwinLog, we have
1472 // nothing to do here.
1473 auto &triple = target ? target->GetArchitecture().GetTriple()
1474 : launch_info.GetArchitecture().GetTriple();
1475 if (triple.getVendor() != llvm::Triple::Apple) {
1479 // If DarwinLog is not enabled (either by explicit user command or via the
1480 // auto-enable option), then we have nothing to do.
1481 if (!GetGlobalProperties()->GetEnableOnStartup() &&
1482 !s_is_explicitly_enabled) {
1483 // Nothing to do, DarwinLog is not enabled.
1487 // If we don't have parsed configuration info, that implies we have enable-
1488 // on-startup set up, but we haven't yet attempted to run the enable command.
1490 // We really can't do this without a target. We need to be able to get to
1491 // the debugger to get the proper options to do this right.
1493 error.SetErrorString("requires a target to auto-enable DarwinLog.");
1497 DebuggerSP debugger_sp = target->GetDebugger().shared_from_this();
1498 auto options_sp = GetGlobalEnableOptions(debugger_sp);
1499 if (!options_sp && debugger_sp) {
1500 options_sp = ParseAutoEnableOptions(error, *debugger_sp.get());
1501 if (!options_sp || !error.Success())
1504 // We already parsed the options, save them now so we don't generate them
1505 // again until the user runs the command manually.
1506 SetGlobalEnableOptions(debugger_sp, options_sp);
1509 if (!options_sp->GetEchoToStdErr()) {
1510 // The user doesn't want to see os_log/NSLog messages echo to stderr. That
1511 // mechanism is entirely separate from the DarwinLog support. By default we
1512 // don't want to get it via stderr, because that would be in duplicate of
1513 // the explicit log support here.
1515 // Here we need to strip out any OS_ACTIVITY_DT_MODE setting to prevent
1516 // echoing of os_log()/NSLog() to stderr in the target program.
1517 launch_info.GetEnvironment().erase("OS_ACTIVITY_DT_MODE");
1519 // We will also set the env var that tells any downstream launcher from
1520 // adding OS_ACTIVITY_DT_MODE.
1521 launch_info.GetEnvironment()["IDE_DISABLED_OS_ACTIVITY_DT_MODE"] = "1";
1524 // Set the OS_ACTIVITY_MODE env var appropriately to enable/disable debug and
1525 // info level messages.
1526 const char *env_var_value;
1527 if (options_sp->GetIncludeDebugLevel())
1528 env_var_value = "debug";
1529 else if (options_sp->GetIncludeInfoLevel())
1530 env_var_value = "info";
1532 env_var_value = "default";
1534 launch_info.GetEnvironment()["OS_ACTIVITY_MODE"] = env_var_value;
1539 bool StructuredDataDarwinLog::InitCompletionHookCallback(
1540 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
1541 lldb::user_id_t break_loc_id) {
1542 // We hit the init function. We now want to enqueue our new thread plan,
1543 // which will in turn enqueue a StepOut thread plan. When the StepOut
1544 // finishes and control returns to our new thread plan, that is the time when
1545 // we can execute our logic to enable the logging support.
1547 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1549 log->Printf("StructuredDataDarwinLog::%s() called", __FUNCTION__);
1551 // Get the current thread.
1554 log->Printf("StructuredDataDarwinLog::%s() warning: no context, "
1560 // Get the plugin from the process.
1561 auto process_sp = context->exe_ctx_ref.GetProcessSP();
1564 log->Printf("StructuredDataDarwinLog::%s() warning: invalid "
1565 "process in context, ignoring",
1570 log->Printf("StructuredDataDarwinLog::%s() call is for process uid %d",
1571 __FUNCTION__, process_sp->GetUniqueID());
1573 auto plugin_sp = process_sp->GetStructuredDataPlugin(GetDarwinLogTypeName());
1576 log->Printf("StructuredDataDarwinLog::%s() warning: no plugin for "
1577 "feature %s in process uid %u",
1578 __FUNCTION__, GetDarwinLogTypeName().AsCString(),
1579 process_sp->GetUniqueID());
1583 // Create the callback for when the thread plan completes.
1584 bool called_enable_method = false;
1585 const auto process_uid = process_sp->GetUniqueID();
1587 std::weak_ptr<StructuredDataPlugin> plugin_wp(plugin_sp);
1588 ThreadPlanCallOnFunctionExit::Callback callback =
1589 [plugin_wp, &called_enable_method, log, process_uid]() {
1591 log->Printf("StructuredDataDarwinLog::post-init callback: "
1592 "called (process uid %u)",
1595 auto strong_plugin_sp = plugin_wp.lock();
1596 if (!strong_plugin_sp) {
1598 log->Printf("StructuredDataDarwinLog::post-init callback: "
1599 "plugin no longer exists, ignoring (process "
1604 // Make sure we only call it once, just in case the thread plan hits
1605 // the breakpoint twice.
1606 if (!called_enable_method) {
1608 log->Printf("StructuredDataDarwinLog::post-init callback: "
1609 "calling EnableNow() (process uid %u)",
1611 static_cast<StructuredDataDarwinLog *>(strong_plugin_sp.get())
1613 called_enable_method = true;
1615 // Our breakpoint was hit more than once. Unexpected but no harm
1618 log->Printf("StructuredDataDarwinLog::post-init callback: "
1619 "skipping EnableNow(), already called by "
1620 "callback [we hit this more than once] "
1626 // Grab the current thread.
1627 auto thread_sp = context->exe_ctx_ref.GetThreadSP();
1630 log->Printf("StructuredDataDarwinLog::%s() warning: failed to "
1631 "retrieve the current thread from the execution "
1632 "context, nowhere to run the thread plan (process uid "
1634 __FUNCTION__, process_sp->GetUniqueID());
1638 // Queue the thread plan.
1639 auto thread_plan_sp = ThreadPlanSP(
1640 new ThreadPlanCallOnFunctionExit(*thread_sp.get(), callback));
1641 const bool abort_other_plans = false;
1642 thread_sp->QueueThreadPlan(thread_plan_sp, abort_other_plans);
1644 log->Printf("StructuredDataDarwinLog::%s() queuing thread plan on "
1645 "trace library init method entry (process uid %u)",
1646 __FUNCTION__, process_sp->GetUniqueID());
1648 // We return false here to indicate that it isn't a public stop.
1652 void StructuredDataDarwinLog::AddInitCompletionHook(Process &process) {
1653 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1655 log->Printf("StructuredDataDarwinLog::%s() called (process uid %u)",
1656 __FUNCTION__, process.GetUniqueID());
1658 // Make sure we haven't already done this.
1660 std::lock_guard<std::mutex> locker(m_added_breakpoint_mutex);
1661 if (m_added_breakpoint) {
1663 log->Printf("StructuredDataDarwinLog::%s() ignoring request, "
1664 "breakpoint already set (process uid %u)",
1665 __FUNCTION__, process.GetUniqueID());
1669 // We're about to do this, don't let anybody else try to do it.
1670 m_added_breakpoint = true;
1673 // Set a breakpoint for the process that will kick in when libtrace has
1674 // finished its initialization.
1675 Target &target = process.GetTarget();
1677 // Build up the module list.
1678 FileSpecList module_spec_list;
1679 auto module_file_spec =
1680 FileSpec(GetGlobalProperties()->GetLoggingModuleName());
1681 module_spec_list.Append(module_file_spec);
1683 // We aren't specifying a source file set.
1684 FileSpecList *source_spec_list = nullptr;
1686 const char *func_name = "_libtrace_init";
1687 const lldb::addr_t offset = 0;
1688 const LazyBool skip_prologue = eLazyBoolCalculate;
1689 // This is an internal breakpoint - the user shouldn't see it.
1690 const bool internal = true;
1691 const bool hardware = false;
1693 auto breakpoint_sp = target.CreateBreakpoint(
1694 &module_spec_list, source_spec_list, func_name, eFunctionNameTypeFull,
1695 eLanguageTypeC, offset, skip_prologue, internal, hardware);
1696 if (!breakpoint_sp) {
1699 log->Printf("StructuredDataDarwinLog::%s() failed to set "
1700 "breakpoint in module %s, function %s (process uid %u)",
1701 __FUNCTION__, GetGlobalProperties()->GetLoggingModuleName(),
1702 func_name, process.GetUniqueID());
1706 // Set our callback.
1707 breakpoint_sp->SetCallback(InitCompletionHookCallback, nullptr);
1708 m_breakpoint_id = breakpoint_sp->GetID();
1710 log->Printf("StructuredDataDarwinLog::%s() breakpoint set in module %s,"
1711 "function %s (process uid %u)",
1712 __FUNCTION__, GetGlobalProperties()->GetLoggingModuleName(),
1713 func_name, process.GetUniqueID());
1716 void StructuredDataDarwinLog::DumpTimestamp(Stream &stream,
1717 uint64_t timestamp) {
1718 const uint64_t delta_nanos = timestamp - m_first_timestamp_seen;
1720 const uint64_t hours = delta_nanos / NANOS_PER_HOUR;
1721 uint64_t nanos_remaining = delta_nanos % NANOS_PER_HOUR;
1723 const uint64_t minutes = nanos_remaining / NANOS_PER_MINUTE;
1724 nanos_remaining = nanos_remaining % NANOS_PER_MINUTE;
1726 const uint64_t seconds = nanos_remaining / NANOS_PER_SECOND;
1727 nanos_remaining = nanos_remaining % NANOS_PER_SECOND;
1729 stream.Printf("%02" PRIu64 ":%02" PRIu64 ":%02" PRIu64 ".%09" PRIu64, hours,
1730 minutes, seconds, nanos_remaining);
1734 StructuredDataDarwinLog::DumpHeader(Stream &output_stream,
1735 const StructuredData::Dictionary &event) {
1736 StreamString stream;
1738 ProcessSP process_sp = GetProcess();
1744 DebuggerSP debugger_sp =
1745 process_sp->GetTarget().GetDebugger().shared_from_this();
1751 auto options_sp = GetGlobalEnableOptions(debugger_sp);
1757 // Check if we should even display a header.
1758 if (!options_sp->GetDisplayAnyHeaderFields())
1761 stream.PutChar('[');
1763 int header_count = 0;
1764 if (options_sp->GetDisplayTimestampRelative()) {
1765 uint64_t timestamp = 0;
1766 if (event.GetValueForKeyAsInteger("timestamp", timestamp)) {
1767 DumpTimestamp(stream, timestamp);
1772 if (options_sp->GetDisplayActivityChain()) {
1773 llvm::StringRef activity_chain;
1774 if (event.GetValueForKeyAsString("activity-chain", activity_chain) &&
1775 !activity_chain.empty()) {
1776 if (header_count > 0)
1777 stream.PutChar(',');
1779 // Display the activity chain, from parent-most to child-most activity,
1780 // separated by a colon (:).
1781 stream.PutCString("activity-chain=");
1782 stream.PutCString(activity_chain);
1787 if (options_sp->GetDisplaySubsystem()) {
1788 llvm::StringRef subsystem;
1789 if (event.GetValueForKeyAsString("subsystem", subsystem) &&
1790 !subsystem.empty()) {
1791 if (header_count > 0)
1792 stream.PutChar(',');
1793 stream.PutCString("subsystem=");
1794 stream.PutCString(subsystem);
1799 if (options_sp->GetDisplayCategory()) {
1800 llvm::StringRef category;
1801 if (event.GetValueForKeyAsString("category", category) &&
1802 !category.empty()) {
1803 if (header_count > 0)
1804 stream.PutChar(',');
1805 stream.PutCString("category=");
1806 stream.PutCString(category);
1810 stream.PutCString("] ");
1812 output_stream.PutCString(stream.GetString());
1814 return stream.GetSize();
1817 size_t StructuredDataDarwinLog::HandleDisplayOfEvent(
1818 const StructuredData::Dictionary &event, Stream &stream) {
1819 // Check the type of the event.
1820 ConstString event_type;
1821 if (!event.GetValueForKeyAsString("type", event_type)) {
1822 // Hmm, we expected to get events that describe what they are. Continue
1827 if (event_type != GetLogEventType())
1830 size_t total_bytes = 0;
1832 // Grab the message content.
1833 llvm::StringRef message;
1834 if (!event.GetValueForKeyAsString("message", message))
1837 // Display the log entry.
1838 const auto len = message.size();
1840 total_bytes += DumpHeader(stream, event);
1842 stream.Write(message.data(), len);
1845 // Add an end of line.
1846 stream.PutChar('\n');
1847 total_bytes += sizeof(char);
1852 void StructuredDataDarwinLog::EnableNow() {
1853 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
1855 log->Printf("StructuredDataDarwinLog::%s() called", __FUNCTION__);
1857 // Run the enable command.
1858 auto process_sp = GetProcess();
1862 log->Printf("StructuredDataDarwinLog::%s() warning: failed to get "
1863 "valid process, skipping",
1868 log->Printf("StructuredDataDarwinLog::%s() call is for process uid %u",
1869 __FUNCTION__, process_sp->GetUniqueID());
1871 // If we have configuration data, we can directly enable it now. Otherwise,
1872 // we need to run through the command interpreter to parse the auto-run
1873 // options (which is the only way we get here without having already-parsed
1874 // configuration data).
1875 DebuggerSP debugger_sp =
1876 process_sp->GetTarget().GetDebugger().shared_from_this();
1879 log->Printf("StructuredDataDarwinLog::%s() warning: failed to get "
1880 "debugger shared pointer, skipping (process uid %u)",
1881 __FUNCTION__, process_sp->GetUniqueID());
1885 auto options_sp = GetGlobalEnableOptions(debugger_sp);
1887 // We haven't run the enable command yet. Just do that now, it'll take
1888 // care of the rest.
1889 auto &interpreter = debugger_sp->GetCommandInterpreter();
1890 const bool success = RunEnableCommand(interpreter);
1893 log->Printf("StructuredDataDarwinLog::%s() ran enable command "
1894 "successfully for (process uid %u)",
1895 __FUNCTION__, process_sp->GetUniqueID());
1897 log->Printf("StructuredDataDarwinLog::%s() error: running "
1898 "enable command failed (process uid %u)",
1899 __FUNCTION__, process_sp->GetUniqueID());
1901 // Report failures to the debugger error stream.
1902 auto error_stream_sp = debugger_sp->GetAsyncErrorStream();
1903 if (error_stream_sp) {
1904 error_stream_sp->Printf("failed to configure DarwinLog "
1906 error_stream_sp->Flush();
1911 // We've previously been enabled. We will re-enable now with the previously
1912 // specified options.
1913 auto config_sp = options_sp->BuildConfigurationData(true);
1916 log->Printf("StructuredDataDarwinLog::%s() warning: failed to "
1917 "build configuration data for enable options, skipping "
1919 __FUNCTION__, process_sp->GetUniqueID());
1923 // We can run it directly.
1924 // Send configuration to the feature by way of the process.
1925 const Status error =
1926 process_sp->ConfigureStructuredData(GetDarwinLogTypeName(), config_sp);
1929 if (!error.Success()) {
1931 log->Printf("StructuredDataDarwinLog::%s() "
1932 "ConfigureStructuredData() call failed "
1933 "(process uid %u): %s",
1934 __FUNCTION__, process_sp->GetUniqueID(), error.AsCString());
1935 auto error_stream_sp = debugger_sp->GetAsyncErrorStream();
1936 if (error_stream_sp) {
1937 error_stream_sp->Printf("failed to configure DarwinLog "
1940 error_stream_sp->Flush();
1942 m_is_enabled = false;
1944 m_is_enabled = true;
1946 log->Printf("StructuredDataDarwinLog::%s() success via direct "
1947 "configuration (process uid %u)",
1948 __FUNCTION__, process_sp->GetUniqueID());