1 //===-- CommandObjectProcess.cpp ------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "CommandObjectProcess.h"
10 #include "CommandObjectTrace.h"
11 #include "CommandObjectBreakpoint.h"
12 #include "CommandOptionsProcessLaunch.h"
13 #include "lldb/Breakpoint/Breakpoint.h"
14 #include "lldb/Breakpoint/BreakpointIDList.h"
15 #include "lldb/Breakpoint/BreakpointLocation.h"
16 #include "lldb/Breakpoint/BreakpointName.h"
17 #include "lldb/Breakpoint/BreakpointSite.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/PluginManager.h"
20 #include "lldb/Host/OptionParser.h"
21 #include "lldb/Interpreter/CommandInterpreter.h"
22 #include "lldb/Interpreter/CommandReturnObject.h"
23 #include "lldb/Interpreter/OptionArgParser.h"
24 #include "lldb/Interpreter/OptionGroupPythonClassWithDict.h"
25 #include "lldb/Interpreter/Options.h"
26 #include "lldb/Target/Platform.h"
27 #include "lldb/Target/Process.h"
28 #include "lldb/Target/StopInfo.h"
29 #include "lldb/Target/Target.h"
30 #include "lldb/Target/Thread.h"
31 #include "lldb/Target/UnixSignals.h"
32 #include "lldb/Utility/Args.h"
33 #include "lldb/Utility/State.h"
34 
35 #include "llvm/ADT/ScopeExit.h"
36 
37 #include <bitset>
38 
39 using namespace lldb;
40 using namespace lldb_private;
41 
42 class CommandObjectProcessLaunchOrAttach : public CommandObjectParsed {
43 public:
44   CommandObjectProcessLaunchOrAttach(CommandInterpreter &interpreter,
45                                      const char *name, const char *help,
46                                      const char *syntax, uint32_t flags,
47                                      const char *new_process_action)
48       : CommandObjectParsed(interpreter, name, help, syntax, flags),
49         m_new_process_action(new_process_action) {}
50 
51   ~CommandObjectProcessLaunchOrAttach() override = default;
52 
53 protected:
54   bool StopProcessIfNecessary(Process *process, StateType &state,
55                               CommandReturnObject &result) {
56     state = eStateInvalid;
57     if (process) {
58       state = process->GetState();
59 
60       if (process->IsAlive() && state != eStateConnected) {
61         std::string message;
62         if (process->GetState() == eStateAttaching)
63           message =
64               llvm::formatv("There is a pending attach, abort it and {0}?",
65                             m_new_process_action);
66         else if (process->GetShouldDetach())
67           message = llvm::formatv(
68               "There is a running process, detach from it and {0}?",
69               m_new_process_action);
70         else
71           message =
72               llvm::formatv("There is a running process, kill it and {0}?",
73                             m_new_process_action);
74 
75         if (!m_interpreter.Confirm(message, true)) {
76           result.SetStatus(eReturnStatusFailed);
77           return false;
78         } else {
79           if (process->GetShouldDetach()) {
80             bool keep_stopped = false;
81             Status detach_error(process->Detach(keep_stopped));
82             if (detach_error.Success()) {
83               result.SetStatus(eReturnStatusSuccessFinishResult);
84               process = nullptr;
85             } else {
86               result.AppendErrorWithFormat(
87                   "Failed to detach from process: %s\n",
88                   detach_error.AsCString());
89             }
90           } else {
91             Status destroy_error(process->Destroy(false));
92             if (destroy_error.Success()) {
93               result.SetStatus(eReturnStatusSuccessFinishResult);
94               process = nullptr;
95             } else {
96               result.AppendErrorWithFormat("Failed to kill process: %s\n",
97                                            destroy_error.AsCString());
98             }
99           }
100         }
101       }
102     }
103     return result.Succeeded();
104   }
105 
106   std::string m_new_process_action;
107 };
108 
109 // CommandObjectProcessLaunch
110 #pragma mark CommandObjectProcessLaunch
111 class CommandObjectProcessLaunch : public CommandObjectProcessLaunchOrAttach {
112 public:
113   CommandObjectProcessLaunch(CommandInterpreter &interpreter)
114       : CommandObjectProcessLaunchOrAttach(
115             interpreter, "process launch",
116             "Launch the executable in the debugger.", nullptr,
117             eCommandRequiresTarget, "restart"),
118 
119         m_class_options("scripted process", true, 'C', 'k', 'v', 0) {
120     m_all_options.Append(&m_options);
121     m_all_options.Append(&m_class_options, LLDB_OPT_SET_1 | LLDB_OPT_SET_2,
122                          LLDB_OPT_SET_ALL);
123     m_all_options.Finalize();
124 
125     CommandArgumentEntry arg;
126     CommandArgumentData run_args_arg;
127 
128     // Define the first (and only) variant of this arg.
129     run_args_arg.arg_type = eArgTypeRunArgs;
130     run_args_arg.arg_repetition = eArgRepeatOptional;
131 
132     // There is only one variant this argument could be; put it into the
133     // argument entry.
134     arg.push_back(run_args_arg);
135 
136     // Push the data for the first argument into the m_arguments vector.
137     m_arguments.push_back(arg);
138   }
139 
140   ~CommandObjectProcessLaunch() override = default;
141 
142   void
143   HandleArgumentCompletion(CompletionRequest &request,
144                            OptionElementVector &opt_element_vector) override {
145 
146     CommandCompletions::InvokeCommonCompletionCallbacks(
147         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
148         request, nullptr);
149   }
150 
151   Options *GetOptions() override { return &m_all_options; }
152 
153   llvm::Optional<std::string> GetRepeatCommand(Args &current_command_args,
154                                                uint32_t index) override {
155     // No repeat for "process launch"...
156     return std::string("");
157   }
158 
159 protected:
160   bool DoExecute(Args &launch_args, CommandReturnObject &result) override {
161     Debugger &debugger = GetDebugger();
162     Target *target = debugger.GetSelectedTarget().get();
163     // If our listener is nullptr, users aren't allows to launch
164     ModuleSP exe_module_sp = target->GetExecutableModule();
165 
166     // If the target already has an executable module, then use that.  If it
167     // doesn't then someone must be trying to launch using a path that will
168     // make sense to the remote stub, but doesn't exist on the local host.
169     // In that case use the ExecutableFile that was set in the target's
170     // ProcessLaunchInfo.
171     if (exe_module_sp == nullptr && !target->GetProcessLaunchInfo().GetExecutableFile()) {
172       result.AppendError("no file in target, create a debug target using the "
173                          "'target create' command");
174       return false;
175     }
176 
177     StateType state = eStateInvalid;
178 
179     if (!StopProcessIfNecessary(m_exe_ctx.GetProcessPtr(), state, result))
180       return false;
181 
182     // Determine whether we will disable ASLR or leave it in the default state
183     // (i.e. enabled if the platform supports it). First check if the process
184     // launch options explicitly turn on/off
185     // disabling ASLR.  If so, use that setting;
186     // otherwise, use the 'settings target.disable-aslr' setting.
187     bool disable_aslr = false;
188     if (m_options.disable_aslr != eLazyBoolCalculate) {
189       // The user specified an explicit setting on the process launch line.
190       // Use it.
191       disable_aslr = (m_options.disable_aslr == eLazyBoolYes);
192     } else {
193       // The user did not explicitly specify whether to disable ASLR.  Fall
194       // back to the target.disable-aslr setting.
195       disable_aslr = target->GetDisableASLR();
196     }
197 
198     if (!m_class_options.GetName().empty()) {
199       m_options.launch_info.SetProcessPluginName("ScriptedProcess");
200       m_options.launch_info.SetScriptedProcessClassName(
201           m_class_options.GetName());
202       m_options.launch_info.SetScriptedProcessDictionarySP(
203           m_class_options.GetStructuredData());
204       target->SetProcessLaunchInfo(m_options.launch_info);
205     }
206 
207     if (disable_aslr)
208       m_options.launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
209     else
210       m_options.launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
211 
212     if (target->GetInheritTCC())
213       m_options.launch_info.GetFlags().Set(eLaunchFlagInheritTCCFromParent);
214 
215     if (target->GetDetachOnError())
216       m_options.launch_info.GetFlags().Set(eLaunchFlagDetachOnError);
217 
218     if (target->GetDisableSTDIO())
219       m_options.launch_info.GetFlags().Set(eLaunchFlagDisableSTDIO);
220 
221     // Merge the launch info environment with the target environment.
222     Environment target_env = target->GetEnvironment();
223     m_options.launch_info.GetEnvironment().insert(target_env.begin(),
224                                                   target_env.end());
225 
226     llvm::StringRef target_settings_argv0 = target->GetArg0();
227 
228     if (!target_settings_argv0.empty()) {
229       m_options.launch_info.GetArguments().AppendArgument(
230           target_settings_argv0);
231       if (exe_module_sp)
232         m_options.launch_info.SetExecutableFile(
233             exe_module_sp->GetPlatformFileSpec(), false);
234       else
235         m_options.launch_info.SetExecutableFile(target->GetProcessLaunchInfo().GetExecutableFile(), false);
236     } else {
237       if (exe_module_sp)
238         m_options.launch_info.SetExecutableFile(
239             exe_module_sp->GetPlatformFileSpec(), true);
240       else
241         m_options.launch_info.SetExecutableFile(target->GetProcessLaunchInfo().GetExecutableFile(), true);
242     }
243 
244     if (launch_args.GetArgumentCount() == 0) {
245       m_options.launch_info.GetArguments().AppendArguments(
246           target->GetProcessLaunchInfo().GetArguments());
247     } else {
248       m_options.launch_info.GetArguments().AppendArguments(launch_args);
249       // Save the arguments for subsequent runs in the current target.
250       target->SetRunArguments(launch_args);
251     }
252 
253     StreamString stream;
254     Status error = target->Launch(m_options.launch_info, &stream);
255 
256     if (error.Success()) {
257       ProcessSP process_sp(target->GetProcessSP());
258       if (process_sp) {
259         // There is a race condition where this thread will return up the call
260         // stack to the main command handler and show an (lldb) prompt before
261         // HandlePrivateEvent (from PrivateStateThread) has a chance to call
262         // PushProcessIOHandler().
263         process_sp->SyncIOHandler(0, std::chrono::seconds(2));
264 
265         llvm::StringRef data = stream.GetString();
266         if (!data.empty())
267           result.AppendMessage(data);
268         // If we didn't have a local executable, then we wouldn't have had an
269         // executable module before launch.
270         if (!exe_module_sp)
271           exe_module_sp = target->GetExecutableModule();
272         if (!exe_module_sp) {
273           result.AppendWarning("Could not get executable module after launch.");
274         } else {
275 
276           const char *archname =
277               exe_module_sp->GetArchitecture().GetArchitectureName();
278           result.AppendMessageWithFormat(
279               "Process %" PRIu64 " launched: '%s' (%s)\n", process_sp->GetID(),
280               exe_module_sp->GetFileSpec().GetPath().c_str(), archname);
281         }
282         result.SetStatus(eReturnStatusSuccessFinishResult);
283         result.SetDidChangeProcessState(true);
284       } else {
285         result.AppendError(
286             "no error returned from Target::Launch, and target has no process");
287       }
288     } else {
289       result.AppendError(error.AsCString());
290     }
291     return result.Succeeded();
292   }
293 
294   CommandOptionsProcessLaunch m_options;
295   OptionGroupPythonClassWithDict m_class_options;
296   OptionGroupOptions m_all_options;
297 };
298 
299 #define LLDB_OPTIONS_process_attach
300 #include "CommandOptions.inc"
301 
302 #pragma mark CommandObjectProcessAttach
303 class CommandObjectProcessAttach : public CommandObjectProcessLaunchOrAttach {
304 public:
305   class CommandOptions : public Options {
306   public:
307     CommandOptions() {
308       // Keep default values of all options in one place: OptionParsingStarting
309       // ()
310       OptionParsingStarting(nullptr);
311     }
312 
313     ~CommandOptions() override = default;
314 
315     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
316                           ExecutionContext *execution_context) override {
317       Status error;
318       const int short_option = m_getopt_table[option_idx].val;
319       switch (short_option) {
320       case 'c':
321         attach_info.SetContinueOnceAttached(true);
322         break;
323 
324       case 'p': {
325         lldb::pid_t pid;
326         if (option_arg.getAsInteger(0, pid)) {
327           error.SetErrorStringWithFormat("invalid process ID '%s'",
328                                          option_arg.str().c_str());
329         } else {
330           attach_info.SetProcessID(pid);
331         }
332       } break;
333 
334       case 'P':
335         attach_info.SetProcessPluginName(option_arg);
336         break;
337 
338       case 'n':
339         attach_info.GetExecutableFile().SetFile(option_arg,
340                                                 FileSpec::Style::native);
341         break;
342 
343       case 'w':
344         attach_info.SetWaitForLaunch(true);
345         break;
346 
347       case 'i':
348         attach_info.SetIgnoreExisting(false);
349         break;
350 
351       default:
352         llvm_unreachable("Unimplemented option");
353       }
354       return error;
355     }
356 
357     void OptionParsingStarting(ExecutionContext *execution_context) override {
358       attach_info.Clear();
359     }
360 
361     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
362       return llvm::makeArrayRef(g_process_attach_options);
363     }
364 
365     ProcessAttachInfo attach_info;
366   };
367 
368   CommandObjectProcessAttach(CommandInterpreter &interpreter)
369       : CommandObjectProcessLaunchOrAttach(
370             interpreter, "process attach", "Attach to a process.",
371             "process attach <cmd-options>", 0, "attach") {}
372 
373   ~CommandObjectProcessAttach() override = default;
374 
375   Options *GetOptions() override { return &m_options; }
376 
377 protected:
378   bool DoExecute(Args &command, CommandReturnObject &result) override {
379     PlatformSP platform_sp(
380         GetDebugger().GetPlatformList().GetSelectedPlatform());
381 
382     Target *target = GetDebugger().GetSelectedTarget().get();
383     // N.B. The attach should be synchronous.  It doesn't help much to get the
384     // prompt back between initiating the attach and the target actually
385     // stopping.  So even if the interpreter is set to be asynchronous, we wait
386     // for the stop ourselves here.
387 
388     StateType state = eStateInvalid;
389     Process *process = m_exe_ctx.GetProcessPtr();
390 
391     if (!StopProcessIfNecessary(process, state, result))
392       return false;
393 
394     if (target == nullptr) {
395       // If there isn't a current target create one.
396       TargetSP new_target_sp;
397       Status error;
398 
399       error = GetDebugger().GetTargetList().CreateTarget(
400           GetDebugger(), "", "", eLoadDependentsNo,
401           nullptr, // No platform options
402           new_target_sp);
403       target = new_target_sp.get();
404       if (target == nullptr || error.Fail()) {
405         result.AppendError(error.AsCString("Error creating target"));
406         return false;
407       }
408     }
409 
410     // Record the old executable module, we want to issue a warning if the
411     // process of attaching changed the current executable (like somebody said
412     // "file foo" then attached to a PID whose executable was bar.)
413 
414     ModuleSP old_exec_module_sp = target->GetExecutableModule();
415     ArchSpec old_arch_spec = target->GetArchitecture();
416 
417     if (command.GetArgumentCount()) {
418       result.AppendErrorWithFormat("Invalid arguments for '%s'.\nUsage: %s\n",
419                                    m_cmd_name.c_str(), m_cmd_syntax.c_str());
420       return false;
421     }
422 
423     StreamString stream;
424     ProcessSP process_sp;
425     const auto error = target->Attach(m_options.attach_info, &stream);
426     if (error.Success()) {
427       process_sp = target->GetProcessSP();
428       if (process_sp) {
429         result.AppendMessage(stream.GetString());
430         result.SetStatus(eReturnStatusSuccessFinishNoResult);
431         result.SetDidChangeProcessState(true);
432       } else {
433         result.AppendError(
434             "no error returned from Target::Attach, and target has no process");
435       }
436     } else {
437       result.AppendErrorWithFormat("attach failed: %s\n", error.AsCString());
438     }
439 
440     if (!result.Succeeded())
441       return false;
442 
443     // Okay, we're done.  Last step is to warn if the executable module has
444     // changed:
445     char new_path[PATH_MAX];
446     ModuleSP new_exec_module_sp(target->GetExecutableModule());
447     if (!old_exec_module_sp) {
448       // We might not have a module if we attached to a raw pid...
449       if (new_exec_module_sp) {
450         new_exec_module_sp->GetFileSpec().GetPath(new_path, PATH_MAX);
451         result.AppendMessageWithFormat("Executable module set to \"%s\".\n",
452                                        new_path);
453       }
454     } else if (old_exec_module_sp->GetFileSpec() !=
455                new_exec_module_sp->GetFileSpec()) {
456       char old_path[PATH_MAX];
457 
458       old_exec_module_sp->GetFileSpec().GetPath(old_path, PATH_MAX);
459       new_exec_module_sp->GetFileSpec().GetPath(new_path, PATH_MAX);
460 
461       result.AppendWarningWithFormat(
462           "Executable module changed from \"%s\" to \"%s\".\n", old_path,
463           new_path);
464     }
465 
466     if (!old_arch_spec.IsValid()) {
467       result.AppendMessageWithFormat(
468           "Architecture set to: %s.\n",
469           target->GetArchitecture().GetTriple().getTriple().c_str());
470     } else if (!old_arch_spec.IsExactMatch(target->GetArchitecture())) {
471       result.AppendWarningWithFormat(
472           "Architecture changed from %s to %s.\n",
473           old_arch_spec.GetTriple().getTriple().c_str(),
474           target->GetArchitecture().GetTriple().getTriple().c_str());
475     }
476 
477     // This supports the use-case scenario of immediately continuing the
478     // process once attached.
479     if (m_options.attach_info.GetContinueOnceAttached()) {
480       // We have made a process but haven't told the interpreter about it yet,
481       // so CheckRequirements will fail for "process continue".  Set the override
482       // here:
483       ExecutionContext exe_ctx(process_sp);
484       m_interpreter.HandleCommand("process continue", eLazyBoolNo, exe_ctx, result);
485     }
486 
487     return result.Succeeded();
488   }
489 
490   CommandOptions m_options;
491 };
492 
493 // CommandObjectProcessContinue
494 
495 #define LLDB_OPTIONS_process_continue
496 #include "CommandOptions.inc"
497 
498 #pragma mark CommandObjectProcessContinue
499 
500 class CommandObjectProcessContinue : public CommandObjectParsed {
501 public:
502   CommandObjectProcessContinue(CommandInterpreter &interpreter)
503       : CommandObjectParsed(
504             interpreter, "process continue",
505             "Continue execution of all threads in the current process.",
506             "process continue",
507             eCommandRequiresProcess | eCommandTryTargetAPILock |
508                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
509 
510   ~CommandObjectProcessContinue() override = default;
511 
512 protected:
513   class CommandOptions : public Options {
514   public:
515     CommandOptions() {
516       // Keep default values of all options in one place: OptionParsingStarting
517       // ()
518       OptionParsingStarting(nullptr);
519     }
520 
521     ~CommandOptions() override = default;
522 
523     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
524                           ExecutionContext *exe_ctx) override {
525       Status error;
526       const int short_option = m_getopt_table[option_idx].val;
527       switch (short_option) {
528       case 'i':
529         if (option_arg.getAsInteger(0, m_ignore))
530           error.SetErrorStringWithFormat(
531               "invalid value for ignore option: \"%s\", should be a number.",
532               option_arg.str().c_str());
533         break;
534       case 'b':
535         m_run_to_bkpt_args.AppendArgument(option_arg);
536         m_any_bkpts_specified = true;
537       break;
538       default:
539         llvm_unreachable("Unimplemented option");
540       }
541       return error;
542     }
543 
544     void OptionParsingStarting(ExecutionContext *execution_context) override {
545       m_ignore = 0;
546       m_run_to_bkpt_args.Clear();
547       m_any_bkpts_specified = false;
548     }
549 
550     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
551       return llvm::makeArrayRef(g_process_continue_options);
552     }
553 
554     uint32_t m_ignore = 0;
555     Args m_run_to_bkpt_args;
556     bool m_any_bkpts_specified = false;
557   };
558 
559 
560   bool DoExecute(Args &command, CommandReturnObject &result) override {
561     Process *process = m_exe_ctx.GetProcessPtr();
562     bool synchronous_execution = m_interpreter.GetSynchronous();
563     StateType state = process->GetState();
564     if (state == eStateStopped) {
565       if (command.GetArgumentCount() != 0) {
566         result.AppendErrorWithFormat(
567             "The '%s' command does not take any arguments.\n",
568             m_cmd_name.c_str());
569         return false;
570       }
571 
572       if (m_options.m_ignore > 0) {
573         ThreadSP sel_thread_sp(GetDefaultThread()->shared_from_this());
574         if (sel_thread_sp) {
575           StopInfoSP stop_info_sp = sel_thread_sp->GetStopInfo();
576           if (stop_info_sp &&
577               stop_info_sp->GetStopReason() == eStopReasonBreakpoint) {
578             lldb::break_id_t bp_site_id =
579                 (lldb::break_id_t)stop_info_sp->GetValue();
580             BreakpointSiteSP bp_site_sp(
581                 process->GetBreakpointSiteList().FindByID(bp_site_id));
582             if (bp_site_sp) {
583               const size_t num_owners = bp_site_sp->GetNumberOfOwners();
584               for (size_t i = 0; i < num_owners; i++) {
585                 Breakpoint &bp_ref =
586                     bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint();
587                 if (!bp_ref.IsInternal()) {
588                   bp_ref.SetIgnoreCount(m_options.m_ignore);
589                 }
590               }
591             }
592           }
593         }
594       }
595 
596       Target *target = m_exe_ctx.GetTargetPtr();
597       BreakpointIDList run_to_bkpt_ids;
598       // Don't pass an empty run_to_breakpoint list, as Verify will look for the
599       // default breakpoint.
600       if (m_options.m_run_to_bkpt_args.GetArgumentCount() > 0)
601         CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
602             m_options.m_run_to_bkpt_args, target, result, &run_to_bkpt_ids,
603             BreakpointName::Permissions::disablePerm);
604       if (!result.Succeeded()) {
605         return false;
606       }
607       result.Clear();
608       if (m_options.m_any_bkpts_specified && run_to_bkpt_ids.GetSize() == 0) {
609         result.AppendError("continue-to breakpoints did not specify any actual "
610                            "breakpoints or locations");
611         return false;
612       }
613 
614       // First figure out which breakpoints & locations were specified by the
615       // user:
616       size_t num_run_to_bkpt_ids = run_to_bkpt_ids.GetSize();
617       std::vector<break_id_t> bkpts_disabled;
618       std::vector<BreakpointID> locs_disabled;
619       if (num_run_to_bkpt_ids != 0) {
620         // Go through the ID's specified, and separate the breakpoints from are
621         // the breakpoint.location specifications since the latter require
622         // special handling.  We also figure out whether there's at least one
623         // specifier in the set that is enabled.
624         BreakpointList &bkpt_list = target->GetBreakpointList();
625         std::unordered_set<break_id_t> bkpts_seen;
626         std::unordered_set<break_id_t> bkpts_with_locs_seen;
627         BreakpointIDList with_locs;
628         bool any_enabled = false;
629 
630         for (size_t idx = 0; idx < num_run_to_bkpt_ids; idx++) {
631           BreakpointID bkpt_id = run_to_bkpt_ids.GetBreakpointIDAtIndex(idx);
632           break_id_t bp_id = bkpt_id.GetBreakpointID();
633           break_id_t loc_id = bkpt_id.GetLocationID();
634           BreakpointSP bp_sp
635               = bkpt_list.FindBreakpointByID(bp_id);
636           // Note, VerifyBreakpointOrLocationIDs checks for existence, so we
637           // don't need to do it again here.
638           if (bp_sp->IsEnabled()) {
639             if (loc_id == LLDB_INVALID_BREAK_ID) {
640               // A breakpoint (without location) was specified.  Make sure that
641               // at least one of the locations is enabled.
642               size_t num_locations = bp_sp->GetNumLocations();
643               for (size_t loc_idx = 0; loc_idx < num_locations; loc_idx++) {
644                 BreakpointLocationSP loc_sp
645                     = bp_sp->GetLocationAtIndex(loc_idx);
646                 if (loc_sp->IsEnabled()) {
647                   any_enabled = true;
648                   break;
649                 }
650               }
651             } else {
652               // A location was specified, check if it was enabled:
653               BreakpointLocationSP loc_sp = bp_sp->FindLocationByID(loc_id);
654               if (loc_sp->IsEnabled())
655                 any_enabled = true;
656             }
657 
658             // Then sort the bp & bp.loc entries for later use:
659             if (bkpt_id.GetLocationID() == LLDB_INVALID_BREAK_ID)
660               bkpts_seen.insert(bkpt_id.GetBreakpointID());
661             else {
662               bkpts_with_locs_seen.insert(bkpt_id.GetBreakpointID());
663               with_locs.AddBreakpointID(bkpt_id);
664             }
665           }
666         }
667         // Do all the error checking here so once we start disabling we don't
668         // have to back out half-way through.
669 
670         // Make sure at least one of the specified breakpoints is enabled.
671         if (!any_enabled) {
672           result.AppendError("at least one of the continue-to breakpoints must "
673                              "be enabled.");
674           return false;
675         }
676 
677         // Also, if you specify BOTH a breakpoint and one of it's locations,
678         // we flag that as an error, since it won't do what you expect, the
679         // breakpoint directive will mean "run to all locations", which is not
680         // what the location directive means...
681         for (break_id_t bp_id : bkpts_with_locs_seen) {
682           if (bkpts_seen.count(bp_id)) {
683             result.AppendErrorWithFormatv("can't specify both a breakpoint and "
684                                "one of its locations: {0}", bp_id);
685           }
686         }
687 
688         // Now go through the breakpoints in the target, disabling all the ones
689         // that the user didn't mention:
690         for (BreakpointSP bp_sp : bkpt_list.Breakpoints()) {
691           break_id_t bp_id = bp_sp->GetID();
692           // Handle the case where no locations were specified.  Note we don't
693           // have to worry about the case where a breakpoint and one of its
694           // locations are both in the lists, we've already disallowed that.
695           if (!bkpts_with_locs_seen.count(bp_id)) {
696             if (!bkpts_seen.count(bp_id) && bp_sp->IsEnabled()) {
697               bkpts_disabled.push_back(bp_id);
698               bp_sp->SetEnabled(false);
699             }
700             continue;
701           }
702           // Next, handle the case where a location was specified:
703           // Run through all the locations of this breakpoint and disable
704           // the ones that aren't on our "with locations" BreakpointID list:
705           size_t num_locations = bp_sp->GetNumLocations();
706           BreakpointID tmp_id(bp_id, LLDB_INVALID_BREAK_ID);
707           for (size_t loc_idx = 0; loc_idx < num_locations; loc_idx++) {
708             BreakpointLocationSP loc_sp = bp_sp->GetLocationAtIndex(loc_idx);
709             tmp_id.SetBreakpointLocationID(loc_idx);
710             size_t position = 0;
711             if (!with_locs.FindBreakpointID(tmp_id, &position)
712                 && loc_sp->IsEnabled()) {
713               locs_disabled.push_back(tmp_id);
714               loc_sp->SetEnabled(false);
715             }
716           }
717         }
718       }
719 
720       { // Scope for thread list mutex:
721         std::lock_guard<std::recursive_mutex> guard(
722             process->GetThreadList().GetMutex());
723         const uint32_t num_threads = process->GetThreadList().GetSize();
724 
725         // Set the actions that the threads should each take when resuming
726         for (uint32_t idx = 0; idx < num_threads; ++idx) {
727           const bool override_suspend = false;
728           process->GetThreadList().GetThreadAtIndex(idx)->SetResumeState(
729               eStateRunning, override_suspend);
730         }
731       }
732 
733       const uint32_t iohandler_id = process->GetIOHandlerID();
734 
735       StreamString stream;
736       Status error;
737       // For now we can only do -b with synchronous:
738       bool old_sync = GetDebugger().GetAsyncExecution();
739 
740       if (run_to_bkpt_ids.GetSize() != 0) {
741         GetDebugger().SetAsyncExecution(false);
742         synchronous_execution = true;
743       }
744       if (synchronous_execution)
745         error = process->ResumeSynchronous(&stream);
746       else
747         error = process->Resume();
748 
749       if (run_to_bkpt_ids.GetSize() != 0) {
750         GetDebugger().SetAsyncExecution(old_sync);
751       }
752 
753       // Now re-enable the breakpoints we disabled:
754       BreakpointList &bkpt_list = target->GetBreakpointList();
755       for (break_id_t bp_id : bkpts_disabled) {
756         BreakpointSP bp_sp = bkpt_list.FindBreakpointByID(bp_id);
757         if (bp_sp)
758           bp_sp->SetEnabled(true);
759       }
760       for (const BreakpointID &bkpt_id : locs_disabled) {
761         BreakpointSP bp_sp
762             = bkpt_list.FindBreakpointByID(bkpt_id.GetBreakpointID());
763         if (bp_sp) {
764           BreakpointLocationSP loc_sp
765               = bp_sp->FindLocationByID(bkpt_id.GetLocationID());
766           if (loc_sp)
767             loc_sp->SetEnabled(true);
768         }
769       }
770 
771       if (error.Success()) {
772         // There is a race condition where this thread will return up the call
773         // stack to the main command handler and show an (lldb) prompt before
774         // HandlePrivateEvent (from PrivateStateThread) has a chance to call
775         // PushProcessIOHandler().
776         process->SyncIOHandler(iohandler_id, std::chrono::seconds(2));
777 
778         result.AppendMessageWithFormat("Process %" PRIu64 " resuming\n",
779                                        process->GetID());
780         if (synchronous_execution) {
781           // If any state changed events had anything to say, add that to the
782           // result
783           result.AppendMessage(stream.GetString());
784 
785           result.SetDidChangeProcessState(true);
786           result.SetStatus(eReturnStatusSuccessFinishNoResult);
787         } else {
788           result.SetStatus(eReturnStatusSuccessContinuingNoResult);
789         }
790       } else {
791         result.AppendErrorWithFormat("Failed to resume process: %s.\n",
792                                      error.AsCString());
793       }
794     } else {
795       result.AppendErrorWithFormat(
796           "Process cannot be continued from its current state (%s).\n",
797           StateAsCString(state));
798     }
799     return result.Succeeded();
800   }
801 
802   Options *GetOptions() override { return &m_options; }
803 
804   CommandOptions m_options;
805 };
806 
807 // CommandObjectProcessDetach
808 #define LLDB_OPTIONS_process_detach
809 #include "CommandOptions.inc"
810 
811 #pragma mark CommandObjectProcessDetach
812 
813 class CommandObjectProcessDetach : public CommandObjectParsed {
814 public:
815   class CommandOptions : public Options {
816   public:
817     CommandOptions() { OptionParsingStarting(nullptr); }
818 
819     ~CommandOptions() override = default;
820 
821     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
822                           ExecutionContext *execution_context) override {
823       Status error;
824       const int short_option = m_getopt_table[option_idx].val;
825 
826       switch (short_option) {
827       case 's':
828         bool tmp_result;
829         bool success;
830         tmp_result = OptionArgParser::ToBoolean(option_arg, false, &success);
831         if (!success)
832           error.SetErrorStringWithFormat("invalid boolean option: \"%s\"",
833                                          option_arg.str().c_str());
834         else {
835           if (tmp_result)
836             m_keep_stopped = eLazyBoolYes;
837           else
838             m_keep_stopped = eLazyBoolNo;
839         }
840         break;
841       default:
842         llvm_unreachable("Unimplemented option");
843       }
844       return error;
845     }
846 
847     void OptionParsingStarting(ExecutionContext *execution_context) override {
848       m_keep_stopped = eLazyBoolCalculate;
849     }
850 
851     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
852       return llvm::makeArrayRef(g_process_detach_options);
853     }
854 
855     // Instance variables to hold the values for command options.
856     LazyBool m_keep_stopped;
857   };
858 
859   CommandObjectProcessDetach(CommandInterpreter &interpreter)
860       : CommandObjectParsed(interpreter, "process detach",
861                             "Detach from the current target process.",
862                             "process detach",
863                             eCommandRequiresProcess | eCommandTryTargetAPILock |
864                                 eCommandProcessMustBeLaunched) {}
865 
866   ~CommandObjectProcessDetach() override = default;
867 
868   Options *GetOptions() override { return &m_options; }
869 
870 protected:
871   bool DoExecute(Args &command, CommandReturnObject &result) override {
872     Process *process = m_exe_ctx.GetProcessPtr();
873     // FIXME: This will be a Command Option:
874     bool keep_stopped;
875     if (m_options.m_keep_stopped == eLazyBoolCalculate) {
876       // Check the process default:
877       keep_stopped = process->GetDetachKeepsStopped();
878     } else if (m_options.m_keep_stopped == eLazyBoolYes)
879       keep_stopped = true;
880     else
881       keep_stopped = false;
882 
883     Status error(process->Detach(keep_stopped));
884     if (error.Success()) {
885       result.SetStatus(eReturnStatusSuccessFinishResult);
886     } else {
887       result.AppendErrorWithFormat("Detach failed: %s\n", error.AsCString());
888       return false;
889     }
890     return result.Succeeded();
891   }
892 
893   CommandOptions m_options;
894 };
895 
896 // CommandObjectProcessConnect
897 #define LLDB_OPTIONS_process_connect
898 #include "CommandOptions.inc"
899 
900 #pragma mark CommandObjectProcessConnect
901 
902 class CommandObjectProcessConnect : public CommandObjectParsed {
903 public:
904   class CommandOptions : public Options {
905   public:
906     CommandOptions() {
907       // Keep default values of all options in one place: OptionParsingStarting
908       // ()
909       OptionParsingStarting(nullptr);
910     }
911 
912     ~CommandOptions() override = default;
913 
914     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
915                           ExecutionContext *execution_context) override {
916       Status error;
917       const int short_option = m_getopt_table[option_idx].val;
918 
919       switch (short_option) {
920       case 'p':
921         plugin_name.assign(std::string(option_arg));
922         break;
923 
924       default:
925         llvm_unreachable("Unimplemented option");
926       }
927       return error;
928     }
929 
930     void OptionParsingStarting(ExecutionContext *execution_context) override {
931       plugin_name.clear();
932     }
933 
934     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
935       return llvm::makeArrayRef(g_process_connect_options);
936     }
937 
938     // Instance variables to hold the values for command options.
939 
940     std::string plugin_name;
941   };
942 
943   CommandObjectProcessConnect(CommandInterpreter &interpreter)
944       : CommandObjectParsed(interpreter, "process connect",
945                             "Connect to a remote debug service.",
946                             "process connect <remote-url>", 0) {}
947 
948   ~CommandObjectProcessConnect() override = default;
949 
950   Options *GetOptions() override { return &m_options; }
951 
952 protected:
953   bool DoExecute(Args &command, CommandReturnObject &result) override {
954     if (command.GetArgumentCount() != 1) {
955       result.AppendErrorWithFormat(
956           "'%s' takes exactly one argument:\nUsage: %s\n", m_cmd_name.c_str(),
957           m_cmd_syntax.c_str());
958       return false;
959     }
960 
961     Process *process = m_exe_ctx.GetProcessPtr();
962     if (process && process->IsAlive()) {
963       result.AppendErrorWithFormat(
964           "Process %" PRIu64
965           " is currently being debugged, kill the process before connecting.\n",
966           process->GetID());
967       return false;
968     }
969 
970     const char *plugin_name = nullptr;
971     if (!m_options.plugin_name.empty())
972       plugin_name = m_options.plugin_name.c_str();
973 
974     Status error;
975     Debugger &debugger = GetDebugger();
976     PlatformSP platform_sp = m_interpreter.GetPlatform(true);
977     ProcessSP process_sp =
978         debugger.GetAsyncExecution()
979             ? platform_sp->ConnectProcess(
980                   command.GetArgumentAtIndex(0), plugin_name, debugger,
981                   debugger.GetSelectedTarget().get(), error)
982             : platform_sp->ConnectProcessSynchronous(
983                   command.GetArgumentAtIndex(0), plugin_name, debugger,
984                   result.GetOutputStream(), debugger.GetSelectedTarget().get(),
985                   error);
986     if (error.Fail() || process_sp == nullptr) {
987       result.AppendError(error.AsCString("Error connecting to the process"));
988       return false;
989     }
990     return true;
991   }
992 
993   CommandOptions m_options;
994 };
995 
996 // CommandObjectProcessPlugin
997 #pragma mark CommandObjectProcessPlugin
998 
999 class CommandObjectProcessPlugin : public CommandObjectProxy {
1000 public:
1001   CommandObjectProcessPlugin(CommandInterpreter &interpreter)
1002       : CommandObjectProxy(
1003             interpreter, "process plugin",
1004             "Send a custom command to the current target process plug-in.",
1005             "process plugin <args>", 0) {}
1006 
1007   ~CommandObjectProcessPlugin() override = default;
1008 
1009   CommandObject *GetProxyCommandObject() override {
1010     Process *process = m_interpreter.GetExecutionContext().GetProcessPtr();
1011     if (process)
1012       return process->GetPluginCommandObject();
1013     return nullptr;
1014   }
1015 };
1016 
1017 // CommandObjectProcessLoad
1018 #define LLDB_OPTIONS_process_load
1019 #include "CommandOptions.inc"
1020 
1021 #pragma mark CommandObjectProcessLoad
1022 
1023 class CommandObjectProcessLoad : public CommandObjectParsed {
1024 public:
1025   class CommandOptions : public Options {
1026   public:
1027     CommandOptions() {
1028       // Keep default values of all options in one place: OptionParsingStarting
1029       // ()
1030       OptionParsingStarting(nullptr);
1031     }
1032 
1033     ~CommandOptions() override = default;
1034 
1035     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1036                           ExecutionContext *execution_context) override {
1037       Status error;
1038       const int short_option = m_getopt_table[option_idx].val;
1039       switch (short_option) {
1040       case 'i':
1041         do_install = true;
1042         if (!option_arg.empty())
1043           install_path.SetFile(option_arg, FileSpec::Style::native);
1044         break;
1045       default:
1046         llvm_unreachable("Unimplemented option");
1047       }
1048       return error;
1049     }
1050 
1051     void OptionParsingStarting(ExecutionContext *execution_context) override {
1052       do_install = false;
1053       install_path.Clear();
1054     }
1055 
1056     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1057       return llvm::makeArrayRef(g_process_load_options);
1058     }
1059 
1060     // Instance variables to hold the values for command options.
1061     bool do_install;
1062     FileSpec install_path;
1063   };
1064 
1065   CommandObjectProcessLoad(CommandInterpreter &interpreter)
1066       : CommandObjectParsed(interpreter, "process load",
1067                             "Load a shared library into the current process.",
1068                             "process load <filename> [<filename> ...]",
1069                             eCommandRequiresProcess | eCommandTryTargetAPILock |
1070                                 eCommandProcessMustBeLaunched |
1071                                 eCommandProcessMustBePaused) {}
1072 
1073   ~CommandObjectProcessLoad() override = default;
1074 
1075   void
1076   HandleArgumentCompletion(CompletionRequest &request,
1077                            OptionElementVector &opt_element_vector) override {
1078     if (!m_exe_ctx.HasProcessScope())
1079       return;
1080 
1081     CommandCompletions::InvokeCommonCompletionCallbacks(
1082         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
1083         request, nullptr);
1084   }
1085 
1086   Options *GetOptions() override { return &m_options; }
1087 
1088 protected:
1089   bool DoExecute(Args &command, CommandReturnObject &result) override {
1090     Process *process = m_exe_ctx.GetProcessPtr();
1091 
1092     for (auto &entry : command.entries()) {
1093       Status error;
1094       PlatformSP platform = process->GetTarget().GetPlatform();
1095       llvm::StringRef image_path = entry.ref();
1096       uint32_t image_token = LLDB_INVALID_IMAGE_TOKEN;
1097 
1098       if (!m_options.do_install) {
1099         FileSpec image_spec(image_path);
1100         platform->ResolveRemotePath(image_spec, image_spec);
1101         image_token =
1102             platform->LoadImage(process, FileSpec(), image_spec, error);
1103       } else if (m_options.install_path) {
1104         FileSpec image_spec(image_path);
1105         FileSystem::Instance().Resolve(image_spec);
1106         platform->ResolveRemotePath(m_options.install_path,
1107                                     m_options.install_path);
1108         image_token = platform->LoadImage(process, image_spec,
1109                                           m_options.install_path, error);
1110       } else {
1111         FileSpec image_spec(image_path);
1112         FileSystem::Instance().Resolve(image_spec);
1113         image_token =
1114             platform->LoadImage(process, image_spec, FileSpec(), error);
1115       }
1116 
1117       if (image_token != LLDB_INVALID_IMAGE_TOKEN) {
1118         result.AppendMessageWithFormat(
1119             "Loading \"%s\"...ok\nImage %u loaded.\n", image_path.str().c_str(),
1120             image_token);
1121         result.SetStatus(eReturnStatusSuccessFinishResult);
1122       } else {
1123         result.AppendErrorWithFormat("failed to load '%s': %s",
1124                                      image_path.str().c_str(),
1125                                      error.AsCString());
1126       }
1127     }
1128     return result.Succeeded();
1129   }
1130 
1131   CommandOptions m_options;
1132 };
1133 
1134 // CommandObjectProcessUnload
1135 #pragma mark CommandObjectProcessUnload
1136 
1137 class CommandObjectProcessUnload : public CommandObjectParsed {
1138 public:
1139   CommandObjectProcessUnload(CommandInterpreter &interpreter)
1140       : CommandObjectParsed(
1141             interpreter, "process unload",
1142             "Unload a shared library from the current process using the index "
1143             "returned by a previous call to \"process load\".",
1144             "process unload <index>",
1145             eCommandRequiresProcess | eCommandTryTargetAPILock |
1146                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
1147 
1148   ~CommandObjectProcessUnload() override = default;
1149 
1150   void
1151   HandleArgumentCompletion(CompletionRequest &request,
1152                            OptionElementVector &opt_element_vector) override {
1153 
1154     if (request.GetCursorIndex() || !m_exe_ctx.HasProcessScope())
1155       return;
1156 
1157     Process *process = m_exe_ctx.GetProcessPtr();
1158 
1159     const std::vector<lldb::addr_t> &tokens = process->GetImageTokens();
1160     const size_t token_num = tokens.size();
1161     for (size_t i = 0; i < token_num; ++i) {
1162       if (tokens[i] == LLDB_INVALID_IMAGE_TOKEN)
1163         continue;
1164       request.TryCompleteCurrentArg(std::to_string(i));
1165     }
1166   }
1167 
1168 protected:
1169   bool DoExecute(Args &command, CommandReturnObject &result) override {
1170     Process *process = m_exe_ctx.GetProcessPtr();
1171 
1172     for (auto &entry : command.entries()) {
1173       uint32_t image_token;
1174       if (entry.ref().getAsInteger(0, image_token)) {
1175         result.AppendErrorWithFormat("invalid image index argument '%s'",
1176                                      entry.ref().str().c_str());
1177         break;
1178       } else {
1179         Status error(process->GetTarget().GetPlatform()->UnloadImage(
1180             process, image_token));
1181         if (error.Success()) {
1182           result.AppendMessageWithFormat(
1183               "Unloading shared library with index %u...ok\n", image_token);
1184           result.SetStatus(eReturnStatusSuccessFinishResult);
1185         } else {
1186           result.AppendErrorWithFormat("failed to unload image: %s",
1187                                        error.AsCString());
1188           break;
1189         }
1190       }
1191     }
1192     return result.Succeeded();
1193   }
1194 };
1195 
1196 // CommandObjectProcessSignal
1197 #pragma mark CommandObjectProcessSignal
1198 
1199 class CommandObjectProcessSignal : public CommandObjectParsed {
1200 public:
1201   CommandObjectProcessSignal(CommandInterpreter &interpreter)
1202       : CommandObjectParsed(
1203             interpreter, "process signal",
1204             "Send a UNIX signal to the current target process.", nullptr,
1205             eCommandRequiresProcess | eCommandTryTargetAPILock) {
1206     CommandArgumentEntry arg;
1207     CommandArgumentData signal_arg;
1208 
1209     // Define the first (and only) variant of this arg.
1210     signal_arg.arg_type = eArgTypeUnixSignal;
1211     signal_arg.arg_repetition = eArgRepeatPlain;
1212 
1213     // There is only one variant this argument could be; put it into the
1214     // argument entry.
1215     arg.push_back(signal_arg);
1216 
1217     // Push the data for the first argument into the m_arguments vector.
1218     m_arguments.push_back(arg);
1219   }
1220 
1221   ~CommandObjectProcessSignal() override = default;
1222 
1223   void
1224   HandleArgumentCompletion(CompletionRequest &request,
1225                            OptionElementVector &opt_element_vector) override {
1226     if (!m_exe_ctx.HasProcessScope() || request.GetCursorIndex() != 0)
1227       return;
1228 
1229     UnixSignalsSP signals = m_exe_ctx.GetProcessPtr()->GetUnixSignals();
1230     int signo = signals->GetFirstSignalNumber();
1231     while (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1232       request.TryCompleteCurrentArg(signals->GetSignalAsCString(signo));
1233       signo = signals->GetNextSignalNumber(signo);
1234     }
1235   }
1236 
1237 protected:
1238   bool DoExecute(Args &command, CommandReturnObject &result) override {
1239     Process *process = m_exe_ctx.GetProcessPtr();
1240 
1241     if (command.GetArgumentCount() == 1) {
1242       int signo = LLDB_INVALID_SIGNAL_NUMBER;
1243 
1244       const char *signal_name = command.GetArgumentAtIndex(0);
1245       if (::isxdigit(signal_name[0])) {
1246         if (!llvm::to_integer(signal_name, signo))
1247           signo = LLDB_INVALID_SIGNAL_NUMBER;
1248       } else
1249         signo = process->GetUnixSignals()->GetSignalNumberFromName(signal_name);
1250 
1251       if (signo == LLDB_INVALID_SIGNAL_NUMBER) {
1252         result.AppendErrorWithFormat("Invalid signal argument '%s'.\n",
1253                                      command.GetArgumentAtIndex(0));
1254       } else {
1255         Status error(process->Signal(signo));
1256         if (error.Success()) {
1257           result.SetStatus(eReturnStatusSuccessFinishResult);
1258         } else {
1259           result.AppendErrorWithFormat("Failed to send signal %i: %s\n", signo,
1260                                        error.AsCString());
1261         }
1262       }
1263     } else {
1264       result.AppendErrorWithFormat(
1265           "'%s' takes exactly one signal number argument:\nUsage: %s\n",
1266           m_cmd_name.c_str(), m_cmd_syntax.c_str());
1267     }
1268     return result.Succeeded();
1269   }
1270 };
1271 
1272 // CommandObjectProcessInterrupt
1273 #pragma mark CommandObjectProcessInterrupt
1274 
1275 class CommandObjectProcessInterrupt : public CommandObjectParsed {
1276 public:
1277   CommandObjectProcessInterrupt(CommandInterpreter &interpreter)
1278       : CommandObjectParsed(interpreter, "process interrupt",
1279                             "Interrupt the current target process.",
1280                             "process interrupt",
1281                             eCommandRequiresProcess | eCommandTryTargetAPILock |
1282                                 eCommandProcessMustBeLaunched) {}
1283 
1284   ~CommandObjectProcessInterrupt() override = default;
1285 
1286 protected:
1287   bool DoExecute(Args &command, CommandReturnObject &result) override {
1288     Process *process = m_exe_ctx.GetProcessPtr();
1289     if (process == nullptr) {
1290       result.AppendError("no process to halt");
1291       return false;
1292     }
1293 
1294     if (command.GetArgumentCount() == 0) {
1295       bool clear_thread_plans = true;
1296       Status error(process->Halt(clear_thread_plans));
1297       if (error.Success()) {
1298         result.SetStatus(eReturnStatusSuccessFinishResult);
1299       } else {
1300         result.AppendErrorWithFormat("Failed to halt process: %s\n",
1301                                      error.AsCString());
1302       }
1303     } else {
1304       result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: %s\n",
1305                                    m_cmd_name.c_str(), m_cmd_syntax.c_str());
1306     }
1307     return result.Succeeded();
1308   }
1309 };
1310 
1311 // CommandObjectProcessKill
1312 #pragma mark CommandObjectProcessKill
1313 
1314 class CommandObjectProcessKill : public CommandObjectParsed {
1315 public:
1316   CommandObjectProcessKill(CommandInterpreter &interpreter)
1317       : CommandObjectParsed(interpreter, "process kill",
1318                             "Terminate the current target process.",
1319                             "process kill",
1320                             eCommandRequiresProcess | eCommandTryTargetAPILock |
1321                                 eCommandProcessMustBeLaunched) {}
1322 
1323   ~CommandObjectProcessKill() override = default;
1324 
1325 protected:
1326   bool DoExecute(Args &command, CommandReturnObject &result) override {
1327     Process *process = m_exe_ctx.GetProcessPtr();
1328     if (process == nullptr) {
1329       result.AppendError("no process to kill");
1330       return false;
1331     }
1332 
1333     if (command.GetArgumentCount() == 0) {
1334       Status error(process->Destroy(true));
1335       if (error.Success()) {
1336         result.SetStatus(eReturnStatusSuccessFinishResult);
1337       } else {
1338         result.AppendErrorWithFormat("Failed to kill process: %s\n",
1339                                      error.AsCString());
1340       }
1341     } else {
1342       result.AppendErrorWithFormat("'%s' takes no arguments:\nUsage: %s\n",
1343                                    m_cmd_name.c_str(), m_cmd_syntax.c_str());
1344     }
1345     return result.Succeeded();
1346   }
1347 };
1348 
1349 // CommandObjectProcessSaveCore
1350 #pragma mark CommandObjectProcessSaveCore
1351 
1352 static constexpr OptionEnumValueElement g_corefile_save_style[] = {
1353     {eSaveCoreFull, "full", "Create a core file with all memory saved"},
1354     {eSaveCoreDirtyOnly, "modified-memory",
1355      "Create a corefile with only modified memory saved"},
1356     {eSaveCoreStackOnly, "stack",
1357      "Create a corefile with only stack  memory saved"}};
1358 
1359 static constexpr OptionEnumValues SaveCoreStyles() {
1360   return OptionEnumValues(g_corefile_save_style);
1361 }
1362 
1363 #define LLDB_OPTIONS_process_save_core
1364 #include "CommandOptions.inc"
1365 
1366 class CommandObjectProcessSaveCore : public CommandObjectParsed {
1367 public:
1368   CommandObjectProcessSaveCore(CommandInterpreter &interpreter)
1369       : CommandObjectParsed(
1370             interpreter, "process save-core",
1371             "Save the current process as a core file using an "
1372             "appropriate file type.",
1373             "process save-core [-s corefile-style -p plugin-name] FILE",
1374             eCommandRequiresProcess | eCommandTryTargetAPILock |
1375                 eCommandProcessMustBeLaunched) {}
1376 
1377   ~CommandObjectProcessSaveCore() override = default;
1378 
1379   Options *GetOptions() override { return &m_options; }
1380 
1381   class CommandOptions : public Options {
1382   public:
1383     CommandOptions() = default;
1384 
1385     ~CommandOptions() override = default;
1386 
1387     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1388       return llvm::makeArrayRef(g_process_save_core_options);
1389     }
1390 
1391     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1392                           ExecutionContext *execution_context) override {
1393       const int short_option = m_getopt_table[option_idx].val;
1394       Status error;
1395 
1396       switch (short_option) {
1397       case 'p':
1398         m_requested_plugin_name = option_arg.str();
1399         break;
1400       case 's':
1401         m_requested_save_core_style =
1402             (lldb::SaveCoreStyle)OptionArgParser::ToOptionEnum(
1403                 option_arg, GetDefinitions()[option_idx].enum_values,
1404                 eSaveCoreUnspecified, error);
1405         break;
1406       default:
1407         llvm_unreachable("Unimplemented option");
1408       }
1409 
1410       return {};
1411     }
1412 
1413     void OptionParsingStarting(ExecutionContext *execution_context) override {
1414       m_requested_save_core_style = eSaveCoreUnspecified;
1415       m_requested_plugin_name.clear();
1416     }
1417 
1418     // Instance variables to hold the values for command options.
1419     SaveCoreStyle m_requested_save_core_style = eSaveCoreUnspecified;
1420     std::string m_requested_plugin_name;
1421   };
1422 
1423 protected:
1424   bool DoExecute(Args &command, CommandReturnObject &result) override {
1425     ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1426     if (process_sp) {
1427       if (command.GetArgumentCount() == 1) {
1428         FileSpec output_file(command.GetArgumentAtIndex(0));
1429         SaveCoreStyle corefile_style = m_options.m_requested_save_core_style;
1430         Status error =
1431             PluginManager::SaveCore(process_sp, output_file, corefile_style,
1432                                     m_options.m_requested_plugin_name);
1433         if (error.Success()) {
1434           if (corefile_style == SaveCoreStyle::eSaveCoreDirtyOnly ||
1435               corefile_style == SaveCoreStyle::eSaveCoreStackOnly) {
1436             result.AppendMessageWithFormat(
1437                 "\nModified-memory or stack-memory only corefile "
1438                 "created.  This corefile may \n"
1439                 "not show library/framework/app binaries "
1440                 "on a different system, or when \n"
1441                 "those binaries have "
1442                 "been updated/modified. Copies are not included\n"
1443                 "in this corefile.  Use --style full to include all "
1444                 "process memory.\n");
1445           }
1446           result.SetStatus(eReturnStatusSuccessFinishResult);
1447         } else {
1448           result.AppendErrorWithFormat(
1449               "Failed to save core file for process: %s\n", error.AsCString());
1450         }
1451       } else {
1452         result.AppendErrorWithFormat("'%s' takes one arguments:\nUsage: %s\n",
1453                                      m_cmd_name.c_str(), m_cmd_syntax.c_str());
1454       }
1455     } else {
1456       result.AppendError("invalid process");
1457       return false;
1458     }
1459 
1460     return result.Succeeded();
1461   }
1462 
1463   CommandOptions m_options;
1464 };
1465 
1466 // CommandObjectProcessStatus
1467 #pragma mark CommandObjectProcessStatus
1468 #define LLDB_OPTIONS_process_status
1469 #include "CommandOptions.inc"
1470 
1471 class CommandObjectProcessStatus : public CommandObjectParsed {
1472 public:
1473   CommandObjectProcessStatus(CommandInterpreter &interpreter)
1474       : CommandObjectParsed(
1475             interpreter, "process status",
1476             "Show status and stop location for the current target process.",
1477             "process status",
1478             eCommandRequiresProcess | eCommandTryTargetAPILock) {}
1479 
1480   ~CommandObjectProcessStatus() override = default;
1481 
1482   Options *GetOptions() override { return &m_options; }
1483 
1484   class CommandOptions : public Options {
1485   public:
1486     CommandOptions() = default;
1487 
1488     ~CommandOptions() override = default;
1489 
1490     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1491                           ExecutionContext *execution_context) override {
1492       const int short_option = m_getopt_table[option_idx].val;
1493 
1494       switch (short_option) {
1495       case 'v':
1496         m_verbose = true;
1497         break;
1498       default:
1499         llvm_unreachable("Unimplemented option");
1500       }
1501 
1502       return {};
1503     }
1504 
1505     void OptionParsingStarting(ExecutionContext *execution_context) override {
1506       m_verbose = false;
1507     }
1508 
1509     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1510       return llvm::makeArrayRef(g_process_status_options);
1511     }
1512 
1513     // Instance variables to hold the values for command options.
1514     bool m_verbose = false;
1515   };
1516 
1517 protected:
1518   bool DoExecute(Args &command, CommandReturnObject &result) override {
1519     Stream &strm = result.GetOutputStream();
1520     result.SetStatus(eReturnStatusSuccessFinishNoResult);
1521 
1522     if (command.GetArgumentCount()) {
1523       result.AppendError("'process status' takes no arguments");
1524       return result.Succeeded();
1525     }
1526 
1527     // No need to check "process" for validity as eCommandRequiresProcess
1528     // ensures it is valid
1529     Process *process = m_exe_ctx.GetProcessPtr();
1530     const bool only_threads_with_stop_reason = true;
1531     const uint32_t start_frame = 0;
1532     const uint32_t num_frames = 1;
1533     const uint32_t num_frames_with_source = 1;
1534     const bool stop_format = true;
1535     process->GetStatus(strm);
1536     process->GetThreadStatus(strm, only_threads_with_stop_reason, start_frame,
1537                              num_frames, num_frames_with_source, stop_format);
1538 
1539     if (m_options.m_verbose) {
1540       addr_t code_mask = process->GetCodeAddressMask();
1541       addr_t data_mask = process->GetDataAddressMask();
1542       if (code_mask != 0) {
1543         int bits = std::bitset<64>(~code_mask).count();
1544         result.AppendMessageWithFormat(
1545             "Addressable code address mask: 0x%" PRIx64 "\n", code_mask);
1546         result.AppendMessageWithFormat(
1547             "Addressable data address mask: 0x%" PRIx64 "\n", data_mask);
1548         result.AppendMessageWithFormat(
1549             "Number of bits used in addressing (code): %d\n", bits);
1550       }
1551 
1552       PlatformSP platform_sp = process->GetTarget().GetPlatform();
1553       if (!platform_sp) {
1554         result.AppendError("Couldn'retrieve the target's platform");
1555         return result.Succeeded();
1556       }
1557 
1558       auto expected_crash_info =
1559           platform_sp->FetchExtendedCrashInformation(*process);
1560 
1561       if (!expected_crash_info) {
1562         result.AppendError(llvm::toString(expected_crash_info.takeError()));
1563         return result.Succeeded();
1564       }
1565 
1566       StructuredData::DictionarySP crash_info_sp = *expected_crash_info;
1567 
1568       if (crash_info_sp) {
1569         strm.PutCString("Extended Crash Information:\n");
1570         crash_info_sp->Dump(strm);
1571       }
1572     }
1573 
1574     return result.Succeeded();
1575   }
1576 
1577 private:
1578   CommandOptions m_options;
1579 };
1580 
1581 // CommandObjectProcessHandle
1582 #define LLDB_OPTIONS_process_handle
1583 #include "CommandOptions.inc"
1584 
1585 #pragma mark CommandObjectProcessHandle
1586 
1587 class CommandObjectProcessHandle : public CommandObjectParsed {
1588 public:
1589   class CommandOptions : public Options {
1590   public:
1591     CommandOptions() { OptionParsingStarting(nullptr); }
1592 
1593     ~CommandOptions() override = default;
1594 
1595     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1596                           ExecutionContext *execution_context) override {
1597       Status error;
1598       const int short_option = m_getopt_table[option_idx].val;
1599 
1600       switch (short_option) {
1601       case 'c':
1602         do_clear = true;
1603         break;
1604       case 'd':
1605         dummy = true;
1606         break;
1607       case 's':
1608         stop = std::string(option_arg);
1609         break;
1610       case 'n':
1611         notify = std::string(option_arg);
1612         break;
1613       case 'p':
1614         pass = std::string(option_arg);
1615         break;
1616       case 't':
1617         only_target_values = true;
1618         break;
1619       default:
1620         llvm_unreachable("Unimplemented option");
1621       }
1622       return error;
1623     }
1624 
1625     void OptionParsingStarting(ExecutionContext *execution_context) override {
1626       stop.clear();
1627       notify.clear();
1628       pass.clear();
1629       only_target_values = false;
1630       do_clear = false;
1631       dummy = false;
1632     }
1633 
1634     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1635       return llvm::makeArrayRef(g_process_handle_options);
1636     }
1637 
1638     // Instance variables to hold the values for command options.
1639 
1640     std::string stop;
1641     std::string notify;
1642     std::string pass;
1643     bool only_target_values = false;
1644     bool do_clear = false;
1645     bool dummy = false;
1646   };
1647 
1648   CommandObjectProcessHandle(CommandInterpreter &interpreter)
1649       : CommandObjectParsed(interpreter, "process handle",
1650                             "Manage LLDB handling of OS signals for the "
1651                             "current target process.  Defaults to showing "
1652                             "current policy.",
1653                             nullptr) {
1654     SetHelpLong("\nIf no signals are specified but one or more actions are, "
1655                 "and there is a live process, update them all.  If no action "
1656                 "is specified, list the current values.\n"
1657                 "If you specify actions with no target (e.g. in an init file) "
1658                 "or in a target with no process "
1659                 "the values will get copied into subsequent targets, but "
1660                 "lldb won't be able to spell-check the options since it can't "
1661                 "know which signal set will later be in force."
1662                 "\nYou can see the signal modifications held by the target"
1663                 "by passing the -t option."
1664                 "\nYou can also clear the target modification for a signal"
1665                 "by passing the -c option");
1666     CommandArgumentEntry arg;
1667     CommandArgumentData signal_arg;
1668 
1669     signal_arg.arg_type = eArgTypeUnixSignal;
1670     signal_arg.arg_repetition = eArgRepeatStar;
1671 
1672     arg.push_back(signal_arg);
1673 
1674     m_arguments.push_back(arg);
1675   }
1676 
1677   ~CommandObjectProcessHandle() override = default;
1678 
1679   Options *GetOptions() override { return &m_options; }
1680 
1681   bool VerifyCommandOptionValue(const std::string &option, int &real_value) {
1682     bool okay = true;
1683     bool success = false;
1684     bool tmp_value = OptionArgParser::ToBoolean(option, false, &success);
1685 
1686     if (success && tmp_value)
1687       real_value = 1;
1688     else if (success && !tmp_value)
1689       real_value = 0;
1690     else {
1691       // If the value isn't 'true' or 'false', it had better be 0 or 1.
1692       if (!llvm::to_integer(option, real_value))
1693         real_value = 3;
1694       if (real_value != 0 && real_value != 1)
1695         okay = false;
1696     }
1697 
1698     return okay;
1699   }
1700 
1701   void PrintSignalHeader(Stream &str) {
1702     str.Printf("NAME         PASS   STOP   NOTIFY\n");
1703     str.Printf("===========  =====  =====  ======\n");
1704   }
1705 
1706   void PrintSignal(Stream &str, int32_t signo, const char *sig_name,
1707                    const UnixSignalsSP &signals_sp) {
1708     bool stop;
1709     bool suppress;
1710     bool notify;
1711 
1712     str.Printf("%-11s  ", sig_name);
1713     if (signals_sp->GetSignalInfo(signo, suppress, stop, notify)) {
1714       bool pass = !suppress;
1715       str.Printf("%s  %s  %s", (pass ? "true " : "false"),
1716                  (stop ? "true " : "false"), (notify ? "true " : "false"));
1717     }
1718     str.Printf("\n");
1719   }
1720 
1721   void PrintSignalInformation(Stream &str, Args &signal_args,
1722                               int num_valid_signals,
1723                               const UnixSignalsSP &signals_sp) {
1724     PrintSignalHeader(str);
1725 
1726     if (num_valid_signals > 0) {
1727       size_t num_args = signal_args.GetArgumentCount();
1728       for (size_t i = 0; i < num_args; ++i) {
1729         int32_t signo = signals_sp->GetSignalNumberFromName(
1730             signal_args.GetArgumentAtIndex(i));
1731         if (signo != LLDB_INVALID_SIGNAL_NUMBER)
1732           PrintSignal(str, signo, signal_args.GetArgumentAtIndex(i),
1733                       signals_sp);
1734       }
1735     } else // Print info for ALL signals
1736     {
1737       int32_t signo = signals_sp->GetFirstSignalNumber();
1738       while (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1739         PrintSignal(str, signo, signals_sp->GetSignalAsCString(signo),
1740                     signals_sp);
1741         signo = signals_sp->GetNextSignalNumber(signo);
1742       }
1743     }
1744   }
1745 
1746 protected:
1747   bool DoExecute(Args &signal_args, CommandReturnObject &result) override {
1748     Target &target = GetSelectedOrDummyTarget();
1749 
1750     // Any signals that are being set should be added to the Target's
1751     // DummySignals so they will get applied on rerun, etc.
1752     // If we have a process, however, we can do a more accurate job of vetting
1753     // the user's options.
1754     ProcessSP process_sp = target.GetProcessSP();
1755 
1756     int stop_action = -1;   // -1 means leave the current setting alone
1757     int pass_action = -1;   // -1 means leave the current setting alone
1758     int notify_action = -1; // -1 means leave the current setting alone
1759 
1760     if (!m_options.stop.empty() &&
1761         !VerifyCommandOptionValue(m_options.stop, stop_action)) {
1762       result.AppendError("Invalid argument for command option --stop; must be "
1763                          "true or false.\n");
1764       return false;
1765     }
1766 
1767     if (!m_options.notify.empty() &&
1768         !VerifyCommandOptionValue(m_options.notify, notify_action)) {
1769       result.AppendError("Invalid argument for command option --notify; must "
1770                          "be true or false.\n");
1771       return false;
1772     }
1773 
1774     if (!m_options.pass.empty() &&
1775         !VerifyCommandOptionValue(m_options.pass, pass_action)) {
1776       result.AppendError("Invalid argument for command option --pass; must be "
1777                          "true or false.\n");
1778       return false;
1779     }
1780 
1781     bool no_actions = (stop_action == -1 && pass_action == -1
1782         && notify_action == -1);
1783     if (m_options.only_target_values && !no_actions) {
1784       result.AppendError("-t is for reporting, not setting, target values.");
1785       return false;
1786     }
1787 
1788     size_t num_args = signal_args.GetArgumentCount();
1789     UnixSignalsSP signals_sp;
1790     if (process_sp)
1791       signals_sp = process_sp->GetUnixSignals();
1792 
1793     int num_signals_set = 0;
1794 
1795     // If we were just asked to print the target values, do that here and
1796     // return:
1797     if (m_options.only_target_values) {
1798       target.PrintDummySignals(result.GetOutputStream(), signal_args);
1799       result.SetStatus(eReturnStatusSuccessFinishResult);
1800       return true;
1801     }
1802 
1803     // This handles clearing values:
1804     if (m_options.do_clear) {
1805       target.ClearDummySignals(signal_args);
1806       if (m_options.dummy)
1807         GetDummyTarget().ClearDummySignals(signal_args);
1808       result.SetStatus(eReturnStatusSuccessFinishNoResult);
1809       return true;
1810     }
1811 
1812     // This rest handles setting values:
1813     if (num_args > 0) {
1814       for (const auto &arg : signal_args) {
1815         // Do the process first.  If we have a process we can catch
1816         // invalid signal names, which we do here.
1817         if (signals_sp) {
1818           int32_t signo = signals_sp->GetSignalNumberFromName(arg.c_str());
1819           if (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1820             // Casting the actions as bools here should be okay, because
1821             // VerifyCommandOptionValue guarantees the value is either 0 or 1.
1822             if (stop_action != -1)
1823               signals_sp->SetShouldStop(signo, stop_action);
1824             if (pass_action != -1) {
1825               bool suppress = !pass_action;
1826               signals_sp->SetShouldSuppress(signo, suppress);
1827             }
1828             if (notify_action != -1)
1829               signals_sp->SetShouldNotify(signo, notify_action);
1830             ++num_signals_set;
1831           } else {
1832             result.AppendErrorWithFormat("Invalid signal name '%s'\n",
1833                                           arg.c_str());
1834             continue;
1835           }
1836         } else {
1837           // If there's no process we can't check, so we just set them all.
1838           // But since the map signal name -> signal number across all platforms
1839           // is not 1-1, we can't sensibly set signal actions by number before
1840           // we have a process.  Check that here:
1841           int32_t signo;
1842           if (llvm::to_integer(arg.c_str(), signo)) {
1843             result.AppendErrorWithFormat("Can't set signal handling by signal "
1844                                          "number with no process");
1845             return false;
1846           }
1847          num_signals_set = num_args;
1848         }
1849         auto set_lazy_bool = [] (int action) -> LazyBool {
1850           LazyBool lazy;
1851           if (action == -1)
1852             lazy = eLazyBoolCalculate;
1853           else if (action)
1854             lazy = eLazyBoolYes;
1855           else
1856             lazy = eLazyBoolNo;
1857           return lazy;
1858         };
1859 
1860         // If there were no actions, we're just listing, don't add the dummy:
1861         if (!no_actions)
1862           target.AddDummySignal(arg.ref(),
1863                                 set_lazy_bool(pass_action),
1864                                 set_lazy_bool(notify_action),
1865                                 set_lazy_bool(stop_action));
1866       }
1867     } else {
1868       // No signal specified, if any command options were specified, update ALL
1869       // signals.  But we can't do this without a process since we don't know
1870       // all the possible signals that might be valid for this target.
1871       if (((notify_action != -1) || (stop_action != -1) || (pass_action != -1))
1872           && process_sp) {
1873         if (m_interpreter.Confirm(
1874                 "Do you really want to update all the signals?", false)) {
1875           int32_t signo = signals_sp->GetFirstSignalNumber();
1876           while (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1877             if (notify_action != -1)
1878               signals_sp->SetShouldNotify(signo, notify_action);
1879             if (stop_action != -1)
1880               signals_sp->SetShouldStop(signo, stop_action);
1881             if (pass_action != -1) {
1882               bool suppress = !pass_action;
1883               signals_sp->SetShouldSuppress(signo, suppress);
1884             }
1885             signo = signals_sp->GetNextSignalNumber(signo);
1886           }
1887         }
1888       }
1889     }
1890 
1891     if (signals_sp)
1892       PrintSignalInformation(result.GetOutputStream(), signal_args,
1893                              num_signals_set, signals_sp);
1894     else
1895       target.PrintDummySignals(result.GetOutputStream(),
1896           signal_args);
1897 
1898     if (num_signals_set > 0)
1899       result.SetStatus(eReturnStatusSuccessFinishResult);
1900     else
1901       result.SetStatus(eReturnStatusFailed);
1902 
1903     return result.Succeeded();
1904   }
1905 
1906   CommandOptions m_options;
1907 };
1908 
1909 // Next are the subcommands of CommandObjectMultiwordProcessTrace
1910 
1911 // CommandObjectProcessTraceStart
1912 class CommandObjectProcessTraceStart : public CommandObjectTraceProxy {
1913 public:
1914   CommandObjectProcessTraceStart(CommandInterpreter &interpreter)
1915       : CommandObjectTraceProxy(
1916             /*live_debug_session_only*/ true, interpreter,
1917             "process trace start",
1918             "Start tracing this process with the corresponding trace "
1919             "plug-in.",
1920             "process trace start [<trace-options>]") {}
1921 
1922 protected:
1923   lldb::CommandObjectSP GetDelegateCommand(Trace &trace) override {
1924     return trace.GetProcessTraceStartCommand(m_interpreter);
1925   }
1926 };
1927 
1928 // CommandObjectProcessTraceSave
1929 #define LLDB_OPTIONS_process_trace_save
1930 #include "CommandOptions.inc"
1931 
1932 #pragma mark CommandObjectProcessTraceSave
1933 
1934 class CommandObjectProcessTraceSave : public CommandObjectParsed {
1935 public:
1936   class CommandOptions : public Options {
1937   public:
1938     CommandOptions() { OptionParsingStarting(nullptr); }
1939 
1940     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1941                           ExecutionContext *execution_context) override {
1942       Status error;
1943       const int short_option = m_getopt_table[option_idx].val;
1944 
1945       switch (short_option) {
1946 
1947       case 'd': {
1948         m_directory.SetFile(option_arg, FileSpec::Style::native);
1949         FileSystem::Instance().Resolve(m_directory);
1950         break;
1951       }
1952       default:
1953         llvm_unreachable("Unimplemented option");
1954       }
1955       return error;
1956     }
1957 
1958     void OptionParsingStarting(ExecutionContext *execution_context) override{};
1959 
1960     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1961       return llvm::makeArrayRef(g_process_trace_save_options);
1962     };
1963 
1964     FileSpec m_directory;
1965   };
1966 
1967   Options *GetOptions() override { return &m_options; }
1968   CommandObjectProcessTraceSave(CommandInterpreter &interpreter)
1969       : CommandObjectParsed(
1970             interpreter, "process trace save",
1971             "Save the trace of the current process in the specified directory. "
1972             "The directory will be created if needed. "
1973             "This will also create a file <directory>/trace.json with the main "
1974             "properties of the trace session, along with others files which "
1975             "contain the actual trace data. The trace.json file can be used "
1976             "later as input for the \"trace load\" command to load the trace "
1977             "in LLDB",
1978             "process trace save [<cmd-options>]",
1979             eCommandRequiresProcess | eCommandTryTargetAPILock |
1980                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused |
1981                 eCommandProcessMustBeTraced) {}
1982 
1983   ~CommandObjectProcessTraceSave() override = default;
1984 
1985 protected:
1986   bool DoExecute(Args &command, CommandReturnObject &result) override {
1987     ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1988 
1989     TraceSP trace_sp = process_sp->GetTarget().GetTrace();
1990 
1991     if (llvm::Error err = trace_sp->SaveLiveTraceToDisk(m_options.m_directory))
1992       result.AppendError(toString(std::move(err)));
1993     else
1994       result.SetStatus(eReturnStatusSuccessFinishResult);
1995 
1996     return result.Succeeded();
1997   }
1998 
1999   CommandOptions m_options;
2000 };
2001 
2002 // CommandObjectProcessTraceStop
2003 class CommandObjectProcessTraceStop : public CommandObjectParsed {
2004 public:
2005   CommandObjectProcessTraceStop(CommandInterpreter &interpreter)
2006       : CommandObjectParsed(interpreter, "process trace stop",
2007                             "Stop tracing this process. This does not affect "
2008                             "traces started with the "
2009                             "\"thread trace start\" command.",
2010                             "process trace stop",
2011                             eCommandRequiresProcess | eCommandTryTargetAPILock |
2012                                 eCommandProcessMustBeLaunched |
2013                                 eCommandProcessMustBePaused |
2014                                 eCommandProcessMustBeTraced) {}
2015 
2016   ~CommandObjectProcessTraceStop() override = default;
2017 
2018   bool DoExecute(Args &command, CommandReturnObject &result) override {
2019     ProcessSP process_sp = m_exe_ctx.GetProcessSP();
2020 
2021     TraceSP trace_sp = process_sp->GetTarget().GetTrace();
2022 
2023     if (llvm::Error err = trace_sp->Stop())
2024       result.AppendError(toString(std::move(err)));
2025     else
2026       result.SetStatus(eReturnStatusSuccessFinishResult);
2027 
2028     return result.Succeeded();
2029   }
2030 };
2031 
2032 // CommandObjectMultiwordProcessTrace
2033 class CommandObjectMultiwordProcessTrace : public CommandObjectMultiword {
2034 public:
2035   CommandObjectMultiwordProcessTrace(CommandInterpreter &interpreter)
2036       : CommandObjectMultiword(
2037             interpreter, "trace", "Commands for tracing the current process.",
2038             "process trace <subcommand> [<subcommand objects>]") {
2039     LoadSubCommand("save", CommandObjectSP(
2040                                new CommandObjectProcessTraceSave(interpreter)));
2041     LoadSubCommand("start", CommandObjectSP(new CommandObjectProcessTraceStart(
2042                                 interpreter)));
2043     LoadSubCommand("stop", CommandObjectSP(
2044                                new CommandObjectProcessTraceStop(interpreter)));
2045   }
2046 
2047   ~CommandObjectMultiwordProcessTrace() override = default;
2048 };
2049 
2050 // CommandObjectMultiwordProcess
2051 
2052 CommandObjectMultiwordProcess::CommandObjectMultiwordProcess(
2053     CommandInterpreter &interpreter)
2054     : CommandObjectMultiword(
2055           interpreter, "process",
2056           "Commands for interacting with processes on the current platform.",
2057           "process <subcommand> [<subcommand-options>]") {
2058   LoadSubCommand("attach",
2059                  CommandObjectSP(new CommandObjectProcessAttach(interpreter)));
2060   LoadSubCommand("launch",
2061                  CommandObjectSP(new CommandObjectProcessLaunch(interpreter)));
2062   LoadSubCommand("continue", CommandObjectSP(new CommandObjectProcessContinue(
2063                                  interpreter)));
2064   LoadSubCommand("connect",
2065                  CommandObjectSP(new CommandObjectProcessConnect(interpreter)));
2066   LoadSubCommand("detach",
2067                  CommandObjectSP(new CommandObjectProcessDetach(interpreter)));
2068   LoadSubCommand("load",
2069                  CommandObjectSP(new CommandObjectProcessLoad(interpreter)));
2070   LoadSubCommand("unload",
2071                  CommandObjectSP(new CommandObjectProcessUnload(interpreter)));
2072   LoadSubCommand("signal",
2073                  CommandObjectSP(new CommandObjectProcessSignal(interpreter)));
2074   LoadSubCommand("handle",
2075                  CommandObjectSP(new CommandObjectProcessHandle(interpreter)));
2076   LoadSubCommand("status",
2077                  CommandObjectSP(new CommandObjectProcessStatus(interpreter)));
2078   LoadSubCommand("interrupt", CommandObjectSP(new CommandObjectProcessInterrupt(
2079                                   interpreter)));
2080   LoadSubCommand("kill",
2081                  CommandObjectSP(new CommandObjectProcessKill(interpreter)));
2082   LoadSubCommand("plugin",
2083                  CommandObjectSP(new CommandObjectProcessPlugin(interpreter)));
2084   LoadSubCommand("save-core", CommandObjectSP(new CommandObjectProcessSaveCore(
2085                                   interpreter)));
2086   LoadSubCommand(
2087       "trace",
2088       CommandObjectSP(new CommandObjectMultiwordProcessTrace(interpreter)));
2089 }
2090 
2091 CommandObjectMultiwordProcess::~CommandObjectMultiwordProcess() = default;
2092