LLDB mainline
PlatformRemoteGDBServer.cpp
Go to the documentation of this file.
1//===-- PlatformRemoteGDBServer.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
10#include "lldb/Host/Config.h"
11
13#include "lldb/Core/Debugger.h"
14#include "lldb/Core/Module.h"
19#include "lldb/Host/Host.h"
20#include "lldb/Host/HostInfo.h"
21#include "lldb/Host/PosixApi.h"
22#include "lldb/Target/Process.h"
23#include "lldb/Target/Target.h"
26#include "lldb/Utility/Log.h"
28#include "lldb/Utility/Status.h"
31#include "llvm/ADT/StringSet.h"
32#include "llvm/Support/FormatAdapters.h"
33
36#include <mutex>
37#include <optional>
38
39using namespace lldb;
40using namespace lldb_private;
42
44
45static bool g_initialized = false;
46// UnixSignals does not store the signal names or descriptions itself.
47// It holds onto StringRefs. Becaue we may get signal information dynamically
48// from the remote, these strings need persistent storage client-side.
49static std::mutex g_signal_string_mutex;
50static llvm::StringSet<> g_signal_string_storage;
51
63
72
74 const ArchSpec *arch) {
75 bool create = force;
76 if (!create) {
77 create = !arch->TripleVendorWasSpecified() && !arch->TripleOSWasSpecified();
78 }
79 if (create)
81 return PlatformSP();
82}
83
85 return "A platform that uses the GDB remote protocol as the communication "
86 "transport.";
87}
88
90 if (m_platform_description.empty()) {
91 if (IsConnected()) {
92 // Send the get description packet
93 }
94 }
95
96 if (!m_platform_description.empty())
97 return m_platform_description.c_str();
98 return GetDescriptionStatic();
99}
100
102 const ArchSpec &arch,
103 ModuleSpec &module_spec) {
105
106 const auto module_path = module_file_spec.GetPath(false);
107
108 if (!m_gdb_client_up ||
109 !m_gdb_client_up->GetModuleInfo(module_file_spec, arch, module_spec)) {
110 LLDB_LOGF(
111 log,
112 "PlatformRemoteGDBServer::%s - failed to get module info for %s:%s",
113 __FUNCTION__, module_path.c_str(),
114 arch.GetTriple().getTriple().c_str());
115 return false;
116 }
117
118 if (log) {
119 StreamString stream;
120 module_spec.Dump(stream);
121 LLDB_LOGF(log,
122 "PlatformRemoteGDBServer::%s - got module info for (%s:%s) : %s",
123 __FUNCTION__, module_path.c_str(),
124 arch.GetTriple().getTriple().c_str(), stream.GetData());
125 }
126
127 return true;
128}
129
131 const UUID *uuid_ptr,
132 FileSpec &local_file) {
133 // Default to the local case
134 local_file = platform_file;
135 return Status();
136}
137
138/// Default Constructor
141
142/// Destructor.
143///
144/// The destructor is virtual since this class is designed to be
145/// inherited from by the plug-in instance.
147
149 Target &target, BreakpointSite *bp_site) {
150 // This isn't needed if the z/Z packets are supported in the GDB remote
151 // server. But we might need a packet to detect this.
152 return 0;
153}
154
156 if (m_gdb_client_up)
157 m_os_version = m_gdb_client_up->GetOSVersion();
158 return !m_os_version.empty();
159}
160
162 if (!m_gdb_client_up)
163 return std::nullopt;
164 return m_gdb_client_up->GetOSBuildString();
165}
166
167std::optional<std::string>
169 if (!m_gdb_client_up)
170 return std::nullopt;
171 return m_gdb_client_up->GetOSKernelDescription();
172}
173
174// Remote Platform subclasses need to override this function
176 if (!m_gdb_client_up)
177 return ArchSpec();
178 return m_gdb_client_up->GetSystemArchitecture();
179}
180
182 if (IsConnected()) {
184 FileSpec working_dir;
185 if (m_gdb_client_up->GetWorkingDir(working_dir) && log)
186 LLDB_LOGF(log,
187 "PlatformRemoteGDBServer::GetRemoteWorkingDirectory() -> '%s'",
188 working_dir.GetPath().c_str());
189 return working_dir;
190 } else {
192 }
193}
194
196 const FileSpec &working_dir) {
197 if (IsConnected()) {
198 // Clear the working directory it case it doesn't get set correctly. This
199 // will for use to re-read it
201 LLDB_LOGF(log, "PlatformRemoteGDBServer::SetRemoteWorkingDirectory('%s')",
202 working_dir.GetPath().c_str());
203 return m_gdb_client_up->SetWorkingDir(working_dir) == 0;
204 } else
205 return Platform::SetRemoteWorkingDirectory(working_dir);
206}
207
209 return m_gdb_client_up && m_gdb_client_up->IsConnected();
210}
211
214 if (IsConnected())
216 "the platform is already connected to '%s', "
217 "execute 'platform disconnect' to close the "
218 "current connection",
219 GetHostname());
220
221 if (args.GetArgumentCount() != 1)
223 "\"platform connect\" takes a single argument: <connect-url>");
224
225 const char *url = args.GetArgumentAtIndex(0);
226 if (!url)
227 return Status::FromErrorString("URL is null.");
228
229 std::optional<URI> parsed_url = URI::Parse(url);
230 if (!parsed_url)
231 return Status::FromErrorStringWithFormat("Invalid URL: %s", url);
232
233 // We're going to reuse the hostname when we connect to the debugserver.
234 m_platform_scheme = parsed_url->scheme.str();
235 m_platform_hostname = parsed_url->hostname.str();
236
237 auto client_up =
238 std::make_unique<process_gdb_remote::GDBRemoteCommunicationClient>();
239 client_up->SetPacketTimeout(
241 client_up->SetConnection(std::make_unique<ConnectionFileDescriptor>());
242 client_up->Connect(url, &error);
243
244 if (error.Fail())
245 return error;
246
247 if (client_up->HandshakeWithServer(&error)) {
248 m_gdb_client_up = std::move(client_up);
249 m_gdb_client_up->GetHostInfo();
250 // If a working directory was set prior to connecting, send it down
251 // now.
252 if (m_working_dir)
253 m_gdb_client_up->SetWorkingDir(m_working_dir);
254
256 ArchSpec remote_arch = m_gdb_client_up->GetSystemArchitecture();
257 if (remote_arch) {
258 m_supported_architectures.push_back(remote_arch);
259 if (remote_arch.GetTriple().isArch64Bit())
261 ArchSpec(remote_arch.GetTriple().get32BitArchVariant()));
262 }
263 } else {
264 client_up->Disconnect();
265 if (error.Success())
266 error = Status::FromErrorString("handshake failed");
267 }
268 return error;
269}
270
277
279 if (m_gdb_client_up)
280 m_gdb_client_up->GetHostname(m_hostname);
281 if (m_hostname.empty())
282 return nullptr;
283 return m_hostname.c_str();
284}
285
286std::optional<std::string>
288 std::string name;
289 if (m_gdb_client_up && m_gdb_client_up->GetUserName(uid, name))
290 return std::move(name);
291 return std::nullopt;
292}
293
294std::optional<std::string>
296 std::string name;
297 if (m_gdb_client_up && m_gdb_client_up->GetGroupName(gid, name))
298 return std::move(name);
299 return std::nullopt;
300}
301
303 const ProcessInstanceInfoMatch &match_info,
304 ProcessInstanceInfoList &process_infos) {
305 if (m_gdb_client_up)
306 return m_gdb_client_up->FindProcesses(match_info, process_infos);
307 return 0;
308}
309
311 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
312 if (m_gdb_client_up)
313 return m_gdb_client_up->GetProcessInfo(pid, process_info);
314 return false;
315}
316
320
321 LLDB_LOGF(log, "PlatformRemoteGDBServer::%s() called", __FUNCTION__);
322
323 if (!IsConnected())
324 return Status::FromErrorStringWithFormat("Not connected.");
325 auto num_file_actions = launch_info.GetNumFileActions();
326 for (decltype(num_file_actions) i = 0; i < num_file_actions; ++i) {
327 const auto file_action = launch_info.GetFileActionAtIndex(i);
328 if (file_action->GetAction() != FileAction::eFileActionOpen)
329 continue;
330 switch (file_action->GetFD()) {
331 case STDIN_FILENO:
332 m_gdb_client_up->SetSTDIN(file_action->GetFileSpec());
333 break;
334 case STDOUT_FILENO:
335 m_gdb_client_up->SetSTDOUT(file_action->GetFileSpec());
336 break;
337 case STDERR_FILENO:
338 m_gdb_client_up->SetSTDERR(file_action->GetFileSpec());
339 break;
340 }
341 }
342
343 m_gdb_client_up->SetDisableASLR(
344 launch_info.GetFlags().Test(eLaunchFlagDisableASLR));
345 m_gdb_client_up->SetDetachOnError(
346 launch_info.GetFlags().Test(eLaunchFlagDetachOnError));
347
348 FileSpec working_dir = launch_info.GetWorkingDirectory();
349 if (working_dir) {
350 m_gdb_client_up->SetWorkingDir(working_dir);
351 }
352
353 // Send the environment and the program + arguments after we connect
354 m_gdb_client_up->SendEnvironment(launch_info.GetEnvironment());
355
356 ArchSpec arch_spec = launch_info.GetArchitecture();
357 const char *arch_triple = arch_spec.GetTriple().str().c_str();
358
359 m_gdb_client_up->SendLaunchArchPacket(arch_triple);
360 LLDB_LOGF(
361 log,
362 "PlatformRemoteGDBServer::%s() set launch architecture triple to '%s'",
363 __FUNCTION__, arch_triple ? arch_triple : "<NULL>");
364
365 {
366 // Scope for the scoped timeout object
368 *m_gdb_client_up, std::chrono::seconds(5));
369 // Since we can't send argv0 separate from the executable path, we need to
370 // make sure to use the actual executable path found in the launch_info...
371 Args args = launch_info.GetArguments();
372 if (FileSpec exe_file = launch_info.GetExecutableFile())
373 args.ReplaceArgumentAtIndex(0, exe_file.GetPath(false));
374 if (llvm::Error err = m_gdb_client_up->LaunchProcess(args)) {
376 "Cannot launch '{0}': {1}", args.GetArgumentAtIndex(0),
377 llvm::fmt_consume(std::move(err)));
378 return error;
379 }
380 }
381
382 const auto pid = m_gdb_client_up->GetCurrentProcessID(false);
383 if (pid != LLDB_INVALID_PROCESS_ID) {
384 launch_info.SetProcessID(pid);
385 LLDB_LOGF(log,
386 "PlatformRemoteGDBServer::%s() pid %" PRIu64
387 " launched successfully",
388 __FUNCTION__, pid);
389 } else {
390 LLDB_LOGF(log,
391 "PlatformRemoteGDBServer::%s() launch succeeded but we "
392 "didn't get a valid process id back!",
393 __FUNCTION__);
394 error = Status::FromErrorString("failed to get PID");
395 }
396 return error;
397}
398
400 if (!KillSpawnedProcess(pid))
402 "failed to kill remote spawned process");
403 return Status();
404}
405
408 Debugger &debugger, Target &target,
409 Status &error) {
410 lldb::ProcessSP process_sp;
411 if (IsRemote()) {
412 if (IsConnected()) {
413 lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
414 std::string connect_url;
415 if (!LaunchGDBServer(debugserver_pid, connect_url)) {
417 "unable to launch a GDB server on '%s'", GetHostname());
418 } else {
419 // By default, we always use the GDB remote debugger plug-in.
420 // Even when debugging locally, we are debugging remotely.
421 llvm::StringRef process_plugin = "gdb-remote";
422
423 // However, if a process plugin is specified by the attach info, we
424 // should honor it.
425 if (!launch_info.GetProcessPluginName().empty())
426 process_plugin = launch_info.GetProcessPluginName();
427
428 process_sp = target.CreateProcess(launch_info.GetListener(),
429 process_plugin, nullptr, true);
430
431 if (process_sp) {
432 process_sp->HijackProcessEvents(launch_info.GetHijackListener());
433 process_sp->SetShadowListener(launch_info.GetShadowListener());
434
435 error = process_sp->ConnectRemote(connect_url.c_str());
436 // Retry the connect remote one time...
437 if (error.Fail())
438 error = process_sp->ConnectRemote(connect_url.c_str());
439 if (error.Success())
440 error = process_sp->Launch(launch_info);
441 else if (debugserver_pid != LLDB_INVALID_PROCESS_ID) {
442 printf("error: connect remote failed (%s)\n", error.AsCString());
443 KillSpawnedProcess(debugserver_pid);
444 }
445 }
446 }
447 } else {
448 error = Status::FromErrorString("not connected to remote gdb server");
449 }
450 }
451 return process_sp;
452}
453
455 std::string &connect_url) {
456 assert(IsConnected());
457
459 llvm::Triple &remote_triple = remote_arch.GetTriple();
460
461 uint16_t port = 0;
462 std::string socket_name;
463 bool launch_result = false;
464 if (remote_triple.getVendor() == llvm::Triple::Apple &&
465 remote_triple.getOS() == llvm::Triple::IOS) {
466 // When remote debugging to iOS, we use a USB mux that always talks to
467 // localhost, so we will need the remote debugserver to accept connections
468 // only from localhost, no matter what our current hostname is
469 launch_result =
470 m_gdb_client_up->LaunchGDBServer("127.0.0.1", pid, port, socket_name);
471 } else {
472 // All other hosts should use their actual hostname
473 launch_result =
474 m_gdb_client_up->LaunchGDBServer(nullptr, pid, port, socket_name);
475 }
476
477 if (!launch_result)
478 return false;
479
480 connect_url =
482 (socket_name.empty()) ? nullptr : socket_name.c_str());
483 return true;
484}
485
487 assert(IsConnected());
488 return m_gdb_client_up->KillSpawnedProcess(pid);
489}
490
492 ProcessAttachInfo &attach_info, Debugger &debugger,
493 Target *target, // Can be NULL, if NULL create a new target, else use
494 // existing one
495 Status &error) {
496 lldb::ProcessSP process_sp;
497 if (IsRemote()) {
498 if (IsConnected()) {
499 lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
500 std::string connect_url;
501 if (!LaunchGDBServer(debugserver_pid, connect_url)) {
503 "unable to launch a GDB server on '%s'", GetHostname());
504 } else {
505 if (target == nullptr) {
506 TargetSP new_target_sp;
507
508 error = debugger.GetTargetList().CreateTarget(
509 debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp);
510 target = new_target_sp.get();
511 } else
512 error.Clear();
513
514 if (target && error.Success()) {
515 // By default, we always use the GDB remote debugger plug-in.
516 // Even when debugging locally, we are debugging remotely.
517 llvm::StringRef process_plugin = "gdb-remote";
518
519 // However, if a process plugin is specified by the attach info, we
520 // should honor it.
521 if (!attach_info.GetProcessPluginName().empty())
522 process_plugin = attach_info.GetProcessPluginName();
523
524 process_sp =
525 target->CreateProcess(attach_info.GetListenerForProcess(debugger),
526 process_plugin, nullptr, true);
527 if (process_sp) {
528 error = process_sp->ConnectRemote(connect_url.c_str());
529 if (error.Success()) {
530 ListenerSP listener_sp = attach_info.GetHijackListener();
531 if (listener_sp)
532 process_sp->HijackProcessEvents(listener_sp);
533 process_sp->SetShadowListener(attach_info.GetShadowListener());
534 error = process_sp->Attach(attach_info);
535 }
536
537 if (error.Fail() && debugserver_pid != LLDB_INVALID_PROCESS_ID) {
538 KillSpawnedProcess(debugserver_pid);
539 }
540 }
541 }
542 }
543 } else {
544 error = Status::FromErrorString("not connected to remote gdb server");
545 }
546 }
547 return process_sp;
548}
549
551 uint32_t mode) {
552 if (!IsConnected())
553 return Status::FromErrorStringWithFormat("Not connected.");
554 Status error = m_gdb_client_up->MakeDirectory(file_spec, mode);
556 LLDB_LOGF(log,
557 "PlatformRemoteGDBServer::MakeDirectory(path='%s', mode=%o) "
558 "error = %u (%s)",
559 file_spec.GetPath().c_str(), mode, error.GetError(),
560 error.AsCString());
561 return error;
562}
563
565 uint32_t &file_permissions) {
566 if (!IsConnected())
567 return Status::FromErrorStringWithFormat("Not connected.");
568 Status error =
569 m_gdb_client_up->GetFilePermissions(file_spec, file_permissions);
571 LLDB_LOGF(log,
572 "PlatformRemoteGDBServer::GetFilePermissions(path='%s', "
573 "file_permissions=%o) error = %u (%s)",
574 file_spec.GetPath().c_str(), file_permissions, error.GetError(),
575 error.AsCString());
576 return error;
577}
578
580 uint32_t file_permissions) {
581 if (!IsConnected())
582 return Status::FromErrorStringWithFormat("Not connected.");
583 Status error =
584 m_gdb_client_up->SetFilePermissions(file_spec, file_permissions);
586 LLDB_LOGF(log,
587 "PlatformRemoteGDBServer::SetFilePermissions(path='%s', "
588 "file_permissions=%o) error = %u (%s)",
589 file_spec.GetPath().c_str(), file_permissions, error.GetError(),
590 error.AsCString());
591 return error;
592}
593
595 File::OpenOptions flags,
596 uint32_t mode,
597 Status &error) {
598 if (IsConnected())
599 return m_gdb_client_up->OpenFile(file_spec, flags, mode, error);
600 return LLDB_INVALID_UID;
601}
602
604 if (IsConnected())
605 return m_gdb_client_up->CloseFile(fd, error);
606 error = Status::FromErrorStringWithFormat("Not connected.");
607 return false;
608}
609
612 if (IsConnected())
613 return m_gdb_client_up->GetFileSize(file_spec);
614 return LLDB_INVALID_UID;
615}
616
618 CompletionRequest &request, bool only_dir) {
619 if (IsConnected())
620 m_gdb_client_up->AutoCompleteDiskFileOrDirectory(request, only_dir);
621}
622
624 void *dst, uint64_t dst_len,
625 Status &error) {
626 if (IsConnected())
627 return m_gdb_client_up->ReadFile(fd, offset, dst, dst_len, error);
628 error = Status::FromErrorStringWithFormat("Not connected.");
629 return 0;
630}
631
633 const void *src, uint64_t src_len,
634 Status &error) {
635 if (IsConnected())
636 return m_gdb_client_up->WriteFile(fd, offset, src, src_len, error);
637 error = Status::FromErrorStringWithFormat("Not connected.");
638 return 0;
639}
640
642 const FileSpec &destination,
643 uint32_t uid, uint32_t gid) {
644 return Platform::PutFile(source, destination, uid, gid);
645}
646
648 const FileSpec &src, // The name of the link is in src
649 const FileSpec &dst) // The symlink points to dst
650{
651 if (!IsConnected())
652 return Status::FromErrorStringWithFormat("Not connected.");
653 Status error = m_gdb_client_up->CreateSymlink(src, dst);
655 LLDB_LOGF(log,
656 "PlatformRemoteGDBServer::CreateSymlink(src='%s', dst='%s') "
657 "error = %u (%s)",
658 src.GetPath().c_str(), dst.GetPath().c_str(), error.GetError(),
659 error.AsCString());
660 return error;
661}
662
664 if (!IsConnected())
665 return Status::FromErrorStringWithFormat("Not connected.");
666 Status error = m_gdb_client_up->Unlink(file_spec);
668 LLDB_LOGF(log, "PlatformRemoteGDBServer::Unlink(path='%s') error = %u (%s)",
669 file_spec.GetPath().c_str(), error.GetError(), error.AsCString());
670 return error;
671}
672
674 if (IsConnected())
675 return m_gdb_client_up->GetFileExists(file_spec);
676 return false;
677}
678
680 llvm::StringRef shell, llvm::StringRef command,
681 const FileSpec &
682 working_dir, // Pass empty FileSpec to use the current working directory
683 int *status_ptr, // Pass NULL if you don't want the process exit status
684 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
685 // process to exit
686 std::string
687 *command_output, // Pass NULL if you don't want the command output
688 const Timeout<std::micro> &timeout) {
689 if (!IsConnected())
690 return Status::FromErrorStringWithFormat("Not connected.");
691 return m_gdb_client_up->RunShellCommand(command, working_dir, status_ptr,
692 signo_ptr, command_output, timeout);
693}
694
695llvm::ErrorOr<llvm::MD5::MD5Result>
697 if (!IsConnected())
698 return std::make_error_code(std::errc::not_connected);
699
700 return m_gdb_client_up->CalculateMD5(file_spec);
701}
702
706
708 if (!IsConnected())
710
712 return m_remote_signals_sp;
713
714 // If packet not implemented or JSON failed to parse, we'll guess the signal
715 // set based on the remote architecture.
717
719 auto result =
720 m_gdb_client_up->SendPacketAndWaitForResponse("jSignalsInfo", response);
721
722 if (result != decltype(result)::Success ||
723 response.GetResponseType() != response.eResponse)
724 return m_remote_signals_sp;
725
726 auto object_sp = StructuredData::ParseJSON(response.GetStringRef());
727 if (!object_sp || !object_sp->IsValid())
728 return m_remote_signals_sp;
729
730 auto array_sp = object_sp->GetAsArray();
731 if (!array_sp || !array_sp->IsValid())
732 return m_remote_signals_sp;
733
734 auto remote_signals_sp = std::make_shared<lldb_private::GDBRemoteSignals>();
735
736 bool done = array_sp->ForEach(
737 [&remote_signals_sp](StructuredData::Object *object) -> bool {
738 if (!object || !object->IsValid())
739 return false;
740
741 auto dict = object->GetAsDictionary();
742 if (!dict || !dict->IsValid())
743 return false;
744
745 // Signal number and signal name are required.
746 uint64_t signo;
747 if (!dict->GetValueForKeyAsInteger("signo", signo))
748 return false;
749
750 llvm::StringRef name;
751 if (!dict->GetValueForKeyAsString("name", name))
752 return false;
753
754 // We can live without short_name, description, etc.
755 bool suppress{false};
756 auto object_sp = dict->GetValueForKey("suppress");
757 if (object_sp && object_sp->IsValid())
758 suppress = object_sp->GetBooleanValue();
759
760 bool stop{false};
761 object_sp = dict->GetValueForKey("stop");
762 if (object_sp && object_sp->IsValid())
763 stop = object_sp->GetBooleanValue();
764
765 bool notify{false};
766 object_sp = dict->GetValueForKey("notify");
767 if (object_sp && object_sp->IsValid())
768 notify = object_sp->GetBooleanValue();
769
770 std::string description;
771 object_sp = dict->GetValueForKey("description");
772 if (object_sp && object_sp->IsValid())
773 description = std::string(object_sp->GetStringValue());
774
775 llvm::StringRef name_backed, description_backed;
776 {
777 std::lock_guard<std::mutex> guard(g_signal_string_mutex);
778 name_backed =
779 g_signal_string_storage.insert(name).first->getKeyData();
780 if (!description.empty())
781 description_backed =
782 g_signal_string_storage.insert(description).first->getKeyData();
783 }
784
785 remote_signals_sp->AddSignal(signo, name_backed, suppress, stop, notify,
786 description_backed);
787 return true;
788 });
789
790 if (done)
791 m_remote_signals_sp = std::move(remote_signals_sp);
792
793 return m_remote_signals_sp;
794}
795
797 const std::string &platform_scheme, const std::string &platform_hostname,
798 uint16_t port, const char *socket_name) {
799 const char *override_scheme =
800 getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_SCHEME");
801 const char *override_hostname =
802 getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_HOSTNAME");
803 const char *port_offset_c_str =
804 getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_PORT_OFFSET");
805 int port_offset = port_offset_c_str ? ::atoi(port_offset_c_str) : 0;
806
807 return MakeUrl(override_scheme ? override_scheme : platform_scheme.c_str(),
808 override_hostname ? override_hostname
809 : platform_hostname.c_str(),
810 port + port_offset, socket_name);
811}
812
813std::string PlatformRemoteGDBServer::MakeUrl(const char *scheme,
814 const char *hostname,
815 uint16_t port, const char *path) {
816 StreamString result;
817 result.Printf("%s://", scheme);
818 if (strlen(hostname) > 0)
819 result.Printf("[%s]", hostname);
820
821 if (port != 0)
822 result.Printf(":%u", port);
823 if (path)
824 result.Write(path, strlen(path));
825 return std::string(result.GetString());
826}
827
829 Status &error) {
830 std::vector<std::string> connection_urls;
831 GetPendingGdbServerList(connection_urls);
832
833 for (size_t i = 0; i < connection_urls.size(); ++i) {
834 ConnectProcess(connection_urls[i].c_str(), "gdb-remote", debugger, nullptr, error);
835 if (error.Fail())
836 return i; // We already connected to i process successfully
837 }
838 return connection_urls.size();
839}
840
842 std::vector<std::string> &connection_urls) {
843 std::vector<std::pair<uint16_t, std::string>> remote_servers;
844 if (!IsConnected())
845 return 0;
846 m_gdb_client_up->QueryGDBServer(remote_servers);
847 for (const auto &gdbserver : remote_servers) {
848 const char *socket_name_cstr =
849 gdbserver.second.empty() ? nullptr : gdbserver.second.c_str();
850 connection_urls.emplace_back(
852 gdbserver.first, socket_name_cstr));
853 }
854 return connection_urls.size();
855}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOGF(log,...)
Definition Log.h:376
static llvm::StringSet g_signal_string_storage
static std::mutex g_signal_string_mutex
static bool g_initialized
#define LLDB_PLUGIN_DEFINE_ADV(ClassName, PluginName)
llvm::StringRef GetStringRef() const
An architecture specification class.
Definition ArchSpec.h:31
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:468
bool TripleVendorWasSpecified() const
Definition ArchSpec.h:371
bool TripleOSWasSpecified() const
Definition ArchSpec.h:375
A command line argument class.
Definition Args.h:33
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition Args.h:120
void ReplaceArgumentAtIndex(size_t idx, llvm::StringRef arg_str, char quote_char='\0')
Replaces the argument value at index idx to arg_str if idx is a valid argument index.
Definition Args.cpp:347
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx.
Definition Args.cpp:273
Class that manages the actual breakpoint that will be inserted into the running program.
"lldb/Utility/ArgCompletionRequest.h"
A uniqued constant string class.
Definition ConstString.h:40
A class to manage flag bits.
Definition Debugger.h:80
TargetList & GetTargetList()
Get accessor for the target list.
Definition Debugger.h:204
A file utility class.
Definition FileSpec.h:57
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:374
bool Test(ValueType bit) const
Test a single flag bit.
Definition Flags.h:96
void Dump(Stream &strm) const
Definition ModuleSpec.h:175
virtual FileSpec GetRemoteWorkingDirectory()
Definition Platform.h:237
std::vector< ConstString > m_trap_handlers
Definition Platform.h:1024
static void Terminate()
Definition Platform.cpp:138
llvm::VersionTuple m_os_version
Definition Platform.h:1008
virtual Status PutFile(const FileSpec &source, const FileSpec &destination, uint32_t uid=UINT32_MAX, uint32_t gid=UINT32_MAX)
Platform(bool is_host_platform)
Default Constructor.
Definition Platform.cpp:233
virtual bool SetRemoteWorkingDirectory(const FileSpec &working_dir)
Definition Platform.cpp:703
virtual lldb::ProcessSP ConnectProcess(llvm::StringRef connect_url, llvm::StringRef plugin_name, Debugger &debugger, Target *target, Status &error)
static void Initialize()
Definition Platform.cpp:136
std::string m_hostname
Definition Platform.h:1007
bool IsRemote() const
Definition Platform.h:507
virtual const lldb::UnixSignalsSP & GetRemoteUnixSignals()
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
lldb::ListenerSP GetListenerForProcess(Debugger &debugger)
Definition Process.cpp:3029
llvm::StringRef GetProcessPluginName() const
Definition Process.h:157
lldb::ListenerSP GetHijackListener() const
void SetProcessID(lldb::pid_t pid)
Definition ProcessInfo.h:70
FileSpec & GetExecutableFile()
Definition ProcessInfo.h:43
lldb::ListenerSP GetListener() const
lldb::ListenerSP GetShadowListener() const
Environment & GetEnvironment()
Definition ProcessInfo.h:88
ArchSpec & GetArchitecture()
Definition ProcessInfo.h:62
llvm::StringRef GetProcessPluginName() const
const FileAction * GetFileActionAtIndex(size_t idx) const
const FileSpec & GetWorkingDirectory() const
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
const char * GetData() const
llvm::StringRef GetString() const
size_t Write(const void *src, size_t src_len)
Output character bytes to the stream.
Definition Stream.h:112
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
static ObjectSP ParseJSON(llvm::StringRef json_text)
Status CreateTarget(Debugger &debugger, llvm::StringRef user_exe_path, llvm::StringRef triple_str, LoadDependentFiles get_dependent_modules, const OptionGroupPlatform *platform_options, lldb::TargetSP &target_sp)
Create a new Target.
const lldb::ProcessSP & CreateProcess(lldb::ListenerSP listener_sp, llvm::StringRef plugin_name, const FileSpec *crash_file, bool can_connect)
Definition Target.cpp:300
Represents UUID's of various sizes.
Definition UUID.h:27
static lldb::UnixSignalsSP Create(const ArchSpec &arch)
lldb::user_id_t GetFileSize(const FileSpec &file_spec) override
std::unique_ptr< process_gdb_remote::GDBRemoteCommunicationClient > m_gdb_client_up
Status MakeDirectory(const FileSpec &file_spec, uint32_t file_permissions) override
uint32_t FindProcesses(const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos) override
Attach to an existing process by process name.
virtual size_t GetPendingGdbServerList(std::vector< std::string > &connection_urls)
llvm::ErrorOr< llvm::MD5::MD5Result > CalculateMD5(const FileSpec &file_spec) override
void CalculateTrapHandlerSymbolNames() override
Ask the Platform subclass to fill in the list of trap handler names.
size_t ConnectToWaitingProcesses(lldb_private::Debugger &debugger, lldb_private::Status &error) override
Connect to all processes waiting for a debugger to attach.
Status RunShellCommand(llvm::StringRef shell, llvm::StringRef command, const FileSpec &working_dir, int *status_ptr, int *signo_ptr, std::string *command_output, const lldb_private::Timeout< std::micro > &timeout) override
virtual bool LaunchGDBServer(lldb::pid_t &pid, std::string &connect_url)
Status PutFile(const FileSpec &source, const FileSpec &destination, uint32_t uid=UINT32_MAX, uint32_t gid=UINT32_MAX) override
uint64_t WriteFile(lldb::user_id_t fd, uint64_t offset, const void *data, uint64_t len, Status &error) override
Status GetFilePermissions(const FileSpec &file_spec, uint32_t &file_permissions) override
virtual std::string MakeUrl(const char *scheme, const char *hostname, uint16_t port, const char *path)
Status GetFileWithUUID(const FileSpec &platform_file, const UUID *uuid_ptr, FileSpec &local_file) override
Locate a file for a platform.
uint64_t ReadFile(lldb::user_id_t fd, uint64_t offset, void *data_ptr, uint64_t len, Status &error) override
bool GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &proc_info) override
bool CloseFile(lldb::user_id_t fd, Status &error) override
std::optional< std::string > DoGetGroupName(UserIDResolver::id_t uid) override
Status SetFilePermissions(const FileSpec &file_spec, uint32_t file_permissions) override
bool SetRemoteWorkingDirectory(const FileSpec &working_dir) override
Status LaunchProcess(ProcessLaunchInfo &launch_info) override
Launch a new process on a platform, not necessarily for debugging, it could be just for running the p...
std::string MakeGdbServerUrl(const std::string &platform_scheme, const std::string &platform_hostname, uint16_t port, const char *socket_name)
bool GetModuleSpec(const FileSpec &module_file_spec, const ArchSpec &arch, ModuleSpec &module_spec) override
std::optional< std::string > DoGetUserName(UserIDResolver::id_t uid) override
void AutoCompleteDiskFileOrDirectory(CompletionRequest &request, bool only_dir) override
lldb::user_id_t OpenFile(const FileSpec &file_spec, File::OpenOptions flags, uint32_t mode, Status &error) override
static lldb::PlatformSP CreateInstance(bool force, const ArchSpec *arch)
Status CreateSymlink(const FileSpec &src, const FileSpec &dst) override
Status KillProcess(const lldb::pid_t pid) override
Kill process on a platform.
lldb::ProcessSP Attach(ProcessAttachInfo &attach_info, Debugger &debugger, Target *target, Status &error) override
Attach to an existing process using a process ID.
size_t GetSoftwareBreakpointTrapOpcode(Target &target, BreakpointSite *bp_site) override
lldb::ProcessSP DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger, Target &target, Status &error) override
Subclasses do not need to implement this function as it uses the Platform::LaunchProcess() followed b...
#define LLDB_INVALID_UID
#define LLDB_INVALID_PROCESS_ID
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:332
std::vector< ProcessInstanceInfo > ProcessInstanceInfoList
Definition Host.h:32
std::shared_ptr< lldb_private::UnixSignals > UnixSignalsSP
std::shared_ptr< lldb_private::Platform > PlatformSP
std::shared_ptr< lldb_private::Process > ProcessSP
uint64_t pid_t
Definition lldb-types.h:83
std::shared_ptr< lldb_private::Listener > ListenerSP
uint64_t user_id_t
Definition lldb-types.h:82
std::shared_ptr< lldb_private::Target > TargetSP
static std::optional< URI > Parse(llvm::StringRef uri)
Definition UriParser.cpp:28