Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / lldb / source / Commands / CommandObjectProcess.cpp
blobc7ce1b1258c196c9ff59fc7d8223257b425240bc
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/Target/Platform.h"
29 #include "lldb/Target/Process.h"
30 #include "lldb/Target/StopInfo.h"
31 #include "lldb/Target/Target.h"
32 #include "lldb/Target/Thread.h"
33 #include "lldb/Target/UnixSignals.h"
34 #include "lldb/Utility/Args.h"
35 #include "lldb/Utility/ScriptedMetadata.h"
36 #include "lldb/Utility/State.h"
38 #include "llvm/ADT/ScopeExit.h"
40 #include <bitset>
41 #include <optional>
43 using namespace lldb;
44 using namespace lldb_private;
46 class CommandObjectProcessLaunchOrAttach : public CommandObjectParsed {
47 public:
48 CommandObjectProcessLaunchOrAttach(CommandInterpreter &interpreter,
49 const char *name, const char *help,
50 const char *syntax, uint32_t flags,
51 const char *new_process_action)
52 : CommandObjectParsed(interpreter, name, help, syntax, flags),
53 m_new_process_action(new_process_action) {}
55 ~CommandObjectProcessLaunchOrAttach() override = default;
57 protected:
58 bool StopProcessIfNecessary(Process *process, StateType &state,
59 CommandReturnObject &result) {
60 state = eStateInvalid;
61 if (process) {
62 state = process->GetState();
64 if (process->IsAlive() && state != eStateConnected) {
65 std::string message;
66 if (process->GetState() == eStateAttaching)
67 message =
68 llvm::formatv("There is a pending attach, abort it and {0}?",
69 m_new_process_action);
70 else if (process->GetShouldDetach())
71 message = llvm::formatv(
72 "There is a running process, detach from it and {0}?",
73 m_new_process_action);
74 else
75 message =
76 llvm::formatv("There is a running process, kill it and {0}?",
77 m_new_process_action);
79 if (!m_interpreter.Confirm(message, true)) {
80 result.SetStatus(eReturnStatusFailed);
81 return false;
82 } else {
83 if (process->GetShouldDetach()) {
84 bool keep_stopped = false;
85 Status detach_error(process->Detach(keep_stopped));
86 if (detach_error.Success()) {
87 result.SetStatus(eReturnStatusSuccessFinishResult);
88 process = nullptr;
89 } else {
90 result.AppendErrorWithFormat(
91 "Failed to detach from process: %s\n",
92 detach_error.AsCString());
94 } else {
95 Status destroy_error(process->Destroy(false));
96 if (destroy_error.Success()) {
97 result.SetStatus(eReturnStatusSuccessFinishResult);
98 process = nullptr;
99 } else {
100 result.AppendErrorWithFormat("Failed to kill process: %s\n",
101 destroy_error.AsCString());
107 return result.Succeeded();
110 std::string m_new_process_action;
113 // CommandObjectProcessLaunch
114 #pragma mark CommandObjectProcessLaunch
115 class CommandObjectProcessLaunch : public CommandObjectProcessLaunchOrAttach {
116 public:
117 CommandObjectProcessLaunch(CommandInterpreter &interpreter)
118 : CommandObjectProcessLaunchOrAttach(
119 interpreter, "process launch",
120 "Launch the executable in the debugger.", nullptr,
121 eCommandRequiresTarget, "restart"),
123 m_class_options("scripted process", true, 'C', 'k', 'v', 0) {
124 m_all_options.Append(&m_options);
125 m_all_options.Append(&m_class_options, LLDB_OPT_SET_1 | LLDB_OPT_SET_2,
126 LLDB_OPT_SET_ALL);
127 m_all_options.Finalize();
129 CommandArgumentEntry arg;
130 CommandArgumentData run_args_arg;
132 // Define the first (and only) variant of this arg.
133 run_args_arg.arg_type = eArgTypeRunArgs;
134 run_args_arg.arg_repetition = eArgRepeatOptional;
136 // There is only one variant this argument could be; put it into the
137 // argument entry.
138 arg.push_back(run_args_arg);
140 // Push the data for the first argument into the m_arguments vector.
141 m_arguments.push_back(arg);
144 ~CommandObjectProcessLaunch() override = default;
146 void
147 HandleArgumentCompletion(CompletionRequest &request,
148 OptionElementVector &opt_element_vector) override {
150 lldb_private::CommandCompletions::InvokeCommonCompletionCallbacks(
151 GetCommandInterpreter(), lldb::eDiskFileCompletion, request, nullptr);
154 Options *GetOptions() override { return &m_all_options; }
156 std::optional<std::string> GetRepeatCommand(Args &current_command_args,
157 uint32_t index) override {
158 // No repeat for "process launch"...
159 return std::string("");
162 protected:
163 void DoExecute(Args &launch_args, CommandReturnObject &result) override {
164 Debugger &debugger = GetDebugger();
165 Target *target = debugger.GetSelectedTarget().get();
166 // If our listener is nullptr, users aren't allows to launch
167 ModuleSP exe_module_sp = target->GetExecutableModule();
169 // If the target already has an executable module, then use that. If it
170 // doesn't then someone must be trying to launch using a path that will
171 // make sense to the remote stub, but doesn't exist on the local host.
172 // In that case use the ExecutableFile that was set in the target's
173 // ProcessLaunchInfo.
174 if (exe_module_sp == nullptr && !target->GetProcessLaunchInfo().GetExecutableFile()) {
175 result.AppendError("no file in target, create a debug target using the "
176 "'target create' command");
177 return;
180 StateType state = eStateInvalid;
182 if (!StopProcessIfNecessary(m_exe_ctx.GetProcessPtr(), state, result))
183 return;
185 // Determine whether we will disable ASLR or leave it in the default state
186 // (i.e. enabled if the platform supports it). First check if the process
187 // launch options explicitly turn on/off
188 // disabling ASLR. If so, use that setting;
189 // otherwise, use the 'settings target.disable-aslr' setting.
190 bool disable_aslr = false;
191 if (m_options.disable_aslr != eLazyBoolCalculate) {
192 // The user specified an explicit setting on the process launch line.
193 // Use it.
194 disable_aslr = (m_options.disable_aslr == eLazyBoolYes);
195 } else {
196 // The user did not explicitly specify whether to disable ASLR. Fall
197 // back to the target.disable-aslr setting.
198 disable_aslr = target->GetDisableASLR();
201 if (!m_class_options.GetName().empty()) {
202 m_options.launch_info.SetProcessPluginName("ScriptedProcess");
203 ScriptedMetadataSP metadata_sp = std::make_shared<ScriptedMetadata>(
204 m_class_options.GetName(), m_class_options.GetStructuredData());
205 m_options.launch_info.SetScriptedMetadata(metadata_sp);
206 target->SetProcessLaunchInfo(m_options.launch_info);
209 if (disable_aslr)
210 m_options.launch_info.GetFlags().Set(eLaunchFlagDisableASLR);
211 else
212 m_options.launch_info.GetFlags().Clear(eLaunchFlagDisableASLR);
214 if (target->GetInheritTCC())
215 m_options.launch_info.GetFlags().Set(eLaunchFlagInheritTCCFromParent);
217 if (target->GetDetachOnError())
218 m_options.launch_info.GetFlags().Set(eLaunchFlagDetachOnError);
220 if (target->GetDisableSTDIO())
221 m_options.launch_info.GetFlags().Set(eLaunchFlagDisableSTDIO);
223 // Merge the launch info environment with the target environment.
224 Environment target_env = target->GetEnvironment();
225 m_options.launch_info.GetEnvironment().insert(target_env.begin(),
226 target_env.end());
228 llvm::StringRef target_settings_argv0 = target->GetArg0();
230 if (!target_settings_argv0.empty()) {
231 m_options.launch_info.GetArguments().AppendArgument(
232 target_settings_argv0);
233 if (exe_module_sp)
234 m_options.launch_info.SetExecutableFile(
235 exe_module_sp->GetPlatformFileSpec(), false);
236 else
237 m_options.launch_info.SetExecutableFile(target->GetProcessLaunchInfo().GetExecutableFile(), false);
238 } else {
239 if (exe_module_sp)
240 m_options.launch_info.SetExecutableFile(
241 exe_module_sp->GetPlatformFileSpec(), true);
242 else
243 m_options.launch_info.SetExecutableFile(target->GetProcessLaunchInfo().GetExecutableFile(), true);
246 if (launch_args.GetArgumentCount() == 0) {
247 m_options.launch_info.GetArguments().AppendArguments(
248 target->GetProcessLaunchInfo().GetArguments());
249 } else {
250 m_options.launch_info.GetArguments().AppendArguments(launch_args);
251 // Save the arguments for subsequent runs in the current target.
252 target->SetRunArguments(launch_args);
255 StreamString stream;
256 Status error = target->Launch(m_options.launch_info, &stream);
258 if (error.Success()) {
259 ProcessSP process_sp(target->GetProcessSP());
260 if (process_sp) {
261 // There is a race condition where this thread will return up the call
262 // stack to the main command handler and show an (lldb) prompt before
263 // HandlePrivateEvent (from PrivateStateThread) has a chance to call
264 // PushProcessIOHandler().
265 process_sp->SyncIOHandler(0, std::chrono::seconds(2));
267 llvm::StringRef data = stream.GetString();
268 if (!data.empty())
269 result.AppendMessage(data);
270 // If we didn't have a local executable, then we wouldn't have had an
271 // executable module before launch.
272 if (!exe_module_sp)
273 exe_module_sp = target->GetExecutableModule();
274 if (!exe_module_sp) {
275 result.AppendWarning("Could not get executable module after launch.");
276 } else {
278 const char *archname =
279 exe_module_sp->GetArchitecture().GetArchitectureName();
280 result.AppendMessageWithFormat(
281 "Process %" PRIu64 " launched: '%s' (%s)\n", process_sp->GetID(),
282 exe_module_sp->GetFileSpec().GetPath().c_str(), archname);
284 result.SetStatus(eReturnStatusSuccessFinishResult);
285 result.SetDidChangeProcessState(true);
286 } else {
287 result.AppendError(
288 "no error returned from Target::Launch, and target has no process");
290 } else {
291 result.AppendError(error.AsCString());
295 CommandOptionsProcessLaunch m_options;
296 OptionGroupPythonClassWithDict m_class_options;
297 OptionGroupOptions m_all_options;
300 #define LLDB_OPTIONS_process_attach
301 #include "CommandOptions.inc"
303 #pragma mark CommandObjectProcessAttach
304 class CommandObjectProcessAttach : public CommandObjectProcessLaunchOrAttach {
305 public:
306 CommandObjectProcessAttach(CommandInterpreter &interpreter)
307 : CommandObjectProcessLaunchOrAttach(
308 interpreter, "process attach", "Attach to a process.",
309 "process attach <cmd-options>", 0, "attach"),
310 m_class_options("scripted process", true, 'C', 'k', 'v', 0) {
311 m_all_options.Append(&m_options);
312 m_all_options.Append(&m_class_options, LLDB_OPT_SET_1 | LLDB_OPT_SET_2,
313 LLDB_OPT_SET_ALL);
314 m_all_options.Finalize();
317 ~CommandObjectProcessAttach() override = default;
319 Options *GetOptions() override { return &m_all_options; }
321 protected:
322 void DoExecute(Args &command, CommandReturnObject &result) override {
323 PlatformSP platform_sp(
324 GetDebugger().GetPlatformList().GetSelectedPlatform());
326 Target *target = GetDebugger().GetSelectedTarget().get();
327 // N.B. The attach should be synchronous. It doesn't help much to get the
328 // prompt back between initiating the attach and the target actually
329 // stopping. So even if the interpreter is set to be asynchronous, we wait
330 // for the stop ourselves here.
332 StateType state = eStateInvalid;
333 Process *process = m_exe_ctx.GetProcessPtr();
335 if (!StopProcessIfNecessary(process, state, result))
336 return;
338 if (target == nullptr) {
339 // If there isn't a current target create one.
340 TargetSP new_target_sp;
341 Status error;
343 error = GetDebugger().GetTargetList().CreateTarget(
344 GetDebugger(), "", "", eLoadDependentsNo,
345 nullptr, // No platform options
346 new_target_sp);
347 target = new_target_sp.get();
348 if (target == nullptr || error.Fail()) {
349 result.AppendError(error.AsCString("Error creating target"));
350 return;
354 if (!m_class_options.GetName().empty()) {
355 m_options.attach_info.SetProcessPluginName("ScriptedProcess");
356 ScriptedMetadataSP metadata_sp = std::make_shared<ScriptedMetadata>(
357 m_class_options.GetName(), m_class_options.GetStructuredData());
358 m_options.attach_info.SetScriptedMetadata(metadata_sp);
361 // Record the old executable module, we want to issue a warning if the
362 // process of attaching changed the current executable (like somebody said
363 // "file foo" then attached to a PID whose executable was bar.)
365 ModuleSP old_exec_module_sp = target->GetExecutableModule();
366 ArchSpec old_arch_spec = target->GetArchitecture();
368 StreamString stream;
369 ProcessSP process_sp;
370 const auto error = target->Attach(m_options.attach_info, &stream);
371 if (error.Success()) {
372 process_sp = target->GetProcessSP();
373 if (process_sp) {
374 result.AppendMessage(stream.GetString());
375 result.SetStatus(eReturnStatusSuccessFinishNoResult);
376 result.SetDidChangeProcessState(true);
377 } else {
378 result.AppendError(
379 "no error returned from Target::Attach, and target has no process");
381 } else {
382 result.AppendErrorWithFormat("attach failed: %s\n", error.AsCString());
385 if (!result.Succeeded())
386 return;
388 // Okay, we're done. Last step is to warn if the executable module has
389 // changed:
390 char new_path[PATH_MAX];
391 ModuleSP new_exec_module_sp(target->GetExecutableModule());
392 if (!old_exec_module_sp) {
393 // We might not have a module if we attached to a raw pid...
394 if (new_exec_module_sp) {
395 new_exec_module_sp->GetFileSpec().GetPath(new_path, PATH_MAX);
396 result.AppendMessageWithFormat("Executable module set to \"%s\".\n",
397 new_path);
399 } else if (old_exec_module_sp->GetFileSpec() !=
400 new_exec_module_sp->GetFileSpec()) {
401 char old_path[PATH_MAX];
403 old_exec_module_sp->GetFileSpec().GetPath(old_path, PATH_MAX);
404 new_exec_module_sp->GetFileSpec().GetPath(new_path, PATH_MAX);
406 result.AppendWarningWithFormat(
407 "Executable module changed from \"%s\" to \"%s\".\n", old_path,
408 new_path);
411 if (!old_arch_spec.IsValid()) {
412 result.AppendMessageWithFormat(
413 "Architecture set to: %s.\n",
414 target->GetArchitecture().GetTriple().getTriple().c_str());
415 } else if (!old_arch_spec.IsExactMatch(target->GetArchitecture())) {
416 result.AppendWarningWithFormat(
417 "Architecture changed from %s to %s.\n",
418 old_arch_spec.GetTriple().getTriple().c_str(),
419 target->GetArchitecture().GetTriple().getTriple().c_str());
422 // This supports the use-case scenario of immediately continuing the
423 // process once attached.
424 if (m_options.attach_info.GetContinueOnceAttached()) {
425 // We have made a process but haven't told the interpreter about it yet,
426 // so CheckRequirements will fail for "process continue". Set the override
427 // here:
428 ExecutionContext exe_ctx(process_sp);
429 m_interpreter.HandleCommand("process continue", eLazyBoolNo, exe_ctx, result);
433 CommandOptionsProcessAttach m_options;
434 OptionGroupPythonClassWithDict m_class_options;
435 OptionGroupOptions m_all_options;
438 // CommandObjectProcessContinue
440 #define LLDB_OPTIONS_process_continue
441 #include "CommandOptions.inc"
443 #pragma mark CommandObjectProcessContinue
445 class CommandObjectProcessContinue : public CommandObjectParsed {
446 public:
447 CommandObjectProcessContinue(CommandInterpreter &interpreter)
448 : CommandObjectParsed(
449 interpreter, "process continue",
450 "Continue execution of all threads in the current process.",
451 "process continue",
452 eCommandRequiresProcess | eCommandTryTargetAPILock |
453 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {}
455 ~CommandObjectProcessContinue() override = default;
457 protected:
458 class CommandOptions : public Options {
459 public:
460 CommandOptions() {
461 // Keep default values of all options in one place: OptionParsingStarting
462 // ()
463 OptionParsingStarting(nullptr);
466 ~CommandOptions() override = default;
468 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
469 ExecutionContext *exe_ctx) override {
470 Status error;
471 const int short_option = m_getopt_table[option_idx].val;
472 switch (short_option) {
473 case 'i':
474 if (option_arg.getAsInteger(0, m_ignore))
475 error.SetErrorStringWithFormat(
476 "invalid value for ignore option: \"%s\", should be a number.",
477 option_arg.str().c_str());
478 break;
479 case 'b':
480 m_run_to_bkpt_args.AppendArgument(option_arg);
481 m_any_bkpts_specified = true;
482 break;
483 default:
484 llvm_unreachable("Unimplemented option");
486 return error;
489 void OptionParsingStarting(ExecutionContext *execution_context) override {
490 m_ignore = 0;
491 m_run_to_bkpt_args.Clear();
492 m_any_bkpts_specified = false;
495 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
496 return llvm::ArrayRef(g_process_continue_options);
499 uint32_t m_ignore = 0;
500 Args m_run_to_bkpt_args;
501 bool m_any_bkpts_specified = false;
504 void DoExecute(Args &command, CommandReturnObject &result) override {
505 Process *process = m_exe_ctx.GetProcessPtr();
506 bool synchronous_execution = m_interpreter.GetSynchronous();
507 StateType state = process->GetState();
508 if (state == eStateStopped) {
509 if (m_options.m_ignore > 0) {
510 ThreadSP sel_thread_sp(GetDefaultThread()->shared_from_this());
511 if (sel_thread_sp) {
512 StopInfoSP stop_info_sp = sel_thread_sp->GetStopInfo();
513 if (stop_info_sp &&
514 stop_info_sp->GetStopReason() == eStopReasonBreakpoint) {
515 lldb::break_id_t bp_site_id =
516 (lldb::break_id_t)stop_info_sp->GetValue();
517 BreakpointSiteSP bp_site_sp(
518 process->GetBreakpointSiteList().FindByID(bp_site_id));
519 if (bp_site_sp) {
520 const size_t num_owners = bp_site_sp->GetNumberOfOwners();
521 for (size_t i = 0; i < num_owners; i++) {
522 Breakpoint &bp_ref =
523 bp_site_sp->GetOwnerAtIndex(i)->GetBreakpoint();
524 if (!bp_ref.IsInternal()) {
525 bp_ref.SetIgnoreCount(m_options.m_ignore);
533 Target *target = m_exe_ctx.GetTargetPtr();
534 BreakpointIDList run_to_bkpt_ids;
535 // Don't pass an empty run_to_breakpoint list, as Verify will look for the
536 // default breakpoint.
537 if (m_options.m_run_to_bkpt_args.GetArgumentCount() > 0)
538 CommandObjectMultiwordBreakpoint::VerifyBreakpointOrLocationIDs(
539 m_options.m_run_to_bkpt_args, target, result, &run_to_bkpt_ids,
540 BreakpointName::Permissions::disablePerm);
541 if (!result.Succeeded()) {
542 return;
544 result.Clear();
545 if (m_options.m_any_bkpts_specified && run_to_bkpt_ids.GetSize() == 0) {
546 result.AppendError("continue-to breakpoints did not specify any actual "
547 "breakpoints or locations");
548 return;
551 // First figure out which breakpoints & locations were specified by the
552 // user:
553 size_t num_run_to_bkpt_ids = run_to_bkpt_ids.GetSize();
554 std::vector<break_id_t> bkpts_disabled;
555 std::vector<BreakpointID> locs_disabled;
556 if (num_run_to_bkpt_ids != 0) {
557 // Go through the ID's specified, and separate the breakpoints from are
558 // the breakpoint.location specifications since the latter require
559 // special handling. We also figure out whether there's at least one
560 // specifier in the set that is enabled.
561 BreakpointList &bkpt_list = target->GetBreakpointList();
562 std::unordered_set<break_id_t> bkpts_seen;
563 std::unordered_set<break_id_t> bkpts_with_locs_seen;
564 BreakpointIDList with_locs;
565 bool any_enabled = false;
567 for (size_t idx = 0; idx < num_run_to_bkpt_ids; idx++) {
568 BreakpointID bkpt_id = run_to_bkpt_ids.GetBreakpointIDAtIndex(idx);
569 break_id_t bp_id = bkpt_id.GetBreakpointID();
570 break_id_t loc_id = bkpt_id.GetLocationID();
571 BreakpointSP bp_sp
572 = bkpt_list.FindBreakpointByID(bp_id);
573 // Note, VerifyBreakpointOrLocationIDs checks for existence, so we
574 // don't need to do it again here.
575 if (bp_sp->IsEnabled()) {
576 if (loc_id == LLDB_INVALID_BREAK_ID) {
577 // A breakpoint (without location) was specified. Make sure that
578 // at least one of the locations is enabled.
579 size_t num_locations = bp_sp->GetNumLocations();
580 for (size_t loc_idx = 0; loc_idx < num_locations; loc_idx++) {
581 BreakpointLocationSP loc_sp
582 = bp_sp->GetLocationAtIndex(loc_idx);
583 if (loc_sp->IsEnabled()) {
584 any_enabled = true;
585 break;
588 } else {
589 // A location was specified, check if it was enabled:
590 BreakpointLocationSP loc_sp = bp_sp->FindLocationByID(loc_id);
591 if (loc_sp->IsEnabled())
592 any_enabled = true;
595 // Then sort the bp & bp.loc entries for later use:
596 if (bkpt_id.GetLocationID() == LLDB_INVALID_BREAK_ID)
597 bkpts_seen.insert(bkpt_id.GetBreakpointID());
598 else {
599 bkpts_with_locs_seen.insert(bkpt_id.GetBreakpointID());
600 with_locs.AddBreakpointID(bkpt_id);
604 // Do all the error checking here so once we start disabling we don't
605 // have to back out half-way through.
607 // Make sure at least one of the specified breakpoints is enabled.
608 if (!any_enabled) {
609 result.AppendError("at least one of the continue-to breakpoints must "
610 "be enabled.");
611 return;
614 // Also, if you specify BOTH a breakpoint and one of it's locations,
615 // we flag that as an error, since it won't do what you expect, the
616 // breakpoint directive will mean "run to all locations", which is not
617 // what the location directive means...
618 for (break_id_t bp_id : bkpts_with_locs_seen) {
619 if (bkpts_seen.count(bp_id)) {
620 result.AppendErrorWithFormatv("can't specify both a breakpoint and "
621 "one of its locations: {0}", bp_id);
625 // Now go through the breakpoints in the target, disabling all the ones
626 // that the user didn't mention:
627 for (BreakpointSP bp_sp : bkpt_list.Breakpoints()) {
628 break_id_t bp_id = bp_sp->GetID();
629 // Handle the case where no locations were specified. Note we don't
630 // have to worry about the case where a breakpoint and one of its
631 // locations are both in the lists, we've already disallowed that.
632 if (!bkpts_with_locs_seen.count(bp_id)) {
633 if (!bkpts_seen.count(bp_id) && bp_sp->IsEnabled()) {
634 bkpts_disabled.push_back(bp_id);
635 bp_sp->SetEnabled(false);
637 continue;
639 // Next, handle the case where a location was specified:
640 // Run through all the locations of this breakpoint and disable
641 // the ones that aren't on our "with locations" BreakpointID list:
642 size_t num_locations = bp_sp->GetNumLocations();
643 BreakpointID tmp_id(bp_id, LLDB_INVALID_BREAK_ID);
644 for (size_t loc_idx = 0; loc_idx < num_locations; loc_idx++) {
645 BreakpointLocationSP loc_sp = bp_sp->GetLocationAtIndex(loc_idx);
646 tmp_id.SetBreakpointLocationID(loc_idx);
647 size_t position = 0;
648 if (!with_locs.FindBreakpointID(tmp_id, &position)
649 && loc_sp->IsEnabled()) {
650 locs_disabled.push_back(tmp_id);
651 loc_sp->SetEnabled(false);
657 { // Scope for thread list mutex:
658 std::lock_guard<std::recursive_mutex> guard(
659 process->GetThreadList().GetMutex());
660 const uint32_t num_threads = process->GetThreadList().GetSize();
662 // Set the actions that the threads should each take when resuming
663 for (uint32_t idx = 0; idx < num_threads; ++idx) {
664 const bool override_suspend = false;
665 process->GetThreadList().GetThreadAtIndex(idx)->SetResumeState(
666 eStateRunning, override_suspend);
670 const uint32_t iohandler_id = process->GetIOHandlerID();
672 StreamString stream;
673 Status error;
674 // For now we can only do -b with synchronous:
675 bool old_sync = GetDebugger().GetAsyncExecution();
677 if (run_to_bkpt_ids.GetSize() != 0) {
678 GetDebugger().SetAsyncExecution(false);
679 synchronous_execution = true;
681 if (synchronous_execution)
682 error = process->ResumeSynchronous(&stream);
683 else
684 error = process->Resume();
686 if (run_to_bkpt_ids.GetSize() != 0) {
687 GetDebugger().SetAsyncExecution(old_sync);
690 // Now re-enable the breakpoints we disabled:
691 BreakpointList &bkpt_list = target->GetBreakpointList();
692 for (break_id_t bp_id : bkpts_disabled) {
693 BreakpointSP bp_sp = bkpt_list.FindBreakpointByID(bp_id);
694 if (bp_sp)
695 bp_sp->SetEnabled(true);
697 for (const BreakpointID &bkpt_id : locs_disabled) {
698 BreakpointSP bp_sp
699 = bkpt_list.FindBreakpointByID(bkpt_id.GetBreakpointID());
700 if (bp_sp) {
701 BreakpointLocationSP loc_sp
702 = bp_sp->FindLocationByID(bkpt_id.GetLocationID());
703 if (loc_sp)
704 loc_sp->SetEnabled(true);
708 if (error.Success()) {
709 // There is a race condition where this thread will return up the call
710 // stack to the main command handler and show an (lldb) prompt before
711 // HandlePrivateEvent (from PrivateStateThread) has a chance to call
712 // PushProcessIOHandler().
713 process->SyncIOHandler(iohandler_id, std::chrono::seconds(2));
715 result.AppendMessageWithFormat("Process %" PRIu64 " resuming\n",
716 process->GetID());
717 if (synchronous_execution) {
718 // If any state changed events had anything to say, add that to the
719 // result
720 result.AppendMessage(stream.GetString());
722 result.SetDidChangeProcessState(true);
723 result.SetStatus(eReturnStatusSuccessFinishNoResult);
724 } else {
725 result.SetStatus(eReturnStatusSuccessContinuingNoResult);
727 } else {
728 result.AppendErrorWithFormat("Failed to resume process: %s.\n",
729 error.AsCString());
731 } else {
732 result.AppendErrorWithFormat(
733 "Process cannot be continued from its current state (%s).\n",
734 StateAsCString(state));
738 Options *GetOptions() override { return &m_options; }
740 CommandOptions m_options;
743 // CommandObjectProcessDetach
744 #define LLDB_OPTIONS_process_detach
745 #include "CommandOptions.inc"
747 #pragma mark CommandObjectProcessDetach
749 class CommandObjectProcessDetach : public CommandObjectParsed {
750 public:
751 class CommandOptions : public Options {
752 public:
753 CommandOptions() { OptionParsingStarting(nullptr); }
755 ~CommandOptions() override = default;
757 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
758 ExecutionContext *execution_context) override {
759 Status error;
760 const int short_option = m_getopt_table[option_idx].val;
762 switch (short_option) {
763 case 's':
764 bool tmp_result;
765 bool success;
766 tmp_result = OptionArgParser::ToBoolean(option_arg, false, &success);
767 if (!success)
768 error.SetErrorStringWithFormat("invalid boolean option: \"%s\"",
769 option_arg.str().c_str());
770 else {
771 if (tmp_result)
772 m_keep_stopped = eLazyBoolYes;
773 else
774 m_keep_stopped = eLazyBoolNo;
776 break;
777 default:
778 llvm_unreachable("Unimplemented option");
780 return error;
783 void OptionParsingStarting(ExecutionContext *execution_context) override {
784 m_keep_stopped = eLazyBoolCalculate;
787 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
788 return llvm::ArrayRef(g_process_detach_options);
791 // Instance variables to hold the values for command options.
792 LazyBool m_keep_stopped;
795 CommandObjectProcessDetach(CommandInterpreter &interpreter)
796 : CommandObjectParsed(interpreter, "process detach",
797 "Detach from the current target process.",
798 "process detach",
799 eCommandRequiresProcess | eCommandTryTargetAPILock |
800 eCommandProcessMustBeLaunched) {}
802 ~CommandObjectProcessDetach() override = default;
804 Options *GetOptions() override { return &m_options; }
806 protected:
807 void DoExecute(Args &command, CommandReturnObject &result) override {
808 Process *process = m_exe_ctx.GetProcessPtr();
809 // FIXME: This will be a Command Option:
810 bool keep_stopped;
811 if (m_options.m_keep_stopped == eLazyBoolCalculate) {
812 // Check the process default:
813 keep_stopped = process->GetDetachKeepsStopped();
814 } else if (m_options.m_keep_stopped == eLazyBoolYes)
815 keep_stopped = true;
816 else
817 keep_stopped = false;
819 Status error(process->Detach(keep_stopped));
820 if (error.Success()) {
821 result.SetStatus(eReturnStatusSuccessFinishResult);
822 } else {
823 result.AppendErrorWithFormat("Detach failed: %s\n", error.AsCString());
827 CommandOptions m_options;
830 // CommandObjectProcessConnect
831 #define LLDB_OPTIONS_process_connect
832 #include "CommandOptions.inc"
834 #pragma mark CommandObjectProcessConnect
836 class CommandObjectProcessConnect : public CommandObjectParsed {
837 public:
838 class CommandOptions : public Options {
839 public:
840 CommandOptions() {
841 // Keep default values of all options in one place: OptionParsingStarting
842 // ()
843 OptionParsingStarting(nullptr);
846 ~CommandOptions() override = default;
848 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
849 ExecutionContext *execution_context) override {
850 Status error;
851 const int short_option = m_getopt_table[option_idx].val;
853 switch (short_option) {
854 case 'p':
855 plugin_name.assign(std::string(option_arg));
856 break;
858 default:
859 llvm_unreachable("Unimplemented option");
861 return error;
864 void OptionParsingStarting(ExecutionContext *execution_context) override {
865 plugin_name.clear();
868 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
869 return llvm::ArrayRef(g_process_connect_options);
872 // Instance variables to hold the values for command options.
874 std::string plugin_name;
877 CommandObjectProcessConnect(CommandInterpreter &interpreter)
878 : CommandObjectParsed(interpreter, "process connect",
879 "Connect to a remote debug service.",
880 "process connect <remote-url>", 0) {
881 CommandArgumentData connect_arg{eArgTypeConnectURL, eArgRepeatPlain};
882 m_arguments.push_back({connect_arg});
885 ~CommandObjectProcessConnect() override = default;
887 Options *GetOptions() override { return &m_options; }
889 protected:
890 void DoExecute(Args &command, CommandReturnObject &result) override {
891 if (command.GetArgumentCount() != 1) {
892 result.AppendErrorWithFormat(
893 "'%s' takes exactly one argument:\nUsage: %s\n", m_cmd_name.c_str(),
894 m_cmd_syntax.c_str());
895 return;
898 Process *process = m_exe_ctx.GetProcessPtr();
899 if (process && process->IsAlive()) {
900 result.AppendErrorWithFormat(
901 "Process %" PRIu64
902 " is currently being debugged, kill the process before connecting.\n",
903 process->GetID());
904 return;
907 const char *plugin_name = nullptr;
908 if (!m_options.plugin_name.empty())
909 plugin_name = m_options.plugin_name.c_str();
911 Status error;
912 Debugger &debugger = GetDebugger();
913 PlatformSP platform_sp = m_interpreter.GetPlatform(true);
914 ProcessSP process_sp =
915 debugger.GetAsyncExecution()
916 ? platform_sp->ConnectProcess(
917 command.GetArgumentAtIndex(0), plugin_name, debugger,
918 debugger.GetSelectedTarget().get(), error)
919 : platform_sp->ConnectProcessSynchronous(
920 command.GetArgumentAtIndex(0), plugin_name, debugger,
921 result.GetOutputStream(), debugger.GetSelectedTarget().get(),
922 error);
923 if (error.Fail() || process_sp == nullptr) {
924 result.AppendError(error.AsCString("Error connecting to the process"));
928 CommandOptions m_options;
931 // CommandObjectProcessPlugin
932 #pragma mark CommandObjectProcessPlugin
934 class CommandObjectProcessPlugin : public CommandObjectProxy {
935 public:
936 CommandObjectProcessPlugin(CommandInterpreter &interpreter)
937 : CommandObjectProxy(
938 interpreter, "process plugin",
939 "Send a custom command to the current target process plug-in.",
940 "process plugin <args>", 0) {}
942 ~CommandObjectProcessPlugin() override = default;
944 CommandObject *GetProxyCommandObject() override {
945 Process *process = m_interpreter.GetExecutionContext().GetProcessPtr();
946 if (process)
947 return process->GetPluginCommandObject();
948 return nullptr;
952 // CommandObjectProcessLoad
953 #define LLDB_OPTIONS_process_load
954 #include "CommandOptions.inc"
956 #pragma mark CommandObjectProcessLoad
958 class CommandObjectProcessLoad : public CommandObjectParsed {
959 public:
960 class CommandOptions : public Options {
961 public:
962 CommandOptions() {
963 // Keep default values of all options in one place: OptionParsingStarting
964 // ()
965 OptionParsingStarting(nullptr);
968 ~CommandOptions() override = default;
970 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
971 ExecutionContext *execution_context) override {
972 Status error;
973 const int short_option = m_getopt_table[option_idx].val;
974 switch (short_option) {
975 case 'i':
976 do_install = true;
977 if (!option_arg.empty())
978 install_path.SetFile(option_arg, FileSpec::Style::native);
979 break;
980 default:
981 llvm_unreachable("Unimplemented option");
983 return error;
986 void OptionParsingStarting(ExecutionContext *execution_context) override {
987 do_install = false;
988 install_path.Clear();
991 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
992 return llvm::ArrayRef(g_process_load_options);
995 // Instance variables to hold the values for command options.
996 bool do_install;
997 FileSpec install_path;
1000 CommandObjectProcessLoad(CommandInterpreter &interpreter)
1001 : CommandObjectParsed(interpreter, "process load",
1002 "Load a shared library into the current process.",
1003 "process load <filename> [<filename> ...]",
1004 eCommandRequiresProcess | eCommandTryTargetAPILock |
1005 eCommandProcessMustBeLaunched |
1006 eCommandProcessMustBePaused) {
1007 CommandArgumentData file_arg{eArgTypePath, eArgRepeatPlus};
1008 m_arguments.push_back({file_arg});
1011 ~CommandObjectProcessLoad() override = default;
1013 void
1014 HandleArgumentCompletion(CompletionRequest &request,
1015 OptionElementVector &opt_element_vector) override {
1016 if (!m_exe_ctx.HasProcessScope())
1017 return;
1019 lldb_private::CommandCompletions::InvokeCommonCompletionCallbacks(
1020 GetCommandInterpreter(), lldb::eDiskFileCompletion, request, nullptr);
1023 Options *GetOptions() override { return &m_options; }
1025 protected:
1026 void DoExecute(Args &command, CommandReturnObject &result) override {
1027 Process *process = m_exe_ctx.GetProcessPtr();
1029 for (auto &entry : command.entries()) {
1030 Status error;
1031 PlatformSP platform = process->GetTarget().GetPlatform();
1032 llvm::StringRef image_path = entry.ref();
1033 uint32_t image_token = LLDB_INVALID_IMAGE_TOKEN;
1035 if (!m_options.do_install) {
1036 FileSpec image_spec(image_path);
1037 platform->ResolveRemotePath(image_spec, image_spec);
1038 image_token =
1039 platform->LoadImage(process, FileSpec(), image_spec, error);
1040 } else if (m_options.install_path) {
1041 FileSpec image_spec(image_path);
1042 FileSystem::Instance().Resolve(image_spec);
1043 platform->ResolveRemotePath(m_options.install_path,
1044 m_options.install_path);
1045 image_token = platform->LoadImage(process, image_spec,
1046 m_options.install_path, error);
1047 } else {
1048 FileSpec image_spec(image_path);
1049 FileSystem::Instance().Resolve(image_spec);
1050 image_token =
1051 platform->LoadImage(process, image_spec, FileSpec(), error);
1054 if (image_token != LLDB_INVALID_IMAGE_TOKEN) {
1055 result.AppendMessageWithFormat(
1056 "Loading \"%s\"...ok\nImage %u loaded.\n", image_path.str().c_str(),
1057 image_token);
1058 result.SetStatus(eReturnStatusSuccessFinishResult);
1059 } else {
1060 result.AppendErrorWithFormat("failed to load '%s': %s",
1061 image_path.str().c_str(),
1062 error.AsCString());
1067 CommandOptions m_options;
1070 // CommandObjectProcessUnload
1071 #pragma mark CommandObjectProcessUnload
1073 class CommandObjectProcessUnload : public CommandObjectParsed {
1074 public:
1075 CommandObjectProcessUnload(CommandInterpreter &interpreter)
1076 : CommandObjectParsed(
1077 interpreter, "process unload",
1078 "Unload a shared library from the current process using the index "
1079 "returned by a previous call to \"process load\".",
1080 "process unload <index>",
1081 eCommandRequiresProcess | eCommandTryTargetAPILock |
1082 eCommandProcessMustBeLaunched | eCommandProcessMustBePaused) {
1083 CommandArgumentData load_idx_arg{eArgTypeUnsignedInteger, eArgRepeatPlain};
1084 m_arguments.push_back({load_idx_arg});
1087 ~CommandObjectProcessUnload() override = default;
1089 void
1090 HandleArgumentCompletion(CompletionRequest &request,
1091 OptionElementVector &opt_element_vector) override {
1093 if (request.GetCursorIndex() || !m_exe_ctx.HasProcessScope())
1094 return;
1096 Process *process = m_exe_ctx.GetProcessPtr();
1098 const std::vector<lldb::addr_t> &tokens = process->GetImageTokens();
1099 const size_t token_num = tokens.size();
1100 for (size_t i = 0; i < token_num; ++i) {
1101 if (tokens[i] == LLDB_INVALID_IMAGE_TOKEN)
1102 continue;
1103 request.TryCompleteCurrentArg(std::to_string(i));
1107 protected:
1108 void DoExecute(Args &command, CommandReturnObject &result) override {
1109 Process *process = m_exe_ctx.GetProcessPtr();
1111 for (auto &entry : command.entries()) {
1112 uint32_t image_token;
1113 if (entry.ref().getAsInteger(0, image_token)) {
1114 result.AppendErrorWithFormat("invalid image index argument '%s'",
1115 entry.ref().str().c_str());
1116 break;
1117 } else {
1118 Status error(process->GetTarget().GetPlatform()->UnloadImage(
1119 process, image_token));
1120 if (error.Success()) {
1121 result.AppendMessageWithFormat(
1122 "Unloading shared library with index %u...ok\n", image_token);
1123 result.SetStatus(eReturnStatusSuccessFinishResult);
1124 } else {
1125 result.AppendErrorWithFormat("failed to unload image: %s",
1126 error.AsCString());
1127 break;
1134 // CommandObjectProcessSignal
1135 #pragma mark CommandObjectProcessSignal
1137 class CommandObjectProcessSignal : public CommandObjectParsed {
1138 public:
1139 CommandObjectProcessSignal(CommandInterpreter &interpreter)
1140 : CommandObjectParsed(
1141 interpreter, "process signal",
1142 "Send a UNIX signal to the current target process.", nullptr,
1143 eCommandRequiresProcess | eCommandTryTargetAPILock) {
1144 CommandArgumentEntry arg;
1145 CommandArgumentData signal_arg;
1147 // Define the first (and only) variant of this arg.
1148 signal_arg.arg_type = eArgTypeUnixSignal;
1149 signal_arg.arg_repetition = eArgRepeatPlain;
1151 // There is only one variant this argument could be; put it into the
1152 // argument entry.
1153 arg.push_back(signal_arg);
1155 // Push the data for the first argument into the m_arguments vector.
1156 m_arguments.push_back(arg);
1159 ~CommandObjectProcessSignal() override = default;
1161 void
1162 HandleArgumentCompletion(CompletionRequest &request,
1163 OptionElementVector &opt_element_vector) override {
1164 if (!m_exe_ctx.HasProcessScope() || request.GetCursorIndex() != 0)
1165 return;
1167 UnixSignalsSP signals = m_exe_ctx.GetProcessPtr()->GetUnixSignals();
1168 int signo = signals->GetFirstSignalNumber();
1169 while (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1170 request.TryCompleteCurrentArg(signals->GetSignalAsStringRef(signo));
1171 signo = signals->GetNextSignalNumber(signo);
1175 protected:
1176 void DoExecute(Args &command, CommandReturnObject &result) override {
1177 Process *process = m_exe_ctx.GetProcessPtr();
1179 if (command.GetArgumentCount() == 1) {
1180 int signo = LLDB_INVALID_SIGNAL_NUMBER;
1182 const char *signal_name = command.GetArgumentAtIndex(0);
1183 if (::isxdigit(signal_name[0])) {
1184 if (!llvm::to_integer(signal_name, signo))
1185 signo = LLDB_INVALID_SIGNAL_NUMBER;
1186 } else
1187 signo = process->GetUnixSignals()->GetSignalNumberFromName(signal_name);
1189 if (signo == LLDB_INVALID_SIGNAL_NUMBER) {
1190 result.AppendErrorWithFormat("Invalid signal argument '%s'.\n",
1191 command.GetArgumentAtIndex(0));
1192 } else {
1193 Status error(process->Signal(signo));
1194 if (error.Success()) {
1195 result.SetStatus(eReturnStatusSuccessFinishResult);
1196 } else {
1197 result.AppendErrorWithFormat("Failed to send signal %i: %s\n", signo,
1198 error.AsCString());
1201 } else {
1202 result.AppendErrorWithFormat(
1203 "'%s' takes exactly one signal number argument:\nUsage: %s\n",
1204 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1209 // CommandObjectProcessInterrupt
1210 #pragma mark CommandObjectProcessInterrupt
1212 class CommandObjectProcessInterrupt : public CommandObjectParsed {
1213 public:
1214 CommandObjectProcessInterrupt(CommandInterpreter &interpreter)
1215 : CommandObjectParsed(interpreter, "process interrupt",
1216 "Interrupt the current target process.",
1217 "process interrupt",
1218 eCommandRequiresProcess | eCommandTryTargetAPILock |
1219 eCommandProcessMustBeLaunched) {}
1221 ~CommandObjectProcessInterrupt() override = default;
1223 protected:
1224 void DoExecute(Args &command, CommandReturnObject &result) override {
1225 Process *process = m_exe_ctx.GetProcessPtr();
1226 if (process == nullptr) {
1227 result.AppendError("no process to halt");
1228 return;
1231 bool clear_thread_plans = true;
1232 Status error(process->Halt(clear_thread_plans));
1233 if (error.Success()) {
1234 result.SetStatus(eReturnStatusSuccessFinishResult);
1235 } else {
1236 result.AppendErrorWithFormat("Failed to halt process: %s\n",
1237 error.AsCString());
1242 // CommandObjectProcessKill
1243 #pragma mark CommandObjectProcessKill
1245 class CommandObjectProcessKill : public CommandObjectParsed {
1246 public:
1247 CommandObjectProcessKill(CommandInterpreter &interpreter)
1248 : CommandObjectParsed(interpreter, "process kill",
1249 "Terminate the current target process.",
1250 "process kill",
1251 eCommandRequiresProcess | eCommandTryTargetAPILock |
1252 eCommandProcessMustBeLaunched) {}
1254 ~CommandObjectProcessKill() override = default;
1256 protected:
1257 void DoExecute(Args &command, CommandReturnObject &result) override {
1258 Process *process = m_exe_ctx.GetProcessPtr();
1259 if (process == nullptr) {
1260 result.AppendError("no process to kill");
1261 return;
1264 Status error(process->Destroy(true));
1265 if (error.Success()) {
1266 result.SetStatus(eReturnStatusSuccessFinishResult);
1267 } else {
1268 result.AppendErrorWithFormat("Failed to kill process: %s\n",
1269 error.AsCString());
1274 #define LLDB_OPTIONS_process_save_core
1275 #include "CommandOptions.inc"
1277 class CommandObjectProcessSaveCore : public CommandObjectParsed {
1278 public:
1279 CommandObjectProcessSaveCore(CommandInterpreter &interpreter)
1280 : CommandObjectParsed(
1281 interpreter, "process save-core",
1282 "Save the current process as a core file using an "
1283 "appropriate file type.",
1284 "process save-core [-s corefile-style -p plugin-name] FILE",
1285 eCommandRequiresProcess | eCommandTryTargetAPILock |
1286 eCommandProcessMustBeLaunched) {
1287 CommandArgumentData file_arg{eArgTypePath, eArgRepeatPlain};
1288 m_arguments.push_back({file_arg});
1291 ~CommandObjectProcessSaveCore() override = default;
1293 Options *GetOptions() override { return &m_options; }
1295 void
1296 HandleArgumentCompletion(CompletionRequest &request,
1297 OptionElementVector &opt_element_vector) override {
1298 CommandCompletions::InvokeCommonCompletionCallbacks(
1299 GetCommandInterpreter(), lldb::eDiskFileCompletion, request, nullptr);
1302 class CommandOptions : public Options {
1303 public:
1304 CommandOptions() = default;
1306 ~CommandOptions() override = default;
1308 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1309 return llvm::ArrayRef(g_process_save_core_options);
1312 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1313 ExecutionContext *execution_context) override {
1314 const int short_option = m_getopt_table[option_idx].val;
1315 Status error;
1317 switch (short_option) {
1318 case 'p':
1319 m_requested_plugin_name = option_arg.str();
1320 break;
1321 case 's':
1322 m_requested_save_core_style =
1323 (lldb::SaveCoreStyle)OptionArgParser::ToOptionEnum(
1324 option_arg, GetDefinitions()[option_idx].enum_values,
1325 eSaveCoreUnspecified, error);
1326 break;
1327 default:
1328 llvm_unreachable("Unimplemented option");
1331 return {};
1334 void OptionParsingStarting(ExecutionContext *execution_context) override {
1335 m_requested_save_core_style = eSaveCoreUnspecified;
1336 m_requested_plugin_name.clear();
1339 // Instance variables to hold the values for command options.
1340 SaveCoreStyle m_requested_save_core_style = eSaveCoreUnspecified;
1341 std::string m_requested_plugin_name;
1344 protected:
1345 void DoExecute(Args &command, CommandReturnObject &result) override {
1346 ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1347 if (process_sp) {
1348 if (command.GetArgumentCount() == 1) {
1349 FileSpec output_file(command.GetArgumentAtIndex(0));
1350 FileSystem::Instance().Resolve(output_file);
1351 SaveCoreStyle corefile_style = m_options.m_requested_save_core_style;
1352 Status error =
1353 PluginManager::SaveCore(process_sp, output_file, corefile_style,
1354 m_options.m_requested_plugin_name);
1355 if (error.Success()) {
1356 if (corefile_style == SaveCoreStyle::eSaveCoreDirtyOnly ||
1357 corefile_style == SaveCoreStyle::eSaveCoreStackOnly) {
1358 result.AppendMessageWithFormat(
1359 "\nModified-memory or stack-memory only corefile "
1360 "created. This corefile may \n"
1361 "not show library/framework/app binaries "
1362 "on a different system, or when \n"
1363 "those binaries have "
1364 "been updated/modified. Copies are not included\n"
1365 "in this corefile. Use --style full to include all "
1366 "process memory.\n");
1368 result.SetStatus(eReturnStatusSuccessFinishResult);
1369 } else {
1370 result.AppendErrorWithFormat(
1371 "Failed to save core file for process: %s\n", error.AsCString());
1373 } else {
1374 result.AppendErrorWithFormat("'%s' takes one arguments:\nUsage: %s\n",
1375 m_cmd_name.c_str(), m_cmd_syntax.c_str());
1377 } else {
1378 result.AppendError("invalid process");
1382 CommandOptions m_options;
1385 // CommandObjectProcessStatus
1386 #pragma mark CommandObjectProcessStatus
1387 #define LLDB_OPTIONS_process_status
1388 #include "CommandOptions.inc"
1390 class CommandObjectProcessStatus : public CommandObjectParsed {
1391 public:
1392 CommandObjectProcessStatus(CommandInterpreter &interpreter)
1393 : CommandObjectParsed(
1394 interpreter, "process status",
1395 "Show status and stop location for the current target process.",
1396 "process status",
1397 eCommandRequiresProcess | eCommandTryTargetAPILock) {}
1399 ~CommandObjectProcessStatus() override = default;
1401 Options *GetOptions() override { return &m_options; }
1403 class CommandOptions : public Options {
1404 public:
1405 CommandOptions() = default;
1407 ~CommandOptions() override = default;
1409 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1410 ExecutionContext *execution_context) override {
1411 const int short_option = m_getopt_table[option_idx].val;
1413 switch (short_option) {
1414 case 'v':
1415 m_verbose = true;
1416 break;
1417 default:
1418 llvm_unreachable("Unimplemented option");
1421 return {};
1424 void OptionParsingStarting(ExecutionContext *execution_context) override {
1425 m_verbose = false;
1428 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1429 return llvm::ArrayRef(g_process_status_options);
1432 // Instance variables to hold the values for command options.
1433 bool m_verbose = false;
1436 protected:
1437 void DoExecute(Args &command, CommandReturnObject &result) override {
1438 Stream &strm = result.GetOutputStream();
1439 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1441 // No need to check "process" for validity as eCommandRequiresProcess
1442 // ensures it is valid
1443 Process *process = m_exe_ctx.GetProcessPtr();
1444 const bool only_threads_with_stop_reason = true;
1445 const uint32_t start_frame = 0;
1446 const uint32_t num_frames = 1;
1447 const uint32_t num_frames_with_source = 1;
1448 const bool stop_format = true;
1449 process->GetStatus(strm);
1450 process->GetThreadStatus(strm, only_threads_with_stop_reason, start_frame,
1451 num_frames, num_frames_with_source, stop_format);
1453 if (m_options.m_verbose) {
1454 addr_t code_mask = process->GetCodeAddressMask();
1455 addr_t data_mask = process->GetDataAddressMask();
1456 if (code_mask != 0) {
1457 int bits = std::bitset<64>(~code_mask).count();
1458 result.AppendMessageWithFormat(
1459 "Addressable code address mask: 0x%" PRIx64 "\n", code_mask);
1460 result.AppendMessageWithFormat(
1461 "Addressable data address mask: 0x%" PRIx64 "\n", data_mask);
1462 result.AppendMessageWithFormat(
1463 "Number of bits used in addressing (code): %d\n", bits);
1466 PlatformSP platform_sp = process->GetTarget().GetPlatform();
1467 if (!platform_sp) {
1468 result.AppendError("Couldn'retrieve the target's platform");
1469 return;
1472 auto expected_crash_info =
1473 platform_sp->FetchExtendedCrashInformation(*process);
1475 if (!expected_crash_info) {
1476 result.AppendError(llvm::toString(expected_crash_info.takeError()));
1477 return;
1480 StructuredData::DictionarySP crash_info_sp = *expected_crash_info;
1482 if (crash_info_sp) {
1483 strm.EOL();
1484 strm.PutCString("Extended Crash Information:\n");
1485 crash_info_sp->GetDescription(strm);
1490 private:
1491 CommandOptions m_options;
1494 // CommandObjectProcessHandle
1495 #define LLDB_OPTIONS_process_handle
1496 #include "CommandOptions.inc"
1498 #pragma mark CommandObjectProcessHandle
1500 class CommandObjectProcessHandle : public CommandObjectParsed {
1501 public:
1502 class CommandOptions : public Options {
1503 public:
1504 CommandOptions() { OptionParsingStarting(nullptr); }
1506 ~CommandOptions() override = default;
1508 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1509 ExecutionContext *execution_context) override {
1510 Status error;
1511 const int short_option = m_getopt_table[option_idx].val;
1513 switch (short_option) {
1514 case 'c':
1515 do_clear = true;
1516 break;
1517 case 'd':
1518 dummy = true;
1519 break;
1520 case 's':
1521 stop = std::string(option_arg);
1522 break;
1523 case 'n':
1524 notify = std::string(option_arg);
1525 break;
1526 case 'p':
1527 pass = std::string(option_arg);
1528 break;
1529 case 't':
1530 only_target_values = true;
1531 break;
1532 default:
1533 llvm_unreachable("Unimplemented option");
1535 return error;
1538 void OptionParsingStarting(ExecutionContext *execution_context) override {
1539 stop.clear();
1540 notify.clear();
1541 pass.clear();
1542 only_target_values = false;
1543 do_clear = false;
1544 dummy = false;
1547 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1548 return llvm::ArrayRef(g_process_handle_options);
1551 // Instance variables to hold the values for command options.
1553 std::string stop;
1554 std::string notify;
1555 std::string pass;
1556 bool only_target_values = false;
1557 bool do_clear = false;
1558 bool dummy = false;
1561 CommandObjectProcessHandle(CommandInterpreter &interpreter)
1562 : CommandObjectParsed(interpreter, "process handle",
1563 "Manage LLDB handling of OS signals for the "
1564 "current target process. Defaults to showing "
1565 "current policy.",
1566 nullptr) {
1567 SetHelpLong("\nIf no signals are specified but one or more actions are, "
1568 "and there is a live process, update them all. If no action "
1569 "is specified, list the current values.\n"
1570 "If you specify actions with no target (e.g. in an init file) "
1571 "or in a target with no process "
1572 "the values will get copied into subsequent targets, but "
1573 "lldb won't be able to spell-check the options since it can't "
1574 "know which signal set will later be in force."
1575 "\nYou can see the signal modifications held by the target"
1576 "by passing the -t option."
1577 "\nYou can also clear the target modification for a signal"
1578 "by passing the -c option");
1579 CommandArgumentEntry arg;
1580 CommandArgumentData signal_arg;
1582 signal_arg.arg_type = eArgTypeUnixSignal;
1583 signal_arg.arg_repetition = eArgRepeatStar;
1585 arg.push_back(signal_arg);
1587 m_arguments.push_back(arg);
1590 ~CommandObjectProcessHandle() override = default;
1592 Options *GetOptions() override { return &m_options; }
1594 bool VerifyCommandOptionValue(const std::string &option, int &real_value) {
1595 bool okay = true;
1596 bool success = false;
1597 bool tmp_value = OptionArgParser::ToBoolean(option, false, &success);
1599 if (success && tmp_value)
1600 real_value = 1;
1601 else if (success && !tmp_value)
1602 real_value = 0;
1603 else {
1604 // If the value isn't 'true' or 'false', it had better be 0 or 1.
1605 if (!llvm::to_integer(option, real_value))
1606 real_value = 3;
1607 if (real_value != 0 && real_value != 1)
1608 okay = false;
1611 return okay;
1614 void PrintSignalHeader(Stream &str) {
1615 str.Printf("NAME PASS STOP NOTIFY\n");
1616 str.Printf("=========== ===== ===== ======\n");
1619 void PrintSignal(Stream &str, int32_t signo, llvm::StringRef sig_name,
1620 const UnixSignalsSP &signals_sp) {
1621 bool stop;
1622 bool suppress;
1623 bool notify;
1625 str.Format("{0, -11} ", sig_name);
1626 if (signals_sp->GetSignalInfo(signo, suppress, stop, notify)) {
1627 bool pass = !suppress;
1628 str.Printf("%s %s %s", (pass ? "true " : "false"),
1629 (stop ? "true " : "false"), (notify ? "true " : "false"));
1631 str.Printf("\n");
1634 void PrintSignalInformation(Stream &str, Args &signal_args,
1635 int num_valid_signals,
1636 const UnixSignalsSP &signals_sp) {
1637 PrintSignalHeader(str);
1639 if (num_valid_signals > 0) {
1640 size_t num_args = signal_args.GetArgumentCount();
1641 for (size_t i = 0; i < num_args; ++i) {
1642 int32_t signo = signals_sp->GetSignalNumberFromName(
1643 signal_args.GetArgumentAtIndex(i));
1644 if (signo != LLDB_INVALID_SIGNAL_NUMBER)
1645 PrintSignal(str, signo, signal_args.GetArgumentAtIndex(i),
1646 signals_sp);
1648 } else // Print info for ALL signals
1650 int32_t signo = signals_sp->GetFirstSignalNumber();
1651 while (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1652 PrintSignal(str, signo, signals_sp->GetSignalAsStringRef(signo),
1653 signals_sp);
1654 signo = signals_sp->GetNextSignalNumber(signo);
1659 protected:
1660 void DoExecute(Args &signal_args, CommandReturnObject &result) override {
1661 Target &target = GetSelectedOrDummyTarget();
1663 // Any signals that are being set should be added to the Target's
1664 // DummySignals so they will get applied on rerun, etc.
1665 // If we have a process, however, we can do a more accurate job of vetting
1666 // the user's options.
1667 ProcessSP process_sp = target.GetProcessSP();
1669 int stop_action = -1; // -1 means leave the current setting alone
1670 int pass_action = -1; // -1 means leave the current setting alone
1671 int notify_action = -1; // -1 means leave the current setting alone
1673 if (!m_options.stop.empty() &&
1674 !VerifyCommandOptionValue(m_options.stop, stop_action)) {
1675 result.AppendError("Invalid argument for command option --stop; must be "
1676 "true or false.\n");
1677 return;
1680 if (!m_options.notify.empty() &&
1681 !VerifyCommandOptionValue(m_options.notify, notify_action)) {
1682 result.AppendError("Invalid argument for command option --notify; must "
1683 "be true or false.\n");
1684 return;
1687 if (!m_options.pass.empty() &&
1688 !VerifyCommandOptionValue(m_options.pass, pass_action)) {
1689 result.AppendError("Invalid argument for command option --pass; must be "
1690 "true or false.\n");
1691 return;
1694 bool no_actions = (stop_action == -1 && pass_action == -1
1695 && notify_action == -1);
1696 if (m_options.only_target_values && !no_actions) {
1697 result.AppendError("-t is for reporting, not setting, target values.");
1698 return;
1701 size_t num_args = signal_args.GetArgumentCount();
1702 UnixSignalsSP signals_sp;
1703 if (process_sp)
1704 signals_sp = process_sp->GetUnixSignals();
1706 int num_signals_set = 0;
1708 // If we were just asked to print the target values, do that here and
1709 // return:
1710 if (m_options.only_target_values) {
1711 target.PrintDummySignals(result.GetOutputStream(), signal_args);
1712 result.SetStatus(eReturnStatusSuccessFinishResult);
1713 return;
1716 // This handles clearing values:
1717 if (m_options.do_clear) {
1718 target.ClearDummySignals(signal_args);
1719 if (m_options.dummy)
1720 GetDummyTarget().ClearDummySignals(signal_args);
1721 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1722 return;
1725 // This rest handles setting values:
1726 if (num_args > 0) {
1727 for (const auto &arg : signal_args) {
1728 // Do the process first. If we have a process we can catch
1729 // invalid signal names, which we do here.
1730 if (signals_sp) {
1731 int32_t signo = signals_sp->GetSignalNumberFromName(arg.c_str());
1732 if (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1733 // Casting the actions as bools here should be okay, because
1734 // VerifyCommandOptionValue guarantees the value is either 0 or 1.
1735 if (stop_action != -1)
1736 signals_sp->SetShouldStop(signo, stop_action);
1737 if (pass_action != -1) {
1738 bool suppress = !pass_action;
1739 signals_sp->SetShouldSuppress(signo, suppress);
1741 if (notify_action != -1)
1742 signals_sp->SetShouldNotify(signo, notify_action);
1743 ++num_signals_set;
1744 } else {
1745 result.AppendErrorWithFormat("Invalid signal name '%s'\n",
1746 arg.c_str());
1747 continue;
1749 } else {
1750 // If there's no process we can't check, so we just set them all.
1751 // But since the map signal name -> signal number across all platforms
1752 // is not 1-1, we can't sensibly set signal actions by number before
1753 // we have a process. Check that here:
1754 int32_t signo;
1755 if (llvm::to_integer(arg.c_str(), signo)) {
1756 result.AppendErrorWithFormat("Can't set signal handling by signal "
1757 "number with no process");
1758 return;
1760 num_signals_set = num_args;
1762 auto set_lazy_bool = [] (int action) -> LazyBool {
1763 LazyBool lazy;
1764 if (action == -1)
1765 lazy = eLazyBoolCalculate;
1766 else if (action)
1767 lazy = eLazyBoolYes;
1768 else
1769 lazy = eLazyBoolNo;
1770 return lazy;
1773 // If there were no actions, we're just listing, don't add the dummy:
1774 if (!no_actions)
1775 target.AddDummySignal(arg.ref(),
1776 set_lazy_bool(pass_action),
1777 set_lazy_bool(notify_action),
1778 set_lazy_bool(stop_action));
1780 } else {
1781 // No signal specified, if any command options were specified, update ALL
1782 // signals. But we can't do this without a process since we don't know
1783 // all the possible signals that might be valid for this target.
1784 if (((notify_action != -1) || (stop_action != -1) || (pass_action != -1))
1785 && process_sp) {
1786 if (m_interpreter.Confirm(
1787 "Do you really want to update all the signals?", false)) {
1788 int32_t signo = signals_sp->GetFirstSignalNumber();
1789 while (signo != LLDB_INVALID_SIGNAL_NUMBER) {
1790 if (notify_action != -1)
1791 signals_sp->SetShouldNotify(signo, notify_action);
1792 if (stop_action != -1)
1793 signals_sp->SetShouldStop(signo, stop_action);
1794 if (pass_action != -1) {
1795 bool suppress = !pass_action;
1796 signals_sp->SetShouldSuppress(signo, suppress);
1798 signo = signals_sp->GetNextSignalNumber(signo);
1804 if (signals_sp)
1805 PrintSignalInformation(result.GetOutputStream(), signal_args,
1806 num_signals_set, signals_sp);
1807 else
1808 target.PrintDummySignals(result.GetOutputStream(),
1809 signal_args);
1811 if (num_signals_set > 0)
1812 result.SetStatus(eReturnStatusSuccessFinishResult);
1813 else
1814 result.SetStatus(eReturnStatusFailed);
1817 CommandOptions m_options;
1820 // Next are the subcommands of CommandObjectMultiwordProcessTrace
1822 // CommandObjectProcessTraceStart
1823 class CommandObjectProcessTraceStart : public CommandObjectTraceProxy {
1824 public:
1825 CommandObjectProcessTraceStart(CommandInterpreter &interpreter)
1826 : CommandObjectTraceProxy(
1827 /*live_debug_session_only*/ true, interpreter,
1828 "process trace start",
1829 "Start tracing this process with the corresponding trace "
1830 "plug-in.",
1831 "process trace start [<trace-options>]") {}
1833 protected:
1834 lldb::CommandObjectSP GetDelegateCommand(Trace &trace) override {
1835 return trace.GetProcessTraceStartCommand(m_interpreter);
1839 // CommandObjectProcessTraceStop
1840 class CommandObjectProcessTraceStop : public CommandObjectParsed {
1841 public:
1842 CommandObjectProcessTraceStop(CommandInterpreter &interpreter)
1843 : CommandObjectParsed(interpreter, "process trace stop",
1844 "Stop tracing this process. This does not affect "
1845 "traces started with the "
1846 "\"thread trace start\" command.",
1847 "process trace stop",
1848 eCommandRequiresProcess | eCommandTryTargetAPILock |
1849 eCommandProcessMustBeLaunched |
1850 eCommandProcessMustBePaused |
1851 eCommandProcessMustBeTraced) {}
1853 ~CommandObjectProcessTraceStop() override = default;
1855 void DoExecute(Args &command, CommandReturnObject &result) override {
1856 ProcessSP process_sp = m_exe_ctx.GetProcessSP();
1858 TraceSP trace_sp = process_sp->GetTarget().GetTrace();
1860 if (llvm::Error err = trace_sp->Stop())
1861 result.AppendError(toString(std::move(err)));
1862 else
1863 result.SetStatus(eReturnStatusSuccessFinishResult);
1867 // CommandObjectMultiwordProcessTrace
1868 class CommandObjectMultiwordProcessTrace : public CommandObjectMultiword {
1869 public:
1870 CommandObjectMultiwordProcessTrace(CommandInterpreter &interpreter)
1871 : CommandObjectMultiword(
1872 interpreter, "trace", "Commands for tracing the current process.",
1873 "process trace <subcommand> [<subcommand objects>]") {
1874 LoadSubCommand("start", CommandObjectSP(new CommandObjectProcessTraceStart(
1875 interpreter)));
1876 LoadSubCommand("stop", CommandObjectSP(
1877 new CommandObjectProcessTraceStop(interpreter)));
1880 ~CommandObjectMultiwordProcessTrace() override = default;
1883 // CommandObjectMultiwordProcess
1885 CommandObjectMultiwordProcess::CommandObjectMultiwordProcess(
1886 CommandInterpreter &interpreter)
1887 : CommandObjectMultiword(
1888 interpreter, "process",
1889 "Commands for interacting with processes on the current platform.",
1890 "process <subcommand> [<subcommand-options>]") {
1891 LoadSubCommand("attach",
1892 CommandObjectSP(new CommandObjectProcessAttach(interpreter)));
1893 LoadSubCommand("launch",
1894 CommandObjectSP(new CommandObjectProcessLaunch(interpreter)));
1895 LoadSubCommand("continue", CommandObjectSP(new CommandObjectProcessContinue(
1896 interpreter)));
1897 LoadSubCommand("connect",
1898 CommandObjectSP(new CommandObjectProcessConnect(interpreter)));
1899 LoadSubCommand("detach",
1900 CommandObjectSP(new CommandObjectProcessDetach(interpreter)));
1901 LoadSubCommand("load",
1902 CommandObjectSP(new CommandObjectProcessLoad(interpreter)));
1903 LoadSubCommand("unload",
1904 CommandObjectSP(new CommandObjectProcessUnload(interpreter)));
1905 LoadSubCommand("signal",
1906 CommandObjectSP(new CommandObjectProcessSignal(interpreter)));
1907 LoadSubCommand("handle",
1908 CommandObjectSP(new CommandObjectProcessHandle(interpreter)));
1909 LoadSubCommand("status",
1910 CommandObjectSP(new CommandObjectProcessStatus(interpreter)));
1911 LoadSubCommand("interrupt", CommandObjectSP(new CommandObjectProcessInterrupt(
1912 interpreter)));
1913 LoadSubCommand("kill",
1914 CommandObjectSP(new CommandObjectProcessKill(interpreter)));
1915 LoadSubCommand("plugin",
1916 CommandObjectSP(new CommandObjectProcessPlugin(interpreter)));
1917 LoadSubCommand("save-core", CommandObjectSP(new CommandObjectProcessSaveCore(
1918 interpreter)));
1919 LoadSubCommand(
1920 "trace",
1921 CommandObjectSP(new CommandObjectMultiwordProcessTrace(interpreter)));
1924 CommandObjectMultiwordProcess::~CommandObjectMultiwordProcess() = default;