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     StreamString stream;
418     ProcessSP process_sp;
419     const auto error = target->Attach(m_options.attach_info, &stream);
420     if (error.Success()) {
421       process_sp = target->GetProcessSP();
422       if (process_sp) {
423         result.AppendMessage(stream.GetString());
424         result.SetStatus(eReturnStatusSuccessFinishNoResult);
425         result.SetDidChangeProcessState(true);
426       } else {
427         result.AppendError(
428             "no error returned from Target::Attach, and target has no process");
429       }
430     } else {
431       result.AppendErrorWithFormat("attach failed: %s\n", error.AsCString());
432     }
433 
434     if (!result.Succeeded())
435       return false;
436 
437     // Okay, we're done.  Last step is to warn if the executable module has
438     // changed:
439     char new_path[PATH_MAX];
440     ModuleSP new_exec_module_sp(target->GetExecutableModule());
441     if (!old_exec_module_sp) {
442       // We might not have a module if we attached to a raw pid...
443       if (new_exec_module_sp) {
444         new_exec_module_sp->GetFileSpec().GetPath(new_path, PATH_MAX);
445         result.AppendMessageWithFormat("Executable module set to \"%s\".\n",
446                                        new_path);
447       }
448     } else if (old_exec_module_sp->GetFileSpec() !=
449                new_exec_module_sp->GetFileSpec()) {
450       char old_path[PATH_MAX];
451 
452       old_exec_module_sp->GetFileSpec().GetPath(old_path, PATH_MAX);
453       new_exec_module_sp->GetFileSpec().GetPath(new_path, PATH_MAX);
454 
455       result.AppendWarningWithFormat(
456           "Executable module changed from \"%s\" to \"%s\".\n", old_path,
457           new_path);
458     }
459 
460     if (!old_arch_spec.IsValid()) {
461       result.AppendMessageWithFormat(
462           "Architecture set to: %s.\n",
463           target->GetArchitecture().GetTriple().getTriple().c_str());
464     } else if (!old_arch_spec.IsExactMatch(target->GetArchitecture())) {
465       result.AppendWarningWithFormat(
466           "Architecture changed from %s to %s.\n",
467           old_arch_spec.GetTriple().getTriple().c_str(),
468           target->GetArchitecture().GetTriple().getTriple().c_str());
469     }
470 
471     // This supports the use-case scenario of immediately continuing the
472     // process once attached.
473     if (m_options.attach_info.GetContinueOnceAttached()) {
474       // We have made a process but haven't told the interpreter about it yet,
475       // so CheckRequirements will fail for "process continue".  Set the override
476       // here:
477       ExecutionContext exe_ctx(process_sp);
478       m_interpreter.HandleCommand("process continue", eLazyBoolNo, exe_ctx, result);
479     }
480 
481     return result.Succeeded();
482   }
483 
484   CommandOptions m_options;
485 };
486 
487 // CommandObjectProcessContinue
488 
489 #define LLDB_OPTIONS_process_continue
490 #include "CommandOptions.inc"
491 
492 #pragma mark CommandObjectProcessContinue
493 
494 class CommandObjectProcessContinue : public CommandObjectParsed {
495 public:
496   CommandObjectProcessContinue(CommandInterpreter &interpreter)
497       : CommandObjectParsed(
498             interpreter, "process continue",
499             "Continue execution of all threads in the current process.",
500             "process continue",
501             eCommandRequiresProcess | eCommandTryTargetAPILock |
502                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
503 
504   ~CommandObjectProcessContinue() override = default;
505 
506 protected:
507   class CommandOptions : public Options {
508   public:
509     CommandOptions() {
510       // Keep default values of all options in one place: OptionParsingStarting
511       // ()
512       OptionParsingStarting(nullptr);
513     }
514 
515     ~CommandOptions() override = default;
516 
517     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
518                           ExecutionContext *exe_ctx) override {
519       Status error;
520       const int short_option = m_getopt_table[option_idx].val;
521       switch (short_option) {
522       case 'i':
523         if (option_arg.getAsInteger(0, m_ignore))
524           error.SetErrorStringWithFormat(
525               "invalid value for ignore option: \"%s\", should be a number.",
526               option_arg.str().c_str());
527         break;
528       case 'b':
529         m_run_to_bkpt_args.AppendArgument(option_arg);
530         m_any_bkpts_specified = true;
531       break;
532       default:
533         llvm_unreachable("Unimplemented option");
534       }
535       return error;
536     }
537 
538     void OptionParsingStarting(ExecutionContext *execution_context) override {
539       m_ignore = 0;
540       m_run_to_bkpt_args.Clear();
541       m_any_bkpts_specified = false;
542     }
543 
544     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
545       return llvm::makeArrayRef(g_process_continue_options);
546     }
547 
548     uint32_t m_ignore = 0;
549     Args m_run_to_bkpt_args;
550     bool m_any_bkpts_specified = false;
551   };
552 
553 
554   bool DoExecute(Args &command, CommandReturnObject &result) override {
555     Process *process = m_exe_ctx.GetProcessPtr();
556     bool synchronous_execution = m_interpreter.GetSynchronous();
557     StateType state = process->GetState();
558     if (state == eStateStopped) {
559       if (m_options.m_ignore > 0) {
560         ThreadSP sel_thread_sp(GetDefaultThread()->shared_from_this());
561         if (sel_thread_sp) {
562           StopInfoSP stop_info_sp = sel_thread_sp->GetStopInfo();
563           if (stop_info_sp &&
564               stop_info_sp->GetStopReason() == eStopReasonBreakpoint) {
565             lldb::break_id_t bp_site_id =
566                 (lldb::break_id_t)stop_info_sp->GetValue();
567             BreakpointSiteSP bp_site_sp(
568                 process->GetBreakpointSiteList().FindByID(bp_site_id));
569             if (bp_site_sp) {
570               const size_t num_owners = bp_site_sp->GetNumberOfOwners();
571               for (size_t i = 0; i < num_owners; i++) {
572                 Breakpoint &bp_ref =
573                     bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint();
574                 if (!bp_ref.IsInternal()) {
575                   bp_ref.SetIgnoreCount(m_options.m_ignore);
576                 }
577               }
578             }
579           }
580         }
581       }
582 
583       Target *target = m_exe_ctx.GetTargetPtr();
584       BreakpointIDList run_to_bkpt_ids;
585       // Don't pass an empty run_to_breakpoint list, as Verify will look for the
586       // default breakpoint.
587       if (m_options.m_run_to_bkpt_args.GetArgumentCount() > 0)
588         CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
589             m_options.m_run_to_bkpt_args, target, result, &run_to_bkpt_ids,
590             BreakpointName::Permissions::disablePerm);
591       if (!result.Succeeded()) {
592         return false;
593       }
594       result.Clear();
595       if (m_options.m_any_bkpts_specified && run_to_bkpt_ids.GetSize() == 0) {
596         result.AppendError("continue-to breakpoints did not specify any actual "
597                            "breakpoints or locations");
598         return false;
599       }
600 
601       // First figure out which breakpoints & locations were specified by the
602       // user:
603       size_t num_run_to_bkpt_ids = run_to_bkpt_ids.GetSize();
604       std::vector<break_id_t> bkpts_disabled;
605       std::vector<BreakpointID> locs_disabled;
606       if (num_run_to_bkpt_ids != 0) {
607         // Go through the ID's specified, and separate the breakpoints from are
608         // the breakpoint.location specifications since the latter require
609         // special handling.  We also figure out whether there's at least one
610         // specifier in the set that is enabled.
611         BreakpointList &bkpt_list = target->GetBreakpointList();
612         std::unordered_set<break_id_t> bkpts_seen;
613         std::unordered_set<break_id_t> bkpts_with_locs_seen;
614         BreakpointIDList with_locs;
615         bool any_enabled = false;
616 
617         for (size_t idx = 0; idx < num_run_to_bkpt_ids; idx++) {
618           BreakpointID bkpt_id = run_to_bkpt_ids.GetBreakpointIDAtIndex(idx);
619           break_id_t bp_id = bkpt_id.GetBreakpointID();
620           break_id_t loc_id = bkpt_id.GetLocationID();
621           BreakpointSP bp_sp
622               = bkpt_list.FindBreakpointByID(bp_id);
623           // Note, VerifyBreakpointOrLocationIDs checks for existence, so we
624           // don't need to do it again here.
625           if (bp_sp->IsEnabled()) {
626             if (loc_id == LLDB_INVALID_BREAK_ID) {
627               // A breakpoint (without location) was specified.  Make sure that
628               // at least one of the locations is enabled.
629               size_t num_locations = bp_sp->GetNumLocations();
630               for (size_t loc_idx = 0; loc_idx < num_locations; loc_idx++) {
631                 BreakpointLocationSP loc_sp
632                     = bp_sp->GetLocationAtIndex(loc_idx);
633                 if (loc_sp->IsEnabled()) {
634                   any_enabled = true;
635                   break;
636                 }
637               }
638             } else {
639               // A location was specified, check if it was enabled:
640               BreakpointLocationSP loc_sp = bp_sp->FindLocationByID(loc_id);
641               if (loc_sp->IsEnabled())
642                 any_enabled = true;
643             }
644 
645             // Then sort the bp & bp.loc entries for later use:
646             if (bkpt_id.GetLocationID() == LLDB_INVALID_BREAK_ID)
647               bkpts_seen.insert(bkpt_id.GetBreakpointID());
648             else {
649               bkpts_with_locs_seen.insert(bkpt_id.GetBreakpointID());
650               with_locs.AddBreakpointID(bkpt_id);
651             }
652           }
653         }
654         // Do all the error checking here so once we start disabling we don't
655         // have to back out half-way through.
656 
657         // Make sure at least one of the specified breakpoints is enabled.
658         if (!any_enabled) {
659           result.AppendError("at least one of the continue-to breakpoints must "
660                              "be enabled.");
661           return false;
662         }
663 
664         // Also, if you specify BOTH a breakpoint and one of it's locations,
665         // we flag that as an error, since it won't do what you expect, the
666         // breakpoint directive will mean "run to all locations", which is not
667         // what the location directive means...
668         for (break_id_t bp_id : bkpts_with_locs_seen) {
669           if (bkpts_seen.count(bp_id)) {
670             result.AppendErrorWithFormatv("can't specify both a breakpoint and "
671                                "one of its locations: {0}", bp_id);
672           }
673         }
674 
675         // Now go through the breakpoints in the target, disabling all the ones
676         // that the user didn't mention:
677         for (BreakpointSP bp_sp : bkpt_list.Breakpoints()) {
678           break_id_t bp_id = bp_sp->GetID();
679           // Handle the case where no locations were specified.  Note we don't
680           // have to worry about the case where a breakpoint and one of its
681           // locations are both in the lists, we've already disallowed that.
682           if (!bkpts_with_locs_seen.count(bp_id)) {
683             if (!bkpts_seen.count(bp_id) && bp_sp->IsEnabled()) {
684               bkpts_disabled.push_back(bp_id);
685               bp_sp->SetEnabled(false);
686             }
687             continue;
688           }
689           // Next, handle the case where a location was specified:
690           // Run through all the locations of this breakpoint and disable
691           // the ones that aren't on our "with locations" BreakpointID list:
692           size_t num_locations = bp_sp->GetNumLocations();
693           BreakpointID tmp_id(bp_id, LLDB_INVALID_BREAK_ID);
694           for (size_t loc_idx = 0; loc_idx < num_locations; loc_idx++) {
695             BreakpointLocationSP loc_sp = bp_sp->GetLocationAtIndex(loc_idx);
696             tmp_id.SetBreakpointLocationID(loc_idx);
697             size_t position = 0;
698             if (!with_locs.FindBreakpointID(tmp_id, &position)
699                 && loc_sp->IsEnabled()) {
700               locs_disabled.push_back(tmp_id);
701               loc_sp->SetEnabled(false);
702             }
703           }
704         }
705       }
706 
707       { // Scope for thread list mutex:
708         std::lock_guard<std::recursive_mutex> guard(
709             process->GetThreadList().GetMutex());
710         const uint32_t num_threads = process->GetThreadList().GetSize();
711 
712         // Set the actions that the threads should each take when resuming
713         for (uint32_t idx = 0; idx < num_threads; ++idx) {
714           const bool override_suspend = false;
715           process->GetThreadList().GetThreadAtIndex(idx)->SetResumeState(
716               eStateRunning, override_suspend);
717         }
718       }
719 
720       const uint32_t iohandler_id = process->GetIOHandlerID();
721 
722       StreamString stream;
723       Status error;
724       // For now we can only do -b with synchronous:
725       bool old_sync = GetDebugger().GetAsyncExecution();
726 
727       if (run_to_bkpt_ids.GetSize() != 0) {
728         GetDebugger().SetAsyncExecution(false);
729         synchronous_execution = true;
730       }
731       if (synchronous_execution)
732         error = process->ResumeSynchronous(&stream);
733       else
734         error = process->Resume();
735 
736       if (run_to_bkpt_ids.GetSize() != 0) {
737         GetDebugger().SetAsyncExecution(old_sync);
738       }
739 
740       // Now re-enable the breakpoints we disabled:
741       BreakpointList &bkpt_list = target->GetBreakpointList();
742       for (break_id_t bp_id : bkpts_disabled) {
743         BreakpointSP bp_sp = bkpt_list.FindBreakpointByID(bp_id);
744         if (bp_sp)
745           bp_sp->SetEnabled(true);
746       }
747       for (const BreakpointID &bkpt_id : locs_disabled) {
748         BreakpointSP bp_sp
749             = bkpt_list.FindBreakpointByID(bkpt_id.GetBreakpointID());
750         if (bp_sp) {
751           BreakpointLocationSP loc_sp
752               = bp_sp->FindLocationByID(bkpt_id.GetLocationID());
753           if (loc_sp)
754             loc_sp->SetEnabled(true);
755         }
756       }
757 
758       if (error.Success()) {
759         // There is a race condition where this thread will return up the call
760         // stack to the main command handler and show an (lldb) prompt before
761         // HandlePrivateEvent (from PrivateStateThread) has a chance to call
762         // PushProcessIOHandler().
763         process->SyncIOHandler(iohandler_id, std::chrono::seconds(2));
764 
765         result.AppendMessageWithFormat("Process %" PRIu64 " resuming\n",
766                                        process->GetID());
767         if (synchronous_execution) {
768           // If any state changed events had anything to say, add that to the
769           // result
770           result.AppendMessage(stream.GetString());
771 
772           result.SetDidChangeProcessState(true);
773           result.SetStatus(eReturnStatusSuccessFinishNoResult);
774         } else {
775           result.SetStatus(eReturnStatusSuccessContinuingNoResult);
776         }
777       } else {
778         result.AppendErrorWithFormat("Failed to resume process: %s.\n",
779                                      error.AsCString());
780       }
781     } else {
782       result.AppendErrorWithFormat(
783           "Process cannot be continued from its current state (%s).\n",
784           StateAsCString(state));
785     }
786     return result.Succeeded();
787   }
788 
789   Options *GetOptions() override { return &m_options; }
790 
791   CommandOptions m_options;
792 };
793 
794 // CommandObjectProcessDetach
795 #define LLDB_OPTIONS_process_detach
796 #include "CommandOptions.inc"
797 
798 #pragma mark CommandObjectProcessDetach
799 
800 class CommandObjectProcessDetach : public CommandObjectParsed {
801 public:
802   class CommandOptions : public Options {
803   public:
804     CommandOptions() { OptionParsingStarting(nullptr); }
805 
806     ~CommandOptions() override = default;
807 
808     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
809                           ExecutionContext *execution_context) override {
810       Status error;
811       const int short_option = m_getopt_table[option_idx].val;
812 
813       switch (short_option) {
814       case 's':
815         bool tmp_result;
816         bool success;
817         tmp_result = OptionArgParser::ToBoolean(option_arg, false, &success);
818         if (!success)
819           error.SetErrorStringWithFormat("invalid boolean option: \"%s\"",
820                                          option_arg.str().c_str());
821         else {
822           if (tmp_result)
823             m_keep_stopped = eLazyBoolYes;
824           else
825             m_keep_stopped = eLazyBoolNo;
826         }
827         break;
828       default:
829         llvm_unreachable("Unimplemented option");
830       }
831       return error;
832     }
833 
834     void OptionParsingStarting(ExecutionContext *execution_context) override {
835       m_keep_stopped = eLazyBoolCalculate;
836     }
837 
838     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
839       return llvm::makeArrayRef(g_process_detach_options);
840     }
841 
842     // Instance variables to hold the values for command options.
843     LazyBool m_keep_stopped;
844   };
845 
846   CommandObjectProcessDetach(CommandInterpreter &interpreter)
847       : CommandObjectParsed(interpreter, "process detach",
848                             "Detach from the current target process.",
849                             "process detach",
850                             eCommandRequiresProcess | eCommandTryTargetAPILock |
851                                 eCommandProcessMustBeLaunched) {}
852 
853   ~CommandObjectProcessDetach() override = default;
854 
855   Options *GetOptions() override { return &m_options; }
856 
857 protected:
858   bool DoExecute(Args &command, CommandReturnObject &result) override {
859     Process *process = m_exe_ctx.GetProcessPtr();
860     // FIXME: This will be a Command Option:
861     bool keep_stopped;
862     if (m_options.m_keep_stopped == eLazyBoolCalculate) {
863       // Check the process default:
864       keep_stopped = process->GetDetachKeepsStopped();
865     } else if (m_options.m_keep_stopped == eLazyBoolYes)
866       keep_stopped = true;
867     else
868       keep_stopped = false;
869 
870     Status error(process->Detach(keep_stopped));
871     if (error.Success()) {
872       result.SetStatus(eReturnStatusSuccessFinishResult);
873     } else {
874       result.AppendErrorWithFormat("Detach failed: %s\n", error.AsCString());
875       return false;
876     }
877     return result.Succeeded();
878   }
879 
880   CommandOptions m_options;
881 };
882 
883 // CommandObjectProcessConnect
884 #define LLDB_OPTIONS_process_connect
885 #include "CommandOptions.inc"
886 
887 #pragma mark CommandObjectProcessConnect
888 
889 class CommandObjectProcessConnect : public CommandObjectParsed {
890 public:
891   class CommandOptions : public Options {
892   public:
893     CommandOptions() {
894       // Keep default values of all options in one place: OptionParsingStarting
895       // ()
896       OptionParsingStarting(nullptr);
897     }
898 
899     ~CommandOptions() override = default;
900 
901     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
902                           ExecutionContext *execution_context) override {
903       Status error;
904       const int short_option = m_getopt_table[option_idx].val;
905 
906       switch (short_option) {
907       case 'p':
908         plugin_name.assign(std::string(option_arg));
909         break;
910 
911       default:
912         llvm_unreachable("Unimplemented option");
913       }
914       return error;
915     }
916 
917     void OptionParsingStarting(ExecutionContext *execution_context) override {
918       plugin_name.clear();
919     }
920 
921     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
922       return llvm::makeArrayRef(g_process_connect_options);
923     }
924 
925     // Instance variables to hold the values for command options.
926 
927     std::string plugin_name;
928   };
929 
930   CommandObjectProcessConnect(CommandInterpreter &interpreter)
931       : CommandObjectParsed(interpreter, "process connect",
932                             "Connect to a remote debug service.",
933                             "process connect <remote-url>", 0) {
934     CommandArgumentData connect_arg{eArgTypeConnectURL, eArgRepeatPlain};
935     m_arguments.push_back({connect_arg});
936   }
937 
938   ~CommandObjectProcessConnect() override = default;
939 
940   Options *GetOptions() override { return &m_options; }
941 
942 protected:
943   bool DoExecute(Args &command, CommandReturnObject &result) override {
944     if (command.GetArgumentCount() != 1) {
945       result.AppendErrorWithFormat(
946           "'%s' takes exactly one argument:\nUsage: %s\n", m_cmd_name.c_str(),
947           m_cmd_syntax.c_str());
948       return false;
949     }
950 
951     Process *process = m_exe_ctx.GetProcessPtr();
952     if (process && process->IsAlive()) {
953       result.AppendErrorWithFormat(
954           "Process %" PRIu64
955           " is currently being debugged, kill the process before connecting.\n",
956           process->GetID());
957       return false;
958     }
959 
960     const char *plugin_name = nullptr;
961     if (!m_options.plugin_name.empty())
962       plugin_name = m_options.plugin_name.c_str();
963 
964     Status error;
965     Debugger &debugger = GetDebugger();
966     PlatformSP platform_sp = m_interpreter.GetPlatform(true);
967     ProcessSP process_sp =
968         debugger.GetAsyncExecution()
969             ? platform_sp->ConnectProcess(
970                   command.GetArgumentAtIndex(0), plugin_name, debugger,
971                   debugger.GetSelectedTarget().get(), error)
972             : platform_sp->ConnectProcessSynchronous(
973                   command.GetArgumentAtIndex(0), plugin_name, debugger,
974                   result.GetOutputStream(), debugger.GetSelectedTarget().get(),
975                   error);
976     if (error.Fail() || process_sp == nullptr) {
977       result.AppendError(error.AsCString("Error connecting to the process"));
978       return false;
979     }
980     return true;
981   }
982 
983   CommandOptions m_options;
984 };
985 
986 // CommandObjectProcessPlugin
987 #pragma mark CommandObjectProcessPlugin
988 
989 class CommandObjectProcessPlugin : public CommandObjectProxy {
990 public:
991   CommandObjectProcessPlugin(CommandInterpreter &interpreter)
992       : CommandObjectProxy(
993             interpreter, "process plugin",
994             "Send a custom command to the current target process plug-in.",
995             "process plugin <args>", 0) {}
996 
997   ~CommandObjectProcessPlugin() override = default;
998 
999   CommandObject *GetProxyCommandObject() override {
1000     Process *process = m_interpreter.GetExecutionContext().GetProcessPtr();
1001     if (process)
1002       return process->GetPluginCommandObject();
1003     return nullptr;
1004   }
1005 };
1006 
1007 // CommandObjectProcessLoad
1008 #define LLDB_OPTIONS_process_load
1009 #include "CommandOptions.inc"
1010 
1011 #pragma mark CommandObjectProcessLoad
1012 
1013 class CommandObjectProcessLoad : public CommandObjectParsed {
1014 public:
1015   class CommandOptions : public Options {
1016   public:
1017     CommandOptions() {
1018       // Keep default values of all options in one place: OptionParsingStarting
1019       // ()
1020       OptionParsingStarting(nullptr);
1021     }
1022 
1023     ~CommandOptions() override = default;
1024 
1025     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1026                           ExecutionContext *execution_context) override {
1027       Status error;
1028       const int short_option = m_getopt_table[option_idx].val;
1029       switch (short_option) {
1030       case 'i':
1031         do_install = true;
1032         if (!option_arg.empty())
1033           install_path.SetFile(option_arg, FileSpec::Style::native);
1034         break;
1035       default:
1036         llvm_unreachable("Unimplemented option");
1037       }
1038       return error;
1039     }
1040 
1041     void OptionParsingStarting(ExecutionContext *execution_context) override {
1042       do_install = false;
1043       install_path.Clear();
1044     }
1045 
1046     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1047       return llvm::makeArrayRef(g_process_load_options);
1048     }
1049 
1050     // Instance variables to hold the values for command options.
1051     bool do_install;
1052     FileSpec install_path;
1053   };
1054 
1055   CommandObjectProcessLoad(CommandInterpreter &interpreter)
1056       : CommandObjectParsed(interpreter, "process load",
1057                             "Load a shared library into the current process.",
1058                             "process load <filename> [<filename> ...]",
1059                             eCommandRequiresProcess | eCommandTryTargetAPILock |
1060                                 eCommandProcessMustBeLaunched |
1061                                 eCommandProcessMustBePaused) {
1062     CommandArgumentData file_arg{eArgTypePath, eArgRepeatPlus};
1063     m_arguments.push_back({file_arg});
1064   }
1065 
1066   ~CommandObjectProcessLoad() override = default;
1067 
1068   void
1069   HandleArgumentCompletion(CompletionRequest &request,
1070                            OptionElementVector &opt_element_vector) override {
1071     if (!m_exe_ctx.HasProcessScope())
1072       return;
1073 
1074     CommandCompletions::InvokeCommonCompletionCallbacks(
1075         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
1076         request, nullptr);
1077   }
1078 
1079   Options *GetOptions() override { return &m_options; }
1080 
1081 protected:
1082   bool DoExecute(Args &command, CommandReturnObject &result) override {
1083     Process *process = m_exe_ctx.GetProcessPtr();
1084 
1085     for (auto &entry : command.entries()) {
1086       Status error;
1087       PlatformSP platform = process->GetTarget().GetPlatform();
1088       llvm::StringRef image_path = entry.ref();
1089       uint32_t image_token = LLDB_INVALID_IMAGE_TOKEN;
1090 
1091       if (!m_options.do_install) {
1092         FileSpec image_spec(image_path);
1093         platform->ResolveRemotePath(image_spec, image_spec);
1094         image_token =
1095             platform->LoadImage(process, FileSpec(), image_spec, error);
1096       } else if (m_options.install_path) {
1097         FileSpec image_spec(image_path);
1098         FileSystem::Instance().Resolve(image_spec);
1099         platform->ResolveRemotePath(m_options.install_path,
1100                                     m_options.install_path);
1101         image_token = platform->LoadImage(process, image_spec,
1102                                           m_options.install_path, error);
1103       } else {
1104         FileSpec image_spec(image_path);
1105         FileSystem::Instance().Resolve(image_spec);
1106         image_token =
1107             platform->LoadImage(process, image_spec, FileSpec(), error);
1108       }
1109 
1110       if (image_token != LLDB_INVALID_IMAGE_TOKEN) {
1111         result.AppendMessageWithFormat(
1112             "Loading \"%s\"...ok\nImage %u loaded.\n", image_path.str().c_str(),
1113             image_token);
1114         result.SetStatus(eReturnStatusSuccessFinishResult);
1115       } else {
1116         result.AppendErrorWithFormat("failed to load '%s': %s",
1117                                      image_path.str().c_str(),
1118                                      error.AsCString());
1119       }
1120     }
1121     return result.Succeeded();
1122   }
1123 
1124   CommandOptions m_options;
1125 };
1126 
1127 // CommandObjectProcessUnload
1128 #pragma mark CommandObjectProcessUnload
1129 
1130 class CommandObjectProcessUnload : public CommandObjectParsed {
1131 public:
1132   CommandObjectProcessUnload(CommandInterpreter &interpreter)
1133       : CommandObjectParsed(
1134             interpreter, "process unload",
1135             "Unload a shared library from the current process using the index "
1136             "returned by a previous call to \"process load\".",
1137             "process unload <index>",
1138             eCommandRequiresProcess | eCommandTryTargetAPILock |
1139                 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {
1140     CommandArgumentData load_idx_arg{eArgTypeUnsignedInteger, eArgRepeatPlain};
1141     m_arguments.push_back({load_idx_arg});
1142   }
1143 
1144   ~CommandObjectProcessUnload() override = default;
1145 
1146   void
1147   HandleArgumentCompletion(CompletionRequest &request,
1148                            OptionElementVector &opt_element_vector) override {
1149 
1150     if (request.GetCursorIndex() || !m_exe_ctx.HasProcessScope())
1151       return;
1152 
1153     Process *process = m_exe_ctx.GetProcessPtr();
1154 
1155     const std::vector<lldb::addr_t> &tokens = process->GetImageTokens();
1156     const size_t token_num = tokens.size();
1157     for (size_t i = 0; i < token_num; ++i) {
1158       if (tokens[i] == LLDB_INVALID_IMAGE_TOKEN)
1159         continue;
1160       request.TryCompleteCurrentArg(std::to_string(i));
1161     }
1162   }
1163 
1164 protected:
1165   bool DoExecute(Args &command, CommandReturnObject &result) override {
1166     Process *process = m_exe_ctx.GetProcessPtr();
1167 
1168     for (auto &entry : command.entries()) {
1169       uint32_t image_token;
1170       if (entry.ref().getAsInteger(0, image_token)) {
1171         result.AppendErrorWithFormat("invalid image index argument '%s'",
1172                                      entry.ref().str().c_str());
1173         break;
1174       } else {
1175         Status error(process->GetTarget().GetPlatform()->UnloadImage(
1176             process, image_token));
1177         if (error.Success()) {
1178           result.AppendMessageWithFormat(
1179               "Unloading shared library with index %u...ok\n", image_token);
1180           result.SetStatus(eReturnStatusSuccessFinishResult);
1181         } else {
1182           result.AppendErrorWithFormat("failed to unload image: %s",
1183                                        error.AsCString());
1184           break;
1185         }
1186       }
1187     }
1188     return result.Succeeded();
1189   }
1190 };
1191 
1192 // CommandObjectProcessSignal
1193 #pragma mark CommandObjectProcessSignal
1194 
1195 class CommandObjectProcessSignal : public CommandObjectParsed {
1196 public:
1197   CommandObjectProcessSignal(CommandInterpreter &interpreter)
1198       : CommandObjectParsed(
1199             interpreter, "process signal",
1200             "Send a UNIX signal to the current target process.", nullptr,
1201             eCommandRequiresProcess | eCommandTryTargetAPILock) {
1202     CommandArgumentEntry arg;
1203     CommandArgumentData signal_arg;
1204 
1205     // Define the first (and only) variant of this arg.
1206     signal_arg.arg_type = eArgTypeUnixSignal;
1207     signal_arg.arg_repetition = eArgRepeatPlain;
1208 
1209     // There is only one variant this argument could be; put it into the
1210     // argument entry.
1211     arg.push_back(signal_arg);
1212 
1213     // Push the data for the first argument into the m_arguments vector.
1214     m_arguments.push_back(arg);
1215   }
1216 
1217   ~CommandObjectProcessSignal() override = default;
1218 
1219   void
1220   HandleArgumentCompletion(CompletionRequest &request,
1221                            OptionElementVector &opt_element_vector) override {
1222     if (!m_exe_ctx.HasProcessScope() || request.GetCursorIndex() != 0)
1223       return;
1224 
1225     UnixSignalsSP signals = m_exe_ctx.GetProcessPtr()->GetUnixSignals();
1226     int signo = signals->GetFirstSignalNumber();
1227     while (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1228       request.TryCompleteCurrentArg(signals->GetSignalAsCString(signo));
1229       signo = signals->GetNextSignalNumber(signo);
1230     }
1231   }
1232 
1233 protected:
1234   bool DoExecute(Args &command, CommandReturnObject &result) override {
1235     Process *process = m_exe_ctx.GetProcessPtr();
1236 
1237     if (command.GetArgumentCount() == 1) {
1238       int signo = LLDB_INVALID_SIGNAL_NUMBER;
1239 
1240       const char *signal_name = command.GetArgumentAtIndex(0);
1241       if (::isxdigit(signal_name[0])) {
1242         if (!llvm::to_integer(signal_name, signo))
1243           signo = LLDB_INVALID_SIGNAL_NUMBER;
1244       } else
1245         signo = process->GetUnixSignals()->GetSignalNumberFromName(signal_name);
1246 
1247       if (signo == LLDB_INVALID_SIGNAL_NUMBER) {
1248         result.AppendErrorWithFormat("Invalid signal argument '%s'.\n",
1249                                      command.GetArgumentAtIndex(0));
1250       } else {
1251         Status error(process->Signal(signo));
1252         if (error.Success()) {
1253           result.SetStatus(eReturnStatusSuccessFinishResult);
1254         } else {
1255           result.AppendErrorWithFormat("Failed to send signal %i: %s\n", signo,
1256                                        error.AsCString());
1257         }
1258       }
1259     } else {
1260       result.AppendErrorWithFormat(
1261           "'%s' takes exactly one signal number argument:\nUsage: %s\n",
1262           m_cmd_name.c_str(), m_cmd_syntax.c_str());
1263     }
1264     return result.Succeeded();
1265   }
1266 };
1267 
1268 // CommandObjectProcessInterrupt
1269 #pragma mark CommandObjectProcessInterrupt
1270 
1271 class CommandObjectProcessInterrupt : public CommandObjectParsed {
1272 public:
1273   CommandObjectProcessInterrupt(CommandInterpreter &interpreter)
1274       : CommandObjectParsed(interpreter, "process interrupt",
1275                             "Interrupt the current target process.",
1276                             "process interrupt",
1277                             eCommandRequiresProcess | eCommandTryTargetAPILock |
1278                                 eCommandProcessMustBeLaunched) {}
1279 
1280   ~CommandObjectProcessInterrupt() override = default;
1281 
1282 protected:
1283   bool DoExecute(Args &command, CommandReturnObject &result) override {
1284     Process *process = m_exe_ctx.GetProcessPtr();
1285     if (process == nullptr) {
1286       result.AppendError("no process to halt");
1287       return false;
1288     }
1289 
1290     bool clear_thread_plans = true;
1291     Status error(process->Halt(clear_thread_plans));
1292     if (error.Success()) {
1293       result.SetStatus(eReturnStatusSuccessFinishResult);
1294     } else {
1295       result.AppendErrorWithFormat("Failed to halt process: %s\n",
1296                                    error.AsCString());
1297     }
1298     return result.Succeeded();
1299   }
1300 };
1301 
1302 // CommandObjectProcessKill
1303 #pragma mark CommandObjectProcessKill
1304 
1305 class CommandObjectProcessKill : public CommandObjectParsed {
1306 public:
1307   CommandObjectProcessKill(CommandInterpreter &interpreter)
1308       : CommandObjectParsed(interpreter, "process kill",
1309                             "Terminate the current target process.",
1310                             "process kill",
1311                             eCommandRequiresProcess | eCommandTryTargetAPILock |
1312                                 eCommandProcessMustBeLaunched) {}
1313 
1314   ~CommandObjectProcessKill() override = default;
1315 
1316 protected:
1317   bool DoExecute(Args &command, CommandReturnObject &result) override {
1318     Process *process = m_exe_ctx.GetProcessPtr();
1319     if (process == nullptr) {
1320       result.AppendError("no process to kill");
1321       return false;
1322     }
1323 
1324     Status error(process->Destroy(true));
1325     if (error.Success()) {
1326       result.SetStatus(eReturnStatusSuccessFinishResult);
1327     } else {
1328       result.AppendErrorWithFormat("Failed to kill process: %s\n",
1329                                    error.AsCString());
1330     }
1331     return result.Succeeded();
1332   }
1333 };
1334 
1335 // CommandObjectProcessSaveCore
1336 #pragma mark CommandObjectProcessSaveCore
1337 
1338 static constexpr OptionEnumValueElement g_corefile_save_style[] = {
1339     {eSaveCoreFull, "full", "Create a core file with all memory saved"},
1340     {eSaveCoreDirtyOnly, "modified-memory",
1341      "Create a corefile with only modified memory saved"},
1342     {eSaveCoreStackOnly, "stack",
1343      "Create a corefile with only stack  memory saved"}};
1344 
1345 static constexpr OptionEnumValues SaveCoreStyles() {
1346   return OptionEnumValues(g_corefile_save_style);
1347 }
1348 
1349 #define LLDB_OPTIONS_process_save_core
1350 #include "CommandOptions.inc"
1351 
1352 class CommandObjectProcessSaveCore : public CommandObjectParsed {
1353 public:
1354   CommandObjectProcessSaveCore(CommandInterpreter &interpreter)
1355       : CommandObjectParsed(
1356             interpreter, "process save-core",
1357             "Save the current process as a core file using an "
1358             "appropriate file type.",
1359             "process save-core [-s corefile-style -p plugin-name] FILE",
1360             eCommandRequiresProcess | eCommandTryTargetAPILock |
1361                 eCommandProcessMustBeLaunched) {
1362     CommandArgumentData file_arg{eArgTypePath, eArgRepeatPlain};
1363     m_arguments.push_back({file_arg});
1364   }
1365 
1366   ~CommandObjectProcessSaveCore() override = default;
1367 
1368   Options *GetOptions() override { return &m_options; }
1369 
1370   class CommandOptions : public Options {
1371   public:
1372     CommandOptions() = default;
1373 
1374     ~CommandOptions() override = default;
1375 
1376     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1377       return llvm::makeArrayRef(g_process_save_core_options);
1378     }
1379 
1380     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1381                           ExecutionContext *execution_context) override {
1382       const int short_option = m_getopt_table[option_idx].val;
1383       Status error;
1384 
1385       switch (short_option) {
1386       case 'p':
1387         m_requested_plugin_name = option_arg.str();
1388         break;
1389       case 's':
1390         m_requested_save_core_style =
1391             (lldb::SaveCoreStyle)OptionArgParser::ToOptionEnum(
1392                 option_arg, GetDefinitions()[option_idx].enum_values,
1393                 eSaveCoreUnspecified, error);
1394         break;
1395       default:
1396         llvm_unreachable("Unimplemented option");
1397       }
1398 
1399       return {};
1400     }
1401 
1402     void OptionParsingStarting(ExecutionContext *execution_context) override {
1403       m_requested_save_core_style = eSaveCoreUnspecified;
1404       m_requested_plugin_name.clear();
1405     }
1406 
1407     // Instance variables to hold the values for command options.
1408     SaveCoreStyle m_requested_save_core_style = eSaveCoreUnspecified;
1409     std::string m_requested_plugin_name;
1410   };
1411 
1412 protected:
1413   bool DoExecute(Args &command, CommandReturnObject &result) override {
1414     ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1415     if (process_sp) {
1416       if (command.GetArgumentCount() == 1) {
1417         FileSpec output_file(command.GetArgumentAtIndex(0));
1418         SaveCoreStyle corefile_style = m_options.m_requested_save_core_style;
1419         Status error =
1420             PluginManager::SaveCore(process_sp, output_file, corefile_style,
1421                                     m_options.m_requested_plugin_name);
1422         if (error.Success()) {
1423           if (corefile_style == SaveCoreStyle::eSaveCoreDirtyOnly ||
1424               corefile_style == SaveCoreStyle::eSaveCoreStackOnly) {
1425             result.AppendMessageWithFormat(
1426                 "\nModified-memory or stack-memory only corefile "
1427                 "created.  This corefile may \n"
1428                 "not show library/framework/app binaries "
1429                 "on a different system, or when \n"
1430                 "those binaries have "
1431                 "been updated/modified. Copies are not included\n"
1432                 "in this corefile.  Use --style full to include all "
1433                 "process memory.\n");
1434           }
1435           result.SetStatus(eReturnStatusSuccessFinishResult);
1436         } else {
1437           result.AppendErrorWithFormat(
1438               "Failed to save core file for process: %s\n", error.AsCString());
1439         }
1440       } else {
1441         result.AppendErrorWithFormat("'%s' takes one arguments:\nUsage: %s\n",
1442                                      m_cmd_name.c_str(), m_cmd_syntax.c_str());
1443       }
1444     } else {
1445       result.AppendError("invalid process");
1446       return false;
1447     }
1448 
1449     return result.Succeeded();
1450   }
1451 
1452   CommandOptions m_options;
1453 };
1454 
1455 // CommandObjectProcessStatus
1456 #pragma mark CommandObjectProcessStatus
1457 #define LLDB_OPTIONS_process_status
1458 #include "CommandOptions.inc"
1459 
1460 class CommandObjectProcessStatus : public CommandObjectParsed {
1461 public:
1462   CommandObjectProcessStatus(CommandInterpreter &interpreter)
1463       : CommandObjectParsed(
1464             interpreter, "process status",
1465             "Show status and stop location for the current target process.",
1466             "process status",
1467             eCommandRequiresProcess | eCommandTryTargetAPILock) {}
1468 
1469   ~CommandObjectProcessStatus() override = default;
1470 
1471   Options *GetOptions() override { return &m_options; }
1472 
1473   class CommandOptions : public Options {
1474   public:
1475     CommandOptions() = default;
1476 
1477     ~CommandOptions() override = default;
1478 
1479     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1480                           ExecutionContext *execution_context) override {
1481       const int short_option = m_getopt_table[option_idx].val;
1482 
1483       switch (short_option) {
1484       case 'v':
1485         m_verbose = true;
1486         break;
1487       default:
1488         llvm_unreachable("Unimplemented option");
1489       }
1490 
1491       return {};
1492     }
1493 
1494     void OptionParsingStarting(ExecutionContext *execution_context) override {
1495       m_verbose = false;
1496     }
1497 
1498     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1499       return llvm::makeArrayRef(g_process_status_options);
1500     }
1501 
1502     // Instance variables to hold the values for command options.
1503     bool m_verbose = false;
1504   };
1505 
1506 protected:
1507   bool DoExecute(Args &command, CommandReturnObject &result) override {
1508     Stream &strm = result.GetOutputStream();
1509     result.SetStatus(eReturnStatusSuccessFinishNoResult);
1510 
1511     // No need to check "process" for validity as eCommandRequiresProcess
1512     // ensures it is valid
1513     Process *process = m_exe_ctx.GetProcessPtr();
1514     const bool only_threads_with_stop_reason = true;
1515     const uint32_t start_frame = 0;
1516     const uint32_t num_frames = 1;
1517     const uint32_t num_frames_with_source = 1;
1518     const bool stop_format = true;
1519     process->GetStatus(strm);
1520     process->GetThreadStatus(strm, only_threads_with_stop_reason, start_frame,
1521                              num_frames, num_frames_with_source, stop_format);
1522 
1523     if (m_options.m_verbose) {
1524       addr_t code_mask = process->GetCodeAddressMask();
1525       addr_t data_mask = process->GetDataAddressMask();
1526       if (code_mask != 0) {
1527         int bits = std::bitset<64>(~code_mask).count();
1528         result.AppendMessageWithFormat(
1529             "Addressable code address mask: 0x%" PRIx64 "\n", code_mask);
1530         result.AppendMessageWithFormat(
1531             "Addressable data address mask: 0x%" PRIx64 "\n", data_mask);
1532         result.AppendMessageWithFormat(
1533             "Number of bits used in addressing (code): %d\n", bits);
1534       }
1535 
1536       PlatformSP platform_sp = process->GetTarget().GetPlatform();
1537       if (!platform_sp) {
1538         result.AppendError("Couldn'retrieve the target's platform");
1539         return result.Succeeded();
1540       }
1541 
1542       auto expected_crash_info =
1543           platform_sp->FetchExtendedCrashInformation(*process);
1544 
1545       if (!expected_crash_info) {
1546         result.AppendError(llvm::toString(expected_crash_info.takeError()));
1547         return result.Succeeded();
1548       }
1549 
1550       StructuredData::DictionarySP crash_info_sp = *expected_crash_info;
1551 
1552       if (crash_info_sp) {
1553         strm.PutCString("Extended Crash Information:\n");
1554         crash_info_sp->Dump(strm);
1555       }
1556     }
1557 
1558     return result.Succeeded();
1559   }
1560 
1561 private:
1562   CommandOptions m_options;
1563 };
1564 
1565 // CommandObjectProcessHandle
1566 #define LLDB_OPTIONS_process_handle
1567 #include "CommandOptions.inc"
1568 
1569 #pragma mark CommandObjectProcessHandle
1570 
1571 class CommandObjectProcessHandle : public CommandObjectParsed {
1572 public:
1573   class CommandOptions : public Options {
1574   public:
1575     CommandOptions() { OptionParsingStarting(nullptr); }
1576 
1577     ~CommandOptions() override = default;
1578 
1579     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1580                           ExecutionContext *execution_context) override {
1581       Status error;
1582       const int short_option = m_getopt_table[option_idx].val;
1583 
1584       switch (short_option) {
1585       case 'c':
1586         do_clear = true;
1587         break;
1588       case 'd':
1589         dummy = true;
1590         break;
1591       case 's':
1592         stop = std::string(option_arg);
1593         break;
1594       case 'n':
1595         notify = std::string(option_arg);
1596         break;
1597       case 'p':
1598         pass = std::string(option_arg);
1599         break;
1600       case 't':
1601         only_target_values = true;
1602         break;
1603       default:
1604         llvm_unreachable("Unimplemented option");
1605       }
1606       return error;
1607     }
1608 
1609     void OptionParsingStarting(ExecutionContext *execution_context) override {
1610       stop.clear();
1611       notify.clear();
1612       pass.clear();
1613       only_target_values = false;
1614       do_clear = false;
1615       dummy = false;
1616     }
1617 
1618     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1619       return llvm::makeArrayRef(g_process_handle_options);
1620     }
1621 
1622     // Instance variables to hold the values for command options.
1623 
1624     std::string stop;
1625     std::string notify;
1626     std::string pass;
1627     bool only_target_values = false;
1628     bool do_clear = false;
1629     bool dummy = false;
1630   };
1631 
1632   CommandObjectProcessHandle(CommandInterpreter &interpreter)
1633       : CommandObjectParsed(interpreter, "process handle",
1634                             "Manage LLDB handling of OS signals for the "
1635                             "current target process.  Defaults to showing "
1636                             "current policy.",
1637                             nullptr) {
1638     SetHelpLong("\nIf no signals are specified but one or more actions are, "
1639                 "and there is a live process, update them all.  If no action "
1640                 "is specified, list the current values.\n"
1641                 "If you specify actions with no target (e.g. in an init file) "
1642                 "or in a target with no process "
1643                 "the values will get copied into subsequent targets, but "
1644                 "lldb won't be able to spell-check the options since it can't "
1645                 "know which signal set will later be in force."
1646                 "\nYou can see the signal modifications held by the target"
1647                 "by passing the -t option."
1648                 "\nYou can also clear the target modification for a signal"
1649                 "by passing the -c option");
1650     CommandArgumentEntry arg;
1651     CommandArgumentData signal_arg;
1652 
1653     signal_arg.arg_type = eArgTypeUnixSignal;
1654     signal_arg.arg_repetition = eArgRepeatStar;
1655 
1656     arg.push_back(signal_arg);
1657 
1658     m_arguments.push_back(arg);
1659   }
1660 
1661   ~CommandObjectProcessHandle() override = default;
1662 
1663   Options *GetOptions() override { return &m_options; }
1664 
1665   bool VerifyCommandOptionValue(const std::string &option, int &real_value) {
1666     bool okay = true;
1667     bool success = false;
1668     bool tmp_value = OptionArgParser::ToBoolean(option, false, &success);
1669 
1670     if (success && tmp_value)
1671       real_value = 1;
1672     else if (success && !tmp_value)
1673       real_value = 0;
1674     else {
1675       // If the value isn't 'true' or 'false', it had better be 0 or 1.
1676       if (!llvm::to_integer(option, real_value))
1677         real_value = 3;
1678       if (real_value != 0 && real_value != 1)
1679         okay = false;
1680     }
1681 
1682     return okay;
1683   }
1684 
1685   void PrintSignalHeader(Stream &str) {
1686     str.Printf("NAME         PASS   STOP   NOTIFY\n");
1687     str.Printf("===========  =====  =====  ======\n");
1688   }
1689 
1690   void PrintSignal(Stream &str, int32_t signo, const char *sig_name,
1691                    const UnixSignalsSP &signals_sp) {
1692     bool stop;
1693     bool suppress;
1694     bool notify;
1695 
1696     str.Printf("%-11s  ", sig_name);
1697     if (signals_sp->GetSignalInfo(signo, suppress, stop, notify)) {
1698       bool pass = !suppress;
1699       str.Printf("%s  %s  %s", (pass ? "true " : "false"),
1700                  (stop ? "true " : "false"), (notify ? "true " : "false"));
1701     }
1702     str.Printf("\n");
1703   }
1704 
1705   void PrintSignalInformation(Stream &str, Args &signal_args,
1706                               int num_valid_signals,
1707                               const UnixSignalsSP &signals_sp) {
1708     PrintSignalHeader(str);
1709 
1710     if (num_valid_signals > 0) {
1711       size_t num_args = signal_args.GetArgumentCount();
1712       for (size_t i = 0; i < num_args; ++i) {
1713         int32_t signo = signals_sp->GetSignalNumberFromName(
1714             signal_args.GetArgumentAtIndex(i));
1715         if (signo != LLDB_INVALID_SIGNAL_NUMBER)
1716           PrintSignal(str, signo, signal_args.GetArgumentAtIndex(i),
1717                       signals_sp);
1718       }
1719     } else // Print info for ALL signals
1720     {
1721       int32_t signo = signals_sp->GetFirstSignalNumber();
1722       while (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1723         PrintSignal(str, signo, signals_sp->GetSignalAsCString(signo),
1724                     signals_sp);
1725         signo = signals_sp->GetNextSignalNumber(signo);
1726       }
1727     }
1728   }
1729 
1730 protected:
1731   bool DoExecute(Args &signal_args, CommandReturnObject &result) override {
1732     Target &target = GetSelectedOrDummyTarget();
1733 
1734     // Any signals that are being set should be added to the Target's
1735     // DummySignals so they will get applied on rerun, etc.
1736     // If we have a process, however, we can do a more accurate job of vetting
1737     // the user's options.
1738     ProcessSP process_sp = target.GetProcessSP();
1739 
1740     int stop_action = -1;   // -1 means leave the current setting alone
1741     int pass_action = -1;   // -1 means leave the current setting alone
1742     int notify_action = -1; // -1 means leave the current setting alone
1743 
1744     if (!m_options.stop.empty() &&
1745         !VerifyCommandOptionValue(m_options.stop, stop_action)) {
1746       result.AppendError("Invalid argument for command option --stop; must be "
1747                          "true or false.\n");
1748       return false;
1749     }
1750 
1751     if (!m_options.notify.empty() &&
1752         !VerifyCommandOptionValue(m_options.notify, notify_action)) {
1753       result.AppendError("Invalid argument for command option --notify; must "
1754                          "be true or false.\n");
1755       return false;
1756     }
1757 
1758     if (!m_options.pass.empty() &&
1759         !VerifyCommandOptionValue(m_options.pass, pass_action)) {
1760       result.AppendError("Invalid argument for command option --pass; must be "
1761                          "true or false.\n");
1762       return false;
1763     }
1764 
1765     bool no_actions = (stop_action == -1 && pass_action == -1
1766         && notify_action == -1);
1767     if (m_options.only_target_values && !no_actions) {
1768       result.AppendError("-t is for reporting, not setting, target values.");
1769       return false;
1770     }
1771 
1772     size_t num_args = signal_args.GetArgumentCount();
1773     UnixSignalsSP signals_sp;
1774     if (process_sp)
1775       signals_sp = process_sp->GetUnixSignals();
1776 
1777     int num_signals_set = 0;
1778 
1779     // If we were just asked to print the target values, do that here and
1780     // return:
1781     if (m_options.only_target_values) {
1782       target.PrintDummySignals(result.GetOutputStream(), signal_args);
1783       result.SetStatus(eReturnStatusSuccessFinishResult);
1784       return true;
1785     }
1786 
1787     // This handles clearing values:
1788     if (m_options.do_clear) {
1789       target.ClearDummySignals(signal_args);
1790       if (m_options.dummy)
1791         GetDummyTarget().ClearDummySignals(signal_args);
1792       result.SetStatus(eReturnStatusSuccessFinishNoResult);
1793       return true;
1794     }
1795 
1796     // This rest handles setting values:
1797     if (num_args > 0) {
1798       for (const auto &arg : signal_args) {
1799         // Do the process first.  If we have a process we can catch
1800         // invalid signal names, which we do here.
1801         if (signals_sp) {
1802           int32_t signo = signals_sp->GetSignalNumberFromName(arg.c_str());
1803           if (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1804             // Casting the actions as bools here should be okay, because
1805             // VerifyCommandOptionValue guarantees the value is either 0 or 1.
1806             if (stop_action != -1)
1807               signals_sp->SetShouldStop(signo, stop_action);
1808             if (pass_action != -1) {
1809               bool suppress = !pass_action;
1810               signals_sp->SetShouldSuppress(signo, suppress);
1811             }
1812             if (notify_action != -1)
1813               signals_sp->SetShouldNotify(signo, notify_action);
1814             ++num_signals_set;
1815           } else {
1816             result.AppendErrorWithFormat("Invalid signal name '%s'\n",
1817                                           arg.c_str());
1818             continue;
1819           }
1820         } else {
1821           // If there's no process we can't check, so we just set them all.
1822           // But since the map signal name -> signal number across all platforms
1823           // is not 1-1, we can't sensibly set signal actions by number before
1824           // we have a process.  Check that here:
1825           int32_t signo;
1826           if (llvm::to_integer(arg.c_str(), signo)) {
1827             result.AppendErrorWithFormat("Can't set signal handling by signal "
1828                                          "number with no process");
1829             return false;
1830           }
1831          num_signals_set = num_args;
1832         }
1833         auto set_lazy_bool = [] (int action) -> LazyBool {
1834           LazyBool lazy;
1835           if (action == -1)
1836             lazy = eLazyBoolCalculate;
1837           else if (action)
1838             lazy = eLazyBoolYes;
1839           else
1840             lazy = eLazyBoolNo;
1841           return lazy;
1842         };
1843 
1844         // If there were no actions, we're just listing, don't add the dummy:
1845         if (!no_actions)
1846           target.AddDummySignal(arg.ref(),
1847                                 set_lazy_bool(pass_action),
1848                                 set_lazy_bool(notify_action),
1849                                 set_lazy_bool(stop_action));
1850       }
1851     } else {
1852       // No signal specified, if any command options were specified, update ALL
1853       // signals.  But we can't do this without a process since we don't know
1854       // all the possible signals that might be valid for this target.
1855       if (((notify_action != -1) || (stop_action != -1) || (pass_action != -1))
1856           && process_sp) {
1857         if (m_interpreter.Confirm(
1858                 "Do you really want to update all the signals?", false)) {
1859           int32_t signo = signals_sp->GetFirstSignalNumber();
1860           while (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1861             if (notify_action != -1)
1862               signals_sp->SetShouldNotify(signo, notify_action);
1863             if (stop_action != -1)
1864               signals_sp->SetShouldStop(signo, stop_action);
1865             if (pass_action != -1) {
1866               bool suppress = !pass_action;
1867               signals_sp->SetShouldSuppress(signo, suppress);
1868             }
1869             signo = signals_sp->GetNextSignalNumber(signo);
1870           }
1871         }
1872       }
1873     }
1874 
1875     if (signals_sp)
1876       PrintSignalInformation(result.GetOutputStream(), signal_args,
1877                              num_signals_set, signals_sp);
1878     else
1879       target.PrintDummySignals(result.GetOutputStream(),
1880           signal_args);
1881 
1882     if (num_signals_set > 0)
1883       result.SetStatus(eReturnStatusSuccessFinishResult);
1884     else
1885       result.SetStatus(eReturnStatusFailed);
1886 
1887     return result.Succeeded();
1888   }
1889 
1890   CommandOptions m_options;
1891 };
1892 
1893 // Next are the subcommands of CommandObjectMultiwordProcessTrace
1894 
1895 // CommandObjectProcessTraceStart
1896 class CommandObjectProcessTraceStart : public CommandObjectTraceProxy {
1897 public:
1898   CommandObjectProcessTraceStart(CommandInterpreter &interpreter)
1899       : CommandObjectTraceProxy(
1900             /*live_debug_session_only*/ true, interpreter,
1901             "process trace start",
1902             "Start tracing this process with the corresponding trace "
1903             "plug-in.",
1904             "process trace start [<trace-options>]") {}
1905 
1906 protected:
1907   lldb::CommandObjectSP GetDelegateCommand(Trace &trace) override {
1908     return trace.GetProcessTraceStartCommand(m_interpreter);
1909   }
1910 };
1911 
1912 // CommandObjectProcessTraceStop
1913 class CommandObjectProcessTraceStop : public CommandObjectParsed {
1914 public:
1915   CommandObjectProcessTraceStop(CommandInterpreter &interpreter)
1916       : CommandObjectParsed(interpreter, "process trace stop",
1917                             "Stop tracing this process. This does not affect "
1918                             "traces started with the "
1919                             "\"thread trace start\" command.",
1920                             "process trace stop",
1921                             eCommandRequiresProcess | eCommandTryTargetAPILock |
1922                                 eCommandProcessMustBeLaunched |
1923                                 eCommandProcessMustBePaused |
1924                                 eCommandProcessMustBeTraced) {}
1925 
1926   ~CommandObjectProcessTraceStop() override = default;
1927 
1928   bool DoExecute(Args &command, CommandReturnObject &result) override {
1929     ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1930 
1931     TraceSP trace_sp = process_sp->GetTarget().GetTrace();
1932 
1933     if (llvm::Error err = trace_sp->Stop())
1934       result.AppendError(toString(std::move(err)));
1935     else
1936       result.SetStatus(eReturnStatusSuccessFinishResult);
1937 
1938     return result.Succeeded();
1939   }
1940 };
1941 
1942 // CommandObjectMultiwordProcessTrace
1943 class CommandObjectMultiwordProcessTrace : public CommandObjectMultiword {
1944 public:
1945   CommandObjectMultiwordProcessTrace(CommandInterpreter &interpreter)
1946       : CommandObjectMultiword(
1947             interpreter, "trace", "Commands for tracing the current process.",
1948             "process trace <subcommand> [<subcommand objects>]") {
1949     LoadSubCommand("start", CommandObjectSP(new CommandObjectProcessTraceStart(
1950                                 interpreter)));
1951     LoadSubCommand("stop", CommandObjectSP(
1952                                new CommandObjectProcessTraceStop(interpreter)));
1953   }
1954 
1955   ~CommandObjectMultiwordProcessTrace() override = default;
1956 };
1957 
1958 // CommandObjectMultiwordProcess
1959 
1960 CommandObjectMultiwordProcess::CommandObjectMultiwordProcess(
1961     CommandInterpreter &interpreter)
1962     : CommandObjectMultiword(
1963           interpreter, "process",
1964           "Commands for interacting with processes on the current platform.",
1965           "process <subcommand> [<subcommand-options>]") {
1966   LoadSubCommand("attach",
1967                  CommandObjectSP(new CommandObjectProcessAttach(interpreter)));
1968   LoadSubCommand("launch",
1969                  CommandObjectSP(new CommandObjectProcessLaunch(interpreter)));
1970   LoadSubCommand("continue", CommandObjectSP(new CommandObjectProcessContinue(
1971                                  interpreter)));
1972   LoadSubCommand("connect",
1973                  CommandObjectSP(new CommandObjectProcessConnect(interpreter)));
1974   LoadSubCommand("detach",
1975                  CommandObjectSP(new CommandObjectProcessDetach(interpreter)));
1976   LoadSubCommand("load",
1977                  CommandObjectSP(new CommandObjectProcessLoad(interpreter)));
1978   LoadSubCommand("unload",
1979                  CommandObjectSP(new CommandObjectProcessUnload(interpreter)));
1980   LoadSubCommand("signal",
1981                  CommandObjectSP(new CommandObjectProcessSignal(interpreter)));
1982   LoadSubCommand("handle",
1983                  CommandObjectSP(new CommandObjectProcessHandle(interpreter)));
1984   LoadSubCommand("status",
1985                  CommandObjectSP(new CommandObjectProcessStatus(interpreter)));
1986   LoadSubCommand("interrupt", CommandObjectSP(new CommandObjectProcessInterrupt(
1987                                   interpreter)));
1988   LoadSubCommand("kill",
1989                  CommandObjectSP(new CommandObjectProcessKill(interpreter)));
1990   LoadSubCommand("plugin",
1991                  CommandObjectSP(new CommandObjectProcessPlugin(interpreter)));
1992   LoadSubCommand("save-core", CommandObjectSP(new CommandObjectProcessSaveCore(
1993                                   interpreter)));
1994   LoadSubCommand(
1995       "trace",
1996       CommandObjectSP(new CommandObjectMultiwordProcessTrace(interpreter)));
1997 }
1998 
1999 CommandObjectMultiwordProcess::~CommandObjectMultiwordProcess() = default;
2000