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/DataExtractor.h"
17 #include "lldb/Core/Debugger.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/PluginManager.h"
20 #include "lldb/Host/StringConvert.h"
21 #include "lldb/Interpreter/Args.h"
22 #include "lldb/Interpreter/CommandInterpreter.h"
23 #include "lldb/Interpreter/CommandOptionValidators.h"
24 #include "lldb/Interpreter/CommandReturnObject.h"
25 #include "lldb/Interpreter/OptionGroupFile.h"
26 #include "lldb/Interpreter/OptionGroupPlatform.h"
27 #include "lldb/Target/ExecutionContext.h"
28 #include "lldb/Target/Platform.h"
29 #include "lldb/Target/Process.h"
30 #include "lldb/Utility/Utils.h"
32 #include "llvm/ADT/SmallString.h"
35 using namespace lldb_private;
37 static mode_t ParsePermissionString(const char *) = delete;
39 static mode_t ParsePermissionString(llvm::StringRef permissions) {
40 if (permissions.size() != 9)
42 bool user_r, user_w, user_x, group_r, group_w, group_x, world_r, world_w,
45 user_r = (permissions[0] == 'r');
46 user_w = (permissions[1] == 'w');
47 user_x = (permissions[2] == 'x');
49 group_r = (permissions[3] == 'r');
50 group_w = (permissions[4] == 'w');
51 group_x = (permissions[5] == 'x');
53 world_r = (permissions[6] == 'r');
54 world_w = (permissions[7] == 'w');
55 world_x = (permissions[8] == 'x');
57 mode_t user, group, world;
58 user = (user_r ? 4 : 0) | (user_w ? 2 : 0) | (user_x ? 1 : 0);
59 group = (group_r ? 4 : 0) | (group_w ? 2 : 0) | (group_x ? 1 : 0);
60 world = (world_r ? 4 : 0) | (world_w ? 2 : 0) | (world_x ? 1 : 0);
62 return user | group | world;
65 static OptionDefinition g_permissions_options[] = {
67 {LLDB_OPT_SET_ALL, false, "permissions-value", 'v', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePermissionsNumber, "Give out the numeric value for permissions (e.g. 757)"},
68 {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--)."},
69 {LLDB_OPT_SET_ALL, false, "user-read", 'r', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow user to read."},
70 {LLDB_OPT_SET_ALL, false, "user-write", 'w', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow user to write."},
71 {LLDB_OPT_SET_ALL, false, "user-exec", 'x', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow user to execute."},
72 {LLDB_OPT_SET_ALL, false, "group-read", 'R', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow group to read."},
73 {LLDB_OPT_SET_ALL, false, "group-write", 'W', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow group to write."},
74 {LLDB_OPT_SET_ALL, false, "group-exec", 'X', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow group to execute."},
75 {LLDB_OPT_SET_ALL, false, "world-read", 'd', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow world to read."},
76 {LLDB_OPT_SET_ALL, false, "world-write", 't', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow world to write."},
77 {LLDB_OPT_SET_ALL, false, "world-exec", 'e', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Allow world to execute."},
81 class OptionPermissions : public OptionGroup {
83 OptionPermissions() {}
85 ~OptionPermissions() override = default;
88 SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
89 ExecutionContext *execution_context) override {
91 char short_option = (char)GetDefinitions()[option_idx].short_option;
92 switch (short_option) {
94 if (option_arg.getAsInteger(8, m_permissions)) {
96 error.SetErrorStringWithFormat("invalid value for permissions: %s",
97 option_arg.str().c_str());
102 mode_t perms = ParsePermissionString(option_arg);
103 if (perms == (mode_t)-1)
104 error.SetErrorStringWithFormat("invalid value for permissions: %s",
105 option_arg.str().c_str());
107 m_permissions = perms;
110 m_permissions |= lldb::eFilePermissionsUserRead;
113 m_permissions |= lldb::eFilePermissionsUserWrite;
116 m_permissions |= lldb::eFilePermissionsUserExecute;
119 m_permissions |= lldb::eFilePermissionsGroupRead;
122 m_permissions |= lldb::eFilePermissionsGroupWrite;
125 m_permissions |= lldb::eFilePermissionsGroupExecute;
128 m_permissions |= lldb::eFilePermissionsWorldRead;
131 m_permissions |= lldb::eFilePermissionsWorldWrite;
134 m_permissions |= lldb::eFilePermissionsWorldExecute;
137 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
144 void OptionParsingStarting(ExecutionContext *execution_context) override {
148 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
149 return llvm::makeArrayRef(g_permissions_options);
152 // Instance variables to hold the values for command options.
154 uint32_t m_permissions;
157 DISALLOW_COPY_AND_ASSIGN(OptionPermissions);
160 //----------------------------------------------------------------------
161 // "platform select <platform-name>"
162 //----------------------------------------------------------------------
163 class CommandObjectPlatformSelect : public CommandObjectParsed {
165 CommandObjectPlatformSelect(CommandInterpreter &interpreter)
166 : CommandObjectParsed(interpreter, "platform select",
167 "Create a platform if needed and select it as the "
169 "platform select <platform-name>", 0),
172 false) // Don't include the "--platform" option by passing false
174 m_option_group.Append(&m_platform_options, LLDB_OPT_SET_ALL, 1);
175 m_option_group.Finalize();
178 ~CommandObjectPlatformSelect() override = default;
180 int HandleCompletion(Args &input, int &cursor_index,
181 int &cursor_char_position, int match_start_point,
182 int max_return_elements, bool &word_complete,
183 StringList &matches) override {
184 std::string completion_str(input.GetArgumentAtIndex(cursor_index));
185 completion_str.erase(cursor_char_position);
187 CommandCompletions::PlatformPluginNames(
188 GetCommandInterpreter(), completion_str.c_str(), match_start_point,
189 max_return_elements, nullptr, word_complete, matches);
190 return matches.GetSize();
193 Options *GetOptions() override { return &m_option_group; }
196 bool DoExecute(Args &args, CommandReturnObject &result) override {
197 if (args.GetArgumentCount() == 1) {
198 const char *platform_name = args.GetArgumentAtIndex(0);
199 if (platform_name && platform_name[0]) {
200 const bool select = true;
201 m_platform_options.SetPlatformName(platform_name);
203 ArchSpec platform_arch;
204 PlatformSP platform_sp(m_platform_options.CreatePlatformWithOptions(
205 m_interpreter, ArchSpec(), select, error, platform_arch));
207 m_interpreter.GetDebugger().GetPlatformList().SetSelectedPlatform(
210 platform_sp->GetStatus(result.GetOutputStream());
211 result.SetStatus(eReturnStatusSuccessFinishResult);
213 result.AppendError(error.AsCString());
214 result.SetStatus(eReturnStatusFailed);
217 result.AppendError("invalid platform name");
218 result.SetStatus(eReturnStatusFailed);
222 "platform create takes a platform name as an argument\n");
223 result.SetStatus(eReturnStatusFailed);
225 return result.Succeeded();
228 OptionGroupOptions m_option_group;
229 OptionGroupPlatform m_platform_options;
232 //----------------------------------------------------------------------
234 //----------------------------------------------------------------------
235 class CommandObjectPlatformList : public CommandObjectParsed {
237 CommandObjectPlatformList(CommandInterpreter &interpreter)
238 : CommandObjectParsed(interpreter, "platform list",
239 "List all platforms that are available.", nullptr,
242 ~CommandObjectPlatformList() override = default;
245 bool DoExecute(Args &args, CommandReturnObject &result) override {
246 Stream &ostrm = result.GetOutputStream();
247 ostrm.Printf("Available platforms:\n");
249 PlatformSP host_platform_sp(Platform::GetHostPlatform());
250 ostrm.Printf("%s: %s\n", host_platform_sp->GetPluginName().GetCString(),
251 host_platform_sp->GetDescription());
254 for (idx = 0; 1; ++idx) {
255 const char *plugin_name =
256 PluginManager::GetPlatformPluginNameAtIndex(idx);
257 if (plugin_name == nullptr)
259 const char *plugin_desc =
260 PluginManager::GetPlatformPluginDescriptionAtIndex(idx);
261 if (plugin_desc == nullptr)
263 ostrm.Printf("%s: %s\n", plugin_name, plugin_desc);
267 result.AppendError("no platforms are available\n");
268 result.SetStatus(eReturnStatusFailed);
270 result.SetStatus(eReturnStatusSuccessFinishResult);
271 return result.Succeeded();
275 //----------------------------------------------------------------------
277 //----------------------------------------------------------------------
278 class CommandObjectPlatformStatus : public CommandObjectParsed {
280 CommandObjectPlatformStatus(CommandInterpreter &interpreter)
281 : CommandObjectParsed(interpreter, "platform status",
282 "Display status for the current platform.", nullptr,
285 ~CommandObjectPlatformStatus() override = default;
288 bool DoExecute(Args &args, CommandReturnObject &result) override {
289 Stream &ostrm = result.GetOutputStream();
291 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
292 PlatformSP platform_sp;
294 platform_sp = target->GetPlatform();
298 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform();
301 platform_sp->GetStatus(ostrm);
302 result.SetStatus(eReturnStatusSuccessFinishResult);
304 result.AppendError("no platform us currently selected\n");
305 result.SetStatus(eReturnStatusFailed);
307 return result.Succeeded();
311 //----------------------------------------------------------------------
312 // "platform connect <connect-url>"
313 //----------------------------------------------------------------------
314 class CommandObjectPlatformConnect : public CommandObjectParsed {
316 CommandObjectPlatformConnect(CommandInterpreter &interpreter)
317 : CommandObjectParsed(
318 interpreter, "platform connect",
319 "Select the current platform by providing a connection URL.",
320 "platform connect <connect-url>", 0) {}
322 ~CommandObjectPlatformConnect() override = default;
325 bool DoExecute(Args &args, CommandReturnObject &result) override {
326 Stream &ostrm = result.GetOutputStream();
328 PlatformSP platform_sp(
329 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
331 Error error(platform_sp->ConnectRemote(args));
332 if (error.Success()) {
333 platform_sp->GetStatus(ostrm);
334 result.SetStatus(eReturnStatusSuccessFinishResult);
336 platform_sp->ConnectToWaitingProcesses(m_interpreter.GetDebugger(),
339 result.AppendError(error.AsCString());
340 result.SetStatus(eReturnStatusFailed);
343 result.AppendErrorWithFormat("%s\n", error.AsCString());
344 result.SetStatus(eReturnStatusFailed);
347 result.AppendError("no platform is currently selected\n");
348 result.SetStatus(eReturnStatusFailed);
350 return result.Succeeded();
353 Options *GetOptions() override {
354 PlatformSP platform_sp(
355 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
356 OptionGroupOptions *m_platform_options = nullptr;
358 m_platform_options = platform_sp->GetConnectionOptions(m_interpreter);
359 if (m_platform_options != nullptr && !m_platform_options->m_did_finalize)
360 m_platform_options->Finalize();
362 return m_platform_options;
366 //----------------------------------------------------------------------
367 // "platform disconnect"
368 //----------------------------------------------------------------------
369 class CommandObjectPlatformDisconnect : public CommandObjectParsed {
371 CommandObjectPlatformDisconnect(CommandInterpreter &interpreter)
372 : CommandObjectParsed(interpreter, "platform disconnect",
373 "Disconnect from the current platform.",
374 "platform disconnect", 0) {}
376 ~CommandObjectPlatformDisconnect() override = default;
379 bool DoExecute(Args &args, CommandReturnObject &result) override {
380 PlatformSP platform_sp(
381 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
383 if (args.GetArgumentCount() == 0) {
386 if (platform_sp->IsConnected()) {
387 // Cache the instance name if there is one since we are
388 // about to disconnect and the name might go with it.
389 const char *hostname_cstr = platform_sp->GetHostname();
390 std::string hostname;
392 hostname.assign(hostname_cstr);
394 error = platform_sp->DisconnectRemote();
395 if (error.Success()) {
396 Stream &ostrm = result.GetOutputStream();
397 if (hostname.empty())
398 ostrm.Printf("Disconnected from \"%s\"\n",
399 platform_sp->GetPluginName().GetCString());
401 ostrm.Printf("Disconnected from \"%s\"\n", hostname.c_str());
402 result.SetStatus(eReturnStatusSuccessFinishResult);
404 result.AppendErrorWithFormat("%s", error.AsCString());
405 result.SetStatus(eReturnStatusFailed);
409 result.AppendErrorWithFormat(
410 "not connected to '%s'",
411 platform_sp->GetPluginName().GetCString());
412 result.SetStatus(eReturnStatusFailed);
417 "\"platform disconnect\" doesn't take any arguments");
418 result.SetStatus(eReturnStatusFailed);
421 result.AppendError("no platform is currently selected");
422 result.SetStatus(eReturnStatusFailed);
424 return result.Succeeded();
428 //----------------------------------------------------------------------
429 // "platform settings"
430 //----------------------------------------------------------------------
431 class CommandObjectPlatformSettings : public CommandObjectParsed {
433 CommandObjectPlatformSettings(CommandInterpreter &interpreter)
434 : CommandObjectParsed(interpreter, "platform settings",
435 "Set settings for the current target's platform, "
436 "or for a platform by name.",
437 "platform settings", 0),
439 m_option_working_dir(LLDB_OPT_SET_1, false, "working-dir", 'w', 0,
441 "The working directory for the platform.") {
442 m_options.Append(&m_option_working_dir, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
445 ~CommandObjectPlatformSettings() override = default;
448 bool DoExecute(Args &args, CommandReturnObject &result) override {
449 PlatformSP platform_sp(
450 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
452 if (m_option_working_dir.GetOptionValue().OptionWasSet())
453 platform_sp->SetWorkingDirectory(
454 m_option_working_dir.GetOptionValue().GetCurrentValue());
456 result.AppendError("no platform is currently selected");
457 result.SetStatus(eReturnStatusFailed);
459 return result.Succeeded();
462 Options *GetOptions() override {
463 if (!m_options.DidFinalize())
464 m_options.Finalize();
469 OptionGroupOptions m_options;
470 OptionGroupFile m_option_working_dir;
473 //----------------------------------------------------------------------
475 //----------------------------------------------------------------------
476 class CommandObjectPlatformMkDir : public CommandObjectParsed {
478 CommandObjectPlatformMkDir(CommandInterpreter &interpreter)
479 : CommandObjectParsed(interpreter, "platform mkdir",
480 "Make a new directory on the remote end.", nullptr,
484 ~CommandObjectPlatformMkDir() override = default;
486 bool DoExecute(Args &args, CommandReturnObject &result) override {
487 PlatformSP platform_sp(
488 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
490 std::string cmd_line;
491 args.GetCommandString(cmd_line);
493 const OptionPermissions *options_permissions =
494 (const OptionPermissions *)m_options.GetGroupWithOption('r');
495 if (options_permissions)
496 mode = options_permissions->m_permissions;
498 mode = lldb::eFilePermissionsUserRWX | lldb::eFilePermissionsGroupRWX |
499 lldb::eFilePermissionsWorldRX;
500 Error error = platform_sp->MakeDirectory(FileSpec{cmd_line, false}, mode);
501 if (error.Success()) {
502 result.SetStatus(eReturnStatusSuccessFinishResult);
504 result.AppendError(error.AsCString());
505 result.SetStatus(eReturnStatusFailed);
508 result.AppendError("no platform currently selected\n");
509 result.SetStatus(eReturnStatusFailed);
511 return result.Succeeded();
514 Options *GetOptions() override {
515 if (!m_options.DidFinalize()) {
516 m_options.Append(new OptionPermissions());
517 m_options.Finalize();
522 OptionGroupOptions m_options;
525 //----------------------------------------------------------------------
527 //----------------------------------------------------------------------
528 class CommandObjectPlatformFOpen : public CommandObjectParsed {
530 CommandObjectPlatformFOpen(CommandInterpreter &interpreter)
531 : CommandObjectParsed(interpreter, "platform file open",
532 "Open a file on the remote end.", nullptr, 0),
535 ~CommandObjectPlatformFOpen() override = default;
537 bool DoExecute(Args &args, CommandReturnObject &result) override {
538 PlatformSP platform_sp(
539 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
542 std::string cmd_line;
543 args.GetCommandString(cmd_line);
545 const OptionPermissions *options_permissions =
546 (const OptionPermissions *)m_options.GetGroupWithOption('r');
547 if (options_permissions)
548 perms = options_permissions->m_permissions;
550 perms = lldb::eFilePermissionsUserRW | lldb::eFilePermissionsGroupRW |
551 lldb::eFilePermissionsWorldRead;
552 lldb::user_id_t fd = platform_sp->OpenFile(
553 FileSpec(cmd_line, false),
554 File::eOpenOptionRead | File::eOpenOptionWrite |
555 File::eOpenOptionAppend | File::eOpenOptionCanCreate,
557 if (error.Success()) {
558 result.AppendMessageWithFormat("File Descriptor = %" PRIu64 "\n", fd);
559 result.SetStatus(eReturnStatusSuccessFinishResult);
561 result.AppendError(error.AsCString());
562 result.SetStatus(eReturnStatusFailed);
565 result.AppendError("no platform currently selected\n");
566 result.SetStatus(eReturnStatusFailed);
568 return result.Succeeded();
571 Options *GetOptions() override {
572 if (!m_options.DidFinalize()) {
573 m_options.Append(new OptionPermissions());
574 m_options.Finalize();
579 OptionGroupOptions m_options;
582 //----------------------------------------------------------------------
584 //----------------------------------------------------------------------
585 class CommandObjectPlatformFClose : public CommandObjectParsed {
587 CommandObjectPlatformFClose(CommandInterpreter &interpreter)
588 : CommandObjectParsed(interpreter, "platform file close",
589 "Close a file on the remote end.", nullptr, 0) {}
591 ~CommandObjectPlatformFClose() override = default;
593 bool DoExecute(Args &args, CommandReturnObject &result) override {
594 PlatformSP platform_sp(
595 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
597 std::string cmd_line;
598 args.GetCommandString(cmd_line);
599 const lldb::user_id_t fd =
600 StringConvert::ToUInt64(cmd_line.c_str(), UINT64_MAX);
602 bool success = platform_sp->CloseFile(fd, error);
604 result.AppendMessageWithFormat("file %" PRIu64 " closed.\n", fd);
605 result.SetStatus(eReturnStatusSuccessFinishResult);
607 result.AppendError(error.AsCString());
608 result.SetStatus(eReturnStatusFailed);
611 result.AppendError("no platform currently selected\n");
612 result.SetStatus(eReturnStatusFailed);
614 return result.Succeeded();
618 //----------------------------------------------------------------------
620 //----------------------------------------------------------------------
622 static OptionDefinition g_platform_fread_options[] = {
624 { LLDB_OPT_SET_1, false, "offset", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeIndex, "Offset into the file at which to start reading." },
625 { LLDB_OPT_SET_1, false, "count", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCount, "Number of bytes to read from the file." },
629 class CommandObjectPlatformFRead : public CommandObjectParsed {
631 CommandObjectPlatformFRead(CommandInterpreter &interpreter)
632 : CommandObjectParsed(interpreter, "platform file read",
633 "Read data from a file on the remote end.", nullptr,
637 ~CommandObjectPlatformFRead() override = default;
639 bool DoExecute(Args &args, CommandReturnObject &result) override {
640 PlatformSP platform_sp(
641 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
643 std::string cmd_line;
644 args.GetCommandString(cmd_line);
645 const lldb::user_id_t fd =
646 StringConvert::ToUInt64(cmd_line.c_str(), UINT64_MAX);
647 std::string buffer(m_options.m_count, 0);
649 uint32_t retcode = platform_sp->ReadFile(
650 fd, m_options.m_offset, &buffer[0], m_options.m_count, error);
651 result.AppendMessageWithFormat("Return = %d\n", retcode);
652 result.AppendMessageWithFormat("Data = \"%s\"\n", buffer.c_str());
653 result.SetStatus(eReturnStatusSuccessFinishResult);
655 result.AppendError("no platform currently selected\n");
656 result.SetStatus(eReturnStatusFailed);
658 return result.Succeeded();
661 Options *GetOptions() override { return &m_options; }
664 class CommandOptions : public Options {
666 CommandOptions() : Options() {}
668 ~CommandOptions() override = default;
670 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
671 ExecutionContext *execution_context) override {
673 char short_option = (char)m_getopt_table[option_idx].val;
675 switch (short_option) {
677 if (option_arg.getAsInteger(0, m_offset))
678 error.SetErrorStringWithFormat("invalid offset: '%s'",
679 option_arg.str().c_str());
682 if (option_arg.getAsInteger(0, m_count))
683 error.SetErrorStringWithFormat("invalid offset: '%s'",
684 option_arg.str().c_str());
687 error.SetErrorStringWithFormat("unrecognized option '%c'",
695 void OptionParsingStarting(ExecutionContext *execution_context) override {
700 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
701 return llvm::makeArrayRef(g_platform_fread_options);
704 // Instance variables to hold the values for command options.
710 CommandOptions m_options;
713 //----------------------------------------------------------------------
715 //----------------------------------------------------------------------
717 static OptionDefinition g_platform_fwrite_options[] = {
719 { LLDB_OPT_SET_1, false, "offset", 'o', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeIndex, "Offset into the file at which to start reading." },
720 { LLDB_OPT_SET_1, false, "data", 'd', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeValue, "Text to write to the file." },
724 class CommandObjectPlatformFWrite : public CommandObjectParsed {
726 CommandObjectPlatformFWrite(CommandInterpreter &interpreter)
727 : CommandObjectParsed(interpreter, "platform file write",
728 "Write data to a file on the remote end.", nullptr,
732 ~CommandObjectPlatformFWrite() override = default;
734 bool DoExecute(Args &args, CommandReturnObject &result) override {
735 PlatformSP platform_sp(
736 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
738 std::string cmd_line;
739 args.GetCommandString(cmd_line);
741 const lldb::user_id_t fd =
742 StringConvert::ToUInt64(cmd_line.c_str(), UINT64_MAX);
744 platform_sp->WriteFile(fd, m_options.m_offset, &m_options.m_data[0],
745 m_options.m_data.size(), error);
746 result.AppendMessageWithFormat("Return = %d\n", retcode);
747 result.SetStatus(eReturnStatusSuccessFinishResult);
749 result.AppendError("no platform currently selected\n");
750 result.SetStatus(eReturnStatusFailed);
752 return result.Succeeded();
755 Options *GetOptions() override { return &m_options; }
758 class CommandOptions : public Options {
760 CommandOptions() : Options() {}
762 ~CommandOptions() override = default;
764 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
765 ExecutionContext *execution_context) override {
767 char short_option = (char)m_getopt_table[option_idx].val;
769 switch (short_option) {
771 if (option_arg.getAsInteger(0, m_offset))
772 error.SetErrorStringWithFormat("invalid offset: '%s'",
773 option_arg.str().c_str());
776 m_data.assign(option_arg);
779 error.SetErrorStringWithFormat("unrecognized option '%c'",
787 void OptionParsingStarting(ExecutionContext *execution_context) override {
792 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
793 return llvm::makeArrayRef(g_platform_fwrite_options);
796 // Instance variables to hold the values for command options.
802 CommandOptions m_options;
805 class CommandObjectPlatformFile : public CommandObjectMultiword {
807 //------------------------------------------------------------------
808 // Constructors and Destructors
809 //------------------------------------------------------------------
810 CommandObjectPlatformFile(CommandInterpreter &interpreter)
811 : CommandObjectMultiword(
812 interpreter, "platform file",
813 "Commands to access files on the current platform.",
814 "platform file [open|close|read|write] ...") {
816 "open", CommandObjectSP(new CommandObjectPlatformFOpen(interpreter)));
818 "close", CommandObjectSP(new CommandObjectPlatformFClose(interpreter)));
820 "read", CommandObjectSP(new CommandObjectPlatformFRead(interpreter)));
822 "write", CommandObjectSP(new CommandObjectPlatformFWrite(interpreter)));
825 ~CommandObjectPlatformFile() override = default;
828 //------------------------------------------------------------------
829 // For CommandObjectPlatform only
830 //------------------------------------------------------------------
831 DISALLOW_COPY_AND_ASSIGN(CommandObjectPlatformFile);
834 //----------------------------------------------------------------------
835 // "platform get-file remote-file-path host-file-path"
836 //----------------------------------------------------------------------
837 class CommandObjectPlatformGetFile : public CommandObjectParsed {
839 CommandObjectPlatformGetFile(CommandInterpreter &interpreter)
840 : CommandObjectParsed(
841 interpreter, "platform get-file",
842 "Transfer a file from the remote end to the local host.",
843 "platform get-file <remote-file-spec> <local-file-spec>", 0) {
847 (lldb) platform get-file /the/remote/file/path /the/local/file/path
849 Transfer a file from the remote end with file path /the/remote/file/path to the local host.)");
851 CommandArgumentEntry arg1, arg2;
852 CommandArgumentData file_arg_remote, file_arg_host;
854 // Define the first (and only) variant of this arg.
855 file_arg_remote.arg_type = eArgTypeFilename;
856 file_arg_remote.arg_repetition = eArgRepeatPlain;
857 // There is only one variant this argument could be; put it into the
859 arg1.push_back(file_arg_remote);
861 // Define the second (and only) variant of this arg.
862 file_arg_host.arg_type = eArgTypeFilename;
863 file_arg_host.arg_repetition = eArgRepeatPlain;
864 // There is only one variant this argument could be; put it into the
866 arg2.push_back(file_arg_host);
868 // Push the data for the first and the second arguments into the m_arguments
870 m_arguments.push_back(arg1);
871 m_arguments.push_back(arg2);
874 ~CommandObjectPlatformGetFile() override = default;
876 bool DoExecute(Args &args, CommandReturnObject &result) override {
877 // If the number of arguments is incorrect, issue an error message.
878 if (args.GetArgumentCount() != 2) {
879 result.GetErrorStream().Printf("error: required arguments missing; "
880 "specify both the source and destination "
882 result.SetStatus(eReturnStatusFailed);
886 PlatformSP platform_sp(
887 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
889 const char *remote_file_path = args.GetArgumentAtIndex(0);
890 const char *local_file_path = args.GetArgumentAtIndex(1);
891 Error error = platform_sp->GetFile(FileSpec(remote_file_path, false),
892 FileSpec(local_file_path, false));
893 if (error.Success()) {
894 result.AppendMessageWithFormat(
895 "successfully get-file from %s (remote) to %s (host)\n",
896 remote_file_path, local_file_path);
897 result.SetStatus(eReturnStatusSuccessFinishResult);
899 result.AppendMessageWithFormat("get-file failed: %s\n",
901 result.SetStatus(eReturnStatusFailed);
904 result.AppendError("no platform currently selected\n");
905 result.SetStatus(eReturnStatusFailed);
907 return result.Succeeded();
911 //----------------------------------------------------------------------
912 // "platform get-size remote-file-path"
913 //----------------------------------------------------------------------
914 class CommandObjectPlatformGetSize : public CommandObjectParsed {
916 CommandObjectPlatformGetSize(CommandInterpreter &interpreter)
917 : CommandObjectParsed(interpreter, "platform get-size",
918 "Get the file size from the remote end.",
919 "platform get-size <remote-file-spec>", 0) {
923 (lldb) platform get-size /the/remote/file/path
925 Get the file size from the remote end with path /the/remote/file/path.)");
927 CommandArgumentEntry arg1;
928 CommandArgumentData file_arg_remote;
930 // Define the first (and only) variant of this arg.
931 file_arg_remote.arg_type = eArgTypeFilename;
932 file_arg_remote.arg_repetition = eArgRepeatPlain;
933 // There is only one variant this argument could be; put it into the
935 arg1.push_back(file_arg_remote);
937 // Push the data for the first argument into the m_arguments vector.
938 m_arguments.push_back(arg1);
941 ~CommandObjectPlatformGetSize() override = default;
943 bool DoExecute(Args &args, CommandReturnObject &result) override {
944 // If the number of arguments is incorrect, issue an error message.
945 if (args.GetArgumentCount() != 1) {
946 result.GetErrorStream().Printf("error: required argument missing; "
947 "specify the source file path as the only "
949 result.SetStatus(eReturnStatusFailed);
953 PlatformSP platform_sp(
954 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
956 std::string remote_file_path(args.GetArgumentAtIndex(0));
958 platform_sp->GetFileSize(FileSpec(remote_file_path, false));
959 if (size != UINT64_MAX) {
960 result.AppendMessageWithFormat("File size of %s (remote): %" PRIu64
962 remote_file_path.c_str(), size);
963 result.SetStatus(eReturnStatusSuccessFinishResult);
965 result.AppendMessageWithFormat(
966 "Error getting file size of %s (remote)\n",
967 remote_file_path.c_str());
968 result.SetStatus(eReturnStatusFailed);
971 result.AppendError("no platform currently selected\n");
972 result.SetStatus(eReturnStatusFailed);
974 return result.Succeeded();
978 //----------------------------------------------------------------------
979 // "platform put-file"
980 //----------------------------------------------------------------------
981 class CommandObjectPlatformPutFile : public CommandObjectParsed {
983 CommandObjectPlatformPutFile(CommandInterpreter &interpreter)
984 : CommandObjectParsed(
985 interpreter, "platform put-file",
986 "Transfer a file from this system to the remote end.", nullptr, 0) {
989 ~CommandObjectPlatformPutFile() override = default;
991 bool DoExecute(Args &args, CommandReturnObject &result) override {
992 const char *src = args.GetArgumentAtIndex(0);
993 const char *dst = args.GetArgumentAtIndex(1);
995 FileSpec src_fs(src, true);
996 FileSpec dst_fs(dst ? dst : src_fs.GetFilename().GetCString(), false);
998 PlatformSP platform_sp(
999 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
1001 Error error(platform_sp->PutFile(src_fs, dst_fs));
1002 if (error.Success()) {
1003 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1005 result.AppendError(error.AsCString());
1006 result.SetStatus(eReturnStatusFailed);
1009 result.AppendError("no platform currently selected\n");
1010 result.SetStatus(eReturnStatusFailed);
1012 return result.Succeeded();
1016 //----------------------------------------------------------------------
1017 // "platform process launch"
1018 //----------------------------------------------------------------------
1019 class CommandObjectPlatformProcessLaunch : public CommandObjectParsed {
1021 CommandObjectPlatformProcessLaunch(CommandInterpreter &interpreter)
1022 : CommandObjectParsed(interpreter, "platform process launch",
1023 "Launch a new process on a remote platform.",
1024 "platform process launch program",
1025 eCommandRequiresTarget | eCommandTryTargetAPILock),
1028 ~CommandObjectPlatformProcessLaunch() override = default;
1030 Options *GetOptions() override { return &m_options; }
1033 bool DoExecute(Args &args, CommandReturnObject &result) override {
1034 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1035 PlatformSP platform_sp;
1037 platform_sp = target->GetPlatform();
1041 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform();
1046 const size_t argc = args.GetArgumentCount();
1047 Target *target = m_exe_ctx.GetTargetPtr();
1048 Module *exe_module = target->GetExecutableModulePointer();
1050 m_options.launch_info.GetExecutableFile() = exe_module->GetFileSpec();
1051 llvm::SmallString<PATH_MAX> exe_path;
1052 m_options.launch_info.GetExecutableFile().GetPath(exe_path);
1053 if (!exe_path.empty())
1054 m_options.launch_info.GetArguments().AppendArgument(exe_path);
1055 m_options.launch_info.GetArchitecture() = exe_module->GetArchitecture();
1059 if (m_options.launch_info.GetExecutableFile()) {
1060 // We already have an executable file, so we will use this
1061 // and all arguments to this function are extra arguments
1062 m_options.launch_info.GetArguments().AppendArguments(args);
1064 // We don't have any file yet, so the first argument is our
1065 // executable, and the rest are program arguments
1066 const bool first_arg_is_executable = true;
1067 m_options.launch_info.SetArguments(args, first_arg_is_executable);
1071 if (m_options.launch_info.GetExecutableFile()) {
1072 Debugger &debugger = m_interpreter.GetDebugger();
1075 target->GetRunArguments(m_options.launch_info.GetArguments());
1077 ProcessSP process_sp(platform_sp->DebugProcess(
1078 m_options.launch_info, debugger, target, error));
1079 if (process_sp && process_sp->IsAlive()) {
1080 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1084 if (error.Success())
1085 result.AppendError("process launch failed");
1087 result.AppendError(error.AsCString());
1088 result.SetStatus(eReturnStatusFailed);
1090 result.AppendError("'platform process launch' uses the current target "
1091 "file and arguments, or the executable and its "
1092 "arguments can be specified in this command");
1093 result.SetStatus(eReturnStatusFailed);
1097 result.AppendError("no platform is selected\n");
1099 return result.Succeeded();
1103 ProcessLaunchCommandOptions m_options;
1106 //----------------------------------------------------------------------
1107 // "platform process list"
1108 //----------------------------------------------------------------------
1110 OptionDefinition g_platform_process_list_options[] = {
1112 { LLDB_OPT_SET_1, false, "pid", 'p', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePid, "List the process info for a specific process ID." },
1113 { LLDB_OPT_SET_2, true, "name", 'n', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeProcessName, "Find processes with executable basenames that match a string." },
1114 { LLDB_OPT_SET_3, true, "ends-with", 'e', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeProcessName, "Find processes with executable basenames that end with a string." },
1115 { LLDB_OPT_SET_4, true, "starts-with", 's', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeProcessName, "Find processes with executable basenames that start with a string." },
1116 { LLDB_OPT_SET_5, true, "contains", 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeProcessName, "Find processes with executable basenames that contain a string." },
1117 { LLDB_OPT_SET_6, true, "regex", 'r', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeRegularExpression, "Find processes with executable basenames that match a regular expression." },
1118 { 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." },
1119 { LLDB_OPT_SET_FROM_TO(2, 6), false, "uid", 'u', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeUnsignedInteger, "Find processes that have a matching user ID." },
1120 { 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." },
1121 { LLDB_OPT_SET_FROM_TO(2, 6), false, "gid", 'g', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeUnsignedInteger, "Find processes that have a matching group ID." },
1122 { 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." },
1123 { LLDB_OPT_SET_FROM_TO(2, 6), false, "arch", 'a', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeArchitecture, "Find processes that have a matching architecture." },
1124 { 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." },
1125 { LLDB_OPT_SET_FROM_TO(1, 6), false, "verbose", 'v', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Enable verbose output." },
1129 class CommandObjectPlatformProcessList : public CommandObjectParsed {
1131 CommandObjectPlatformProcessList(CommandInterpreter &interpreter)
1132 : CommandObjectParsed(interpreter, "platform process list",
1133 "List processes on a remote platform by name, pid, "
1134 "or many other matching attributes.",
1135 "platform process list", 0),
1138 ~CommandObjectPlatformProcessList() override = default;
1140 Options *GetOptions() override { return &m_options; }
1143 bool DoExecute(Args &args, CommandReturnObject &result) override {
1144 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1145 PlatformSP platform_sp;
1147 platform_sp = target->GetPlatform();
1151 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform();
1156 if (args.GetArgumentCount() == 0) {
1158 Stream &ostrm = result.GetOutputStream();
1161 m_options.match_info.GetProcessInfo().GetProcessID();
1162 if (pid != LLDB_INVALID_PROCESS_ID) {
1163 ProcessInstanceInfo proc_info;
1164 if (platform_sp->GetProcessInfo(pid, proc_info)) {
1165 ProcessInstanceInfo::DumpTableHeader(ostrm, platform_sp.get(),
1166 m_options.show_args,
1168 proc_info.DumpAsTableRow(ostrm, platform_sp.get(),
1169 m_options.show_args, m_options.verbose);
1170 result.SetStatus(eReturnStatusSuccessFinishResult);
1172 result.AppendErrorWithFormat(
1173 "no process found with pid = %" PRIu64 "\n", pid);
1174 result.SetStatus(eReturnStatusFailed);
1177 ProcessInstanceInfoList proc_infos;
1178 const uint32_t matches =
1179 platform_sp->FindProcesses(m_options.match_info, proc_infos);
1180 const char *match_desc = nullptr;
1181 const char *match_name =
1182 m_options.match_info.GetProcessInfo().GetName();
1183 if (match_name && match_name[0]) {
1184 switch (m_options.match_info.GetNameMatchType()) {
1185 case eNameMatchIgnore:
1187 case eNameMatchEquals:
1188 match_desc = "matched";
1190 case eNameMatchContains:
1191 match_desc = "contained";
1193 case eNameMatchStartsWith:
1194 match_desc = "started with";
1196 case eNameMatchEndsWith:
1197 match_desc = "ended with";
1199 case eNameMatchRegularExpression:
1200 match_desc = "matched the regular expression";
1207 result.AppendErrorWithFormat(
1208 "no processes were found that %s \"%s\" on the \"%s\" "
1210 match_desc, match_name,
1211 platform_sp->GetPluginName().GetCString());
1213 result.AppendErrorWithFormat(
1214 "no processes were found on the \"%s\" platform\n",
1215 platform_sp->GetPluginName().GetCString());
1216 result.SetStatus(eReturnStatusFailed);
1218 result.AppendMessageWithFormat(
1219 "%u matching process%s found on \"%s\"", matches,
1220 matches > 1 ? "es were" : " was",
1221 platform_sp->GetName().GetCString());
1223 result.AppendMessageWithFormat(" whose name %s \"%s\"",
1224 match_desc, match_name);
1225 result.AppendMessageWithFormat("\n");
1226 ProcessInstanceInfo::DumpTableHeader(ostrm, platform_sp.get(),
1227 m_options.show_args,
1229 for (uint32_t i = 0; i < matches; ++i) {
1230 proc_infos.GetProcessInfoAtIndex(i).DumpAsTableRow(
1231 ostrm, platform_sp.get(), m_options.show_args,
1238 result.AppendError("invalid args: process list takes only options\n");
1239 result.SetStatus(eReturnStatusFailed);
1242 result.AppendError("no platform is selected\n");
1243 result.SetStatus(eReturnStatusFailed);
1245 return result.Succeeded();
1248 class CommandOptions : public Options {
1251 : Options(), match_info(), show_args(false), verbose(false) {
1252 static std::once_flag g_once_flag;
1253 std::call_once(g_once_flag, []() {
1254 PosixPlatformCommandOptionValidator *posix_validator =
1255 new PosixPlatformCommandOptionValidator();
1256 for (auto &Option : g_platform_process_list_options) {
1257 switch (Option.short_option) {
1262 Option.validator = posix_validator;
1271 ~CommandOptions() override = default;
1273 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1274 ExecutionContext *execution_context) override {
1276 const int short_option = m_getopt_table[option_idx].val;
1277 bool success = false;
1279 uint32_t id = LLDB_INVALID_PROCESS_ID;
1280 success = !option_arg.getAsInteger(0, id);
1281 switch (short_option) {
1283 match_info.GetProcessInfo().SetProcessID(id);
1285 error.SetErrorStringWithFormat("invalid process ID string: '%s'",
1286 option_arg.str().c_str());
1290 match_info.GetProcessInfo().SetParentProcessID(id);
1292 error.SetErrorStringWithFormat(
1293 "invalid parent process ID string: '%s'",
1294 option_arg.str().c_str());
1298 match_info.GetProcessInfo().SetUserID(success ? id : UINT32_MAX);
1300 error.SetErrorStringWithFormat("invalid user ID string: '%s'",
1301 option_arg.str().c_str());
1305 match_info.GetProcessInfo().SetEffectiveUserID(success ? id
1308 error.SetErrorStringWithFormat(
1309 "invalid effective user ID string: '%s'",
1310 option_arg.str().c_str());
1314 match_info.GetProcessInfo().SetGroupID(success ? id : UINT32_MAX);
1316 error.SetErrorStringWithFormat("invalid group ID string: '%s'",
1317 option_arg.str().c_str());
1321 match_info.GetProcessInfo().SetEffectiveGroupID(success ? id
1324 error.SetErrorStringWithFormat(
1325 "invalid effective group ID string: '%s'",
1326 option_arg.str().c_str());
1330 TargetSP target_sp =
1331 execution_context ? execution_context->GetTargetSP() : TargetSP();
1332 DebuggerSP debugger_sp =
1333 target_sp ? target_sp->GetDebugger().shared_from_this()
1335 PlatformSP platform_sp =
1336 debugger_sp ? debugger_sp->GetPlatformList().GetSelectedPlatform()
1338 match_info.GetProcessInfo().GetArchitecture().SetTriple(
1339 option_arg, platform_sp.get());
1343 match_info.GetProcessInfo().GetExecutableFile().SetFile(option_arg,
1345 match_info.SetNameMatchType(eNameMatchEquals);
1349 match_info.GetProcessInfo().GetExecutableFile().SetFile(option_arg,
1351 match_info.SetNameMatchType(eNameMatchEndsWith);
1355 match_info.GetProcessInfo().GetExecutableFile().SetFile(option_arg,
1357 match_info.SetNameMatchType(eNameMatchStartsWith);
1361 match_info.GetProcessInfo().GetExecutableFile().SetFile(option_arg,
1363 match_info.SetNameMatchType(eNameMatchContains);
1367 match_info.GetProcessInfo().GetExecutableFile().SetFile(option_arg,
1369 match_info.SetNameMatchType(eNameMatchRegularExpression);
1381 error.SetErrorStringWithFormat("unrecognized option '%c'",
1389 void OptionParsingStarting(ExecutionContext *execution_context) override {
1395 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1396 return llvm::makeArrayRef(g_platform_process_list_options);
1399 // Instance variables to hold the values for command options.
1401 ProcessInstanceInfoMatch match_info;
1406 CommandOptions m_options;
1409 //----------------------------------------------------------------------
1410 // "platform process info"
1411 //----------------------------------------------------------------------
1412 class CommandObjectPlatformProcessInfo : public CommandObjectParsed {
1414 CommandObjectPlatformProcessInfo(CommandInterpreter &interpreter)
1415 : CommandObjectParsed(
1416 interpreter, "platform process info",
1417 "Get detailed information for one or more process by process ID.",
1418 "platform process info <pid> [<pid> <pid> ...]", 0) {
1419 CommandArgumentEntry arg;
1420 CommandArgumentData pid_args;
1422 // Define the first (and only) variant of this arg.
1423 pid_args.arg_type = eArgTypePid;
1424 pid_args.arg_repetition = eArgRepeatStar;
1426 // There is only one variant this argument could be; put it into the
1428 arg.push_back(pid_args);
1430 // Push the data for the first argument into the m_arguments vector.
1431 m_arguments.push_back(arg);
1434 ~CommandObjectPlatformProcessInfo() override = default;
1437 bool DoExecute(Args &args, CommandReturnObject &result) override {
1438 Target *target = m_interpreter.GetDebugger().GetSelectedTarget().get();
1439 PlatformSP platform_sp;
1441 platform_sp = target->GetPlatform();
1445 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform();
1449 const size_t argc = args.GetArgumentCount();
1453 if (platform_sp->IsConnected()) {
1454 Stream &ostrm = result.GetOutputStream();
1455 for (auto &entry : args.entries()) {
1457 if (entry.ref.getAsInteger(0, pid)) {
1458 result.AppendErrorWithFormat("invalid process ID argument '%s'",
1459 entry.ref.str().c_str());
1460 result.SetStatus(eReturnStatusFailed);
1463 ProcessInstanceInfo proc_info;
1464 if (platform_sp->GetProcessInfo(pid, proc_info)) {
1465 ostrm.Printf("Process information for process %" PRIu64 ":\n",
1467 proc_info.Dump(ostrm, platform_sp.get());
1469 ostrm.Printf("error: no process information is available for "
1470 "process %" PRIu64 "\n",
1478 result.AppendErrorWithFormat(
1479 "not connected to '%s'",
1480 platform_sp->GetPluginName().GetCString());
1481 result.SetStatus(eReturnStatusFailed);
1485 result.AppendError("one or more process id(s) must be specified");
1486 result.SetStatus(eReturnStatusFailed);
1489 result.AppendError("no platform is currently selected");
1490 result.SetStatus(eReturnStatusFailed);
1492 return result.Succeeded();
1496 static OptionDefinition g_platform_process_attach_options[] = {
1498 { LLDB_OPT_SET_ALL, false, "plugin", 'P', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePlugin, "Name of the process plugin you want to use." },
1499 { LLDB_OPT_SET_1, false, "pid", 'p', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePid, "The process ID of an existing process to attach to." },
1500 { LLDB_OPT_SET_2, false, "name", 'n', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeProcessName, "The name of the process to attach to." },
1501 { LLDB_OPT_SET_2, false, "waitfor", 'w', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone, "Wait for the process with <process-name> to launch." },
1505 class CommandObjectPlatformProcessAttach : public CommandObjectParsed {
1507 class CommandOptions : public Options {
1509 CommandOptions() : Options() {
1510 // Keep default values of all options in one place: OptionParsingStarting
1512 OptionParsingStarting(nullptr);
1515 ~CommandOptions() override = default;
1517 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1518 ExecutionContext *execution_context) override {
1520 char short_option = (char)m_getopt_table[option_idx].val;
1521 switch (short_option) {
1523 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1524 if (option_arg.getAsInteger(0, pid)) {
1525 error.SetErrorStringWithFormat("invalid process ID '%s'",
1526 option_arg.str().c_str());
1528 attach_info.SetProcessID(pid);
1533 attach_info.SetProcessPluginName(option_arg);
1537 attach_info.GetExecutableFile().SetFile(option_arg, false);
1541 attach_info.SetWaitForLaunch(true);
1545 error.SetErrorStringWithFormat("invalid short option character '%c'",
1552 void OptionParsingStarting(ExecutionContext *execution_context) override {
1553 attach_info.Clear();
1556 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1557 return llvm::makeArrayRef(g_platform_process_attach_options);
1560 bool HandleOptionArgumentCompletion(
1561 Args &input, int cursor_index, int char_pos,
1562 OptionElementVector &opt_element_vector, int opt_element_index,
1563 int match_start_point, int max_return_elements,
1564 CommandInterpreter &interpreter, bool &word_complete,
1565 StringList &matches) override {
1566 int opt_arg_pos = opt_element_vector[opt_element_index].opt_arg_pos;
1567 int opt_defs_index = opt_element_vector[opt_element_index].opt_defs_index;
1569 // We are only completing the name option for now...
1571 if (GetDefinitions()[opt_defs_index].short_option == 'n') {
1572 // Are we in the name?
1574 // Look to see if there is a -P argument provided, and if so use that
1575 // plugin, otherwise
1576 // use the default plugin.
1578 const char *partial_name = nullptr;
1579 partial_name = input.GetArgumentAtIndex(opt_arg_pos);
1581 PlatformSP platform_sp(interpreter.GetPlatform(true));
1583 ProcessInstanceInfoList process_infos;
1584 ProcessInstanceInfoMatch match_info;
1586 match_info.GetProcessInfo().GetExecutableFile().SetFile(
1587 partial_name, false);
1588 match_info.SetNameMatchType(eNameMatchStartsWith);
1590 platform_sp->FindProcesses(match_info, process_infos);
1591 const uint32_t num_matches = process_infos.GetSize();
1592 if (num_matches > 0) {
1593 for (uint32_t i = 0; i < num_matches; ++i) {
1594 matches.AppendString(
1595 process_infos.GetProcessNameAtIndex(i),
1596 process_infos.GetProcessNameLengthAtIndex(i));
1605 // Options table: Required for subclasses of Options.
1607 static OptionDefinition g_option_table[];
1609 // Instance variables to hold the values for command options.
1611 ProcessAttachInfo attach_info;
1614 CommandObjectPlatformProcessAttach(CommandInterpreter &interpreter)
1615 : CommandObjectParsed(interpreter, "platform process attach",
1616 "Attach to a process.",
1617 "platform process attach <cmd-options>"),
1620 ~CommandObjectPlatformProcessAttach() override = default;
1622 bool DoExecute(Args &command, CommandReturnObject &result) override {
1623 PlatformSP platform_sp(
1624 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
1627 ProcessSP remote_process_sp = platform_sp->Attach(
1628 m_options.attach_info, m_interpreter.GetDebugger(), nullptr, err);
1630 result.AppendError(err.AsCString());
1631 result.SetStatus(eReturnStatusFailed);
1632 } else if (!remote_process_sp) {
1633 result.AppendError("could not attach: unknown reason");
1634 result.SetStatus(eReturnStatusFailed);
1636 result.SetStatus(eReturnStatusSuccessFinishResult);
1638 result.AppendError("no platform is currently selected");
1639 result.SetStatus(eReturnStatusFailed);
1641 return result.Succeeded();
1644 Options *GetOptions() override { return &m_options; }
1647 CommandOptions m_options;
1650 class CommandObjectPlatformProcess : public CommandObjectMultiword {
1652 //------------------------------------------------------------------
1653 // Constructors and Destructors
1654 //------------------------------------------------------------------
1655 CommandObjectPlatformProcess(CommandInterpreter &interpreter)
1656 : CommandObjectMultiword(interpreter, "platform process",
1657 "Commands to query, launch and attach to "
1658 "processes on the current platform.",
1659 "platform process [attach|launch|list] ...") {
1662 CommandObjectSP(new CommandObjectPlatformProcessAttach(interpreter)));
1665 CommandObjectSP(new CommandObjectPlatformProcessLaunch(interpreter)));
1666 LoadSubCommand("info", CommandObjectSP(new CommandObjectPlatformProcessInfo(
1668 LoadSubCommand("list", CommandObjectSP(new CommandObjectPlatformProcessList(
1672 ~CommandObjectPlatformProcess() override = default;
1675 //------------------------------------------------------------------
1676 // For CommandObjectPlatform only
1677 //------------------------------------------------------------------
1678 DISALLOW_COPY_AND_ASSIGN(CommandObjectPlatformProcess);
1681 //----------------------------------------------------------------------
1683 //----------------------------------------------------------------------
1684 static OptionDefinition g_platform_shell_options[] = {
1686 { 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." },
1690 class CommandObjectPlatformShell : public CommandObjectRaw {
1692 class CommandOptions : public Options {
1694 CommandOptions() : Options(), timeout(10) {}
1696 ~CommandOptions() override = default;
1698 llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1699 return llvm::makeArrayRef(g_platform_shell_options);
1702 Error SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1703 ExecutionContext *execution_context) override {
1706 const char short_option = (char)GetDefinitions()[option_idx].short_option;
1708 switch (short_option) {
1711 if (option_arg.getAsInteger(10, timeout))
1712 error.SetErrorStringWithFormat(
1713 "could not convert \"%s\" to a numeric value.",
1714 option_arg.str().c_str());
1717 error.SetErrorStringWithFormat("invalid short option character '%c'",
1725 void OptionParsingStarting(ExecutionContext *execution_context) override {}
1730 CommandObjectPlatformShell(CommandInterpreter &interpreter)
1731 : CommandObjectRaw(interpreter, "platform shell",
1732 "Run a shell command on the current platform.",
1733 "platform shell <shell-command>", 0),
1736 ~CommandObjectPlatformShell() override = default;
1738 Options *GetOptions() override { return &m_options; }
1740 bool DoExecute(const char *raw_command_line,
1741 CommandReturnObject &result) override {
1742 ExecutionContext exe_ctx = GetCommandInterpreter().GetExecutionContext();
1743 m_options.NotifyOptionParsingStarting(&exe_ctx);
1745 const char *expr = nullptr;
1747 // Print out an usage syntax on an empty command line.
1748 if (raw_command_line[0] == '\0') {
1749 result.GetOutputStream().Printf("%s\n", this->GetSyntax().str().c_str());
1753 if (raw_command_line[0] == '-') {
1754 // We have some options and these options MUST end with --.
1755 const char *end_options = nullptr;
1756 const char *s = raw_command_line;
1758 end_options = ::strstr(s, "--");
1760 end_options += 2; // Get past the "--"
1761 if (::isspace(end_options[0])) {
1763 while (::isspace(*expr))
1773 llvm::StringRef(raw_command_line, end_options - raw_command_line));
1774 if (!ParseOptions(args, result))
1779 if (expr == nullptr)
1780 expr = raw_command_line;
1782 PlatformSP platform_sp(
1783 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
1786 FileSpec working_dir{};
1790 error = (platform_sp->RunShellCommand(expr, working_dir, &status, &signo,
1791 &output, m_options.timeout));
1792 if (!output.empty())
1793 result.GetOutputStream().PutCString(output);
1796 const char *signo_cstr = Host::GetSignalAsCString(signo);
1798 result.GetOutputStream().Printf(
1799 "error: command returned with status %i and signal %s\n",
1800 status, signo_cstr);
1802 result.GetOutputStream().Printf(
1803 "error: command returned with status %i and signal %i\n",
1806 result.GetOutputStream().Printf(
1807 "error: command returned with status %i\n", status);
1810 result.GetOutputStream().Printf(
1811 "error: cannot run remote shell commands without a platform\n");
1812 error.SetErrorString(
1813 "error: cannot run remote shell commands without a platform");
1817 result.AppendError(error.AsCString());
1818 result.SetStatus(eReturnStatusFailed);
1820 result.SetStatus(eReturnStatusSuccessFinishResult);
1825 CommandOptions m_options;
1828 //----------------------------------------------------------------------
1829 // "platform install" - install a target to a remote end
1830 //----------------------------------------------------------------------
1831 class CommandObjectPlatformInstall : public CommandObjectParsed {
1833 CommandObjectPlatformInstall(CommandInterpreter &interpreter)
1834 : CommandObjectParsed(
1835 interpreter, "platform target-install",
1836 "Install a target (bundle or executable file) to the remote end.",
1837 "platform target-install <local-thing> <remote-sandbox>", 0) {}
1839 ~CommandObjectPlatformInstall() override = default;
1841 bool DoExecute(Args &args, CommandReturnObject &result) override {
1842 if (args.GetArgumentCount() != 2) {
1843 result.AppendError("platform target-install takes two arguments");
1844 result.SetStatus(eReturnStatusFailed);
1847 // TODO: move the bulk of this code over to the platform itself
1848 FileSpec src(args.GetArgumentAtIndex(0), true);
1849 FileSpec dst(args.GetArgumentAtIndex(1), false);
1850 if (!src.Exists()) {
1851 result.AppendError("source location does not exist or is not accessible");
1852 result.SetStatus(eReturnStatusFailed);
1855 PlatformSP platform_sp(
1856 m_interpreter.GetDebugger().GetPlatformList().GetSelectedPlatform());
1858 result.AppendError("no platform currently selected");
1859 result.SetStatus(eReturnStatusFailed);
1863 Error error = platform_sp->Install(src, dst);
1864 if (error.Success()) {
1865 result.SetStatus(eReturnStatusSuccessFinishNoResult);
1867 result.AppendErrorWithFormat("install failed: %s", error.AsCString());
1868 result.SetStatus(eReturnStatusFailed);
1870 return result.Succeeded();
1874 CommandObjectPlatform::CommandObjectPlatform(CommandInterpreter &interpreter)
1875 : CommandObjectMultiword(
1876 interpreter, "platform", "Commands to manage and create platforms.",
1877 "platform [connect|disconnect|info|list|status|select] ...") {
1878 LoadSubCommand("select",
1879 CommandObjectSP(new CommandObjectPlatformSelect(interpreter)));
1880 LoadSubCommand("list",
1881 CommandObjectSP(new CommandObjectPlatformList(interpreter)));
1882 LoadSubCommand("status",
1883 CommandObjectSP(new CommandObjectPlatformStatus(interpreter)));
1884 LoadSubCommand("connect", CommandObjectSP(
1885 new CommandObjectPlatformConnect(interpreter)));
1888 CommandObjectSP(new CommandObjectPlatformDisconnect(interpreter)));
1889 LoadSubCommand("settings", CommandObjectSP(new CommandObjectPlatformSettings(
1891 LoadSubCommand("mkdir",
1892 CommandObjectSP(new CommandObjectPlatformMkDir(interpreter)));
1893 LoadSubCommand("file",
1894 CommandObjectSP(new CommandObjectPlatformFile(interpreter)));
1895 LoadSubCommand("get-file", CommandObjectSP(new CommandObjectPlatformGetFile(
1897 LoadSubCommand("get-size", CommandObjectSP(new CommandObjectPlatformGetSize(
1899 LoadSubCommand("put-file", CommandObjectSP(new CommandObjectPlatformPutFile(
1901 LoadSubCommand("process", CommandObjectSP(
1902 new CommandObjectPlatformProcess(interpreter)));
1903 LoadSubCommand("shell",
1904 CommandObjectSP(new CommandObjectPlatformShell(interpreter)));
1907 CommandObjectSP(new CommandObjectPlatformInstall(interpreter)));
1910 CommandObjectPlatform::~CommandObjectPlatform() = default;