[RISCV][VLOPT] Add vector narrowing integer right shift instructions to isSupportedIn...
[llvm-project.git] / lldb / source / Commands / CommandObjectProcess.cpp
blob7444e46aa729e78eb0c3493906bb61dbb4b5a809
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 //===----------------------------------------------------------------------===//
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"
39 #include "llvm/ADT/ScopeExit.h"
41 #include <bitset>
42 #include <optional>
44 using namespace lldb;
45 using namespace lldb_private;
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) {}
56 ~CommandObjectProcessLaunchOrAttach() override = default;
58 protected:
59 bool StopProcessIfNecessary(Process *process, StateType &state,
60 CommandReturnObject &result) {
61 state = eStateInvalid;
62 if (process) {
63 state = process->GetState();
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);
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());
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());
108 return result.Succeeded();
111 std::string m_new_process_action;
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"),
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();
130 AddSimpleArgumentList(eArgTypeRunArgs, eArgRepeatOptional);
133 ~CommandObjectProcessLaunch() override = default;
135 Options *GetOptions() override { return &m_all_options; }
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("");
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();
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;
161 StateType state = eStateInvalid;
163 if (!StopProcessIfNecessary(m_exe_ctx.GetProcessPtr(), state, result))
164 return;
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();
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);
190 if (disable_aslr)
191 m_options.launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
192 else
193 m_options.launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
195 if (target->GetInheritTCC())
196 m_options.launch_info.GetFlags().Set(eLaunchFlagInheritTCCFromParent);
198 if (target->GetDetachOnError())
199 m_options.launch_info.GetFlags().Set(eLaunchFlagDetachOnError);
201 if (target->GetDisableSTDIO())
202 m_options.launch_info.GetFlags().Set(eLaunchFlagDisableSTDIO);
204 if (!m_options.launch_info.GetWorkingDirectory()) {
205 if (llvm::StringRef wd = target->GetLaunchWorkingDirectory();
206 !wd.empty()) {
207 m_options.launch_info.SetWorkingDirectory(FileSpec(wd));
211 // Merge the launch info environment with the target environment.
212 Environment target_env = target->GetEnvironment();
213 m_options.launch_info.GetEnvironment().insert(target_env.begin(),
214 target_env.end());
216 llvm::StringRef target_settings_argv0 = target->GetArg0();
218 if (!target_settings_argv0.empty()) {
219 m_options.launch_info.GetArguments().AppendArgument(
220 target_settings_argv0);
221 if (exe_module_sp)
222 m_options.launch_info.SetExecutableFile(
223 exe_module_sp->GetPlatformFileSpec(), false);
224 else
225 m_options.launch_info.SetExecutableFile(target->GetProcessLaunchInfo().GetExecutableFile(), false);
226 } else {
227 if (exe_module_sp)
228 m_options.launch_info.SetExecutableFile(
229 exe_module_sp->GetPlatformFileSpec(), true);
230 else
231 m_options.launch_info.SetExecutableFile(target->GetProcessLaunchInfo().GetExecutableFile(), true);
234 if (launch_args.GetArgumentCount() == 0) {
235 m_options.launch_info.GetArguments().AppendArguments(
236 target->GetProcessLaunchInfo().GetArguments());
237 } else {
238 m_options.launch_info.GetArguments().AppendArguments(launch_args);
239 // Save the arguments for subsequent runs in the current target.
240 target->SetRunArguments(launch_args);
243 StreamString stream;
244 Status error = target->Launch(m_options.launch_info, &stream);
246 if (error.Success()) {
247 ProcessSP process_sp(target->GetProcessSP());
248 if (process_sp) {
249 // There is a race condition where this thread will return up the call
250 // stack to the main command handler and show an (lldb) prompt before
251 // HandlePrivateEvent (from PrivateStateThread) has a chance to call
252 // PushProcessIOHandler().
253 process_sp->SyncIOHandler(0, std::chrono::seconds(2));
255 // If we didn't have a local executable, then we wouldn't have had an
256 // executable module before launch.
257 if (!exe_module_sp)
258 exe_module_sp = target->GetExecutableModule();
259 if (!exe_module_sp) {
260 result.AppendWarning("Could not get executable module after launch.");
261 } else {
263 const char *archname =
264 exe_module_sp->GetArchitecture().GetArchitectureName();
265 result.AppendMessageWithFormat(
266 "Process %" PRIu64 " launched: '%s' (%s)\n", process_sp->GetID(),
267 exe_module_sp->GetFileSpec().GetPath().c_str(), archname);
269 result.SetStatus(eReturnStatusSuccessFinishResult);
270 // This message will refer to an event that happened after the process
271 // launched.
272 llvm::StringRef data = stream.GetString();
273 if (!data.empty())
274 result.AppendMessage(data);
275 result.SetDidChangeProcessState(true);
276 } else {
277 result.AppendError(
278 "no error returned from Target::Launch, and target has no process");
280 } else {
281 result.AppendError(error.AsCString());
285 CommandOptionsProcessLaunch m_options;
286 OptionGroupPythonClassWithDict m_class_options;
287 OptionGroupOptions m_all_options;
290 #define LLDB_OPTIONS_process_attach
291 #include "CommandOptions.inc"
293 #pragma mark CommandObjectProcessAttach
294 class CommandObjectProcessAttach : public CommandObjectProcessLaunchOrAttach {
295 public:
296 CommandObjectProcessAttach(CommandInterpreter &interpreter)
297 : CommandObjectProcessLaunchOrAttach(
298 interpreter, "process attach", "Attach to a process.",
299 "process attach <cmd-options>", 0, "attach"),
300 m_class_options("scripted process", true, 'C', 'k', 'v', 0) {
301 m_all_options.Append(&m_options);
302 m_all_options.Append(&m_class_options, LLDB_OPT_SET_1 | LLDB_OPT_SET_2,
303 LLDB_OPT_SET_ALL);
304 m_all_options.Finalize();
307 ~CommandObjectProcessAttach() override = default;
309 Options *GetOptions() override { return &m_all_options; }
311 protected:
312 void DoExecute(Args &command, CommandReturnObject &result) override {
313 PlatformSP platform_sp(
314 GetDebugger().GetPlatformList().GetSelectedPlatform());
316 Target *target = GetDebugger().GetSelectedTarget().get();
317 // N.B. The attach should be synchronous. It doesn't help much to get the
318 // prompt back between initiating the attach and the target actually
319 // stopping. So even if the interpreter is set to be asynchronous, we wait
320 // for the stop ourselves here.
322 StateType state = eStateInvalid;
323 Process *process = m_exe_ctx.GetProcessPtr();
325 if (!StopProcessIfNecessary(process, state, result))
326 return;
328 if (target == nullptr) {
329 // If there isn't a current target create one.
330 TargetSP new_target_sp;
331 Status error;
333 error = GetDebugger().GetTargetList().CreateTarget(
334 GetDebugger(), "", "", eLoadDependentsNo,
335 nullptr, // No platform options
336 new_target_sp);
337 target = new_target_sp.get();
338 if (target == nullptr || error.Fail()) {
339 result.AppendError(error.AsCString("Error creating target"));
340 return;
344 if (!m_class_options.GetName().empty()) {
345 m_options.attach_info.SetProcessPluginName("ScriptedProcess");
346 ScriptedMetadataSP metadata_sp = std::make_shared<ScriptedMetadata>(
347 m_class_options.GetName(), m_class_options.GetStructuredData());
348 m_options.attach_info.SetScriptedMetadata(metadata_sp);
351 // Record the old executable module, we want to issue a warning if the
352 // process of attaching changed the current executable (like somebody said
353 // "file foo" then attached to a PID whose executable was bar.)
355 ModuleSP old_exec_module_sp = target->GetExecutableModule();
356 ArchSpec old_arch_spec = target->GetArchitecture();
358 StreamString stream;
359 ProcessSP process_sp;
360 const auto error = target->Attach(m_options.attach_info, &stream);
361 if (error.Success()) {
362 process_sp = target->GetProcessSP();
363 if (process_sp) {
364 result.AppendMessage(stream.GetString());
365 result.SetStatus(eReturnStatusSuccessFinishNoResult);
366 result.SetDidChangeProcessState(true);
367 } else {
368 result.AppendError(
369 "no error returned from Target::Attach, and target has no process");
371 } else {
372 result.AppendErrorWithFormat("attach failed: %s\n", error.AsCString());
375 if (!result.Succeeded())
376 return;
378 // Okay, we're done. Last step is to warn if the executable module has
379 // changed:
380 ModuleSP new_exec_module_sp(target->GetExecutableModule());
381 if (!old_exec_module_sp) {
382 // We might not have a module if we attached to a raw pid...
383 if (new_exec_module_sp) {
384 result.AppendMessageWithFormat(
385 "Executable binary set to \"%s\".\n",
386 new_exec_module_sp->GetFileSpec().GetPath().c_str());
388 } else if (!new_exec_module_sp) {
389 result.AppendWarningWithFormat("No executable binary.");
390 } else if (old_exec_module_sp->GetFileSpec() !=
391 new_exec_module_sp->GetFileSpec()) {
393 result.AppendWarningWithFormat(
394 "Executable binary changed from \"%s\" to \"%s\".\n",
395 old_exec_module_sp->GetFileSpec().GetPath().c_str(),
396 new_exec_module_sp->GetFileSpec().GetPath().c_str());
399 if (!old_arch_spec.IsValid()) {
400 result.AppendMessageWithFormat(
401 "Architecture set to: %s.\n",
402 target->GetArchitecture().GetTriple().getTriple().c_str());
403 } else if (!old_arch_spec.IsExactMatch(target->GetArchitecture())) {
404 result.AppendWarningWithFormat(
405 "Architecture changed from %s to %s.\n",
406 old_arch_spec.GetTriple().getTriple().c_str(),
407 target->GetArchitecture().GetTriple().getTriple().c_str());
410 // This supports the use-case scenario of immediately continuing the
411 // process once attached.
412 if (m_options.attach_info.GetContinueOnceAttached()) {
413 // We have made a process but haven't told the interpreter about it yet,
414 // so CheckRequirements will fail for "process continue". Set the override
415 // here:
416 ExecutionContext exe_ctx(process_sp);
417 m_interpreter.HandleCommand("process continue", eLazyBoolNo, exe_ctx, result);
421 CommandOptionsProcessAttach m_options;
422 OptionGroupPythonClassWithDict m_class_options;
423 OptionGroupOptions m_all_options;
426 // CommandObjectProcessContinue
428 #define LLDB_OPTIONS_process_continue
429 #include "CommandOptions.inc"
431 #pragma mark CommandObjectProcessContinue
433 class CommandObjectProcessContinue : public CommandObjectParsed {
434 public:
435 CommandObjectProcessContinue(CommandInterpreter &interpreter)
436 : CommandObjectParsed(
437 interpreter, "process continue",
438 "Continue execution of all threads in the current process.",
439 "process continue",
440 eCommandRequiresProcess | eCommandTryTargetAPILock |
441 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
443 ~CommandObjectProcessContinue() override = default;
445 protected:
446 class CommandOptions : public Options {
447 public:
448 CommandOptions() {
449 // Keep default values of all options in one place: OptionParsingStarting
450 // ()
451 OptionParsingStarting(nullptr);
454 ~CommandOptions() override = default;
456 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
457 ExecutionContext *exe_ctx) override {
458 Status error;
459 const int short_option = m_getopt_table[option_idx].val;
460 switch (short_option) {
461 case 'i':
462 if (option_arg.getAsInteger(0, m_ignore))
463 error = Status::FromErrorStringWithFormat(
464 "invalid value for ignore option: \"%s\", should be a number.",
465 option_arg.str().c_str());
466 break;
467 case 'b':
468 m_run_to_bkpt_args.AppendArgument(option_arg);
469 m_any_bkpts_specified = true;
470 break;
471 default:
472 llvm_unreachable("Unimplemented option");
474 return error;
477 void OptionParsingStarting(ExecutionContext *execution_context) override {
478 m_ignore = 0;
479 m_run_to_bkpt_args.Clear();
480 m_any_bkpts_specified = false;
483 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
484 return llvm::ArrayRef(g_process_continue_options);
487 uint32_t m_ignore = 0;
488 Args m_run_to_bkpt_args;
489 bool m_any_bkpts_specified = false;
492 void DoExecute(Args &command, CommandReturnObject &result) override {
493 Process *process = m_exe_ctx.GetProcessPtr();
494 bool synchronous_execution = m_interpreter.GetSynchronous();
495 StateType state = process->GetState();
496 if (state == eStateStopped) {
497 if (m_options.m_ignore > 0) {
498 ThreadSP sel_thread_sp(GetDefaultThread()->shared_from_this());
499 if (sel_thread_sp) {
500 StopInfoSP stop_info_sp = sel_thread_sp->GetStopInfo();
501 if (stop_info_sp &&
502 stop_info_sp->GetStopReason() == eStopReasonBreakpoint) {
503 lldb::break_id_t bp_site_id =
504 (lldb::break_id_t)stop_info_sp->GetValue();
505 BreakpointSiteSP bp_site_sp(
506 process->GetBreakpointSiteList().FindByID(bp_site_id));
507 if (bp_site_sp) {
508 const size_t num_owners = bp_site_sp->GetNumberOfConstituents();
509 for (size_t i = 0; i < num_owners; i++) {
510 Breakpoint &bp_ref =
511 bp_site_sp->GetConstituentAtIndex(i)->GetBreakpoint();
512 if (!bp_ref.IsInternal()) {
513 bp_ref.SetIgnoreCount(m_options.m_ignore);
521 Target &target = GetTarget();
522 BreakpointIDList run_to_bkpt_ids;
523 // Don't pass an empty run_to_breakpoint list, as Verify will look for the
524 // default breakpoint.
525 if (m_options.m_run_to_bkpt_args.GetArgumentCount() > 0)
526 CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
527 m_options.m_run_to_bkpt_args, target, result, &run_to_bkpt_ids,
528 BreakpointName::Permissions::disablePerm);
529 if (!result.Succeeded()) {
530 return;
532 result.Clear();
533 if (m_options.m_any_bkpts_specified && run_to_bkpt_ids.GetSize() == 0) {
534 result.AppendError("continue-to breakpoints did not specify any actual "
535 "breakpoints or locations");
536 return;
539 // First figure out which breakpoints & locations were specified by the
540 // user:
541 size_t num_run_to_bkpt_ids = run_to_bkpt_ids.GetSize();
542 std::vector<break_id_t> bkpts_disabled;
543 std::vector<BreakpointID> locs_disabled;
544 if (num_run_to_bkpt_ids != 0) {
545 // Go through the ID's specified, and separate the breakpoints from are
546 // the breakpoint.location specifications since the latter require
547 // special handling. We also figure out whether there's at least one
548 // specifier in the set that is enabled.
549 BreakpointList &bkpt_list = target.GetBreakpointList();
550 std::unordered_set<break_id_t> bkpts_seen;
551 std::unordered_set<break_id_t> bkpts_with_locs_seen;
552 BreakpointIDList with_locs;
553 bool any_enabled = false;
555 for (size_t idx = 0; idx < num_run_to_bkpt_ids; idx++) {
556 BreakpointID bkpt_id = run_to_bkpt_ids.GetBreakpointIDAtIndex(idx);
557 break_id_t bp_id = bkpt_id.GetBreakpointID();
558 break_id_t loc_id = bkpt_id.GetLocationID();
559 BreakpointSP bp_sp
560 = bkpt_list.FindBreakpointByID(bp_id);
561 // Note, VerifyBreakpointOrLocationIDs checks for existence, so we
562 // don't need to do it again here.
563 if (bp_sp->IsEnabled()) {
564 if (loc_id == LLDB_INVALID_BREAK_ID) {
565 // A breakpoint (without location) was specified. Make sure that
566 // at least one of the locations is enabled.
567 size_t num_locations = bp_sp->GetNumLocations();
568 for (size_t loc_idx = 0; loc_idx < num_locations; loc_idx++) {
569 BreakpointLocationSP loc_sp
570 = bp_sp->GetLocationAtIndex(loc_idx);
571 if (loc_sp->IsEnabled()) {
572 any_enabled = true;
573 break;
576 } else {
577 // A location was specified, check if it was enabled:
578 BreakpointLocationSP loc_sp = bp_sp->FindLocationByID(loc_id);
579 if (loc_sp->IsEnabled())
580 any_enabled = true;
583 // Then sort the bp & bp.loc entries for later use:
584 if (bkpt_id.GetLocationID() == LLDB_INVALID_BREAK_ID)
585 bkpts_seen.insert(bkpt_id.GetBreakpointID());
586 else {
587 bkpts_with_locs_seen.insert(bkpt_id.GetBreakpointID());
588 with_locs.AddBreakpointID(bkpt_id);
592 // Do all the error checking here so once we start disabling we don't
593 // have to back out half-way through.
595 // Make sure at least one of the specified breakpoints is enabled.
596 if (!any_enabled) {
597 result.AppendError("at least one of the continue-to breakpoints must "
598 "be enabled.");
599 return;
602 // Also, if you specify BOTH a breakpoint and one of it's locations,
603 // we flag that as an error, since it won't do what you expect, the
604 // breakpoint directive will mean "run to all locations", which is not
605 // what the location directive means...
606 for (break_id_t bp_id : bkpts_with_locs_seen) {
607 if (bkpts_seen.count(bp_id)) {
608 result.AppendErrorWithFormatv("can't specify both a breakpoint and "
609 "one of its locations: {0}", bp_id);
613 // Now go through the breakpoints in the target, disabling all the ones
614 // that the user didn't mention:
615 for (BreakpointSP bp_sp : bkpt_list.Breakpoints()) {
616 break_id_t bp_id = bp_sp->GetID();
617 // Handle the case where no locations were specified. Note we don't
618 // have to worry about the case where a breakpoint and one of its
619 // locations are both in the lists, we've already disallowed that.
620 if (!bkpts_with_locs_seen.count(bp_id)) {
621 if (!bkpts_seen.count(bp_id) && bp_sp->IsEnabled()) {
622 bkpts_disabled.push_back(bp_id);
623 bp_sp->SetEnabled(false);
625 continue;
627 // Next, handle the case where a location was specified:
628 // Run through all the locations of this breakpoint and disable
629 // the ones that aren't on our "with locations" BreakpointID list:
630 size_t num_locations = bp_sp->GetNumLocations();
631 BreakpointID tmp_id(bp_id, LLDB_INVALID_BREAK_ID);
632 for (size_t loc_idx = 0; loc_idx < num_locations; loc_idx++) {
633 BreakpointLocationSP loc_sp = bp_sp->GetLocationAtIndex(loc_idx);
634 tmp_id.SetBreakpointLocationID(loc_idx);
635 if (!with_locs.Contains(tmp_id) && loc_sp->IsEnabled()) {
636 locs_disabled.push_back(tmp_id);
637 loc_sp->SetEnabled(false);
643 { // Scope for thread list mutex:
644 std::lock_guard<std::recursive_mutex> guard(
645 process->GetThreadList().GetMutex());
646 const uint32_t num_threads = process->GetThreadList().GetSize();
648 // Set the actions that the threads should each take when resuming
649 for (uint32_t idx = 0; idx < num_threads; ++idx) {
650 const bool override_suspend = false;
651 process->GetThreadList().GetThreadAtIndex(idx)->SetResumeState(
652 eStateRunning, override_suspend);
656 const uint32_t iohandler_id = process->GetIOHandlerID();
658 StreamString stream;
659 Status error;
660 // For now we can only do -b with synchronous:
661 bool old_sync = GetDebugger().GetAsyncExecution();
663 if (run_to_bkpt_ids.GetSize() != 0) {
664 GetDebugger().SetAsyncExecution(false);
665 synchronous_execution = true;
667 if (synchronous_execution)
668 error = process->ResumeSynchronous(&stream);
669 else
670 error = process->Resume();
672 if (run_to_bkpt_ids.GetSize() != 0) {
673 GetDebugger().SetAsyncExecution(old_sync);
676 // Now re-enable the breakpoints we disabled:
677 BreakpointList &bkpt_list = target.GetBreakpointList();
678 for (break_id_t bp_id : bkpts_disabled) {
679 BreakpointSP bp_sp = bkpt_list.FindBreakpointByID(bp_id);
680 if (bp_sp)
681 bp_sp->SetEnabled(true);
683 for (const BreakpointID &bkpt_id : locs_disabled) {
684 BreakpointSP bp_sp
685 = bkpt_list.FindBreakpointByID(bkpt_id.GetBreakpointID());
686 if (bp_sp) {
687 BreakpointLocationSP loc_sp
688 = bp_sp->FindLocationByID(bkpt_id.GetLocationID());
689 if (loc_sp)
690 loc_sp->SetEnabled(true);
694 if (error.Success()) {
695 // There is a race condition where this thread will return up the call
696 // stack to the main command handler and show an (lldb) prompt before
697 // HandlePrivateEvent (from PrivateStateThread) has a chance to call
698 // PushProcessIOHandler().
699 process->SyncIOHandler(iohandler_id, std::chrono::seconds(2));
701 result.AppendMessageWithFormat("Process %" PRIu64 " resuming\n",
702 process->GetID());
703 if (synchronous_execution) {
704 // If any state changed events had anything to say, add that to the
705 // result
706 result.AppendMessage(stream.GetString());
708 result.SetDidChangeProcessState(true);
709 result.SetStatus(eReturnStatusSuccessFinishNoResult);
710 } else {
711 result.SetStatus(eReturnStatusSuccessContinuingNoResult);
713 } else {
714 result.AppendErrorWithFormat("Failed to resume process: %s.\n",
715 error.AsCString());
717 } else {
718 result.AppendErrorWithFormat(
719 "Process cannot be continued from its current state (%s).\n",
720 StateAsCString(state));
724 Options *GetOptions() override { return &m_options; }
726 CommandOptions m_options;
729 // CommandObjectProcessDetach
730 #define LLDB_OPTIONS_process_detach
731 #include "CommandOptions.inc"
733 #pragma mark CommandObjectProcessDetach
735 class CommandObjectProcessDetach : public CommandObjectParsed {
736 public:
737 class CommandOptions : public Options {
738 public:
739 CommandOptions() { OptionParsingStarting(nullptr); }
741 ~CommandOptions() override = default;
743 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
744 ExecutionContext *execution_context) override {
745 Status error;
746 const int short_option = m_getopt_table[option_idx].val;
748 switch (short_option) {
749 case 's':
750 bool tmp_result;
751 bool success;
752 tmp_result = OptionArgParser::ToBoolean(option_arg, false, &success);
753 if (!success)
754 error = Status::FromErrorStringWithFormat(
755 "invalid boolean option: \"%s\"", option_arg.str().c_str());
756 else {
757 if (tmp_result)
758 m_keep_stopped = eLazyBoolYes;
759 else
760 m_keep_stopped = eLazyBoolNo;
762 break;
763 default:
764 llvm_unreachable("Unimplemented option");
766 return error;
769 void OptionParsingStarting(ExecutionContext *execution_context) override {
770 m_keep_stopped = eLazyBoolCalculate;
773 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
774 return llvm::ArrayRef(g_process_detach_options);
777 // Instance variables to hold the values for command options.
778 LazyBool m_keep_stopped;
781 CommandObjectProcessDetach(CommandInterpreter &interpreter)
782 : CommandObjectParsed(interpreter, "process detach",
783 "Detach from the current target process.",
784 "process detach",
785 eCommandRequiresProcess | eCommandTryTargetAPILock |
786 eCommandProcessMustBeLaunched) {}
788 ~CommandObjectProcessDetach() override = default;
790 Options *GetOptions() override { return &m_options; }
792 protected:
793 void DoExecute(Args &command, CommandReturnObject &result) override {
794 Process *process = m_exe_ctx.GetProcessPtr();
795 // FIXME: This will be a Command Option:
796 bool keep_stopped;
797 if (m_options.m_keep_stopped == eLazyBoolCalculate) {
798 // Check the process default:
799 keep_stopped = process->GetDetachKeepsStopped();
800 } else if (m_options.m_keep_stopped == eLazyBoolYes)
801 keep_stopped = true;
802 else
803 keep_stopped = false;
805 Status error(process->Detach(keep_stopped));
806 if (error.Success()) {
807 result.SetStatus(eReturnStatusSuccessFinishResult);
808 } else {
809 result.AppendErrorWithFormat("Detach failed: %s\n", error.AsCString());
813 CommandOptions m_options;
816 // CommandObjectProcessConnect
817 #define LLDB_OPTIONS_process_connect
818 #include "CommandOptions.inc"
820 #pragma mark CommandObjectProcessConnect
822 class CommandObjectProcessConnect : public CommandObjectParsed {
823 public:
824 class CommandOptions : public Options {
825 public:
826 CommandOptions() {
827 // Keep default values of all options in one place: OptionParsingStarting
828 // ()
829 OptionParsingStarting(nullptr);
832 ~CommandOptions() override = default;
834 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
835 ExecutionContext *execution_context) override {
836 Status error;
837 const int short_option = m_getopt_table[option_idx].val;
839 switch (short_option) {
840 case 'p':
841 plugin_name.assign(std::string(option_arg));
842 break;
844 default:
845 llvm_unreachable("Unimplemented option");
847 return error;
850 void OptionParsingStarting(ExecutionContext *execution_context) override {
851 plugin_name.clear();
854 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
855 return llvm::ArrayRef(g_process_connect_options);
858 // Instance variables to hold the values for command options.
860 std::string plugin_name;
863 CommandObjectProcessConnect(CommandInterpreter &interpreter)
864 : CommandObjectParsed(interpreter, "process connect",
865 "Connect to a remote debug service.",
866 "process connect <remote-url>", 0) {
867 AddSimpleArgumentList(eArgTypeConnectURL);
870 ~CommandObjectProcessConnect() override = default;
872 Options *GetOptions() override { return &m_options; }
874 protected:
875 void DoExecute(Args &command, CommandReturnObject &result) override {
876 if (command.GetArgumentCount() != 1) {
877 result.AppendErrorWithFormat(
878 "'%s' takes exactly one argument:\nUsage: %s\n", m_cmd_name.c_str(),
879 m_cmd_syntax.c_str());
880 return;
883 Process *process = m_exe_ctx.GetProcessPtr();
884 if (process && process->IsAlive()) {
885 result.AppendErrorWithFormat(
886 "Process %" PRIu64
887 " is currently being debugged, kill the process before connecting.\n",
888 process->GetID());
889 return;
892 const char *plugin_name = nullptr;
893 if (!m_options.plugin_name.empty())
894 plugin_name = m_options.plugin_name.c_str();
896 Status error;
897 Debugger &debugger = GetDebugger();
898 PlatformSP platform_sp = m_interpreter.GetPlatform(true);
899 ProcessSP process_sp =
900 debugger.GetAsyncExecution()
901 ? platform_sp->ConnectProcess(
902 command.GetArgumentAtIndex(0), plugin_name, debugger,
903 debugger.GetSelectedTarget().get(), error)
904 : platform_sp->ConnectProcessSynchronous(
905 command.GetArgumentAtIndex(0), plugin_name, debugger,
906 result.GetOutputStream(), debugger.GetSelectedTarget().get(),
907 error);
908 if (error.Fail() || process_sp == nullptr) {
909 result.AppendError(error.AsCString("Error connecting to the process"));
913 CommandOptions m_options;
916 // CommandObjectProcessPlugin
917 #pragma mark CommandObjectProcessPlugin
919 class CommandObjectProcessPlugin : public CommandObjectProxy {
920 public:
921 CommandObjectProcessPlugin(CommandInterpreter &interpreter)
922 : CommandObjectProxy(
923 interpreter, "process plugin",
924 "Send a custom command to the current target process plug-in.",
925 "process plugin <args>", 0) {}
927 ~CommandObjectProcessPlugin() override = default;
929 CommandObject *GetProxyCommandObject() override {
930 Process *process = m_interpreter.GetExecutionContext().GetProcessPtr();
931 if (process)
932 return process->GetPluginCommandObject();
933 return nullptr;
937 // CommandObjectProcessLoad
938 #define LLDB_OPTIONS_process_load
939 #include "CommandOptions.inc"
941 #pragma mark CommandObjectProcessLoad
943 class CommandObjectProcessLoad : public CommandObjectParsed {
944 public:
945 class CommandOptions : public Options {
946 public:
947 CommandOptions() {
948 // Keep default values of all options in one place: OptionParsingStarting
949 // ()
950 OptionParsingStarting(nullptr);
953 ~CommandOptions() override = default;
955 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
956 ExecutionContext *execution_context) override {
957 Status error;
958 const int short_option = m_getopt_table[option_idx].val;
959 ArchSpec arch =
960 execution_context->GetProcessPtr()->GetSystemArchitecture();
961 switch (short_option) {
962 case 'i':
963 do_install = true;
964 if (!option_arg.empty())
965 install_path.SetFile(option_arg, arch.GetTriple());
966 break;
967 default:
968 llvm_unreachable("Unimplemented option");
970 return error;
973 void OptionParsingStarting(ExecutionContext *execution_context) override {
974 do_install = false;
975 install_path.Clear();
978 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
979 return llvm::ArrayRef(g_process_load_options);
982 // Instance variables to hold the values for command options.
983 bool do_install;
984 FileSpec install_path;
987 CommandObjectProcessLoad(CommandInterpreter &interpreter)
988 : CommandObjectParsed(interpreter, "process load",
989 "Load a shared library into the current process.",
990 "process load <filename> [<filename> ...]",
991 eCommandRequiresProcess | eCommandTryTargetAPILock |
992 eCommandProcessMustBeLaunched |
993 eCommandProcessMustBePaused) {
994 AddSimpleArgumentList(eArgTypePath, eArgRepeatPlus);
997 ~CommandObjectProcessLoad() override = default;
999 void
1000 HandleArgumentCompletion(CompletionRequest &request,
1001 OptionElementVector &opt_element_vector) override {
1002 if (!m_exe_ctx.HasProcessScope())
1003 return;
1004 CommandObject::HandleArgumentCompletion(request, opt_element_vector);
1007 Options *GetOptions() override { return &m_options; }
1009 protected:
1010 void DoExecute(Args &command, CommandReturnObject &result) override {
1011 Process *process = m_exe_ctx.GetProcessPtr();
1013 for (auto &entry : command.entries()) {
1014 Status error;
1015 PlatformSP platform = process->GetTarget().GetPlatform();
1016 llvm::StringRef image_path = entry.ref();
1017 uint32_t image_token = LLDB_INVALID_IMAGE_TOKEN;
1019 if (!m_options.do_install) {
1020 FileSpec image_spec(image_path);
1021 platform->ResolveRemotePath(image_spec, image_spec);
1022 image_token =
1023 platform->LoadImage(process, FileSpec(), image_spec, error);
1024 } else if (m_options.install_path) {
1025 FileSpec image_spec(image_path);
1026 FileSystem::Instance().Resolve(image_spec);
1027 platform->ResolveRemotePath(m_options.install_path,
1028 m_options.install_path);
1029 image_token = platform->LoadImage(process, image_spec,
1030 m_options.install_path, error);
1031 } else {
1032 FileSpec image_spec(image_path);
1033 FileSystem::Instance().Resolve(image_spec);
1034 image_token =
1035 platform->LoadImage(process, image_spec, FileSpec(), error);
1038 if (image_token != LLDB_INVALID_IMAGE_TOKEN) {
1039 result.AppendMessageWithFormat(
1040 "Loading \"%s\"...ok\nImage %u loaded.\n", image_path.str().c_str(),
1041 image_token);
1042 result.SetStatus(eReturnStatusSuccessFinishResult);
1043 } else {
1044 result.AppendErrorWithFormat("failed to load '%s': %s",
1045 image_path.str().c_str(),
1046 error.AsCString());
1051 CommandOptions m_options;
1054 // CommandObjectProcessUnload
1055 #pragma mark CommandObjectProcessUnload
1057 class CommandObjectProcessUnload : public CommandObjectParsed {
1058 public:
1059 CommandObjectProcessUnload(CommandInterpreter &interpreter)
1060 : CommandObjectParsed(
1061 interpreter, "process unload",
1062 "Unload a shared library from the current process using the index "
1063 "returned by a previous call to \"process load\".",
1064 "process unload <index>",
1065 eCommandRequiresProcess | eCommandTryTargetAPILock |
1066 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {
1067 AddSimpleArgumentList(eArgTypeUnsignedInteger);
1070 ~CommandObjectProcessUnload() override = default;
1072 void
1073 HandleArgumentCompletion(CompletionRequest &request,
1074 OptionElementVector &opt_element_vector) override {
1076 if (request.GetCursorIndex() || !m_exe_ctx.HasProcessScope())
1077 return;
1079 Process *process = m_exe_ctx.GetProcessPtr();
1081 const std::vector<lldb::addr_t> &tokens = process->GetImageTokens();
1082 const size_t token_num = tokens.size();
1083 for (size_t i = 0; i < token_num; ++i) {
1084 if (tokens[i] == LLDB_INVALID_IMAGE_TOKEN)
1085 continue;
1086 request.TryCompleteCurrentArg(std::to_string(i));
1090 protected:
1091 void DoExecute(Args &command, CommandReturnObject &result) override {
1092 Process *process = m_exe_ctx.GetProcessPtr();
1094 for (auto &entry : command.entries()) {
1095 uint32_t image_token;
1096 if (entry.ref().getAsInteger(0, image_token)) {
1097 result.AppendErrorWithFormat("invalid image index argument '%s'",
1098 entry.ref().str().c_str());
1099 break;
1100 } else {
1101 Status error(process->GetTarget().GetPlatform()->UnloadImage(
1102 process, image_token));
1103 if (error.Success()) {
1104 result.AppendMessageWithFormat(
1105 "Unloading shared library with index %u...ok\n", image_token);
1106 result.SetStatus(eReturnStatusSuccessFinishResult);
1107 } else {
1108 result.AppendErrorWithFormat("failed to unload image: %s",
1109 error.AsCString());
1110 break;
1117 // CommandObjectProcessSignal
1118 #pragma mark CommandObjectProcessSignal
1120 class CommandObjectProcessSignal : public CommandObjectParsed {
1121 public:
1122 CommandObjectProcessSignal(CommandInterpreter &interpreter)
1123 : CommandObjectParsed(
1124 interpreter, "process signal",
1125 "Send a UNIX signal to the current target process.", nullptr,
1126 eCommandRequiresProcess | eCommandTryTargetAPILock) {
1127 AddSimpleArgumentList(eArgTypeUnixSignal);
1130 ~CommandObjectProcessSignal() override = default;
1132 void
1133 HandleArgumentCompletion(CompletionRequest &request,
1134 OptionElementVector &opt_element_vector) override {
1135 if (!m_exe_ctx.HasProcessScope() || request.GetCursorIndex() != 0)
1136 return;
1138 UnixSignalsSP signals = m_exe_ctx.GetProcessPtr()->GetUnixSignals();
1139 int signo = signals->GetFirstSignalNumber();
1140 while (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1141 request.TryCompleteCurrentArg(signals->GetSignalAsStringRef(signo));
1142 signo = signals->GetNextSignalNumber(signo);
1146 protected:
1147 void DoExecute(Args &command, CommandReturnObject &result) override {
1148 Process *process = m_exe_ctx.GetProcessPtr();
1150 if (command.GetArgumentCount() == 1) {
1151 int signo = LLDB_INVALID_SIGNAL_NUMBER;
1153 const char *signal_name = command.GetArgumentAtIndex(0);
1154 if (::isxdigit(signal_name[0])) {
1155 if (!llvm::to_integer(signal_name, signo))
1156 signo = LLDB_INVALID_SIGNAL_NUMBER;
1157 } else
1158 signo = process->GetUnixSignals()->GetSignalNumberFromName(signal_name);
1160 if (signo == LLDB_INVALID_SIGNAL_NUMBER) {
1161 result.AppendErrorWithFormat("Invalid signal argument '%s'.\n",
1162 command.GetArgumentAtIndex(0));
1163 } else {
1164 Status error(process->Signal(signo));
1165 if (error.Success()) {
1166 result.SetStatus(eReturnStatusSuccessFinishResult);
1167 } else {
1168 result.AppendErrorWithFormat("Failed to send signal %i: %s\n", signo,
1169 error.AsCString());
1172 } else {
1173 result.AppendErrorWithFormat(
1174 "'%s' takes exactly one signal number argument:\nUsage: %s\n",
1175 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1180 // CommandObjectProcessInterrupt
1181 #pragma mark CommandObjectProcessInterrupt
1183 class CommandObjectProcessInterrupt : public CommandObjectParsed {
1184 public:
1185 CommandObjectProcessInterrupt(CommandInterpreter &interpreter)
1186 : CommandObjectParsed(interpreter, "process interrupt",
1187 "Interrupt the current target process.",
1188 "process interrupt",
1189 eCommandRequiresProcess | eCommandTryTargetAPILock |
1190 eCommandProcessMustBeLaunched) {}
1192 ~CommandObjectProcessInterrupt() override = default;
1194 protected:
1195 void DoExecute(Args &command, CommandReturnObject &result) override {
1196 Process *process = m_exe_ctx.GetProcessPtr();
1197 if (process == nullptr) {
1198 result.AppendError("no process to halt");
1199 return;
1202 bool clear_thread_plans = true;
1203 Status error(process->Halt(clear_thread_plans));
1204 if (error.Success()) {
1205 result.SetStatus(eReturnStatusSuccessFinishResult);
1206 } else {
1207 result.AppendErrorWithFormat("Failed to halt process: %s\n",
1208 error.AsCString());
1213 // CommandObjectProcessKill
1214 #pragma mark CommandObjectProcessKill
1216 class CommandObjectProcessKill : public CommandObjectParsed {
1217 public:
1218 CommandObjectProcessKill(CommandInterpreter &interpreter)
1219 : CommandObjectParsed(interpreter, "process kill",
1220 "Terminate the current target process.",
1221 "process kill",
1222 eCommandRequiresProcess | eCommandTryTargetAPILock |
1223 eCommandProcessMustBeLaunched) {}
1225 ~CommandObjectProcessKill() override = default;
1227 protected:
1228 void DoExecute(Args &command, CommandReturnObject &result) override {
1229 Process *process = m_exe_ctx.GetProcessPtr();
1230 if (process == nullptr) {
1231 result.AppendError("no process to kill");
1232 return;
1235 Status error(process->Destroy(true));
1236 if (error.Success()) {
1237 result.SetStatus(eReturnStatusSuccessFinishResult);
1238 } else {
1239 result.AppendErrorWithFormat("Failed to kill process: %s\n",
1240 error.AsCString());
1245 #define LLDB_OPTIONS_process_save_core
1246 #include "CommandOptions.inc"
1248 class CommandObjectProcessSaveCore : public CommandObjectParsed {
1249 public:
1250 CommandObjectProcessSaveCore(CommandInterpreter &interpreter)
1251 : CommandObjectParsed(
1252 interpreter, "process save-core",
1253 "Save the current process as a core file using an "
1254 "appropriate file type.",
1255 "process save-core [-s corefile-style -p plugin-name] FILE",
1256 eCommandRequiresProcess | eCommandTryTargetAPILock |
1257 eCommandProcessMustBeLaunched) {
1258 AddSimpleArgumentList(eArgTypePath);
1261 ~CommandObjectProcessSaveCore() override = default;
1263 Options *GetOptions() override { return &m_options; }
1265 class CommandOptions : public Options {
1266 public:
1267 CommandOptions() = default;
1269 ~CommandOptions() override = default;
1271 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1272 return llvm::ArrayRef(g_process_save_core_options);
1275 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1276 ExecutionContext *execution_context) override {
1277 const int short_option = m_getopt_table[option_idx].val;
1278 Status error;
1280 switch (short_option) {
1281 case 'p':
1282 error = m_core_dump_options.SetPluginName(option_arg.data());
1283 break;
1284 case 's':
1285 m_core_dump_options.SetStyle(
1286 (lldb::SaveCoreStyle)OptionArgParser::ToOptionEnum(
1287 option_arg, GetDefinitions()[option_idx].enum_values,
1288 eSaveCoreUnspecified, error));
1289 break;
1290 default:
1291 llvm_unreachable("Unimplemented option");
1294 return {};
1297 void OptionParsingStarting(ExecutionContext *execution_context) override {
1298 m_core_dump_options.Clear();
1301 // Instance variables to hold the values for command options.
1302 SaveCoreOptions m_core_dump_options;
1305 protected:
1306 void DoExecute(Args &command, CommandReturnObject &result) override {
1307 ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1308 if (process_sp) {
1309 if (command.GetArgumentCount() == 1) {
1310 FileSpec output_file(command.GetArgumentAtIndex(0));
1311 FileSystem::Instance().Resolve(output_file);
1312 auto &core_dump_options = m_options.m_core_dump_options;
1313 core_dump_options.SetOutputFile(output_file);
1314 Status error = PluginManager::SaveCore(process_sp, core_dump_options);
1315 if (error.Success()) {
1316 if (core_dump_options.GetStyle() ==
1317 SaveCoreStyle::eSaveCoreDirtyOnly ||
1318 core_dump_options.GetStyle() ==
1319 SaveCoreStyle::eSaveCoreStackOnly) {
1320 result.AppendMessageWithFormat(
1321 "\nModified-memory or stack-memory only corefile "
1322 "created. This corefile may \n"
1323 "not show library/framework/app binaries "
1324 "on a different system, or when \n"
1325 "those binaries have "
1326 "been updated/modified. Copies are not included\n"
1327 "in this corefile. Use --style full to include all "
1328 "process memory.\n");
1330 result.SetStatus(eReturnStatusSuccessFinishResult);
1331 } else {
1332 result.AppendErrorWithFormat(
1333 "Failed to save core file for process: %s\n", error.AsCString());
1335 } else {
1336 result.AppendErrorWithFormat("'%s' takes one arguments:\nUsage: %s\n",
1337 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1339 } else {
1340 result.AppendError("invalid process");
1344 CommandOptions m_options;
1347 // CommandObjectProcessStatus
1348 #pragma mark CommandObjectProcessStatus
1349 #define LLDB_OPTIONS_process_status
1350 #include "CommandOptions.inc"
1352 class CommandObjectProcessStatus : public CommandObjectParsed {
1353 public:
1354 CommandObjectProcessStatus(CommandInterpreter &interpreter)
1355 : CommandObjectParsed(
1356 interpreter, "process status",
1357 "Show status and stop location for the current target process.",
1358 "process status",
1359 eCommandRequiresProcess | eCommandTryTargetAPILock) {}
1361 ~CommandObjectProcessStatus() override = default;
1363 Options *GetOptions() override { return &m_options; }
1365 class CommandOptions : public Options {
1366 public:
1367 CommandOptions() = default;
1369 ~CommandOptions() override = default;
1371 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1372 ExecutionContext *execution_context) override {
1373 const int short_option = m_getopt_table[option_idx].val;
1375 switch (short_option) {
1376 case 'v':
1377 m_verbose = true;
1378 break;
1379 default:
1380 llvm_unreachable("Unimplemented option");
1383 return {};
1386 void OptionParsingStarting(ExecutionContext *execution_context) override {
1387 m_verbose = false;
1390 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1391 return llvm::ArrayRef(g_process_status_options);
1394 // Instance variables to hold the values for command options.
1395 bool m_verbose = false;
1398 protected:
1399 void DoExecute(Args &command, CommandReturnObject &result) override {
1400 Stream &strm = result.GetOutputStream();
1401 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1403 // No need to check "process" for validity as eCommandRequiresProcess
1404 // ensures it is valid
1405 Process *process = m_exe_ctx.GetProcessPtr();
1406 const bool only_threads_with_stop_reason = true;
1407 const uint32_t start_frame = 0;
1408 const uint32_t num_frames = 1;
1409 const uint32_t num_frames_with_source = 1;
1410 const bool stop_format = true;
1411 process->GetStatus(strm);
1412 process->GetThreadStatus(strm, only_threads_with_stop_reason, start_frame,
1413 num_frames, num_frames_with_source, stop_format);
1415 if (m_options.m_verbose) {
1416 addr_t code_mask = process->GetCodeAddressMask();
1417 addr_t data_mask = process->GetDataAddressMask();
1418 if (code_mask != LLDB_INVALID_ADDRESS_MASK) {
1419 int bits = std::bitset<64>(~code_mask).count();
1420 result.AppendMessageWithFormat(
1421 "Addressable code address mask: 0x%" PRIx64 "\n", code_mask);
1422 result.AppendMessageWithFormat(
1423 "Addressable data address mask: 0x%" PRIx64 "\n", data_mask);
1424 result.AppendMessageWithFormat(
1425 "Number of bits used in addressing (code): %d\n", bits);
1428 PlatformSP platform_sp = process->GetTarget().GetPlatform();
1429 if (!platform_sp) {
1430 result.AppendError("Couldn't retrieve the target's platform");
1431 return;
1434 auto expected_crash_info =
1435 platform_sp->FetchExtendedCrashInformation(*process);
1437 if (!expected_crash_info) {
1438 result.AppendError(llvm::toString(expected_crash_info.takeError()));
1439 return;
1442 StructuredData::DictionarySP crash_info_sp = *expected_crash_info;
1444 if (crash_info_sp) {
1445 strm.EOL();
1446 strm.PutCString("Extended Crash Information:\n");
1447 crash_info_sp->GetDescription(strm);
1452 private:
1453 CommandOptions m_options;
1456 // CommandObjectProcessHandle
1457 #define LLDB_OPTIONS_process_handle
1458 #include "CommandOptions.inc"
1460 #pragma mark CommandObjectProcessHandle
1462 class CommandObjectProcessHandle : public CommandObjectParsed {
1463 public:
1464 class CommandOptions : public Options {
1465 public:
1466 CommandOptions() { OptionParsingStarting(nullptr); }
1468 ~CommandOptions() override = default;
1470 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1471 ExecutionContext *execution_context) override {
1472 Status error;
1473 const int short_option = m_getopt_table[option_idx].val;
1475 switch (short_option) {
1476 case 'c':
1477 do_clear = true;
1478 break;
1479 case 'd':
1480 dummy = true;
1481 break;
1482 case 's':
1483 stop = std::string(option_arg);
1484 break;
1485 case 'n':
1486 notify = std::string(option_arg);
1487 break;
1488 case 'p':
1489 pass = std::string(option_arg);
1490 break;
1491 case 't':
1492 only_target_values = true;
1493 break;
1494 default:
1495 llvm_unreachable("Unimplemented option");
1497 return error;
1500 void OptionParsingStarting(ExecutionContext *execution_context) override {
1501 stop.clear();
1502 notify.clear();
1503 pass.clear();
1504 only_target_values = false;
1505 do_clear = false;
1506 dummy = false;
1509 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1510 return llvm::ArrayRef(g_process_handle_options);
1513 // Instance variables to hold the values for command options.
1515 std::string stop;
1516 std::string notify;
1517 std::string pass;
1518 bool only_target_values = false;
1519 bool do_clear = false;
1520 bool dummy = false;
1523 CommandObjectProcessHandle(CommandInterpreter &interpreter)
1524 : CommandObjectParsed(interpreter, "process handle",
1525 "Manage LLDB handling of OS signals for the "
1526 "current target process. Defaults to showing "
1527 "current policy.",
1528 nullptr) {
1529 SetHelpLong("\nIf no signals are specified but one or more actions are, "
1530 "and there is a live process, update them all. If no action "
1531 "is specified, list the current values.\n"
1532 "If you specify actions with no target (e.g. in an init file) "
1533 "or in a target with no process "
1534 "the values will get copied into subsequent targets, but "
1535 "lldb won't be able to spell-check the options since it can't "
1536 "know which signal set will later be in force."
1537 "\nYou can see the signal modifications held by the target"
1538 "by passing the -t option."
1539 "\nYou can also clear the target modification for a signal"
1540 "by passing the -c option");
1541 AddSimpleArgumentList(eArgTypeUnixSignal, eArgRepeatStar);
1544 ~CommandObjectProcessHandle() override = default;
1546 Options *GetOptions() override { return &m_options; }
1548 void PrintSignalHeader(Stream &str) {
1549 str.Printf("NAME PASS STOP NOTIFY\n");
1550 str.Printf("=========== ===== ===== ======\n");
1553 void PrintSignal(Stream &str, int32_t signo, llvm::StringRef sig_name,
1554 const UnixSignalsSP &signals_sp) {
1555 bool stop;
1556 bool suppress;
1557 bool notify;
1559 str.Format("{0, -11} ", sig_name);
1560 if (signals_sp->GetSignalInfo(signo, suppress, stop, notify)) {
1561 bool pass = !suppress;
1562 str.Printf("%s %s %s", (pass ? "true " : "false"),
1563 (stop ? "true " : "false"), (notify ? "true " : "false"));
1565 str.Printf("\n");
1568 void PrintSignalInformation(Stream &str, Args &signal_args,
1569 int num_valid_signals,
1570 const UnixSignalsSP &signals_sp) {
1571 PrintSignalHeader(str);
1573 if (num_valid_signals > 0) {
1574 size_t num_args = signal_args.GetArgumentCount();
1575 for (size_t i = 0; i < num_args; ++i) {
1576 int32_t signo = signals_sp->GetSignalNumberFromName(
1577 signal_args.GetArgumentAtIndex(i));
1578 if (signo != LLDB_INVALID_SIGNAL_NUMBER)
1579 PrintSignal(str, signo, signal_args.GetArgumentAtIndex(i),
1580 signals_sp);
1582 } else // Print info for ALL signals
1584 int32_t signo = signals_sp->GetFirstSignalNumber();
1585 while (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1586 PrintSignal(str, signo, signals_sp->GetSignalAsStringRef(signo),
1587 signals_sp);
1588 signo = signals_sp->GetNextSignalNumber(signo);
1593 protected:
1594 void DoExecute(Args &signal_args, CommandReturnObject &result) override {
1595 Target &target = GetTarget();
1597 // Any signals that are being set should be added to the Target's
1598 // DummySignals so they will get applied on rerun, etc.
1599 // If we have a process, however, we can do a more accurate job of vetting
1600 // the user's options.
1601 ProcessSP process_sp = target.GetProcessSP();
1603 std::optional<bool> stop_action = {};
1604 std::optional<bool> pass_action = {};
1605 std::optional<bool> notify_action = {};
1607 if (!m_options.stop.empty()) {
1608 bool success = false;
1609 bool value = OptionArgParser::ToBoolean(m_options.stop, false, &success);
1610 if (!success) {
1611 result.AppendError(
1612 "Invalid argument for command option --stop; must be "
1613 "true or false.\n");
1614 return;
1617 stop_action = value;
1620 if (!m_options.pass.empty()) {
1621 bool success = false;
1622 bool value = OptionArgParser::ToBoolean(m_options.pass, false, &success);
1623 if (!success) {
1624 result.AppendError(
1625 "Invalid argument for command option --pass; must be "
1626 "true or false.\n");
1627 return;
1629 pass_action = value;
1632 if (!m_options.notify.empty()) {
1633 bool success = false;
1634 bool value =
1635 OptionArgParser::ToBoolean(m_options.notify, false, &success);
1636 if (!success) {
1637 result.AppendError("Invalid argument for command option --notify; must "
1638 "be true or false.\n");
1639 return;
1641 notify_action = value;
1644 if (!m_options.notify.empty() && !notify_action.has_value()) {
1647 bool no_actions = (!stop_action.has_value() && !pass_action.has_value() &&
1648 !notify_action.has_value());
1649 if (m_options.only_target_values && !no_actions) {
1650 result.AppendError("-t is for reporting, not setting, target values.");
1651 return;
1654 size_t num_args = signal_args.GetArgumentCount();
1655 UnixSignalsSP signals_sp;
1656 if (process_sp)
1657 signals_sp = process_sp->GetUnixSignals();
1659 int num_signals_set = 0;
1661 // If we were just asked to print the target values, do that here and
1662 // return:
1663 if (m_options.only_target_values) {
1664 target.PrintDummySignals(result.GetOutputStream(), signal_args);
1665 result.SetStatus(eReturnStatusSuccessFinishResult);
1666 return;
1669 // This handles clearing values:
1670 if (m_options.do_clear) {
1671 target.ClearDummySignals(signal_args);
1672 if (m_options.dummy)
1673 GetDummyTarget().ClearDummySignals(signal_args);
1674 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1675 return;
1678 // This rest handles setting values:
1679 if (num_args > 0) {
1680 for (const auto &arg : signal_args) {
1681 // Do the process first. If we have a process we can catch
1682 // invalid signal names, which we do here.
1683 if (signals_sp) {
1684 int32_t signo = signals_sp->GetSignalNumberFromName(arg.c_str());
1685 if (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1686 if (stop_action.has_value())
1687 signals_sp->SetShouldStop(signo, *stop_action);
1688 if (pass_action.has_value()) {
1689 bool suppress = !*pass_action;
1690 signals_sp->SetShouldSuppress(signo, suppress);
1692 if (notify_action.has_value())
1693 signals_sp->SetShouldNotify(signo, *notify_action);
1694 ++num_signals_set;
1695 } else {
1696 result.AppendErrorWithFormat("Invalid signal name '%s'\n",
1697 arg.c_str());
1698 continue;
1700 } else {
1701 // If there's no process we can't check, so we just set them all.
1702 // But since the map signal name -> signal number across all platforms
1703 // is not 1-1, we can't sensibly set signal actions by number before
1704 // we have a process. Check that here:
1705 int32_t signo;
1706 if (llvm::to_integer(arg.c_str(), signo)) {
1707 result.AppendErrorWithFormat("Can't set signal handling by signal "
1708 "number with no process");
1709 return;
1711 num_signals_set = num_args;
1713 auto set_lazy_bool = [](std::optional<bool> action) -> LazyBool {
1714 if (!action.has_value())
1715 return eLazyBoolCalculate;
1716 return (*action) ? eLazyBoolYes : eLazyBoolNo;
1719 // If there were no actions, we're just listing, don't add the dummy:
1720 if (!no_actions)
1721 target.AddDummySignal(arg.ref(), set_lazy_bool(pass_action),
1722 set_lazy_bool(notify_action),
1723 set_lazy_bool(stop_action));
1725 } else {
1726 // No signal specified, if any command options were specified, update ALL
1727 // signals. But we can't do this without a process since we don't know
1728 // all the possible signals that might be valid for this target.
1729 if ((notify_action.has_value() || stop_action.has_value() ||
1730 pass_action.has_value()) &&
1731 process_sp) {
1732 if (m_interpreter.Confirm(
1733 "Do you really want to update all the signals?", false)) {
1734 int32_t signo = signals_sp->GetFirstSignalNumber();
1735 while (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1736 if (notify_action.has_value())
1737 signals_sp->SetShouldNotify(signo, *notify_action);
1738 if (stop_action.has_value())
1739 signals_sp->SetShouldStop(signo, *stop_action);
1740 if (pass_action.has_value()) {
1741 bool suppress = !*pass_action;
1742 signals_sp->SetShouldSuppress(signo, suppress);
1744 signo = signals_sp->GetNextSignalNumber(signo);
1750 if (signals_sp)
1751 PrintSignalInformation(result.GetOutputStream(), signal_args,
1752 num_signals_set, signals_sp);
1753 else
1754 target.PrintDummySignals(result.GetOutputStream(),
1755 signal_args);
1757 if (num_signals_set > 0)
1758 result.SetStatus(eReturnStatusSuccessFinishResult);
1759 else
1760 result.SetStatus(eReturnStatusFailed);
1763 CommandOptions m_options;
1766 // Next are the subcommands of CommandObjectMultiwordProcessTrace
1768 // CommandObjectProcessTraceStart
1769 class CommandObjectProcessTraceStart : public CommandObjectTraceProxy {
1770 public:
1771 CommandObjectProcessTraceStart(CommandInterpreter &interpreter)
1772 : CommandObjectTraceProxy(
1773 /*live_debug_session_only*/ true, interpreter,
1774 "process trace start",
1775 "Start tracing this process with the corresponding trace "
1776 "plug-in.",
1777 "process trace start [<trace-options>]") {}
1779 protected:
1780 lldb::CommandObjectSP GetDelegateCommand(Trace &trace) override {
1781 return trace.GetProcessTraceStartCommand(m_interpreter);
1785 // CommandObjectProcessTraceStop
1786 class CommandObjectProcessTraceStop : public CommandObjectParsed {
1787 public:
1788 CommandObjectProcessTraceStop(CommandInterpreter &interpreter)
1789 : CommandObjectParsed(interpreter, "process trace stop",
1790 "Stop tracing this process. This does not affect "
1791 "traces started with the "
1792 "\"thread trace start\" command.",
1793 "process trace stop",
1794 eCommandRequiresProcess | eCommandTryTargetAPILock |
1795 eCommandProcessMustBeLaunched |
1796 eCommandProcessMustBePaused |
1797 eCommandProcessMustBeTraced) {}
1799 ~CommandObjectProcessTraceStop() override = default;
1801 void DoExecute(Args &command, CommandReturnObject &result) override {
1802 ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1804 TraceSP trace_sp = process_sp->GetTarget().GetTrace();
1806 if (llvm::Error err = trace_sp->Stop())
1807 result.AppendError(toString(std::move(err)));
1808 else
1809 result.SetStatus(eReturnStatusSuccessFinishResult);
1813 // CommandObjectMultiwordProcessTrace
1814 class CommandObjectMultiwordProcessTrace : public CommandObjectMultiword {
1815 public:
1816 CommandObjectMultiwordProcessTrace(CommandInterpreter &interpreter)
1817 : CommandObjectMultiword(
1818 interpreter, "trace", "Commands for tracing the current process.",
1819 "process trace <subcommand> [<subcommand objects>]") {
1820 LoadSubCommand("start", CommandObjectSP(new CommandObjectProcessTraceStart(
1821 interpreter)));
1822 LoadSubCommand("stop", CommandObjectSP(
1823 new CommandObjectProcessTraceStop(interpreter)));
1826 ~CommandObjectMultiwordProcessTrace() override = default;
1829 // CommandObjectMultiwordProcess
1831 CommandObjectMultiwordProcess::CommandObjectMultiwordProcess(
1832 CommandInterpreter &interpreter)
1833 : CommandObjectMultiword(
1834 interpreter, "process",
1835 "Commands for interacting with processes on the current platform.",
1836 "process <subcommand> [<subcommand-options>]") {
1837 LoadSubCommand("attach",
1838 CommandObjectSP(new CommandObjectProcessAttach(interpreter)));
1839 LoadSubCommand("launch",
1840 CommandObjectSP(new CommandObjectProcessLaunch(interpreter)));
1841 LoadSubCommand("continue", CommandObjectSP(new CommandObjectProcessContinue(
1842 interpreter)));
1843 LoadSubCommand("connect",
1844 CommandObjectSP(new CommandObjectProcessConnect(interpreter)));
1845 LoadSubCommand("detach",
1846 CommandObjectSP(new CommandObjectProcessDetach(interpreter)));
1847 LoadSubCommand("load",
1848 CommandObjectSP(new CommandObjectProcessLoad(interpreter)));
1849 LoadSubCommand("unload",
1850 CommandObjectSP(new CommandObjectProcessUnload(interpreter)));
1851 LoadSubCommand("signal",
1852 CommandObjectSP(new CommandObjectProcessSignal(interpreter)));
1853 LoadSubCommand("handle",
1854 CommandObjectSP(new CommandObjectProcessHandle(interpreter)));
1855 LoadSubCommand("status",
1856 CommandObjectSP(new CommandObjectProcessStatus(interpreter)));
1857 LoadSubCommand("interrupt", CommandObjectSP(new CommandObjectProcessInterrupt(
1858 interpreter)));
1859 LoadSubCommand("kill",
1860 CommandObjectSP(new CommandObjectProcessKill(interpreter)));
1861 LoadSubCommand("plugin",
1862 CommandObjectSP(new CommandObjectProcessPlugin(interpreter)));
1863 LoadSubCommand("save-core", CommandObjectSP(new CommandObjectProcessSaveCore(
1864 interpreter)));
1865 LoadSubCommand(
1866 "trace",
1867 CommandObjectSP(new CommandObjectMultiwordProcessTrace(interpreter)));
1870 CommandObjectMultiwordProcess::~CommandObjectMultiwordProcess() = default;