brintos

brintos / llvm-project-archived public Read only

0
0
Text · 13.6 KiB · 31d277b Raw
391 lines · cpp
1//===-- DynamicLoader.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-exception6//7//===----------------------------------------------------------------------===//8 9#include "lldb/Target/DynamicLoader.h"10 11#include "lldb/Core/Debugger.h"12#include "lldb/Core/Module.h"13#include "lldb/Core/ModuleList.h"14#include "lldb/Core/ModuleSpec.h"15#include "lldb/Core/PluginManager.h"16#include "lldb/Core/Progress.h"17#include "lldb/Core/Section.h"18#include "lldb/Symbol/ObjectFile.h"19#include "lldb/Target/MemoryRegionInfo.h"20#include "lldb/Target/Platform.h"21#include "lldb/Target/Process.h"22#include "lldb/Target/Target.h"23#include "lldb/Utility/ConstString.h"24#include "lldb/Utility/LLDBLog.h"25#include "lldb/Utility/Log.h"26#include "lldb/lldb-private-interfaces.h"27 28#include "llvm/ADT/StringRef.h"29 30#include <memory>31 32#include <cassert>33 34using namespace lldb;35using namespace lldb_private;36 37DynamicLoader *DynamicLoader::FindPlugin(Process *process,38                                         llvm::StringRef plugin_name) {39  DynamicLoaderCreateInstance create_callback = nullptr;40  if (!plugin_name.empty()) {41    create_callback =42        PluginManager::GetDynamicLoaderCreateCallbackForPluginName(plugin_name);43    if (create_callback) {44      std::unique_ptr<DynamicLoader> instance_up(45          create_callback(process, true));46      if (instance_up)47        return instance_up.release();48    }49  } else {50    for (uint32_t idx = 0;51         (create_callback =52              PluginManager::GetDynamicLoaderCreateCallbackAtIndex(idx)) !=53         nullptr;54         ++idx) {55      std::unique_ptr<DynamicLoader> instance_up(56          create_callback(process, false));57      if (instance_up)58        return instance_up.release();59    }60  }61  return nullptr;62}63 64DynamicLoader::DynamicLoader(Process *process) : m_process(process) {}65 66// Accessors to the global setting as to whether to stop at image (shared67// library) loading/unloading.68 69bool DynamicLoader::GetStopWhenImagesChange() const {70  return m_process->GetStopOnSharedLibraryEvents();71}72 73void DynamicLoader::SetStopWhenImagesChange(bool stop) {74  m_process->SetStopOnSharedLibraryEvents(stop);75}76 77ModuleSP DynamicLoader::GetTargetExecutable() {78  Target &target = m_process->GetTarget();79  ModuleSP executable = target.GetExecutableModule();80 81  if (executable) {82    if (FileSystem::Instance().Exists(executable->GetFileSpec())) {83      ModuleSpec module_spec(executable->GetFileSpec(),84                             executable->GetArchitecture());85      auto module_sp = std::make_shared<Module>(module_spec);86      // If we're a coredump and we already have a main executable, we don't87      // need to reload the module list that target already has88      if (!m_process->IsLiveDebugSession()) {89        return executable;90      }91      // Check if the executable has changed and set it to the target92      // executable if they differ.93      if (module_sp && module_sp->GetUUID().IsValid() &&94          executable->GetUUID().IsValid()) {95        if (module_sp->GetUUID() != executable->GetUUID())96          executable.reset();97      } else if (executable->FileHasChanged()) {98        executable.reset();99      }100 101      if (!executable) {102        executable = target.GetOrCreateModule(module_spec, true /* notify */);103        if (executable.get() != target.GetExecutableModulePointer()) {104          // Don't load dependent images since we are in dyld where we will105          // know and find out about all images that are loaded106          target.SetExecutableModule(executable, eLoadDependentsNo);107        }108      }109    }110  }111  return executable;112}113 114void DynamicLoader::UpdateLoadedSections(ModuleSP module, addr_t link_map_addr,115                                         addr_t base_addr,116                                         bool base_addr_is_offset) {117  UpdateLoadedSectionsCommon(module, base_addr, base_addr_is_offset);118}119 120void DynamicLoader::UpdateLoadedSectionsCommon(ModuleSP module,121                                               addr_t base_addr,122                                               bool base_addr_is_offset) {123  bool changed;124  module->SetLoadAddress(m_process->GetTarget(), base_addr, base_addr_is_offset,125                         changed);126}127 128void DynamicLoader::UnloadSections(const ModuleSP module) {129  UnloadSectionsCommon(module);130}131 132void DynamicLoader::UnloadSectionsCommon(const ModuleSP module) {133  Target &target = m_process->GetTarget();134  const SectionList *sections = GetSectionListFromModule(module);135 136  assert(sections && "SectionList missing from unloaded module.");137 138  const size_t num_sections = sections->GetSize();139  for (size_t i = 0; i < num_sections; ++i) {140    SectionSP section_sp(sections->GetSectionAtIndex(i));141    target.SetSectionUnloaded(section_sp);142  }143}144 145const SectionList *146DynamicLoader::GetSectionListFromModule(const ModuleSP module) const {147  SectionList *sections = nullptr;148  if (module) {149    ObjectFile *obj_file = module->GetObjectFile();150    if (obj_file != nullptr) {151      sections = obj_file->GetSectionList();152    }153  }154  return sections;155}156 157ModuleSP DynamicLoader::FindModuleViaTarget(const FileSpec &file) {158  Target &target = m_process->GetTarget();159  ModuleSpec module_spec(file, target.GetArchitecture());160  if (UUID uuid = m_process->FindModuleUUID(file.GetPath())) {161    // Process may be able to augment the module_spec with UUID, e.g. ELF core.162    module_spec.GetUUID() = uuid;163  }164 165  if (ModuleSP module_sp = target.GetImages().FindFirstModule(module_spec))166    return module_sp;167 168  if (ModuleSP module_sp =169          target.GetOrCreateModule(module_spec, /*notify=*/false))170    return module_sp;171 172  return nullptr;173}174 175ModuleSP DynamicLoader::LoadModuleAtAddress(const FileSpec &file,176                                            addr_t link_map_addr,177                                            addr_t base_addr,178                                            bool base_addr_is_offset) {179  if (ModuleSP module_sp = FindModuleViaTarget(file)) {180    UpdateLoadedSections(module_sp, link_map_addr, base_addr,181                         base_addr_is_offset);182    return module_sp;183  }184 185  return nullptr;186}187 188static ModuleSP ReadUnnamedMemoryModule(Process *process, addr_t addr,189                                        llvm::StringRef name) {190  char namebuf[80];191  if (name.empty()) {192    snprintf(namebuf, sizeof(namebuf), "memory-image-0x%" PRIx64, addr);193    name = namebuf;194  }195  return process->ReadModuleFromMemory(FileSpec(name), addr);196}197 198ModuleSP DynamicLoader::LoadBinaryWithUUIDAndAddress(199    Process *process, llvm::StringRef name, UUID uuid, addr_t value,200    bool value_is_offset, bool force_symbol_search, bool notify,201    bool set_address_in_target, bool allow_memory_image_last_resort) {202  ModuleSP memory_module_sp;203  ModuleSP module_sp;204  PlatformSP platform_sp = process->GetTarget().GetPlatform();205  Target &target = process->GetTarget();206  Status error;207 208  StreamString prog_str;209  if (!name.empty()) {210    prog_str << name.str() << " ";211  }212  if (uuid.IsValid())213    prog_str << uuid.GetAsString();214  if (value_is_offset == 0 && value != LLDB_INVALID_ADDRESS) {215    prog_str << " at 0x";216    prog_str.PutHex64(value);217  }218 219  if (!uuid.IsValid() && !value_is_offset) {220    memory_module_sp = ReadUnnamedMemoryModule(process, value, name);221 222    if (memory_module_sp) {223      uuid = memory_module_sp->GetUUID();224      if (uuid.IsValid()) {225        prog_str << " ";226        prog_str << uuid.GetAsString();227      }228    }229  }230  ModuleSpec module_spec;231  module_spec.SetTarget(target.shared_from_this());232  module_spec.GetUUID() = uuid;233  FileSpec name_filespec(name);234  if (FileSystem::Instance().Exists(name_filespec))235    module_spec.GetFileSpec() = name_filespec;236 237  if (uuid.IsValid()) {238    Progress progress("Locating binary", prog_str.GetString().str());239 240    // Has lldb already seen a module with this UUID?241    // Or have external lookup enabled in DebugSymbols on macOS.242    if (!module_sp)243      error =244          ModuleList::GetSharedModule(module_spec, module_sp, nullptr, nullptr);245 246    // Can lldb's symbol/executable location schemes247    // find an executable and symbol file.248    if (!module_sp) {249      FileSpecList search_paths = Target::GetDefaultDebugFileSearchPaths();250      StatisticsMap symbol_locator_map;251      module_spec.GetSymbolFileSpec() =252          PluginManager::LocateExecutableSymbolFile(module_spec, search_paths,253                                                    symbol_locator_map);254      ModuleSpec objfile_module_spec =255          PluginManager::LocateExecutableObjectFile(module_spec,256                                                    symbol_locator_map);257      module_spec.GetFileSpec() = objfile_module_spec.GetFileSpec();258      if (FileSystem::Instance().Exists(module_spec.GetFileSpec()) &&259          FileSystem::Instance().Exists(module_spec.GetSymbolFileSpec())) {260        module_sp = std::make_shared<Module>(module_spec);261      }262 263      if (module_sp) {264        module_sp->GetSymbolLocatorStatistics().merge(symbol_locator_map);265      }266    }267 268    // If we haven't found a binary, or we don't have a SymbolFile, see269    // if there is an external search tool that can find it.270    if (!module_sp || !module_sp->GetSymbolFileFileSpec()) {271      PluginManager::DownloadObjectAndSymbolFile(module_spec, error,272                                                 force_symbol_search);273      if (FileSystem::Instance().Exists(module_spec.GetFileSpec())) {274        module_sp = std::make_shared<Module>(module_spec);275      } else if (force_symbol_search && error.AsCString("") &&276                 error.AsCString("")[0] != '\0') {277        *target.GetDebugger().GetAsyncErrorStream() << error.AsCString();278      }279    }280 281    // If we only found the executable, create a Module based on that.282    if (!module_sp && FileSystem::Instance().Exists(module_spec.GetFileSpec()))283      module_sp = std::make_shared<Module>(module_spec);284  }285 286  // If we couldn't find the binary anywhere else, as a last resort,287  // read it out of memory.288  if (allow_memory_image_last_resort && !module_sp.get() &&289      value != LLDB_INVALID_ADDRESS && !value_is_offset) {290    if (!memory_module_sp)291      memory_module_sp = ReadUnnamedMemoryModule(process, value, name);292    if (memory_module_sp)293      module_sp = memory_module_sp;294  }295 296  Log *log = GetLog(LLDBLog::DynamicLoader);297  if (module_sp.get()) {298    // Ensure the Target has an architecture set in case299    // we need it while processing this binary/eh_frame/debug info.300    if (!target.GetArchitecture().IsValid())301      target.SetArchitecture(module_sp->GetArchitecture());302    target.GetImages().AppendIfNeeded(module_sp, false);303 304    bool changed = false;305    if (set_address_in_target) {306      if (module_sp->GetObjectFile()) {307        if (value != LLDB_INVALID_ADDRESS) {308          LLDB_LOGF(log,309                    "DynamicLoader::LoadBinaryWithUUIDAndAddress Loading "310                    "binary %s UUID %s at %s 0x%" PRIx64,311                    name.str().c_str(), uuid.GetAsString().c_str(),312                    value_is_offset ? "offset" : "address", value);313          module_sp->SetLoadAddress(target, value, value_is_offset, changed);314        } else {315          // No address/offset/slide, load the binary at file address,316          // offset 0.317          LLDB_LOGF(log,318                    "DynamicLoader::LoadBinaryWithUUIDAndAddress Loading "319                    "binary %s UUID %s at file address",320                    name.str().c_str(), uuid.GetAsString().c_str());321          module_sp->SetLoadAddress(target, 0, true /* value_is_slide */,322                                    changed);323        }324      } else {325        // In-memory image, load at its true address, offset 0.326        LLDB_LOGF(log,327                  "DynamicLoader::LoadBinaryWithUUIDAndAddress Loading binary "328                  "%s UUID %s from memory at address 0x%" PRIx64,329                  name.str().c_str(), uuid.GetAsString().c_str(), value);330        module_sp->SetLoadAddress(target, 0, true /* value_is_slide */,331                                  changed);332      }333    }334 335    if (notify) {336      ModuleList added_module;337      added_module.Append(module_sp, false);338      target.ModulesDidLoad(added_module);339    }340  } else {341    if (force_symbol_search) {342      lldb::StreamUP s = target.GetDebugger().GetAsyncErrorStream();343      s->Printf("Unable to find file");344      if (!name.empty())345        s->Printf(" %s", name.str().c_str());346      if (uuid.IsValid())347        s->Printf(" with UUID %s", uuid.GetAsString().c_str());348      if (value != LLDB_INVALID_ADDRESS) {349        if (value_is_offset)350          s->Printf(" with slide 0x%" PRIx64, value);351        else352          s->Printf(" at address 0x%" PRIx64, value);353      }354      s->Printf("\n");355    }356    LLDB_LOGF(log,357              "Unable to find binary %s with UUID %s and load it at "358              "%s 0x%" PRIx64,359              name.str().c_str(), uuid.GetAsString().c_str(),360              value_is_offset ? "offset" : "address", value);361  }362 363  return module_sp;364}365 366int64_t DynamicLoader::ReadUnsignedIntWithSizeInBytes(addr_t addr,367                                                      int size_in_bytes) {368  Status error;369  uint64_t value =370      m_process->ReadUnsignedIntegerFromMemory(addr, size_in_bytes, 0, error);371  if (error.Fail())372    return -1;373  else374    return (int64_t)value;375}376 377addr_t DynamicLoader::ReadPointer(addr_t addr) {378  Status error;379  addr_t value = m_process->ReadPointerFromMemory(addr, error);380  if (error.Fail())381    return LLDB_INVALID_ADDRESS;382  else383    return value;384}385 386void DynamicLoader::LoadOperatingSystemPlugin(bool flush)387{388    if (m_process)389        m_process->LoadOperatingSystemPlugin(flush);390}391