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