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>
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 if (launch_info.GetPTY().GetPrimaryFileDescriptor() !=
498 process_sp->SetSTDIOPseudoTerminal(launch_info.GetPTY());
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
513 m_trap_handlers.push_back("_sigtramp");
514}
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
556llvm::Expected<std::unique_ptr<UtilityFunction>>
558 // Remember to prepend this with the prefix from
559 // GetLibdlFunctionDeclarations. The returned values are all in
560 // __lldb_dlopen_result for consistency. The wrapper returns a void * but
561 // doesn't use it because UtilityFunctions don't work with void returns at
562 // present.
563 //
564 // Use lazy binding so as to not make dlopen()'s success conditional on
565 // forcing every symbol in the library.
566 //
567 // In general, the debugger should allow programs to load & run with
568 // libraries as far as they can, instead of defaulting to being super-picky
569 // about unavailable symbols.
570 //
571 // The value "1" appears to imply lazy binding (RTLD_LAZY) on both Darwin
572 // and other POSIX OSes.
573 static const char *dlopen_wrapper_code = R"(
574 const int RTLD_LAZY = 1;
575
576 struct __lldb_dlopen_result {
577 void *image_ptr;
578 const char *error_str;
579 };
580
581 extern "C" void *memcpy(void *, const void *, size_t size);
582 extern "C" size_t strlen(const char *);
583
584
585 void * __lldb_dlopen_wrapper (const char *name,
586 const char *path_strings,
587 char *buffer,
588 __lldb_dlopen_result *result_ptr)
589 {
590 // This is the case where the name is the full path:
591 if (!path_strings) {
592 result_ptr->image_ptr = dlopen(name, RTLD_LAZY);
593 if (result_ptr->image_ptr)
594 result_ptr->error_str = nullptr;
595 else
596 result_ptr->error_str = dlerror();
597 return nullptr;
598 }
599
600 // This is the case where we have a list of paths:
601 size_t name_len = strlen(name);
602 while (path_strings && path_strings[0] != '\0') {
603 size_t path_len = strlen(path_strings);
604 memcpy((void *) buffer, (void *) path_strings, path_len);
605 buffer[path_len] = '/';
606 char *target_ptr = buffer+path_len+1;
607 memcpy((void *) target_ptr, (void *) name, name_len + 1);
608 result_ptr->image_ptr = dlopen(buffer, RTLD_LAZY);
609 if (result_ptr->image_ptr) {
610 result_ptr->error_str = nullptr;
611 break;
612 }
613 result_ptr->error_str = dlerror();
614 path_strings = path_strings + path_len + 1;
615 }
616 return nullptr;
617 }
618 )";
619
620 static const char *dlopen_wrapper_name = "__lldb_dlopen_wrapper";
621 Process *process = exe_ctx.GetProcessSP().get();
622 // Insert the dlopen shim defines into our generic expression:
623 std::string expr(std::string(GetLibdlFunctionDeclarations(process)));
624 expr.append(dlopen_wrapper_code);
625 Status utility_error;
626 DiagnosticManager diagnostics;
627
628 auto utility_fn_or_error = process->GetTarget().CreateUtilityFunction(
629 std::move(expr), dlopen_wrapper_name, eLanguageTypeC_plus_plus, exe_ctx);
630 if (!utility_fn_or_error) {
631 std::string error_str = llvm::toString(utility_fn_or_error.takeError());
632 return llvm::createStringError(
633 "dlopen error: could not create utility function: %s",
634 error_str.c_str());
635 }
636 std::unique_ptr<UtilityFunction> dlopen_utility_func_up =
637 std::move(*utility_fn_or_error);
638
639 Value value;
640 ValueList arguments;
641
642 // Fetch the clang types we will need:
643 TypeSystemClangSP scratch_ts_sp =
644 ScratchTypeSystemClang::GetForTarget(process->GetTarget());
645 if (!scratch_ts_sp)
646 return llvm::createStringError("dlopen error: no scratch type system");
647
648 CompilerType clang_void_pointer_type =
649 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
650 CompilerType clang_char_pointer_type =
651 scratch_ts_sp->GetBasicType(eBasicTypeChar).GetPointerType();
652
653 // We are passing four arguments, the basename, the list of places to look,
654 // a buffer big enough for all the path + name combos, and
655 // a pointer to the storage we've made for the result:
657 value.SetCompilerType(clang_void_pointer_type);
658 arguments.PushValue(value);
659 value.SetCompilerType(clang_char_pointer_type);
660 arguments.PushValue(value);
661 arguments.PushValue(value);
662 arguments.PushValue(value);
663
664 dlopen_utility_func_up->MakeFunctionCaller(
665 clang_void_pointer_type, arguments, exe_ctx.GetThreadSP(), utility_error);
666 if (utility_error.Fail())
667 return llvm::createStringError(
668 "dlopen error: could not make function caller: %s",
669 utility_error.AsCString());
670
671 if (!dlopen_utility_func_up->GetFunctionCaller())
672 return llvm::createStringError(
673 "dlopen error: could not get function caller.");
674
675 return dlopen_utility_func_up;
676}
677
679 const lldb_private::FileSpec &remote_file,
680 const std::vector<std::string> *paths,
682 lldb_private::FileSpec *loaded_image) {
683 if (loaded_image)
684 loaded_image->Clear();
685
686 std::string path;
687 path = remote_file.GetPath(false);
688
689 ThreadSP thread_sp = process->GetThreadList().GetExpressionExecutionThread();
690 if (!thread_sp) {
691 error = Status::FromErrorString(
692 "dlopen error: no thread available to call dlopen.");
694 }
695
696 DiagnosticManager diagnostics;
697
698 ExecutionContext exe_ctx;
699 thread_sp->CalculateExecutionContext(exe_ctx);
700
701 Status utility_error;
702 ValueList arguments;
703
704 // The UtilityFunction is held in the Process. Platforms don't track the
705 // lifespan of the Targets that use them, we can't put this in the Platform.
706 llvm::Expected<UtilityFunction &> dlopen_utility_func_or_err =
708 this, [&]() { return MakeLoadImageUtilityFunction(exe_ctx); });
709 if (!dlopen_utility_func_or_err) {
710 error = Status::FromError(dlopen_utility_func_or_err.takeError());
712 }
713
714 FunctionCaller *do_dlopen_function =
715 dlopen_utility_func_or_err->GetFunctionCaller();
716 if (!do_dlopen_function) {
717 error =
718 Status::FromErrorString("dlopen error: could not get function caller.");
720 }
721 arguments = do_dlopen_function->GetArgumentValues();
722
723 // Now insert the path we are searching for and the result structure into the
724 // target.
725 uint32_t permissions = ePermissionsReadable|ePermissionsWritable;
726 size_t path_len = path.size() + 1;
727 lldb::addr_t path_addr = process->AllocateMemory(path_len,
728 permissions,
729 utility_error);
730 if (path_addr == LLDB_INVALID_ADDRESS) {
731 error = Status::FromErrorStringWithFormat(
732 "dlopen error: could not allocate memory for path: %s",
733 utility_error.AsCString());
735 }
736
737 // Make sure we deallocate the input string memory:
738 llvm::scope_exit path_cleanup([process, path_addr] {
739 // Deallocate the buffer.
740 process->DeallocateMemory(path_addr);
741 });
742
743 process->WriteMemory(path_addr, path.c_str(), path_len, utility_error);
744 if (utility_error.Fail()) {
745 error = Status::FromErrorStringWithFormat(
746 "dlopen error: could not write path string: %s",
747 utility_error.AsCString());
749 }
750
751 // Make space for our return structure. It is two pointers big: the token
752 // and the error string.
753 const uint32_t addr_size = process->GetAddressByteSize();
754 lldb::addr_t return_addr = process->CallocateMemory(2*addr_size,
755 permissions,
756 utility_error);
757 if (utility_error.Fail()) {
758 error = Status::FromErrorStringWithFormat(
759 "dlopen error: could not allocate memory for path: %s",
760 utility_error.AsCString());
762 }
763
764 // Make sure we deallocate the result structure memory
765 llvm::scope_exit return_cleanup([process, return_addr] {
766 // Deallocate the buffer
767 process->DeallocateMemory(return_addr);
768 });
769
770 // This will be the address of the storage for paths, if we are using them,
771 // or nullptr to signal we aren't.
772 lldb::addr_t path_array_addr = 0x0;
773 std::optional<llvm::scope_exit<std::function<void()>>> path_array_cleanup;
774
775 // This is the address to a buffer large enough to hold the largest path
776 // conjoined with the library name we're passing in. This is a convenience
777 // to avoid having to call malloc in the dlopen function.
778 lldb::addr_t buffer_addr = 0x0;
779 std::optional<llvm::scope_exit<std::function<void()>>> buffer_cleanup;
780
781 // Set the values into our args and write them to the target:
782 if (paths != nullptr) {
783 // First insert the paths into the target. This is expected to be a
784 // continuous buffer with the strings laid out null-terminated and
785 // end to end with an empty string terminating the buffer.
786 // We also compute the buffer's required size as we go.
787 size_t buffer_size = 0;
788 std::string path_array;
789 for (auto path : *paths) {
790 // Don't insert empty paths, they will make us abort the path
791 // search prematurely.
792 if (path.empty())
793 continue;
794 size_t path_size = path.size();
795 path_array.append(path);
796 path_array.push_back('\0');
797 if (path_size > buffer_size)
798 buffer_size = path_size;
799 }
800 path_array.push_back('\0');
801
802 path_array_addr = process->AllocateMemory(path_array.size(),
803 permissions,
804 utility_error);
805 if (path_array_addr == LLDB_INVALID_ADDRESS) {
806 error = Status::FromErrorStringWithFormat(
807 "dlopen error: could not allocate memory for path array: %s",
808 utility_error.AsCString());
810 }
811
812 // Make sure we deallocate the paths array.
813 path_array_cleanup.emplace([process, path_array_addr]() {
814 // Deallocate the path array.
815 process->DeallocateMemory(path_array_addr);
816 });
817
818 process->WriteMemory(path_array_addr, path_array.data(),
819 path_array.size(), utility_error);
820
821 if (utility_error.Fail()) {
822 error = Status::FromErrorStringWithFormat(
823 "dlopen error: could not write path array: %s",
824 utility_error.AsCString());
826 }
827 // Now make spaces in the target for the buffer. We need to add one for
828 // the '/' that the utility function will insert and one for the '\0':
829 buffer_size += path.size() + 2;
830
831 buffer_addr = process->AllocateMemory(buffer_size,
832 permissions,
833 utility_error);
834 if (buffer_addr == LLDB_INVALID_ADDRESS) {
835 error = Status::FromErrorStringWithFormat(
836 "dlopen error: could not allocate memory for buffer: %s",
837 utility_error.AsCString());
839 }
840
841 // Make sure we deallocate the buffer memory:
842 buffer_cleanup.emplace([process, buffer_addr]() {
843 // Deallocate the buffer.
844 process->DeallocateMemory(buffer_addr);
845 });
846 }
847
848 arguments.GetValueAtIndex(0)->GetScalar() = path_addr;
849 arguments.GetValueAtIndex(1)->GetScalar() = path_array_addr;
850 arguments.GetValueAtIndex(2)->GetScalar() = buffer_addr;
851 arguments.GetValueAtIndex(3)->GetScalar() = return_addr;
852
853 lldb::addr_t func_args_addr = LLDB_INVALID_ADDRESS;
854
855 diagnostics.Clear();
856 if (!do_dlopen_function->WriteFunctionArguments(exe_ctx,
857 func_args_addr,
858 arguments,
859 diagnostics)) {
860 error = Status::FromError(diagnostics.GetAsError(
862 "dlopen error: could not write function arguments:"));
864 }
865
866 // Make sure we clean up the args structure. We can't reuse it because the
867 // Platform lives longer than the process and the Platforms don't get a
868 // signal to clean up cached data when a process goes away.
869 llvm::scope_exit args_cleanup([do_dlopen_function, &exe_ctx, func_args_addr] {
870 do_dlopen_function->DeallocateFunctionResults(exe_ctx, func_args_addr);
871 });
872
873 // Now run the caller:
874 EvaluateExpressionOptions options;
875 options.SetExecutionPolicy(eExecutionPolicyAlways);
876 options.SetLanguage(eLanguageTypeC_plus_plus);
877 options.SetIgnoreBreakpoints(true);
878 options.SetUnwindOnError(true);
879 options.SetTrapExceptions(false); // dlopen can't throw exceptions, so
880 // don't do the work to trap them.
881 options.SetTimeout(process->GetUtilityExpressionTimeout());
882 options.SetIsForUtilityExpr(true);
883
884 Value return_value;
885 // Fetch the clang types we will need:
886 TypeSystemClangSP scratch_ts_sp =
888 if (!scratch_ts_sp) {
889 error =
890 Status::FromErrorString("dlopen error: Unable to get TypeSystemClang");
892 }
893
894 CompilerType clang_void_pointer_type =
895 scratch_ts_sp->GetBasicType(eBasicTypeVoid).GetPointerType();
896
897 return_value.SetCompilerType(clang_void_pointer_type);
898
899 ExpressionResults results = do_dlopen_function->ExecuteFunction(
900 exe_ctx, &func_args_addr, options, diagnostics, return_value);
901 if (results != eExpressionCompleted) {
902 error = Status::FromError(diagnostics.GetAsError(
904 "dlopen error: failed executing dlopen wrapper function:"));
906 }
907
908 // Read the dlopen token from the return area:
909 llvm::Expected<lldb::addr_t> token =
910 process->ReadPointerFromMemory(return_addr);
911 if (!token) {
913 "dlopen error: could not read the return struct: {0}",
914 llvm::fmt_consume(token.takeError()));
916 }
917
918 // The dlopen succeeded!
919 if (*token != 0x0) {
920 if (loaded_image && buffer_addr != 0x0)
921 {
922 // Capture the image which was loaded. We leave it in the buffer on
923 // exit from the dlopen function, so we can just read it from there:
924 std::string name_string;
925 process->ReadCStringFromMemory(buffer_addr, name_string, utility_error);
926 if (utility_error.Success())
927 loaded_image->SetFile(name_string, llvm::sys::path::Style::posix);
928 }
929 return process->AddImageToken(*token);
930 }
931
932 // We got an error, lets read in the error string:
933 std::string dlopen_error_str;
934 llvm::Expected<lldb::addr_t> error_addr =
935 process->ReadPointerFromMemory(return_addr + addr_size);
936 if (!error_addr) {
937 error = Status::FromErrorStringWithFormatv(
938 "dlopen error: could not read error string: {0}",
939 llvm::fmt_consume(error_addr.takeError()));
941 }
942
943 size_t num_chars = process->ReadCStringFromMemory(
944 *error_addr + addr_size, dlopen_error_str, utility_error);
945 if (utility_error.Success() && num_chars > 0)
946 error = Status::FromErrorStringWithFormat("dlopen error: %s",
947 dlopen_error_str.c_str());
948 else
949 error =
950 Status::FromErrorStringWithFormat("dlopen failed for unknown reasons.");
951
953}
954
956 uint32_t image_token) {
957 const addr_t image_addr = process->GetImagePtrFromToken(image_token);
958 if (image_addr == LLDB_INVALID_ADDRESS)
959 return Status::FromErrorString("Invalid image token");
960
961 StreamString expr;
962 expr.Printf("dlclose((void *)0x%" PRIx64 ")", image_addr);
963 llvm::StringRef prefix = GetLibdlFunctionDeclarations(process);
964 lldb::ValueObjectSP result_valobj_sp;
965 Status error = EvaluateLibdlExpression(process, expr.GetData(), prefix,
966 result_valobj_sp);
967 if (error.Fail())
968 return error;
969
970 if (result_valobj_sp->GetError().Fail())
971 return result_valobj_sp->GetError().Clone();
972
973 Scalar scalar;
974 if (result_valobj_sp->ResolveValue(scalar)) {
975 if (scalar.UInt(1))
976 return Status::FromErrorStringWithFormat("expression failed: \"%s\"",
977 expr.GetData());
978 process->ResetImageToken(image_token);
979 }
980 return Status();
981}
982
983llvm::StringRef
985 return R"(
986 extern "C" void* dlopen(const char*, int);
987 extern "C" void* dlsym(void*, const char*);
988 extern "C" int dlclose(void*);
989 extern "C" char* dlerror(void);
990 )";
991}
992
993std::string PlatformPOSIX::GetFullNameForDylib(llvm::StringRef basename) {
994 if (basename.empty())
995 return basename.str();
996
997 return llvm::formatv("lib{0}.so", basename).str();
998}
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...
llvm::Expected< std::unique_ptr< lldb_private::UtilityFunction > > MakeLoadImageUtilityFunction(lldb_private::ExecutionContext &exe_ctx)
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::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 subclass of DataBuffer that stores a data buffer on the heap.
A class to manage flag bits.
Definition Debugger.h:101
TargetList & GetTargetList()
Get accessor for the target list.
Definition Debugger.h:221
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:407
void SetExecutionPolicy(ExecutionPolicy policy=eExecutionPolicyAlways)
Definition Target.h:365
void SetLanguage(lldb::LanguageType language_type)
Definition Target.h:371
void SetTimeout(const Timeout< std::micro > &timeout)
Definition Target.h:428
void SetIgnoreBreakpoints(bool ignore=false)
Definition Target.h:411
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
const lldb::ProcessSP & GetProcessSP() const
Get accessor to get the process 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
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:81
virtual void SetSupportsSSH(bool flag)
Definition Platform.h:707
virtual const char * GetRSyncPrefix()
Definition Platform.h:699
virtual void SetIgnoresRemoteHostname(bool flag)
Definition Platform.h:715
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:693
virtual bool GetSupportsSSH()
Definition Platform.h:705
virtual void SetSSHOpts(const char *opts)
Definition Platform.h:711
virtual const char * GetLocalCacheDirectory()
virtual const char * GetRSyncOpts()
Definition Platform.h:695
virtual void SetLocalCacheDirectory(const char *local)
virtual void SetRSyncOpts(const char *opts)
Definition Platform.h:697
virtual void SetRSyncPrefix(const char *prefix)
Definition Platform.h:701
virtual bool GetIgnoresRemoteHostname()
Definition Platform.h:713
bool IsRemote() const
Definition Platform.h:560
virtual Status GetFile(const FileSpec &source, const FileSpec &destination)
virtual bool GetSupportsRSync()
Definition Platform.h:691
bool IsHost() const
Definition Platform.h:556
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)
std::vector< std::string > m_trap_handlers
Definition Platform.h:1089
virtual const char * GetSSHOpts()
Definition Platform.h:709
virtual llvm::StringRef GetPluginName()=0
lldb::ListenerSP GetListenerForProcess(Debugger &debugger)
Definition Process.cpp:3231
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:380
A plug-in interface definition class for debugging a process.
Definition Process.h:369
void ResetImageToken(size_t token)
Definition Process.cpp:6531
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:2752
ThreadList & GetThreadList()
Definition Process.h:2370
lldb::addr_t AllocateMemory(size_t size, uint32_t permissions, Status &error)
The public interface to allocating memory in the process.
Definition Process.cpp:2737
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:2414
size_t AddImageToken(lldb::addr_t image_ptr)
Definition Process.cpp:6520
llvm::Expected< lldb::addr_t > ReadPointerFromMemory(lldb::addr_t vm_addr)
Definition Process.cpp:2550
Status DeallocateMemory(lldb::addr_t ptr)
The public interface to deallocating memory in the process.
Definition Process.cpp:2782
lldb::addr_t GetImagePtrFromToken(size_t token) const
Definition Process.cpp:6525
uint32_t GetAddressByteSize() const
Definition Process.cpp:3953
size_t WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, Status &error)
Write memory to a process.
Definition Process.cpp:2599
virtual DynamicLoader * GetDynamicLoader()
Get the dynamic loader plug-in for this process.
Definition Process.cpp:3125
llvm::Expected< UtilityFunction & > GetLoadImageUtilityFunction(Platform *platform, llvm::function_ref< llvm::Expected< std::unique_ptr< UtilityFunction > >()> factory)
Get the cached UtilityFunction that assists in loading binary images into the process.
Definition Process.cpp:6759
Target & GetTarget()
Get the target object pointer for this module.
Definition Process.h:1270
@ invalid_fd
Invalid file descriptor value.
int GetPrimaryFileDescriptor() const
The primary file descriptor accessor.
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:1630
const lldb::ProcessSP & CreateProcess(lldb::ListenerSP listener_sp, llvm::StringRef plugin_name, const FileSpec *crash_file, bool can_connect)
Definition Target.cpp:318
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:2892
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...
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