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
52void PlatformRemoteGDBServer::Initialize() {
54
55 if (!g_initialized) {
56 g_initialized = true;
61 }
62}
63
65 if (g_initialized) {
66 g_initialized = false;
68 }
69
71}
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
140 : Platform(/*is_host=*/false) {}
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 if (m_gdb_client_up) {
210 assert(m_gdb_client_up->IsConnected());
211 return true;
212 }
213 return false;
214}
215
218 if (IsConnected())
220 "the platform is already connected to '%s', "
221 "execute 'platform disconnect' to close the "
222 "current connection",
223 GetHostname());
224
225 if (args.GetArgumentCount() != 1)
227 "\"platform connect\" takes a single argument: <connect-url>");
228
229 const char *url = args.GetArgumentAtIndex(0);
230 if (!url)
231 return Status::FromErrorString("URL is null.");
232
233 std::optional<URI> parsed_url = URI::Parse(url);
234 if (!parsed_url)
235 return Status::FromErrorStringWithFormat("Invalid URL: %s", url);
236
237 // We're going to reuse the hostname when we connect to the debugserver.
238 m_platform_scheme = parsed_url->scheme.str();
239 m_platform_hostname = parsed_url->hostname.str();
240
241 auto client_up =
242 std::make_unique<process_gdb_remote::GDBRemoteCommunicationClient>();
243 client_up->SetPacketTimeout(
245 client_up->SetConnection(std::make_unique<ConnectionFileDescriptor>());
246 client_up->Connect(url, &error);
247
248 if (error.Fail())
249 return error;
250
251 if (client_up->HandshakeWithServer(&error)) {
252 m_gdb_client_up = std::move(client_up);
253 m_gdb_client_up->GetHostInfo();
254 // If a working directory was set prior to connecting, send it down
255 // now.
256 if (m_working_dir)
257 m_gdb_client_up->SetWorkingDir(m_working_dir);
258
260 ArchSpec remote_arch = m_gdb_client_up->GetSystemArchitecture();
261 if (remote_arch) {
262 m_supported_architectures.push_back(remote_arch);
263 if (remote_arch.GetTriple().isArch64Bit())
265 ArchSpec(remote_arch.GetTriple().get32BitArchVariant()));
266 }
267 } else {
268 client_up->Disconnect();
269 if (error.Success())
270 error = Status::FromErrorString("handshake failed");
271 }
272 return error;
273}
274
277 m_gdb_client_up.reset();
278 m_remote_signals_sp.reset();
279 return error;
280}
281
283 if (m_gdb_client_up)
284 m_gdb_client_up->GetHostname(m_hostname);
285 if (m_hostname.empty())
286 return nullptr;
287 return m_hostname.c_str();
288}
289
290std::optional<std::string>
292 std::string name;
293 if (m_gdb_client_up && m_gdb_client_up->GetUserName(uid, name))
294 return std::move(name);
295 return std::nullopt;
296}
297
298std::optional<std::string>
300 std::string name;
301 if (m_gdb_client_up && m_gdb_client_up->GetGroupName(gid, name))
302 return std::move(name);
303 return std::nullopt;
304}
305
307 const ProcessInstanceInfoMatch &match_info,
308 ProcessInstanceInfoList &process_infos) {
309 if (m_gdb_client_up)
310 return m_gdb_client_up->FindProcesses(match_info, process_infos);
311 return 0;
312}
313
315 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
316 if (m_gdb_client_up)
317 return m_gdb_client_up->GetProcessInfo(pid, process_info);
318 return false;
319}
320
324
325 LLDB_LOGF(log, "PlatformRemoteGDBServer::%s() called", __FUNCTION__);
326
327 if (!IsConnected())
328 return Status::FromErrorStringWithFormat("Not connected.");
329 auto num_file_actions = launch_info.GetNumFileActions();
330 for (decltype(num_file_actions) i = 0; i < num_file_actions; ++i) {
331 const auto file_action = launch_info.GetFileActionAtIndex(i);
332 if (file_action->GetAction() != FileAction::eFileActionOpen)
333 continue;
334 switch (file_action->GetFD()) {
335 case STDIN_FILENO:
336 m_gdb_client_up->SetSTDIN(file_action->GetFileSpec());
337 break;
338 case STDOUT_FILENO:
339 m_gdb_client_up->SetSTDOUT(file_action->GetFileSpec());
340 break;
341 case STDERR_FILENO:
342 m_gdb_client_up->SetSTDERR(file_action->GetFileSpec());
343 break;
344 }
345 }
346
347 m_gdb_client_up->SetDisableASLR(
348 launch_info.GetFlags().Test(eLaunchFlagDisableASLR));
349 m_gdb_client_up->SetDetachOnError(
350 launch_info.GetFlags().Test(eLaunchFlagDetachOnError));
351
352 FileSpec working_dir = launch_info.GetWorkingDirectory();
353 if (working_dir) {
354 m_gdb_client_up->SetWorkingDir(working_dir);
355 }
356
357 // Send the environment and the program + arguments after we connect
358 m_gdb_client_up->SendEnvironment(launch_info.GetEnvironment());
359
360 ArchSpec arch_spec = launch_info.GetArchitecture();
361 const char *arch_triple = arch_spec.GetTriple().str().c_str();
362
363 m_gdb_client_up->SendLaunchArchPacket(arch_triple);
364 LLDB_LOGF(
365 log,
366 "PlatformRemoteGDBServer::%s() set launch architecture triple to '%s'",
367 __FUNCTION__, arch_triple ? arch_triple : "<NULL>");
368
369 {
370 // Scope for the scoped timeout object
372 *m_gdb_client_up, std::chrono::seconds(5));
373 // Since we can't send argv0 separate from the executable path, we need to
374 // make sure to use the actual executable path found in the launch_info...
375 Args args = launch_info.GetArguments();
376 if (FileSpec exe_file = launch_info.GetExecutableFile())
377 args.ReplaceArgumentAtIndex(0, exe_file.GetPath(false));
378 if (llvm::Error err = m_gdb_client_up->LaunchProcess(args)) {
380 "Cannot launch '{0}': {1}", args.GetArgumentAtIndex(0),
381 llvm::fmt_consume(std::move(err)));
382 return error;
383 }
384 }
385
386 const auto pid = m_gdb_client_up->GetCurrentProcessID(false);
387 if (pid != LLDB_INVALID_PROCESS_ID) {
388 launch_info.SetProcessID(pid);
389 LLDB_LOGF(log,
390 "PlatformRemoteGDBServer::%s() pid %" PRIu64
391 " launched successfully",
392 __FUNCTION__, pid);
393 } else {
394 LLDB_LOGF(log,
395 "PlatformRemoteGDBServer::%s() launch succeeded but we "
396 "didn't get a valid process id back!",
397 __FUNCTION__);
398 error = Status::FromErrorString("failed to get PID");
399 }
400 return error;
401}
402
404 if (!KillSpawnedProcess(pid))
406 "failed to kill remote spawned process");
407 return Status();
408}
409
412 Debugger &debugger, Target &target,
413 Status &error) {
414 lldb::ProcessSP process_sp;
415 if (IsRemote()) {
416 if (IsConnected()) {
417 lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
418 std::string connect_url;
419 if (!LaunchGDBServer(debugserver_pid, connect_url)) {
421 "unable to launch a GDB server on '%s'", GetHostname());
422 } else {
423 // The darwin always currently uses the GDB remote debugger plug-in
424 // so even when debugging locally we are debugging remotely!
425 process_sp = target.CreateProcess(launch_info.GetListener(),
426 "gdb-remote", nullptr, true);
427
428 if (process_sp) {
429 process_sp->HijackProcessEvents(launch_info.GetHijackListener());
430 process_sp->SetShadowListener(launch_info.GetShadowListener());
431
432 error = process_sp->ConnectRemote(connect_url.c_str());
433 // Retry the connect remote one time...
434 if (error.Fail())
435 error = process_sp->ConnectRemote(connect_url.c_str());
436 if (error.Success())
437 error = process_sp->Launch(launch_info);
438 else if (debugserver_pid != LLDB_INVALID_PROCESS_ID) {
439 printf("error: connect remote failed (%s)\n", error.AsCString());
440 KillSpawnedProcess(debugserver_pid);
441 }
442 }
443 }
444 } else {
445 error = Status::FromErrorString("not connected to remote gdb server");
446 }
447 }
448 return process_sp;
449}
450
452 std::string &connect_url) {
453 assert(IsConnected());
454
456 llvm::Triple &remote_triple = remote_arch.GetTriple();
457
458 uint16_t port = 0;
459 std::string socket_name;
460 bool launch_result = false;
461 if (remote_triple.getVendor() == llvm::Triple::Apple &&
462 remote_triple.getOS() == llvm::Triple::IOS) {
463 // When remote debugging to iOS, we use a USB mux that always talks to
464 // localhost, so we will need the remote debugserver to accept connections
465 // only from localhost, no matter what our current hostname is
466 launch_result =
467 m_gdb_client_up->LaunchGDBServer("127.0.0.1", pid, port, socket_name);
468 } else {
469 // All other hosts should use their actual hostname
470 launch_result =
471 m_gdb_client_up->LaunchGDBServer(nullptr, pid, port, socket_name);
472 }
473
474 if (!launch_result)
475 return false;
476
477 connect_url =
479 (socket_name.empty()) ? nullptr : socket_name.c_str());
480 return true;
481}
482
484 assert(IsConnected());
485 return m_gdb_client_up->KillSpawnedProcess(pid);
486}
487
489 ProcessAttachInfo &attach_info, Debugger &debugger,
490 Target *target, // Can be NULL, if NULL create a new target, else use
491 // existing one
492 Status &error) {
493 lldb::ProcessSP process_sp;
494 if (IsRemote()) {
495 if (IsConnected()) {
496 lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
497 std::string connect_url;
498 if (!LaunchGDBServer(debugserver_pid, connect_url)) {
500 "unable to launch a GDB server on '%s'", GetHostname());
501 } else {
502 if (target == nullptr) {
503 TargetSP new_target_sp;
504
505 error = debugger.GetTargetList().CreateTarget(
506 debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp);
507 target = new_target_sp.get();
508 } else
509 error.Clear();
510
511 if (target && error.Success()) {
512 // The darwin always currently uses the GDB remote debugger plug-in
513 // so even when debugging locally we are debugging remotely!
514 process_sp =
515 target->CreateProcess(attach_info.GetListenerForProcess(debugger),
516 "gdb-remote", nullptr, true);
517 if (process_sp) {
518 error = process_sp->ConnectRemote(connect_url.c_str());
519 if (error.Success()) {
520 ListenerSP listener_sp = attach_info.GetHijackListener();
521 if (listener_sp)
522 process_sp->HijackProcessEvents(listener_sp);
523 process_sp->SetShadowListener(attach_info.GetShadowListener());
524 error = process_sp->Attach(attach_info);
525 }
526
527 if (error.Fail() && debugserver_pid != LLDB_INVALID_PROCESS_ID) {
528 KillSpawnedProcess(debugserver_pid);
529 }
530 }
531 }
532 }
533 } else {
534 error = Status::FromErrorString("not connected to remote gdb server");
535 }
536 }
537 return process_sp;
538}
539
541 uint32_t mode) {
542 if (!IsConnected())
543 return Status::FromErrorStringWithFormat("Not connected.");
544 Status error = m_gdb_client_up->MakeDirectory(file_spec, mode);
546 LLDB_LOGF(log,
547 "PlatformRemoteGDBServer::MakeDirectory(path='%s', mode=%o) "
548 "error = %u (%s)",
549 file_spec.GetPath().c_str(), mode, error.GetError(),
550 error.AsCString());
551 return error;
552}
553
555 uint32_t &file_permissions) {
556 if (!IsConnected())
557 return Status::FromErrorStringWithFormat("Not connected.");
558 Status error =
559 m_gdb_client_up->GetFilePermissions(file_spec, file_permissions);
561 LLDB_LOGF(log,
562 "PlatformRemoteGDBServer::GetFilePermissions(path='%s', "
563 "file_permissions=%o) error = %u (%s)",
564 file_spec.GetPath().c_str(), file_permissions, error.GetError(),
565 error.AsCString());
566 return error;
567}
568
570 uint32_t file_permissions) {
571 if (!IsConnected())
572 return Status::FromErrorStringWithFormat("Not connected.");
573 Status error =
574 m_gdb_client_up->SetFilePermissions(file_spec, file_permissions);
576 LLDB_LOGF(log,
577 "PlatformRemoteGDBServer::SetFilePermissions(path='%s', "
578 "file_permissions=%o) error = %u (%s)",
579 file_spec.GetPath().c_str(), file_permissions, error.GetError(),
580 error.AsCString());
581 return error;
582}
583
585 File::OpenOptions flags,
586 uint32_t mode,
587 Status &error) {
588 if (IsConnected())
589 return m_gdb_client_up->OpenFile(file_spec, flags, mode, error);
590 return LLDB_INVALID_UID;
591}
592
594 if (IsConnected())
595 return m_gdb_client_up->CloseFile(fd, error);
596 error = Status::FromErrorStringWithFormat("Not connected.");
597 return false;
598}
599
602 if (IsConnected())
603 return m_gdb_client_up->GetFileSize(file_spec);
604 return LLDB_INVALID_UID;
605}
606
608 CompletionRequest &request, bool only_dir) {
609 if (IsConnected())
610 m_gdb_client_up->AutoCompleteDiskFileOrDirectory(request, only_dir);
611}
612
614 void *dst, uint64_t dst_len,
615 Status &error) {
616 if (IsConnected())
617 return m_gdb_client_up->ReadFile(fd, offset, dst, dst_len, error);
618 error = Status::FromErrorStringWithFormat("Not connected.");
619 return 0;
620}
621
623 const void *src, uint64_t src_len,
624 Status &error) {
625 if (IsConnected())
626 return m_gdb_client_up->WriteFile(fd, offset, src, src_len, error);
627 error = Status::FromErrorStringWithFormat("Not connected.");
628 return 0;
629}
630
632 const FileSpec &destination,
633 uint32_t uid, uint32_t gid) {
634 return Platform::PutFile(source, destination, uid, gid);
635}
636
638 const FileSpec &src, // The name of the link is in src
639 const FileSpec &dst) // The symlink points to dst
640{
641 if (!IsConnected())
642 return Status::FromErrorStringWithFormat("Not connected.");
643 Status error = m_gdb_client_up->CreateSymlink(src, dst);
645 LLDB_LOGF(log,
646 "PlatformRemoteGDBServer::CreateSymlink(src='%s', dst='%s') "
647 "error = %u (%s)",
648 src.GetPath().c_str(), dst.GetPath().c_str(), error.GetError(),
649 error.AsCString());
650 return error;
651}
652
654 if (!IsConnected())
655 return Status::FromErrorStringWithFormat("Not connected.");
656 Status error = m_gdb_client_up->Unlink(file_spec);
658 LLDB_LOGF(log, "PlatformRemoteGDBServer::Unlink(path='%s') error = %u (%s)",
659 file_spec.GetPath().c_str(), error.GetError(), error.AsCString());
660 return error;
661}
662
664 if (IsConnected())
665 return m_gdb_client_up->GetFileExists(file_spec);
666 return false;
667}
668
670 llvm::StringRef shell, llvm::StringRef command,
671 const FileSpec &
672 working_dir, // Pass empty FileSpec to use the current working directory
673 int *status_ptr, // Pass NULL if you don't want the process exit status
674 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
675 // process to exit
676 std::string
677 *command_output, // Pass NULL if you don't want the command output
678 const Timeout<std::micro> &timeout) {
679 if (!IsConnected())
680 return Status::FromErrorStringWithFormat("Not connected.");
681 return m_gdb_client_up->RunShellCommand(command, working_dir, status_ptr,
682 signo_ptr, command_output, timeout);
683}
684
685llvm::ErrorOr<llvm::MD5::MD5Result>
687 if (!IsConnected())
688 return std::make_error_code(std::errc::not_connected);
689
690 return m_gdb_client_up->CalculateMD5(file_spec);
691}
692
694 m_trap_handlers.push_back(ConstString("_sigtramp"));
695}
696
698 if (!IsConnected())
700
702 return m_remote_signals_sp;
703
704 // If packet not implemented or JSON failed to parse, we'll guess the signal
705 // set based on the remote architecture.
707
709 auto result =
710 m_gdb_client_up->SendPacketAndWaitForResponse("jSignalsInfo", response);
711
712 if (result != decltype(result)::Success ||
713 response.GetResponseType() != response.eResponse)
714 return m_remote_signals_sp;
715
716 auto object_sp = StructuredData::ParseJSON(response.GetStringRef());
717 if (!object_sp || !object_sp->IsValid())
718 return m_remote_signals_sp;
719
720 auto array_sp = object_sp->GetAsArray();
721 if (!array_sp || !array_sp->IsValid())
722 return m_remote_signals_sp;
723
724 auto remote_signals_sp = std::make_shared<lldb_private::GDBRemoteSignals>();
725
726 bool done = array_sp->ForEach(
727 [&remote_signals_sp](StructuredData::Object *object) -> bool {
728 if (!object || !object->IsValid())
729 return false;
730
731 auto dict = object->GetAsDictionary();
732 if (!dict || !dict->IsValid())
733 return false;
734
735 // Signal number and signal name are required.
736 uint64_t signo;
737 if (!dict->GetValueForKeyAsInteger("signo", signo))
738 return false;
739
740 llvm::StringRef name;
741 if (!dict->GetValueForKeyAsString("name", name))
742 return false;
743
744 // We can live without short_name, description, etc.
745 bool suppress{false};
746 auto object_sp = dict->GetValueForKey("suppress");
747 if (object_sp && object_sp->IsValid())
748 suppress = object_sp->GetBooleanValue();
749
750 bool stop{false};
751 object_sp = dict->GetValueForKey("stop");
752 if (object_sp && object_sp->IsValid())
753 stop = object_sp->GetBooleanValue();
754
755 bool notify{false};
756 object_sp = dict->GetValueForKey("notify");
757 if (object_sp && object_sp->IsValid())
758 notify = object_sp->GetBooleanValue();
759
760 std::string description;
761 object_sp = dict->GetValueForKey("description");
762 if (object_sp && object_sp->IsValid())
763 description = std::string(object_sp->GetStringValue());
764
765 llvm::StringRef name_backed, description_backed;
766 {
767 std::lock_guard<std::mutex> guard(g_signal_string_mutex);
768 name_backed =
769 g_signal_string_storage.insert(name).first->getKeyData();
770 if (!description.empty())
771 description_backed =
772 g_signal_string_storage.insert(description).first->getKeyData();
773 }
774
775 remote_signals_sp->AddSignal(signo, name_backed, suppress, stop, notify,
776 description_backed);
777 return true;
778 });
779
780 if (done)
781 m_remote_signals_sp = std::move(remote_signals_sp);
782
783 return m_remote_signals_sp;
784}
785
787 const std::string &platform_scheme, const std::string &platform_hostname,
788 uint16_t port, const char *socket_name) {
789 const char *override_scheme =
790 getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_SCHEME");
791 const char *override_hostname =
792 getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_HOSTNAME");
793 const char *port_offset_c_str =
794 getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_PORT_OFFSET");
795 int port_offset = port_offset_c_str ? ::atoi(port_offset_c_str) : 0;
796
797 return MakeUrl(override_scheme ? override_scheme : platform_scheme.c_str(),
798 override_hostname ? override_hostname
799 : platform_hostname.c_str(),
800 port + port_offset, socket_name);
801}
802
803std::string PlatformRemoteGDBServer::MakeUrl(const char *scheme,
804 const char *hostname,
805 uint16_t port, const char *path) {
806 StreamString result;
807 result.Printf("%s://[%s]", scheme, hostname);
808 if (port != 0)
809 result.Printf(":%u", port);
810 if (path)
811 result.Write(path, strlen(path));
812 return std::string(result.GetString());
813}
814
816 Status &error) {
817 std::vector<std::string> connection_urls;
818 GetPendingGdbServerList(connection_urls);
819
820 for (size_t i = 0; i < connection_urls.size(); ++i) {
821 ConnectProcess(connection_urls[i].c_str(), "gdb-remote", debugger, nullptr, error);
822 if (error.Fail())
823 return i; // We already connected to i process successfully
824 }
825 return connection_urls.size();
826}
827
829 std::vector<std::string> &connection_urls) {
830 std::vector<std::pair<uint16_t, std::string>> remote_servers;
831 if (!IsConnected())
832 return 0;
833 m_gdb_client_up->QueryGDBServer(remote_servers);
834 for (const auto &gdbserver : remote_servers) {
835 const char *socket_name_cstr =
836 gdbserver.second.empty() ? nullptr : gdbserver.second.c_str();
837 connection_urls.emplace_back(
839 gdbserver.first, socket_name_cstr));
840 }
841 return connection_urls.size();
842}
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)
Definition: PluginManager.h:26
ResponseType GetResponseType() const
llvm::StringRef GetStringRef() const
An architecture specification class.
Definition: ArchSpec.h:31
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition: ArchSpec.h:461
bool TripleVendorWasSpecified() const
Definition: ArchSpec.h:364
bool TripleOSWasSpecified() const
Definition: ArchSpec.h:368
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:198
A file utility class.
Definition: FileSpec.h:56
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition: FileSpec.cpp:367
bool Test(ValueType bit) const
Test a single flag bit.
Definition: Flags.h:96
void Dump(Stream &strm) const
Definition: ModuleSpec.h:162
A plug-in interface definition class for debug platform that includes many platform abilities such as...
Definition: Platform.h:76
virtual FileSpec GetRemoteWorkingDirectory()
Definition: Platform.h:237
std::vector< ConstString > m_trap_handlers
Definition: Platform.h:1021
static void Terminate()
Definition: Platform.cpp:138
llvm::VersionTuple m_os_version
Definition: Platform.h:1005
virtual Status PutFile(const FileSpec &source, const FileSpec &destination, uint32_t uid=UINT32_MAX, uint32_t gid=UINT32_MAX)
Definition: Platform.cpp:1120
virtual bool SetRemoteWorkingDirectory(const FileSpec &working_dir)
Definition: Platform.cpp:705
virtual lldb::ProcessSP ConnectProcess(llvm::StringRef connect_url, llvm::StringRef plugin_name, Debugger &debugger, Target *target, Status &error)
Definition: Platform.cpp:1876
static void Initialize()
Definition: Platform.cpp:136
std::string m_hostname
Definition: Platform.h:1004
bool IsRemote() const
Definition: Platform.h:506
virtual const lldb::UnixSignalsSP & GetRemoteUnixSignals()
Definition: Platform.cpp:1794
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:2936
lldb::ListenerSP GetHijackListener() const
Definition: ProcessInfo.h:108
void SetProcessID(lldb::pid_t pid)
Definition: ProcessInfo.h:70
FileSpec & GetExecutableFile()
Definition: ProcessInfo.h:43
lldb::ListenerSP GetListener() const
Definition: ProcessInfo.h:102
lldb::ListenerSP GetShadowListener() const
Definition: ProcessInfo.h:114
Environment & GetEnvironment()
Definition: ProcessInfo.h:88
ArchSpec & GetArchitecture()
Definition: ProcessInfo.h:62
const FileAction * GetFileActionAtIndex(size_t idx) const
const FileSpec & GetWorkingDirectory() const
An error handling class.
Definition: Status.h:115
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition: Status.cpp:106
static Status FromErrorString(const char *str)
Definition: Status.h:138
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition: Status.h:148
const char * GetData() const
Definition: StreamString.h:45
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
ObjectSP GetValueForKey(llvm::StringRef key) const
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.
Definition: TargetList.cpp:45
const lldb::ProcessSP & CreateProcess(lldb::ListenerSP listener_sp, llvm::StringRef plugin_name, const FileSpec *crash_file, bool can_connect)
Definition: Target.cpp:285
static lldb::UnixSignalsSP Create(const ArchSpec &arch)
Definition: UnixSignals.cpp:29
lldb::user_id_t GetFileSize(const FileSpec &file_spec) override
std::unique_ptr< process_gdb_remote::GDBRemoteCommunicationClient > m_gdb_client_up
std::optional< std::string > GetRemoteOSKernelDescription() override
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
Definition: lldb-defines.h:88
#define LLDB_INVALID_PROCESS_ID
Definition: lldb-defines.h:89
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
Definition: SBAddress.h:15
std::shared_ptr< lldb_private::UnixSignals > UnixSignalsSP
Definition: lldb-forward.h:480
std::shared_ptr< lldb_private::Platform > PlatformSP
Definition: lldb-forward.h:388
std::shared_ptr< lldb_private::Process > ProcessSP
Definition: lldb-forward.h:389
uint64_t pid_t
Definition: lldb-types.h:83
std::shared_ptr< lldb_private::Listener > ListenerSP
Definition: lldb-forward.h:368
uint64_t user_id_t
Definition: lldb-types.h:82
std::shared_ptr< lldb_private::Target > TargetSP
Definition: lldb-forward.h:448
Definition: Debugger.h:54
static std::optional< URI > Parse(llvm::StringRef uri)
Definition: UriParser.cpp:28