LLDB mainline
PlatformPOSIX.cpp
Go to the documentation of this file.
1//===-- PlatformPOSIX.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 "PlatformPOSIX.h"
10
13#include "lldb/Core/Debugger.h"
14#include "lldb/Core/Module.h"
19#include "lldb/Host/File.h"
22#include "lldb/Host/Host.h"
23#include "lldb/Host/HostInfo.h"
27#include "lldb/Target/Process.h"
28#include "lldb/Target/Thread.h"
32#include "lldb/Utility/Log.h"
35#include "llvm/ADT/ScopeExit.h"
36#include "llvm/Support/Error.h"
37#include "llvm/Support/FormatAdapters.h"
38#include <optional>
39
40using namespace lldb;
41using namespace lldb_private;
42
43/// Default Constructor
49
50/// Destructor.
51///
52/// The destructor is virtual since this class is designed to be
53/// inherited from by the plug-in instance.
55
58 auto iter = m_options.find(&interpreter), end = m_options.end();
59 if (iter == end) {
60 std::unique_ptr<lldb_private::OptionGroupOptions> options(
61 new OptionGroupOptions());
62 options->Append(m_option_group_platform_rsync.get());
63 options->Append(m_option_group_platform_ssh.get());
64 options->Append(m_option_group_platform_caching.get());
65 m_options[&interpreter] = std::move(options);
66 }
67
68 return m_options.at(&interpreter).get();
69}
70
71static uint32_t chown_file(Platform *platform, const char *path,
72 uint32_t uid = UINT32_MAX,
73 uint32_t gid = UINT32_MAX) {
74 if (!platform || !path || *path == 0)
75 return UINT32_MAX;
76
77 if (uid == UINT32_MAX && gid == UINT32_MAX)
78 return 0; // pretend I did chown correctly - actually I just didn't care
79
80 StreamString command;
81 command.PutCString("chown ");
82 if (uid != UINT32_MAX)
83 command.Printf("%d", uid);
84 if (gid != UINT32_MAX)
85 command.Printf(":%d", gid);
86 command.Printf("%s", path);
87 int status;
88 platform->RunShellCommand(command.GetData(), FileSpec(), &status, nullptr,
89 nullptr, nullptr, std::chrono::seconds(10));
90 return status;
91}
92
95 const lldb_private::FileSpec &destination, uint32_t uid,
96 uint32_t gid) {
98
99 if (IsHost()) {
100 if (source == destination)
101 return Status();
102 // cp src dst
103 // chown uid:gid dst
104 std::string src_path(source.GetPath());
105 if (src_path.empty())
106 return Status::FromErrorString("unable to get file path for source");
107 std::string dst_path(destination.GetPath());
108 if (dst_path.empty())
109 return Status::FromErrorString("unable to get file path for destination");
110 StreamString command;
111 command.Printf("cp %s %s", src_path.c_str(), dst_path.c_str());
112 int status;
113 RunShellCommand(command.GetData(), FileSpec(), &status, nullptr, nullptr,
114 nullptr, std::chrono::seconds(10));
115 if (status != 0)
116 return Status::FromErrorString("unable to perform copy");
117 if (uid == UINT32_MAX && gid == UINT32_MAX)
118 return Status();
119 if (chown_file(this, dst_path.c_str(), uid, gid) != 0)
120 return Status::FromErrorString("unable to perform chown");
121 return Status();
122 } else if (m_remote_platform_sp) {
123 if (GetSupportsRSync()) {
124 std::string src_path(source.GetPath());
125 if (src_path.empty())
126 return Status::FromErrorString("unable to get file path for source");
127 std::string dst_path(destination.GetPath());
128 if (dst_path.empty())
130 "unable to get file path for destination");
131 StreamString command;
133 if (!GetRSyncPrefix())
134 command.Printf("rsync %s %s %s", GetRSyncOpts(), src_path.c_str(),
135 dst_path.c_str());
136 else
137 command.Printf("rsync %s %s %s%s", GetRSyncOpts(), src_path.c_str(),
138 GetRSyncPrefix(), dst_path.c_str());
139 } else
140 command.Printf("rsync %s %s %s:%s", GetRSyncOpts(), src_path.c_str(),
141 GetHostname(), dst_path.c_str());
142 LLDB_LOGF(log, "[PutFile] Running command: %s\n", command.GetData());
143 int retcode;
144 Host::RunShellCommand(command.GetData(), FileSpec(), &retcode, nullptr,
145 nullptr, nullptr, std::chrono::minutes(1));
146 if (retcode == 0) {
147 // Don't chown a local file for a remote system
148 // if (chown_file(this,dst_path.c_str(),uid,gid) != 0)
149 // return Status::FromErrorString("unable to perform
150 // chown");
151 return Status();
152 }
153 // if we are still here rsync has failed - let's try the slow way before
154 // giving up
155 }
156 }
157 return Platform::PutFile(source, destination, uid, gid);
158}
159
161 const lldb_private::FileSpec &source, // remote file path
162 const lldb_private::FileSpec &destination) // local file path
163{
165
166 // Check the args, first.
167 std::string src_path(source.GetPath());
168 if (src_path.empty())
169 return Status::FromErrorString("unable to get file path for source");
170 std::string dst_path(destination.GetPath());
171 if (dst_path.empty())
172 return Status::FromErrorString("unable to get file path for destination");
173 if (IsHost()) {
174 if (source == destination)
176 "local scenario->source and destination are the same file "
177 "path: no operation performed");
178 // cp src dst
179 StreamString cp_command;
180 cp_command.Printf("cp %s %s", src_path.c_str(), dst_path.c_str());
181 int status;
182 RunShellCommand(cp_command.GetData(), FileSpec(), &status, nullptr, nullptr,
183 nullptr, std::chrono::seconds(10));
184 if (status != 0)
185 return Status::FromErrorString("unable to perform copy");
186 return Status();
187 } else if (m_remote_platform_sp) {
188 if (GetSupportsRSync()) {
189 StreamString command;
191 if (!GetRSyncPrefix())
192 command.Printf("rsync %s %s %s", GetRSyncOpts(), src_path.c_str(),
193 dst_path.c_str());
194 else
195 command.Printf("rsync %s %s%s %s", GetRSyncOpts(), GetRSyncPrefix(),
196 src_path.c_str(), dst_path.c_str());
197 } else
198 command.Printf("rsync %s %s:%s %s", GetRSyncOpts(),
199 m_remote_platform_sp->GetHostname(), src_path.c_str(),
200 dst_path.c_str());
201 LLDB_LOGF(log, "[GetFile] Running command: %s\n", command.GetData());
202 int retcode;
203 Host::RunShellCommand(command.GetData(), FileSpec(), &retcode, nullptr,
204 nullptr, nullptr, std::chrono::minutes(1));
205 if (retcode == 0)
206 return Status();
207 // If we are here, rsync has failed - let's try the slow way before
208 // giving up
209 }
210 // open src and dst
211 // read/write, read/write, read/write, ...
212 // close src
213 // close dst
214 LLDB_LOGF(log, "[GetFile] Using block by block transfer....\n");
217 lldb::eFilePermissionsFileDefault, error);
218
219 if (fd_src == UINT64_MAX)
220 return Status::FromErrorString("unable to open source file");
221
222 uint32_t permissions = 0;
223 error = GetFilePermissions(source, permissions);
224
225 if (permissions == 0)
226 permissions = lldb::eFilePermissionsFileDefault;
227
228 user_id_t fd_dst = FileCache::GetInstance().OpenFile(
231 permissions, error);
232
233 if (fd_dst == UINT64_MAX) {
234 if (error.Success())
235 error = Status::FromErrorString("unable to open destination file");
236 }
237
238 if (error.Success()) {
239 lldb::WritableDataBufferSP buffer_sp(new DataBufferHeap(1024, 0));
240 uint64_t offset = 0;
241 error.Clear();
242 while (error.Success()) {
243 const uint64_t n_read = ReadFile(fd_src, offset, buffer_sp->GetBytes(),
244 buffer_sp->GetByteSize(), error);
245 if (error.Fail())
246 break;
247 if (n_read == 0)
248 break;
249 if (FileCache::GetInstance().WriteFile(fd_dst, offset,
250 buffer_sp->GetBytes(), n_read,
251 error) != n_read) {
252 if (!error.Fail())
253 error =
254 Status::FromErrorString("unable to write to destination file");
255 break;
256 }
257 offset += n_read;
258 }
259 }
260 if (fd_src != UINT64_MAX) {
261 // Ignore the close error of src.
262 Status close_error;
263 CloseFile(fd_src, close_error);
264 }
265 // And close the dst file descriptor.
266 if (fd_dst != UINT64_MAX &&
268 if (!error.Fail())
269 error = Status::FromErrorString("unable to close destination file");
270 }
271 return error;
272 }
273 return Platform::GetFile(source, destination);
274}
275
277 StreamString stream;
278 if (GetSupportsRSync()) {
279 stream.PutCString("rsync");
280 if ((GetRSyncOpts() && *GetRSyncOpts()) ||
282 stream.Printf(", options: ");
283 if (GetRSyncOpts() && *GetRSyncOpts())
284 stream.Printf("'%s' ", GetRSyncOpts());
285 stream.Printf(", prefix: ");
286 if (GetRSyncPrefix() && *GetRSyncPrefix())
287 stream.Printf("'%s' ", GetRSyncPrefix());
289 stream.Printf("ignore remote-hostname ");
290 }
291 }
292 if (GetSupportsSSH()) {
293 stream.PutCString("ssh");
294 if (GetSSHOpts() && *GetSSHOpts())
295 stream.Printf(", options: '%s' ", GetSSHOpts());
296 }
298 stream.Printf("cache dir: %s", GetLocalCacheDirectory());
299 if (stream.GetSize())
300 return std::string(stream.GetString());
301 else
302 return "";
303}
304
310
313 if (IsHost()) {
315 "can't connect to the host platform '{0}', always connected",
316 GetPluginName());
317 } else {
321 /*force=*/true, nullptr);
322
323 if (m_remote_platform_sp && error.Success())
324 error = m_remote_platform_sp->ConnectRemote(args);
325 else
327 "failed to create a 'remote-gdb-server' platform");
328
329 if (error.Fail())
330 m_remote_platform_sp.reset();
331 }
332
333 if (error.Success() && m_remote_platform_sp) {
337 if (m_option_group_platform_rsync->m_rsync) {
338 SetSupportsRSync(true);
339 SetRSyncOpts(m_option_group_platform_rsync->m_rsync_opts.c_str());
340 SetRSyncPrefix(m_option_group_platform_rsync->m_rsync_prefix.c_str());
342 m_option_group_platform_rsync->m_ignores_remote_hostname);
343 }
344 if (m_option_group_platform_ssh->m_ssh) {
345 SetSupportsSSH(true);
346 SetSSHOpts(m_option_group_platform_ssh->m_ssh_opts.c_str());
347 }
349 m_option_group_platform_caching->m_cache_dir.c_str());
350 }
351 }
352
353 return error;
354}
355
358
359 if (IsHost()) {
361 "can't disconnect from the host platform '{0}', always connected",
362 GetPluginName());
363 } else {
365 error = m_remote_platform_sp->DisconnectRemote();
366 else
367 error =
368 Status::FromErrorString("the platform is not currently connected");
369 }
370 return error;
371}
372
374 Debugger &debugger, Target *target,
375 Status &error) {
376 lldb::ProcessSP process_sp;
378
379 if (IsHost()) {
380 if (target == nullptr) {
381 TargetSP new_target_sp;
382
383 error = debugger.GetTargetList().CreateTarget(
384 debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp);
385 target = new_target_sp.get();
386 LLDB_LOGF(log, "PlatformPOSIX::%s created new target", __FUNCTION__);
387 } else {
388 error.Clear();
389 LLDB_LOGF(log, "PlatformPOSIX::%s target already existed, setting target",
390 __FUNCTION__);
391 }
392
393 if (target && error.Success()) {
394 if (log) {
395 ModuleSP exe_module_sp = target->GetExecutableModule();
396 LLDB_LOGF(log, "PlatformPOSIX::%s set selected target to %p %s",
397 __FUNCTION__, (void *)target,
398 exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str()
399 : "<null>");
400 }
401
402 process_sp =
403 target->CreateProcess(attach_info.GetListenerForProcess(debugger),
404 "gdb-remote", nullptr, true);
405
406 if (process_sp) {
407 ListenerSP listener_sp = attach_info.GetHijackListener();
408 if (listener_sp == nullptr) {
409 listener_sp =
410 Listener::MakeListener("lldb.PlatformPOSIX.attach.hijack");
411 attach_info.SetHijackListener(listener_sp);
412 }
413 process_sp->HijackProcessEvents(listener_sp);
414 process_sp->SetShadowListener(attach_info.GetShadowListener());
415 error = process_sp->Attach(attach_info);
416 }
417 }
418 } else {
420 process_sp =
421 m_remote_platform_sp->Attach(attach_info, debugger, target, error);
422 else
423 error =
424 Status::FromErrorString("the platform is not currently connected");
425 }
426 return process_sp;
427}
428
430 Debugger &debugger, Target &target,
431 Status &error) {
433 LLDB_LOG(log, "target {0}", &target);
434
435 ProcessSP process_sp;
436
437 if (!IsHost()) {
439 process_sp = m_remote_platform_sp->DebugProcess(launch_info, debugger,
440 target, error);
441 else
442 error =
443 Status::FromErrorString("the platform is not currently connected");
444 return process_sp;
445 }
446
447 //
448 // For local debugging, we'll insist on having ProcessGDBRemote create the
449 // process.
450 //
451
452 // Make sure we stop at the entry point
453 launch_info.GetFlags().Set(eLaunchFlagDebug);
454
455 // We always launch the process we are going to debug in a separate process
456 // group, since then we can handle ^C interrupts ourselves w/o having to
457 // worry about the target getting them as well.
458 launch_info.SetLaunchInSeparateProcessGroup(true);
459
460 // Now create the gdb-remote process.
461 LLDB_LOG(log, "having target create process with gdb-remote plugin");
462 process_sp = target.CreateProcess(launch_info.GetListener(), "gdb-remote",
463 nullptr, true);
464
465 if (!process_sp) {
467 "CreateProcess() failed for gdb-remote process");
468 LLDB_LOG(log, "error: {0}", error);
469 return process_sp;
470 }
471
472 LLDB_LOG(log, "successfully created process");
473
474 process_sp->HijackProcessEvents(launch_info.GetHijackListener());
475 process_sp->SetShadowListener(launch_info.GetShadowListener());
476
477 // Log file actions.
478 if (log) {
479 LLDB_LOG(log, "launching process with the following file actions:");
480 StreamString stream;
481 size_t i = 0;
482 const FileAction *file_action;
483 while ((file_action = launch_info.GetFileActionAtIndex(i++)) != nullptr) {
484 file_action->Dump(stream);
485 LLDB_LOG(log, "{0}", stream.GetData());
486 stream.Clear();
487 }
488 }
489
490 // Do the launch.
491 error = process_sp->Launch(launch_info);
492 if (error.Success()) {
493 // Hook up process PTY if we have one (which we should for local debugging
494 // with llgs).
495#ifndef _WIN32 // TODO: Implement on Windows
496 int pty_fd = launch_info.GetPTY().ReleasePrimaryFileDescriptor();
497 if (pty_fd != PseudoTerminal::invalid_fd) {
498 process_sp->SetSTDIOFileDescriptor(pty_fd);
499 LLDB_LOG(log, "hooked up STDIO pty to process");
500 } else
501 LLDB_LOG(log, "not using process STDIO pty");
502#endif
503 } else {
504 LLDB_LOG(log, "{0}", error);
505 // FIXME figure out appropriate cleanup here. Do we delete the process?
506 // Does our caller do that?
507 }
508
509 return process_sp;
510}
511
515
517 lldb_private::Process *process, const char *expr_cstr,
518 llvm::StringRef expr_prefix, lldb::ValueObjectSP &result_valobj_sp) {
519 DynamicLoader *loader = process->GetDynamicLoader();
520 if (loader) {
521 Status error = loader->CanLoadImage();
522 if (error.Fail())
523 return error;
524 }
525
527 if (!thread_sp)
528 return Status::FromErrorString("Selected thread isn't valid");
529
530 StackFrameSP frame_sp(thread_sp->GetStackFrameAtIndex(0));
531 if (!frame_sp)
532 return Status::FromErrorString("Frame 0 isn't valid");
533
534 ExecutionContext exe_ctx;
535 frame_sp->CalculateExecutionContext(exe_ctx);
536 EvaluateExpressionOptions expr_options;
537 expr_options.SetUnwindOnError(true);
538 expr_options.SetIgnoreBreakpoints(true);
541 expr_options.SetTrapExceptions(false); // dlopen can't throw exceptions, so
542 // don't do the work to trap them.
543 expr_options.SetTimeout(process->GetUtilityExpressionTimeout());
544
546 exe_ctx, expr_options, expr_cstr, expr_prefix, result_valobj_sp);
547 if (result != eExpressionCompleted)
548 return result_valobj_sp ? result_valobj_sp->GetError().Clone()
549 : Status("unknown error");
550
551 if (result_valobj_sp->GetError().Fail())
552 return result_valobj_sp->GetError().Clone();
553 return Status();
554}
555
556std::unique_ptr<UtilityFunction>
558 Status &error) {
559 // Remember to prepend this with the prefix from
560 // GetLibdlFunctionDeclarations. The returned values are all in
561 // __lldb_dlopen_result for consistency. The wrapper returns a void * but
562 // doesn't use it because UtilityFunctions don't work with void returns at
563 // present.
564 //
565 // Use lazy binding so as to not make dlopen()'s success conditional on
566 // forcing every symbol in the library.
567 //
568 // In general, the debugger should allow programs to load & run with
569 // libraries as far as they can, instead of defaulting to being super-picky
570 // about unavailable symbols.
571 //
572 // The value "1" appears to imply lazy binding (RTLD_LAZY) on both Darwin
573 // and other POSIX OSes.
574 static const char *dlopen_wrapper_code = R"(
575 const int RTLD_LAZY = 1;
576
577 struct __lldb_dlopen_result {
578 void *image_ptr;
579 const char *error_str;
580 };
581
582 extern "C" void *memcpy(void *, const void *, size_t size);
583 extern "C" size_t strlen(const char *);
584
585
586 void * __lldb_dlopen_wrapper (const char *name,
587 const char *path_strings,
588 char *buffer,
589 __lldb_dlopen_result *result_ptr)
590 {
591 // This is the case where the name is the full path:
592 if (!path_strings) {
593 result_ptr->image_ptr = dlopen(name, RTLD_LAZY);
594 if (result_ptr->image_ptr)
595 result_ptr->error_str = nullptr;
596 else
597 result_ptr->error_str = dlerror();
598 return nullptr;
599 }
600
601 // This is the case where we have a list of paths:
602 size_t name_len = strlen(name);
603 while (path_strings && path_strings[0] != '\0') {
604 size_t path_len = strlen(path_strings);
605 memcpy((void *) buffer, (void *) path_strings, path_len);
606 buffer[path_len] = '/';
607 char *target_ptr = buffer+path_len+1;
608 memcpy((void *) target_ptr, (void *) name, name_len + 1);
609 result_ptr->image_ptr = dlopen(buffer, RTLD_LAZY);
610 if (result_ptr->image_ptr) {
611 result_ptr->error_str = nullptr;
612 break;
613 }
614 result_ptr->error_str = dlerror();
615 path_strings = path_strings + path_len + 1;
616 }
617 return nullptr;
618 }
619 )";
620
621 static const char *dlopen_wrapper_name = "__lldb_dlopen_wrapper";
622 Process *process = exe_ctx.GetProcessSP().get();
623 // Insert the dlopen shim defines into our generic expression:
624 std::string expr(std::string(GetLibdlFunctionDeclarations(process)));
625 expr.append(dlopen_wrapper_code);
626 Status utility_error;
627 DiagnosticManager diagnostics;
628
629 auto utility_fn_or_error = process->GetTarget().CreateUtilityFunction(
630 std::move(expr), dlopen_wrapper_name, eLanguageTypeC_plus_plus, exe_ctx);
631 if (!utility_fn_or_error) {
632 std::string error_str = llvm::toString(utility_fn_or_error.takeError());
634 "dlopen error: could not create utility function: %s",
635 error_str.c_str());
636 return nullptr;
637 }
638 std::unique_ptr<UtilityFunction> dlopen_utility_func_up =
639 std::move(*utility_fn_or_error);
640
641 Value value;
642 ValueList arguments;
643 FunctionCaller *do_dlopen_function = nullptr;
644
645 // Fetch the clang types we will need:
646 TypeSystemClangSP scratch_ts_sp =
648 if (!scratch_ts_sp)
649 return nullptr;
650
651 CompilerType clang_void_pointer_type =
652 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
653 CompilerType clang_char_pointer_type =
654 scratch_ts_sp->GetBasicType(eBasicTypeChar).GetPointerType();
655
656 // We are passing four arguments, the basename, the list of places to look,
657 // a buffer big enough for all the path + name combos, and
658 // a pointer to the storage we've made for the result:
660 value.SetCompilerType(clang_void_pointer_type);
661 arguments.PushValue(value);
662 value.SetCompilerType(clang_char_pointer_type);
663 arguments.PushValue(value);
664 arguments.PushValue(value);
665 arguments.PushValue(value);
666
667 do_dlopen_function = dlopen_utility_func_up->MakeFunctionCaller(
668 clang_void_pointer_type, arguments, exe_ctx.GetThreadSP(), utility_error);
669 if (utility_error.Fail()) {
671 "dlopen error: could not make function caller: %s",
672 utility_error.AsCString());
673 return nullptr;
674 }
675
676 do_dlopen_function = dlopen_utility_func_up->GetFunctionCaller();
677 if (!do_dlopen_function) {
678 error =
679 Status::FromErrorString("dlopen error: could not get function caller.");
680 return nullptr;
681 }
682
683 // We made a good utility function, so cache it in the process:
684 return dlopen_utility_func_up;
685}
686
688 const lldb_private::FileSpec &remote_file,
689 const std::vector<std::string> *paths,
691 lldb_private::FileSpec *loaded_image) {
692 if (loaded_image)
693 loaded_image->Clear();
694
695 std::string path;
696 path = remote_file.GetPath(false);
697
698 ThreadSP thread_sp = process->GetThreadList().GetExpressionExecutionThread();
699 if (!thread_sp) {
700 error = Status::FromErrorString(
701 "dlopen error: no thread available to call dlopen.");
703 }
704
705 DiagnosticManager diagnostics;
706
707 ExecutionContext exe_ctx;
708 thread_sp->CalculateExecutionContext(exe_ctx);
709
710 Status utility_error;
711 UtilityFunction *dlopen_utility_func;
712 ValueList arguments;
713 FunctionCaller *do_dlopen_function = nullptr;
714
715 // The UtilityFunction is held in the Process. Platforms don't track the
716 // lifespan of the Targets that use them, we can't put this in the Platform.
717 dlopen_utility_func = process->GetLoadImageUtilityFunction(
718 this, [&]() -> std::unique_ptr<UtilityFunction> {
719 return MakeLoadImageUtilityFunction(exe_ctx, error);
720 });
721 // If we couldn't make it, the error will be in error, so we can exit here.
722 if (!dlopen_utility_func)
724
725 do_dlopen_function = dlopen_utility_func->GetFunctionCaller();
726 if (!do_dlopen_function) {
727 error =
728 Status::FromErrorString("dlopen error: could not get function caller.");
730 }
731 arguments = do_dlopen_function->GetArgumentValues();
732
733 // Now insert the path we are searching for and the result structure into the
734 // target.
735 uint32_t permissions = ePermissionsReadable|ePermissionsWritable;
736 size_t path_len = path.size() + 1;
737 lldb::addr_t path_addr = process->AllocateMemory(path_len,
738 permissions,
739 utility_error);
740 if (path_addr == LLDB_INVALID_ADDRESS) {
741 error = Status::FromErrorStringWithFormat(
742 "dlopen error: could not allocate memory for path: %s",
743 utility_error.AsCString());
745 }
746
747 // Make sure we deallocate the input string memory:
748 llvm::scope_exit path_cleanup([process, path_addr] {
749 // Deallocate the buffer.
750 process->DeallocateMemory(path_addr);
751 });
752
753 process->WriteMemory(path_addr, path.c_str(), path_len, utility_error);
754 if (utility_error.Fail()) {
755 error = Status::FromErrorStringWithFormat(
756 "dlopen error: could not write path string: %s",
757 utility_error.AsCString());
759 }
760
761 // Make space for our return structure. It is two pointers big: the token
762 // and the error string.
763 const uint32_t addr_size = process->GetAddressByteSize();
764 lldb::addr_t return_addr = process->CallocateMemory(2*addr_size,
765 permissions,
766 utility_error);
767 if (utility_error.Fail()) {
768 error = Status::FromErrorStringWithFormat(
769 "dlopen error: could not allocate memory for path: %s",
770 utility_error.AsCString());
772 }
773
774 // Make sure we deallocate the result structure memory
775 llvm::scope_exit return_cleanup([process, return_addr] {
776 // Deallocate the buffer
777 process->DeallocateMemory(return_addr);
778 });
779
780 // This will be the address of the storage for paths, if we are using them,
781 // or nullptr to signal we aren't.
782 lldb::addr_t path_array_addr = 0x0;
783 std::optional<llvm::scope_exit<std::function<void()>>> path_array_cleanup;
784
785 // This is the address to a buffer large enough to hold the largest path
786 // conjoined with the library name we're passing in. This is a convenience
787 // to avoid having to call malloc in the dlopen function.
788 lldb::addr_t buffer_addr = 0x0;
789 std::optional<llvm::scope_exit<std::function<void()>>> buffer_cleanup;
790
791 // Set the values into our args and write them to the target:
792 if (paths != nullptr) {
793 // First insert the paths into the target. This is expected to be a
794 // continuous buffer with the strings laid out null terminated and
795 // end to end with an empty string terminating the buffer.
796 // We also compute the buffer's required size as we go.
797 size_t buffer_size = 0;
798 std::string path_array;
799 for (auto path : *paths) {
800 // Don't insert empty paths, they will make us abort the path
801 // search prematurely.
802 if (path.empty())
803 continue;
804 size_t path_size = path.size();
805 path_array.append(path);
806 path_array.push_back('\0');
807 if (path_size > buffer_size)
808 buffer_size = path_size;
809 }
810 path_array.push_back('\0');
811
812 path_array_addr = process->AllocateMemory(path_array.size(),
813 permissions,
814 utility_error);
815 if (path_array_addr == LLDB_INVALID_ADDRESS) {
816 error = Status::FromErrorStringWithFormat(
817 "dlopen error: could not allocate memory for path array: %s",
818 utility_error.AsCString());
820 }
821
822 // Make sure we deallocate the paths array.
823 path_array_cleanup.emplace([process, path_array_addr]() {
824 // Deallocate the path array.
825 process->DeallocateMemory(path_array_addr);
826 });
827
828 process->WriteMemory(path_array_addr, path_array.data(),
829 path_array.size(), utility_error);
830
831 if (utility_error.Fail()) {
832 error = Status::FromErrorStringWithFormat(
833 "dlopen error: could not write path array: %s",
834 utility_error.AsCString());
836 }
837 // Now make spaces in the target for the buffer. We need to add one for
838 // the '/' that the utility function will insert and one for the '\0':
839 buffer_size += path.size() + 2;
840
841 buffer_addr = process->AllocateMemory(buffer_size,
842 permissions,
843 utility_error);
844 if (buffer_addr == LLDB_INVALID_ADDRESS) {
845 error = Status::FromErrorStringWithFormat(
846 "dlopen error: could not allocate memory for buffer: %s",
847 utility_error.AsCString());
849 }
850
851 // Make sure we deallocate the buffer memory:
852 buffer_cleanup.emplace([process, buffer_addr]() {
853 // Deallocate the buffer.
854 process->DeallocateMemory(buffer_addr);
855 });
856 }
857
858 arguments.GetValueAtIndex(0)->GetScalar() = path_addr;
859 arguments.GetValueAtIndex(1)->GetScalar() = path_array_addr;
860 arguments.GetValueAtIndex(2)->GetScalar() = buffer_addr;
861 arguments.GetValueAtIndex(3)->GetScalar() = return_addr;
862
863 lldb::addr_t func_args_addr = LLDB_INVALID_ADDRESS;
864
865 diagnostics.Clear();
866 if (!do_dlopen_function->WriteFunctionArguments(exe_ctx,
867 func_args_addr,
868 arguments,
869 diagnostics)) {
870 error = Status::FromError(diagnostics.GetAsError(
872 "dlopen error: could not write function arguments:"));
874 }
875
876 // Make sure we clean up the args structure. We can't reuse it because the
877 // Platform lives longer than the process and the Platforms don't get a
878 // signal to clean up cached data when a process goes away.
879 llvm::scope_exit args_cleanup([do_dlopen_function, &exe_ctx, func_args_addr] {
880 do_dlopen_function->DeallocateFunctionResults(exe_ctx, func_args_addr);
881 });
882
883 // Now run the caller:
884 EvaluateExpressionOptions options;
885 options.SetExecutionPolicy(eExecutionPolicyAlways);
886 options.SetLanguage(eLanguageTypeC_plus_plus);
887 options.SetIgnoreBreakpoints(true);
888 options.SetUnwindOnError(true);
889 options.SetTrapExceptions(false); // dlopen can't throw exceptions, so
890 // don't do the work to trap them.
891 options.SetTimeout(process->GetUtilityExpressionTimeout());
892 options.SetIsForUtilityExpr(true);
893
894 Value return_value;
895 // Fetch the clang types we will need:
896 TypeSystemClangSP scratch_ts_sp =
898 if (!scratch_ts_sp) {
899 error =
900 Status::FromErrorString("dlopen error: Unable to get TypeSystemClang");
902 }
903
904 CompilerType clang_void_pointer_type =
905 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
906
907 return_value.SetCompilerType(clang_void_pointer_type);
908
909 ExpressionResults results = do_dlopen_function->ExecuteFunction(
910 exe_ctx, &func_args_addr, options, diagnostics, return_value);
911 if (results != eExpressionCompleted) {
912 error = Status::FromError(diagnostics.GetAsError(
914 "dlopen error: failed executing dlopen wrapper function:"));
916 }
917
918 // Read the dlopen token from the return area:
919 llvm::Expected<lldb::addr_t> token =
920 process->ReadPointerFromMemory(return_addr);
921 if (!token) {
923 "dlopen error: could not read the return struct: {0}",
924 llvm::fmt_consume(token.takeError()));
926 }
927
928 // The dlopen succeeded!
929 if (*token != 0x0) {
930 if (loaded_image && buffer_addr != 0x0)
931 {
932 // Capture the image which was loaded. We leave it in the buffer on
933 // exit from the dlopen function, so we can just read it from there:
934 std::string name_string;
935 process->ReadCStringFromMemory(buffer_addr, name_string, utility_error);
936 if (utility_error.Success())
937 loaded_image->SetFile(name_string, llvm::sys::path::Style::posix);
938 }
939 return process->AddImageToken(*token);
940 }
941
942 // We got an error, lets read in the error string:
943 std::string dlopen_error_str;
944 llvm::Expected<lldb::addr_t> error_addr =
945 process->ReadPointerFromMemory(return_addr + addr_size);
946 if (!error_addr) {
947 error = Status::FromErrorStringWithFormatv(
948 "dlopen error: could not read error string: {0}",
949 llvm::fmt_consume(error_addr.takeError()));
951 }
952
953 size_t num_chars = process->ReadCStringFromMemory(
954 *error_addr + addr_size, dlopen_error_str, utility_error);
955 if (utility_error.Success() && num_chars > 0)
956 error = Status::FromErrorStringWithFormat("dlopen error: %s",
957 dlopen_error_str.c_str());
958 else
959 error =
960 Status::FromErrorStringWithFormat("dlopen failed for unknown reasons.");
961
963}
964
966 uint32_t image_token) {
967 const addr_t image_addr = process->GetImagePtrFromToken(image_token);
968 if (image_addr == LLDB_INVALID_ADDRESS)
969 return Status::FromErrorString("Invalid image token");
970
971 StreamString expr;
972 expr.Printf("dlclose((void *)0x%" PRIx64 ")", image_addr);
973 llvm::StringRef prefix = GetLibdlFunctionDeclarations(process);
974 lldb::ValueObjectSP result_valobj_sp;
975 Status error = EvaluateLibdlExpression(process, expr.GetData(), prefix,
976 result_valobj_sp);
977 if (error.Fail())
978 return error;
979
980 if (result_valobj_sp->GetError().Fail())
981 return result_valobj_sp->GetError().Clone();
982
983 Scalar scalar;
984 if (result_valobj_sp->ResolveValue(scalar)) {
985 if (scalar.UInt(1))
986 return Status::FromErrorStringWithFormat("expression failed: \"%s\"",
987 expr.GetData());
988 process->ResetImageToken(image_token);
989 }
990 return Status();
991}
992
993llvm::StringRef
995 return R"(
996 extern "C" void* dlopen(const char*, int);
997 extern "C" void* dlsym(void*, const char*);
998 extern "C" int dlclose(void*);
999 extern "C" char* dlerror(void);
1000 )";
1001}
1002
1003std::string PlatformPOSIX::GetFullNameForDylib(llvm::StringRef basename) {
1004 if (basename.empty())
1005 return basename.str();
1006
1007 return llvm::formatv("lib{0}.so", basename).str();
1008}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOGF(log,...)
Definition Log.h:389
static uint32_t chown_file(Platform *platform, const char *path, uint32_t uid=UINT32_MAX, uint32_t gid=UINT32_MAX)
lldb::ProcessSP Attach(lldb_private::ProcessAttachInfo &attach_info, lldb_private::Debugger &debugger, lldb_private::Target *target, lldb_private::Status &error) override
Attach to an existing process using a process ID.
std::map< lldb_private::CommandInterpreter *, std::unique_ptr< lldb_private::OptionGroupOptions > > m_options
lldb::ProcessSP DebugProcess(lldb_private::ProcessLaunchInfo &launch_info, lldb_private::Debugger &debugger, lldb_private::Target &target, lldb_private::Status &error) override
Subclasses do not need to implement this function as it uses the Platform::LaunchProcess() followed b...
lldb_private::Status GetFile(const lldb_private::FileSpec &source, const lldb_private::FileSpec &destination) override
std::string GetFullNameForDylib(llvm::StringRef basename) override
PlatformPOSIX(bool is_host)
Default Constructor.
lldb_private::Status ConnectRemote(lldb_private::Args &args) override
lldb_private::Status DisconnectRemote() override
lldb_private::Status UnloadImage(lldb_private::Process *process, uint32_t image_token) override
lldb_private::Status EvaluateLibdlExpression(lldb_private::Process *process, const char *expr_cstr, llvm::StringRef expr_prefix, lldb::ValueObjectSP &result_valobj_sp)
lldb_private::Status PutFile(const lldb_private::FileSpec &source, const lldb_private::FileSpec &destination, uint32_t uid=UINT32_MAX, uint32_t gid=UINT32_MAX) override
std::unique_ptr< lldb_private::UtilityFunction > MakeLoadImageUtilityFunction(lldb_private::ExecutionContext &exe_ctx, lldb_private::Status &error)
std::unique_ptr< lldb_private::OptionGroupPlatformRSync > m_option_group_platform_rsync
~PlatformPOSIX() override
Destructor.
lldb_private::OptionGroupOptions * GetConnectionOptions(lldb_private::CommandInterpreter &interpreter) override
std::unique_ptr< lldb_private::OptionGroupPlatformCaching > m_option_group_platform_caching
std::string GetPlatformSpecificConnectionInformation() override
const lldb::UnixSignalsSP & GetRemoteUnixSignals() override
std::unique_ptr< lldb_private::OptionGroupPlatformSSH > m_option_group_platform_ssh
void CalculateTrapHandlerSymbolNames() override
Ask the Platform subclass to fill in the list of trap handler names.
virtual llvm::StringRef GetLibdlFunctionDeclarations(lldb_private::Process *process)
uint32_t DoLoadImage(lldb_private::Process *process, const lldb_private::FileSpec &remote_file, const std::vector< std::string > *paths, lldb_private::Status &error, lldb_private::FileSpec *loaded_image) override
A command line argument class.
Definition Args.h:33
Generic representation of a type in a programming language.
A uniqued constant string class.
Definition ConstString.h:40
A subclass of DataBuffer that stores a data buffer on the heap.
A class to manage flag bits.
Definition Debugger.h:100
TargetList & GetTargetList()
Get accessor for the target list.
Definition Debugger.h:220
llvm::Error GetAsError(lldb::ExpressionResults result, llvm::Twine message={}) const
Returns an ExpressionError with arg as error code.
A plug-in interface definition class for dynamic loaders.
virtual Status CanLoadImage()=0
Ask if it is ok to try and load or unload an shared library (image).
void SetUnwindOnError(bool unwind=false)
Definition Target.h:402
void SetExecutionPolicy(ExecutionPolicy policy=eExecutionPolicyAlways)
Definition Target.h:360
void SetLanguage(lldb::LanguageType language_type)
Definition Target.h:366
void SetTimeout(const Timeout< std::micro > &timeout)
Definition Target.h:423
void SetIgnoreBreakpoints(bool ignore=false)
Definition Target.h:406
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
const lldb::ProcessSP & GetProcessSP() const
Get accessor to get the process shared pointer.
const lldb::ThreadSP & GetThreadSP() const
Get accessor to get the thread shared pointer.
Represents a file descriptor action to be performed during process launch.
Definition FileAction.h:21
void Dump(Stream &stream) const
static FileCache & GetInstance()
Definition FileCache.cpp:19
A file utility class.
Definition FileSpec.h:56
void SetFile(llvm::StringRef path, Style style)
Change the file specified with a new path.
Definition FileSpec.cpp:174
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
void Clear()
Clears the object state.
Definition FileSpec.cpp:265
ValueType Set(ValueType mask)
Set one or more flags by logical OR'ing mask with the current flags.
Definition Flags.h:73
Encapsulates a function that can be called.
ValueList GetArgumentValues() const
void DeallocateFunctionResults(ExecutionContext &exe_ctx, lldb::addr_t args_addr)
Deallocate the arguments structure.
lldb::ExpressionResults ExecuteFunction(ExecutionContext &exe_ctx, lldb::addr_t *args_addr_ptr, const EvaluateExpressionOptions &options, DiagnosticManager &diagnostic_manager, Value &results)
Run the function this FunctionCaller was created with.
bool WriteFunctionArguments(ExecutionContext &exe_ctx, lldb::addr_t &args_addr_ref, DiagnosticManager &diagnostic_manager)
Insert the default function argument struct.
static Status RunShellCommand(llvm::StringRef command, const FileSpec &working_dir, int *status_ptr, int *signo_ptr, std::string *command_output, std::string *error_output, const Timeout< std::micro > &timeout, bool run_in_shell=true)
Run a shell command.
static lldb::ListenerSP MakeListener(llvm::StringRef name)
Definition Listener.cpp:373
A plug-in interface definition class for debug platform that includes many platform abilities such as...
Definition Platform.h:79
virtual void SetSupportsSSH(bool flag)
Definition Platform.h:722
std::vector< ConstString > m_trap_handlers
Definition Platform.h:1105
virtual const char * GetRSyncPrefix()
Definition Platform.h:714
virtual void SetIgnoresRemoteHostname(bool flag)
Definition Platform.h:730
virtual Status PutFile(const FileSpec &source, const FileSpec &destination, uint32_t uid=UINT32_MAX, uint32_t gid=UINT32_MAX)
virtual void SetSupportsRSync(bool flag)
Definition Platform.h:708
virtual bool GetSupportsSSH()
Definition Platform.h:720
virtual void SetSSHOpts(const char *opts)
Definition Platform.h:726
virtual const char * GetLocalCacheDirectory()
virtual const char * GetRSyncOpts()
Definition Platform.h:710
virtual void SetLocalCacheDirectory(const char *local)
virtual void SetRSyncOpts(const char *opts)
Definition Platform.h:712
virtual void SetRSyncPrefix(const char *prefix)
Definition Platform.h:716
virtual bool GetIgnoresRemoteHostname()
Definition Platform.h:728
bool IsRemote() const
Definition Platform.h:575
virtual Status GetFile(const FileSpec &source, const FileSpec &destination)
virtual bool GetSupportsRSync()
Definition Platform.h:706
bool IsHost() const
Definition Platform.h:571
virtual const lldb::UnixSignalsSP & GetRemoteUnixSignals()
virtual lldb_private::Status RunShellCommand(llvm::StringRef command, const FileSpec &working_dir, int *status_ptr, int *signo_ptr, std::string *command_output, std::string *separated_error_output, const Timeout< std::micro > &timeout)
virtual const char * GetSSHOpts()
Definition Platform.h:724
virtual llvm::StringRef GetPluginName()=0
lldb::ListenerSP GetListenerForProcess(Debugger &debugger)
Definition Process.cpp:3260
void SetHijackListener(const lldb::ListenerSP &listener_sp)
lldb::ListenerSP GetHijackListener() const
lldb::ListenerSP GetListener() const
lldb::ListenerSP GetShadowListener() const
const FileAction * GetFileActionAtIndex(size_t idx) const
void SetLaunchInSeparateProcessGroup(bool separate)
std::chrono::seconds GetUtilityExpressionTimeout() const
Definition Process.cpp:361
A plug-in interface definition class for debugging a process.
Definition Process.h:367
UtilityFunction * GetLoadImageUtilityFunction(Platform *platform, llvm::function_ref< std::unique_ptr< UtilityFunction >()> factory)
Get the cached UtilityFunction that assists in loading binary images into the process.
Definition Process.cpp:6704
void ResetImageToken(size_t token)
Definition Process.cpp:6476
lldb::addr_t CallocateMemory(size_t size, uint32_t permissions, Status &error)
The public interface to allocating memory in the process, this also clears the allocated memory.
Definition Process.cpp:2763
ThreadList & GetThreadList()
Definition Process.h:2408
lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Status &error)
The public interface to allocating memory in the process.
Definition Process.cpp:2748
size_t ReadCStringFromMemory(lldb::addr_t vm_addr, char *cstr, size_t cstr_max_len, Status &error)
Read a NULL terminated C string from memory.
Definition Process.cpp:2381
size_t AddImageToken(lldb::addr_t image_ptr)
Definition Process.cpp:6465
llvm::Expected< lldb::addr_t > ReadPointerFromMemory(lldb::addr_t vm_addr)
Definition Process.cpp:2561
Status DeallocateMemory(lldb::addr_t ptr)
The public interface to deallocating memory in the process.
Definition Process.cpp:2811
lldb::addr_t GetImagePtrFromToken(size_t token) const
Definition Process.cpp:6470
uint32_t GetAddressByteSize() const
Definition Process.cpp:3977
size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, Status &error)
Write memory to a process.
Definition Process.cpp:2610
virtual DynamicLoader * GetDynamicLoader()
Get the dynamic loader plug-in for this process.
Definition Process.cpp:3154
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1266
@ invalid_fd
Invalid file descriptor value.
int ReleasePrimaryFileDescriptor()
Release the primary file descriptor.
A base class for platforms which automatically want to be able to forward operations to a remote plat...
uint64_t WriteFile(lldb::user_id_t fd, uint64_t offset, const void *src, uint64_t src_len, Status &error) override
uint64_t ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst, uint64_t dst_len, Status &error) override
bool CloseFile(lldb::user_id_t fd, Status &error) override
lldb::user_id_t OpenFile(const FileSpec &file_spec, File::OpenOptions flags, uint32_t mode, Status &error) override
Status RunShellCommand(llvm::StringRef command, const FileSpec &working_dir, int *status_ptr, int *signo_ptr, std::string *command_output, std::string *separated_error_output, const Timeout< std::micro > &timeout) override
Status GetFilePermissions(const FileSpec &file_spec, uint32_t &file_permissions) override
unsigned int UInt(unsigned int fail_value=0) const
Definition Scalar.cpp:352
static lldb::TypeSystemClangSP GetForTarget(Target &target, std::optional< IsolatedASTKind > ast_kind=DefaultAST, bool create_on_demand=true)
Returns the scratch TypeSystemClang for the given target.
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
bool Fail() const
Test for error condition.
Definition Status.cpp:293
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition Status.cpp:194
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
bool Success() const
Test for success condition.
Definition Status.cpp:303
const char * GetData() const
llvm::StringRef GetString() const
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
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.
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
Definition Target.cpp:1625
const lldb::ProcessSP & CreateProcess(lldb::ListenerSP listener_sp, llvm::StringRef plugin_name, const FileSpec *crash_file, bool can_connect)
Definition Target.cpp:317
llvm::Expected< std::unique_ptr< UtilityFunction > > CreateUtilityFunction(std::string expression, std::string name, lldb::LanguageType language, ExecutionContext &exe_ctx)
Creates and installs a UtilityFunction for the given language.
Definition Target.cpp:2870
lldb::ThreadSP GetExpressionExecutionThread()
static lldb::ExpressionResults Evaluate(ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options, llvm::StringRef expr_cstr, llvm::StringRef expr_prefix, lldb::ValueObjectSP &result_valobj_sp, std::string *fixed_expression=nullptr, ValueObject *ctx_obj=nullptr)
Evaluate one expression in the scratch context of the target passed in the exe_ctx and return its res...
FunctionCaller * GetFunctionCaller()
void PushValue(const Value &value)
Definition Value.cpp:698
Value * GetValueAtIndex(size_t idx)
Definition Value.cpp:702
const Scalar & GetScalar() const
See comment on m_scalar to understand what GetScalar returns.
Definition Value.h:114
@ Scalar
A raw scalar value.
Definition Value.h:46
void SetCompilerType(const CompilerType &compiler_type)
Definition Value.cpp:276
void SetValueType(ValueType value_type)
Definition Value.h:90
static lldb::PlatformSP CreateInstance(bool force, const ArchSpec *arch)
#define UINT64_MAX
#define LLDB_INVALID_IMAGE_TOKEN
#define LLDB_INVALID_ADDRESS
#define UINT32_MAX
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:338
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
std::shared_ptr< lldb_private::UnixSignals > UnixSignalsSP
@ eLanguageTypeC_plus_plus
ISO C++:1998.
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
@ eExpressionSetupError
std::shared_ptr< lldb_private::Process > ProcessSP
std::shared_ptr< lldb_private::Listener > ListenerSP
std::shared_ptr< lldb_private::TypeSystemClang > TypeSystemClangSP
uint64_t user_id_t
Definition lldb-types.h:83
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::Module > ModuleSP