LLDB mainline
StructuredDataDarwinLog.cpp
Go to the documentation of this file.
1//===-- StructuredDataDarwinLog.cpp ---------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10
11#include <cstring>
12
13#include <memory>
14#include <sstream>
15
17#include "lldb/Core/Debugger.h"
18#include "lldb/Core/Module.h"
28#include "lldb/Target/Process.h"
29#include "lldb/Target/Target.h"
32#include "lldb/Utility/Log.h"
34
35#define DARWIN_LOG_TYPE_VALUE "DarwinLog"
36
37using namespace lldb;
38using namespace lldb_private;
39
41
42#pragma mark -
43#pragma mark Anonymous Namespace
44
45// Anonymous namespace
46
48const uint64_t NANOS_PER_MICRO = 1000;
49const uint64_t NANOS_PER_MILLI = NANOS_PER_MICRO * 1000;
50const uint64_t NANOS_PER_SECOND = NANOS_PER_MILLI * 1000;
51const uint64_t NANOS_PER_MINUTE = NANOS_PER_SECOND * 60;
52const uint64_t NANOS_PER_HOUR = NANOS_PER_MINUTE * 60;
53
55
56/// Global, sticky enable switch. If true, the user has explicitly
57/// run the enable command. When a process launches or is attached to,
58/// we will enable DarwinLog if either the settings for auto-enable is
59/// on, or if the user had explicitly run enable at some point prior
60/// to the launch/attach.
62
63class EnableOptions;
64using EnableOptionsSP = std::shared_ptr<EnableOptions>;
65
67 std::map<DebuggerWP, EnableOptionsSP, std::owner_less<DebuggerWP>>;
68
70 static OptionsMap s_options_map;
71 return s_options_map;
72}
73
74static std::mutex &GetGlobalOptionsMapLock() {
75 static std::mutex s_options_map_lock;
76 return s_options_map_lock;
77}
78
79EnableOptionsSP GetGlobalEnableOptions(const DebuggerSP &debugger_sp) {
80 if (!debugger_sp)
81 return EnableOptionsSP();
82
83 std::lock_guard<std::mutex> locker(GetGlobalOptionsMapLock());
84 OptionsMap &options_map = GetGlobalOptionsMap();
85 DebuggerWP debugger_wp(debugger_sp);
86 auto find_it = options_map.find(debugger_wp);
87 if (find_it != options_map.end())
88 return find_it->second;
89 else
90 return EnableOptionsSP();
91}
92
93void SetGlobalEnableOptions(const DebuggerSP &debugger_sp,
94 const EnableOptionsSP &options_sp) {
95 std::lock_guard<std::mutex> locker(GetGlobalOptionsMapLock());
96 OptionsMap &options_map = GetGlobalOptionsMap();
97 DebuggerWP debugger_wp(debugger_sp);
98 auto find_it = options_map.find(debugger_wp);
99 if (find_it != options_map.end())
100 find_it->second = options_sp;
101 else
102 options_map.insert(std::make_pair(debugger_wp, options_sp));
103}
104
105#pragma mark -
106#pragma mark Settings Handling
107
108/// Code to handle the StructuredDataDarwinLog settings
109
110#define LLDB_PROPERTIES_darwinlog
111#include "StructuredDataDarwinLogProperties.inc"
112
113enum {
114#define LLDB_PROPERTIES_darwinlog
115#include "StructuredDataDarwinLogPropertiesEnum.inc"
116};
117
119public:
121 static ConstString g_setting_name("darwin-log");
122 return g_setting_name;
123 }
124
126 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
127 m_collection_sp->Initialize(g_darwinlog_properties);
128 }
129
131
132 bool GetEnableOnStartup() const {
133 const uint32_t idx = ePropertyEnableOnStartup;
134 return GetPropertyAtIndexAs<bool>(
135 idx, g_darwinlog_properties[idx].default_uint_value != 0);
136 }
137
138 llvm::StringRef GetAutoEnableOptions() const {
139 const uint32_t idx = ePropertyAutoEnableOptions;
140 return GetPropertyAtIndexAs<llvm::StringRef>(
141 idx, g_darwinlog_properties[idx].default_cstr_value);
142 }
143
144 const char *GetLoggingModuleName() const { return "libsystem_trace.dylib"; }
145};
146
148 static StructuredDataDarwinLogProperties g_settings;
149 return g_settings;
150}
151
152const char *const s_filter_attributes[] = {
153 "activity", // current activity
154 "activity-chain", // entire activity chain, each level separated by ':'
155 "category", // category of the log message
156 "message", // message contents, fully expanded
157 "subsystem" // subsystem of the log message
158
159 // Consider implementing this action as it would be cheaper to filter.
160 // "message" requires always formatting the message, which is a waste of
161 // cycles if it ends up being rejected. "format", // format string
162 // used to format message text
163};
164
165static llvm::StringRef GetDarwinLogTypeName() {
166 static constexpr llvm::StringLiteral s_key_name("DarwinLog");
167 return s_key_name;
168}
169
170static llvm::StringRef GetLogEventType() {
171 static constexpr llvm::StringLiteral s_event_type("log");
172 return s_event_type;
173}
174
175class FilterRule;
176using FilterRuleSP = std::shared_ptr<FilterRule>;
177
179public:
180 virtual ~FilterRule() = default;
181
183 std::function<FilterRuleSP(bool accept, size_t attribute_index,
184 const std::string &op_arg, Status &error)>;
185
186 static void RegisterOperation(ConstString operation,
187 const OperationCreationFunc &creation_func) {
188 GetCreationFuncMap().insert(std::make_pair(operation, creation_func));
189 }
190
191 static FilterRuleSP CreateRule(bool match_accepts, size_t attribute,
192 ConstString operation,
193 const std::string &op_arg, Status &error) {
194 // Find the creation func for this type of filter rule.
195 auto map = GetCreationFuncMap();
196 auto find_it = map.find(operation);
197 if (find_it == map.end()) {
198 error.SetErrorStringWithFormat("unknown filter operation \""
199 "%s\"",
200 operation.GetCString());
201 return FilterRuleSP();
202 }
203
204 return find_it->second(match_accepts, attribute, op_arg, error);
205 }
206
209
210 // Indicate whether this is an accept or reject rule.
211 dict_p->AddBooleanItem("accept", m_accept);
212
213 // Indicate which attribute of the message this filter references. This can
214 // drop into the rule-specific DoSerialization if we get to the point where
215 // not all FilterRule derived classes work on an attribute. (e.g. logical
216 // and/or and other compound operations).
218
219 // Indicate the type of the rule.
220 dict_p->AddStringItem("type", GetOperationType().GetCString());
221
222 // Let the rule add its own specific details here.
223 DoSerialization(*dict_p);
224
225 return StructuredData::ObjectSP(dict_p);
226 }
227
228 virtual void Dump(Stream &stream) const = 0;
229
231
232protected:
233 FilterRule(bool accept, size_t attribute_index, ConstString operation)
234 : m_accept(accept), m_attribute_index(attribute_index),
235 m_operation(operation) {}
236
237 virtual void DoSerialization(StructuredData::Dictionary &dict) const = 0;
238
239 bool GetMatchAccepts() const { return m_accept; }
240
241 const char *GetFilterAttribute() const {
243 }
244
245private:
246 using CreationFuncMap = std::map<ConstString, OperationCreationFunc>;
247
249 static CreationFuncMap s_map;
250 return s_map;
251 }
252
253 const bool m_accept;
254 const size_t m_attribute_index;
256};
257
258using FilterRules = std::vector<FilterRuleSP>;
259
261public:
262 static void RegisterOperation() {
264 }
265
266 void Dump(Stream &stream) const override {
267 stream.Printf("%s %s regex %s", GetMatchAccepts() ? "accept" : "reject",
269 }
270
271protected:
272 void DoSerialization(StructuredData::Dictionary &dict) const override {
273 dict.AddStringItem("regex", m_regex_text);
274 }
275
276private:
277 static FilterRuleSP CreateOperation(bool accept, size_t attribute_index,
278 const std::string &op_arg,
279 Status &error) {
280 // We treat the op_arg as a regex. Validate it.
281 if (op_arg.empty()) {
282 error.SetErrorString("regex filter type requires a regex "
283 "argument");
284 return FilterRuleSP();
285 }
286
287 // Instantiate the regex so we can report any errors.
288 auto regex = RegularExpression(op_arg);
289 if (llvm::Error err = regex.GetError()) {
290 error.SetErrorString(llvm::toString(std::move(err)));
291 return FilterRuleSP();
292 }
293
294 // We passed all our checks, this appears fine.
295 error.Clear();
296 return FilterRuleSP(new RegexFilterRule(accept, attribute_index, op_arg));
297 }
298
300 static ConstString s_operation("regex");
301 return s_operation;
302 }
303
304 RegexFilterRule(bool accept, size_t attribute_index,
305 const std::string &regex_text)
306 : FilterRule(accept, attribute_index, StaticGetOperation()),
307 m_regex_text(regex_text) {}
308
309 const std::string m_regex_text;
310};
311
313public:
314 static void RegisterOperation() {
316 }
317
318 void Dump(Stream &stream) const override {
319 stream.Printf("%s %s match %s", GetMatchAccepts() ? "accept" : "reject",
321 }
322
323protected:
324 void DoSerialization(StructuredData::Dictionary &dict) const override {
325 dict.AddStringItem("exact_text", m_match_text);
326 }
327
328private:
329 static FilterRuleSP CreateOperation(bool accept, size_t attribute_index,
330 const std::string &op_arg,
331 Status &error) {
332 if (op_arg.empty()) {
333 error.SetErrorString("exact match filter type requires an "
334 "argument containing the text that must "
335 "match the specified message attribute.");
336 return FilterRuleSP();
337 }
338
339 error.Clear();
340 return FilterRuleSP(
341 new ExactMatchFilterRule(accept, attribute_index, op_arg));
342 }
343
345 static ConstString s_operation("match");
346 return s_operation;
347 }
348
349 ExactMatchFilterRule(bool accept, size_t attribute_index,
350 const std::string &match_text)
351 : FilterRule(accept, attribute_index, StaticGetOperation()),
352 m_match_text(match_text) {}
353
354 const std::string m_match_text;
355};
356
360}
361
362// =========================================================================
363// Commands
364// =========================================================================
365
366/// Provides the main on-off switch for enabling darwin logging.
367///
368/// It is valid to run the enable command when logging is already enabled.
369/// This resets the logging with whatever settings are currently set.
370
372 // Source stream include/exclude options (the first-level filter). This one
373 // should be made as small as possible as everything that goes through here
374 // must be processed by the process monitor.
375 {LLDB_OPT_SET_ALL, false, "any-process", 'a', OptionParser::eNoArgument,
376 nullptr, {}, 0, eArgTypeNone,
377 "Specifies log messages from other related processes should be "
378 "included."},
379 {LLDB_OPT_SET_ALL, false, "debug", 'd', OptionParser::eNoArgument, nullptr,
380 {}, 0, eArgTypeNone,
381 "Specifies debug-level log messages should be included. Specifying"
382 " --debug implies --info."},
383 {LLDB_OPT_SET_ALL, false, "info", 'i', OptionParser::eNoArgument, nullptr,
384 {}, 0, eArgTypeNone,
385 "Specifies info-level log messages should be included."},
387 nullptr, {}, 0, eArgRawInput,
388 // There doesn't appear to be a great way for me to have these multi-line,
389 // formatted tables in help. This looks mostly right but there are extra
390 // linefeeds added at seemingly random spots, and indentation isn't
391 // handled properly on those lines.
392 "Appends a filter rule to the log message filter chain. Multiple "
393 "rules may be added by specifying this option multiple times, "
394 "once per filter rule. Filter rules are processed in the order "
395 "they are specified, with the --no-match-accepts setting used "
396 "for any message that doesn't match one of the rules.\n"
397 "\n"
398 " Filter spec format:\n"
399 "\n"
400 " --filter \"{action} {attribute} {op}\"\n"
401 "\n"
402 " {action} :=\n"
403 " accept |\n"
404 " reject\n"
405 "\n"
406 " {attribute} :=\n"
407 " activity | // message's most-derived activity\n"
408 " activity-chain | // message's {parent}:{child} activity\n"
409 " category | // message's category\n"
410 " message | // message's expanded contents\n"
411 " subsystem | // message's subsystem\n"
412 "\n"
413 " {op} :=\n"
414 " match {exact-match-text} |\n"
415 " regex {search-regex}\n"
416 "\n"
417 "The regex flavor used is the C++ std::regex ECMAScript format. "
418 "Prefer character classes like [[:digit:]] to \\d and the like, as "
419 "getting the backslashes escaped through properly is error-prone."},
420 {LLDB_OPT_SET_ALL, false, "live-stream", 'l',
422 "Specify whether logging events are live-streamed or buffered. "
423 "True indicates live streaming, false indicates buffered. The "
424 "default is true (live streaming). Live streaming will deliver "
425 "log messages with less delay, but buffered capture mode has less "
426 "of an observer effect."},
427 {LLDB_OPT_SET_ALL, false, "no-match-accepts", 'n',
429 "Specify whether a log message that doesn't match any filter rule "
430 "is accepted or rejected, where true indicates accept. The "
431 "default is true."},
432 {LLDB_OPT_SET_ALL, false, "echo-to-stderr", 'e',
434 "Specify whether os_log()/NSLog() messages are echoed to the "
435 "target program's stderr. When DarwinLog is enabled, we shut off "
436 "the mirroring of os_log()/NSLog() to the program's stderr. "
437 "Setting this flag to true will restore the stderr mirroring."
438 "The default is false."},
439 {LLDB_OPT_SET_ALL, false, "broadcast-events", 'b',
441 "Specify if the plugin should broadcast events. Broadcasting "
442 "log events is a requirement for displaying the log entries in "
443 "LLDB command-line. It is also required if LLDB clients want to "
444 "process log events. The default is true."},
445 // Message formatting options
446 {LLDB_OPT_SET_ALL, false, "timestamp-relative", 'r',
448 "Include timestamp in the message header when printing a log "
449 "message. The timestamp is relative to the first displayed "
450 "message."},
451 {LLDB_OPT_SET_ALL, false, "subsystem", 's', OptionParser::eNoArgument,
452 nullptr, {}, 0, eArgTypeNone,
453 "Include the subsystem in the message header when displaying "
454 "a log message."},
455 {LLDB_OPT_SET_ALL, false, "category", 'c', OptionParser::eNoArgument,
456 nullptr, {}, 0, eArgTypeNone,
457 "Include the category in the message header when displaying "
458 "a log message."},
459 {LLDB_OPT_SET_ALL, false, "activity-chain", 'C', OptionParser::eNoArgument,
460 nullptr, {}, 0, eArgTypeNone,
461 "Include the activity parent-child chain in the message header "
462 "when displaying a log message. The activity hierarchy is "
463 "displayed as {grandparent-activity}:"
464 "{parent-activity}:{activity}[:...]."},
465 {LLDB_OPT_SET_ALL, false, "all-fields", 'A', OptionParser::eNoArgument,
466 nullptr, {}, 0, eArgTypeNone,
467 "Shortcut to specify that all header fields should be displayed."}};
468
469class EnableOptions : public Options {
470public:
472 : Options(),
474 m_filter_rules() {}
475
476 void OptionParsingStarting(ExecutionContext *execution_context) override {
477 m_include_debug_level = false;
478 m_include_info_level = false;
479 m_include_any_process = false;
481 m_echo_to_stderr = false;
483 m_display_subsystem = false;
484 m_display_category = false;
486 m_broadcast_events = true;
487 m_live_stream = true;
488 m_filter_rules.clear();
489 }
490
491 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
492 ExecutionContext *execution_context) override {
494
495 const int short_option = m_getopt_table[option_idx].val;
496 switch (short_option) {
497 case 'a':
499 break;
500
501 case 'A':
503 m_display_category = true;
504 m_display_subsystem = true;
506 break;
507
508 case 'b':
510 OptionArgParser::ToBoolean(option_arg, true, nullptr);
511 break;
512
513 case 'c':
514 m_display_category = true;
515 break;
516
517 case 'C':
519 break;
520
521 case 'd':
523 break;
524
525 case 'e':
526 m_echo_to_stderr = OptionArgParser::ToBoolean(option_arg, false, nullptr);
527 break;
528
529 case 'f':
530 return ParseFilterRule(option_arg);
531
532 case 'i':
534 break;
535
536 case 'l':
537 m_live_stream = OptionArgParser::ToBoolean(option_arg, false, nullptr);
538 break;
539
540 case 'n':
542 OptionArgParser::ToBoolean(option_arg, true, nullptr);
543 break;
544
545 case 'r':
547 break;
548
549 case 's':
550 m_display_subsystem = true;
551 break;
552
553 default:
554 error.SetErrorStringWithFormat("unsupported option '%c'", short_option);
555 }
556 return error;
557 }
558
559 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
560 return llvm::ArrayRef(g_enable_option_table);
561 }
562
565
566 // Set the basic enabled state.
567 config_sp->AddBooleanItem("enabled", enabled);
568
569 // If we're disabled, there's nothing more to add.
570 if (!enabled)
571 return config_sp;
572
573 // Handle source stream flags.
574 auto source_flags_sp =
576 config_sp->AddItem("source-flags", source_flags_sp);
577
578 source_flags_sp->AddBooleanItem("any-process", m_include_any_process);
579 source_flags_sp->AddBooleanItem("debug-level", m_include_debug_level);
580 // The debug-level flag, if set, implies info-level.
581 source_flags_sp->AddBooleanItem("info-level", m_include_info_level ||
583 source_flags_sp->AddBooleanItem("live-stream", m_live_stream);
584
585 // Specify default filter rule (the fall-through)
586 config_sp->AddBooleanItem("filter-fall-through-accepts",
588
589 // Handle filter rules
590 if (!m_filter_rules.empty()) {
591 auto json_filter_rules_sp =
593 config_sp->AddItem("filter-rules", json_filter_rules_sp);
594 for (auto &rule_sp : m_filter_rules) {
595 if (!rule_sp)
596 continue;
597 json_filter_rules_sp->AddItem(rule_sp->Serialize());
598 }
599 }
600 return config_sp;
601 }
602
604
605 bool GetIncludeInfoLevel() const {
606 // Specifying debug level implies info level.
608 }
609
610 const FilterRules &GetFilterRules() const { return m_filter_rules; }
611
613
614 bool GetEchoToStdErr() const { return m_echo_to_stderr; }
615
618 }
619
621 bool GetDisplayCategory() const { return m_display_category; }
623
627 }
628
629 bool GetBroadcastEvents() const { return m_broadcast_events; }
630
631private:
632 Status ParseFilterRule(llvm::StringRef rule_text) {
634
635 if (rule_text.empty()) {
636 error.SetErrorString("invalid rule_text");
637 return error;
638 }
639
640 // filter spec format:
641 //
642 // {action} {attribute} {op}
643 //
644 // {action} :=
645 // accept |
646 // reject
647 //
648 // {attribute} :=
649 // category |
650 // subsystem |
651 // activity |
652 // activity-chain |
653 // message |
654 // format
655 //
656 // {op} :=
657 // match {exact-match-text} |
658 // regex {search-regex}
659
660 // Parse action.
661 auto action_end_pos = rule_text.find(' ');
662 if (action_end_pos == std::string::npos) {
663 error.SetErrorStringWithFormat("could not parse filter rule "
664 "action from \"%s\"",
665 rule_text.str().c_str());
666 return error;
667 }
668 auto action = rule_text.substr(0, action_end_pos);
669 bool accept;
670 if (action == "accept")
671 accept = true;
672 else if (action == "reject")
673 accept = false;
674 else {
675 error.SetErrorString("filter action must be \"accept\" or \"deny\"");
676 return error;
677 }
678
679 // parse attribute
680 auto attribute_end_pos = rule_text.find(" ", action_end_pos + 1);
681 if (attribute_end_pos == std::string::npos) {
682 error.SetErrorStringWithFormat("could not parse filter rule "
683 "attribute from \"%s\"",
684 rule_text.str().c_str());
685 return error;
686 }
687 auto attribute = rule_text.substr(action_end_pos + 1,
688 attribute_end_pos - (action_end_pos + 1));
689 auto attribute_index = MatchAttributeIndex(attribute);
690 if (attribute_index < 0) {
691 error.SetErrorStringWithFormat("filter rule attribute unknown: "
692 "%s",
693 attribute.str().c_str());
694 return error;
695 }
696
697 // parse operation
698 auto operation_end_pos = rule_text.find(" ", attribute_end_pos + 1);
699 auto operation = rule_text.substr(
700 attribute_end_pos + 1, operation_end_pos - (attribute_end_pos + 1));
701
702 // add filter spec
703 auto rule_sp = FilterRule::CreateRule(
704 accept, attribute_index, ConstString(operation),
705 std::string(rule_text.substr(operation_end_pos + 1)), error);
706
707 if (rule_sp && error.Success())
708 m_filter_rules.push_back(rule_sp);
709
710 return error;
711 }
712
713 int MatchAttributeIndex(llvm::StringRef attribute_name) const {
714 for (const auto &Item : llvm::enumerate(s_filter_attributes)) {
715 if (attribute_name == Item.value())
716 return Item.index();
717 }
718
719 // We didn't match anything.
720 return -1;
721 }
722
727 bool m_echo_to_stderr = false;
730 bool m_display_category = false;
733 bool m_live_stream = true;
735};
736
738public:
739 EnableCommand(CommandInterpreter &interpreter, bool enable, const char *name,
740 const char *help, const char *syntax)
741 : CommandObjectParsed(interpreter, name, help, syntax), m_enable(enable),
742 m_options_sp(enable ? new EnableOptions() : nullptr) {}
743
744protected:
746 const char *source_name) {
747 if (!source_name)
748 return;
749
750 // Check if we're *not* using strict sources. If not, then the user is
751 // going to get debug-level info anyways, probably not what they're
752 // expecting. Unfortunately we can only fix this by adding an env var,
753 // which would have had to have happened already. Thus, a warning is the
754 // best we can do here.
755 StreamString stream;
756 stream.Printf("darwin-log source settings specify to exclude "
757 "%s messages, but setting "
758 "'plugin.structured-data.darwin-log."
759 "strict-sources' is disabled. This process will "
760 "automatically have %s messages included. Enable"
761 " the property and relaunch the target binary to have"
762 " these messages excluded.",
763 source_name, source_name);
764 result.AppendWarning(stream.GetString());
765 }
766
767 bool DoExecute(Args &command, CommandReturnObject &result) override {
768 // First off, set the global sticky state of enable/disable based on this
769 // command execution.
771
772 // Next, if this is an enable, save off the option data. We will need it
773 // later if a process hasn't been launched or attached yet.
774 if (m_enable) {
775 // Save off enabled configuration so we can apply these parsed options
776 // the next time an attach or launch occurs.
777 DebuggerSP debugger_sp =
778 GetCommandInterpreter().GetDebugger().shared_from_this();
780 }
781
782 // Now check if we have a running process. If so, we should instruct the
783 // process monitor to enable/disable DarwinLog support now.
785
786 // Grab the active process.
787 auto process_sp = target.GetProcessSP();
788 if (!process_sp) {
789 // No active process, so there is nothing more to do right now.
791 return true;
792 }
793
794 // If the process is no longer alive, we can't do this now. We'll catch it
795 // the next time the process is started up.
796 if (!process_sp->IsAlive()) {
798 return true;
799 }
800
801 // Get the plugin for the process.
802 auto plugin_sp = process_sp->GetStructuredDataPlugin(
804 if (!plugin_sp || (plugin_sp->GetPluginName() !=
806 result.AppendError("failed to get StructuredDataPlugin for "
807 "the process");
808 }
810 *static_cast<StructuredDataDarwinLog *>(plugin_sp.get());
811
812 if (m_enable) {
813 // Hook up the breakpoint for the process that detects when libtrace has
814 // been sufficiently initialized to really start the os_log stream. This
815 // is insurance to assure us that logging is really enabled. Requesting
816 // that logging be enabled for a process before libtrace is initialized
817 // results in a scenario where no errors occur, but no logging is
818 // captured, either. This step is to eliminate that possibility.
819 plugin.AddInitCompletionHook(*process_sp);
820 }
821
822 // Send configuration to the feature by way of the process. Construct the
823 // options we will use.
824 auto config_sp = m_options_sp->BuildConfigurationData(m_enable);
825 const Status error = process_sp->ConfigureStructuredData(
826 ConstString(GetDarwinLogTypeName()), config_sp);
827
828 // Report results.
829 if (!error.Success()) {
830 result.AppendError(error.AsCString());
831 // Our configuration failed, so we're definitely disabled.
832 plugin.SetEnabled(false);
833 } else {
835 // Our configuration succeeded, so we're enabled/disabled per whichever
836 // one this command is setup to do.
837 plugin.SetEnabled(m_enable);
838 }
839 return result.Succeeded();
840 }
841
842 Options *GetOptions() override {
843 // We don't have options when this represents disable.
844 return m_enable ? m_options_sp.get() : nullptr;
845 }
846
847private:
848 const bool m_enable;
850};
851
852/// Provides the status command.
854public:
856 : CommandObjectParsed(interpreter, "status",
857 "Show whether Darwin log supported is available"
858 " and enabled.",
859 "plugin structured-data darwin-log status") {}
860
861protected:
862 bool DoExecute(Args &command, CommandReturnObject &result) override {
863 auto &stream = result.GetOutputStream();
864
865 // Figure out if we've got a process. If so, we can tell if DarwinLog is
866 // available for that process.
868 auto process_sp = target.GetProcessSP();
869 if (!process_sp) {
870 stream.PutCString("Availability: unknown (requires process)\n");
871 stream.PutCString("Enabled: not applicable "
872 "(requires process)\n");
873 } else {
874 auto plugin_sp = process_sp->GetStructuredDataPlugin(
876 stream.Printf("Availability: %s\n",
877 plugin_sp ? "available" : "unavailable");
878 llvm::StringRef plugin_name = StructuredDataDarwinLog::GetStaticPluginName();
879 const bool enabled =
880 plugin_sp ? plugin_sp->GetEnabled(ConstString(plugin_name)) : false;
881 stream.Printf("Enabled: %s\n", enabled ? "true" : "false");
882 }
883
884 // Display filter settings.
885 DebuggerSP debugger_sp =
886 GetCommandInterpreter().GetDebugger().shared_from_this();
887 auto options_sp = GetGlobalEnableOptions(debugger_sp);
888 if (!options_sp) {
889 // Nothing more to do.
891 return true;
892 }
893
894 // Print filter rules
895 stream.PutCString("DarwinLog filter rules:\n");
896
897 stream.IndentMore();
898
899 if (options_sp->GetFilterRules().empty()) {
900 stream.Indent();
901 stream.PutCString("none\n");
902 } else {
903 // Print each of the filter rules.
904 int rule_number = 0;
905 for (auto rule_sp : options_sp->GetFilterRules()) {
906 ++rule_number;
907 if (!rule_sp)
908 continue;
909
910 stream.Indent();
911 stream.Printf("%02d: ", rule_number);
912 rule_sp->Dump(stream);
913 stream.PutChar('\n');
914 }
915 }
916 stream.IndentLess();
917
918 // Print no-match handling.
919 stream.Indent();
920 stream.Printf("no-match behavior: %s\n",
921 options_sp->GetFallthroughAccepts() ? "accept" : "reject");
922
924 return true;
925 }
926};
927
928/// Provides the darwin-log base command
930public:
932 : CommandObjectMultiword(interpreter, "plugin structured-data darwin-log",
933 "Commands for configuring Darwin os_log "
934 "support.",
935 "") {
936 // enable
937 auto enable_help = "Enable Darwin log collection, or re-enable "
938 "with modified configuration.";
939 auto enable_syntax = "plugin structured-data darwin-log enable";
940 auto enable_cmd_sp = CommandObjectSP(
941 new EnableCommand(interpreter,
942 true, // enable
943 "enable", enable_help, enable_syntax));
944 LoadSubCommand("enable", enable_cmd_sp);
945
946 // disable
947 auto disable_help = "Disable Darwin log collection.";
948 auto disable_syntax = "plugin structured-data darwin-log disable";
949 auto disable_cmd_sp = CommandObjectSP(
950 new EnableCommand(interpreter,
951 false, // disable
952 "disable", disable_help, disable_syntax));
953 LoadSubCommand("disable", disable_cmd_sp);
954
955 // status
956 auto status_cmd_sp = CommandObjectSP(new StatusCommand(interpreter));
957 LoadSubCommand("status", status_cmd_sp);
958 }
959};
960
962 Log *log = GetLog(LLDBLog::Process);
963 // We are abusing the options data model here so that we can parse options
964 // without requiring the Debugger instance.
965
966 // We have an empty execution context at this point. We only want to parse
967 // options, and we don't need any context to do this here. In fact, we want
968 // to be able to parse the enable options before having any context.
969 ExecutionContext exe_ctx;
970
971 EnableOptionsSP options_sp(new EnableOptions());
972 options_sp->NotifyOptionParsingStarting(&exe_ctx);
973
974 CommandReturnObject result(debugger.GetUseColor());
975
976 // Parse the arguments.
977 auto options_property_sp =
978 debugger.GetPropertyValue(nullptr,
979 "plugin.structured-data.darwin-log."
980 "auto-enable-options",
981 error);
982 if (!error.Success())
983 return EnableOptionsSP();
984 if (!options_property_sp) {
985 error.SetErrorString("failed to find option setting for "
986 "plugin.structured-data.darwin-log.");
987 return EnableOptionsSP();
988 }
989
990 const char *enable_options =
991 options_property_sp->GetAsString()->GetCurrentValue();
992 Args args(enable_options);
993 if (args.GetArgumentCount() > 0) {
994 // Eliminate the initial '--' that would be required to set the settings
995 // that themselves include '-' and/or '--'.
996 const char *first_arg = args.GetArgumentAtIndex(0);
997 if (first_arg && (strcmp(first_arg, "--") == 0))
998 args.Shift();
999 }
1000
1001 bool require_validation = false;
1002 llvm::Expected<Args> args_or =
1003 options_sp->Parse(args, &exe_ctx, PlatformSP(), require_validation);
1004 if (!args_or) {
1006 log, args_or.takeError(),
1007 "Parsing plugin.structured-data.darwin-log.auto-enable-options value "
1008 "failed: {0}");
1009 return EnableOptionsSP();
1010 }
1011
1012 if (!options_sp->VerifyOptions(result))
1013 return EnableOptionsSP();
1014
1015 // We successfully parsed and validated the options.
1016 return options_sp;
1017}
1018
1020 StreamString command_stream;
1021
1022 command_stream << "plugin structured-data darwin-log enable";
1023 auto enable_options = GetGlobalProperties().GetAutoEnableOptions();
1024 if (!enable_options.empty()) {
1025 command_stream << ' ';
1026 command_stream << enable_options;
1027 }
1028
1029 // Run the command.
1030 CommandReturnObject return_object(interpreter.GetDebugger().GetUseColor());
1031 interpreter.HandleCommand(command_stream.GetData(), eLazyBoolNo,
1032 return_object);
1033 return return_object.Succeeded();
1034}
1035}
1036using namespace sddarwinlog_private;
1037
1038#pragma mark -
1039#pragma mark Public static API
1040
1041// Public static API
1042
1046 GetStaticPluginName(), "Darwin os_log() and os_activity() support",
1048}
1049
1052}
1053
1054#pragma mark -
1055#pragma mark StructuredDataPlugin API
1056
1057// StructuredDataPlugin API
1058
1060 ConstString type_name) {
1061 return type_name == GetDarwinLogTypeName();
1062}
1063
1065 Process &process, ConstString type_name,
1066 const StructuredData::ObjectSP &object_sp) {
1067 Log *log = GetLog(LLDBLog::Process);
1068 if (log) {
1069 StreamString json_stream;
1070 if (object_sp)
1071 object_sp->Dump(json_stream);
1072 else
1073 json_stream.PutCString("<null>");
1074 LLDB_LOGF(log, "StructuredDataDarwinLog::%s() called with json: %s",
1075 __FUNCTION__, json_stream.GetData());
1076 }
1077
1078 // Ignore empty structured data.
1079 if (!object_sp) {
1080 LLDB_LOGF(log,
1081 "StructuredDataDarwinLog::%s() StructuredData object "
1082 "is null",
1083 __FUNCTION__);
1084 return;
1085 }
1086
1087 // Ignore any data that isn't for us.
1088 if (type_name != GetDarwinLogTypeName()) {
1089 LLDB_LOGF(log,
1090 "StructuredDataDarwinLog::%s() StructuredData type "
1091 "expected to be %s but was %s, ignoring",
1092 __FUNCTION__, GetDarwinLogTypeName().str().c_str(),
1093 type_name.AsCString());
1094 return;
1095 }
1096
1097 // Broadcast the structured data event if we have that enabled. This is the
1098 // way that the outside world (all clients) get access to this data. This
1099 // plugin sets policy as to whether we do that.
1100 DebuggerSP debugger_sp = process.GetTarget().GetDebugger().shared_from_this();
1101 auto options_sp = GetGlobalEnableOptions(debugger_sp);
1102 if (options_sp && options_sp->GetBroadcastEvents()) {
1103 LLDB_LOGF(log, "StructuredDataDarwinLog::%s() broadcasting event",
1104 __FUNCTION__);
1105 process.BroadcastStructuredData(object_sp, shared_from_this());
1106 }
1107
1108 // Later, hang on to a configurable amount of these and allow commands to
1109 // inspect, including showing backtraces.
1110}
1111
1112static void SetErrorWithJSON(Status &error, const char *message,
1113 StructuredData::Object &object) {
1114 if (!message) {
1115 error.SetErrorString("Internal error: message not set.");
1116 return;
1117 }
1118
1119 StreamString object_stream;
1120 object.Dump(object_stream);
1121 object_stream.Flush();
1122
1123 error.SetErrorStringWithFormat("%s: %s", message, object_stream.GetData());
1124}
1125
1127 const StructuredData::ObjectSP &object_sp, lldb_private::Stream &stream) {
1128 Status error;
1129
1130 if (!object_sp) {
1131 error.SetErrorString("No structured data.");
1132 return error;
1133 }
1134
1135 // Log message payload objects will be dictionaries.
1136 const StructuredData::Dictionary *dictionary = object_sp->GetAsDictionary();
1137 if (!dictionary) {
1138 SetErrorWithJSON(error, "Structured data should have been a dictionary "
1139 "but wasn't",
1140 *object_sp);
1141 return error;
1142 }
1143
1144 // Validate this is really a message for our plugin.
1145 llvm::StringRef type_name;
1146 if (!dictionary->GetValueForKeyAsString("type", type_name)) {
1147 SetErrorWithJSON(error, "Structured data doesn't contain mandatory "
1148 "type field",
1149 *object_sp);
1150 return error;
1151 }
1152
1153 if (type_name != GetDarwinLogTypeName()) {
1154 // This is okay - it simply means the data we received is not a log
1155 // message. We'll just format it as is.
1156 object_sp->Dump(stream);
1157 return error;
1158 }
1159
1160 // DarwinLog dictionaries store their data
1161 // in an array with key name "events".
1162 StructuredData::Array *events = nullptr;
1163 if (!dictionary->GetValueForKeyAsArray("events", events) || !events) {
1164 SetErrorWithJSON(error, "Log structured data is missing mandatory "
1165 "'events' field, expected to be an array",
1166 *object_sp);
1167 return error;
1168 }
1169
1170 events->ForEach(
1171 [&stream, &error, &object_sp, this](StructuredData::Object *object) {
1172 if (!object) {
1173 // Invalid. Stop iterating.
1174 SetErrorWithJSON(error, "Log event entry is null", *object_sp);
1175 return false;
1176 }
1177
1178 auto event = object->GetAsDictionary();
1179 if (!event) {
1180 // Invalid, stop iterating.
1181 SetErrorWithJSON(error, "Log event is not a dictionary", *object_sp);
1182 return false;
1183 }
1184
1185 // If we haven't already grabbed the first timestamp value, do that
1186 // now.
1188 uint64_t timestamp = 0;
1189 if (event->GetValueForKeyAsInteger("timestamp", timestamp)) {
1190 m_first_timestamp_seen = timestamp;
1192 }
1193 }
1194
1195 HandleDisplayOfEvent(*event, stream);
1196 return true;
1197 });
1198
1199 stream.Flush();
1200 return error;
1201}
1202
1204 if (type_name.GetStringRef() == GetStaticPluginName())
1205 return m_is_enabled;
1206 else
1207 return false;
1208}
1209
1211 m_is_enabled = enabled;
1212}
1213
1215 ModuleList &module_list) {
1216 Log *log = GetLog(LLDBLog::Process);
1217 LLDB_LOGF(log, "StructuredDataDarwinLog::%s called (process uid %u)",
1218 __FUNCTION__, process.GetUniqueID());
1219
1220 // Check if we should enable the darwin log support on startup/attach.
1221 if (!GetGlobalProperties().GetEnableOnStartup() &&
1223 // We're neither auto-enabled or explicitly enabled, so we shouldn't try to
1224 // enable here.
1225 LLDB_LOGF(log,
1226 "StructuredDataDarwinLog::%s not applicable, we're not "
1227 "enabled (process uid %u)",
1228 __FUNCTION__, process.GetUniqueID());
1229 return;
1230 }
1231
1232 // If we already added the breakpoint, we've got nothing left to do.
1233 {
1234 std::lock_guard<std::mutex> locker(m_added_breakpoint_mutex);
1235 if (m_added_breakpoint) {
1236 LLDB_LOGF(log,
1237 "StructuredDataDarwinLog::%s process uid %u's "
1238 "post-libtrace-init breakpoint is already set",
1239 __FUNCTION__, process.GetUniqueID());
1240 return;
1241 }
1242 }
1243
1244 // The logging support module name, specifies the name of the image name that
1245 // must be loaded into the debugged process before we can try to enable
1246 // logging.
1247 const char *logging_module_cstr =
1248 GetGlobalProperties().GetLoggingModuleName();
1249 if (!logging_module_cstr || (logging_module_cstr[0] == 0)) {
1250 // We need this. Bail.
1251 LLDB_LOGF(log,
1252 "StructuredDataDarwinLog::%s no logging module name "
1253 "specified, we don't know where to set a breakpoint "
1254 "(process uid %u)",
1255 __FUNCTION__, process.GetUniqueID());
1256 return;
1257 }
1258
1259 const ConstString logging_module_name = ConstString(logging_module_cstr);
1260
1261 // We need to see libtrace in the list of modules before we can enable
1262 // tracing for the target process.
1263 bool found_logging_support_module = false;
1264 for (size_t i = 0; i < module_list.GetSize(); ++i) {
1265 auto module_sp = module_list.GetModuleAtIndex(i);
1266 if (!module_sp)
1267 continue;
1268
1269 auto &file_spec = module_sp->GetFileSpec();
1270 found_logging_support_module =
1271 (file_spec.GetFilename() == logging_module_name);
1272 if (found_logging_support_module)
1273 break;
1274 }
1275
1276 if (!found_logging_support_module) {
1277 LLDB_LOGF(log,
1278 "StructuredDataDarwinLog::%s logging module %s "
1279 "has not yet been loaded, can't set a breakpoint "
1280 "yet (process uid %u)",
1281 __FUNCTION__, logging_module_name.AsCString(),
1282 process.GetUniqueID());
1283 return;
1284 }
1285
1286 // Time to enqueue the breakpoint so we can wait for logging support to be
1287 // initialized before we try to tap the libtrace stream.
1288 AddInitCompletionHook(process);
1289 LLDB_LOGF(log,
1290 "StructuredDataDarwinLog::%s post-init hook breakpoint "
1291 "set for logging module %s (process uid %u)",
1292 __FUNCTION__, logging_module_name.AsCString(),
1293 process.GetUniqueID());
1294
1295 // We need to try the enable here as well, which will succeed in the event
1296 // that we're attaching to (rather than launching) the process and the
1297 // process is already past initialization time. In that case, the completion
1298 // breakpoint will never get hit and therefore won't start that way. It
1299 // doesn't hurt much beyond a bit of bandwidth if we end up doing this twice.
1300 // It hurts much more if we don't get the logging enabled when the user
1301 // expects it.
1302 EnableNow();
1303}
1304
1305// public destructor
1306
1309 ProcessSP process_sp(GetProcess());
1310 if (process_sp) {
1311 process_sp->GetTarget().RemoveBreakpointByID(m_breakpoint_id);
1313 }
1314 }
1315}
1316
1317#pragma mark -
1318#pragma mark Private instance methods
1319
1320// Private constructors
1321
1323 : StructuredDataPlugin(process_wp), m_recorded_first_timestamp(false),
1324 m_first_timestamp_seen(0), m_is_enabled(false),
1325 m_added_breakpoint_mutex(), m_added_breakpoint(),
1326 m_breakpoint_id(LLDB_INVALID_BREAK_ID) {}
1327
1328// Private static methods
1329
1330StructuredDataPluginSP
1332 // Currently only Apple targets support the os_log/os_activity protocol.
1333 if (process.GetTarget().GetArchitecture().GetTriple().getVendor() ==
1334 llvm::Triple::VendorType::Apple) {
1335 auto process_wp = ProcessWP(process.shared_from_this());
1336 return StructuredDataPluginSP(new StructuredDataDarwinLog(process_wp));
1337 } else {
1338 return StructuredDataPluginSP();
1339 }
1340}
1341
1343 // Setup parent class first.
1345
1346 // Get parent command.
1347 auto &interpreter = debugger.GetCommandInterpreter();
1348 llvm::StringRef parent_command_text = "plugin structured-data";
1349 auto parent_command =
1350 interpreter.GetCommandObjectForCommand(parent_command_text);
1351 if (!parent_command) {
1352 // Ut oh, parent failed to create parent command.
1353 // TODO log
1354 return;
1355 }
1356
1357 auto command_name = "darwin-log";
1358 auto command_sp = CommandObjectSP(new BaseCommand(interpreter));
1359 bool result = parent_command->LoadSubCommand(command_name, command_sp);
1360 if (!result) {
1361 // TODO log it once we setup structured data logging
1362 }
1363
1366 const bool is_global_setting = true;
1368 debugger, GetGlobalProperties().GetValueProperties(),
1369 "Properties for the darwin-log plug-in.", is_global_setting);
1370 }
1371}
1372
1374 Target *target) {
1375 Status error;
1376
1377 // If we're not debugging this launched process, there's nothing for us to do
1378 // here.
1379 if (!launch_info.GetFlags().AnySet(eLaunchFlagDebug))
1380 return error;
1381
1382 // Darwin os_log() support automatically adds debug-level and info-level
1383 // messages when a debugger is attached to a process. However, with
1384 // integrated support for debugging built into the command-line LLDB, the
1385 // user may specifically set to *not* include debug-level and info-level
1386 // content. When the user is using the integrated log support, we want to
1387 // put the kabosh on that automatic adding of info and debug level. This is
1388 // done by adding an environment variable to the process on launch. (This
1389 // also means it is not possible to suppress this behavior if attaching to an
1390 // already-running app).
1391 // Log *log = GetLog(LLDBLog::Platform);
1392
1393 // If the target architecture is not one that supports DarwinLog, we have
1394 // nothing to do here.
1395 auto &triple = target ? target->GetArchitecture().GetTriple()
1396 : launch_info.GetArchitecture().GetTriple();
1397 if (triple.getVendor() != llvm::Triple::Apple) {
1398 return error;
1399 }
1400
1401 // If DarwinLog is not enabled (either by explicit user command or via the
1402 // auto-enable option), then we have nothing to do.
1403 if (!GetGlobalProperties().GetEnableOnStartup() &&
1405 // Nothing to do, DarwinLog is not enabled.
1406 return error;
1407 }
1408
1409 // If we don't have parsed configuration info, that implies we have enable-
1410 // on-startup set up, but we haven't yet attempted to run the enable command.
1411 if (!target) {
1412 // We really can't do this without a target. We need to be able to get to
1413 // the debugger to get the proper options to do this right.
1414 // TODO log.
1415 error.SetErrorString("requires a target to auto-enable DarwinLog.");
1416 return error;
1417 }
1418
1419 DebuggerSP debugger_sp = target->GetDebugger().shared_from_this();
1420 auto options_sp = GetGlobalEnableOptions(debugger_sp);
1421 if (!options_sp && debugger_sp) {
1422 options_sp = ParseAutoEnableOptions(error, *debugger_sp.get());
1423 if (!options_sp || !error.Success())
1424 return error;
1425
1426 // We already parsed the options, save them now so we don't generate them
1427 // again until the user runs the command manually.
1428 SetGlobalEnableOptions(debugger_sp, options_sp);
1429 }
1430
1431 if (!options_sp->GetEchoToStdErr()) {
1432 // The user doesn't want to see os_log/NSLog messages echo to stderr. That
1433 // mechanism is entirely separate from the DarwinLog support. By default we
1434 // don't want to get it via stderr, because that would be in duplicate of
1435 // the explicit log support here.
1436
1437 // Here we need to strip out any OS_ACTIVITY_DT_MODE setting to prevent
1438 // echoing of os_log()/NSLog() to stderr in the target program.
1439 launch_info.GetEnvironment().erase("OS_ACTIVITY_DT_MODE");
1440
1441 // We will also set the env var that tells any downstream launcher from
1442 // adding OS_ACTIVITY_DT_MODE.
1443 launch_info.GetEnvironment()["IDE_DISABLED_OS_ACTIVITY_DT_MODE"] = "1";
1444 }
1445
1446 // Set the OS_ACTIVITY_MODE env var appropriately to enable/disable debug and
1447 // info level messages.
1448 const char *env_var_value;
1449 if (options_sp->GetIncludeDebugLevel())
1450 env_var_value = "debug";
1451 else if (options_sp->GetIncludeInfoLevel())
1452 env_var_value = "info";
1453 else
1454 env_var_value = "default";
1455
1456 launch_info.GetEnvironment()["OS_ACTIVITY_MODE"] = env_var_value;
1457
1458 return error;
1459}
1460
1462 void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
1463 lldb::user_id_t break_loc_id) {
1464 // We hit the init function. We now want to enqueue our new thread plan,
1465 // which will in turn enqueue a StepOut thread plan. When the StepOut
1466 // finishes and control returns to our new thread plan, that is the time when
1467 // we can execute our logic to enable the logging support.
1468
1469 Log *log = GetLog(LLDBLog::Process);
1470 LLDB_LOGF(log, "StructuredDataDarwinLog::%s() called", __FUNCTION__);
1471
1472 // Get the current thread.
1473 if (!context) {
1474 LLDB_LOGF(log,
1475 "StructuredDataDarwinLog::%s() warning: no context, "
1476 "ignoring",
1477 __FUNCTION__);
1478 return false;
1479 }
1480
1481 // Get the plugin from the process.
1482 auto process_sp = context->exe_ctx_ref.GetProcessSP();
1483 if (!process_sp) {
1484 LLDB_LOGF(log,
1485 "StructuredDataDarwinLog::%s() warning: invalid "
1486 "process in context, ignoring",
1487 __FUNCTION__);
1488 return false;
1489 }
1490 LLDB_LOGF(log, "StructuredDataDarwinLog::%s() call is for process uid %d",
1491 __FUNCTION__, process_sp->GetUniqueID());
1492
1493 auto plugin_sp =
1494 process_sp->GetStructuredDataPlugin(ConstString(GetDarwinLogTypeName()));
1495 if (!plugin_sp) {
1496 LLDB_LOG(log, "warning: no plugin for feature {0} in process uid {1}",
1497 GetDarwinLogTypeName(), process_sp->GetUniqueID());
1498 return false;
1499 }
1500
1501 // Create the callback for when the thread plan completes.
1502 bool called_enable_method = false;
1503 const auto process_uid = process_sp->GetUniqueID();
1504
1505 std::weak_ptr<StructuredDataPlugin> plugin_wp(plugin_sp);
1507 [plugin_wp, &called_enable_method, log, process_uid]() {
1508 LLDB_LOGF(log,
1509 "StructuredDataDarwinLog::post-init callback: "
1510 "called (process uid %u)",
1511 process_uid);
1512
1513 auto strong_plugin_sp = plugin_wp.lock();
1514 if (!strong_plugin_sp) {
1515 LLDB_LOGF(log,
1516 "StructuredDataDarwinLog::post-init callback: "
1517 "plugin no longer exists, ignoring (process "
1518 "uid %u)",
1519 process_uid);
1520 return;
1521 }
1522 // Make sure we only call it once, just in case the thread plan hits
1523 // the breakpoint twice.
1524 if (!called_enable_method) {
1525 LLDB_LOGF(log,
1526 "StructuredDataDarwinLog::post-init callback: "
1527 "calling EnableNow() (process uid %u)",
1528 process_uid);
1529 static_cast<StructuredDataDarwinLog *>(strong_plugin_sp.get())
1530 ->EnableNow();
1531 called_enable_method = true;
1532 } else {
1533 // Our breakpoint was hit more than once. Unexpected but no harm
1534 // done. Log it.
1535 LLDB_LOGF(log,
1536 "StructuredDataDarwinLog::post-init callback: "
1537 "skipping EnableNow(), already called by "
1538 "callback [we hit this more than once] "
1539 "(process uid %u)",
1540 process_uid);
1541 }
1542 };
1543
1544 // Grab the current thread.
1545 auto thread_sp = context->exe_ctx_ref.GetThreadSP();
1546 if (!thread_sp) {
1547 LLDB_LOGF(log,
1548 "StructuredDataDarwinLog::%s() warning: failed to "
1549 "retrieve the current thread from the execution "
1550 "context, nowhere to run the thread plan (process uid "
1551 "%u)",
1552 __FUNCTION__, process_sp->GetUniqueID());
1553 return false;
1554 }
1555
1556 // Queue the thread plan.
1557 auto thread_plan_sp =
1558 ThreadPlanSP(new ThreadPlanCallOnFunctionExit(*thread_sp, callback));
1559 const bool abort_other_plans = false;
1560 thread_sp->QueueThreadPlan(thread_plan_sp, abort_other_plans);
1561 LLDB_LOGF(log,
1562 "StructuredDataDarwinLog::%s() queuing thread plan on "
1563 "trace library init method entry (process uid %u)",
1564 __FUNCTION__, process_sp->GetUniqueID());
1565
1566 // We return false here to indicate that it isn't a public stop.
1567 return false;
1568}
1569
1571 Log *log = GetLog(LLDBLog::Process);
1572 LLDB_LOGF(log, "StructuredDataDarwinLog::%s() called (process uid %u)",
1573 __FUNCTION__, process.GetUniqueID());
1574
1575 // Make sure we haven't already done this.
1576 {
1577 std::lock_guard<std::mutex> locker(m_added_breakpoint_mutex);
1578 if (m_added_breakpoint) {
1579 LLDB_LOGF(log,
1580 "StructuredDataDarwinLog::%s() ignoring request, "
1581 "breakpoint already set (process uid %u)",
1582 __FUNCTION__, process.GetUniqueID());
1583 return;
1584 }
1585
1586 // We're about to do this, don't let anybody else try to do it.
1587 m_added_breakpoint = true;
1588 }
1589
1590 // Set a breakpoint for the process that will kick in when libtrace has
1591 // finished its initialization.
1592 Target &target = process.GetTarget();
1593
1594 // Build up the module list.
1595 FileSpecList module_spec_list;
1596 auto module_file_spec =
1597 FileSpec(GetGlobalProperties().GetLoggingModuleName());
1598 module_spec_list.Append(module_file_spec);
1599
1600 // We aren't specifying a source file set.
1601 FileSpecList *source_spec_list = nullptr;
1602
1603 const char *func_name = "_libtrace_init";
1604 const lldb::addr_t offset = 0;
1605 const LazyBool skip_prologue = eLazyBoolCalculate;
1606 // This is an internal breakpoint - the user shouldn't see it.
1607 const bool internal = true;
1608 const bool hardware = false;
1609
1610 auto breakpoint_sp = target.CreateBreakpoint(
1611 &module_spec_list, source_spec_list, func_name, eFunctionNameTypeFull,
1612 eLanguageTypeC, offset, skip_prologue, internal, hardware);
1613 if (!breakpoint_sp) {
1614 // Huh? Bail here.
1615 LLDB_LOGF(log,
1616 "StructuredDataDarwinLog::%s() failed to set "
1617 "breakpoint in module %s, function %s (process uid %u)",
1618 __FUNCTION__, GetGlobalProperties().GetLoggingModuleName(),
1619 func_name, process.GetUniqueID());
1620 return;
1621 }
1622
1623 // Set our callback.
1624 breakpoint_sp->SetCallback(InitCompletionHookCallback, nullptr);
1625 m_breakpoint_id = breakpoint_sp->GetID();
1626 LLDB_LOGF(log,
1627 "StructuredDataDarwinLog::%s() breakpoint set in module %s,"
1628 "function %s (process uid %u)",
1629 __FUNCTION__, GetGlobalProperties().GetLoggingModuleName(),
1630 func_name, process.GetUniqueID());
1631}
1632
1634 uint64_t timestamp) {
1635 const uint64_t delta_nanos = timestamp - m_first_timestamp_seen;
1636
1637 const uint64_t hours = delta_nanos / NANOS_PER_HOUR;
1638 uint64_t nanos_remaining = delta_nanos % NANOS_PER_HOUR;
1639
1640 const uint64_t minutes = nanos_remaining / NANOS_PER_MINUTE;
1641 nanos_remaining = nanos_remaining % NANOS_PER_MINUTE;
1642
1643 const uint64_t seconds = nanos_remaining / NANOS_PER_SECOND;
1644 nanos_remaining = nanos_remaining % NANOS_PER_SECOND;
1645
1646 stream.Printf("%02" PRIu64 ":%02" PRIu64 ":%02" PRIu64 ".%09" PRIu64, hours,
1647 minutes, seconds, nanos_remaining);
1648}
1649
1650size_t
1652 const StructuredData::Dictionary &event) {
1653 StreamString stream;
1654
1655 ProcessSP process_sp = GetProcess();
1656 if (!process_sp) {
1657 // TODO log
1658 return 0;
1659 }
1660
1661 DebuggerSP debugger_sp =
1662 process_sp->GetTarget().GetDebugger().shared_from_this();
1663 if (!debugger_sp) {
1664 // TODO log
1665 return 0;
1666 }
1667
1668 auto options_sp = GetGlobalEnableOptions(debugger_sp);
1669 if (!options_sp) {
1670 // TODO log
1671 return 0;
1672 }
1673
1674 // Check if we should even display a header.
1675 if (!options_sp->GetDisplayAnyHeaderFields())
1676 return 0;
1677
1678 stream.PutChar('[');
1679
1680 int header_count = 0;
1681 if (options_sp->GetDisplayTimestampRelative()) {
1682 uint64_t timestamp = 0;
1683 if (event.GetValueForKeyAsInteger("timestamp", timestamp)) {
1684 DumpTimestamp(stream, timestamp);
1685 ++header_count;
1686 }
1687 }
1688
1689 if (options_sp->GetDisplayActivityChain()) {
1690 llvm::StringRef activity_chain;
1691 if (event.GetValueForKeyAsString("activity-chain", activity_chain) &&
1692 !activity_chain.empty()) {
1693 if (header_count > 0)
1694 stream.PutChar(',');
1695
1696 // Display the activity chain, from parent-most to child-most activity,
1697 // separated by a colon (:).
1698 stream.PutCString("activity-chain=");
1699 stream.PutCString(activity_chain);
1700 ++header_count;
1701 }
1702 }
1703
1704 if (options_sp->GetDisplaySubsystem()) {
1705 llvm::StringRef subsystem;
1706 if (event.GetValueForKeyAsString("subsystem", subsystem) &&
1707 !subsystem.empty()) {
1708 if (header_count > 0)
1709 stream.PutChar(',');
1710 stream.PutCString("subsystem=");
1711 stream.PutCString(subsystem);
1712 ++header_count;
1713 }
1714 }
1715
1716 if (options_sp->GetDisplayCategory()) {
1717 llvm::StringRef category;
1718 if (event.GetValueForKeyAsString("category", category) &&
1719 !category.empty()) {
1720 if (header_count > 0)
1721 stream.PutChar(',');
1722 stream.PutCString("category=");
1723 stream.PutCString(category);
1724 ++header_count;
1725 }
1726 }
1727 stream.PutCString("] ");
1728
1729 output_stream.PutCString(stream.GetString());
1730
1731 return stream.GetSize();
1732}
1733
1735 const StructuredData::Dictionary &event, Stream &stream) {
1736 // Check the type of the event.
1737 llvm::StringRef event_type;
1738 if (!event.GetValueForKeyAsString("type", event_type)) {
1739 // Hmm, we expected to get events that describe what they are. Continue
1740 // anyway.
1741 return 0;
1742 }
1743
1744 if (event_type != GetLogEventType())
1745 return 0;
1746
1747 size_t total_bytes = 0;
1748
1749 // Grab the message content.
1750 llvm::StringRef message;
1751 if (!event.GetValueForKeyAsString("message", message))
1752 return true;
1753
1754 // Display the log entry.
1755 const auto len = message.size();
1756
1757 total_bytes += DumpHeader(stream, event);
1758
1759 stream.Write(message.data(), len);
1760 total_bytes += len;
1761
1762 // Add an end of line.
1763 stream.PutChar('\n');
1764 total_bytes += sizeof(char);
1765
1766 return total_bytes;
1767}
1768
1770 Log *log = GetLog(LLDBLog::Process);
1771 LLDB_LOGF(log, "StructuredDataDarwinLog::%s() called", __FUNCTION__);
1772
1773 // Run the enable command.
1774 auto process_sp = GetProcess();
1775 if (!process_sp) {
1776 // Nothing to do.
1777 LLDB_LOGF(log,
1778 "StructuredDataDarwinLog::%s() warning: failed to get "
1779 "valid process, skipping",
1780 __FUNCTION__);
1781 return;
1782 }
1783 LLDB_LOGF(log, "StructuredDataDarwinLog::%s() call is for process uid %u",
1784 __FUNCTION__, process_sp->GetUniqueID());
1785
1786 // If we have configuration data, we can directly enable it now. Otherwise,
1787 // we need to run through the command interpreter to parse the auto-run
1788 // options (which is the only way we get here without having already-parsed
1789 // configuration data).
1790 DebuggerSP debugger_sp =
1791 process_sp->GetTarget().GetDebugger().shared_from_this();
1792 if (!debugger_sp) {
1793 LLDB_LOGF(log,
1794 "StructuredDataDarwinLog::%s() warning: failed to get "
1795 "debugger shared pointer, skipping (process uid %u)",
1796 __FUNCTION__, process_sp->GetUniqueID());
1797 return;
1798 }
1799
1800 auto options_sp = GetGlobalEnableOptions(debugger_sp);
1801 if (!options_sp) {
1802 // We haven't run the enable command yet. Just do that now, it'll take
1803 // care of the rest.
1804 auto &interpreter = debugger_sp->GetCommandInterpreter();
1805 const bool success = RunEnableCommand(interpreter);
1806 if (log) {
1807 if (success)
1808 LLDB_LOGF(log,
1809 "StructuredDataDarwinLog::%s() ran enable command "
1810 "successfully for (process uid %u)",
1811 __FUNCTION__, process_sp->GetUniqueID());
1812 else
1813 LLDB_LOGF(log,
1814 "StructuredDataDarwinLog::%s() error: running "
1815 "enable command failed (process uid %u)",
1816 __FUNCTION__, process_sp->GetUniqueID());
1817 }
1818 Debugger::ReportError("failed to configure DarwinLog support",
1819 debugger_sp->GetID());
1820 return;
1821 }
1822
1823 // We've previously been enabled. We will re-enable now with the previously
1824 // specified options.
1825 auto config_sp = options_sp->BuildConfigurationData(true);
1826 if (!config_sp) {
1827 LLDB_LOGF(log,
1828 "StructuredDataDarwinLog::%s() warning: failed to "
1829 "build configuration data for enable options, skipping "
1830 "(process uid %u)",
1831 __FUNCTION__, process_sp->GetUniqueID());
1832 return;
1833 }
1834
1835 // We can run it directly.
1836 // Send configuration to the feature by way of the process.
1837 const Status error = process_sp->ConfigureStructuredData(
1838 ConstString(GetDarwinLogTypeName()), config_sp);
1839
1840 // Report results.
1841 if (!error.Success()) {
1842 LLDB_LOGF(log,
1843 "StructuredDataDarwinLog::%s() "
1844 "ConfigureStructuredData() call failed "
1845 "(process uid %u): %s",
1846 __FUNCTION__, process_sp->GetUniqueID(), error.AsCString());
1847 Debugger::ReportError("failed to configure DarwinLog support",
1848 debugger_sp->GetID());
1849 m_is_enabled = false;
1850 } else {
1851 m_is_enabled = true;
1852 LLDB_LOGF(log,
1853 "StructuredDataDarwinLog::%s() success via direct "
1854 "configuration (process uid %u)",
1855 __FUNCTION__, process_sp->GetUniqueID());
1856 }
1857}
static llvm::raw_ostream & error(Stream &strm)
static DynamicLoaderDarwinKernelProperties & GetGlobalProperties()
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition: Log.h:337
#define LLDB_LOGF(log,...)
Definition: Log.h:344
#define LLDB_LOG_ERROR(log, error,...)
Definition: Log.h:360
#define LLDB_PLUGIN_DEFINE(PluginName)
Definition: PluginManager.h:31
static void SetErrorWithJSON(Status &error, const char *message, StructuredData::Object &object)
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition: ArchSpec.h:450
A command line argument class.
Definition: Args.h:33
void Shift()
Shifts the first argument C string value of the array off the argument array.
Definition: Args.cpp:285
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition: Args.h:116
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx.
Definition: Args.cpp:263
bool HandleCommand(const char *command_line, LazyBool add_to_history, const ExecutionContext &override_context, CommandReturnObject &result)
CommandObject * GetCommandObjectForCommand(llvm::StringRef &command_line)
bool LoadSubCommand(llvm::StringRef cmd_name, const lldb::CommandObjectSP &command_obj) override
CommandInterpreter & GetCommandInterpreter()
Target & GetSelectedOrDummyTarget(bool prefer_dummy=false)
void void AppendError(llvm::StringRef in_string)
void SetStatus(lldb::ReturnStatus status)
void void AppendWarning(llvm::StringRef in_string)
A uniqued constant string class.
Definition: ConstString.h:39
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
Definition: ConstString.h:195
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
Definition: ConstString.h:204
const char * GetCString() const
Get the string value as a C string.
Definition: ConstString.h:218
A class to manage flag bits.
Definition: Debugger.h:78
CommandInterpreter & GetCommandInterpreter()
Definition: Debugger.h:171
bool GetUseColor() const
Definition: Debugger.cpp:382
static void ReportError(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report error events.
Definition: Debugger.cpp:1488
lldb::ThreadSP GetThreadSP() const
Get accessor that creates a strong reference from the weak thread reference contained in this object.
lldb::ProcessSP GetProcessSP() const
Get accessor that creates a strong reference from the weak process reference contained in this object...
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
A file collection class.
Definition: FileSpecList.h:24
void Append(const FileSpec &file)
Append a FileSpec object to the list.
A file utility class.
Definition: FileSpec.h:56
bool AnySet(ValueType mask) const
Test one or more flags.
Definition: Flags.h:90
A collection class for Module objects.
Definition: ModuleList.h:82
lldb::ModuleSP GetModuleAtIndex(size_t idx) const
Get the module shared pointer for the module at index idx.
Definition: ModuleList.cpp:403
size_t GetSize() const
Gets the size of the module list.
Definition: ModuleList.cpp:627
A command line option parsing protocol class.
Definition: Options.h:58
std::vector< Option > m_getopt_table
Definition: Options.h:198
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static lldb::OptionValuePropertiesSP GetSettingForPlatformPlugin(Debugger &debugger, ConstString setting_name)
static bool CreateSettingForStructuredDataPlugin(Debugger &debugger, const lldb::OptionValuePropertiesSP &properties_sp, llvm::StringRef description, bool is_global_property)
static bool UnregisterPlugin(ABICreateInstance create_callback)
Environment & GetEnvironment()
Definition: ProcessInfo.h:87
ArchSpec & GetArchitecture()
Definition: ProcessInfo.h:61
A plug-in interface definition class for debugging a process.
Definition: Process.h:333
void BroadcastStructuredData(const StructuredData::ObjectSP &object_sp, const lldb::StructuredDataPluginSP &plugin_sp)
Broadcasts the given structured data object from the given plugin.
Definition: Process.cpp:4284
uint32_t GetUniqueID() const
Definition: Process.h:535
Target & GetTarget()
Get the target object pointer for this module.
Definition: Process.h:1222
lldb::OptionValuePropertiesSP m_collection_sp
virtual lldb::OptionValueSP GetPropertyValue(const ExecutionContext *exe_ctx, llvm::StringRef property_path, Status &error) const
An error handling class.
Definition: Status.h:44
General Outline: When we hit a breakpoint we need to package up whatever information is needed to eva...
const char * GetData() const
Definition: StreamString.h:43
void Flush() override
Flush the stream.
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
size_t Write(const void *src, size_t src_len)
Output character bytes to the stream.
Definition: Stream.h:101
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition: Stream.cpp:107
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition: Stream.cpp:63
size_t PutChar(char ch)
Definition: Stream.cpp:104
virtual void Flush()=0
Flush the stream.
Status GetDescription(const StructuredData::ObjectSP &object_sp, lldb_private::Stream &stream) override
Get a human-readable description of the contents of the data.
bool GetEnabled(ConstString type_name) const override
Returns whether the plugin's features are enabled.
static void DebuggerInitialize(Debugger &debugger)
bool SupportsStructuredDataType(ConstString type_name) override
Return whether this plugin supports the given StructuredData feature.
void HandleArrivalOfStructuredData(Process &process, ConstString type_name, const StructuredData::ObjectSP &object_sp) override
Handle the arrival of asynchronous structured data from the process.
void DumpTimestamp(Stream &stream, uint64_t timestamp)
static bool InitCompletionHookCallback(void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id)
StructuredDataDarwinLog(const lldb::ProcessWP &process_wp)
size_t HandleDisplayOfEvent(const StructuredData::Dictionary &event, Stream &stream)
static lldb::StructuredDataPluginSP CreateInstance(Process &process)
static Status FilterLaunchInfo(ProcessLaunchInfo &launch_info, Target *target)
void EnableNow()
Call the enable command again, using whatever settings were initially made.
size_t DumpHeader(Stream &stream, const StructuredData::Dictionary &event)
void ModulesDidLoad(Process &process, ModuleList &module_list) override
Allow the plugin to do work related to modules that loaded in the the corresponding process.
Plugin that supports process-related structured data sent asynchronously from the debug monitor (e....
static void InitializeBasePluginForDebugger(Debugger &debugger)
Derived classes must call this before attempting to hook up commands to the 'plugin structured-data' ...
bool ForEach(std::function< bool(Object *object)> const &foreach_callback) const
void AddBooleanItem(llvm::StringRef key, bool value)
bool GetValueForKeyAsInteger(llvm::StringRef key, IntType &result) const
bool GetValueForKeyAsString(llvm::StringRef key, llvm::StringRef &result) const
void AddStringItem(llvm::StringRef key, llvm::StringRef value)
bool GetValueForKeyAsArray(llvm::StringRef key, Array *&result) const
std::shared_ptr< Dictionary > DictionarySP
std::shared_ptr< Object > ObjectSP
std::shared_ptr< Array > ArraySP
Debugger & GetDebugger()
Definition: Target.h:1037
const lldb::ProcessSP & GetProcessSP() const
Definition: Target.cpp:219
lldb::BreakpointSP CreateBreakpoint(const FileSpecList *containingModules, const FileSpec &file, uint32_t line_no, uint32_t column, lldb::addr_t offset, LazyBool check_inlines, LazyBool skip_prologue, bool internal, bool request_hardware, LazyBool move_to_nearest_code)
Definition: Target.cpp:354
const ArchSpec & GetArchitecture() const
Definition: Target.h:996
This thread plan calls a function object when the current function exits.
std::function< void()> Callback
Definition for the callback made when the currently executing thread finishes executing its function.
Provides the darwin-log base command.
BaseCommand(CommandInterpreter &interpreter)
EnableCommand(CommandInterpreter &interpreter, bool enable, const char *name, const char *help, const char *syntax)
void AppendStrictSourcesWarning(CommandReturnObject &result, const char *source_name)
bool DoExecute(Args &command, CommandReturnObject &result) override
Status ParseFilterRule(llvm::StringRef rule_text)
Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg, ExecutionContext *execution_context) override
Set the value of an option.
int MatchAttributeIndex(llvm::StringRef attribute_name) const
const FilterRules & GetFilterRules() const
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
StructuredData::DictionarySP BuildConfigurationData(bool enabled)
void OptionParsingStarting(ExecutionContext *execution_context) override
static FilterRuleSP CreateOperation(bool accept, size_t attribute_index, const std::string &op_arg, Status &error)
void DoSerialization(StructuredData::Dictionary &dict) const override
void Dump(Stream &stream) const override
ExactMatchFilterRule(bool accept, size_t attribute_index, const std::string &match_text)
static CreationFuncMap & GetCreationFuncMap()
virtual void Dump(Stream &stream) const =0
FilterRule(bool accept, size_t attribute_index, ConstString operation)
virtual void DoSerialization(StructuredData::Dictionary &dict) const =0
static void RegisterOperation(ConstString operation, const OperationCreationFunc &creation_func)
StructuredData::ObjectSP Serialize() const
std::map< ConstString, OperationCreationFunc > CreationFuncMap
static FilterRuleSP CreateRule(bool match_accepts, size_t attribute, ConstString operation, const std::string &op_arg, Status &error)
std::function< FilterRuleSP(bool accept, size_t attribute_index, const std::string &op_arg, Status &error)> OperationCreationFunc
static FilterRuleSP CreateOperation(bool accept, size_t attribute_index, const std::string &op_arg, Status &error)
void DoSerialization(StructuredData::Dictionary &dict) const override
RegexFilterRule(bool accept, size_t attribute_index, const std::string &regex_text)
void Dump(Stream &stream) const override
bool DoExecute(Args &command, CommandReturnObject &result) override
StatusCommand(CommandInterpreter &interpreter)
#define LLDB_INVALID_BREAK_ID
Definition: lldb-defines.h:37
#define LLDB_OPT_SET_ALL
Definition: lldb-defines.h:101
A class that represents a running process on the host machine.
Definition: SBAttachInfo.h:14
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition: Log.h:309
Definition: SBAddress.h:15
@ eLanguageTypeC
Non-standardized C, such as K&R.
@ eReturnStatusSuccessFinishResult
@ eReturnStatusSuccessFinishNoResult
uint64_t user_id_t
Definition: lldb-types.h:80
uint64_t addr_t
Definition: lldb-types.h:79
EnableOptionsSP GetGlobalEnableOptions(const DebuggerSP &debugger_sp)
std::map< DebuggerWP, EnableOptionsSP, std::owner_less< DebuggerWP > > OptionsMap
static OptionsMap & GetGlobalOptionsMap()
const char *const s_filter_attributes[]
bool RunEnableCommand(CommandInterpreter &interpreter)
static llvm::StringRef GetLogEventType()
void SetGlobalEnableOptions(const DebuggerSP &debugger_sp, const EnableOptionsSP &options_sp)
static bool s_is_explicitly_enabled
Global, sticky enable switch.
static bool DEFAULT_FILTER_FALLTHROUGH_ACCEPTS
static std::mutex & GetGlobalOptionsMapLock()
std::shared_ptr< FilterRule > FilterRuleSP
static llvm::StringRef GetDarwinLogTypeName()
std::vector< FilterRuleSP > FilterRules
std::shared_ptr< EnableOptions > EnableOptionsSP
static constexpr OptionDefinition g_enable_option_table[]
Provides the main on-off switch for enabling darwin logging.
static StructuredDataDarwinLogProperties & GetGlobalProperties()
EnableOptionsSP ParseAutoEnableOptions(Status &error, Debugger &debugger)
static bool ToBoolean(llvm::StringRef s, bool fail_value, bool *success_ptr)