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