xref: /freebsd-src/contrib/llvm-project/lldb/source/Commands/CommandObjectPlatform.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
1 //===-- CommandObjectPlatform.cpp -----------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "CommandObjectPlatform.h"
10 #include "CommandOptionsProcessLaunch.h"
11 #include "lldb/Core/Debugger.h"
12 #include "lldb/Core/Module.h"
13 #include "lldb/Core/PluginManager.h"
14 #include "lldb/Host/OptionParser.h"
15 #include "lldb/Interpreter/CommandInterpreter.h"
16 #include "lldb/Interpreter/CommandOptionValidators.h"
17 #include "lldb/Interpreter/CommandReturnObject.h"
18 #include "lldb/Interpreter/OptionGroupFile.h"
19 #include "lldb/Interpreter/OptionGroupPlatform.h"
20 #include "lldb/Target/ExecutionContext.h"
21 #include "lldb/Target/Platform.h"
22 #include "lldb/Target/Process.h"
23 #include "lldb/Utility/Args.h"
24 
25 #include "llvm/ADT/SmallString.h"
26 
27 using namespace lldb;
28 using namespace lldb_private;
29 
30 static mode_t ParsePermissionString(const char *) = delete;
31 
32 static mode_t ParsePermissionString(llvm::StringRef permissions) {
33   if (permissions.size() != 9)
34     return (mode_t)(-1);
35   bool user_r, user_w, user_x, group_r, group_w, group_x, world_r, world_w,
36       world_x;
37 
38   user_r = (permissions[0] == 'r');
39   user_w = (permissions[1] == 'w');
40   user_x = (permissions[2] == 'x');
41 
42   group_r = (permissions[3] == 'r');
43   group_w = (permissions[4] == 'w');
44   group_x = (permissions[5] == 'x');
45 
46   world_r = (permissions[6] == 'r');
47   world_w = (permissions[7] == 'w');
48   world_x = (permissions[8] == 'x');
49 
50   mode_t user, group, world;
51   user = (user_r ? 4 : 0) | (user_w ? 2 : 0) | (user_x ? 1 : 0);
52   group = (group_r ? 4 : 0) | (group_w ? 2 : 0) | (group_x ? 1 : 0);
53   world = (world_r ? 4 : 0) | (world_w ? 2 : 0) | (world_x ? 1 : 0);
54 
55   return user | group | world;
56 }
57 
58 #define LLDB_OPTIONS_permissions
59 #include "CommandOptions.inc"
60 
61 class OptionPermissions : public OptionGroup {
62 public:
63   OptionPermissions() = default;
64 
65   ~OptionPermissions() override = default;
66 
67   lldb_private::Status
68   SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
69                  ExecutionContext *execution_context) override {
70     Status error;
71     char short_option = (char)GetDefinitions()[option_idx].short_option;
72     switch (short_option) {
73     case 'v': {
74       if (option_arg.getAsInteger(8, m_permissions)) {
75         m_permissions = 0777;
76         error.SetErrorStringWithFormat("invalid value for permissions: %s",
77                                        option_arg.str().c_str());
78       }
79 
80     } break;
81     case 's': {
82       mode_t perms = ParsePermissionString(option_arg);
83       if (perms == (mode_t)-1)
84         error.SetErrorStringWithFormat("invalid value for permissions: %s",
85                                        option_arg.str().c_str());
86       else
87         m_permissions = perms;
88     } break;
89     case 'r':
90       m_permissions |= lldb::eFilePermissionsUserRead;
91       break;
92     case 'w':
93       m_permissions |= lldb::eFilePermissionsUserWrite;
94       break;
95     case 'x':
96       m_permissions |= lldb::eFilePermissionsUserExecute;
97       break;
98     case 'R':
99       m_permissions |= lldb::eFilePermissionsGroupRead;
100       break;
101     case 'W':
102       m_permissions |= lldb::eFilePermissionsGroupWrite;
103       break;
104     case 'X':
105       m_permissions |= lldb::eFilePermissionsGroupExecute;
106       break;
107     case 'd':
108       m_permissions |= lldb::eFilePermissionsWorldRead;
109       break;
110     case 't':
111       m_permissions |= lldb::eFilePermissionsWorldWrite;
112       break;
113     case 'e':
114       m_permissions |= lldb::eFilePermissionsWorldExecute;
115       break;
116     default:
117       llvm_unreachable("Unimplemented option");
118     }
119 
120     return error;
121   }
122 
123   void OptionParsingStarting(ExecutionContext *execution_context) override {
124     m_permissions = 0;
125   }
126 
127   llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
128     return llvm::makeArrayRef(g_permissions_options);
129   }
130 
131   // Instance variables to hold the values for command options.
132 
133   uint32_t m_permissions;
134 
135 private:
136   OptionPermissions(const OptionPermissions &) = delete;
137   const OptionPermissions &operator=(const OptionPermissions &) = delete;
138 };
139 
140 // "platform select <platform-name>"
141 class CommandObjectPlatformSelect : public CommandObjectParsed {
142 public:
143   CommandObjectPlatformSelect(CommandInterpreter &interpreter)
144       : CommandObjectParsed(interpreter, "platform select",
145                             "Create a platform if needed and select it as the "
146                             "current platform.",
147                             "platform select <platform-name>", 0),
148         m_option_group(),
149         m_platform_options(
150             false) // Don't include the "--platform" option by passing false
151   {
152     m_option_group.Append(&m_platform_options, LLDB_OPT_SET_ALL, 1);
153     m_option_group.Finalize();
154   }
155 
156   ~CommandObjectPlatformSelect() override = default;
157 
158   void HandleCompletion(CompletionRequest &request) override {
159     CommandCompletions::PlatformPluginNames(GetCommandInterpreter(), request,
160                                             nullptr);
161   }
162 
163   Options *GetOptions() override { return &m_option_group; }
164 
165 protected:
166   bool DoExecute(Args &args, CommandReturnObject &result) override {
167     if (args.GetArgumentCount() == 1) {
168       const char *platform_name = args.GetArgumentAtIndex(0);
169       if (platform_name && platform_name[0]) {
170         const bool select = true;
171         m_platform_options.SetPlatformName(platform_name);
172         Status error;
173         ArchSpec platform_arch;
174         PlatformSP platform_sp(m_platform_options.CreatePlatformWithOptions(
175             m_interpreter, ArchSpec(), select, error, platform_arch));
176         if (platform_sp) {
177           GetDebugger().GetPlatformList().SetSelectedPlatform(platform_sp);
178 
179           platform_sp->GetStatus(result.GetOutputStream());
180           result.SetStatus(eReturnStatusSuccessFinishResult);
181         } else {
182           result.AppendError(error.AsCString());
183         }
184       } else {
185         result.AppendError("invalid platform name");
186       }
187     } else {
188       result.AppendError(
189           "platform create takes a platform name as an argument\n");
190     }
191     return result.Succeeded();
192   }
193 
194   OptionGroupOptions m_option_group;
195   OptionGroupPlatform m_platform_options;
196 };
197 
198 // "platform list"
199 class CommandObjectPlatformList : public CommandObjectParsed {
200 public:
201   CommandObjectPlatformList(CommandInterpreter &interpreter)
202       : CommandObjectParsed(interpreter, "platform list",
203                             "List all platforms that are available.", nullptr,
204                             0) {}
205 
206   ~CommandObjectPlatformList() override = default;
207 
208 protected:
209   bool DoExecute(Args &args, CommandReturnObject &result) override {
210     Stream &ostrm = result.GetOutputStream();
211     ostrm.Printf("Available platforms:\n");
212 
213     PlatformSP host_platform_sp(Platform::GetHostPlatform());
214     ostrm.Format("{0}: {1}\n", host_platform_sp->GetPluginName(),
215                  host_platform_sp->GetDescription());
216 
217     uint32_t idx;
218     for (idx = 0; true; ++idx) {
219       llvm::StringRef plugin_name =
220           PluginManager::GetPlatformPluginNameAtIndex(idx);
221       if (plugin_name.empty())
222         break;
223       llvm::StringRef plugin_desc =
224           PluginManager::GetPlatformPluginDescriptionAtIndex(idx);
225       ostrm.Format("{0}: {1}\n", plugin_name, plugin_desc);
226     }
227 
228     if (idx == 0) {
229       result.AppendError("no platforms are available\n");
230     } else
231       result.SetStatus(eReturnStatusSuccessFinishResult);
232     return result.Succeeded();
233   }
234 };
235 
236 // "platform status"
237 class CommandObjectPlatformStatus : public CommandObjectParsed {
238 public:
239   CommandObjectPlatformStatus(CommandInterpreter &interpreter)
240       : CommandObjectParsed(interpreter, "platform status",
241                             "Display status for the current platform.", nullptr,
242                             0) {}
243 
244   ~CommandObjectPlatformStatus() override = default;
245 
246 protected:
247   bool DoExecute(Args &args, CommandReturnObject &result) override {
248     Stream &ostrm = result.GetOutputStream();
249 
250     Target *target = GetDebugger().GetSelectedTarget().get();
251     PlatformSP platform_sp;
252     if (target) {
253       platform_sp = target->GetPlatform();
254     }
255     if (!platform_sp) {
256       platform_sp = GetDebugger().GetPlatformList().GetSelectedPlatform();
257     }
258     if (platform_sp) {
259       platform_sp->GetStatus(ostrm);
260       result.SetStatus(eReturnStatusSuccessFinishResult);
261     } else {
262       result.AppendError("no platform is currently selected\n");
263     }
264     return result.Succeeded();
265   }
266 };
267 
268 // "platform connect <connect-url>"
269 class CommandObjectPlatformConnect : public CommandObjectParsed {
270 public:
271   CommandObjectPlatformConnect(CommandInterpreter &interpreter)
272       : CommandObjectParsed(
273             interpreter, "platform connect",
274             "Select the current platform by providing a connection URL.",
275             "platform connect <connect-url>", 0) {}
276 
277   ~CommandObjectPlatformConnect() override = default;
278 
279 protected:
280   bool DoExecute(Args &args, CommandReturnObject &result) override {
281     Stream &ostrm = result.GetOutputStream();
282 
283     PlatformSP platform_sp(
284         GetDebugger().GetPlatformList().GetSelectedPlatform());
285     if (platform_sp) {
286       Status error(platform_sp->ConnectRemote(args));
287       if (error.Success()) {
288         platform_sp->GetStatus(ostrm);
289         result.SetStatus(eReturnStatusSuccessFinishResult);
290 
291         platform_sp->ConnectToWaitingProcesses(GetDebugger(), error);
292         if (error.Fail()) {
293           result.AppendError(error.AsCString());
294         }
295       } else {
296         result.AppendErrorWithFormat("%s\n", error.AsCString());
297       }
298     } else {
299       result.AppendError("no platform is currently selected\n");
300     }
301     return result.Succeeded();
302   }
303 
304   Options *GetOptions() override {
305     PlatformSP platform_sp(
306         GetDebugger().GetPlatformList().GetSelectedPlatform());
307     OptionGroupOptions *m_platform_options = nullptr;
308     if (platform_sp) {
309       m_platform_options = platform_sp->GetConnectionOptions(m_interpreter);
310       if (m_platform_options != nullptr && !m_platform_options->m_did_finalize)
311         m_platform_options->Finalize();
312     }
313     return m_platform_options;
314   }
315 };
316 
317 // "platform disconnect"
318 class CommandObjectPlatformDisconnect : public CommandObjectParsed {
319 public:
320   CommandObjectPlatformDisconnect(CommandInterpreter &interpreter)
321       : CommandObjectParsed(interpreter, "platform disconnect",
322                             "Disconnect from the current platform.",
323                             "platform disconnect", 0) {}
324 
325   ~CommandObjectPlatformDisconnect() override = default;
326 
327 protected:
328   bool DoExecute(Args &args, CommandReturnObject &result) override {
329     PlatformSP platform_sp(
330         GetDebugger().GetPlatformList().GetSelectedPlatform());
331     if (platform_sp) {
332       if (args.GetArgumentCount() == 0) {
333         Status error;
334 
335         if (platform_sp->IsConnected()) {
336           // Cache the instance name if there is one since we are about to
337           // disconnect and the name might go with it.
338           const char *hostname_cstr = platform_sp->GetHostname();
339           std::string hostname;
340           if (hostname_cstr)
341             hostname.assign(hostname_cstr);
342 
343           error = platform_sp->DisconnectRemote();
344           if (error.Success()) {
345             Stream &ostrm = result.GetOutputStream();
346             if (hostname.empty())
347               ostrm.Format("Disconnected from \"{0}\"\n",
348                            platform_sp->GetPluginName());
349             else
350               ostrm.Printf("Disconnected from \"%s\"\n", hostname.c_str());
351             result.SetStatus(eReturnStatusSuccessFinishResult);
352           } else {
353             result.AppendErrorWithFormat("%s", error.AsCString());
354           }
355         } else {
356           // Not connected...
357           result.AppendErrorWithFormatv("not connected to '{0}'",
358                                         platform_sp->GetPluginName());
359         }
360       } else {
361         // Bad args
362         result.AppendError(
363             "\"platform disconnect\" doesn't take any arguments");
364       }
365     } else {
366       result.AppendError("no platform is currently selected");
367     }
368     return result.Succeeded();
369   }
370 };
371 
372 // "platform settings"
373 class CommandObjectPlatformSettings : public CommandObjectParsed {
374 public:
375   CommandObjectPlatformSettings(CommandInterpreter &interpreter)
376       : CommandObjectParsed(interpreter, "platform settings",
377                             "Set settings for the current target's platform, "
378                             "or for a platform by name.",
379                             "platform settings", 0),
380         m_options(),
381         m_option_working_dir(LLDB_OPT_SET_1, false, "working-dir", 'w',
382                              CommandCompletions::eRemoteDiskDirectoryCompletion,
383                              eArgTypePath,
384                              "The working directory for the platform.") {
385     m_options.Append(&m_option_working_dir, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1);
386   }
387 
388   ~CommandObjectPlatformSettings() override = default;
389 
390 protected:
391   bool DoExecute(Args &args, CommandReturnObject &result) override {
392     PlatformSP platform_sp(
393         GetDebugger().GetPlatformList().GetSelectedPlatform());
394     if (platform_sp) {
395       if (m_option_working_dir.GetOptionValue().OptionWasSet())
396         platform_sp->SetWorkingDirectory(
397             m_option_working_dir.GetOptionValue().GetCurrentValue());
398     } else {
399       result.AppendError("no platform is currently selected");
400     }
401     return result.Succeeded();
402   }
403 
404   Options *GetOptions() override {
405     if (!m_options.DidFinalize())
406       m_options.Finalize();
407     return &m_options;
408   }
409 
410   OptionGroupOptions m_options;
411   OptionGroupFile m_option_working_dir;
412 };
413 
414 // "platform mkdir"
415 class CommandObjectPlatformMkDir : public CommandObjectParsed {
416 public:
417   CommandObjectPlatformMkDir(CommandInterpreter &interpreter)
418       : CommandObjectParsed(interpreter, "platform mkdir",
419                             "Make a new directory on the remote end.", nullptr,
420                             0),
421         m_options() {}
422 
423   ~CommandObjectPlatformMkDir() override = default;
424 
425   bool DoExecute(Args &args, CommandReturnObject &result) override {
426     PlatformSP platform_sp(
427         GetDebugger().GetPlatformList().GetSelectedPlatform());
428     if (platform_sp) {
429       std::string cmd_line;
430       args.GetCommandString(cmd_line);
431       uint32_t mode;
432       const OptionPermissions *options_permissions =
433           (const OptionPermissions *)m_options.GetGroupWithOption('r');
434       if (options_permissions)
435         mode = options_permissions->m_permissions;
436       else
437         mode = lldb::eFilePermissionsUserRWX | lldb::eFilePermissionsGroupRWX |
438                lldb::eFilePermissionsWorldRX;
439       Status error = platform_sp->MakeDirectory(FileSpec(cmd_line), mode);
440       if (error.Success()) {
441         result.SetStatus(eReturnStatusSuccessFinishResult);
442       } else {
443         result.AppendError(error.AsCString());
444       }
445     } else {
446       result.AppendError("no platform currently selected\n");
447     }
448     return result.Succeeded();
449   }
450 
451   Options *GetOptions() override {
452     if (!m_options.DidFinalize()) {
453       m_options.Append(new OptionPermissions());
454       m_options.Finalize();
455     }
456     return &m_options;
457   }
458 
459   OptionGroupOptions m_options;
460 };
461 
462 // "platform fopen"
463 class CommandObjectPlatformFOpen : public CommandObjectParsed {
464 public:
465   CommandObjectPlatformFOpen(CommandInterpreter &interpreter)
466       : CommandObjectParsed(interpreter, "platform file open",
467                             "Open a file on the remote end.", nullptr, 0),
468         m_options() {}
469 
470   ~CommandObjectPlatformFOpen() override = default;
471 
472   void
473   HandleArgumentCompletion(CompletionRequest &request,
474                            OptionElementVector &opt_element_vector) override {
475     if (request.GetCursorIndex() == 0)
476       CommandCompletions::InvokeCommonCompletionCallbacks(
477           GetCommandInterpreter(),
478           CommandCompletions::eRemoteDiskFileCompletion, request, nullptr);
479   }
480 
481   bool DoExecute(Args &args, CommandReturnObject &result) override {
482     PlatformSP platform_sp(
483         GetDebugger().GetPlatformList().GetSelectedPlatform());
484     if (platform_sp) {
485       Status error;
486       std::string cmd_line;
487       args.GetCommandString(cmd_line);
488       mode_t perms;
489       const OptionPermissions *options_permissions =
490           (const OptionPermissions *)m_options.GetGroupWithOption('r');
491       if (options_permissions)
492         perms = options_permissions->m_permissions;
493       else
494         perms = lldb::eFilePermissionsUserRW | lldb::eFilePermissionsGroupRW |
495                 lldb::eFilePermissionsWorldRead;
496       lldb::user_id_t fd = platform_sp->OpenFile(
497           FileSpec(cmd_line),
498           File::eOpenOptionReadWrite | File::eOpenOptionCanCreate,
499           perms, error);
500       if (error.Success()) {
501         result.AppendMessageWithFormat("File Descriptor = %" PRIu64 "\n", fd);
502         result.SetStatus(eReturnStatusSuccessFinishResult);
503       } else {
504         result.AppendError(error.AsCString());
505       }
506     } else {
507       result.AppendError("no platform currently selected\n");
508     }
509     return result.Succeeded();
510   }
511 
512   Options *GetOptions() override {
513     if (!m_options.DidFinalize()) {
514       m_options.Append(new OptionPermissions());
515       m_options.Finalize();
516     }
517     return &m_options;
518   }
519 
520   OptionGroupOptions m_options;
521 };
522 
523 // "platform fclose"
524 class CommandObjectPlatformFClose : public CommandObjectParsed {
525 public:
526   CommandObjectPlatformFClose(CommandInterpreter &interpreter)
527       : CommandObjectParsed(interpreter, "platform file close",
528                             "Close a file on the remote end.", nullptr, 0) {}
529 
530   ~CommandObjectPlatformFClose() override = default;
531 
532   bool DoExecute(Args &args, CommandReturnObject &result) override {
533     PlatformSP platform_sp(
534         GetDebugger().GetPlatformList().GetSelectedPlatform());
535     if (platform_sp) {
536       std::string cmd_line;
537       args.GetCommandString(cmd_line);
538       lldb::user_id_t fd;
539       if (!llvm::to_integer(cmd_line, fd)) {
540         result.AppendErrorWithFormatv("'{0}' is not a valid file descriptor.\n",
541                                       cmd_line);
542         return result.Succeeded();
543       }
544       Status error;
545       bool success = platform_sp->CloseFile(fd, error);
546       if (success) {
547         result.AppendMessageWithFormat("file %" PRIu64 " closed.\n", fd);
548         result.SetStatus(eReturnStatusSuccessFinishResult);
549       } else {
550         result.AppendError(error.AsCString());
551       }
552     } else {
553       result.AppendError("no platform currently selected\n");
554     }
555     return result.Succeeded();
556   }
557 };
558 
559 // "platform fread"
560 
561 #define LLDB_OPTIONS_platform_fread
562 #include "CommandOptions.inc"
563 
564 class CommandObjectPlatformFRead : public CommandObjectParsed {
565 public:
566   CommandObjectPlatformFRead(CommandInterpreter &interpreter)
567       : CommandObjectParsed(interpreter, "platform file read",
568                             "Read data from a file on the remote end.", nullptr,
569                             0),
570         m_options() {}
571 
572   ~CommandObjectPlatformFRead() override = default;
573 
574   bool DoExecute(Args &args, CommandReturnObject &result) override {
575     PlatformSP platform_sp(
576         GetDebugger().GetPlatformList().GetSelectedPlatform());
577     if (platform_sp) {
578       std::string cmd_line;
579       args.GetCommandString(cmd_line);
580       lldb::user_id_t fd;
581       if (!llvm::to_integer(cmd_line, fd)) {
582         result.AppendErrorWithFormatv("'{0}' is not a valid file descriptor.\n",
583                                       cmd_line);
584         return result.Succeeded();
585       }
586       std::string buffer(m_options.m_count, 0);
587       Status error;
588       uint64_t retcode = platform_sp->ReadFile(
589           fd, m_options.m_offset, &buffer[0], m_options.m_count, error);
590       if (retcode != UINT64_MAX) {
591         result.AppendMessageWithFormat("Return = %" PRIu64 "\n", retcode);
592         result.AppendMessageWithFormat("Data = \"%s\"\n", buffer.c_str());
593         result.SetStatus(eReturnStatusSuccessFinishResult);
594       } else {
595         result.AppendError(error.AsCString());
596       }
597     } else {
598       result.AppendError("no platform currently selected\n");
599     }
600     return result.Succeeded();
601   }
602 
603   Options *GetOptions() override { return &m_options; }
604 
605 protected:
606   class CommandOptions : public Options {
607   public:
608     CommandOptions() : Options() {}
609 
610     ~CommandOptions() override = default;
611 
612     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
613                           ExecutionContext *execution_context) override {
614       Status error;
615       char short_option = (char)m_getopt_table[option_idx].val;
616 
617       switch (short_option) {
618       case 'o':
619         if (option_arg.getAsInteger(0, m_offset))
620           error.SetErrorStringWithFormat("invalid offset: '%s'",
621                                          option_arg.str().c_str());
622         break;
623       case 'c':
624         if (option_arg.getAsInteger(0, m_count))
625           error.SetErrorStringWithFormat("invalid offset: '%s'",
626                                          option_arg.str().c_str());
627         break;
628       default:
629         llvm_unreachable("Unimplemented option");
630       }
631 
632       return error;
633     }
634 
635     void OptionParsingStarting(ExecutionContext *execution_context) override {
636       m_offset = 0;
637       m_count = 1;
638     }
639 
640     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
641       return llvm::makeArrayRef(g_platform_fread_options);
642     }
643 
644     // Instance variables to hold the values for command options.
645 
646     uint32_t m_offset;
647     uint32_t m_count;
648   };
649 
650   CommandOptions m_options;
651 };
652 
653 // "platform fwrite"
654 
655 #define LLDB_OPTIONS_platform_fwrite
656 #include "CommandOptions.inc"
657 
658 class CommandObjectPlatformFWrite : public CommandObjectParsed {
659 public:
660   CommandObjectPlatformFWrite(CommandInterpreter &interpreter)
661       : CommandObjectParsed(interpreter, "platform file write",
662                             "Write data to a file on the remote end.", nullptr,
663                             0),
664         m_options() {}
665 
666   ~CommandObjectPlatformFWrite() override = default;
667 
668   bool DoExecute(Args &args, CommandReturnObject &result) override {
669     PlatformSP platform_sp(
670         GetDebugger().GetPlatformList().GetSelectedPlatform());
671     if (platform_sp) {
672       std::string cmd_line;
673       args.GetCommandString(cmd_line);
674       Status error;
675       lldb::user_id_t fd;
676       if (!llvm::to_integer(cmd_line, fd)) {
677         result.AppendErrorWithFormatv("'{0}' is not a valid file descriptor.",
678                                       cmd_line);
679         return result.Succeeded();
680       }
681       uint64_t retcode =
682           platform_sp->WriteFile(fd, m_options.m_offset, &m_options.m_data[0],
683                                  m_options.m_data.size(), error);
684       if (retcode != UINT64_MAX) {
685         result.AppendMessageWithFormat("Return = %" PRIu64 "\n", retcode);
686         result.SetStatus(eReturnStatusSuccessFinishResult);
687       } else {
688         result.AppendError(error.AsCString());
689       }
690     } else {
691       result.AppendError("no platform currently selected\n");
692     }
693     return result.Succeeded();
694   }
695 
696   Options *GetOptions() override { return &m_options; }
697 
698 protected:
699   class CommandOptions : public Options {
700   public:
701     CommandOptions() : Options() {}
702 
703     ~CommandOptions() override = default;
704 
705     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
706                           ExecutionContext *execution_context) override {
707       Status error;
708       char short_option = (char)m_getopt_table[option_idx].val;
709 
710       switch (short_option) {
711       case 'o':
712         if (option_arg.getAsInteger(0, m_offset))
713           error.SetErrorStringWithFormat("invalid offset: '%s'",
714                                          option_arg.str().c_str());
715         break;
716       case 'd':
717         m_data.assign(std::string(option_arg));
718         break;
719       default:
720         llvm_unreachable("Unimplemented option");
721       }
722 
723       return error;
724     }
725 
726     void OptionParsingStarting(ExecutionContext *execution_context) override {
727       m_offset = 0;
728       m_data.clear();
729     }
730 
731     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
732       return llvm::makeArrayRef(g_platform_fwrite_options);
733     }
734 
735     // Instance variables to hold the values for command options.
736 
737     uint32_t m_offset;
738     std::string m_data;
739   };
740 
741   CommandOptions m_options;
742 };
743 
744 class CommandObjectPlatformFile : public CommandObjectMultiword {
745 public:
746   // Constructors and Destructors
747   CommandObjectPlatformFile(CommandInterpreter &interpreter)
748       : CommandObjectMultiword(
749             interpreter, "platform file",
750             "Commands to access files on the current platform.",
751             "platform file [open|close|read|write] ...") {
752     LoadSubCommand(
753         "open", CommandObjectSP(new CommandObjectPlatformFOpen(interpreter)));
754     LoadSubCommand(
755         "close", CommandObjectSP(new CommandObjectPlatformFClose(interpreter)));
756     LoadSubCommand(
757         "read", CommandObjectSP(new CommandObjectPlatformFRead(interpreter)));
758     LoadSubCommand(
759         "write", CommandObjectSP(new CommandObjectPlatformFWrite(interpreter)));
760   }
761 
762   ~CommandObjectPlatformFile() override = default;
763 
764 private:
765   // For CommandObjectPlatform only
766   CommandObjectPlatformFile(const CommandObjectPlatformFile &) = delete;
767   const CommandObjectPlatformFile &
768   operator=(const CommandObjectPlatformFile &) = delete;
769 };
770 
771 // "platform get-file remote-file-path host-file-path"
772 class CommandObjectPlatformGetFile : public CommandObjectParsed {
773 public:
774   CommandObjectPlatformGetFile(CommandInterpreter &interpreter)
775       : CommandObjectParsed(
776             interpreter, "platform get-file",
777             "Transfer a file from the remote end to the local host.",
778             "platform get-file <remote-file-spec> <local-file-spec>", 0) {
779     SetHelpLong(
780         R"(Examples:
781 
782 (lldb) platform get-file /the/remote/file/path /the/local/file/path
783 
784     Transfer a file from the remote end with file path /the/remote/file/path to the local host.)");
785 
786     CommandArgumentEntry arg1, arg2;
787     CommandArgumentData file_arg_remote, file_arg_host;
788 
789     // Define the first (and only) variant of this arg.
790     file_arg_remote.arg_type = eArgTypeFilename;
791     file_arg_remote.arg_repetition = eArgRepeatPlain;
792     // There is only one variant this argument could be; put it into the
793     // argument entry.
794     arg1.push_back(file_arg_remote);
795 
796     // Define the second (and only) variant of this arg.
797     file_arg_host.arg_type = eArgTypeFilename;
798     file_arg_host.arg_repetition = eArgRepeatPlain;
799     // There is only one variant this argument could be; put it into the
800     // argument entry.
801     arg2.push_back(file_arg_host);
802 
803     // Push the data for the first and the second arguments into the
804     // m_arguments vector.
805     m_arguments.push_back(arg1);
806     m_arguments.push_back(arg2);
807   }
808 
809   ~CommandObjectPlatformGetFile() override = default;
810 
811   void
812   HandleArgumentCompletion(CompletionRequest &request,
813                            OptionElementVector &opt_element_vector) override {
814     if (request.GetCursorIndex() == 0)
815       CommandCompletions::InvokeCommonCompletionCallbacks(
816           GetCommandInterpreter(),
817           CommandCompletions::eRemoteDiskFileCompletion, request, nullptr);
818     else if (request.GetCursorIndex() == 1)
819       CommandCompletions::InvokeCommonCompletionCallbacks(
820           GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
821           request, nullptr);
822   }
823 
824   bool DoExecute(Args &args, CommandReturnObject &result) override {
825     // If the number of arguments is incorrect, issue an error message.
826     if (args.GetArgumentCount() != 2) {
827       result.AppendError("required arguments missing; specify both the "
828                          "source and destination file paths");
829       return false;
830     }
831 
832     PlatformSP platform_sp(
833         GetDebugger().GetPlatformList().GetSelectedPlatform());
834     if (platform_sp) {
835       const char *remote_file_path = args.GetArgumentAtIndex(0);
836       const char *local_file_path = args.GetArgumentAtIndex(1);
837       Status error = platform_sp->GetFile(FileSpec(remote_file_path),
838                                           FileSpec(local_file_path));
839       if (error.Success()) {
840         result.AppendMessageWithFormat(
841             "successfully get-file from %s (remote) to %s (host)\n",
842             remote_file_path, local_file_path);
843         result.SetStatus(eReturnStatusSuccessFinishResult);
844       } else {
845         result.AppendMessageWithFormat("get-file failed: %s\n",
846                                        error.AsCString());
847       }
848     } else {
849       result.AppendError("no platform currently selected\n");
850     }
851     return result.Succeeded();
852   }
853 };
854 
855 // "platform get-size remote-file-path"
856 class CommandObjectPlatformGetSize : public CommandObjectParsed {
857 public:
858   CommandObjectPlatformGetSize(CommandInterpreter &interpreter)
859       : CommandObjectParsed(interpreter, "platform get-size",
860                             "Get the file size from the remote end.",
861                             "platform get-size <remote-file-spec>", 0) {
862     SetHelpLong(
863         R"(Examples:
864 
865 (lldb) platform get-size /the/remote/file/path
866 
867     Get the file size from the remote end with path /the/remote/file/path.)");
868 
869     CommandArgumentEntry arg1;
870     CommandArgumentData file_arg_remote;
871 
872     // Define the first (and only) variant of this arg.
873     file_arg_remote.arg_type = eArgTypeFilename;
874     file_arg_remote.arg_repetition = eArgRepeatPlain;
875     // There is only one variant this argument could be; put it into the
876     // argument entry.
877     arg1.push_back(file_arg_remote);
878 
879     // Push the data for the first argument into the m_arguments vector.
880     m_arguments.push_back(arg1);
881   }
882 
883   ~CommandObjectPlatformGetSize() override = default;
884 
885   void
886   HandleArgumentCompletion(CompletionRequest &request,
887                            OptionElementVector &opt_element_vector) override {
888     if (request.GetCursorIndex() != 0)
889       return;
890 
891     CommandCompletions::InvokeCommonCompletionCallbacks(
892         GetCommandInterpreter(), CommandCompletions::eRemoteDiskFileCompletion,
893         request, nullptr);
894   }
895 
896   bool DoExecute(Args &args, CommandReturnObject &result) override {
897     // If the number of arguments is incorrect, issue an error message.
898     if (args.GetArgumentCount() != 1) {
899       result.AppendError("required argument missing; specify the source file "
900                          "path as the only argument");
901       return false;
902     }
903 
904     PlatformSP platform_sp(
905         GetDebugger().GetPlatformList().GetSelectedPlatform());
906     if (platform_sp) {
907       std::string remote_file_path(args.GetArgumentAtIndex(0));
908       user_id_t size = platform_sp->GetFileSize(FileSpec(remote_file_path));
909       if (size != UINT64_MAX) {
910         result.AppendMessageWithFormat("File size of %s (remote): %" PRIu64
911                                        "\n",
912                                        remote_file_path.c_str(), size);
913         result.SetStatus(eReturnStatusSuccessFinishResult);
914       } else {
915         result.AppendMessageWithFormat(
916             "Error getting file size of %s (remote)\n",
917             remote_file_path.c_str());
918       }
919     } else {
920       result.AppendError("no platform currently selected\n");
921     }
922     return result.Succeeded();
923   }
924 };
925 
926 // "platform get-permissions remote-file-path"
927 class CommandObjectPlatformGetPermissions : public CommandObjectParsed {
928 public:
929   CommandObjectPlatformGetPermissions(CommandInterpreter &interpreter)
930       : CommandObjectParsed(interpreter, "platform get-permissions",
931                             "Get the file permission bits from the remote end.",
932                             "platform get-permissions <remote-file-spec>", 0) {
933     SetHelpLong(
934         R"(Examples:
935 
936 (lldb) platform get-permissions /the/remote/file/path
937 
938     Get the file permissions from the remote end with path /the/remote/file/path.)");
939 
940     CommandArgumentEntry arg1;
941     CommandArgumentData file_arg_remote;
942 
943     // Define the first (and only) variant of this arg.
944     file_arg_remote.arg_type = eArgTypeFilename;
945     file_arg_remote.arg_repetition = eArgRepeatPlain;
946     // There is only one variant this argument could be; put it into the
947     // argument entry.
948     arg1.push_back(file_arg_remote);
949 
950     // Push the data for the first argument into the m_arguments vector.
951     m_arguments.push_back(arg1);
952   }
953 
954   ~CommandObjectPlatformGetPermissions() override = default;
955 
956   void
957   HandleArgumentCompletion(CompletionRequest &request,
958                            OptionElementVector &opt_element_vector) override {
959     if (request.GetCursorIndex() != 0)
960       return;
961 
962     CommandCompletions::InvokeCommonCompletionCallbacks(
963         GetCommandInterpreter(), CommandCompletions::eRemoteDiskFileCompletion,
964         request, nullptr);
965   }
966 
967   bool DoExecute(Args &args, CommandReturnObject &result) override {
968     // If the number of arguments is incorrect, issue an error message.
969     if (args.GetArgumentCount() != 1) {
970       result.AppendError("required argument missing; specify the source file "
971                          "path as the only argument");
972       return false;
973     }
974 
975     PlatformSP platform_sp(
976         GetDebugger().GetPlatformList().GetSelectedPlatform());
977     if (platform_sp) {
978       std::string remote_file_path(args.GetArgumentAtIndex(0));
979       uint32_t permissions;
980       Status error = platform_sp->GetFilePermissions(FileSpec(remote_file_path),
981                                                      permissions);
982       if (error.Success()) {
983         result.AppendMessageWithFormat(
984             "File permissions of %s (remote): 0o%04" PRIo32 "\n",
985             remote_file_path.c_str(), permissions);
986         result.SetStatus(eReturnStatusSuccessFinishResult);
987       } else
988         result.AppendError(error.AsCString());
989     } else {
990       result.AppendError("no platform currently selected\n");
991     }
992     return result.Succeeded();
993   }
994 };
995 
996 // "platform file-exists remote-file-path"
997 class CommandObjectPlatformFileExists : public CommandObjectParsed {
998 public:
999   CommandObjectPlatformFileExists(CommandInterpreter &interpreter)
1000       : CommandObjectParsed(interpreter, "platform file-exists",
1001                             "Check if the file exists on the remote end.",
1002                             "platform file-exists <remote-file-spec>", 0) {
1003     SetHelpLong(
1004         R"(Examples:
1005 
1006 (lldb) platform file-exists /the/remote/file/path
1007 
1008     Check if /the/remote/file/path exists on the remote end.)");
1009 
1010     CommandArgumentEntry arg1;
1011     CommandArgumentData file_arg_remote;
1012 
1013     // Define the first (and only) variant of this arg.
1014     file_arg_remote.arg_type = eArgTypeFilename;
1015     file_arg_remote.arg_repetition = eArgRepeatPlain;
1016     // There is only one variant this argument could be; put it into the
1017     // argument entry.
1018     arg1.push_back(file_arg_remote);
1019 
1020     // Push the data for the first argument into the m_arguments vector.
1021     m_arguments.push_back(arg1);
1022   }
1023 
1024   ~CommandObjectPlatformFileExists() override = default;
1025 
1026   void
1027   HandleArgumentCompletion(CompletionRequest &request,
1028                            OptionElementVector &opt_element_vector) override {
1029     if (request.GetCursorIndex() != 0)
1030       return;
1031 
1032     CommandCompletions::InvokeCommonCompletionCallbacks(
1033         GetCommandInterpreter(), CommandCompletions::eRemoteDiskFileCompletion,
1034         request, nullptr);
1035   }
1036 
1037   bool DoExecute(Args &args, CommandReturnObject &result) override {
1038     // If the number of arguments is incorrect, issue an error message.
1039     if (args.GetArgumentCount() != 1) {
1040       result.AppendError("required argument missing; specify the source file "
1041                          "path as the only argument");
1042       return false;
1043     }
1044 
1045     PlatformSP platform_sp(
1046         GetDebugger().GetPlatformList().GetSelectedPlatform());
1047     if (platform_sp) {
1048       std::string remote_file_path(args.GetArgumentAtIndex(0));
1049       bool exists = platform_sp->GetFileExists(FileSpec(remote_file_path));
1050       result.AppendMessageWithFormat(
1051           "File %s (remote) %s\n",
1052           remote_file_path.c_str(), exists ? "exists" : "does not exist");
1053       result.SetStatus(eReturnStatusSuccessFinishResult);
1054     } else {
1055       result.AppendError("no platform currently selected\n");
1056     }
1057     return result.Succeeded();
1058   }
1059 };
1060 
1061 // "platform put-file"
1062 class CommandObjectPlatformPutFile : public CommandObjectParsed {
1063 public:
1064   CommandObjectPlatformPutFile(CommandInterpreter &interpreter)
1065       : CommandObjectParsed(
1066             interpreter, "platform put-file",
1067             "Transfer a file from this system to the remote end.",
1068             "platform put-file <source> [<destination>]", 0) {
1069     SetHelpLong(
1070         R"(Examples:
1071 
1072 (lldb) platform put-file /source/foo.txt /destination/bar.txt
1073 
1074 (lldb) platform put-file /source/foo.txt
1075 
1076     Relative source file paths are resolved against lldb's local working directory.
1077 
1078     Omitting the destination places the file in the platform working directory.)");
1079   }
1080 
1081   ~CommandObjectPlatformPutFile() override = default;
1082 
1083   void
1084   HandleArgumentCompletion(CompletionRequest &request,
1085                            OptionElementVector &opt_element_vector) override {
1086     if (request.GetCursorIndex() == 0)
1087       CommandCompletions::InvokeCommonCompletionCallbacks(
1088           GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
1089           request, nullptr);
1090     else if (request.GetCursorIndex() == 1)
1091       CommandCompletions::InvokeCommonCompletionCallbacks(
1092           GetCommandInterpreter(),
1093           CommandCompletions::eRemoteDiskFileCompletion, request, nullptr);
1094   }
1095 
1096   bool DoExecute(Args &args, CommandReturnObject &result) override {
1097     const char *src = args.GetArgumentAtIndex(0);
1098     const char *dst = args.GetArgumentAtIndex(1);
1099 
1100     FileSpec src_fs(src);
1101     FileSystem::Instance().Resolve(src_fs);
1102     FileSpec dst_fs(dst ? dst : src_fs.GetFilename().GetCString());
1103 
1104     PlatformSP platform_sp(
1105         GetDebugger().GetPlatformList().GetSelectedPlatform());
1106     if (platform_sp) {
1107       Status error(platform_sp->PutFile(src_fs, dst_fs));
1108       if (error.Success()) {
1109         result.SetStatus(eReturnStatusSuccessFinishNoResult);
1110       } else {
1111         result.AppendError(error.AsCString());
1112       }
1113     } else {
1114       result.AppendError("no platform currently selected\n");
1115     }
1116     return result.Succeeded();
1117   }
1118 };
1119 
1120 // "platform process launch"
1121 class CommandObjectPlatformProcessLaunch : public CommandObjectParsed {
1122 public:
1123   CommandObjectPlatformProcessLaunch(CommandInterpreter &interpreter)
1124       : CommandObjectParsed(interpreter, "platform process launch",
1125                             "Launch a new process on a remote platform.",
1126                             "platform process launch program",
1127                             eCommandRequiresTarget | eCommandTryTargetAPILock),
1128         m_options(), m_all_options() {
1129     m_all_options.Append(&m_options);
1130     m_all_options.Finalize();
1131   }
1132 
1133   ~CommandObjectPlatformProcessLaunch() override = default;
1134 
1135   Options *GetOptions() override { return &m_all_options; }
1136 
1137 protected:
1138   bool DoExecute(Args &args, CommandReturnObject &result) override {
1139     Target *target = GetDebugger().GetSelectedTarget().get();
1140     PlatformSP platform_sp;
1141     if (target) {
1142       platform_sp = target->GetPlatform();
1143     }
1144     if (!platform_sp) {
1145       platform_sp = GetDebugger().GetPlatformList().GetSelectedPlatform();
1146     }
1147 
1148     if (platform_sp) {
1149       Status error;
1150       const size_t argc = args.GetArgumentCount();
1151       Target *target = m_exe_ctx.GetTargetPtr();
1152       Module *exe_module = target->GetExecutableModulePointer();
1153       if (exe_module) {
1154         m_options.launch_info.GetExecutableFile() = exe_module->GetFileSpec();
1155         llvm::SmallString<128> exe_path;
1156         m_options.launch_info.GetExecutableFile().GetPath(exe_path);
1157         if (!exe_path.empty())
1158           m_options.launch_info.GetArguments().AppendArgument(exe_path);
1159         m_options.launch_info.GetArchitecture() = exe_module->GetArchitecture();
1160       }
1161 
1162       if (argc > 0) {
1163         if (m_options.launch_info.GetExecutableFile()) {
1164           // We already have an executable file, so we will use this and all
1165           // arguments to this function are extra arguments
1166           m_options.launch_info.GetArguments().AppendArguments(args);
1167         } else {
1168           // We don't have any file yet, so the first argument is our
1169           // executable, and the rest are program arguments
1170           const bool first_arg_is_executable = true;
1171           m_options.launch_info.SetArguments(args, first_arg_is_executable);
1172         }
1173       }
1174 
1175       if (m_options.launch_info.GetExecutableFile()) {
1176         Debugger &debugger = GetDebugger();
1177 
1178         if (argc == 0)
1179           target->GetRunArguments(m_options.launch_info.GetArguments());
1180 
1181         ProcessSP process_sp(platform_sp->DebugProcess(
1182             m_options.launch_info, debugger, *target, error));
1183         if (process_sp && process_sp->IsAlive()) {
1184           result.SetStatus(eReturnStatusSuccessFinishNoResult);
1185           return true;
1186         }
1187 
1188         if (error.Success())
1189           result.AppendError("process launch failed");
1190         else
1191           result.AppendError(error.AsCString());
1192       } else {
1193         result.AppendError("'platform process launch' uses the current target "
1194                            "file and arguments, or the executable and its "
1195                            "arguments can be specified in this command");
1196         return false;
1197       }
1198     } else {
1199       result.AppendError("no platform is selected\n");
1200     }
1201     return result.Succeeded();
1202   }
1203 
1204   CommandOptionsProcessLaunch m_options;
1205   OptionGroupOptions m_all_options;
1206 };
1207 
1208 // "platform process list"
1209 
1210 static PosixPlatformCommandOptionValidator posix_validator;
1211 #define LLDB_OPTIONS_platform_process_list
1212 #include "CommandOptions.inc"
1213 
1214 class CommandObjectPlatformProcessList : public CommandObjectParsed {
1215 public:
1216   CommandObjectPlatformProcessList(CommandInterpreter &interpreter)
1217       : CommandObjectParsed(interpreter, "platform process list",
1218                             "List processes on a remote platform by name, pid, "
1219                             "or many other matching attributes.",
1220                             "platform process list", 0),
1221         m_options() {}
1222 
1223   ~CommandObjectPlatformProcessList() override = default;
1224 
1225   Options *GetOptions() override { return &m_options; }
1226 
1227 protected:
1228   bool DoExecute(Args &args, CommandReturnObject &result) override {
1229     Target *target = GetDebugger().GetSelectedTarget().get();
1230     PlatformSP platform_sp;
1231     if (target) {
1232       platform_sp = target->GetPlatform();
1233     }
1234     if (!platform_sp) {
1235       platform_sp = GetDebugger().GetPlatformList().GetSelectedPlatform();
1236     }
1237 
1238     if (platform_sp) {
1239       Status error;
1240       if (args.GetArgumentCount() == 0) {
1241         if (platform_sp) {
1242           Stream &ostrm = result.GetOutputStream();
1243 
1244           lldb::pid_t pid =
1245               m_options.match_info.GetProcessInfo().GetProcessID();
1246           if (pid != LLDB_INVALID_PROCESS_ID) {
1247             ProcessInstanceInfo proc_info;
1248             if (platform_sp->GetProcessInfo(pid, proc_info)) {
1249               ProcessInstanceInfo::DumpTableHeader(ostrm, m_options.show_args,
1250                                                    m_options.verbose);
1251               proc_info.DumpAsTableRow(ostrm, platform_sp->GetUserIDResolver(),
1252                                        m_options.show_args, m_options.verbose);
1253               result.SetStatus(eReturnStatusSuccessFinishResult);
1254             } else {
1255               result.AppendErrorWithFormat(
1256                   "no process found with pid = %" PRIu64 "\n", pid);
1257             }
1258           } else {
1259             ProcessInstanceInfoList proc_infos;
1260             const uint32_t matches =
1261                 platform_sp->FindProcesses(m_options.match_info, proc_infos);
1262             const char *match_desc = nullptr;
1263             const char *match_name =
1264                 m_options.match_info.GetProcessInfo().GetName();
1265             if (match_name && match_name[0]) {
1266               switch (m_options.match_info.GetNameMatchType()) {
1267               case NameMatch::Ignore:
1268                 break;
1269               case NameMatch::Equals:
1270                 match_desc = "matched";
1271                 break;
1272               case NameMatch::Contains:
1273                 match_desc = "contained";
1274                 break;
1275               case NameMatch::StartsWith:
1276                 match_desc = "started with";
1277                 break;
1278               case NameMatch::EndsWith:
1279                 match_desc = "ended with";
1280                 break;
1281               case NameMatch::RegularExpression:
1282                 match_desc = "matched the regular expression";
1283                 break;
1284               }
1285             }
1286 
1287             if (matches == 0) {
1288               if (match_desc)
1289                 result.AppendErrorWithFormatv(
1290                     "no processes were found that {0} \"{1}\" on the \"{2}\" "
1291                     "platform\n",
1292                     match_desc, match_name, platform_sp->GetPluginName());
1293               else
1294                 result.AppendErrorWithFormatv(
1295                     "no processes were found on the \"{0}\" platform\n",
1296                     platform_sp->GetPluginName());
1297             } else {
1298               result.AppendMessageWithFormat(
1299                   "%u matching process%s found on \"%s\"", matches,
1300                   matches > 1 ? "es were" : " was",
1301                   platform_sp->GetName().GetCString());
1302               if (match_desc)
1303                 result.AppendMessageWithFormat(" whose name %s \"%s\"",
1304                                                match_desc, match_name);
1305               result.AppendMessageWithFormat("\n");
1306               ProcessInstanceInfo::DumpTableHeader(ostrm, m_options.show_args,
1307                                                    m_options.verbose);
1308               for (uint32_t i = 0; i < matches; ++i) {
1309                 proc_infos[i].DumpAsTableRow(
1310                     ostrm, platform_sp->GetUserIDResolver(),
1311                     m_options.show_args, m_options.verbose);
1312               }
1313             }
1314           }
1315         }
1316       } else {
1317         result.AppendError("invalid args: process list takes only options\n");
1318       }
1319     } else {
1320       result.AppendError("no platform is selected\n");
1321     }
1322     return result.Succeeded();
1323   }
1324 
1325   class CommandOptions : public Options {
1326   public:
1327     CommandOptions() : Options(), match_info() {}
1328 
1329     ~CommandOptions() override = default;
1330 
1331     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1332                           ExecutionContext *execution_context) override {
1333       Status error;
1334       const int short_option = m_getopt_table[option_idx].val;
1335       bool success = false;
1336 
1337       uint32_t id = LLDB_INVALID_PROCESS_ID;
1338       success = !option_arg.getAsInteger(0, id);
1339       switch (short_option) {
1340       case 'p': {
1341         match_info.GetProcessInfo().SetProcessID(id);
1342         if (!success)
1343           error.SetErrorStringWithFormat("invalid process ID string: '%s'",
1344                                          option_arg.str().c_str());
1345         break;
1346       }
1347       case 'P':
1348         match_info.GetProcessInfo().SetParentProcessID(id);
1349         if (!success)
1350           error.SetErrorStringWithFormat(
1351               "invalid parent process ID string: '%s'",
1352               option_arg.str().c_str());
1353         break;
1354 
1355       case 'u':
1356         match_info.GetProcessInfo().SetUserID(success ? id : UINT32_MAX);
1357         if (!success)
1358           error.SetErrorStringWithFormat("invalid user ID string: '%s'",
1359                                          option_arg.str().c_str());
1360         break;
1361 
1362       case 'U':
1363         match_info.GetProcessInfo().SetEffectiveUserID(success ? id
1364                                                                : UINT32_MAX);
1365         if (!success)
1366           error.SetErrorStringWithFormat(
1367               "invalid effective user ID string: '%s'",
1368               option_arg.str().c_str());
1369         break;
1370 
1371       case 'g':
1372         match_info.GetProcessInfo().SetGroupID(success ? id : UINT32_MAX);
1373         if (!success)
1374           error.SetErrorStringWithFormat("invalid group ID string: '%s'",
1375                                          option_arg.str().c_str());
1376         break;
1377 
1378       case 'G':
1379         match_info.GetProcessInfo().SetEffectiveGroupID(success ? id
1380                                                                 : UINT32_MAX);
1381         if (!success)
1382           error.SetErrorStringWithFormat(
1383               "invalid effective group ID string: '%s'",
1384               option_arg.str().c_str());
1385         break;
1386 
1387       case 'a': {
1388         TargetSP target_sp =
1389             execution_context ? execution_context->GetTargetSP() : TargetSP();
1390         DebuggerSP debugger_sp =
1391             target_sp ? target_sp->GetDebugger().shared_from_this()
1392                       : DebuggerSP();
1393         PlatformSP platform_sp =
1394             debugger_sp ? debugger_sp->GetPlatformList().GetSelectedPlatform()
1395                         : PlatformSP();
1396         match_info.GetProcessInfo().GetArchitecture() =
1397             Platform::GetAugmentedArchSpec(platform_sp.get(), option_arg);
1398       } break;
1399 
1400       case 'n':
1401         match_info.GetProcessInfo().GetExecutableFile().SetFile(
1402             option_arg, FileSpec::Style::native);
1403         match_info.SetNameMatchType(NameMatch::Equals);
1404         break;
1405 
1406       case 'e':
1407         match_info.GetProcessInfo().GetExecutableFile().SetFile(
1408             option_arg, FileSpec::Style::native);
1409         match_info.SetNameMatchType(NameMatch::EndsWith);
1410         break;
1411 
1412       case 's':
1413         match_info.GetProcessInfo().GetExecutableFile().SetFile(
1414             option_arg, FileSpec::Style::native);
1415         match_info.SetNameMatchType(NameMatch::StartsWith);
1416         break;
1417 
1418       case 'c':
1419         match_info.GetProcessInfo().GetExecutableFile().SetFile(
1420             option_arg, FileSpec::Style::native);
1421         match_info.SetNameMatchType(NameMatch::Contains);
1422         break;
1423 
1424       case 'r':
1425         match_info.GetProcessInfo().GetExecutableFile().SetFile(
1426             option_arg, FileSpec::Style::native);
1427         match_info.SetNameMatchType(NameMatch::RegularExpression);
1428         break;
1429 
1430       case 'A':
1431         show_args = true;
1432         break;
1433 
1434       case 'v':
1435         verbose = true;
1436         break;
1437 
1438       case 'x':
1439         match_info.SetMatchAllUsers(true);
1440         break;
1441 
1442       default:
1443         llvm_unreachable("Unimplemented option");
1444       }
1445 
1446       return error;
1447     }
1448 
1449     void OptionParsingStarting(ExecutionContext *execution_context) override {
1450       match_info.Clear();
1451       show_args = false;
1452       verbose = false;
1453     }
1454 
1455     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1456       return llvm::makeArrayRef(g_platform_process_list_options);
1457     }
1458 
1459     // Instance variables to hold the values for command options.
1460 
1461     ProcessInstanceInfoMatch match_info;
1462     bool show_args = false;
1463     bool verbose = false;
1464   };
1465 
1466   CommandOptions m_options;
1467 };
1468 
1469 // "platform process info"
1470 class CommandObjectPlatformProcessInfo : public CommandObjectParsed {
1471 public:
1472   CommandObjectPlatformProcessInfo(CommandInterpreter &interpreter)
1473       : CommandObjectParsed(
1474             interpreter, "platform process info",
1475             "Get detailed information for one or more process by process ID.",
1476             "platform process info <pid> [<pid> <pid> ...]", 0) {
1477     CommandArgumentEntry arg;
1478     CommandArgumentData pid_args;
1479 
1480     // Define the first (and only) variant of this arg.
1481     pid_args.arg_type = eArgTypePid;
1482     pid_args.arg_repetition = eArgRepeatStar;
1483 
1484     // There is only one variant this argument could be; put it into the
1485     // argument entry.
1486     arg.push_back(pid_args);
1487 
1488     // Push the data for the first argument into the m_arguments vector.
1489     m_arguments.push_back(arg);
1490   }
1491 
1492   ~CommandObjectPlatformProcessInfo() override = default;
1493 
1494   void
1495   HandleArgumentCompletion(CompletionRequest &request,
1496                            OptionElementVector &opt_element_vector) override {
1497     CommandCompletions::InvokeCommonCompletionCallbacks(
1498         GetCommandInterpreter(), CommandCompletions::eProcessIDCompletion,
1499         request, nullptr);
1500   }
1501 
1502 protected:
1503   bool DoExecute(Args &args, CommandReturnObject &result) override {
1504     Target *target = GetDebugger().GetSelectedTarget().get();
1505     PlatformSP platform_sp;
1506     if (target) {
1507       platform_sp = target->GetPlatform();
1508     }
1509     if (!platform_sp) {
1510       platform_sp = GetDebugger().GetPlatformList().GetSelectedPlatform();
1511     }
1512 
1513     if (platform_sp) {
1514       const size_t argc = args.GetArgumentCount();
1515       if (argc > 0) {
1516         Status error;
1517 
1518         if (platform_sp->IsConnected()) {
1519           Stream &ostrm = result.GetOutputStream();
1520           for (auto &entry : args.entries()) {
1521             lldb::pid_t pid;
1522             if (entry.ref().getAsInteger(0, pid)) {
1523               result.AppendErrorWithFormat("invalid process ID argument '%s'",
1524                                            entry.ref().str().c_str());
1525               break;
1526             } else {
1527               ProcessInstanceInfo proc_info;
1528               if (platform_sp->GetProcessInfo(pid, proc_info)) {
1529                 ostrm.Printf("Process information for process %" PRIu64 ":\n",
1530                              pid);
1531                 proc_info.Dump(ostrm, platform_sp->GetUserIDResolver());
1532               } else {
1533                 ostrm.Printf("error: no process information is available for "
1534                              "process %" PRIu64 "\n",
1535                              pid);
1536               }
1537               ostrm.EOL();
1538             }
1539           }
1540         } else {
1541           // Not connected...
1542           result.AppendErrorWithFormatv("not connected to '{0}'",
1543                                         platform_sp->GetPluginName());
1544         }
1545       } else {
1546         // No args
1547         result.AppendError("one or more process id(s) must be specified");
1548       }
1549     } else {
1550       result.AppendError("no platform is currently selected");
1551     }
1552     return result.Succeeded();
1553   }
1554 };
1555 
1556 #define LLDB_OPTIONS_platform_process_attach
1557 #include "CommandOptions.inc"
1558 
1559 class CommandObjectPlatformProcessAttach : public CommandObjectParsed {
1560 public:
1561   class CommandOptions : public Options {
1562   public:
1563     CommandOptions() : Options() {
1564       // Keep default values of all options in one place: OptionParsingStarting
1565       // ()
1566       OptionParsingStarting(nullptr);
1567     }
1568 
1569     ~CommandOptions() override = default;
1570 
1571     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1572                           ExecutionContext *execution_context) override {
1573       Status error;
1574       char short_option = (char)m_getopt_table[option_idx].val;
1575       switch (short_option) {
1576       case 'p': {
1577         lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
1578         if (option_arg.getAsInteger(0, pid)) {
1579           error.SetErrorStringWithFormat("invalid process ID '%s'",
1580                                          option_arg.str().c_str());
1581         } else {
1582           attach_info.SetProcessID(pid);
1583         }
1584       } break;
1585 
1586       case 'P':
1587         attach_info.SetProcessPluginName(option_arg);
1588         break;
1589 
1590       case 'n':
1591         attach_info.GetExecutableFile().SetFile(option_arg,
1592                                                 FileSpec::Style::native);
1593         break;
1594 
1595       case 'w':
1596         attach_info.SetWaitForLaunch(true);
1597         break;
1598 
1599       default:
1600         llvm_unreachable("Unimplemented option");
1601       }
1602       return error;
1603     }
1604 
1605     void OptionParsingStarting(ExecutionContext *execution_context) override {
1606       attach_info.Clear();
1607     }
1608 
1609     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1610       return llvm::makeArrayRef(g_platform_process_attach_options);
1611     }
1612 
1613     // Options table: Required for subclasses of Options.
1614 
1615     static OptionDefinition g_option_table[];
1616 
1617     // Instance variables to hold the values for command options.
1618 
1619     ProcessAttachInfo attach_info;
1620   };
1621 
1622   CommandObjectPlatformProcessAttach(CommandInterpreter &interpreter)
1623       : CommandObjectParsed(interpreter, "platform process attach",
1624                             "Attach to a process.",
1625                             "platform process attach <cmd-options>"),
1626         m_options() {}
1627 
1628   ~CommandObjectPlatformProcessAttach() override = default;
1629 
1630   bool DoExecute(Args &command, CommandReturnObject &result) override {
1631     PlatformSP platform_sp(
1632         GetDebugger().GetPlatformList().GetSelectedPlatform());
1633     if (platform_sp) {
1634       Status err;
1635       ProcessSP remote_process_sp = platform_sp->Attach(
1636           m_options.attach_info, GetDebugger(), nullptr, err);
1637       if (err.Fail()) {
1638         result.AppendError(err.AsCString());
1639       } else if (!remote_process_sp) {
1640         result.AppendError("could not attach: unknown reason");
1641       } else
1642         result.SetStatus(eReturnStatusSuccessFinishResult);
1643     } else {
1644       result.AppendError("no platform is currently selected");
1645     }
1646     return result.Succeeded();
1647   }
1648 
1649   Options *GetOptions() override { return &m_options; }
1650 
1651 protected:
1652   CommandOptions m_options;
1653 };
1654 
1655 class CommandObjectPlatformProcess : public CommandObjectMultiword {
1656 public:
1657   // Constructors and Destructors
1658   CommandObjectPlatformProcess(CommandInterpreter &interpreter)
1659       : CommandObjectMultiword(interpreter, "platform process",
1660                                "Commands to query, launch and attach to "
1661                                "processes on the current platform.",
1662                                "platform process [attach|launch|list] ...") {
1663     LoadSubCommand(
1664         "attach",
1665         CommandObjectSP(new CommandObjectPlatformProcessAttach(interpreter)));
1666     LoadSubCommand(
1667         "launch",
1668         CommandObjectSP(new CommandObjectPlatformProcessLaunch(interpreter)));
1669     LoadSubCommand("info", CommandObjectSP(new CommandObjectPlatformProcessInfo(
1670                                interpreter)));
1671     LoadSubCommand("list", CommandObjectSP(new CommandObjectPlatformProcessList(
1672                                interpreter)));
1673   }
1674 
1675   ~CommandObjectPlatformProcess() override = default;
1676 
1677 private:
1678   // For CommandObjectPlatform only
1679   CommandObjectPlatformProcess(const CommandObjectPlatformProcess &) = delete;
1680   const CommandObjectPlatformProcess &
1681   operator=(const CommandObjectPlatformProcess &) = delete;
1682 };
1683 
1684 // "platform shell"
1685 #define LLDB_OPTIONS_platform_shell
1686 #include "CommandOptions.inc"
1687 
1688 class CommandObjectPlatformShell : public CommandObjectRaw {
1689 public:
1690   class CommandOptions : public Options {
1691   public:
1692     CommandOptions() : Options() {}
1693 
1694     ~CommandOptions() override = default;
1695 
1696     llvm::ArrayRef<OptionDefinition> GetDefinitions() override {
1697       return llvm::makeArrayRef(g_platform_shell_options);
1698     }
1699 
1700     Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_arg,
1701                           ExecutionContext *execution_context) override {
1702       Status error;
1703 
1704       const char short_option = (char)GetDefinitions()[option_idx].short_option;
1705 
1706       switch (short_option) {
1707       case 'h':
1708         m_use_host_platform = true;
1709         break;
1710       case 't':
1711         uint32_t timeout_sec;
1712         if (option_arg.getAsInteger(10, timeout_sec))
1713           error.SetErrorStringWithFormat(
1714               "could not convert \"%s\" to a numeric value.",
1715               option_arg.str().c_str());
1716         else
1717           m_timeout = std::chrono::seconds(timeout_sec);
1718         break;
1719       case 's': {
1720         if (option_arg.empty()) {
1721           error.SetErrorStringWithFormat(
1722               "missing shell interpreter path for option -i|--interpreter.");
1723           return error;
1724         }
1725 
1726         m_shell_interpreter = option_arg.str();
1727         break;
1728       }
1729       default:
1730         llvm_unreachable("Unimplemented option");
1731       }
1732 
1733       return error;
1734     }
1735 
1736     void OptionParsingStarting(ExecutionContext *execution_context) override {
1737       m_timeout.reset();
1738       m_use_host_platform = false;
1739       m_shell_interpreter.clear();
1740     }
1741 
1742     Timeout<std::micro> m_timeout = std::chrono::seconds(10);
1743     bool m_use_host_platform;
1744     std::string m_shell_interpreter;
1745   };
1746 
1747   CommandObjectPlatformShell(CommandInterpreter &interpreter)
1748       : CommandObjectRaw(interpreter, "platform shell",
1749                          "Run a shell command on the current platform.",
1750                          "platform shell <shell-command>", 0),
1751         m_options() {}
1752 
1753   ~CommandObjectPlatformShell() override = default;
1754 
1755   Options *GetOptions() override { return &m_options; }
1756 
1757   bool DoExecute(llvm::StringRef raw_command_line,
1758                  CommandReturnObject &result) override {
1759     ExecutionContext exe_ctx = GetCommandInterpreter().GetExecutionContext();
1760     m_options.NotifyOptionParsingStarting(&exe_ctx);
1761 
1762     // Print out an usage syntax on an empty command line.
1763     if (raw_command_line.empty()) {
1764       result.GetOutputStream().Printf("%s\n", this->GetSyntax().str().c_str());
1765       return true;
1766     }
1767 
1768     const bool is_alias = !raw_command_line.contains("platform");
1769     OptionsWithRaw args(raw_command_line);
1770 
1771     if (args.HasArgs())
1772       if (!ParseOptions(args.GetArgs(), result))
1773         return false;
1774 
1775     if (args.GetRawPart().empty()) {
1776       result.GetOutputStream().Printf("%s <shell-command>\n",
1777                                       is_alias ? "shell" : "platform shell");
1778       return false;
1779     }
1780 
1781     llvm::StringRef cmd = args.GetRawPart();
1782 
1783     PlatformSP platform_sp(
1784         m_options.m_use_host_platform
1785             ? Platform::GetHostPlatform()
1786             : GetDebugger().GetPlatformList().GetSelectedPlatform());
1787     Status error;
1788     if (platform_sp) {
1789       FileSpec working_dir{};
1790       std::string output;
1791       int status = -1;
1792       int signo = -1;
1793       error = (platform_sp->RunShellCommand(m_options.m_shell_interpreter, cmd,
1794                                             working_dir, &status, &signo,
1795                                             &output, m_options.m_timeout));
1796       if (!output.empty())
1797         result.GetOutputStream().PutCString(output);
1798       if (status > 0) {
1799         if (signo > 0) {
1800           const char *signo_cstr = Host::GetSignalAsCString(signo);
1801           if (signo_cstr)
1802             result.GetOutputStream().Printf(
1803                 "error: command returned with status %i and signal %s\n",
1804                 status, signo_cstr);
1805           else
1806             result.GetOutputStream().Printf(
1807                 "error: command returned with status %i and signal %i\n",
1808                 status, signo);
1809         } else
1810           result.GetOutputStream().Printf(
1811               "error: command returned with status %i\n", status);
1812       }
1813     } else {
1814       result.GetOutputStream().Printf(
1815           "error: cannot run remote shell commands without a platform\n");
1816       error.SetErrorString(
1817           "error: cannot run remote shell commands without a platform");
1818     }
1819 
1820     if (error.Fail()) {
1821       result.AppendError(error.AsCString());
1822     } else {
1823       result.SetStatus(eReturnStatusSuccessFinishResult);
1824     }
1825     return true;
1826   }
1827 
1828   CommandOptions m_options;
1829 };
1830 
1831 // "platform install" - install a target to a remote end
1832 class CommandObjectPlatformInstall : public CommandObjectParsed {
1833 public:
1834   CommandObjectPlatformInstall(CommandInterpreter &interpreter)
1835       : CommandObjectParsed(
1836             interpreter, "platform target-install",
1837             "Install a target (bundle or executable file) to the remote end.",
1838             "platform target-install <local-thing> <remote-sandbox>", 0) {}
1839 
1840   ~CommandObjectPlatformInstall() override = default;
1841 
1842   void
1843   HandleArgumentCompletion(CompletionRequest &request,
1844                            OptionElementVector &opt_element_vector) override {
1845     if (request.GetCursorIndex())
1846       return;
1847     CommandCompletions::InvokeCommonCompletionCallbacks(
1848         GetCommandInterpreter(), CommandCompletions::eDiskFileCompletion,
1849         request, nullptr);
1850   }
1851 
1852   bool DoExecute(Args &args, CommandReturnObject &result) override {
1853     if (args.GetArgumentCount() != 2) {
1854       result.AppendError("platform target-install takes two arguments");
1855       return false;
1856     }
1857     // TODO: move the bulk of this code over to the platform itself
1858     FileSpec src(args.GetArgumentAtIndex(0));
1859     FileSystem::Instance().Resolve(src);
1860     FileSpec dst(args.GetArgumentAtIndex(1));
1861     if (!FileSystem::Instance().Exists(src)) {
1862       result.AppendError("source location does not exist or is not accessible");
1863       return false;
1864     }
1865     PlatformSP platform_sp(
1866         GetDebugger().GetPlatformList().GetSelectedPlatform());
1867     if (!platform_sp) {
1868       result.AppendError("no platform currently selected");
1869       return false;
1870     }
1871 
1872     Status error = platform_sp->Install(src, dst);
1873     if (error.Success()) {
1874       result.SetStatus(eReturnStatusSuccessFinishNoResult);
1875     } else {
1876       result.AppendErrorWithFormat("install failed: %s", error.AsCString());
1877     }
1878     return result.Succeeded();
1879   }
1880 };
1881 
1882 CommandObjectPlatform::CommandObjectPlatform(CommandInterpreter &interpreter)
1883     : CommandObjectMultiword(
1884           interpreter, "platform", "Commands to manage and create platforms.",
1885           "platform [connect|disconnect|info|list|status|select] ...") {
1886   LoadSubCommand("select",
1887                  CommandObjectSP(new CommandObjectPlatformSelect(interpreter)));
1888   LoadSubCommand("list",
1889                  CommandObjectSP(new CommandObjectPlatformList(interpreter)));
1890   LoadSubCommand("status",
1891                  CommandObjectSP(new CommandObjectPlatformStatus(interpreter)));
1892   LoadSubCommand("connect", CommandObjectSP(
1893                                 new CommandObjectPlatformConnect(interpreter)));
1894   LoadSubCommand(
1895       "disconnect",
1896       CommandObjectSP(new CommandObjectPlatformDisconnect(interpreter)));
1897   LoadSubCommand("settings", CommandObjectSP(new CommandObjectPlatformSettings(
1898                                  interpreter)));
1899   LoadSubCommand("mkdir",
1900                  CommandObjectSP(new CommandObjectPlatformMkDir(interpreter)));
1901   LoadSubCommand("file",
1902                  CommandObjectSP(new CommandObjectPlatformFile(interpreter)));
1903   LoadSubCommand("file-exists",
1904       CommandObjectSP(new CommandObjectPlatformFileExists(interpreter)));
1905   LoadSubCommand("get-file", CommandObjectSP(new CommandObjectPlatformGetFile(
1906                                  interpreter)));
1907   LoadSubCommand("get-permissions",
1908       CommandObjectSP(new CommandObjectPlatformGetPermissions(interpreter)));
1909   LoadSubCommand("get-size", CommandObjectSP(new CommandObjectPlatformGetSize(
1910                                  interpreter)));
1911   LoadSubCommand("put-file", CommandObjectSP(new CommandObjectPlatformPutFile(
1912                                  interpreter)));
1913   LoadSubCommand("process", CommandObjectSP(
1914                                 new CommandObjectPlatformProcess(interpreter)));
1915   LoadSubCommand("shell",
1916                  CommandObjectSP(new CommandObjectPlatformShell(interpreter)));
1917   LoadSubCommand(
1918       "target-install",
1919       CommandObjectSP(new CommandObjectPlatformInstall(interpreter)));
1920 }
1921 
1922 CommandObjectPlatform::~CommandObjectPlatform() = default;
1923