Path: blob/main/contrib/llvm-project/lldb/source/Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.cpp
39644 views
//===-- ObjectContainerBSDArchive.cpp -------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "ObjectContainerBSDArchive.h"910#if defined(_WIN32) || defined(__ANDROID__)11// Defines from ar, missing on Windows12#define SARMAG 813#define ARFMAG "`\n"1415typedef struct ar_hdr {16char ar_name[16];17char ar_date[12];18char ar_uid[6], ar_gid[6];19char ar_mode[8];20char ar_size[10];21char ar_fmag[2];22} ar_hdr;23#else24#include <ar.h>25#endif2627#include "lldb/Core/Module.h"28#include "lldb/Core/ModuleSpec.h"29#include "lldb/Core/PluginManager.h"30#include "lldb/Host/FileSystem.h"31#include "lldb/Symbol/ObjectFile.h"32#include "lldb/Utility/ArchSpec.h"33#include "lldb/Utility/LLDBLog.h"34#include "lldb/Utility/Stream.h"35#include "lldb/Utility/Timer.h"3637#include "llvm/Object/Archive.h"38#include "llvm/Support/MemoryBuffer.h"3940using namespace lldb;41using namespace lldb_private;4243using namespace llvm::object;4445LLDB_PLUGIN_DEFINE(ObjectContainerBSDArchive)4647ObjectContainerBSDArchive::Object::Object() : ar_name() {}4849void ObjectContainerBSDArchive::Object::Clear() {50ar_name.Clear();51modification_time = 0;52size = 0;53file_offset = 0;54file_size = 0;55}5657void ObjectContainerBSDArchive::Object::Dump() const {58printf("name = \"%s\"\n", ar_name.GetCString());59printf("mtime = 0x%8.8" PRIx32 "\n", modification_time);60printf("size = 0x%8.8" PRIx32 " (%" PRIu32 ")\n", size, size);61printf("file_offset = 0x%16.16" PRIx64 " (%" PRIu64 ")\n", file_offset,62file_offset);63printf("file_size = 0x%16.16" PRIx64 " (%" PRIu64 ")\n\n", file_size,64file_size);65}6667ObjectContainerBSDArchive::Archive::Archive(const lldb_private::ArchSpec &arch,68const llvm::sys::TimePoint<> &time,69lldb::offset_t file_offset,70lldb_private::DataExtractor &data,71ArchiveType archive_type)72: m_arch(arch), m_modification_time(time), m_file_offset(file_offset),73m_objects(), m_data(data), m_archive_type(archive_type) {}7475Log *l = GetLog(LLDBLog::Object);76ObjectContainerBSDArchive::Archive::~Archive() = default;7778size_t ObjectContainerBSDArchive::Archive::ParseObjects() {79DataExtractor &data = m_data;8081std::unique_ptr<llvm::MemoryBuffer> mem_buffer =82llvm::MemoryBuffer::getMemBuffer(83llvm::StringRef((const char *)data.GetDataStart(),84data.GetByteSize()),85llvm::StringRef(),86/*RequiresNullTerminator=*/false);8788auto exp_ar = llvm::object::Archive::create(mem_buffer->getMemBufferRef());89if (!exp_ar) {90LLDB_LOG_ERROR(l, exp_ar.takeError(), "failed to create archive: {0}");91return 0;92}93auto llvm_archive = std::move(exp_ar.get());9495llvm::Error iter_err = llvm::Error::success();96Object obj;97for (const auto &child: llvm_archive->children(iter_err)) {98obj.Clear();99auto exp_name = child.getName();100if (exp_name) {101obj.ar_name = ConstString(exp_name.get());102} else {103LLDB_LOG_ERROR(l, exp_name.takeError(),104"failed to get archive object name: {0}");105continue;106}107108auto exp_mtime = child.getLastModified();109if (exp_mtime) {110obj.modification_time =111std::chrono::duration_cast<std::chrono::seconds>(112std::chrono::time_point_cast<std::chrono::seconds>(113exp_mtime.get()).time_since_epoch()).count();114} else {115LLDB_LOG_ERROR(l, exp_mtime.takeError(),116"failed to get archive object time: {0}");117continue;118}119120auto exp_size = child.getRawSize();121if (exp_size) {122obj.size = exp_size.get();123} else {124LLDB_LOG_ERROR(l, exp_size.takeError(),125"failed to get archive object size: {0}");126continue;127}128129obj.file_offset = child.getDataOffset();130131auto exp_file_size = child.getSize();132if (exp_file_size) {133obj.file_size = exp_file_size.get();134} else {135LLDB_LOG_ERROR(l, exp_file_size.takeError(),136"failed to get archive object file size: {0}");137continue;138}139m_object_name_to_index_map.Append(obj.ar_name, m_objects.size());140m_objects.push_back(obj);141}142if (iter_err) {143LLDB_LOG_ERROR(l, std::move(iter_err),144"failed to iterate over archive objects: {0}");145}146// Now sort all of the object name pointers147m_object_name_to_index_map.Sort();148return m_objects.size();149}150151ObjectContainerBSDArchive::Object *152ObjectContainerBSDArchive::Archive::FindObject(153ConstString object_name, const llvm::sys::TimePoint<> &object_mod_time) {154const ObjectNameToIndexMap::Entry *match =155m_object_name_to_index_map.FindFirstValueForName(object_name);156if (!match)157return nullptr;158if (object_mod_time == llvm::sys::TimePoint<>())159return &m_objects[match->value];160161const uint64_t object_modification_date = llvm::sys::toTimeT(object_mod_time);162if (m_objects[match->value].modification_time == object_modification_date)163return &m_objects[match->value];164165const ObjectNameToIndexMap::Entry *next_match =166m_object_name_to_index_map.FindNextValueForName(match);167while (next_match) {168if (m_objects[next_match->value].modification_time ==169object_modification_date)170return &m_objects[next_match->value];171next_match = m_object_name_to_index_map.FindNextValueForName(next_match);172}173174return nullptr;175}176177ObjectContainerBSDArchive::Archive::shared_ptr178ObjectContainerBSDArchive::Archive::FindCachedArchive(179const FileSpec &file, const ArchSpec &arch,180const llvm::sys::TimePoint<> &time, lldb::offset_t file_offset) {181std::lock_guard<std::recursive_mutex> guard(Archive::GetArchiveCacheMutex());182shared_ptr archive_sp;183Archive::Map &archive_map = Archive::GetArchiveCache();184Archive::Map::iterator pos = archive_map.find(file);185// Don't cache a value for "archive_map.end()" below since we might delete an186// archive entry...187while (pos != archive_map.end() && pos->first == file) {188bool match = true;189if (arch.IsValid() &&190!pos->second->GetArchitecture().IsCompatibleMatch(arch))191match = false;192else if (file_offset != LLDB_INVALID_OFFSET &&193pos->second->GetFileOffset() != file_offset)194match = false;195if (match) {196if (pos->second->GetModificationTime() == time) {197return pos->second;198} else {199// We have a file at the same path with the same architecture whose200// modification time doesn't match. It doesn't make sense for us to201// continue to use this BSD archive since we cache only the object info202// which consists of file time info and also the file offset and file203// size of any contained objects. Since this information is now out of204// date, we won't get the correct information if we go and extract the205// file data, so we should remove the old and outdated entry.206archive_map.erase(pos);207pos = archive_map.find(file);208continue; // Continue to next iteration so we don't increment pos209// below...210}211}212++pos;213}214return archive_sp;215}216217ObjectContainerBSDArchive::Archive::shared_ptr218ObjectContainerBSDArchive::Archive::ParseAndCacheArchiveForFile(219const FileSpec &file, const ArchSpec &arch,220const llvm::sys::TimePoint<> &time, lldb::offset_t file_offset,221DataExtractor &data, ArchiveType archive_type) {222shared_ptr archive_sp(223new Archive(arch, time, file_offset, data, archive_type));224if (archive_sp) {225const size_t num_objects = archive_sp->ParseObjects();226if (num_objects > 0) {227std::lock_guard<std::recursive_mutex> guard(228Archive::GetArchiveCacheMutex());229Archive::GetArchiveCache().insert(std::make_pair(file, archive_sp));230} else {231archive_sp.reset();232}233}234return archive_sp;235}236237ObjectContainerBSDArchive::Archive::Map &238ObjectContainerBSDArchive::Archive::GetArchiveCache() {239static Archive::Map g_archive_map;240return g_archive_map;241}242243std::recursive_mutex &244ObjectContainerBSDArchive::Archive::GetArchiveCacheMutex() {245static std::recursive_mutex g_archive_map_mutex;246return g_archive_map_mutex;247}248249void ObjectContainerBSDArchive::Initialize() {250PluginManager::RegisterPlugin(GetPluginNameStatic(),251GetPluginDescriptionStatic(), CreateInstance,252GetModuleSpecifications);253}254255void ObjectContainerBSDArchive::Terminate() {256PluginManager::UnregisterPlugin(CreateInstance);257}258259ObjectContainer *ObjectContainerBSDArchive::CreateInstance(260const lldb::ModuleSP &module_sp, DataBufferSP &data_sp,261lldb::offset_t data_offset, const FileSpec *file,262lldb::offset_t file_offset, lldb::offset_t length) {263ConstString object_name(module_sp->GetObjectName());264if (!object_name)265return nullptr;266267if (data_sp) {268// We have data, which means this is the first 512 bytes of the file Check269// to see if the magic bytes match and if they do, read the entire table of270// contents for the archive and cache it271DataExtractor data;272data.SetData(data_sp, data_offset, length);273ArchiveType archive_type = ObjectContainerBSDArchive::MagicBytesMatch(data);274if (file && data_sp && archive_type != ArchiveType::Invalid) {275LLDB_SCOPED_TIMERF(276"ObjectContainerBSDArchive::CreateInstance (module = %s, file = "277"%p, file_offset = 0x%8.8" PRIx64 ", file_size = 0x%8.8" PRIx64 ")",278module_sp->GetFileSpec().GetPath().c_str(),279static_cast<const void *>(file), static_cast<uint64_t>(file_offset),280static_cast<uint64_t>(length));281282// Map the entire .a file to be sure that we don't lose any data if the283// file gets updated by a new build while this .a file is being used for284// debugging285DataBufferSP archive_data_sp =286FileSystem::Instance().CreateDataBuffer(*file, length, file_offset);287if (!archive_data_sp)288return nullptr;289290lldb::offset_t archive_data_offset = 0;291292Archive::shared_ptr archive_sp(Archive::FindCachedArchive(293*file, module_sp->GetArchitecture(), module_sp->GetModificationTime(),294file_offset));295std::unique_ptr<ObjectContainerBSDArchive> container_up(296new ObjectContainerBSDArchive(module_sp, archive_data_sp,297archive_data_offset, file, file_offset,298length, archive_type));299300if (container_up) {301if (archive_sp) {302// We already have this archive in our cache, use it303container_up->SetArchive(archive_sp);304return container_up.release();305} else if (container_up->ParseHeader())306return container_up.release();307}308}309} else {310// No data, just check for a cached archive311Archive::shared_ptr archive_sp(Archive::FindCachedArchive(312*file, module_sp->GetArchitecture(), module_sp->GetModificationTime(),313file_offset));314if (archive_sp) {315std::unique_ptr<ObjectContainerBSDArchive> container_up(316new ObjectContainerBSDArchive(module_sp, data_sp, data_offset, file,317file_offset, length,318archive_sp->GetArchiveType()));319320if (container_up) {321// We already have this archive in our cache, use it322container_up->SetArchive(archive_sp);323return container_up.release();324}325}326}327return nullptr;328}329330ArchiveType331ObjectContainerBSDArchive::MagicBytesMatch(const DataExtractor &data) {332uint32_t offset = 0;333const char *armag = (const char *)data.PeekData(offset,334sizeof(ar_hdr) + SARMAG);335if (armag == nullptr)336return ArchiveType::Invalid;337ArchiveType result = ArchiveType::Invalid;338if (strncmp(armag, ArchiveMagic, SARMAG) == 0)339result = ArchiveType::Archive;340else if (strncmp(armag, ThinArchiveMagic, SARMAG) == 0)341result = ArchiveType::ThinArchive;342else343return ArchiveType::Invalid;344345armag += offsetof(struct ar_hdr, ar_fmag) + SARMAG;346if (strncmp(armag, ARFMAG, 2) == 0)347return result;348return ArchiveType::Invalid;349}350351ObjectContainerBSDArchive::ObjectContainerBSDArchive(352const lldb::ModuleSP &module_sp, DataBufferSP &data_sp,353lldb::offset_t data_offset, const lldb_private::FileSpec *file,354lldb::offset_t file_offset, lldb::offset_t size, ArchiveType archive_type)355: ObjectContainer(module_sp, file, file_offset, size, data_sp, data_offset),356m_archive_sp() {357m_archive_type = archive_type;358}359360void ObjectContainerBSDArchive::SetArchive(Archive::shared_ptr &archive_sp) {361m_archive_sp = archive_sp;362}363364ObjectContainerBSDArchive::~ObjectContainerBSDArchive() = default;365366bool ObjectContainerBSDArchive::ParseHeader() {367if (m_archive_sp.get() == nullptr) {368if (m_data.GetByteSize() > 0) {369ModuleSP module_sp(GetModule());370if (module_sp) {371m_archive_sp = Archive::ParseAndCacheArchiveForFile(372m_file, module_sp->GetArchitecture(),373module_sp->GetModificationTime(), m_offset, m_data, m_archive_type);374}375// Clear the m_data that contains the entire archive data and let our376// m_archive_sp hold onto the data.377m_data.Clear();378}379}380return m_archive_sp.get() != nullptr;381}382383FileSpec GetChildFileSpecificationsFromThin(llvm::StringRef childPath,384const FileSpec &parentFileSpec) {385llvm::SmallString<128> FullPath;386if (llvm::sys::path::is_absolute(childPath)) {387FullPath = childPath;388} else {389FullPath = parentFileSpec.GetDirectory().GetStringRef();390llvm::sys::path::append(FullPath, childPath);391}392FileSpec child = FileSpec(FullPath.str(), llvm::sys::path::Style::posix);393return child;394}395396ObjectFileSP ObjectContainerBSDArchive::GetObjectFile(const FileSpec *file) {397ModuleSP module_sp(GetModule());398if (module_sp) {399if (module_sp->GetObjectName() && m_archive_sp) {400Object *object = m_archive_sp->FindObject(401module_sp->GetObjectName(), module_sp->GetObjectModificationTime());402if (object) {403if (m_archive_type == ArchiveType::ThinArchive) {404// Set file to child object file405FileSpec child = GetChildFileSpecificationsFromThin(406object->ar_name.GetStringRef(), m_file);407lldb::offset_t file_offset = 0;408lldb::offset_t file_size = object->size;409std::shared_ptr<DataBuffer> child_data_sp =410FileSystem::Instance().CreateDataBuffer(child, file_size,411file_offset);412if (!child_data_sp ||413child_data_sp->GetByteSize() != object->file_size)414return ObjectFileSP();415lldb::offset_t data_offset = 0;416return ObjectFile::FindPlugin(417module_sp, &child, m_offset + object->file_offset,418object->file_size, child_data_sp, data_offset);419}420lldb::offset_t data_offset = object->file_offset;421return ObjectFile::FindPlugin(422module_sp, file, m_offset + object->file_offset, object->file_size,423m_archive_sp->GetData().GetSharedDataBuffer(), data_offset);424}425}426}427return ObjectFileSP();428}429430size_t ObjectContainerBSDArchive::GetModuleSpecifications(431const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,432lldb::offset_t data_offset, lldb::offset_t file_offset,433lldb::offset_t file_size, lldb_private::ModuleSpecList &specs) {434435// We have data, which means this is the first 512 bytes of the file Check to436// see if the magic bytes match and if they do, read the entire table of437// contents for the archive and cache it438DataExtractor data;439data.SetData(data_sp, data_offset, data_sp->GetByteSize());440ArchiveType archive_type = ObjectContainerBSDArchive::MagicBytesMatch(data);441if (!file || !data_sp || archive_type == ArchiveType::Invalid)442return 0;443444const size_t initial_count = specs.GetSize();445llvm::sys::TimePoint<> file_mod_time = FileSystem::Instance().GetModificationTime(file);446Archive::shared_ptr archive_sp(447Archive::FindCachedArchive(file, ArchSpec(), file_mod_time, file_offset));448bool set_archive_arch = false;449if (!archive_sp) {450set_archive_arch = true;451data_sp =452FileSystem::Instance().CreateDataBuffer(file, file_size, file_offset);453if (data_sp) {454data.SetData(data_sp, 0, data_sp->GetByteSize());455archive_sp = Archive::ParseAndCacheArchiveForFile(456file, ArchSpec(), file_mod_time, file_offset, data, archive_type);457}458}459460if (archive_sp) {461const size_t num_objects = archive_sp->GetNumObjects();462for (size_t idx = 0; idx < num_objects; ++idx) {463const Object *object = archive_sp->GetObjectAtIndex(idx);464if (object) {465if (archive_sp->GetArchiveType() == ArchiveType::ThinArchive) {466if (object->ar_name.IsEmpty())467continue;468FileSpec child = GetChildFileSpecificationsFromThin(469object->ar_name.GetStringRef(), file);470if (ObjectFile::GetModuleSpecifications(child, 0, object->file_size,471specs)) {472ModuleSpec &spec =473specs.GetModuleSpecRefAtIndex(specs.GetSize() - 1);474llvm::sys::TimePoint<> object_mod_time(475std::chrono::seconds(object->modification_time));476spec.GetObjectName() = object->ar_name;477spec.SetObjectOffset(0);478spec.SetObjectSize(object->file_size);479spec.GetObjectModificationTime() = object_mod_time;480}481continue;482}483const lldb::offset_t object_file_offset =484file_offset + object->file_offset;485if (object->file_offset < file_size && file_size > object_file_offset) {486if (ObjectFile::GetModuleSpecifications(487file, object_file_offset, file_size - object_file_offset,488specs)) {489ModuleSpec &spec =490specs.GetModuleSpecRefAtIndex(specs.GetSize() - 1);491llvm::sys::TimePoint<> object_mod_time(492std::chrono::seconds(object->modification_time));493spec.GetObjectName() = object->ar_name;494spec.SetObjectOffset(object_file_offset);495spec.SetObjectSize(object->file_size);496spec.GetObjectModificationTime() = object_mod_time;497}498}499}500}501}502const size_t end_count = specs.GetSize();503size_t num_specs_added = end_count - initial_count;504if (set_archive_arch && num_specs_added > 0) {505// The archive was created but we didn't have an architecture so we need to506// set it507for (size_t i = initial_count; i < end_count; ++i) {508ModuleSpec module_spec;509if (specs.GetModuleSpecAtIndex(i, module_spec)) {510if (module_spec.GetArchitecture().IsValid()) {511archive_sp->SetArchitecture(module_spec.GetArchitecture());512break;513}514}515}516}517return num_specs_added;518}519520521