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