1 //===-- CommandObjectPlatform.cpp -------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
13 // Other libraries and framework includes
15 #include "CommandObjectPlatform.h"
16 #include "lldb/Core/Debugger.h"
17 #include "lldb/Core/Module.h"
18 #include "lldb/Core/PluginManager.h"
19 #include "lldb/Host/OptionParser.h"
20 #include "lldb/Host/StringConvert.h"
21 #include "lldb/Interpreter/CommandInterpreter.h"
22 #include "lldb/Interpreter/CommandOptionValidators.h"
23 #include "lldb/Interpreter/CommandReturnObject.h"
24 #include "lldb/Interpreter/OptionGroupFile.h"
25 #include "lldb/Interpreter/OptionGroupPlatform.h"
26 #include "lldb/Target/ExecutionContext.h"
27 #include "lldb/Target/Platform.h"
28 #include "lldb/Target/Process.h"
29 #include "lldb/Utility/Args.h"
30 #include "lldb/Utility/DataExtractor.h"
32 #include "llvm/ADT/SmallString.h"
33 #include "llvm/Support/Threading.h"
36 using namespace lldb_private;
38 static mode_t ParsePermissionString(const char *) = delete;
40 static mode_t ParsePermissionString(llvm::StringRef permissions) {
41 if (permissions.size() != 9)
43 bool user_r, user_w, user_x, group_r, group_w, group_x, world_r, world_w,
46 user_r = (permissions[0] == 'r');
47 user_w = (permissions[1] == 'w');
48 user_x = (permissions[2] == 'x');
50 group_r = (permissions[3] == 'r');
51 group_w = (permissions[4] == 'w');
52 group_x = (permissions[5] == 'x');
54 world_r = (permissions[6] == 'r');
55 world_w = (permissions[7] == 'w');
56 world_x = (permissions[8] == 'x');
58 mode_t user, group, world;
59 user = (user_r ? 4 : 0) | (user_w ? 2 : 0) | (user_x ? 1 : 0);
60 group = (group_r ? 4 : 0) | (group_w ? 2 : 0) | (group_x ? 1 : 0);
61 world = (world_r ? 4 : 0) | (world_w ? 2 : 0) | (world_x ? 1 : 0);
63 return user | group | world;
66 static OptionDefinition g_permissions_options[] = {
68 {LLDB_OPT_SET_ALL, false, "permissions-value", 'v', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePermissionsNumber, "Give out the numeric value for permissions (e.g. 757)"},
69 {LLDB_OPT_SET_ALL, false, "permissions-string", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePermissionsString, "Give out the string value for permissions (e.g. rwxr-xr--)."},
70 {LLDB_OPT_SET_ALL, false, "user-read", 'r', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow user to read."},
71 {LLDB_OPT_SET_ALL, false, "user-write", 'w', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow user to write."},
72 {LLDB_OPT_SET_ALL, false, "user-exec", 'x', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow user to execute."},
73 {LLDB_OPT_SET_ALL, false, "group-read", 'R', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow group to read."},
74 {LLDB_OPT_SET_ALL, false, "group-write", 'W', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow group to write."},
75 {LLDB_OPT_SET_ALL, false, "group-exec", 'X', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow group to execute."},
76 {LLDB_OPT_SET_ALL, false, "world-read", 'd', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow world to read."},
77 {LLDB_OPT_SET_ALL, false, "world-write", 't', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow world to write."},
78 {LLDB_OPT_SET_ALL, false, "world-exec", 'e', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow world to execute."},
82 class OptionPermissions : public OptionGroup {
84 OptionPermissions() {}
86 ~OptionPermissions() override = default;
89 SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
90 ExecutionContext *execution_context) override {
92 char short_option = (char)GetDefinitions()[option_idx].short_option;
93 switch (short_option) {
95 if (option_arg.getAsInteger(8, m_permissions)) {
97 error.SetErrorStringWithFormat("invalid value for permissions: %s",
98 option_arg.str().c_str());
103 mode_t perms = ParsePermissionString(option_arg);
104 if (perms == (mode_t)-1)
105 error.SetErrorStringWithFormat("invalid value for permissions: %s",
106 option_arg.str().c_str());
108 m_permissions = perms;
111 m_permissions |= lldb::eFilePermissionsUserRead;
114 m_permissions |= lldb::eFilePermissionsUserWrite;
117 m_permissions |= lldb::eFilePermissionsUserExecute;
120 m_permissions |= lldb::eFilePermissionsGroupRead;
123 m_permissions |= lldb::eFilePermissionsGroupWrite;
126 m_permissions |= lldb::eFilePermissionsGroupExecute;
129 m_permissions |= lldb::eFilePermissionsWorldRead;
132 m_permissions |= lldb::eFilePermissionsWorldWrite;
135 m_permissions |= lldb::eFilePermissionsWorldExecute;
138 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
145 void OptionParsingStarting(ExecutionContext *execution_context) override {
149 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
150 return llvm::makeArrayRef(g_permissions_options);
153 // Instance variables to hold the values for command options.
155 uint32_t m_permissions;
158 DISALLOW_COPY_AND_ASSIGN(OptionPermissions);
161 //----------------------------------------------------------------------
162 // "platform select <platform-name>"
163 //----------------------------------------------------------------------
164 class CommandObjectPlatformSelect : public CommandObjectParsed {
166 CommandObjectPlatformSelect(CommandInterpreter &interpreter)
167 : CommandObjectParsed(interpreter, "platform select",
168 "Create a platform if needed and select it as the "
170 "platform select <platform-name>", 0),
173 false) // Don't include the "--platform" option by passing false
175 m_option_group.Append(&m_platform_options, LLDB_OPT_SET_ALL, 1);
176 m_option_group.Finalize();
179 ~CommandObjectPlatformSelect() override = default;
181 int HandleCompletion(CompletionRequest &request) override {
182 CommandCompletions::PlatformPluginNames(GetCommandInterpreter(), request,
184 return request.GetNumberOfMatches();
187 Options *GetOptions() override { return &m_option_group; }
190 bool DoExecute(Args &args, CommandReturnObject &result) override {
191 if (args.GetArgumentCount() == 1) {
192 const char *platform_name = args.GetArgumentAtIndex(0);
193 if (platform_name && platform_name[0]) {
194 const bool select = true;
195 m_platform_options.SetPlatformName(platform_name);
197 ArchSpec platform_arch;
198 PlatformSP platform_sp(m_platform_options.CreatePlatformWithOptions(
199 m_interpreter, ArchSpec(), select, error, platform_arch));
201 m_interpreter.GetDebugger().GetPlatformList().SetSelectedPlatform(
204 platform_sp->GetStatus(result.GetOutputStream());
205 result.SetStatus(eReturnStatusSuccessFinishResult);
207 result.AppendError(error.AsCString());
208 result.SetStatus(eReturnStatusFailed);
211 result.AppendError("invalid platform name");
212 result.SetStatus(eReturnStatusFailed);
216 "platform create takes a platform name as an argument\n");
217 result.SetStatus(eReturnStatusFailed);
219 return result.Succeeded();
222 OptionGroupOptions m_option_group;
223 OptionGroupPlatform m_platform_options;
226 //----------------------------------------------------------------------
228 //----------------------------------------------------------------------
229 class CommandObjectPlatformList : public CommandObjectParsed {
231 CommandObjectPlatformList(CommandInterpreter &interpreter)
232 : CommandObjectParsed(interpreter, "platform list",
233 "List all platforms that are available.", nullptr,
236 ~CommandObjectPlatformList() override = default;
239 bool DoExecute(Args &args, CommandReturnObject &result) override {
240 Stream &ostrm = result.GetOutputStream();
241 ostrm.Printf("Available platforms:\n");
243 PlatformSP host_platform_sp(Platform::GetHostPlatform());
244 ostrm.Printf("%s: %s\n", host_platform_sp->GetPluginName().GetCString(),
245 host_platform_sp->GetDescription());
248 for (idx = 0; 1; ++idx) {
249 const char *plugin_name =
250 PluginManager::GetPlatformPluginNameAtIndex(idx);
251 if (plugin_name == nullptr)
253 const char *plugin_desc =
254 PluginManager::GetPlatformPluginDescriptionAtIndex(idx);
255 if (plugin_desc == nullptr)
257 ostrm.Printf("%s: %s\n", plugin_name, plugin_desc);
261 result.AppendError("no platforms are available\n");
262 result.SetStatus(eReturnStatusFailed);
264 result.SetStatus(eReturnStatusSuccessFinishResult);
265 return result.Succeeded();
269 //----------------------------------------------------------------------
271 //----------------------------------------------------------------------
272 class CommandObjectPlatformStatus : public CommandObjectParsed {
274 CommandObjectPlatformStatus(CommandInterpreter &interpreter)
275 : CommandObjectParsed(interpreter, "platform status",
276 "Display status for the current platform.", nullptr,
279 ~CommandObjectPlatformStatus() override = default;
282 bool DoExecute(Args &args, CommandReturnObject &result) override {
283 Stream &ostrm = result.GetOutputStream();
285 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
286 PlatformSP platform_sp;
288 platform_sp = target->GetPlatform();
292 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform();
295 platform_sp->GetStatus(ostrm);
296 result.SetStatus(eReturnStatusSuccessFinishResult);
298 result.AppendError("no platform is currently selected\n");
299 result.SetStatus(eReturnStatusFailed);
301 return result.Succeeded();
305 //----------------------------------------------------------------------
306 // "platform connect <connect-url>"
307 //----------------------------------------------------------------------
308 class CommandObjectPlatformConnect : public CommandObjectParsed {
310 CommandObjectPlatformConnect(CommandInterpreter &interpreter)
311 : CommandObjectParsed(
312 interpreter, "platform connect",
313 "Select the current platform by providing a connection URL.",
314 "platform connect <connect-url>", 0) {}
316 ~CommandObjectPlatformConnect() override = default;
319 bool DoExecute(Args &args, CommandReturnObject &result) override {
320 Stream &ostrm = result.GetOutputStream();
322 PlatformSP platform_sp(
323 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
325 Status error(platform_sp->ConnectRemote(args));
326 if (error.Success()) {
327 platform_sp->GetStatus(ostrm);
328 result.SetStatus(eReturnStatusSuccessFinishResult);
330 platform_sp->ConnectToWaitingProcesses(m_interpreter.GetDebugger(),
333 result.AppendError(error.AsCString());
334 result.SetStatus(eReturnStatusFailed);
337 result.AppendErrorWithFormat("%s\n", error.AsCString());
338 result.SetStatus(eReturnStatusFailed);
341 result.AppendError("no platform is currently selected\n");
342 result.SetStatus(eReturnStatusFailed);
344 return result.Succeeded();
347 Options *GetOptions() override {
348 PlatformSP platform_sp(
349 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
350 OptionGroupOptions *m_platform_options = nullptr;
352 m_platform_options = platform_sp->GetConnectionOptions(m_interpreter);
353 if (m_platform_options != nullptr && !m_platform_options->m_did_finalize)
354 m_platform_options->Finalize();
356 return m_platform_options;
360 //----------------------------------------------------------------------
361 // "platform disconnect"
362 //----------------------------------------------------------------------
363 class CommandObjectPlatformDisconnect : public CommandObjectParsed {
365 CommandObjectPlatformDisconnect(CommandInterpreter &interpreter)
366 : CommandObjectParsed(interpreter, "platform disconnect",
367 "Disconnect from the current platform.",
368 "platform disconnect", 0) {}
370 ~CommandObjectPlatformDisconnect() override = default;
373 bool DoExecute(Args &args, CommandReturnObject &result) override {
374 PlatformSP platform_sp(
375 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
377 if (args.GetArgumentCount() == 0) {
380 if (platform_sp->IsConnected()) {
381 // Cache the instance name if there is one since we are about to
382 // disconnect and the name might go with it.
383 const char *hostname_cstr = platform_sp->GetHostname();
384 std::string hostname;
386 hostname.assign(hostname_cstr);
388 error = platform_sp->DisconnectRemote();
389 if (error.Success()) {
390 Stream &ostrm = result.GetOutputStream();
391 if (hostname.empty())
392 ostrm.Printf("Disconnected from \"%s\"\n",
393 platform_sp->GetPluginName().GetCString());
395 ostrm.Printf("Disconnected from \"%s\"\n", hostname.c_str());
396 result.SetStatus(eReturnStatusSuccessFinishResult);
398 result.AppendErrorWithFormat("%s", error.AsCString());
399 result.SetStatus(eReturnStatusFailed);
403 result.AppendErrorWithFormat(
404 "not connected to '%s'",
405 platform_sp->GetPluginName().GetCString());
406 result.SetStatus(eReturnStatusFailed);
411 "\"platform disconnect\" doesn't take any arguments");
412 result.SetStatus(eReturnStatusFailed);
415 result.AppendError("no platform is currently selected");
416 result.SetStatus(eReturnStatusFailed);
418 return result.Succeeded();
422 //----------------------------------------------------------------------
423 // "platform settings"
424 //----------------------------------------------------------------------
425 class CommandObjectPlatformSettings : public CommandObjectParsed {
427 CommandObjectPlatformSettings(CommandInterpreter &interpreter)
428 : CommandObjectParsed(interpreter, "platform settings",
429 "Set settings for the current target's platform, "
430 "or for a platform by name.",
431 "platform settings", 0),
433 m_option_working_dir(LLDB_OPT_SET_1, false, "working-dir", 'w', 0,
435 "The working directory for the platform.") {
436 m_options.Append(&m_option_working_dir, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
439 ~CommandObjectPlatformSettings() override = default;
442 bool DoExecute(Args &args, CommandReturnObject &result) override {
443 PlatformSP platform_sp(
444 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
446 if (m_option_working_dir.GetOptionValue().OptionWasSet())
447 platform_sp->SetWorkingDirectory(
448 m_option_working_dir.GetOptionValue().GetCurrentValue());
450 result.AppendError("no platform is currently selected");
451 result.SetStatus(eReturnStatusFailed);
453 return result.Succeeded();
456 Options *GetOptions() override {
457 if (!m_options.DidFinalize())
458 m_options.Finalize();
463 OptionGroupOptions m_options;
464 OptionGroupFile m_option_working_dir;
467 //----------------------------------------------------------------------
469 //----------------------------------------------------------------------
470 class CommandObjectPlatformMkDir : public CommandObjectParsed {
472 CommandObjectPlatformMkDir(CommandInterpreter &interpreter)
473 : CommandObjectParsed(interpreter, "platform mkdir",
474 "Make a new directory on the remote end.", nullptr,
478 ~CommandObjectPlatformMkDir() override = default;
480 bool DoExecute(Args &args, CommandReturnObject &result) override {
481 PlatformSP platform_sp(
482 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
484 std::string cmd_line;
485 args.GetCommandString(cmd_line);
487 const OptionPermissions *options_permissions =
488 (const OptionPermissions *)m_options.GetGroupWithOption('r');
489 if (options_permissions)
490 mode = options_permissions->m_permissions;
492 mode = lldb::eFilePermissionsUserRWX | lldb::eFilePermissionsGroupRWX |
493 lldb::eFilePermissionsWorldRX;
495 platform_sp->MakeDirectory(FileSpec{cmd_line, false}, mode);
496 if (error.Success()) {
497 result.SetStatus(eReturnStatusSuccessFinishResult);
499 result.AppendError(error.AsCString());
500 result.SetStatus(eReturnStatusFailed);
503 result.AppendError("no platform currently selected\n");
504 result.SetStatus(eReturnStatusFailed);
506 return result.Succeeded();
509 Options *GetOptions() override {
510 if (!m_options.DidFinalize()) {
511 m_options.Append(new OptionPermissions());
512 m_options.Finalize();
517 OptionGroupOptions m_options;
520 //----------------------------------------------------------------------
522 //----------------------------------------------------------------------
523 class CommandObjectPlatformFOpen : public CommandObjectParsed {
525 CommandObjectPlatformFOpen(CommandInterpreter &interpreter)
526 : CommandObjectParsed(interpreter, "platform file open",
527 "Open a file on the remote end.", nullptr, 0),
530 ~CommandObjectPlatformFOpen() override = default;
532 bool DoExecute(Args &args, CommandReturnObject &result) override {
533 PlatformSP platform_sp(
534 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
537 std::string cmd_line;
538 args.GetCommandString(cmd_line);
540 const OptionPermissions *options_permissions =
541 (const OptionPermissions *)m_options.GetGroupWithOption('r');
542 if (options_permissions)
543 perms = options_permissions->m_permissions;
545 perms = lldb::eFilePermissionsUserRW | lldb::eFilePermissionsGroupRW |
546 lldb::eFilePermissionsWorldRead;
547 lldb::user_id_t fd = platform_sp->OpenFile(
548 FileSpec(cmd_line, false),
549 File::eOpenOptionRead | File::eOpenOptionWrite |
550 File::eOpenOptionAppend | File::eOpenOptionCanCreate,
552 if (error.Success()) {
553 result.AppendMessageWithFormat("File Descriptor = %" PRIu64 "\n", fd);
554 result.SetStatus(eReturnStatusSuccessFinishResult);
556 result.AppendError(error.AsCString());
557 result.SetStatus(eReturnStatusFailed);
560 result.AppendError("no platform currently selected\n");
561 result.SetStatus(eReturnStatusFailed);
563 return result.Succeeded();
566 Options *GetOptions() override {
567 if (!m_options.DidFinalize()) {
568 m_options.Append(new OptionPermissions());
569 m_options.Finalize();
574 OptionGroupOptions m_options;
577 //----------------------------------------------------------------------
579 //----------------------------------------------------------------------
580 class CommandObjectPlatformFClose : public CommandObjectParsed {
582 CommandObjectPlatformFClose(CommandInterpreter &interpreter)
583 : CommandObjectParsed(interpreter, "platform file close",
584 "Close a file on the remote end.", nullptr, 0) {}
586 ~CommandObjectPlatformFClose() override = default;
588 bool DoExecute(Args &args, CommandReturnObject &result) override {
589 PlatformSP platform_sp(
590 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
592 std::string cmd_line;
593 args.GetCommandString(cmd_line);
594 const lldb::user_id_t fd =
595 StringConvert::ToUInt64(cmd_line.c_str(), UINT64_MAX);
597 bool success = platform_sp->CloseFile(fd, error);
599 result.AppendMessageWithFormat("file %" PRIu64 " closed.\n", fd);
600 result.SetStatus(eReturnStatusSuccessFinishResult);
602 result.AppendError(error.AsCString());
603 result.SetStatus(eReturnStatusFailed);
606 result.AppendError("no platform currently selected\n");
607 result.SetStatus(eReturnStatusFailed);
609 return result.Succeeded();
613 //----------------------------------------------------------------------
615 //----------------------------------------------------------------------
617 static OptionDefinition g_platform_fread_options[] = {
619 { LLDB_OPT_SET_1, false, "offset", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeIndex, "Offset into the file at which to start reading." },
620 { LLDB_OPT_SET_1, false, "count", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCount, "Number of bytes to read from the file." },
624 class CommandObjectPlatformFRead : public CommandObjectParsed {
626 CommandObjectPlatformFRead(CommandInterpreter &interpreter)
627 : CommandObjectParsed(interpreter, "platform file read",
628 "Read data from a file on the remote end.", nullptr,
632 ~CommandObjectPlatformFRead() override = default;
634 bool DoExecute(Args &args, CommandReturnObject &result) override {
635 PlatformSP platform_sp(
636 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
638 std::string cmd_line;
639 args.GetCommandString(cmd_line);
640 const lldb::user_id_t fd =
641 StringConvert::ToUInt64(cmd_line.c_str(), UINT64_MAX);
642 std::string buffer(m_options.m_count, 0);
644 uint32_t retcode = platform_sp->ReadFile(
645 fd, m_options.m_offset, &buffer[0], m_options.m_count, error);
646 result.AppendMessageWithFormat("Return = %d\n", retcode);
647 result.AppendMessageWithFormat("Data = \"%s\"\n", buffer.c_str());
648 result.SetStatus(eReturnStatusSuccessFinishResult);
650 result.AppendError("no platform currently selected\n");
651 result.SetStatus(eReturnStatusFailed);
653 return result.Succeeded();
656 Options *GetOptions() override { return &m_options; }
659 class CommandOptions : public Options {
661 CommandOptions() : Options() {}
663 ~CommandOptions() override = default;
665 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
666 ExecutionContext *execution_context) override {
668 char short_option = (char)m_getopt_table[option_idx].val;
670 switch (short_option) {
672 if (option_arg.getAsInteger(0, m_offset))
673 error.SetErrorStringWithFormat("invalid offset: '%s'",
674 option_arg.str().c_str());
677 if (option_arg.getAsInteger(0, m_count))
678 error.SetErrorStringWithFormat("invalid offset: '%s'",
679 option_arg.str().c_str());
682 error.SetErrorStringWithFormat("unrecognized option '%c'",
690 void OptionParsingStarting(ExecutionContext *execution_context) override {
695 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
696 return llvm::makeArrayRef(g_platform_fread_options);
699 // Instance variables to hold the values for command options.
705 CommandOptions m_options;
708 //----------------------------------------------------------------------
710 //----------------------------------------------------------------------
712 static OptionDefinition g_platform_fwrite_options[] = {
714 { LLDB_OPT_SET_1, false, "offset", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeIndex, "Offset into the file at which to start reading." },
715 { LLDB_OPT_SET_1, false, "data", 'd', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeValue, "Text to write to the file." },
719 class CommandObjectPlatformFWrite : public CommandObjectParsed {
721 CommandObjectPlatformFWrite(CommandInterpreter &interpreter)
722 : CommandObjectParsed(interpreter, "platform file write",
723 "Write data to a file on the remote end.", nullptr,
727 ~CommandObjectPlatformFWrite() override = default;
729 bool DoExecute(Args &args, CommandReturnObject &result) override {
730 PlatformSP platform_sp(
731 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
733 std::string cmd_line;
734 args.GetCommandString(cmd_line);
736 const lldb::user_id_t fd =
737 StringConvert::ToUInt64(cmd_line.c_str(), UINT64_MAX);
739 platform_sp->WriteFile(fd, m_options.m_offset, &m_options.m_data[0],
740 m_options.m_data.size(), error);
741 result.AppendMessageWithFormat("Return = %d\n", retcode);
742 result.SetStatus(eReturnStatusSuccessFinishResult);
744 result.AppendError("no platform currently selected\n");
745 result.SetStatus(eReturnStatusFailed);
747 return result.Succeeded();
750 Options *GetOptions() override { return &m_options; }
753 class CommandOptions : public Options {
755 CommandOptions() : Options() {}
757 ~CommandOptions() override = default;
759 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
760 ExecutionContext *execution_context) override {
762 char short_option = (char)m_getopt_table[option_idx].val;
764 switch (short_option) {
766 if (option_arg.getAsInteger(0, m_offset))
767 error.SetErrorStringWithFormat("invalid offset: '%s'",
768 option_arg.str().c_str());
771 m_data.assign(option_arg);
774 error.SetErrorStringWithFormat("unrecognized option '%c'",
782 void OptionParsingStarting(ExecutionContext *execution_context) override {
787 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
788 return llvm::makeArrayRef(g_platform_fwrite_options);
791 // Instance variables to hold the values for command options.
797 CommandOptions m_options;
800 class CommandObjectPlatformFile : public CommandObjectMultiword {
802 //------------------------------------------------------------------
803 // Constructors and Destructors
804 //------------------------------------------------------------------
805 CommandObjectPlatformFile(CommandInterpreter &interpreter)
806 : CommandObjectMultiword(
807 interpreter, "platform file",
808 "Commands to access files on the current platform.",
809 "platform file [open|close|read|write] ...") {
811 "open", CommandObjectSP(new CommandObjectPlatformFOpen(interpreter)));
813 "close", CommandObjectSP(new CommandObjectPlatformFClose(interpreter)));
815 "read", CommandObjectSP(new CommandObjectPlatformFRead(interpreter)));
817 "write", CommandObjectSP(new CommandObjectPlatformFWrite(interpreter)));
820 ~CommandObjectPlatformFile() override = default;
823 //------------------------------------------------------------------
824 // For CommandObjectPlatform only
825 //------------------------------------------------------------------
826 DISALLOW_COPY_AND_ASSIGN(CommandObjectPlatformFile);
829 //----------------------------------------------------------------------
830 // "platform get-file remote-file-path host-file-path"
831 //----------------------------------------------------------------------
832 class CommandObjectPlatformGetFile : public CommandObjectParsed {
834 CommandObjectPlatformGetFile(CommandInterpreter &interpreter)
835 : CommandObjectParsed(
836 interpreter, "platform get-file",
837 "Transfer a file from the remote end to the local host.",
838 "platform get-file <remote-file-spec> <local-file-spec>", 0) {
842 (lldb) platform get-file /the/remote/file/path /the/local/file/path
844 Transfer a file from the remote end with file path /the/remote/file/path to the local host.)");
846 CommandArgumentEntry arg1, arg2;
847 CommandArgumentData file_arg_remote, file_arg_host;
849 // Define the first (and only) variant of this arg.
850 file_arg_remote.arg_type = eArgTypeFilename;
851 file_arg_remote.arg_repetition = eArgRepeatPlain;
852 // There is only one variant this argument could be; put it into the
854 arg1.push_back(file_arg_remote);
856 // Define the second (and only) variant of this arg.
857 file_arg_host.arg_type = eArgTypeFilename;
858 file_arg_host.arg_repetition = eArgRepeatPlain;
859 // There is only one variant this argument could be; put it into the
861 arg2.push_back(file_arg_host);
863 // Push the data for the first and the second arguments into the
864 // m_arguments vector.
865 m_arguments.push_back(arg1);
866 m_arguments.push_back(arg2);
869 ~CommandObjectPlatformGetFile() override = default;
871 bool DoExecute(Args &args, CommandReturnObject &result) override {
872 // If the number of arguments is incorrect, issue an error message.
873 if (args.GetArgumentCount() != 2) {
874 result.GetErrorStream().Printf("error: required arguments missing; "
875 "specify both the source and destination "
877 result.SetStatus(eReturnStatusFailed);
881 PlatformSP platform_sp(
882 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
884 const char *remote_file_path = args.GetArgumentAtIndex(0);
885 const char *local_file_path = args.GetArgumentAtIndex(1);
886 Status error = platform_sp->GetFile(FileSpec(remote_file_path, false),
887 FileSpec(local_file_path, false));
888 if (error.Success()) {
889 result.AppendMessageWithFormat(
890 "successfully get-file from %s (remote) to %s (host)\n",
891 remote_file_path, local_file_path);
892 result.SetStatus(eReturnStatusSuccessFinishResult);
894 result.AppendMessageWithFormat("get-file failed: %s\n",
896 result.SetStatus(eReturnStatusFailed);
899 result.AppendError("no platform currently selected\n");
900 result.SetStatus(eReturnStatusFailed);
902 return result.Succeeded();
906 //----------------------------------------------------------------------
907 // "platform get-size remote-file-path"
908 //----------------------------------------------------------------------
909 class CommandObjectPlatformGetSize : public CommandObjectParsed {
911 CommandObjectPlatformGetSize(CommandInterpreter &interpreter)
912 : CommandObjectParsed(interpreter, "platform get-size",
913 "Get the file size from the remote end.",
914 "platform get-size <remote-file-spec>", 0) {
918 (lldb) platform get-size /the/remote/file/path
920 Get the file size from the remote end with path /the/remote/file/path.)");
922 CommandArgumentEntry arg1;
923 CommandArgumentData file_arg_remote;
925 // Define the first (and only) variant of this arg.
926 file_arg_remote.arg_type = eArgTypeFilename;
927 file_arg_remote.arg_repetition = eArgRepeatPlain;
928 // There is only one variant this argument could be; put it into the
930 arg1.push_back(file_arg_remote);
932 // Push the data for the first argument into the m_arguments vector.
933 m_arguments.push_back(arg1);
936 ~CommandObjectPlatformGetSize() override = default;
938 bool DoExecute(Args &args, CommandReturnObject &result) override {
939 // If the number of arguments is incorrect, issue an error message.
940 if (args.GetArgumentCount() != 1) {
941 result.GetErrorStream().Printf("error: required argument missing; "
942 "specify the source file path as the only "
944 result.SetStatus(eReturnStatusFailed);
948 PlatformSP platform_sp(
949 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
951 std::string remote_file_path(args.GetArgumentAtIndex(0));
953 platform_sp->GetFileSize(FileSpec(remote_file_path, false));
954 if (size != UINT64_MAX) {
955 result.AppendMessageWithFormat("File size of %s (remote): %" PRIu64
957 remote_file_path.c_str(), size);
958 result.SetStatus(eReturnStatusSuccessFinishResult);
960 result.AppendMessageWithFormat(
961 "Error getting file size of %s (remote)\n",
962 remote_file_path.c_str());
963 result.SetStatus(eReturnStatusFailed);
966 result.AppendError("no platform currently selected\n");
967 result.SetStatus(eReturnStatusFailed);
969 return result.Succeeded();
973 //----------------------------------------------------------------------
974 // "platform put-file"
975 //----------------------------------------------------------------------
976 class CommandObjectPlatformPutFile : public CommandObjectParsed {
978 CommandObjectPlatformPutFile(CommandInterpreter &interpreter)
979 : CommandObjectParsed(
980 interpreter, "platform put-file",
981 "Transfer a file from this system to the remote end.", nullptr, 0) {
984 ~CommandObjectPlatformPutFile() override = default;
986 bool DoExecute(Args &args, CommandReturnObject &result) override {
987 const char *src = args.GetArgumentAtIndex(0);
988 const char *dst = args.GetArgumentAtIndex(1);
990 FileSpec src_fs(src, true);
991 FileSpec dst_fs(dst ? dst : src_fs.GetFilename().GetCString(), false);
993 PlatformSP platform_sp(
994 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
996 Status error(platform_sp->PutFile(src_fs, dst_fs));
997 if (error.Success()) {
998 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1000 result.AppendError(error.AsCString());
1001 result.SetStatus(eReturnStatusFailed);
1004 result.AppendError("no platform currently selected\n");
1005 result.SetStatus(eReturnStatusFailed);
1007 return result.Succeeded();
1011 //----------------------------------------------------------------------
1012 // "platform process launch"
1013 //----------------------------------------------------------------------
1014 class CommandObjectPlatformProcessLaunch : public CommandObjectParsed {
1016 CommandObjectPlatformProcessLaunch(CommandInterpreter &interpreter)
1017 : CommandObjectParsed(interpreter, "platform process launch",
1018 "Launch a new process on a remote platform.",
1019 "platform process launch program",
1020 eCommandRequiresTarget | eCommandTryTargetAPILock),
1023 ~CommandObjectPlatformProcessLaunch() override = default;
1025 Options *GetOptions() override { return &m_options; }
1028 bool DoExecute(Args &args, CommandReturnObject &result) override {
1029 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1030 PlatformSP platform_sp;
1032 platform_sp = target->GetPlatform();
1036 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform();
1041 const size_t argc = args.GetArgumentCount();
1042 Target *target = m_exe_ctx.GetTargetPtr();
1043 Module *exe_module = target->GetExecutableModulePointer();
1045 m_options.launch_info.GetExecutableFile() = exe_module->GetFileSpec();
1046 llvm::SmallString<PATH_MAX> exe_path;
1047 m_options.launch_info.GetExecutableFile().GetPath(exe_path);
1048 if (!exe_path.empty())
1049 m_options.launch_info.GetArguments().AppendArgument(exe_path);
1050 m_options.launch_info.GetArchitecture() = exe_module->GetArchitecture();
1054 if (m_options.launch_info.GetExecutableFile()) {
1055 // We already have an executable file, so we will use this and all
1056 // arguments to this function are extra arguments
1057 m_options.launch_info.GetArguments().AppendArguments(args);
1059 // We don't have any file yet, so the first argument is our
1060 // executable, and the rest are program arguments
1061 const bool first_arg_is_executable = true;
1062 m_options.launch_info.SetArguments(args, first_arg_is_executable);
1066 if (m_options.launch_info.GetExecutableFile()) {
1067 Debugger &debugger = m_interpreter.GetDebugger();
1070 target->GetRunArguments(m_options.launch_info.GetArguments());
1072 ProcessSP process_sp(platform_sp->DebugProcess(
1073 m_options.launch_info, debugger, target, error));
1074 if (process_sp && process_sp->IsAlive()) {
1075 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1079 if (error.Success())
1080 result.AppendError("process launch failed");
1082 result.AppendError(error.AsCString());
1083 result.SetStatus(eReturnStatusFailed);
1085 result.AppendError("'platform process launch' uses the current target "
1086 "file and arguments, or the executable and its "
1087 "arguments can be specified in this command");
1088 result.SetStatus(eReturnStatusFailed);
1092 result.AppendError("no platform is selected\n");
1094 return result.Succeeded();
1098 ProcessLaunchCommandOptions m_options;
1101 //----------------------------------------------------------------------
1102 // "platform process list"
1103 //----------------------------------------------------------------------
1105 OptionDefinition g_platform_process_list_options[] = {
1107 { LLDB_OPT_SET_1, false, "pid", 'p', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePid, "List the process info for a specific process ID." },
1108 { LLDB_OPT_SET_2, true, "name", 'n', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeProcessName, "Find processes with executable basenames that match a string." },
1109 { LLDB_OPT_SET_3, true, "ends-with", 'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeProcessName, "Find processes with executable basenames that end with a string." },
1110 { LLDB_OPT_SET_4, true, "starts-with", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeProcessName, "Find processes with executable basenames that start with a string." },
1111 { LLDB_OPT_SET_5, true, "contains", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeProcessName, "Find processes with executable basenames that contain a string." },
1112 { LLDB_OPT_SET_6, true, "regex", 'r', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeRegularExpression, "Find processes with executable basenames that match a regular expression." },
1113 { LLDB_OPT_SET_FROM_TO(2, 6), false, "parent", 'P', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePid, "Find processes that have a matching parent process ID." },
1114 { LLDB_OPT_SET_FROM_TO(2, 6), false, "uid", 'u', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeUnsignedInteger, "Find processes that have a matching user ID." },
1115 { LLDB_OPT_SET_FROM_TO(2, 6), false, "euid", 'U', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeUnsignedInteger, "Find processes that have a matching effective user ID." },
1116 { LLDB_OPT_SET_FROM_TO(2, 6), false, "gid", 'g', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeUnsignedInteger, "Find processes that have a matching group ID." },
1117 { LLDB_OPT_SET_FROM_TO(2, 6), false, "egid", 'G', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeUnsignedInteger, "Find processes that have a matching effective group ID." },
1118 { LLDB_OPT_SET_FROM_TO(2, 6), false, "arch", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeArchitecture, "Find processes that have a matching architecture." },
1119 { LLDB_OPT_SET_FROM_TO(1, 6), false, "show-args", 'A', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Show process arguments instead of the process executable basename." },
1120 { LLDB_OPT_SET_FROM_TO(1, 6), false, "verbose", 'v', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Enable verbose output." },
1124 class CommandObjectPlatformProcessList : public CommandObjectParsed {
1126 CommandObjectPlatformProcessList(CommandInterpreter &interpreter)
1127 : CommandObjectParsed(interpreter, "platform process list",
1128 "List processes on a remote platform by name, pid, "
1129 "or many other matching attributes.",
1130 "platform process list", 0),
1133 ~CommandObjectPlatformProcessList() override = default;
1135 Options *GetOptions() override { return &m_options; }
1138 bool DoExecute(Args &args, CommandReturnObject &result) override {
1139 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1140 PlatformSP platform_sp;
1142 platform_sp = target->GetPlatform();
1146 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform();
1151 if (args.GetArgumentCount() == 0) {
1153 Stream &ostrm = result.GetOutputStream();
1156 m_options.match_info.GetProcessInfo().GetProcessID();
1157 if (pid != LLDB_INVALID_PROCESS_ID) {
1158 ProcessInstanceInfo proc_info;
1159 if (platform_sp->GetProcessInfo(pid, proc_info)) {
1160 ProcessInstanceInfo::DumpTableHeader(ostrm, platform_sp.get(),
1161 m_options.show_args,
1163 proc_info.DumpAsTableRow(ostrm, platform_sp.get(),
1164 m_options.show_args, m_options.verbose);
1165 result.SetStatus(eReturnStatusSuccessFinishResult);
1167 result.AppendErrorWithFormat(
1168 "no process found with pid = %" PRIu64 "\n", pid);
1169 result.SetStatus(eReturnStatusFailed);
1172 ProcessInstanceInfoList proc_infos;
1173 const uint32_t matches =
1174 platform_sp->FindProcesses(m_options.match_info, proc_infos);
1175 const char *match_desc = nullptr;
1176 const char *match_name =
1177 m_options.match_info.GetProcessInfo().GetName();
1178 if (match_name && match_name[0]) {
1179 switch (m_options.match_info.GetNameMatchType()) {
1180 case NameMatch::Ignore:
1182 case NameMatch::Equals:
1183 match_desc = "matched";
1185 case NameMatch::Contains:
1186 match_desc = "contained";
1188 case NameMatch::StartsWith:
1189 match_desc = "started with";
1191 case NameMatch::EndsWith:
1192 match_desc = "ended with";
1194 case NameMatch::RegularExpression:
1195 match_desc = "matched the regular expression";
1202 result.AppendErrorWithFormat(
1203 "no processes were found that %s \"%s\" on the \"%s\" "
1205 match_desc, match_name,
1206 platform_sp->GetPluginName().GetCString());
1208 result.AppendErrorWithFormat(
1209 "no processes were found on the \"%s\" platform\n",
1210 platform_sp->GetPluginName().GetCString());
1211 result.SetStatus(eReturnStatusFailed);
1213 result.AppendMessageWithFormat(
1214 "%u matching process%s found on \"%s\"", matches,
1215 matches > 1 ? "es were" : " was",
1216 platform_sp->GetName().GetCString());
1218 result.AppendMessageWithFormat(" whose name %s \"%s\"",
1219 match_desc, match_name);
1220 result.AppendMessageWithFormat("\n");
1221 ProcessInstanceInfo::DumpTableHeader(ostrm, platform_sp.get(),
1222 m_options.show_args,
1224 for (uint32_t i = 0; i < matches; ++i) {
1225 proc_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
1226 ostrm, platform_sp.get(), m_options.show_args,
1233 result.AppendError("invalid args: process list takes only options\n");
1234 result.SetStatus(eReturnStatusFailed);
1237 result.AppendError("no platform is selected\n");
1238 result.SetStatus(eReturnStatusFailed);
1240 return result.Succeeded();
1243 class CommandOptions : public Options {
1246 : Options(), match_info(), show_args(false), verbose(false) {
1247 static llvm::once_flag g_once_flag;
1248 llvm::call_once(g_once_flag, []() {
1249 PosixPlatformCommandOptionValidator *posix_validator =
1250 new PosixPlatformCommandOptionValidator();
1251 for (auto &Option : g_platform_process_list_options) {
1252 switch (Option.short_option) {
1257 Option.validator = posix_validator;
1266 ~CommandOptions() override = default;
1268 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1269 ExecutionContext *execution_context) override {
1271 const int short_option = m_getopt_table[option_idx].val;
1272 bool success = false;
1274 uint32_t id = LLDB_INVALID_PROCESS_ID;
1275 success = !option_arg.getAsInteger(0, id);
1276 switch (short_option) {
1278 match_info.GetProcessInfo().SetProcessID(id);
1280 error.SetErrorStringWithFormat("invalid process ID string: '%s'",
1281 option_arg.str().c_str());
1285 match_info.GetProcessInfo().SetParentProcessID(id);
1287 error.SetErrorStringWithFormat(
1288 "invalid parent process ID string: '%s'",
1289 option_arg.str().c_str());
1293 match_info.GetProcessInfo().SetUserID(success ? id : UINT32_MAX);
1295 error.SetErrorStringWithFormat("invalid user ID string: '%s'",
1296 option_arg.str().c_str());
1300 match_info.GetProcessInfo().SetEffectiveUserID(success ? id
1303 error.SetErrorStringWithFormat(
1304 "invalid effective user ID string: '%s'",
1305 option_arg.str().c_str());
1309 match_info.GetProcessInfo().SetGroupID(success ? id : UINT32_MAX);
1311 error.SetErrorStringWithFormat("invalid group ID string: '%s'",
1312 option_arg.str().c_str());
1316 match_info.GetProcessInfo().SetEffectiveGroupID(success ? id
1319 error.SetErrorStringWithFormat(
1320 "invalid effective group ID string: '%s'",
1321 option_arg.str().c_str());
1325 TargetSP target_sp =
1326 execution_context ? execution_context->GetTargetSP() : TargetSP();
1327 DebuggerSP debugger_sp =
1328 target_sp ? target_sp->GetDebugger().shared_from_this()
1330 PlatformSP platform_sp =
1331 debugger_sp ? debugger_sp->GetPlatformList().GetSelectedPlatform()
1333 match_info.GetProcessInfo().GetArchitecture() =
1334 Platform::GetAugmentedArchSpec(platform_sp.get(), option_arg);
1338 match_info.GetProcessInfo().GetExecutableFile().SetFile(
1339 option_arg, false, FileSpec::Style::native);
1340 match_info.SetNameMatchType(NameMatch::Equals);
1344 match_info.GetProcessInfo().GetExecutableFile().SetFile(
1345 option_arg, false, FileSpec::Style::native);
1346 match_info.SetNameMatchType(NameMatch::EndsWith);
1350 match_info.GetProcessInfo().GetExecutableFile().SetFile(
1351 option_arg, false, FileSpec::Style::native);
1352 match_info.SetNameMatchType(NameMatch::StartsWith);
1356 match_info.GetProcessInfo().GetExecutableFile().SetFile(
1357 option_arg, false, FileSpec::Style::native);
1358 match_info.SetNameMatchType(NameMatch::Contains);
1362 match_info.GetProcessInfo().GetExecutableFile().SetFile(
1363 option_arg, false, FileSpec::Style::native);
1364 match_info.SetNameMatchType(NameMatch::RegularExpression);
1376 error.SetErrorStringWithFormat("unrecognized option '%c'",
1384 void OptionParsingStarting(ExecutionContext *execution_context) override {
1390 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1391 return llvm::makeArrayRef(g_platform_process_list_options);
1394 // Instance variables to hold the values for command options.
1396 ProcessInstanceInfoMatch match_info;
1401 CommandOptions m_options;
1404 //----------------------------------------------------------------------
1405 // "platform process info"
1406 //----------------------------------------------------------------------
1407 class CommandObjectPlatformProcessInfo : public CommandObjectParsed {
1409 CommandObjectPlatformProcessInfo(CommandInterpreter &interpreter)
1410 : CommandObjectParsed(
1411 interpreter, "platform process info",
1412 "Get detailed information for one or more process by process ID.",
1413 "platform process info <pid> [<pid> <pid> ...]", 0) {
1414 CommandArgumentEntry arg;
1415 CommandArgumentData pid_args;
1417 // Define the first (and only) variant of this arg.
1418 pid_args.arg_type = eArgTypePid;
1419 pid_args.arg_repetition = eArgRepeatStar;
1421 // There is only one variant this argument could be; put it into the
1423 arg.push_back(pid_args);
1425 // Push the data for the first argument into the m_arguments vector.
1426 m_arguments.push_back(arg);
1429 ~CommandObjectPlatformProcessInfo() override = default;
1432 bool DoExecute(Args &args, CommandReturnObject &result) override {
1433 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1434 PlatformSP platform_sp;
1436 platform_sp = target->GetPlatform();
1440 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform();
1444 const size_t argc = args.GetArgumentCount();
1448 if (platform_sp->IsConnected()) {
1449 Stream &ostrm = result.GetOutputStream();
1450 for (auto &entry : args.entries()) {
1452 if (entry.ref.getAsInteger(0, pid)) {
1453 result.AppendErrorWithFormat("invalid process ID argument '%s'",
1454 entry.ref.str().c_str());
1455 result.SetStatus(eReturnStatusFailed);
1458 ProcessInstanceInfo proc_info;
1459 if (platform_sp->GetProcessInfo(pid, proc_info)) {
1460 ostrm.Printf("Process information for process %" PRIu64 ":\n",
1462 proc_info.Dump(ostrm, platform_sp.get());
1464 ostrm.Printf("error: no process information is available for "
1465 "process %" PRIu64 "\n",
1473 result.AppendErrorWithFormat(
1474 "not connected to '%s'",
1475 platform_sp->GetPluginName().GetCString());
1476 result.SetStatus(eReturnStatusFailed);
1480 result.AppendError("one or more process id(s) must be specified");
1481 result.SetStatus(eReturnStatusFailed);
1484 result.AppendError("no platform is currently selected");
1485 result.SetStatus(eReturnStatusFailed);
1487 return result.Succeeded();
1491 static OptionDefinition g_platform_process_attach_options[] = {
1493 { LLDB_OPT_SET_ALL, false, "plugin", 'P', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePlugin, "Name of the process plugin you want to use." },
1494 { LLDB_OPT_SET_1, false, "pid", 'p', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePid, "The process ID of an existing process to attach to." },
1495 { LLDB_OPT_SET_2, false, "name", 'n', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeProcessName, "The name of the process to attach to." },
1496 { LLDB_OPT_SET_2, false, "waitfor", 'w', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Wait for the process with <process-name> to launch." },
1500 class CommandObjectPlatformProcessAttach : public CommandObjectParsed {
1502 class CommandOptions : public Options {
1504 CommandOptions() : Options() {
1505 // Keep default values of all options in one place: OptionParsingStarting
1507 OptionParsingStarting(nullptr);
1510 ~CommandOptions() override = default;
1512 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1513 ExecutionContext *execution_context) override {
1515 char short_option = (char)m_getopt_table[option_idx].val;
1516 switch (short_option) {
1518 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1519 if (option_arg.getAsInteger(0, pid)) {
1520 error.SetErrorStringWithFormat("invalid process ID '%s'",
1521 option_arg.str().c_str());
1523 attach_info.SetProcessID(pid);
1528 attach_info.SetProcessPluginName(option_arg);
1532 attach_info.GetExecutableFile().SetFile(option_arg, false,
1533 FileSpec::Style::native);
1537 attach_info.SetWaitForLaunch(true);
1541 error.SetErrorStringWithFormat("invalid short option character '%c'",
1548 void OptionParsingStarting(ExecutionContext *execution_context) override {
1549 attach_info.Clear();
1552 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1553 return llvm::makeArrayRef(g_platform_process_attach_options);
1556 bool HandleOptionArgumentCompletion(
1557 CompletionRequest &request, OptionElementVector &opt_element_vector,
1558 int opt_element_index, CommandInterpreter &interpreter) override {
1559 int opt_arg_pos = opt_element_vector[opt_element_index].opt_arg_pos;
1560 int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index;
1562 // We are only completing the name option for now...
1564 if (GetDefinitions()[opt_defs_index].short_option == 'n') {
1565 // Are we in the name?
1567 // Look to see if there is a -P argument provided, and if so use that
1568 // plugin, otherwise use the default plugin.
1570 const char *partial_name = nullptr;
1571 partial_name = request.GetParsedLine().GetArgumentAtIndex(opt_arg_pos);
1573 PlatformSP platform_sp(interpreter.GetPlatform(true));
1575 ProcessInstanceInfoList process_infos;
1576 ProcessInstanceInfoMatch match_info;
1578 match_info.GetProcessInfo().GetExecutableFile().SetFile(
1579 partial_name, false, FileSpec::Style::native);
1580 match_info.SetNameMatchType(NameMatch::StartsWith);
1582 platform_sp->FindProcesses(match_info, process_infos);
1583 const uint32_t num_matches = process_infos.GetSize();
1584 if (num_matches > 0) {
1585 for (uint32_t i = 0; i < num_matches; ++i) {
1586 request.AddCompletion(llvm::StringRef(
1587 process_infos.GetProcessNameAtIndex(i),
1588 process_infos.GetProcessNameLengthAtIndex(i)));
1597 // Options table: Required for subclasses of Options.
1599 static OptionDefinition g_option_table[];
1601 // Instance variables to hold the values for command options.
1603 ProcessAttachInfo attach_info;
1606 CommandObjectPlatformProcessAttach(CommandInterpreter &interpreter)
1607 : CommandObjectParsed(interpreter, "platform process attach",
1608 "Attach to a process.",
1609 "platform process attach <cmd-options>"),
1612 ~CommandObjectPlatformProcessAttach() override = default;
1614 bool DoExecute(Args &command, CommandReturnObject &result) override {
1615 PlatformSP platform_sp(
1616 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
1619 ProcessSP remote_process_sp = platform_sp->Attach(
1620 m_options.attach_info, m_interpreter.GetDebugger(), nullptr, err);
1622 result.AppendError(err.AsCString());
1623 result.SetStatus(eReturnStatusFailed);
1624 } else if (!remote_process_sp) {
1625 result.AppendError("could not attach: unknown reason");
1626 result.SetStatus(eReturnStatusFailed);
1628 result.SetStatus(eReturnStatusSuccessFinishResult);
1630 result.AppendError("no platform is currently selected");
1631 result.SetStatus(eReturnStatusFailed);
1633 return result.Succeeded();
1636 Options *GetOptions() override { return &m_options; }
1639 CommandOptions m_options;
1642 class CommandObjectPlatformProcess : public CommandObjectMultiword {
1644 //------------------------------------------------------------------
1645 // Constructors and Destructors
1646 //------------------------------------------------------------------
1647 CommandObjectPlatformProcess(CommandInterpreter &interpreter)
1648 : CommandObjectMultiword(interpreter, "platform process",
1649 "Commands to query, launch and attach to "
1650 "processes on the current platform.",
1651 "platform process [attach|launch|list] ...") {
1654 CommandObjectSP(new CommandObjectPlatformProcessAttach(interpreter)));
1657 CommandObjectSP(new CommandObjectPlatformProcessLaunch(interpreter)));
1658 LoadSubCommand("info", CommandObjectSP(new CommandObjectPlatformProcessInfo(
1660 LoadSubCommand("list", CommandObjectSP(new CommandObjectPlatformProcessList(
1664 ~CommandObjectPlatformProcess() override = default;
1667 //------------------------------------------------------------------
1668 // For CommandObjectPlatform only
1669 //------------------------------------------------------------------
1670 DISALLOW_COPY_AND_ASSIGN(CommandObjectPlatformProcess);
1673 //----------------------------------------------------------------------
1675 //----------------------------------------------------------------------
1676 static OptionDefinition g_platform_shell_options[] = {
1678 { LLDB_OPT_SET_ALL, false, "timeout", 't', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeValue, "Seconds to wait for the remote host to finish running the command." },
1682 class CommandObjectPlatformShell : public CommandObjectRaw {
1684 class CommandOptions : public Options {
1686 CommandOptions() : Options() {}
1688 ~CommandOptions() override = default;
1690 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1691 return llvm::makeArrayRef(g_platform_shell_options);
1694 Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1695 ExecutionContext *execution_context) override {
1698 const char short_option = (char)GetDefinitions()[option_idx].short_option;
1700 switch (short_option) {
1702 uint32_t timeout_sec;
1703 if (option_arg.getAsInteger(10, timeout_sec))
1704 error.SetErrorStringWithFormat(
1705 "could not convert \"%s\" to a numeric value.",
1706 option_arg.str().c_str());
1708 timeout = std::chrono::seconds(timeout_sec);
1711 error.SetErrorStringWithFormat("invalid short option character '%c'",
1719 void OptionParsingStarting(ExecutionContext *execution_context) override {}
1721 Timeout<std::micro> timeout = std::chrono::seconds(10);
1724 CommandObjectPlatformShell(CommandInterpreter &interpreter)
1725 : CommandObjectRaw(interpreter, "platform shell",
1726 "Run a shell command on the current platform.",
1727 "platform shell <shell-command>", 0),
1730 ~CommandObjectPlatformShell() override = default;
1732 Options *GetOptions() override { return &m_options; }
1734 bool DoExecute(llvm::StringRef raw_command_line,
1735 CommandReturnObject &result) override {
1736 ExecutionContext exe_ctx = GetCommandInterpreter().GetExecutionContext();
1737 m_options.NotifyOptionParsingStarting(&exe_ctx);
1740 // Print out an usage syntax on an empty command line.
1741 if (raw_command_line.empty()) {
1742 result.GetOutputStream().Printf("%s\n", this->GetSyntax().str().c_str());
1746 OptionsWithRaw args(raw_command_line);
1747 const char *expr = args.GetRawPart().c_str();
1750 if (!ParseOptions(args.GetArgs(), result))
1753 PlatformSP platform_sp(
1754 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
1757 FileSpec working_dir{};
1761 error = (platform_sp->RunShellCommand(expr, working_dir, &status, &signo,
1762 &output, m_options.timeout));
1763 if (!output.empty())
1764 result.GetOutputStream().PutCString(output);
1767 const char *signo_cstr = Host::GetSignalAsCString(signo);
1769 result.GetOutputStream().Printf(
1770 "error: command returned with status %i and signal %s\n",
1771 status, signo_cstr);
1773 result.GetOutputStream().Printf(
1774 "error: command returned with status %i and signal %i\n",
1777 result.GetOutputStream().Printf(
1778 "error: command returned with status %i\n", status);
1781 result.GetOutputStream().Printf(
1782 "error: cannot run remote shell commands without a platform\n");
1783 error.SetErrorString(
1784 "error: cannot run remote shell commands without a platform");
1788 result.AppendError(error.AsCString());
1789 result.SetStatus(eReturnStatusFailed);
1791 result.SetStatus(eReturnStatusSuccessFinishResult);
1796 CommandOptions m_options;
1799 //----------------------------------------------------------------------
1800 // "platform install" - install a target to a remote end
1801 //----------------------------------------------------------------------
1802 class CommandObjectPlatformInstall : public CommandObjectParsed {
1804 CommandObjectPlatformInstall(CommandInterpreter &interpreter)
1805 : CommandObjectParsed(
1806 interpreter, "platform target-install",
1807 "Install a target (bundle or executable file) to the remote end.",
1808 "platform target-install <local-thing> <remote-sandbox>", 0) {}
1810 ~CommandObjectPlatformInstall() override = default;
1812 bool DoExecute(Args &args, CommandReturnObject &result) override {
1813 if (args.GetArgumentCount() != 2) {
1814 result.AppendError("platform target-install takes two arguments");
1815 result.SetStatus(eReturnStatusFailed);
1818 // TODO: move the bulk of this code over to the platform itself
1819 FileSpec src(args.GetArgumentAtIndex(0), true);
1820 FileSpec dst(args.GetArgumentAtIndex(1), false);
1821 if (!src.Exists()) {
1822 result.AppendError("source location does not exist or is not accessible");
1823 result.SetStatus(eReturnStatusFailed);
1826 PlatformSP platform_sp(
1827 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
1829 result.AppendError("no platform currently selected");
1830 result.SetStatus(eReturnStatusFailed);
1834 Status error = platform_sp->Install(src, dst);
1835 if (error.Success()) {
1836 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1838 result.AppendErrorWithFormat("install failed: %s", error.AsCString());
1839 result.SetStatus(eReturnStatusFailed);
1841 return result.Succeeded();
1845 CommandObjectPlatform::CommandObjectPlatform(CommandInterpreter &interpreter)
1846 : CommandObjectMultiword(
1847 interpreter, "platform", "Commands to manage and create platforms.",
1848 "platform [connect|disconnect|info|list|status|select] ...") {
1849 LoadSubCommand("select",
1850 CommandObjectSP(new CommandObjectPlatformSelect(interpreter)));
1851 LoadSubCommand("list",
1852 CommandObjectSP(new CommandObjectPlatformList(interpreter)));
1853 LoadSubCommand("status",
1854 CommandObjectSP(new CommandObjectPlatformStatus(interpreter)));
1855 LoadSubCommand("connect", CommandObjectSP(
1856 new CommandObjectPlatformConnect(interpreter)));
1859 CommandObjectSP(new CommandObjectPlatformDisconnect(interpreter)));
1860 LoadSubCommand("settings", CommandObjectSP(new CommandObjectPlatformSettings(
1862 LoadSubCommand("mkdir",
1863 CommandObjectSP(new CommandObjectPlatformMkDir(interpreter)));
1864 LoadSubCommand("file",
1865 CommandObjectSP(new CommandObjectPlatformFile(interpreter)));
1866 LoadSubCommand("get-file", CommandObjectSP(new CommandObjectPlatformGetFile(
1868 LoadSubCommand("get-size", CommandObjectSP(new CommandObjectPlatformGetSize(
1870 LoadSubCommand("put-file", CommandObjectSP(new CommandObjectPlatformPutFile(
1872 LoadSubCommand("process", CommandObjectSP(
1873 new CommandObjectPlatformProcess(interpreter)));
1874 LoadSubCommand("shell",
1875 CommandObjectSP(new CommandObjectPlatformShell(interpreter)));
1878 CommandObjectSP(new CommandObjectPlatformInstall(interpreter)));
1881 CommandObjectPlatform::~CommandObjectPlatform() = default;