1 //===-- CommandObjectProcess.cpp ------------------------------------------===//
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
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"
44 using namespace lldb_private
;
46 class CommandObjectProcessLaunchOrAttach
: public CommandObjectParsed
{
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;
58 bool StopProcessIfNecessary(Process
*process
, StateType
&state
,
59 CommandReturnObject
&result
) {
60 state
= eStateInvalid
;
62 state
= process
->GetState();
64 if (process
->IsAlive() && state
!= eStateConnected
) {
66 if (process
->GetState() == eStateAttaching
)
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
);
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
);
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
);
90 result
.AppendErrorWithFormat(
91 "Failed to detach from process: %s\n",
92 detach_error
.AsCString());
95 Status
destroy_error(process
->Destroy(false));
96 if (destroy_error
.Success()) {
97 result
.SetStatus(eReturnStatusSuccessFinishResult
);
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
{
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
,
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
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;
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
¤t_command_args
,
157 uint32_t index
) override
{
158 // No repeat for "process launch"...
159 return std::string("");
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");
180 StateType state
= eStateInvalid
;
182 if (!StopProcessIfNecessary(m_exe_ctx
.GetProcessPtr(), state
, result
))
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.
194 disable_aslr
= (m_options
.disable_aslr
== eLazyBoolYes
);
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
);
210 m_options
.launch_info
.GetFlags().Set(eLaunchFlagDisableASLR
);
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(),
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
);
234 m_options
.launch_info
.SetExecutableFile(
235 exe_module_sp
->GetPlatformFileSpec(), false);
237 m_options
.launch_info
.SetExecutableFile(target
->GetProcessLaunchInfo().GetExecutableFile(), false);
240 m_options
.launch_info
.SetExecutableFile(
241 exe_module_sp
->GetPlatformFileSpec(), true);
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());
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
);
256 Status error
= target
->Launch(m_options
.launch_info
, &stream
);
258 if (error
.Success()) {
259 ProcessSP
process_sp(target
->GetProcessSP());
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();
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.
273 exe_module_sp
= target
->GetExecutableModule();
274 if (!exe_module_sp
) {
275 result
.AppendWarning("Could not get executable module after launch.");
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);
288 "no error returned from Target::Launch, and target has no process");
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
{
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
,
314 m_all_options
.Finalize();
317 ~CommandObjectProcessAttach() override
= default;
319 Options
*GetOptions() override
{ return &m_all_options
; }
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
))
338 if (target
== nullptr) {
339 // If there isn't a current target create one.
340 TargetSP new_target_sp
;
343 error
= GetDebugger().GetTargetList().CreateTarget(
344 GetDebugger(), "", "", eLoadDependentsNo
,
345 nullptr, // No platform options
347 target
= new_target_sp
.get();
348 if (target
== nullptr || error
.Fail()) {
349 result
.AppendError(error
.AsCString("Error creating target"));
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();
369 ProcessSP process_sp
;
370 const auto error
= target
->Attach(m_options
.attach_info
, &stream
);
371 if (error
.Success()) {
372 process_sp
= target
->GetProcessSP();
374 result
.AppendMessage(stream
.GetString());
375 result
.SetStatus(eReturnStatusSuccessFinishNoResult
);
376 result
.SetDidChangeProcessState(true);
379 "no error returned from Target::Attach, and target has no process");
382 result
.AppendErrorWithFormat("attach failed: %s\n", error
.AsCString());
385 if (!result
.Succeeded())
388 // Okay, we're done. Last step is to warn if the executable module has
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",
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
,
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
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
{
447 CommandObjectProcessContinue(CommandInterpreter
&interpreter
)
448 : CommandObjectParsed(
449 interpreter
, "process continue",
450 "Continue execution of all threads in the current process.",
452 eCommandRequiresProcess
| eCommandTryTargetAPILock
|
453 eCommandProcessMustBeLaunched
| eCommandProcessMustBePaused
) {}
455 ~CommandObjectProcessContinue() override
= default;
458 class CommandOptions
: public Options
{
461 // Keep default values of all options in one place: OptionParsingStarting
463 OptionParsingStarting(nullptr);
466 ~CommandOptions() override
= default;
468 Status
SetOptionValue(uint32_t option_idx
, llvm::StringRef option_arg
,
469 ExecutionContext
*exe_ctx
) override
{
471 const int short_option
= m_getopt_table
[option_idx
].val
;
472 switch (short_option
) {
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());
480 m_run_to_bkpt_args
.AppendArgument(option_arg
);
481 m_any_bkpts_specified
= true;
484 llvm_unreachable("Unimplemented option");
489 void OptionParsingStarting(ExecutionContext
*execution_context
) override
{
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());
512 StopInfoSP stop_info_sp
= sel_thread_sp
->GetStopInfo();
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
));
520 const size_t num_owners
= bp_site_sp
->GetNumberOfOwners();
521 for (size_t i
= 0; i
< num_owners
; i
++) {
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()) {
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");
551 // First figure out which breakpoints & locations were specified by the
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();
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()) {
589 // A location was specified, check if it was enabled:
590 BreakpointLocationSP loc_sp
= bp_sp
->FindLocationByID(loc_id
);
591 if (loc_sp
->IsEnabled())
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());
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.
609 result
.AppendError("at least one of the continue-to breakpoints must "
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);
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
);
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();
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
);
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
);
695 bp_sp
->SetEnabled(true);
697 for (const BreakpointID
&bkpt_id
: locs_disabled
) {
699 = bkpt_list
.FindBreakpointByID(bkpt_id
.GetBreakpointID());
701 BreakpointLocationSP loc_sp
702 = bp_sp
->FindLocationByID(bkpt_id
.GetLocationID());
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",
717 if (synchronous_execution
) {
718 // If any state changed events had anything to say, add that to the
720 result
.AppendMessage(stream
.GetString());
722 result
.SetDidChangeProcessState(true);
723 result
.SetStatus(eReturnStatusSuccessFinishNoResult
);
725 result
.SetStatus(eReturnStatusSuccessContinuingNoResult
);
728 result
.AppendErrorWithFormat("Failed to resume process: %s.\n",
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
{
751 class CommandOptions
: public Options
{
753 CommandOptions() { OptionParsingStarting(nullptr); }
755 ~CommandOptions() override
= default;
757 Status
SetOptionValue(uint32_t option_idx
, llvm::StringRef option_arg
,
758 ExecutionContext
*execution_context
) override
{
760 const int short_option
= m_getopt_table
[option_idx
].val
;
762 switch (short_option
) {
766 tmp_result
= OptionArgParser::ToBoolean(option_arg
, false, &success
);
768 error
.SetErrorStringWithFormat("invalid boolean option: \"%s\"",
769 option_arg
.str().c_str());
772 m_keep_stopped
= eLazyBoolYes
;
774 m_keep_stopped
= eLazyBoolNo
;
778 llvm_unreachable("Unimplemented option");
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.",
799 eCommandRequiresProcess
| eCommandTryTargetAPILock
|
800 eCommandProcessMustBeLaunched
) {}
802 ~CommandObjectProcessDetach() override
= default;
804 Options
*GetOptions() override
{ return &m_options
; }
807 void DoExecute(Args
&command
, CommandReturnObject
&result
) override
{
808 Process
*process
= m_exe_ctx
.GetProcessPtr();
809 // FIXME: This will be a Command Option:
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
)
817 keep_stopped
= false;
819 Status
error(process
->Detach(keep_stopped
));
820 if (error
.Success()) {
821 result
.SetStatus(eReturnStatusSuccessFinishResult
);
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
{
838 class CommandOptions
: public Options
{
841 // Keep default values of all options in one place: OptionParsingStarting
843 OptionParsingStarting(nullptr);
846 ~CommandOptions() override
= default;
848 Status
SetOptionValue(uint32_t option_idx
, llvm::StringRef option_arg
,
849 ExecutionContext
*execution_context
) override
{
851 const int short_option
= m_getopt_table
[option_idx
].val
;
853 switch (short_option
) {
855 plugin_name
.assign(std::string(option_arg
));
859 llvm_unreachable("Unimplemented option");
864 void OptionParsingStarting(ExecutionContext
*execution_context
) override
{
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
; }
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());
898 Process
*process
= m_exe_ctx
.GetProcessPtr();
899 if (process
&& process
->IsAlive()) {
900 result
.AppendErrorWithFormat(
902 " is currently being debugged, kill the process before connecting.\n",
907 const char *plugin_name
= nullptr;
908 if (!m_options
.plugin_name
.empty())
909 plugin_name
= m_options
.plugin_name
.c_str();
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(),
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
{
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();
947 return process
->GetPluginCommandObject();
952 // CommandObjectProcessLoad
953 #define LLDB_OPTIONS_process_load
954 #include "CommandOptions.inc"
956 #pragma mark CommandObjectProcessLoad
958 class CommandObjectProcessLoad
: public CommandObjectParsed
{
960 class CommandOptions
: public Options
{
963 // Keep default values of all options in one place: OptionParsingStarting
965 OptionParsingStarting(nullptr);
968 ~CommandOptions() override
= default;
970 Status
SetOptionValue(uint32_t option_idx
, llvm::StringRef option_arg
,
971 ExecutionContext
*execution_context
) override
{
973 const int short_option
= m_getopt_table
[option_idx
].val
;
974 switch (short_option
) {
977 if (!option_arg
.empty())
978 install_path
.SetFile(option_arg
, FileSpec::Style::native
);
981 llvm_unreachable("Unimplemented option");
986 void OptionParsingStarting(ExecutionContext
*execution_context
) override
{
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.
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;
1014 HandleArgumentCompletion(CompletionRequest
&request
,
1015 OptionElementVector
&opt_element_vector
) override
{
1016 if (!m_exe_ctx
.HasProcessScope())
1019 lldb_private::CommandCompletions::InvokeCommonCompletionCallbacks(
1020 GetCommandInterpreter(), lldb::eDiskFileCompletion
, request
, nullptr);
1023 Options
*GetOptions() override
{ return &m_options
; }
1026 void DoExecute(Args
&command
, CommandReturnObject
&result
) override
{
1027 Process
*process
= m_exe_ctx
.GetProcessPtr();
1029 for (auto &entry
: command
.entries()) {
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
);
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
);
1048 FileSpec
image_spec(image_path
);
1049 FileSystem::Instance().Resolve(image_spec
);
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(),
1058 result
.SetStatus(eReturnStatusSuccessFinishResult
);
1060 result
.AppendErrorWithFormat("failed to load '%s': %s",
1061 image_path
.str().c_str(),
1067 CommandOptions m_options
;
1070 // CommandObjectProcessUnload
1071 #pragma mark CommandObjectProcessUnload
1073 class CommandObjectProcessUnload
: public CommandObjectParsed
{
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;
1090 HandleArgumentCompletion(CompletionRequest
&request
,
1091 OptionElementVector
&opt_element_vector
) override
{
1093 if (request
.GetCursorIndex() || !m_exe_ctx
.HasProcessScope())
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
)
1103 request
.TryCompleteCurrentArg(std::to_string(i
));
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());
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
);
1125 result
.AppendErrorWithFormat("failed to unload image: %s",
1134 // CommandObjectProcessSignal
1135 #pragma mark CommandObjectProcessSignal
1137 class CommandObjectProcessSignal
: public CommandObjectParsed
{
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
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;
1162 HandleArgumentCompletion(CompletionRequest
&request
,
1163 OptionElementVector
&opt_element_vector
) override
{
1164 if (!m_exe_ctx
.HasProcessScope() || request
.GetCursorIndex() != 0)
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
);
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
;
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));
1193 Status
error(process
->Signal(signo
));
1194 if (error
.Success()) {
1195 result
.SetStatus(eReturnStatusSuccessFinishResult
);
1197 result
.AppendErrorWithFormat("Failed to send signal %i: %s\n", signo
,
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
{
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;
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");
1231 bool clear_thread_plans
= true;
1232 Status
error(process
->Halt(clear_thread_plans
));
1233 if (error
.Success()) {
1234 result
.SetStatus(eReturnStatusSuccessFinishResult
);
1236 result
.AppendErrorWithFormat("Failed to halt process: %s\n",
1242 // CommandObjectProcessKill
1243 #pragma mark CommandObjectProcessKill
1245 class CommandObjectProcessKill
: public CommandObjectParsed
{
1247 CommandObjectProcessKill(CommandInterpreter
&interpreter
)
1248 : CommandObjectParsed(interpreter
, "process kill",
1249 "Terminate the current target process.",
1251 eCommandRequiresProcess
| eCommandTryTargetAPILock
|
1252 eCommandProcessMustBeLaunched
) {}
1254 ~CommandObjectProcessKill() override
= default;
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");
1264 Status
error(process
->Destroy(true));
1265 if (error
.Success()) {
1266 result
.SetStatus(eReturnStatusSuccessFinishResult
);
1268 result
.AppendErrorWithFormat("Failed to kill process: %s\n",
1274 #define LLDB_OPTIONS_process_save_core
1275 #include "CommandOptions.inc"
1277 class CommandObjectProcessSaveCore
: public CommandObjectParsed
{
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
; }
1296 HandleArgumentCompletion(CompletionRequest
&request
,
1297 OptionElementVector
&opt_element_vector
) override
{
1298 CommandCompletions::InvokeCommonCompletionCallbacks(
1299 GetCommandInterpreter(), lldb::eDiskFileCompletion
, request
, nullptr);
1302 class CommandOptions
: public Options
{
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
;
1317 switch (short_option
) {
1319 m_requested_plugin_name
= option_arg
.str();
1322 m_requested_save_core_style
=
1323 (lldb::SaveCoreStyle
)OptionArgParser::ToOptionEnum(
1324 option_arg
, GetDefinitions()[option_idx
].enum_values
,
1325 eSaveCoreUnspecified
, error
);
1328 llvm_unreachable("Unimplemented option");
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
;
1345 void DoExecute(Args
&command
, CommandReturnObject
&result
) override
{
1346 ProcessSP process_sp
= m_exe_ctx
.GetProcessSP();
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
;
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
);
1370 result
.AppendErrorWithFormat(
1371 "Failed to save core file for process: %s\n", error
.AsCString());
1374 result
.AppendErrorWithFormat("'%s' takes one arguments:\nUsage: %s\n",
1375 m_cmd_name
.c_str(), m_cmd_syntax
.c_str());
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
{
1392 CommandObjectProcessStatus(CommandInterpreter
&interpreter
)
1393 : CommandObjectParsed(
1394 interpreter
, "process status",
1395 "Show status and stop location for the current target process.",
1397 eCommandRequiresProcess
| eCommandTryTargetAPILock
) {}
1399 ~CommandObjectProcessStatus() override
= default;
1401 Options
*GetOptions() override
{ return &m_options
; }
1403 class CommandOptions
: public Options
{
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
) {
1418 llvm_unreachable("Unimplemented option");
1424 void OptionParsingStarting(ExecutionContext
*execution_context
) override
{
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;
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();
1468 result
.AppendError("Couldn'retrieve the target's platform");
1472 auto expected_crash_info
=
1473 platform_sp
->FetchExtendedCrashInformation(*process
);
1475 if (!expected_crash_info
) {
1476 result
.AppendError(llvm::toString(expected_crash_info
.takeError()));
1480 StructuredData::DictionarySP crash_info_sp
= *expected_crash_info
;
1482 if (crash_info_sp
) {
1484 strm
.PutCString("Extended Crash Information:\n");
1485 crash_info_sp
->GetDescription(strm
);
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
{
1502 class CommandOptions
: public Options
{
1504 CommandOptions() { OptionParsingStarting(nullptr); }
1506 ~CommandOptions() override
= default;
1508 Status
SetOptionValue(uint32_t option_idx
, llvm::StringRef option_arg
,
1509 ExecutionContext
*execution_context
) override
{
1511 const int short_option
= m_getopt_table
[option_idx
].val
;
1513 switch (short_option
) {
1521 stop
= std::string(option_arg
);
1524 notify
= std::string(option_arg
);
1527 pass
= std::string(option_arg
);
1530 only_target_values
= true;
1533 llvm_unreachable("Unimplemented option");
1538 void OptionParsingStarting(ExecutionContext
*execution_context
) override
{
1542 only_target_values
= 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.
1556 bool only_target_values
= false;
1557 bool do_clear
= 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 "
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
) {
1596 bool success
= false;
1597 bool tmp_value
= OptionArgParser::ToBoolean(option
, false, &success
);
1599 if (success
&& tmp_value
)
1601 else if (success
&& !tmp_value
)
1604 // If the value isn't 'true' or 'false', it had better be 0 or 1.
1605 if (!llvm::to_integer(option
, real_value
))
1607 if (real_value
!= 0 && real_value
!= 1)
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
) {
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"));
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
),
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
),
1654 signo
= signals_sp
->GetNextSignalNumber(signo
);
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");
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");
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");
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.");
1701 size_t num_args
= signal_args
.GetArgumentCount();
1702 UnixSignalsSP signals_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
1710 if (m_options
.only_target_values
) {
1711 target
.PrintDummySignals(result
.GetOutputStream(), signal_args
);
1712 result
.SetStatus(eReturnStatusSuccessFinishResult
);
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
);
1725 // This rest handles setting values:
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.
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
);
1745 result
.AppendErrorWithFormat("Invalid signal name '%s'\n",
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:
1755 if (llvm::to_integer(arg
.c_str(), signo
)) {
1756 result
.AppendErrorWithFormat("Can't set signal handling by signal "
1757 "number with no process");
1760 num_signals_set
= num_args
;
1762 auto set_lazy_bool
= [] (int action
) -> LazyBool
{
1765 lazy
= eLazyBoolCalculate
;
1767 lazy
= eLazyBoolYes
;
1773 // If there were no actions, we're just listing, don't add the dummy:
1775 target
.AddDummySignal(arg
.ref(),
1776 set_lazy_bool(pass_action
),
1777 set_lazy_bool(notify_action
),
1778 set_lazy_bool(stop_action
));
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))
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
);
1805 PrintSignalInformation(result
.GetOutputStream(), signal_args
,
1806 num_signals_set
, signals_sp
);
1808 target
.PrintDummySignals(result
.GetOutputStream(),
1811 if (num_signals_set
> 0)
1812 result
.SetStatus(eReturnStatusSuccessFinishResult
);
1814 result
.SetStatus(eReturnStatusFailed
);
1817 CommandOptions m_options
;
1820 // Next are the subcommands of CommandObjectMultiwordProcessTrace
1822 // CommandObjectProcessTraceStart
1823 class CommandObjectProcessTraceStart
: public CommandObjectTraceProxy
{
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 "
1831 "process trace start [<trace-options>]") {}
1834 lldb::CommandObjectSP
GetDelegateCommand(Trace
&trace
) override
{
1835 return trace
.GetProcessTraceStartCommand(m_interpreter
);
1839 // CommandObjectProcessTraceStop
1840 class CommandObjectProcessTraceStop
: public CommandObjectParsed
{
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
)));
1863 result
.SetStatus(eReturnStatusSuccessFinishResult
);
1867 // CommandObjectMultiwordProcessTrace
1868 class CommandObjectMultiwordProcessTrace
: public CommandObjectMultiword
{
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(
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(
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(
1913 LoadSubCommand("kill",
1914 CommandObjectSP(new CommandObjectProcessKill(interpreter
)));
1915 LoadSubCommand("plugin",
1916 CommandObjectSP(new CommandObjectProcessPlugin(interpreter
)));
1917 LoadSubCommand("save-core", CommandObjectSP(new CommandObjectProcessSaveCore(
1921 CommandObjectSP(new CommandObjectMultiwordProcessTrace(interpreter
)));
1924 CommandObjectMultiwordProcess::~CommandObjectMultiwordProcess() = default;