1 //===-- BreakpointOptions.cpp -----------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 // C Includes
11 // C++ Includes
12 // Other libraries and framework includes
13 // Project includes
14 #include "lldb/Breakpoint/BreakpointOptions.h"
15 
16 #include "lldb/Breakpoint/StoppointCallbackContext.h"
17 #include "lldb/Core/Stream.h"
18 #include "lldb/Core/StringList.h"
19 #include "lldb/Core/Value.h"
20 #include "lldb/Interpreter/CommandInterpreter.h"
21 #include "lldb/Interpreter/CommandReturnObject.h"
22 #include "lldb/Target/Process.h"
23 #include "lldb/Target/Target.h"
24 #include "lldb/Target/ThreadSpec.h"
25 
26 #include "llvm/ADT/STLExtras.h"
27 
28 using namespace lldb;
29 using namespace lldb_private;
30 
31 const char *BreakpointOptions::CommandData::g_option_names
32     [BreakpointOptions::CommandData::OptionNames::LastOptionName]{
33         "UserSource", "ScriptSource", "StopOnError"};
34 
35 StructuredData::ObjectSP
36 BreakpointOptions::CommandData::SerializeToStructuredData() {
37   size_t num_strings = user_source.GetSize();
38   if (num_strings == 0 && script_source.empty()) {
39     // We shouldn't serialize commands if there aren't any, return an empty sp
40     // to indicate this.
41     return StructuredData::ObjectSP();
42   }
43 
44   StructuredData::DictionarySP options_dict_sp(
45       new StructuredData::Dictionary());
46   options_dict_sp->AddBooleanItem(GetKey(OptionNames::StopOnError),
47                                   stop_on_error);
48 
49   StructuredData::ArraySP user_source_sp(new StructuredData::Array());
50   for (size_t i = 0; i < num_strings; i++) {
51     StructuredData::StringSP item_sp(
52         new StructuredData::String(user_source[i]));
53     user_source_sp->AddItem(item_sp);
54     options_dict_sp->AddItem(GetKey(OptionNames::UserSource), user_source_sp);
55   }
56 
57   if (!script_source.empty()) {
58     StructuredData::StringSP item_sp(new StructuredData::String(script_source));
59     options_dict_sp->AddItem(GetKey(OptionNames::ScriptSource), user_source_sp);
60   }
61   return options_dict_sp;
62 }
63 
64 std::unique_ptr<BreakpointOptions::CommandData>
65 BreakpointOptions::CommandData::CreateFromStructuredData(
66     const StructuredData::Dictionary &options_dict, Error &error) {
67   std::string script_source;
68   CommandData *data = new CommandData();
69   bool success = options_dict.GetValueForKeyAsBoolean(
70       GetKey(OptionNames::StopOnError), data->stop_on_error);
71 
72   success = options_dict.GetValueForKeyAsString(
73       GetKey(OptionNames::ScriptSource), data->script_source);
74 
75   StructuredData::Array *user_source;
76   success = options_dict.GetValueForKeyAsArray(GetKey(OptionNames::UserSource),
77                                                user_source);
78   if (success) {
79     size_t num_elems = user_source->GetSize();
80     for (size_t i = 0; i < num_elems; i++) {
81       std::string elem_string;
82       success = user_source->GetItemAtIndexAsString(i, elem_string);
83       if (success)
84         data->user_source.AppendString(elem_string);
85     }
86   }
87   return std::unique_ptr<BreakpointOptions::CommandData>(data);
88 }
89 
90 const char *BreakpointOptions::g_option_names
91     [BreakpointOptions::OptionNames::LastOptionName]{
92         "ConditionText", "IgnoreCount", "EnabledState", "OneShotState"};
93 
94 bool BreakpointOptions::NullCallback(void *baton,
95                                      StoppointCallbackContext *context,
96                                      lldb::user_id_t break_id,
97                                      lldb::user_id_t break_loc_id) {
98   return true;
99 }
100 
101 //----------------------------------------------------------------------
102 // BreakpointOptions constructor
103 //----------------------------------------------------------------------
104 BreakpointOptions::BreakpointOptions()
105     : m_callback(BreakpointOptions::NullCallback), m_callback_baton_sp(),
106       m_baton_is_command_baton(false), m_callback_is_synchronous(false),
107       m_enabled(true), m_one_shot(false), m_ignore_count(0), m_thread_spec_ap(),
108       m_condition_text(), m_condition_text_hash(0) {}
109 
110 BreakpointOptions::BreakpointOptions(const char *condition, bool enabled,
111                                      int32_t ignore, bool one_shot)
112     : m_callback(nullptr), m_baton_is_command_baton(false),
113       m_callback_is_synchronous(false), m_enabled(enabled),
114       m_one_shot(one_shot), m_ignore_count(ignore), m_condition_text(condition),
115       m_condition_text_hash(0)
116 
117 {}
118 
119 //----------------------------------------------------------------------
120 // BreakpointOptions copy constructor
121 //----------------------------------------------------------------------
122 BreakpointOptions::BreakpointOptions(const BreakpointOptions &rhs)
123     : m_callback(rhs.m_callback), m_callback_baton_sp(rhs.m_callback_baton_sp),
124       m_baton_is_command_baton(rhs.m_baton_is_command_baton),
125       m_callback_is_synchronous(rhs.m_callback_is_synchronous),
126       m_enabled(rhs.m_enabled), m_one_shot(rhs.m_one_shot),
127       m_ignore_count(rhs.m_ignore_count), m_thread_spec_ap() {
128   if (rhs.m_thread_spec_ap.get() != nullptr)
129     m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get()));
130   m_condition_text = rhs.m_condition_text;
131   m_condition_text_hash = rhs.m_condition_text_hash;
132 }
133 
134 //----------------------------------------------------------------------
135 // BreakpointOptions assignment operator
136 //----------------------------------------------------------------------
137 const BreakpointOptions &BreakpointOptions::
138 operator=(const BreakpointOptions &rhs) {
139   m_callback = rhs.m_callback;
140   m_callback_baton_sp = rhs.m_callback_baton_sp;
141   m_baton_is_command_baton = rhs.m_baton_is_command_baton;
142   m_callback_is_synchronous = rhs.m_callback_is_synchronous;
143   m_enabled = rhs.m_enabled;
144   m_one_shot = rhs.m_one_shot;
145   m_ignore_count = rhs.m_ignore_count;
146   if (rhs.m_thread_spec_ap.get() != nullptr)
147     m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get()));
148   m_condition_text = rhs.m_condition_text;
149   m_condition_text_hash = rhs.m_condition_text_hash;
150   return *this;
151 }
152 
153 BreakpointOptions *
154 BreakpointOptions::CopyOptionsNoCallback(BreakpointOptions &orig) {
155   BreakpointHitCallback orig_callback = orig.m_callback;
156   lldb::BatonSP orig_callback_baton_sp = orig.m_callback_baton_sp;
157   bool orig_is_sync = orig.m_callback_is_synchronous;
158 
159   orig.ClearCallback();
160   BreakpointOptions *ret_val = new BreakpointOptions(orig);
161 
162   orig.SetCallback(orig_callback, orig_callback_baton_sp, orig_is_sync);
163 
164   return ret_val;
165 }
166 
167 //----------------------------------------------------------------------
168 // Destructor
169 //----------------------------------------------------------------------
170 BreakpointOptions::~BreakpointOptions() = default;
171 
172 std::unique_ptr<BreakpointOptions> BreakpointOptions::CreateFromStructuredData(
173     const StructuredData::Dictionary &options_dict, Error &error) {
174   bool enabled = true;
175   bool one_shot = false;
176   int32_t ignore_count = 0;
177   std::string condition_text;
178 
179   bool success = options_dict.GetValueForKeyAsBoolean(
180       GetKey(OptionNames::EnabledState), enabled);
181   if (!success) {
182     error.SetErrorStringWithFormat("%s key is not a boolean.",
183                                    GetKey(OptionNames::EnabledState));
184     return nullptr;
185   }
186 
187   success = options_dict.GetValueForKeyAsBoolean(
188       GetKey(OptionNames::OneShotState), one_shot);
189   if (!success) {
190     error.SetErrorStringWithFormat("%s key is not a boolean.",
191                                    GetKey(OptionNames::OneShotState));
192     return nullptr;
193   }
194   success = options_dict.GetValueForKeyAsInteger(
195       GetKey(OptionNames::IgnoreCount), ignore_count);
196   if (!success) {
197     error.SetErrorStringWithFormat("%s key is not an integer.",
198                                    GetKey(OptionNames::IgnoreCount));
199     return nullptr;
200   }
201 
202   std::unique_ptr<CommandData> cmd_data;
203   StructuredData::Dictionary *cmds_dict;
204   success = options_dict.GetValueForKeyAsDictionary(
205       CommandData::GetSerializationKey(), cmds_dict);
206   if (success && cmds_dict) {
207     Error cmds_error;
208     cmd_data = CommandData::CreateFromStructuredData(*cmds_dict, cmds_error);
209     if (cmds_error.Fail()) {
210       error.SetErrorStringWithFormat(
211           "Failed to deserialize breakpoint command options: %s.",
212           cmds_error.AsCString());
213       return nullptr;
214     }
215   }
216 
217   auto bp_options = llvm::make_unique<BreakpointOptions>(
218       condition_text.c_str(), enabled, ignore_count, one_shot);
219   bp_options->SetCommandDataCallback(std::move(cmd_data));
220   return bp_options;
221 }
222 
223 StructuredData::ObjectSP BreakpointOptions::SerializeToStructuredData() {
224   StructuredData::DictionarySP options_dict_sp(
225       new StructuredData::Dictionary());
226   options_dict_sp->AddBooleanItem(GetKey(OptionNames::EnabledState), m_enabled);
227   options_dict_sp->AddBooleanItem(GetKey(OptionNames::OneShotState),
228                                   m_one_shot);
229   options_dict_sp->AddIntegerItem(GetKey(OptionNames::IgnoreCount),
230                                   m_ignore_count);
231   options_dict_sp->AddStringItem(GetKey(OptionNames::ConditionText),
232                                  m_condition_text);
233   if (m_baton_is_command_baton) {
234     auto cmd_baton =
235         std::static_pointer_cast<CommandBaton>(m_callback_baton_sp);
236     StructuredData::ObjectSP commands_sp =
237         cmd_baton->getItem()->SerializeToStructuredData();
238     if (commands_sp) {
239       options_dict_sp->AddItem(
240           BreakpointOptions::CommandData::GetSerializationKey(), commands_sp);
241     }
242   }
243   // FIXME: Need to serialize thread filter...
244   return options_dict_sp;
245 }
246 
247 //------------------------------------------------------------------
248 // Callbacks
249 //------------------------------------------------------------------
250 void BreakpointOptions::SetCallback(BreakpointHitCallback callback,
251                                     const lldb::BatonSP &callback_baton_sp,
252                                     bool callback_is_synchronous) {
253   // FIXME: This seems unsafe.  If BatonSP actually *is* a CommandBaton, but
254   // in a shared_ptr<Baton> instead of a shared_ptr<CommandBaton>, then we
255   // will set m_baton_is_command_baton to false, which is incorrect.
256   // One possible solution is to make the base Baton class provide a method
257   // such as:
258   //     virtual StringRef getBatonId() const { return ""; }
259   // and have CommandBaton override this to return something unique, and then
260   // check for it here.  Another option might be to make Baton using the llvm
261   // casting infrastructure, so that we could write something like:
262   //     if (llvm::isa<CommandBaton>(callback_baton_sp))
263   // at relevant callsites instead of storing a boolean.
264   m_callback_is_synchronous = callback_is_synchronous;
265   m_callback = callback;
266   m_callback_baton_sp = callback_baton_sp;
267   m_baton_is_command_baton = false;
268 }
269 
270 void BreakpointOptions::SetCallback(
271     BreakpointHitCallback callback,
272     const BreakpointOptions::CommandBatonSP &callback_baton_sp,
273     bool callback_is_synchronous) {
274   m_callback_is_synchronous = callback_is_synchronous;
275   m_callback = callback;
276   m_callback_baton_sp = callback_baton_sp;
277   m_baton_is_command_baton = true;
278 }
279 
280 void BreakpointOptions::ClearCallback() {
281   m_callback = BreakpointOptions::NullCallback;
282   m_callback_is_synchronous = false;
283   m_callback_baton_sp.reset();
284   m_baton_is_command_baton = false;
285 }
286 
287 Baton *BreakpointOptions::GetBaton() { return m_callback_baton_sp.get(); }
288 
289 const Baton *BreakpointOptions::GetBaton() const {
290   return m_callback_baton_sp.get();
291 }
292 
293 bool BreakpointOptions::InvokeCallback(StoppointCallbackContext *context,
294                                        lldb::user_id_t break_id,
295                                        lldb::user_id_t break_loc_id) {
296   if (m_callback && context->is_synchronous == IsCallbackSynchronous()) {
297     return m_callback(m_callback_baton_sp ? m_callback_baton_sp->data()
298                                           : nullptr,
299                       context, break_id, break_loc_id);
300   } else
301     return true;
302 }
303 
304 bool BreakpointOptions::HasCallback() const {
305   return m_callback != BreakpointOptions::NullCallback;
306 }
307 
308 void BreakpointOptions::SetCondition(const char *condition) {
309   if (!condition)
310     condition = "";
311 
312   m_condition_text.assign(condition);
313   std::hash<std::string> hasher;
314   m_condition_text_hash = hasher(m_condition_text);
315 }
316 
317 const char *BreakpointOptions::GetConditionText(size_t *hash) const {
318   if (!m_condition_text.empty()) {
319     if (hash)
320       *hash = m_condition_text_hash;
321 
322     return m_condition_text.c_str();
323   } else {
324     return nullptr;
325   }
326 }
327 
328 const ThreadSpec *BreakpointOptions::GetThreadSpecNoCreate() const {
329   return m_thread_spec_ap.get();
330 }
331 
332 ThreadSpec *BreakpointOptions::GetThreadSpec() {
333   if (m_thread_spec_ap.get() == nullptr)
334     m_thread_spec_ap.reset(new ThreadSpec());
335 
336   return m_thread_spec_ap.get();
337 }
338 
339 void BreakpointOptions::SetThreadID(lldb::tid_t thread_id) {
340   GetThreadSpec()->SetTID(thread_id);
341 }
342 
343 void BreakpointOptions::GetDescription(Stream *s,
344                                        lldb::DescriptionLevel level) const {
345   // Figure out if there are any options not at their default value, and only
346   // print
347   // anything if there are:
348 
349   if (m_ignore_count != 0 || !m_enabled || m_one_shot ||
350       (GetThreadSpecNoCreate() != nullptr &&
351        GetThreadSpecNoCreate()->HasSpecification())) {
352     if (level == lldb::eDescriptionLevelVerbose) {
353       s->EOL();
354       s->IndentMore();
355       s->Indent();
356       s->PutCString("Breakpoint Options:\n");
357       s->IndentMore();
358       s->Indent();
359     } else
360       s->PutCString(" Options: ");
361 
362     if (m_ignore_count > 0)
363       s->Printf("ignore: %d ", m_ignore_count);
364     s->Printf("%sabled ", m_enabled ? "en" : "dis");
365 
366     if (m_one_shot)
367       s->Printf("one-shot ");
368 
369     if (m_thread_spec_ap.get())
370       m_thread_spec_ap->GetDescription(s, level);
371 
372     if (level == lldb::eDescriptionLevelFull) {
373       s->IndentLess();
374       s->IndentMore();
375     }
376   }
377 
378   if (m_callback_baton_sp.get()) {
379     if (level != eDescriptionLevelBrief) {
380       s->EOL();
381       m_callback_baton_sp->GetDescription(s, level);
382     }
383   }
384   if (!m_condition_text.empty()) {
385     if (level != eDescriptionLevelBrief) {
386       s->EOL();
387       s->Printf("Condition: %s\n", m_condition_text.c_str());
388     }
389   }
390 }
391 
392 void BreakpointOptions::CommandBaton::GetDescription(
393     Stream *s, lldb::DescriptionLevel level) const {
394   const CommandData *data = getItem();
395 
396   if (level == eDescriptionLevelBrief) {
397     s->Printf(", commands = %s",
398               (data && data->user_source.GetSize() > 0) ? "yes" : "no");
399     return;
400   }
401 
402   s->IndentMore();
403   s->Indent("Breakpoint commands:\n");
404 
405   s->IndentMore();
406   if (data && data->user_source.GetSize() > 0) {
407     const size_t num_strings = data->user_source.GetSize();
408     for (size_t i = 0; i < num_strings; ++i) {
409       s->Indent(data->user_source.GetStringAtIndex(i));
410       s->EOL();
411     }
412   } else {
413     s->PutCString("No commands.\n");
414   }
415   s->IndentLess();
416   s->IndentLess();
417 }
418 
419 void BreakpointOptions::SetCommandDataCallback(
420     std::unique_ptr<CommandData> cmd_data) {
421   auto baton_sp = std::make_shared<CommandBaton>(std::move(cmd_data));
422   SetCallback(BreakpointOptions::BreakpointOptionsCallbackFunction, baton_sp);
423 }
424 
425 bool BreakpointOptions::BreakpointOptionsCallbackFunction(
426     void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id,
427     lldb::user_id_t break_loc_id) {
428   bool ret_value = true;
429   if (baton == nullptr)
430     return true;
431 
432   CommandData *data = (CommandData *)baton;
433   StringList &commands = data->user_source;
434 
435   if (commands.GetSize() > 0) {
436     ExecutionContext exe_ctx(context->exe_ctx_ref);
437     Target *target = exe_ctx.GetTargetPtr();
438     if (target) {
439       CommandReturnObject result;
440       Debugger &debugger = target->GetDebugger();
441       // Rig up the results secondary output stream to the debugger's, so the
442       // output will come out synchronously
443       // if the debugger is set up that way.
444 
445       StreamSP output_stream(debugger.GetAsyncOutputStream());
446       StreamSP error_stream(debugger.GetAsyncErrorStream());
447       result.SetImmediateOutputStream(output_stream);
448       result.SetImmediateErrorStream(error_stream);
449 
450       CommandInterpreterRunOptions options;
451       options.SetStopOnContinue(true);
452       options.SetStopOnError(data->stop_on_error);
453       options.SetEchoCommands(true);
454       options.SetPrintResults(true);
455       options.SetAddToHistory(false);
456 
457       debugger.GetCommandInterpreter().HandleCommands(commands, &exe_ctx,
458                                                       options, result);
459       result.GetImmediateOutputStream()->Flush();
460       result.GetImmediateErrorStream()->Flush();
461     }
462   }
463   return ret_value;
464 }
465