xref: /llvm-project/lldb/source/Commands/CommandObjectThread.cpp (revision e1cfbc79420fee0b71bad62f8d413b68a0eca91e)
1 //===-- CommandObjectThread.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 #include "CommandObjectThread.h"
11 
12 // C Includes
13 // C++ Includes
14 // Other libraries and framework includes
15 // Project includes
16 #include "lldb/lldb-private.h"
17 #include "lldb/Core/State.h"
18 #include "lldb/Core/SourceManager.h"
19 #include "lldb/Core/ValueObject.h"
20 #include "lldb/Host/Host.h"
21 #include "lldb/Host/StringConvert.h"
22 #include "lldb/Interpreter/CommandInterpreter.h"
23 #include "lldb/Interpreter/CommandReturnObject.h"
24 #include "lldb/Interpreter/Options.h"
25 #include "lldb/Symbol/CompileUnit.h"
26 #include "lldb/Symbol/Function.h"
27 #include "lldb/Symbol/LineTable.h"
28 #include "lldb/Symbol/LineEntry.h"
29 #include "lldb/Target/Process.h"
30 #include "lldb/Target/RegisterContext.h"
31 #include "lldb/Target/SystemRuntime.h"
32 #include "lldb/Target/Target.h"
33 #include "lldb/Target/Thread.h"
34 #include "lldb/Target/ThreadPlan.h"
35 #include "lldb/Target/ThreadPlanStepInstruction.h"
36 #include "lldb/Target/ThreadPlanStepOut.h"
37 #include "lldb/Target/ThreadPlanStepRange.h"
38 #include "lldb/Target/ThreadPlanStepInRange.h"
39 
40 using namespace lldb;
41 using namespace lldb_private;
42 
43 //-------------------------------------------------------------------------
44 // CommandObjectThreadBacktrace
45 //-------------------------------------------------------------------------
46 
47 class CommandObjectIterateOverThreads : public CommandObjectParsed
48 {
49 public:
50     CommandObjectIterateOverThreads (CommandInterpreter &interpreter,
51                          const char *name,
52                          const char *help,
53                          const char *syntax,
54                          uint32_t flags) :
55         CommandObjectParsed (interpreter, name, help, syntax, flags)
56     {
57     }
58 
59     ~CommandObjectIterateOverThreads() override = default;
60 
61     bool
62     DoExecute (Args& command, CommandReturnObject &result) override
63     {
64         result.SetStatus (m_success_return);
65 
66         if (command.GetArgumentCount() == 0)
67         {
68             Thread *thread = m_exe_ctx.GetThreadPtr();
69             if (!HandleOneThread (thread->GetID(), result))
70                 return false;
71             return result.Succeeded();
72         }
73 
74         // Use tids instead of ThreadSPs to prevent deadlocking problems which result from JIT-ing
75         // code while iterating over the (locked) ThreadSP list.
76         std::vector<lldb::tid_t> tids;
77 
78         if (command.GetArgumentCount() == 1 && ::strcmp (command.GetArgumentAtIndex(0), "all") == 0)
79         {
80             Process *process = m_exe_ctx.GetProcessPtr();
81 
82             for (ThreadSP thread_sp : process->Threads())
83                 tids.push_back(thread_sp->GetID());
84         }
85         else
86         {
87             const size_t num_args = command.GetArgumentCount();
88             Process *process = m_exe_ctx.GetProcessPtr();
89 
90             std::lock_guard<std::recursive_mutex> guard(process->GetThreadList().GetMutex());
91 
92             for (size_t i = 0; i < num_args; i++)
93             {
94                 bool success;
95 
96                 uint32_t thread_idx = StringConvert::ToUInt32(command.GetArgumentAtIndex(i), 0, 0, &success);
97                 if (!success)
98                 {
99                     result.AppendErrorWithFormat ("invalid thread specification: \"%s\"\n", command.GetArgumentAtIndex(i));
100                     result.SetStatus (eReturnStatusFailed);
101                     return false;
102                 }
103 
104                 ThreadSP thread = process->GetThreadList().FindThreadByIndexID(thread_idx);
105 
106                 if (!thread)
107                 {
108                     result.AppendErrorWithFormat ("no thread with index: \"%s\"\n", command.GetArgumentAtIndex(i));
109                     result.SetStatus (eReturnStatusFailed);
110                     return false;
111                 }
112 
113                 tids.push_back(thread->GetID());
114             }
115         }
116 
117         uint32_t idx = 0;
118         for (const lldb::tid_t &tid : tids)
119         {
120             if (idx != 0 && m_add_return)
121                 result.AppendMessage("");
122 
123             if (!HandleOneThread (tid, result))
124                 return false;
125 
126             ++idx;
127         }
128         return result.Succeeded();
129     }
130 
131 protected:
132     // Override this to do whatever you need to do for one thread.
133     //
134     // If you return false, the iteration will stop, otherwise it will proceed.
135     // The result is set to m_success_return (defaults to eReturnStatusSuccessFinishResult) before the iteration,
136     // so you only need to set the return status in HandleOneThread if you want to indicate an error.
137     // If m_add_return is true, a blank line will be inserted between each of the listings (except the last one.)
138 
139     virtual bool
140     HandleOneThread (lldb::tid_t, CommandReturnObject &result) = 0;
141 
142     ReturnStatus m_success_return = eReturnStatusSuccessFinishResult;
143     bool m_add_return = true;
144 };
145 
146 //-------------------------------------------------------------------------
147 // CommandObjectThreadBacktrace
148 //-------------------------------------------------------------------------
149 
150 class CommandObjectThreadBacktrace : public CommandObjectIterateOverThreads
151 {
152 public:
153     class CommandOptions : public Options
154     {
155     public:
156         CommandOptions() :
157             Options()
158         {
159             // Keep default values of all options in one place: OptionParsingStarting ()
160             OptionParsingStarting(nullptr);
161         }
162 
163         ~CommandOptions() override = default;
164 
165         Error
166         SetOptionValue(uint32_t option_idx, const char *option_arg,
167                        ExecutionContext *execution_context) override
168         {
169             Error error;
170             const int short_option = m_getopt_table[option_idx].val;
171 
172             switch (short_option)
173             {
174                 case 'c':
175                 {
176                     bool success;
177                     int32_t input_count =  StringConvert::ToSInt32 (option_arg, -1, 0, &success);
178                     if (!success)
179                         error.SetErrorStringWithFormat("invalid integer value for option '%c'", short_option);
180                     if (input_count < -1)
181                         m_count = UINT32_MAX;
182                     else
183                         m_count = input_count;
184                 }
185                 break;
186                 case 's':
187                 {
188                     bool success;
189                     m_start =  StringConvert::ToUInt32 (option_arg, 0, 0, &success);
190                     if (!success)
191                         error.SetErrorStringWithFormat("invalid integer value for option '%c'", short_option);
192                 }
193                 break;
194                 case 'e':
195                 {
196                     bool success;
197                     m_extended_backtrace =  Args::StringToBoolean (option_arg, false, &success);
198                     if (!success)
199                         error.SetErrorStringWithFormat("invalid boolean value for option '%c'", short_option);
200                 }
201                 break;
202                 default:
203                     error.SetErrorStringWithFormat("invalid short option character '%c'", short_option);
204                     break;
205             }
206             return error;
207         }
208 
209         void
210         OptionParsingStarting(ExecutionContext *execution_context) override
211         {
212             m_count = UINT32_MAX;
213             m_start = 0;
214             m_extended_backtrace = false;
215         }
216 
217         const OptionDefinition*
218         GetDefinitions () override
219         {
220             return g_option_table;
221         }
222 
223         // Options table: Required for subclasses of Options.
224 
225         static OptionDefinition g_option_table[];
226 
227         // Instance variables to hold the values for command options.
228         uint32_t m_count;
229         uint32_t m_start;
230         bool     m_extended_backtrace;
231     };
232 
233     CommandObjectThreadBacktrace(CommandInterpreter &interpreter)
234         : CommandObjectIterateOverThreads(
235               interpreter, "thread backtrace", "Show thread call stacks.  Defaults to the current thread, thread "
236                                                "indexes can be specified as arguments.  Use the thread-index \"all\" "
237                                                "to see all threads.",
238               nullptr, eCommandRequiresProcess | eCommandRequiresThread | eCommandTryTargetAPILock |
239                            eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
240           m_options()
241     {
242     }
243 
244     ~CommandObjectThreadBacktrace() override = default;
245 
246     Options *
247     GetOptions () override
248     {
249         return &m_options;
250     }
251 
252 protected:
253     void
254     DoExtendedBacktrace (Thread *thread, CommandReturnObject &result)
255     {
256         SystemRuntime *runtime = thread->GetProcess()->GetSystemRuntime();
257         if (runtime)
258         {
259             Stream &strm = result.GetOutputStream();
260             const std::vector<ConstString> &types = runtime->GetExtendedBacktraceTypes();
261             for (auto type : types)
262             {
263                 ThreadSP ext_thread_sp = runtime->GetExtendedBacktraceThread (thread->shared_from_this(), type);
264                 if (ext_thread_sp && ext_thread_sp->IsValid ())
265                 {
266                     const uint32_t num_frames_with_source = 0;
267                     if (ext_thread_sp->GetStatus (strm,
268                         m_options.m_start,
269                         m_options.m_count,
270                         num_frames_with_source))
271                     {
272                         DoExtendedBacktrace (ext_thread_sp.get(), result);
273                     }
274                 }
275             }
276         }
277     }
278 
279     bool
280     HandleOneThread (lldb::tid_t tid, CommandReturnObject &result) override
281     {
282         ThreadSP thread_sp = m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
283         if (!thread_sp)
284         {
285             result.AppendErrorWithFormat ("thread disappeared while computing backtraces: 0x%" PRIx64 "\n", tid);
286             result.SetStatus (eReturnStatusFailed);
287             return false;
288         }
289 
290         Thread *thread = thread_sp.get();
291 
292         Stream &strm = result.GetOutputStream();
293 
294         // Don't show source context when doing backtraces.
295         const uint32_t num_frames_with_source = 0;
296 
297         if (!thread->GetStatus (strm,
298                                 m_options.m_start,
299                                 m_options.m_count,
300                                 num_frames_with_source))
301         {
302             result.AppendErrorWithFormat ("error displaying backtrace for thread: \"0x%4.4x\"\n", thread->GetIndexID());
303             result.SetStatus (eReturnStatusFailed);
304             return false;
305         }
306         if (m_options.m_extended_backtrace)
307         {
308             DoExtendedBacktrace (thread, result);
309         }
310 
311         return true;
312     }
313 
314     CommandOptions m_options;
315 };
316 
317 OptionDefinition
318 CommandObjectThreadBacktrace::CommandOptions::g_option_table[] =
319 {
320 { LLDB_OPT_SET_1, false, "count", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCount, "How many frames to display (-1 for all)"},
321 { LLDB_OPT_SET_1, false, "start", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeFrameIndex, "Frame in which to start the backtrace"},
322 { LLDB_OPT_SET_1, false, "extended", 'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeBoolean, "Show the extended backtrace, if available"},
323 { 0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr }
324 };
325 
326 enum StepScope
327 {
328     eStepScopeSource,
329     eStepScopeInstruction
330 };
331 
332 class CommandObjectThreadStepWithTypeAndScope : public CommandObjectParsed
333 {
334 public:
335     class CommandOptions : public Options
336     {
337     public:
338         CommandOptions() :
339             Options()
340         {
341             // Keep default values of all options in one place: OptionParsingStarting ()
342             OptionParsingStarting(nullptr);
343         }
344 
345         ~CommandOptions() override = default;
346 
347         Error
348         SetOptionValue (uint32_t option_idx, const char *option_arg,
349                         ExecutionContext *execution_context) override
350         {
351             Error error;
352             const int short_option = m_getopt_table[option_idx].val;
353 
354             switch (short_option)
355             {
356             case 'a':
357                 {
358                     bool success;
359                     bool avoid_no_debug =  Args::StringToBoolean (option_arg, true, &success);
360                     if (!success)
361                         error.SetErrorStringWithFormat("invalid boolean value for option '%c'", short_option);
362                     else
363                     {
364                         m_step_in_avoid_no_debug = avoid_no_debug ? eLazyBoolYes : eLazyBoolNo;
365                     }
366                 }
367                 break;
368 
369             case 'A':
370                 {
371                     bool success;
372                     bool avoid_no_debug =  Args::StringToBoolean (option_arg, true, &success);
373                     if (!success)
374                         error.SetErrorStringWithFormat("invalid boolean value for option '%c'", short_option);
375                     else
376                     {
377                         m_step_out_avoid_no_debug = avoid_no_debug ? eLazyBoolYes : eLazyBoolNo;
378                     }
379                 }
380                 break;
381 
382             case 'c':
383                 m_step_count = StringConvert::ToUInt32(option_arg, UINT32_MAX, 0);
384                 if (m_step_count == UINT32_MAX)
385                     error.SetErrorStringWithFormat ("invalid step count '%s'", option_arg);
386                 break;
387 
388             case 'C':
389                 m_class_name.clear();
390                 m_class_name.assign(option_arg);
391                 break;
392 
393             case 'm':
394                 {
395                     OptionEnumValueElement *enum_values = g_option_table[option_idx].enum_values;
396                     m_run_mode = (lldb::RunMode) Args::StringToOptionEnum(option_arg, enum_values, eOnlyDuringStepping, error);
397                 }
398                 break;
399 
400             case 'e':
401                 {
402                     if (strcmp(option_arg, "block") == 0)
403                     {
404                         m_end_line_is_block_end = 1;
405                         break;
406                     }
407                     uint32_t tmp_end_line = StringConvert::ToUInt32(option_arg, UINT32_MAX, 0);
408                     if (tmp_end_line == UINT32_MAX)
409                        error.SetErrorStringWithFormat ("invalid end line number '%s'", option_arg);
410                     else
411                         m_end_line = tmp_end_line;
412                     break;
413                 }
414                 break;
415 
416             case 'r':
417                 m_avoid_regexp.clear();
418                 m_avoid_regexp.assign(option_arg);
419                 break;
420 
421             case 't':
422                 m_step_in_target.clear();
423                 m_step_in_target.assign(option_arg);
424                 break;
425 
426             default:
427                 error.SetErrorStringWithFormat("invalid short option character '%c'", short_option);
428                 break;
429             }
430             return error;
431         }
432 
433         void
434         OptionParsingStarting(ExecutionContext *execution_context) override
435         {
436             m_step_in_avoid_no_debug = eLazyBoolCalculate;
437             m_step_out_avoid_no_debug = eLazyBoolCalculate;
438             m_run_mode = eOnlyDuringStepping;
439 
440             // Check if we are in Non-Stop mode
441             TargetSP target_sp =
442                 execution_context ? execution_context->GetTargetSP() :
443                 TargetSP();
444             if (target_sp && target_sp->GetNonStopModeEnabled())
445                 m_run_mode = eOnlyThisThread;
446 
447             m_avoid_regexp.clear();
448             m_step_in_target.clear();
449             m_class_name.clear();
450             m_step_count = 1;
451             m_end_line = LLDB_INVALID_LINE_NUMBER;
452             m_end_line_is_block_end = false;
453         }
454 
455         const OptionDefinition*
456         GetDefinitions () override
457         {
458             return g_option_table;
459         }
460 
461         // Options table: Required for subclasses of Options.
462 
463         static OptionDefinition g_option_table[];
464 
465         // Instance variables to hold the values for command options.
466         LazyBool m_step_in_avoid_no_debug;
467         LazyBool m_step_out_avoid_no_debug;
468         RunMode m_run_mode;
469         std::string m_avoid_regexp;
470         std::string m_step_in_target;
471         std::string m_class_name;
472         uint32_t m_step_count;
473         uint32_t m_end_line;
474         bool     m_end_line_is_block_end;
475     };
476 
477     CommandObjectThreadStepWithTypeAndScope (CommandInterpreter &interpreter,
478                                              const char *name,
479                                              const char *help,
480                                              const char *syntax,
481                                              StepType step_type,
482                                              StepScope step_scope) :
483         CommandObjectParsed (interpreter, name, help, syntax,
484                              eCommandRequiresProcess       |
485                              eCommandRequiresThread        |
486                              eCommandTryTargetAPILock      |
487                              eCommandProcessMustBeLaunched |
488                              eCommandProcessMustBePaused   ),
489         m_step_type (step_type),
490         m_step_scope (step_scope),
491         m_options()
492     {
493         CommandArgumentEntry arg;
494         CommandArgumentData thread_id_arg;
495 
496         // Define the first (and only) variant of this arg.
497         thread_id_arg.arg_type = eArgTypeThreadID;
498         thread_id_arg.arg_repetition = eArgRepeatOptional;
499 
500         // There is only one variant this argument could be; put it into the argument entry.
501         arg.push_back (thread_id_arg);
502 
503         // Push the data for the first argument into the m_arguments vector.
504         m_arguments.push_back (arg);
505     }
506 
507     ~CommandObjectThreadStepWithTypeAndScope() override = default;
508 
509     Options *
510     GetOptions () override
511     {
512         return &m_options;
513     }
514 
515 protected:
516     bool
517     DoExecute (Args& command, CommandReturnObject &result) override
518     {
519         Process *process = m_exe_ctx.GetProcessPtr();
520         bool synchronous_execution = m_interpreter.GetSynchronous();
521 
522         const uint32_t num_threads = process->GetThreadList().GetSize();
523         Thread *thread = nullptr;
524 
525         if (command.GetArgumentCount() == 0)
526         {
527             thread = GetDefaultThread();
528 
529             if (thread == nullptr)
530             {
531                 result.AppendError ("no selected thread in process");
532                 result.SetStatus (eReturnStatusFailed);
533                 return false;
534             }
535         }
536         else
537         {
538             const char *thread_idx_cstr = command.GetArgumentAtIndex(0);
539             uint32_t step_thread_idx = StringConvert::ToUInt32 (thread_idx_cstr, LLDB_INVALID_INDEX32);
540             if (step_thread_idx == LLDB_INVALID_INDEX32)
541             {
542                 result.AppendErrorWithFormat ("invalid thread index '%s'.\n", thread_idx_cstr);
543                 result.SetStatus (eReturnStatusFailed);
544                 return false;
545             }
546             thread = process->GetThreadList().FindThreadByIndexID(step_thread_idx).get();
547             if (thread == nullptr)
548             {
549                 result.AppendErrorWithFormat ("Thread index %u is out of range (valid values are 0 - %u).\n",
550                                               step_thread_idx, num_threads);
551                 result.SetStatus (eReturnStatusFailed);
552                 return false;
553             }
554         }
555 
556         if (m_step_type == eStepTypeScripted)
557         {
558             if (m_options.m_class_name.empty())
559             {
560                 result.AppendErrorWithFormat ("empty class name for scripted step.");
561                 result.SetStatus(eReturnStatusFailed);
562                 return false;
563             }
564             else if (!m_interpreter.GetScriptInterpreter()->CheckObjectExists(m_options.m_class_name.c_str()))
565             {
566                 result.AppendErrorWithFormat ("class for scripted step: \"%s\" does not exist.", m_options.m_class_name.c_str());
567                 result.SetStatus(eReturnStatusFailed);
568                 return false;
569             }
570         }
571 
572         if (m_options.m_end_line != LLDB_INVALID_LINE_NUMBER
573             && m_step_type != eStepTypeInto)
574         {
575             result.AppendErrorWithFormat("end line option is only valid for step into");
576             result.SetStatus(eReturnStatusFailed);
577             return false;
578         }
579 
580         const bool abort_other_plans = false;
581         const lldb::RunMode stop_other_threads = m_options.m_run_mode;
582 
583         // This is a bit unfortunate, but not all the commands in this command object support
584         // only while stepping, so I use the bool for them.
585         bool bool_stop_other_threads;
586         if (m_options.m_run_mode == eAllThreads)
587             bool_stop_other_threads = false;
588         else if (m_options.m_run_mode == eOnlyDuringStepping)
589             bool_stop_other_threads = (m_step_type != eStepTypeOut && m_step_type != eStepTypeScripted);
590         else
591             bool_stop_other_threads = true;
592 
593         ThreadPlanSP new_plan_sp;
594 
595         if (m_step_type == eStepTypeInto)
596         {
597             StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
598             assert(frame != nullptr);
599 
600             if (frame->HasDebugInformation ())
601             {
602                 AddressRange range;
603                 SymbolContext sc = frame->GetSymbolContext(eSymbolContextEverything);
604                 if (m_options.m_end_line != LLDB_INVALID_LINE_NUMBER)
605                 {
606                     Error error;
607                     if (!sc.GetAddressRangeFromHereToEndLine(m_options.m_end_line, range, error))
608                     {
609                         result.AppendErrorWithFormat("invalid end-line option: %s.", error.AsCString());
610                         result.SetStatus(eReturnStatusFailed);
611                         return false;
612                     }
613                 }
614                 else if (m_options.m_end_line_is_block_end)
615                 {
616                     Error error;
617                     Block *block = frame->GetSymbolContext(eSymbolContextBlock).block;
618                     if (!block)
619                     {
620                         result.AppendErrorWithFormat("Could not find the current block.");
621                         result.SetStatus(eReturnStatusFailed);
622                         return false;
623                     }
624 
625                     AddressRange block_range;
626                     Address pc_address = frame->GetFrameCodeAddress();
627                     block->GetRangeContainingAddress(pc_address, block_range);
628                     if (!block_range.GetBaseAddress().IsValid())
629                     {
630                         result.AppendErrorWithFormat("Could not find the current block address.");
631                         result.SetStatus(eReturnStatusFailed);
632                         return false;
633                     }
634                     lldb::addr_t pc_offset_in_block = pc_address.GetFileAddress() - block_range.GetBaseAddress().GetFileAddress();
635                     lldb::addr_t range_length = block_range.GetByteSize() - pc_offset_in_block;
636                     range = AddressRange(pc_address, range_length);
637                 }
638                 else
639                 {
640                     range = sc.line_entry.range;
641                 }
642 
643                 new_plan_sp = thread->QueueThreadPlanForStepInRange (abort_other_plans,
644                                                                      range,
645                                                                      frame->GetSymbolContext(eSymbolContextEverything),
646                                                                      m_options.m_step_in_target.c_str(),
647                                                                      stop_other_threads,
648                                                                      m_options.m_step_in_avoid_no_debug,
649                                                                      m_options.m_step_out_avoid_no_debug);
650 
651                 if (new_plan_sp && !m_options.m_avoid_regexp.empty())
652                 {
653                     ThreadPlanStepInRange *step_in_range_plan = static_cast<ThreadPlanStepInRange *> (new_plan_sp.get());
654                     step_in_range_plan->SetAvoidRegexp(m_options.m_avoid_regexp.c_str());
655                 }
656             }
657             else
658                 new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction (false, abort_other_plans, bool_stop_other_threads);
659         }
660         else if (m_step_type == eStepTypeOver)
661         {
662             StackFrame *frame = thread->GetStackFrameAtIndex(0).get();
663 
664             if (frame->HasDebugInformation())
665                 new_plan_sp = thread->QueueThreadPlanForStepOverRange (abort_other_plans,
666                                                                     frame->GetSymbolContext(eSymbolContextEverything).line_entry,
667                                                                     frame->GetSymbolContext(eSymbolContextEverything),
668                                                                     stop_other_threads,
669                                                                     m_options.m_step_out_avoid_no_debug);
670             else
671                 new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction (true,
672                                                                             abort_other_plans,
673                                                                             bool_stop_other_threads);
674         }
675         else if (m_step_type == eStepTypeTrace)
676         {
677             new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction (false, abort_other_plans, bool_stop_other_threads);
678         }
679         else if (m_step_type == eStepTypeTraceOver)
680         {
681             new_plan_sp = thread->QueueThreadPlanForStepSingleInstruction (true, abort_other_plans, bool_stop_other_threads);
682         }
683         else if (m_step_type == eStepTypeOut)
684         {
685             new_plan_sp = thread->QueueThreadPlanForStepOut(abort_other_plans,
686                                                             nullptr,
687                                                             false,
688                                                             bool_stop_other_threads,
689                                                             eVoteYes,
690                                                             eVoteNoOpinion,
691                                                             thread->GetSelectedFrameIndex(),
692                                                             m_options.m_step_out_avoid_no_debug);
693         }
694         else if (m_step_type == eStepTypeScripted)
695         {
696             new_plan_sp = thread->QueueThreadPlanForStepScripted (abort_other_plans,
697                                                                   m_options.m_class_name.c_str(),
698                                                                   bool_stop_other_threads);
699         }
700         else
701         {
702             result.AppendError ("step type is not supported");
703             result.SetStatus (eReturnStatusFailed);
704             return false;
705         }
706 
707         // If we got a new plan, then set it to be a master plan (User level Plans should be master plans
708         // so that they can be interruptible).  Then resume the process.
709 
710         if (new_plan_sp)
711         {
712             new_plan_sp->SetIsMasterPlan (true);
713             new_plan_sp->SetOkayToDiscard (false);
714 
715             if (m_options.m_step_count > 1)
716             {
717                 if (new_plan_sp->SetIterationCount(m_options.m_step_count))
718                 {
719                     result.AppendWarning ("step operation does not support iteration count.");
720                 }
721             }
722 
723             process->GetThreadList().SetSelectedThreadByID (thread->GetID());
724 
725             const uint32_t iohandler_id = process->GetIOHandlerID();
726 
727             StreamString stream;
728             Error error;
729             if (synchronous_execution)
730                 error = process->ResumeSynchronous (&stream);
731             else
732                 error = process->Resume ();
733 
734             // There is a race condition where this thread will return up the call stack to the main command handler
735             // and show an (lldb) prompt before HandlePrivateEvent (from PrivateStateThread) has
736             // a chance to call PushProcessIOHandler().
737             process->SyncIOHandler(iohandler_id, 2000);
738 
739             if (synchronous_execution)
740             {
741                 // If any state changed events had anything to say, add that to the result
742                 if (stream.GetData())
743                     result.AppendMessage(stream.GetData());
744 
745                 process->GetThreadList().SetSelectedThreadByID (thread->GetID());
746                 result.SetDidChangeProcessState (true);
747                 result.SetStatus (eReturnStatusSuccessFinishNoResult);
748             }
749             else
750             {
751                 result.SetStatus (eReturnStatusSuccessContinuingNoResult);
752             }
753         }
754         else
755         {
756             result.AppendError ("Couldn't find thread plan to implement step type.");
757             result.SetStatus (eReturnStatusFailed);
758         }
759         return result.Succeeded();
760     }
761 
762 protected:
763     StepType m_step_type;
764     StepScope m_step_scope;
765     CommandOptions m_options;
766 };
767 
768 static OptionEnumValueElement
769 g_tri_running_mode[] =
770 {
771 { eOnlyThisThread,     "this-thread",    "Run only this thread"},
772 { eAllThreads,         "all-threads",    "Run all threads"},
773 { eOnlyDuringStepping, "while-stepping", "Run only this thread while stepping"},
774 { 0, nullptr, nullptr }
775 };
776 
777 static OptionEnumValueElement
778 g_duo_running_mode[] =
779 {
780 { eOnlyThisThread,     "this-thread",    "Run only this thread"},
781 { eAllThreads,         "all-threads",    "Run all threads"},
782 { 0, nullptr, nullptr }
783 };
784 
785 OptionDefinition
786 CommandObjectThreadStepWithTypeAndScope::CommandOptions::g_option_table[] =
787 {
788 { LLDB_OPT_SET_1, false, "step-in-avoids-no-debug",   'a', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypeBoolean,     "A boolean value that sets whether stepping into functions will step over functions with no debug information."},
789 { LLDB_OPT_SET_1, false, "step-out-avoids-no-debug",  'A', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypeBoolean,     "A boolean value, if true stepping out of functions will continue to step out till it hits a function with debug information."},
790 { LLDB_OPT_SET_1, false, "count",                     'c', OptionParser::eRequiredArgument, nullptr, nullptr,               1, eArgTypeCount,     "How many times to perform the stepping operation - currently only supported for step-inst and next-inst."},
791 { LLDB_OPT_SET_1, false, "end-linenumber",            'e', OptionParser::eRequiredArgument, nullptr, nullptr,               1, eArgTypeLineNum,     "The line at which to stop stepping - defaults to the next line and only supported for step-in and step-over."
792                                                                                                                                               "  You can also pass the string 'block' to step to the end of the current block."
793                                                                                                                                               "  This is particularly useful in conjunction with --step-target to step through a complex calling sequence."},
794 { LLDB_OPT_SET_1, false, "run-mode",                  'm', OptionParser::eRequiredArgument, nullptr, g_tri_running_mode, 0, eArgTypeRunMode, "Determine how to run other threads while stepping the current thread."},
795 { LLDB_OPT_SET_1, false, "step-over-regexp",          'r', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypeRegularExpression,   "A regular expression that defines function names to not to stop at when stepping in."},
796 { LLDB_OPT_SET_1, false, "step-in-target",            't', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypeFunctionName,   "The name of the directly called function step in should stop at when stepping into."},
797 { LLDB_OPT_SET_2, false, "python-class",              'C', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypePythonClass, "The name of the class that will manage this step - only supported for Scripted Step."},
798 { 0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr }
799 };
800 
801 //-------------------------------------------------------------------------
802 // CommandObjectThreadContinue
803 //-------------------------------------------------------------------------
804 
805 class CommandObjectThreadContinue : public CommandObjectParsed
806 {
807 public:
808     CommandObjectThreadContinue(CommandInterpreter &interpreter)
809         : CommandObjectParsed(interpreter, "thread continue", "Continue execution of the current target process.  One "
810                                                               "or more threads may be specified, by default all "
811                                                               "threads continue.",
812                               nullptr, eCommandRequiresThread | eCommandTryTargetAPILock |
813                                            eCommandProcessMustBeLaunched | eCommandProcessMustBePaused)
814     {
815         CommandArgumentEntry arg;
816         CommandArgumentData thread_idx_arg;
817 
818         // Define the first (and only) variant of this arg.
819         thread_idx_arg.arg_type = eArgTypeThreadIndex;
820         thread_idx_arg.arg_repetition = eArgRepeatPlus;
821 
822         // There is only one variant this argument could be; put it into the argument entry.
823         arg.push_back (thread_idx_arg);
824 
825         // Push the data for the first argument into the m_arguments vector.
826         m_arguments.push_back (arg);
827     }
828 
829     ~CommandObjectThreadContinue() override = default;
830 
831     bool
832     DoExecute (Args& command, CommandReturnObject &result) override
833     {
834         bool synchronous_execution = m_interpreter.GetSynchronous ();
835 
836         if (!m_interpreter.GetDebugger().GetSelectedTarget())
837         {
838             result.AppendError ("invalid target, create a debug target using the 'target create' command");
839             result.SetStatus (eReturnStatusFailed);
840             return false;
841         }
842 
843         Process *process = m_exe_ctx.GetProcessPtr();
844         if (process == nullptr)
845         {
846             result.AppendError ("no process exists. Cannot continue");
847             result.SetStatus (eReturnStatusFailed);
848             return false;
849         }
850 
851         StateType state = process->GetState();
852         if ((state == eStateCrashed) || (state == eStateStopped) || (state == eStateSuspended))
853         {
854             const size_t argc = command.GetArgumentCount();
855             if (argc > 0)
856             {
857                 // These two lines appear at the beginning of both blocks in
858                 // this if..else, but that is because we need to release the
859                 // lock before calling process->Resume below.
860                 std::lock_guard<std::recursive_mutex> guard(process->GetThreadList().GetMutex());
861                 const uint32_t num_threads = process->GetThreadList().GetSize();
862                 std::vector<Thread *> resume_threads;
863                 for (uint32_t i = 0; i < argc; ++i)
864                 {
865                     bool success;
866                     const int base = 0;
867                     uint32_t thread_idx = StringConvert::ToUInt32 (command.GetArgumentAtIndex(i), LLDB_INVALID_INDEX32, base, &success);
868                     if (success)
869                     {
870                         Thread *thread = process->GetThreadList().FindThreadByIndexID(thread_idx).get();
871 
872                         if (thread)
873                         {
874                             resume_threads.push_back(thread);
875                         }
876                         else
877                         {
878                             result.AppendErrorWithFormat("invalid thread index %u.\n", thread_idx);
879                             result.SetStatus (eReturnStatusFailed);
880                             return false;
881                         }
882                     }
883                     else
884                     {
885                         result.AppendErrorWithFormat ("invalid thread index argument: \"%s\".\n", command.GetArgumentAtIndex(i));
886                         result.SetStatus (eReturnStatusFailed);
887                         return false;
888                     }
889                 }
890 
891                 if (resume_threads.empty())
892                 {
893                     result.AppendError ("no valid thread indexes were specified");
894                     result.SetStatus (eReturnStatusFailed);
895                     return false;
896                 }
897                 else
898                 {
899                     if (resume_threads.size() == 1)
900                         result.AppendMessageWithFormat ("Resuming thread: ");
901                     else
902                         result.AppendMessageWithFormat ("Resuming threads: ");
903 
904                     for (uint32_t idx = 0; idx < num_threads; ++idx)
905                     {
906                         Thread *thread = process->GetThreadList().GetThreadAtIndex(idx).get();
907                         std::vector<Thread *>::iterator this_thread_pos = find(resume_threads.begin(), resume_threads.end(), thread);
908 
909                         if (this_thread_pos != resume_threads.end())
910                         {
911                             resume_threads.erase(this_thread_pos);
912                             if (!resume_threads.empty())
913                                 result.AppendMessageWithFormat ("%u, ", thread->GetIndexID());
914                             else
915                                 result.AppendMessageWithFormat ("%u ", thread->GetIndexID());
916 
917                             const bool override_suspend = true;
918                             thread->SetResumeState (eStateRunning, override_suspend);
919                         }
920                         else
921                         {
922                             thread->SetResumeState (eStateSuspended);
923                         }
924                     }
925                     result.AppendMessageWithFormat ("in process %" PRIu64 "\n", process->GetID());
926                 }
927             }
928             else
929             {
930                 // These two lines appear at the beginning of both blocks in
931                 // this if..else, but that is because we need to release the
932                 // lock before calling process->Resume below.
933                 std::lock_guard<std::recursive_mutex> guard(process->GetThreadList().GetMutex());
934                 const uint32_t num_threads = process->GetThreadList().GetSize();
935                 Thread *current_thread = GetDefaultThread();
936                 if (current_thread == nullptr)
937                 {
938                     result.AppendError ("the process doesn't have a current thread");
939                     result.SetStatus (eReturnStatusFailed);
940                     return false;
941                 }
942                 // Set the actions that the threads should each take when resuming
943                 for (uint32_t idx = 0; idx < num_threads; ++idx)
944                 {
945                     Thread *thread = process->GetThreadList().GetThreadAtIndex(idx).get();
946                     if (thread == current_thread)
947                     {
948                         result.AppendMessageWithFormat ("Resuming thread 0x%4.4" PRIx64 " in process %" PRIu64 "\n", thread->GetID(), process->GetID());
949                         const bool override_suspend = true;
950                         thread->SetResumeState (eStateRunning, override_suspend);
951                     }
952                     else
953                     {
954                         thread->SetResumeState (eStateSuspended);
955                     }
956                 }
957             }
958 
959             StreamString stream;
960             Error error;
961             if (synchronous_execution)
962                 error = process->ResumeSynchronous (&stream);
963             else
964                 error = process->Resume ();
965 
966             // We should not be holding the thread list lock when we do this.
967             if (error.Success())
968             {
969                 result.AppendMessageWithFormat ("Process %" PRIu64 " resuming\n", process->GetID());
970                 if (synchronous_execution)
971                 {
972                     // If any state changed events had anything to say, add that to the result
973                     if (stream.GetData())
974                         result.AppendMessage(stream.GetData());
975 
976                     result.SetDidChangeProcessState (true);
977                     result.SetStatus (eReturnStatusSuccessFinishNoResult);
978                 }
979                 else
980                 {
981                     result.SetStatus (eReturnStatusSuccessContinuingNoResult);
982                 }
983             }
984             else
985             {
986                 result.AppendErrorWithFormat("Failed to resume process: %s\n", error.AsCString());
987                 result.SetStatus (eReturnStatusFailed);
988             }
989         }
990         else
991         {
992             result.AppendErrorWithFormat ("Process cannot be continued from its current state (%s).\n",
993                                           StateAsCString(state));
994             result.SetStatus (eReturnStatusFailed);
995         }
996 
997         return result.Succeeded();
998     }
999 };
1000 
1001 //-------------------------------------------------------------------------
1002 // CommandObjectThreadUntil
1003 //-------------------------------------------------------------------------
1004 
1005 class CommandObjectThreadUntil : public CommandObjectParsed
1006 {
1007 public:
1008     class CommandOptions : public Options
1009     {
1010     public:
1011         uint32_t m_thread_idx;
1012         uint32_t m_frame_idx;
1013 
1014         CommandOptions() :
1015             Options(),
1016             m_thread_idx(LLDB_INVALID_THREAD_ID),
1017             m_frame_idx(LLDB_INVALID_FRAME_ID)
1018         {
1019             // Keep default values of all options in one place: OptionParsingStarting ()
1020             OptionParsingStarting(nullptr);
1021         }
1022 
1023         ~CommandOptions() override = default;
1024 
1025         Error
1026         SetOptionValue(uint32_t option_idx, const char *option_arg,
1027                        ExecutionContext *execution_context) override
1028         {
1029             Error error;
1030             const int short_option = m_getopt_table[option_idx].val;
1031 
1032             switch (short_option)
1033             {
1034                 case 'a':
1035                 {
1036                     lldb::addr_t tmp_addr =
1037                         Args::StringToAddress(execution_context, option_arg,
1038                                               LLDB_INVALID_ADDRESS, &error);
1039                     if (error.Success())
1040                         m_until_addrs.push_back(tmp_addr);
1041                 }
1042                 break;
1043                 case 't':
1044                     m_thread_idx = StringConvert::ToUInt32 (option_arg, LLDB_INVALID_INDEX32);
1045                     if (m_thread_idx == LLDB_INVALID_INDEX32)
1046                     {
1047                         error.SetErrorStringWithFormat ("invalid thread index '%s'", option_arg);
1048                     }
1049                     break;
1050                 case 'f':
1051                     m_frame_idx = StringConvert::ToUInt32 (option_arg, LLDB_INVALID_FRAME_ID);
1052                     if (m_frame_idx == LLDB_INVALID_FRAME_ID)
1053                     {
1054                         error.SetErrorStringWithFormat ("invalid frame index '%s'", option_arg);
1055                     }
1056                     break;
1057                 case 'm':
1058                 {
1059                     OptionEnumValueElement *enum_values = g_option_table[option_idx].enum_values;
1060                     lldb::RunMode run_mode = (lldb::RunMode) Args::StringToOptionEnum(option_arg, enum_values, eOnlyDuringStepping, error);
1061 
1062                     if (error.Success())
1063                     {
1064                         if (run_mode == eAllThreads)
1065                             m_stop_others = false;
1066                         else
1067                             m_stop_others = true;
1068                     }
1069                 }
1070                 break;
1071                 default:
1072                     error.SetErrorStringWithFormat("invalid short option character '%c'", short_option);
1073                     break;
1074             }
1075             return error;
1076         }
1077 
1078         void
1079         OptionParsingStarting(ExecutionContext *execution_context) override
1080         {
1081             m_thread_idx = LLDB_INVALID_THREAD_ID;
1082             m_frame_idx = 0;
1083             m_stop_others = false;
1084             m_until_addrs.clear();
1085         }
1086 
1087         const OptionDefinition*
1088         GetDefinitions () override
1089         {
1090             return g_option_table;
1091         }
1092 
1093         uint32_t m_step_thread_idx;
1094         bool m_stop_others;
1095         std::vector<lldb::addr_t> m_until_addrs;
1096 
1097         // Options table: Required for subclasses of Options.
1098 
1099         static OptionDefinition g_option_table[];
1100 
1101         // Instance variables to hold the values for command options.
1102     };
1103 
1104     CommandObjectThreadUntil(CommandInterpreter &interpreter)
1105         : CommandObjectParsed(interpreter, "thread until", "Continue until a line number or address is reached by the "
1106                                                            "current or specified thread.  Stops when returning from "
1107                                                            "the current function as a safety measure.",
1108                               nullptr, eCommandRequiresThread | eCommandTryTargetAPILock |
1109                                            eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
1110           m_options()
1111     {
1112         CommandArgumentEntry arg;
1113         CommandArgumentData line_num_arg;
1114 
1115         // Define the first (and only) variant of this arg.
1116         line_num_arg.arg_type = eArgTypeLineNum;
1117         line_num_arg.arg_repetition = eArgRepeatPlain;
1118 
1119         // There is only one variant this argument could be; put it into the argument entry.
1120         arg.push_back (line_num_arg);
1121 
1122         // Push the data for the first argument into the m_arguments vector.
1123         m_arguments.push_back (arg);
1124     }
1125 
1126     ~CommandObjectThreadUntil() override = default;
1127 
1128     Options *
1129     GetOptions () override
1130     {
1131         return &m_options;
1132     }
1133 
1134 protected:
1135     bool
1136     DoExecute (Args& command, CommandReturnObject &result) override
1137     {
1138         bool synchronous_execution = m_interpreter.GetSynchronous ();
1139 
1140         Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1141         if (target == nullptr)
1142         {
1143             result.AppendError ("invalid target, create a debug target using the 'target create' command");
1144             result.SetStatus (eReturnStatusFailed);
1145             return false;
1146         }
1147 
1148         Process *process = m_exe_ctx.GetProcessPtr();
1149         if (process == nullptr)
1150         {
1151             result.AppendError ("need a valid process to step");
1152             result.SetStatus (eReturnStatusFailed);
1153         }
1154         else
1155         {
1156             Thread *thread = nullptr;
1157             std::vector<uint32_t> line_numbers;
1158 
1159             if (command.GetArgumentCount() >= 1)
1160             {
1161                 size_t num_args = command.GetArgumentCount();
1162                 for (size_t i = 0; i < num_args; i++)
1163                 {
1164                     uint32_t line_number;
1165                     line_number = StringConvert::ToUInt32 (command.GetArgumentAtIndex(0), UINT32_MAX);
1166                     if (line_number == UINT32_MAX)
1167                     {
1168                         result.AppendErrorWithFormat ("invalid line number: '%s'.\n", command.GetArgumentAtIndex(0));
1169                         result.SetStatus (eReturnStatusFailed);
1170                         return false;
1171                     }
1172                     else
1173                         line_numbers.push_back(line_number);
1174                 }
1175             }
1176             else if (m_options.m_until_addrs.empty())
1177             {
1178                 result.AppendErrorWithFormat ("No line number or address provided:\n%s", GetSyntax());
1179                 result.SetStatus (eReturnStatusFailed);
1180                 return false;
1181             }
1182 
1183             if (m_options.m_thread_idx == LLDB_INVALID_THREAD_ID)
1184             {
1185                 thread = GetDefaultThread();
1186             }
1187             else
1188             {
1189                 thread = process->GetThreadList().FindThreadByIndexID(m_options.m_thread_idx).get();
1190             }
1191 
1192             if (thread == nullptr)
1193             {
1194                 const uint32_t num_threads = process->GetThreadList().GetSize();
1195                 result.AppendErrorWithFormat ("Thread index %u is out of range (valid values are 0 - %u).\n",
1196                                               m_options.m_thread_idx,
1197                                               num_threads);
1198                 result.SetStatus (eReturnStatusFailed);
1199                 return false;
1200             }
1201 
1202             const bool abort_other_plans = false;
1203 
1204             StackFrame *frame = thread->GetStackFrameAtIndex(m_options.m_frame_idx).get();
1205             if (frame == nullptr)
1206             {
1207                 result.AppendErrorWithFormat ("Frame index %u is out of range for thread %u.\n",
1208                                               m_options.m_frame_idx,
1209                                               m_options.m_thread_idx);
1210                 result.SetStatus (eReturnStatusFailed);
1211                 return false;
1212             }
1213 
1214             ThreadPlanSP new_plan_sp;
1215 
1216             if (frame->HasDebugInformation ())
1217             {
1218                 // Finally we got here...  Translate the given line number to a bunch of addresses:
1219                 SymbolContext sc(frame->GetSymbolContext (eSymbolContextCompUnit));
1220                 LineTable *line_table = nullptr;
1221                 if (sc.comp_unit)
1222                     line_table = sc.comp_unit->GetLineTable();
1223 
1224                 if (line_table == nullptr)
1225                 {
1226                     result.AppendErrorWithFormat ("Failed to resolve the line table for frame %u of thread index %u.\n",
1227                                                  m_options.m_frame_idx, m_options.m_thread_idx);
1228                     result.SetStatus (eReturnStatusFailed);
1229                     return false;
1230                 }
1231 
1232                 LineEntry function_start;
1233                 uint32_t index_ptr = 0, end_ptr;
1234                 std::vector<addr_t> address_list;
1235 
1236                 // Find the beginning & end index of the
1237                 AddressRange fun_addr_range = sc.function->GetAddressRange();
1238                 Address fun_start_addr = fun_addr_range.GetBaseAddress();
1239                 line_table->FindLineEntryByAddress (fun_start_addr, function_start, &index_ptr);
1240 
1241                 Address fun_end_addr(fun_start_addr.GetSection(),
1242                                      fun_start_addr.GetOffset() + fun_addr_range.GetByteSize());
1243 
1244                 bool all_in_function = true;
1245 
1246                 line_table->FindLineEntryByAddress (fun_end_addr, function_start, &end_ptr);
1247 
1248                 for (uint32_t line_number : line_numbers)
1249                 {
1250                     uint32_t start_idx_ptr = index_ptr;
1251                     while (start_idx_ptr <= end_ptr)
1252                     {
1253                         LineEntry line_entry;
1254                         const bool exact = false;
1255                         start_idx_ptr = sc.comp_unit->FindLineEntry(start_idx_ptr, line_number, sc.comp_unit, exact, &line_entry);
1256                         if (start_idx_ptr == UINT32_MAX)
1257                             break;
1258 
1259                         addr_t address = line_entry.range.GetBaseAddress().GetLoadAddress(target);
1260                         if (address != LLDB_INVALID_ADDRESS)
1261                         {
1262                             if (fun_addr_range.ContainsLoadAddress (address, target))
1263                                 address_list.push_back (address);
1264                             else
1265                                 all_in_function = false;
1266                         }
1267                         start_idx_ptr++;
1268                     }
1269                 }
1270 
1271                 for (lldb::addr_t address : m_options.m_until_addrs)
1272                 {
1273                     if (fun_addr_range.ContainsLoadAddress (address, target))
1274                         address_list.push_back (address);
1275                     else
1276                         all_in_function = false;
1277                 }
1278 
1279                 if (address_list.empty())
1280                 {
1281                     if (all_in_function)
1282                         result.AppendErrorWithFormat ("No line entries matching until target.\n");
1283                     else
1284                         result.AppendErrorWithFormat ("Until target outside of the current function.\n");
1285 
1286                     result.SetStatus (eReturnStatusFailed);
1287                     return false;
1288                 }
1289 
1290                 new_plan_sp = thread->QueueThreadPlanForStepUntil (abort_other_plans,
1291                                                                 &address_list.front(),
1292                                                                 address_list.size(),
1293                                                                 m_options.m_stop_others,
1294                                                                 m_options.m_frame_idx);
1295                 // User level plans should be master plans so they can be interrupted (e.g. by hitting a breakpoint)
1296                 // and other plans executed by the user (stepping around the breakpoint) and then a "continue"
1297                 // will resume the original plan.
1298                 new_plan_sp->SetIsMasterPlan (true);
1299                 new_plan_sp->SetOkayToDiscard(false);
1300             }
1301             else
1302             {
1303                 result.AppendErrorWithFormat ("Frame index %u of thread %u has no debug information.\n",
1304                                               m_options.m_frame_idx,
1305                                               m_options.m_thread_idx);
1306                 result.SetStatus (eReturnStatusFailed);
1307                 return false;
1308             }
1309 
1310             process->GetThreadList().SetSelectedThreadByID (m_options.m_thread_idx);
1311 
1312             StreamString stream;
1313             Error error;
1314             if (synchronous_execution)
1315                 error = process->ResumeSynchronous (&stream);
1316             else
1317                 error = process->Resume ();
1318 
1319             if (error.Success())
1320             {
1321                 result.AppendMessageWithFormat ("Process %" PRIu64 " resuming\n", process->GetID());
1322                 if (synchronous_execution)
1323                 {
1324                     // If any state changed events had anything to say, add that to the result
1325                     if (stream.GetData())
1326                         result.AppendMessage(stream.GetData());
1327 
1328                     result.SetDidChangeProcessState (true);
1329                     result.SetStatus (eReturnStatusSuccessFinishNoResult);
1330                 }
1331                 else
1332                 {
1333                     result.SetStatus (eReturnStatusSuccessContinuingNoResult);
1334                 }
1335             }
1336             else
1337             {
1338                 result.AppendErrorWithFormat("Failed to resume process: %s.\n", error.AsCString());
1339                 result.SetStatus (eReturnStatusFailed);
1340             }
1341 
1342         }
1343         return result.Succeeded();
1344     }
1345 
1346     CommandOptions m_options;
1347 };
1348 
1349 OptionDefinition
1350 CommandObjectThreadUntil::CommandOptions::g_option_table[] =
1351 {
1352 { LLDB_OPT_SET_1, false, "frame",   'f', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypeFrameIndex,   "Frame index for until operation - defaults to 0"},
1353 { LLDB_OPT_SET_1, false, "thread",  't', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypeThreadIndex,  "Thread index for the thread for until operation"},
1354 { LLDB_OPT_SET_1, false, "run-mode",'m', OptionParser::eRequiredArgument, nullptr, g_duo_running_mode, 0, eArgTypeRunMode, "Determine how to run other threads while stepping this one"},
1355 { LLDB_OPT_SET_1, false, "address", 'a', OptionParser::eRequiredArgument, nullptr, nullptr,               0, eArgTypeAddressOrExpression, "Run until we reach the specified address, or leave the function - can be specified multiple times."},
1356 { 0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr }
1357 };
1358 
1359 //-------------------------------------------------------------------------
1360 // CommandObjectThreadSelect
1361 //-------------------------------------------------------------------------
1362 
1363 class CommandObjectThreadSelect : public CommandObjectParsed
1364 {
1365 public:
1366     CommandObjectThreadSelect(CommandInterpreter &interpreter)
1367         : CommandObjectParsed(interpreter, "thread select", "Change the currently selected thread.", nullptr,
1368                               eCommandRequiresProcess | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
1369                                   eCommandProcessMustBePaused)
1370     {
1371         CommandArgumentEntry arg;
1372         CommandArgumentData thread_idx_arg;
1373 
1374         // Define the first (and only) variant of this arg.
1375         thread_idx_arg.arg_type = eArgTypeThreadIndex;
1376         thread_idx_arg.arg_repetition = eArgRepeatPlain;
1377 
1378         // There is only one variant this argument could be; put it into the argument entry.
1379         arg.push_back (thread_idx_arg);
1380 
1381         // Push the data for the first argument into the m_arguments vector.
1382         m_arguments.push_back (arg);
1383     }
1384 
1385     ~CommandObjectThreadSelect() override = default;
1386 
1387 protected:
1388     bool
1389     DoExecute (Args& command, CommandReturnObject &result) override
1390     {
1391         Process *process = m_exe_ctx.GetProcessPtr();
1392         if (process == nullptr)
1393         {
1394             result.AppendError ("no process");
1395             result.SetStatus (eReturnStatusFailed);
1396             return false;
1397         }
1398         else if (command.GetArgumentCount() != 1)
1399         {
1400             result.AppendErrorWithFormat("'%s' takes exactly one thread index argument:\nUsage: %s\n", m_cmd_name.c_str(), m_cmd_syntax.c_str());
1401             result.SetStatus (eReturnStatusFailed);
1402             return false;
1403         }
1404 
1405         uint32_t index_id = StringConvert::ToUInt32(command.GetArgumentAtIndex(0), 0, 0);
1406 
1407         Thread *new_thread = process->GetThreadList().FindThreadByIndexID(index_id).get();
1408         if (new_thread == nullptr)
1409         {
1410             result.AppendErrorWithFormat ("invalid thread #%s.\n", command.GetArgumentAtIndex(0));
1411             result.SetStatus (eReturnStatusFailed);
1412             return false;
1413         }
1414 
1415         process->GetThreadList().SetSelectedThreadByID(new_thread->GetID(), true);
1416         result.SetStatus (eReturnStatusSuccessFinishNoResult);
1417 
1418         return result.Succeeded();
1419     }
1420 };
1421 
1422 //-------------------------------------------------------------------------
1423 // CommandObjectThreadList
1424 //-------------------------------------------------------------------------
1425 
1426 class CommandObjectThreadList : public CommandObjectParsed
1427 {
1428 public:
1429     CommandObjectThreadList(CommandInterpreter &interpreter)
1430         : CommandObjectParsed(interpreter, "thread list",
1431                               "Show a summary of each thread in the current target process.", "thread list",
1432                               eCommandRequiresProcess | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
1433                                   eCommandProcessMustBePaused)
1434     {
1435     }
1436 
1437     ~CommandObjectThreadList() override = default;
1438 
1439 protected:
1440     bool
1441     DoExecute (Args& command, CommandReturnObject &result) override
1442     {
1443         Stream &strm = result.GetOutputStream();
1444         result.SetStatus (eReturnStatusSuccessFinishNoResult);
1445         Process *process = m_exe_ctx.GetProcessPtr();
1446         const bool only_threads_with_stop_reason = false;
1447         const uint32_t start_frame = 0;
1448         const uint32_t num_frames = 0;
1449         const uint32_t num_frames_with_source = 0;
1450         process->GetStatus(strm);
1451         process->GetThreadStatus (strm,
1452                                   only_threads_with_stop_reason,
1453                                   start_frame,
1454                                   num_frames,
1455                                   num_frames_with_source);
1456         return result.Succeeded();
1457     }
1458 };
1459 
1460 //-------------------------------------------------------------------------
1461 // CommandObjectThreadInfo
1462 //-------------------------------------------------------------------------
1463 
1464 class CommandObjectThreadInfo : public CommandObjectIterateOverThreads
1465 {
1466 public:
1467     class CommandOptions : public Options
1468     {
1469     public:
1470         CommandOptions() :
1471             Options()
1472         {
1473             OptionParsingStarting(nullptr);
1474         }
1475 
1476         ~CommandOptions() override = default;
1477 
1478         void
1479         OptionParsingStarting(ExecutionContext *execution_context) override
1480         {
1481             m_json_thread = false;
1482             m_json_stopinfo = false;
1483         }
1484 
1485         Error
1486         SetOptionValue(uint32_t option_idx, const char *option_arg,
1487                        ExecutionContext *execution_context) override
1488         {
1489             const int short_option = m_getopt_table[option_idx].val;
1490             Error error;
1491 
1492             switch (short_option)
1493             {
1494                 case 'j':
1495                     m_json_thread = true;
1496                     break;
1497 
1498                 case 's':
1499                     m_json_stopinfo = true;
1500                     break;
1501 
1502                 default:
1503                     return Error("invalid short option character '%c'", short_option);
1504             }
1505             return error;
1506         }
1507 
1508         const OptionDefinition*
1509         GetDefinitions () override
1510         {
1511             return g_option_table;
1512         }
1513 
1514         bool m_json_thread;
1515         bool m_json_stopinfo;
1516 
1517         static OptionDefinition g_option_table[];
1518     };
1519 
1520     CommandObjectThreadInfo(CommandInterpreter &interpreter)
1521         : CommandObjectIterateOverThreads(
1522               interpreter, "thread info",
1523               "Show an extended summary of one or more threads.  Defaults to the current thread.", "thread info",
1524               eCommandRequiresProcess | eCommandTryTargetAPILock | eCommandProcessMustBeLaunched |
1525                   eCommandProcessMustBePaused),
1526           m_options()
1527     {
1528         m_add_return = false;
1529     }
1530 
1531     ~CommandObjectThreadInfo() override = default;
1532 
1533     Options *
1534     GetOptions () override
1535     {
1536         return &m_options;
1537     }
1538 
1539     bool
1540     HandleOneThread (lldb::tid_t tid, CommandReturnObject &result) override
1541     {
1542         ThreadSP thread_sp = m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
1543         if (!thread_sp)
1544         {
1545             result.AppendErrorWithFormat ("thread no longer exists: 0x%" PRIx64 "\n", tid);
1546             result.SetStatus (eReturnStatusFailed);
1547             return false;
1548         }
1549 
1550         Thread *thread = thread_sp.get();
1551 
1552         Stream &strm = result.GetOutputStream();
1553         if (!thread->GetDescription (strm, eDescriptionLevelFull, m_options.m_json_thread, m_options.m_json_stopinfo))
1554         {
1555             result.AppendErrorWithFormat ("error displaying info for thread: \"%d\"\n", thread->GetIndexID());
1556             result.SetStatus (eReturnStatusFailed);
1557             return false;
1558         }
1559         return true;
1560     }
1561 
1562     CommandOptions m_options;
1563 };
1564 
1565 OptionDefinition
1566 CommandObjectThreadInfo::CommandOptions::g_option_table[] =
1567 {
1568     { LLDB_OPT_SET_ALL, false, "json",'j', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display the thread info in JSON format."},
1569     { LLDB_OPT_SET_ALL, false, "stop-info",'s', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display the extended stop info in JSON format."},
1570 
1571     { 0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr }
1572 };
1573 
1574 //-------------------------------------------------------------------------
1575 // CommandObjectThreadReturn
1576 //-------------------------------------------------------------------------
1577 
1578 class CommandObjectThreadReturn : public CommandObjectRaw
1579 {
1580 public:
1581     class CommandOptions : public Options
1582     {
1583     public:
1584         CommandOptions() :
1585             Options(),
1586             m_from_expression(false)
1587         {
1588             // Keep default values of all options in one place: OptionParsingStarting ()
1589             OptionParsingStarting(nullptr);
1590         }
1591 
1592         ~CommandOptions() override = default;
1593 
1594         Error
1595         SetOptionValue (uint32_t option_idx, const char *option_arg,
1596                         ExecutionContext *execution_context) override
1597         {
1598             Error error;
1599             const int short_option = m_getopt_table[option_idx].val;
1600 
1601             switch (short_option)
1602             {
1603                 case 'x':
1604                 {
1605                     bool success;
1606                     bool tmp_value = Args::StringToBoolean (option_arg, false, &success);
1607                     if (success)
1608                         m_from_expression = tmp_value;
1609                     else
1610                     {
1611                         error.SetErrorStringWithFormat ("invalid boolean value '%s' for 'x' option", option_arg);
1612                     }
1613                 }
1614                 break;
1615                 default:
1616                     error.SetErrorStringWithFormat("invalid short option character '%c'", short_option);
1617                     break;
1618             }
1619             return error;
1620         }
1621 
1622         void
1623         OptionParsingStarting(ExecutionContext *execution_context) override
1624         {
1625             m_from_expression = false;
1626         }
1627 
1628         const OptionDefinition*
1629         GetDefinitions () override
1630         {
1631             return g_option_table;
1632         }
1633 
1634         bool m_from_expression;
1635 
1636         // Options table: Required for subclasses of Options.
1637 
1638         static OptionDefinition g_option_table[];
1639 
1640         // Instance variables to hold the values for command options.
1641     };
1642 
1643     CommandObjectThreadReturn(CommandInterpreter &interpreter)
1644         : CommandObjectRaw(interpreter, "thread return",
1645                            "Prematurely return from a stack frame, short-circuiting execution of newer frames "
1646                            "and optionally yielding a specified value.  Defaults to the exiting the current stack "
1647                            "frame.",
1648                            "thread return", eCommandRequiresFrame | eCommandTryTargetAPILock |
1649                                                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
1650           m_options()
1651     {
1652         CommandArgumentEntry arg;
1653         CommandArgumentData expression_arg;
1654 
1655         // Define the first (and only) variant of this arg.
1656         expression_arg.arg_type = eArgTypeExpression;
1657         expression_arg.arg_repetition = eArgRepeatOptional;
1658 
1659         // There is only one variant this argument could be; put it into the argument entry.
1660         arg.push_back (expression_arg);
1661 
1662         // Push the data for the first argument into the m_arguments vector.
1663         m_arguments.push_back (arg);
1664     }
1665 
1666     ~CommandObjectThreadReturn() override = default;
1667 
1668     Options *
1669     GetOptions() override
1670     {
1671         return &m_options;
1672     }
1673 
1674 protected:
1675     bool
1676     DoExecute (const char *command, CommandReturnObject &result) override
1677     {
1678         // I am going to handle this by hand, because I don't want you to have to say:
1679         // "thread return -- -5".
1680         if (command[0] == '-' && command[1] == 'x')
1681         {
1682             if (command && command[2] != '\0')
1683                 result.AppendWarning("Return values ignored when returning from user called expressions");
1684 
1685             Thread *thread = m_exe_ctx.GetThreadPtr();
1686             Error error;
1687             error = thread->UnwindInnermostExpression();
1688             if (!error.Success())
1689             {
1690                 result.AppendErrorWithFormat ("Unwinding expression failed - %s.", error.AsCString());
1691                 result.SetStatus (eReturnStatusFailed);
1692             }
1693             else
1694             {
1695                 bool success = thread->SetSelectedFrameByIndexNoisily (0, result.GetOutputStream());
1696                 if (success)
1697                 {
1698                     m_exe_ctx.SetFrameSP(thread->GetSelectedFrame ());
1699                     result.SetStatus (eReturnStatusSuccessFinishResult);
1700                 }
1701                 else
1702                 {
1703                     result.AppendErrorWithFormat ("Could not select 0th frame after unwinding expression.");
1704                     result.SetStatus (eReturnStatusFailed);
1705                 }
1706             }
1707             return result.Succeeded();
1708         }
1709 
1710         ValueObjectSP return_valobj_sp;
1711 
1712         StackFrameSP frame_sp = m_exe_ctx.GetFrameSP();
1713         uint32_t frame_idx = frame_sp->GetFrameIndex();
1714 
1715         if (frame_sp->IsInlined())
1716         {
1717             result.AppendError("Don't know how to return from inlined frames.");
1718             result.SetStatus (eReturnStatusFailed);
1719             return false;
1720         }
1721 
1722         if (command && command[0] != '\0')
1723         {
1724             Target *target = m_exe_ctx.GetTargetPtr();
1725             EvaluateExpressionOptions options;
1726 
1727             options.SetUnwindOnError(true);
1728             options.SetUseDynamic(eNoDynamicValues);
1729 
1730             ExpressionResults exe_results = eExpressionSetupError;
1731             exe_results = target->EvaluateExpression (command,
1732                                                       frame_sp.get(),
1733                                                       return_valobj_sp,
1734                                                       options);
1735             if (exe_results != eExpressionCompleted)
1736             {
1737                 if (return_valobj_sp)
1738                     result.AppendErrorWithFormat("Error evaluating result expression: %s", return_valobj_sp->GetError().AsCString());
1739                 else
1740                     result.AppendErrorWithFormat("Unknown error evaluating result expression.");
1741                 result.SetStatus (eReturnStatusFailed);
1742                 return false;
1743             }
1744         }
1745 
1746         Error error;
1747         ThreadSP thread_sp = m_exe_ctx.GetThreadSP();
1748         const bool broadcast = true;
1749         error = thread_sp->ReturnFromFrame (frame_sp, return_valobj_sp, broadcast);
1750         if (!error.Success())
1751         {
1752             result.AppendErrorWithFormat("Error returning from frame %d of thread %d: %s.", frame_idx, thread_sp->GetIndexID(), error.AsCString());
1753             result.SetStatus (eReturnStatusFailed);
1754             return false;
1755         }
1756 
1757         result.SetStatus (eReturnStatusSuccessFinishResult);
1758         return true;
1759     }
1760 
1761     CommandOptions m_options;
1762 };
1763 
1764 OptionDefinition
1765 CommandObjectThreadReturn::CommandOptions::g_option_table[] =
1766 {
1767 { LLDB_OPT_SET_ALL, false, "from-expression",  'x', OptionParser::eNoArgument, nullptr, nullptr,               0, eArgTypeNone,     "Return from the innermost expression evaluation."},
1768 { 0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr }
1769 };
1770 
1771 //-------------------------------------------------------------------------
1772 // CommandObjectThreadJump
1773 //-------------------------------------------------------------------------
1774 
1775 class CommandObjectThreadJump : public CommandObjectParsed
1776 {
1777 public:
1778     class CommandOptions : public Options
1779     {
1780     public:
1781         CommandOptions() :
1782             Options()
1783         {
1784             OptionParsingStarting(nullptr);
1785         }
1786 
1787         ~CommandOptions() override = default;
1788 
1789         void
1790         OptionParsingStarting(ExecutionContext *execution_context) override
1791         {
1792             m_filenames.Clear();
1793             m_line_num = 0;
1794             m_line_offset = 0;
1795             m_load_addr = LLDB_INVALID_ADDRESS;
1796             m_force = false;
1797         }
1798 
1799         Error
1800         SetOptionValue(uint32_t option_idx, const char *option_arg,
1801                        ExecutionContext *execution_context) override
1802         {
1803             bool success;
1804             const int short_option = m_getopt_table[option_idx].val;
1805             Error error;
1806 
1807             switch (short_option)
1808             {
1809                 case 'f':
1810                     m_filenames.AppendIfUnique (FileSpec(option_arg, false));
1811                     if (m_filenames.GetSize() > 1)
1812                         return Error("only one source file expected.");
1813                     break;
1814                 case 'l':
1815                     m_line_num = StringConvert::ToUInt32 (option_arg, 0, 0, &success);
1816                     if (!success || m_line_num == 0)
1817                         return Error("invalid line number: '%s'.", option_arg);
1818                     break;
1819                 case 'b':
1820                     m_line_offset = StringConvert::ToSInt32 (option_arg, 0, 0, &success);
1821                     if (!success)
1822                         return Error("invalid line offset: '%s'.", option_arg);
1823                     break;
1824                 case 'a':
1825                     m_load_addr = Args::StringToAddress(execution_context,
1826                                                         option_arg,
1827                                                         LLDB_INVALID_ADDRESS,
1828                                                         &error);
1829                     break;
1830                 case 'r':
1831                     m_force = true;
1832                     break;
1833                  default:
1834                     return Error("invalid short option character '%c'", short_option);
1835             }
1836             return error;
1837         }
1838 
1839         const OptionDefinition*
1840         GetDefinitions () override
1841         {
1842             return g_option_table;
1843         }
1844 
1845         FileSpecList m_filenames;
1846         uint32_t m_line_num;
1847         int32_t m_line_offset;
1848         lldb::addr_t m_load_addr;
1849         bool m_force;
1850 
1851         static OptionDefinition g_option_table[];
1852     };
1853 
1854     CommandObjectThreadJump (CommandInterpreter &interpreter) :
1855         CommandObjectParsed (interpreter,
1856                           "thread jump",
1857                           "Sets the program counter to a new address.",
1858                           "thread jump",
1859                           eCommandRequiresFrame         |
1860                           eCommandTryTargetAPILock      |
1861                           eCommandProcessMustBeLaunched |
1862                           eCommandProcessMustBePaused   ),
1863         m_options()
1864     {
1865     }
1866 
1867     ~CommandObjectThreadJump() override = default;
1868 
1869     Options *
1870     GetOptions() override
1871     {
1872         return &m_options;
1873     }
1874 
1875 protected:
1876     bool DoExecute (Args& args, CommandReturnObject &result) override
1877     {
1878         RegisterContext *reg_ctx = m_exe_ctx.GetRegisterContext();
1879         StackFrame *frame = m_exe_ctx.GetFramePtr();
1880         Thread *thread = m_exe_ctx.GetThreadPtr();
1881         Target *target = m_exe_ctx.GetTargetPtr();
1882         const SymbolContext &sym_ctx = frame->GetSymbolContext (eSymbolContextLineEntry);
1883 
1884         if (m_options.m_load_addr != LLDB_INVALID_ADDRESS)
1885         {
1886             // Use this address directly.
1887             Address dest = Address(m_options.m_load_addr);
1888 
1889             lldb::addr_t callAddr = dest.GetCallableLoadAddress (target);
1890             if (callAddr == LLDB_INVALID_ADDRESS)
1891             {
1892                 result.AppendErrorWithFormat ("Invalid destination address.");
1893                 result.SetStatus (eReturnStatusFailed);
1894                 return false;
1895             }
1896 
1897             if (!reg_ctx->SetPC (callAddr))
1898             {
1899                 result.AppendErrorWithFormat ("Error changing PC value for thread %d.", thread->GetIndexID());
1900                 result.SetStatus (eReturnStatusFailed);
1901                 return false;
1902             }
1903         }
1904         else
1905         {
1906             // Pick either the absolute line, or work out a relative one.
1907             int32_t line = (int32_t)m_options.m_line_num;
1908             if (line == 0)
1909                 line = sym_ctx.line_entry.line + m_options.m_line_offset;
1910 
1911             // Try the current file, but override if asked.
1912             FileSpec file = sym_ctx.line_entry.file;
1913             if (m_options.m_filenames.GetSize() == 1)
1914                 file = m_options.m_filenames.GetFileSpecAtIndex(0);
1915 
1916             if (!file)
1917             {
1918                 result.AppendErrorWithFormat ("No source file available for the current location.");
1919                 result.SetStatus (eReturnStatusFailed);
1920                 return false;
1921             }
1922 
1923             std::string warnings;
1924             Error err = thread->JumpToLine (file, line, m_options.m_force, &warnings);
1925 
1926             if (err.Fail())
1927             {
1928                 result.SetError (err);
1929                 return false;
1930             }
1931 
1932             if (!warnings.empty())
1933                 result.AppendWarning (warnings.c_str());
1934         }
1935 
1936         result.SetStatus (eReturnStatusSuccessFinishResult);
1937         return true;
1938     }
1939 
1940     CommandOptions m_options;
1941 };
1942 
1943 OptionDefinition
1944 CommandObjectThreadJump::CommandOptions::g_option_table[] =
1945 {
1946     { LLDB_OPT_SET_1, false, "file", 'f', OptionParser::eRequiredArgument, nullptr, nullptr, CommandCompletions::eSourceFileCompletion, eArgTypeFilename,
1947         "Specifies the source file to jump to."},
1948 
1949     { LLDB_OPT_SET_1, true, "line", 'l', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeLineNum,
1950         "Specifies the line number to jump to."},
1951 
1952     { LLDB_OPT_SET_2, true, "by", 'b', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeOffset,
1953         "Jumps by a relative line offset from the current line."},
1954 
1955     { LLDB_OPT_SET_3, true, "address", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeAddressOrExpression,
1956         "Jumps to a specific address."},
1957 
1958     { LLDB_OPT_SET_1|
1959       LLDB_OPT_SET_2|
1960       LLDB_OPT_SET_3, false, "force",'r', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone,"Allows the PC to leave the current function."},
1961 
1962     { 0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr }
1963 };
1964 
1965 //-------------------------------------------------------------------------
1966 // Next are the subcommands of CommandObjectMultiwordThreadPlan
1967 //-------------------------------------------------------------------------
1968 
1969 //-------------------------------------------------------------------------
1970 // CommandObjectThreadPlanList
1971 //-------------------------------------------------------------------------
1972 
1973 class CommandObjectThreadPlanList : public CommandObjectIterateOverThreads
1974 {
1975 public:
1976     class CommandOptions : public Options
1977     {
1978     public:
1979         CommandOptions() :
1980             Options()
1981         {
1982             // Keep default values of all options in one place: OptionParsingStarting ()
1983             OptionParsingStarting(nullptr);
1984         }
1985 
1986         ~CommandOptions() override = default;
1987 
1988         Error
1989         SetOptionValue(uint32_t option_idx, const char *option_arg,
1990                        ExecutionContext *execution_context) override
1991         {
1992             Error error;
1993             const int short_option = m_getopt_table[option_idx].val;
1994 
1995             switch (short_option)
1996             {
1997                 case 'i':
1998                     m_internal = true;
1999                     break;
2000                 case 'v':
2001                     m_verbose = true;
2002                     break;
2003                 default:
2004                     error.SetErrorStringWithFormat("invalid short option character '%c'", short_option);
2005                     break;
2006             }
2007             return error;
2008         }
2009 
2010         void
2011         OptionParsingStarting(ExecutionContext *execution_context) override
2012         {
2013             m_verbose = false;
2014             m_internal = false;
2015         }
2016 
2017         const OptionDefinition*
2018         GetDefinitions () override
2019         {
2020             return g_option_table;
2021         }
2022 
2023         // Options table: Required for subclasses of Options.
2024 
2025         static OptionDefinition g_option_table[];
2026 
2027         // Instance variables to hold the values for command options.
2028         bool m_verbose;
2029         bool m_internal;
2030     };
2031 
2032     CommandObjectThreadPlanList(CommandInterpreter &interpreter)
2033         : CommandObjectIterateOverThreads(
2034               interpreter, "thread plan list",
2035               "Show thread plans for one or more threads.  If no threads are specified, show the "
2036               "current thread.  Use the thread-index \"all\" to see all threads.",
2037               nullptr, eCommandRequiresProcess | eCommandRequiresThread | eCommandTryTargetAPILock |
2038                            eCommandProcessMustBeLaunched | eCommandProcessMustBePaused),
2039           m_options()
2040     {
2041     }
2042 
2043     ~CommandObjectThreadPlanList() override = default;
2044 
2045     Options *
2046     GetOptions () override
2047     {
2048         return &m_options;
2049     }
2050 
2051 protected:
2052     bool
2053     HandleOneThread (lldb::tid_t tid, CommandReturnObject &result) override
2054     {
2055         ThreadSP thread_sp = m_exe_ctx.GetProcessPtr()->GetThreadList().FindThreadByID(tid);
2056         if (!thread_sp)
2057         {
2058             result.AppendErrorWithFormat ("thread no longer exists: 0x%" PRIx64 "\n", tid);
2059             result.SetStatus (eReturnStatusFailed);
2060             return false;
2061         }
2062 
2063         Thread *thread = thread_sp.get();
2064 
2065         Stream &strm = result.GetOutputStream();
2066         DescriptionLevel desc_level = eDescriptionLevelFull;
2067         if (m_options.m_verbose)
2068             desc_level = eDescriptionLevelVerbose;
2069 
2070         thread->DumpThreadPlans (&strm, desc_level, m_options.m_internal, true);
2071         return true;
2072     }
2073 
2074     CommandOptions m_options;
2075 };
2076 
2077 OptionDefinition
2078 CommandObjectThreadPlanList::CommandOptions::g_option_table[] =
2079 {
2080 { LLDB_OPT_SET_1, false, "verbose", 'v', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display more information about the thread plans"},
2081 { LLDB_OPT_SET_1, false, "internal", 'i', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Display internal as well as user thread plans"},
2082 { 0, false, nullptr, 0, 0, nullptr, nullptr, 0, eArgTypeNone, nullptr }
2083 };
2084 
2085 class CommandObjectThreadPlanDiscard : public CommandObjectParsed
2086 {
2087 public:
2088     CommandObjectThreadPlanDiscard(CommandInterpreter &interpreter)
2089         : CommandObjectParsed(
2090               interpreter, "thread plan discard",
2091               "Discards thread plans up to and including the specified index (see 'thread plan list'.)  "
2092               "Only user visible plans can be discarded.",
2093               nullptr, eCommandRequiresProcess | eCommandRequiresThread | eCommandTryTargetAPILock |
2094                            eCommandProcessMustBeLaunched | eCommandProcessMustBePaused)
2095     {
2096         CommandArgumentEntry arg;
2097         CommandArgumentData plan_index_arg;
2098 
2099         // Define the first (and only) variant of this arg.
2100         plan_index_arg.arg_type = eArgTypeUnsignedInteger;
2101         plan_index_arg.arg_repetition = eArgRepeatPlain;
2102 
2103         // There is only one variant this argument could be; put it into the argument entry.
2104         arg.push_back (plan_index_arg);
2105 
2106         // Push the data for the first argument into the m_arguments vector.
2107         m_arguments.push_back (arg);
2108     }
2109 
2110     ~CommandObjectThreadPlanDiscard() override = default;
2111 
2112     bool
2113     DoExecute (Args& args, CommandReturnObject &result) override
2114     {
2115         Thread *thread = m_exe_ctx.GetThreadPtr();
2116         if (args.GetArgumentCount() != 1)
2117         {
2118             result.AppendErrorWithFormat("Too many arguments, expected one - the thread plan index - but got %zu.",
2119                                          args.GetArgumentCount());
2120             result.SetStatus (eReturnStatusFailed);
2121             return false;
2122         }
2123 
2124         bool success;
2125         uint32_t thread_plan_idx = StringConvert::ToUInt32(args.GetArgumentAtIndex(0), 0, 0, &success);
2126         if (!success)
2127         {
2128             result.AppendErrorWithFormat("Invalid thread index: \"%s\" - should be unsigned int.",
2129                                          args.GetArgumentAtIndex(0));
2130             result.SetStatus (eReturnStatusFailed);
2131             return false;
2132         }
2133 
2134         if (thread_plan_idx == 0)
2135         {
2136             result.AppendErrorWithFormat("You wouldn't really want me to discard the base thread plan.");
2137             result.SetStatus (eReturnStatusFailed);
2138             return false;
2139         }
2140 
2141         if (thread->DiscardUserThreadPlansUpToIndex(thread_plan_idx))
2142         {
2143             result.SetStatus(eReturnStatusSuccessFinishNoResult);
2144             return true;
2145         }
2146         else
2147         {
2148             result.AppendErrorWithFormat("Could not find User thread plan with index %s.",
2149                                          args.GetArgumentAtIndex(0));
2150             result.SetStatus (eReturnStatusFailed);
2151             return false;
2152         }
2153     }
2154 };
2155 
2156 //-------------------------------------------------------------------------
2157 // CommandObjectMultiwordThreadPlan
2158 //-------------------------------------------------------------------------
2159 
2160 class CommandObjectMultiwordThreadPlan : public CommandObjectMultiword
2161 {
2162 public:
2163     CommandObjectMultiwordThreadPlan(CommandInterpreter &interpreter)
2164         : CommandObjectMultiword(interpreter, "plan", "Commands for managing thread plans that control execution.",
2165                                  "thread plan <subcommand> [<subcommand objects]")
2166     {
2167         LoadSubCommand ("list", CommandObjectSP (new CommandObjectThreadPlanList (interpreter)));
2168         LoadSubCommand ("discard", CommandObjectSP (new CommandObjectThreadPlanDiscard (interpreter)));
2169     }
2170 
2171     ~CommandObjectMultiwordThreadPlan() override = default;
2172 };
2173 
2174 //-------------------------------------------------------------------------
2175 // CommandObjectMultiwordThread
2176 //-------------------------------------------------------------------------
2177 
2178 CommandObjectMultiwordThread::CommandObjectMultiwordThread(CommandInterpreter &interpreter)
2179     : CommandObjectMultiword(interpreter, "thread",
2180                              "Commands for operating on one or more threads in the current process.",
2181                              "thread <subcommand> [<subcommand-options>]")
2182 {
2183     LoadSubCommand ("backtrace",  CommandObjectSP (new CommandObjectThreadBacktrace (interpreter)));
2184     LoadSubCommand ("continue",   CommandObjectSP (new CommandObjectThreadContinue (interpreter)));
2185     LoadSubCommand ("list",       CommandObjectSP (new CommandObjectThreadList (interpreter)));
2186     LoadSubCommand ("return",     CommandObjectSP (new CommandObjectThreadReturn (interpreter)));
2187     LoadSubCommand ("jump",       CommandObjectSP (new CommandObjectThreadJump (interpreter)));
2188     LoadSubCommand ("select",     CommandObjectSP (new CommandObjectThreadSelect (interpreter)));
2189     LoadSubCommand ("until",      CommandObjectSP (new CommandObjectThreadUntil (interpreter)));
2190     LoadSubCommand ("info",       CommandObjectSP (new CommandObjectThreadInfo (interpreter)));
2191     LoadSubCommand("step-in",
2192                    CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2193                        interpreter, "thread step-in",
2194                        "Source level single step, stepping into calls.  Defaults to current thread unless specified.",
2195                        nullptr, eStepTypeInto, eStepScopeSource)));
2196 
2197     LoadSubCommand("step-out",
2198                    CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2199                        interpreter, "thread step-out", "Finish executing the current stack frame and stop after "
2200                                                        "returning.  Defaults to current thread unless specified.",
2201                        nullptr, eStepTypeOut, eStepScopeSource)));
2202 
2203     LoadSubCommand("step-over",
2204                    CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2205                        interpreter, "thread step-over",
2206                        "Source level single step, stepping over calls.  Defaults to current thread unless specified.",
2207                        nullptr, eStepTypeOver, eStepScopeSource)));
2208 
2209     LoadSubCommand(
2210         "step-inst",
2211         CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2212             interpreter, "thread step-inst",
2213             "Instruction level single step, stepping into calls.  Defaults to current thread unless specified.",
2214             nullptr, eStepTypeTrace, eStepScopeInstruction)));
2215 
2216     LoadSubCommand(
2217         "step-inst-over",
2218         CommandObjectSP(new CommandObjectThreadStepWithTypeAndScope(
2219             interpreter, "thread step-inst-over",
2220             "Instruction level single step, stepping over calls.  Defaults to current thread unless specified.",
2221             nullptr, eStepTypeTraceOver, eStepScopeInstruction)));
2222 
2223     LoadSubCommand ("step-scripted", CommandObjectSP (new CommandObjectThreadStepWithTypeAndScope (
2224                                                     interpreter,
2225                                                     "thread step-scripted",
2226                                                     "Step as instructed by the script class passed in the -C option.",
2227                                                     nullptr,
2228                                                     eStepTypeScripted,
2229                                                     eStepScopeSource)));
2230 
2231     LoadSubCommand ("plan", CommandObjectSP (new CommandObjectMultiwordThreadPlan(interpreter)));
2232 }
2233 
2234 CommandObjectMultiwordThread::~CommandObjectMultiwordThread() = default;
2235