LLDB mainline
ObjectContainerBSDArchive.cpp
Go to the documentation of this file.
1//===-- ObjectContainerBSDArchive.cpp -------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10
11#if defined(_WIN32) || defined(_AIX)
12// Defines from ar, missing on Windows
13#define SARMAG 8
14#define ARFMAG "`\n"
15
16typedef struct ar_hdr {
17 char ar_name[16];
18 char ar_date[12];
19 char ar_uid[6], ar_gid[6];
20 char ar_mode[8];
21 char ar_size[10];
22 char ar_fmag[2];
23} ar_hdr;
24#else
25#include <ar.h>
26#endif
27
28#include "lldb/Core/Module.h"
35#include "lldb/Utility/Stream.h"
36#include "lldb/Utility/Timer.h"
37
38#include "llvm/Object/Archive.h"
39#include "llvm/Support/MemoryBuffer.h"
40
41using namespace lldb;
42using namespace lldb_private;
43
44using namespace llvm::object;
45
47
49
51 ar_name.clear();
53 size = 0;
54 file_offset = 0;
55 file_size = 0;
56}
57
59 printf("name = \"%s\"\n", ar_name.c_str());
60 printf("mtime = 0x%8.8" PRIx32 "\n", modification_time);
61 printf("size = 0x%8.8" PRIx32 " (%" PRIu32 ")\n", size, size);
62 printf("file_offset = 0x%16.16" PRIx64 " (%" PRIu64 ")\n", file_offset,
64 printf("file_size = 0x%16.16" PRIx64 " (%" PRIu64 ")\n\n", file_size,
65 file_size);
66}
67
69 const llvm::sys::TimePoint<> &time,
70 lldb::offset_t file_offset,
71 lldb::DataExtractorSP extractor_sp,
72 ArchiveType archive_type)
73 : m_arch(arch), m_modification_time(time), m_file_offset(file_offset),
74 m_objects(), m_extractor_sp(extractor_sp), m_archive_type(archive_type) {}
75
78
80 std::unique_ptr<llvm::MemoryBuffer> mem_buffer =
81 llvm::MemoryBuffer::getMemBuffer(
82 llvm::StringRef((const char *)m_extractor_sp->GetDataStart(),
83 m_extractor_sp->GetByteSize()),
84 llvm::StringRef(),
85 /*RequiresNullTerminator=*/false);
86
87 auto exp_ar = llvm::object::Archive::create(mem_buffer->getMemBufferRef());
88 if (!exp_ar) {
89 LLDB_LOG_ERROR(l, exp_ar.takeError(), "failed to create archive: {0}");
90 return 0;
91 }
92 auto llvm_archive = std::move(exp_ar.get());
93
94 llvm::Error iter_err = llvm::Error::success();
95 Object obj;
96 for (const auto &child : llvm_archive->children(iter_err)) {
97 obj.Clear();
98 auto exp_name = child.getName();
99 if (exp_name) {
100 obj.ar_name = exp_name.get().str();
101 } else {
102 LLDB_LOG_ERROR(l, exp_name.takeError(),
103 "failed to get archive object name: {0}");
104 continue;
105 }
106
107 auto exp_mtime = child.getLastModified();
108 if (exp_mtime) {
110 std::chrono::duration_cast<std::chrono::seconds>(
111 std::chrono::time_point_cast<std::chrono::seconds>(
112 exp_mtime.get())
113 .time_since_epoch())
114 .count();
115 } else {
116 LLDB_LOG_ERROR(l, exp_mtime.takeError(),
117 "failed to get archive object time: {0}");
118 continue;
119 }
120
121 auto exp_size = child.getRawSize();
122 if (exp_size) {
123 obj.size = exp_size.get();
124 } else {
125 LLDB_LOG_ERROR(l, exp_size.takeError(),
126 "failed to get archive object size: {0}");
127 continue;
128 }
129
130 obj.file_offset = child.getDataOffset();
131
132 auto exp_file_size = child.getSize();
133 if (exp_file_size) {
134 obj.file_size = exp_file_size.get();
135 } else {
136 LLDB_LOG_ERROR(l, exp_file_size.takeError(),
137 "failed to get archive object file size: {0}");
138 continue;
139 }
140 auto &indices = m_object_name_to_index_map[obj.ar_name];
141 indices.push_back(m_objects.size());
142 m_objects.push_back(obj);
143 }
144 if (iter_err) {
145 LLDB_LOG_ERROR(l, std::move(iter_err),
146 "failed to iterate over archive objects: {0}");
147 }
148 return m_objects.size();
149}
150
153 llvm::StringRef object_name,
154 const llvm::sys::TimePoint<> &object_mod_time) {
155 auto it = m_object_name_to_index_map.find(object_name);
156 if (it == m_object_name_to_index_map.end())
157 return nullptr;
158 if (object_mod_time == llvm::sys::TimePoint<>())
159 return &m_objects[it->second.front()];
160
161 const uint64_t object_modification_date = llvm::sys::toTimeT(object_mod_time);
162 for (uint32_t idx : it->second) {
163 if (m_objects[idx].modification_time == object_modification_date)
164 return &m_objects[idx];
165 }
166 return nullptr;
167}
168
171 const FileSpec &file, const ArchSpec &arch,
172 const llvm::sys::TimePoint<> &time, lldb::offset_t file_offset) {
173 std::lock_guard<std::recursive_mutex> guard(Archive::GetArchiveCacheMutex());
174 ArchiveSP archive_sp;
175 Archive::Map &archive_map = Archive::GetArchiveCache();
176 Archive::Map::iterator pos = archive_map.find(file);
177 // Don't cache a value for "archive_map.end()" below since we might delete an
178 // archive entry...
179 while (pos != archive_map.end() && pos->first == file) {
180 bool match = true;
181 if (arch.IsValid() &&
182 !pos->second->GetArchitecture().IsCompatibleMatch(arch))
183 match = false;
184 else if (file_offset != LLDB_INVALID_OFFSET &&
185 pos->second->GetFileOffset() != file_offset)
186 match = false;
187 if (match) {
188 if (pos->second->GetModificationTime() == time) {
189 return pos->second;
190 } else {
191 // We have a file at the same path with the same architecture whose
192 // modification time doesn't match. It doesn't make sense for us to
193 // continue to use this BSD archive since we cache only the object info
194 // which consists of file time info and also the file offset and file
195 // size of any contained objects. Since this information is now out of
196 // date, we won't get the correct information if we go and extract the
197 // file data, so we should remove the old and outdated entry.
198 archive_map.erase(pos);
199 pos = archive_map.find(file);
200 continue; // Continue to next iteration so we don't increment pos
201 // below...
202 }
203 }
204 ++pos;
205 }
206 return archive_sp;
207}
208
211 const FileSpec &file, const ArchSpec &arch,
212 const llvm::sys::TimePoint<> &time, lldb::offset_t file_offset,
213 DataExtractorSP extractor_sp, ArchiveType archive_type) {
214 ArchiveSP archive_sp = std::make_shared<Archive>(arch, time, file_offset,
215 extractor_sp, archive_type);
216 if (archive_sp) {
217 const size_t num_objects = archive_sp->ParseObjects();
218 if (num_objects > 0) {
219 std::lock_guard<std::recursive_mutex> guard(
221 Archive::GetArchiveCache().insert(std::make_pair(file, archive_sp));
222 } else {
223 archive_sp.reset();
224 }
225 }
226 return archive_sp;
227}
228
231 static Archive::Map g_archive_map;
232 return g_archive_map;
233}
234
235std::recursive_mutex &
237 static std::recursive_mutex g_archive_map_mutex;
238 return g_archive_map_mutex;
239}
240
246
250
252 const lldb::ModuleSP &module_sp, DataBufferSP &data_sp,
253 lldb::offset_t data_offset, const FileSpec *file,
254 lldb::offset_t file_offset, lldb::offset_t length) {
255 ConstString object_name(module_sp->GetObjectName());
256 if (!object_name)
257 return nullptr;
258
259 if (data_sp) {
260 // We have data, which means this is the first 512 bytes of the file Check
261 // to see if the magic bytes match and if they do, read the entire table of
262 // contents for the archive and cache it
263 DataExtractor data;
264 data.SetData(data_sp, data_offset, length);
266 if (file && data_sp && archive_type != ArchiveType::Invalid) {
268 "ObjectContainerBSDArchive::CreateInstance (module = %s, file = "
269 "%p, file_offset = 0x%8.8" PRIx64 ", file_size = 0x%8.8" PRIx64 ")",
270 module_sp->GetFileSpec().GetPath().c_str(),
271 static_cast<const void *>(file), static_cast<uint64_t>(file_offset),
272 static_cast<uint64_t>(length));
273
274 // Map the entire .a file to be sure that we don't lose any data if the
275 // file gets updated by a new build while this .a file is being used for
276 // debugging
277 DataBufferSP archive_data_sp =
278 FileSystem::Instance().CreateDataBuffer(*file, length, file_offset);
279 if (!archive_data_sp)
280 return nullptr;
281
282 lldb::offset_t archive_data_offset = 0;
283
285 *file, module_sp->GetArchitecture(), module_sp->GetModificationTime(),
286 file_offset));
287 std::unique_ptr<ObjectContainerBSDArchive> container_up(
288 new ObjectContainerBSDArchive(module_sp, archive_data_sp,
289 archive_data_offset, file, file_offset,
290 length, archive_type));
291
292 if (container_up) {
293 if (archive_sp) {
294 // We already have this archive in our cache, use it
295 container_up->SetArchive(archive_sp);
296 return container_up.release();
297 } else if (container_up->ParseHeader())
298 return container_up.release();
299 }
300 }
301 } else {
302 // No data, just check for a cached archive
304 *file, module_sp->GetArchitecture(), module_sp->GetModificationTime(),
305 file_offset));
306 if (archive_sp) {
307 std::unique_ptr<ObjectContainerBSDArchive> container_up(
308 new ObjectContainerBSDArchive(module_sp, data_sp, data_offset, file,
309 file_offset, length,
310 archive_sp->GetArchiveType()));
311
312 if (container_up) {
313 // We already have this archive in our cache, use it
314 container_up->SetArchive(archive_sp);
315 return container_up.release();
316 }
317 }
318 }
319 return nullptr;
320}
321
324 uint32_t offset = 0;
325 const char *armag =
326 (const char *)data.PeekData(offset, sizeof(ar_hdr) + SARMAG);
327 if (armag == nullptr)
330 if (strncmp(armag, ArchiveMagic, SARMAG) == 0)
331 result = ArchiveType::Archive;
332 else if (strncmp(armag, ThinArchiveMagic, SARMAG) == 0)
334 else
336
337 armag += offsetof(struct ar_hdr, ar_fmag) + SARMAG;
338 if (strncmp(armag, ARFMAG, 2) == 0)
339 return result;
341}
342
344 const lldb::ModuleSP &module_sp, DataBufferSP &data_sp,
345 lldb::offset_t data_offset, const FileSpec *file,
346 lldb::offset_t file_offset, lldb::offset_t size, ArchiveType archive_type)
347 : ObjectContainer(module_sp, file, file_offset, size, data_sp, data_offset),
348 m_archive_sp() {
349 m_archive_type = archive_type;
350}
351
353 m_archive_sp = archive_sp;
354}
355
357
359 if (m_archive_sp.get() == nullptr) {
360 if (m_extractor_sp->GetByteSize() > 0) {
361 ModuleSP module_sp(GetModule());
362 if (module_sp) {
364 m_file, module_sp->GetArchitecture(),
365 module_sp->GetModificationTime(), m_offset, m_extractor_sp,
367 }
368 // Clear the m_extractor_sp that contains the entire archive data and let
369 // our m_archive_sp hold onto the data. Need to have an empty
370 // DataExtractor for code that assumes it is non-null.
371 m_extractor_sp = std::make_shared<DataExtractor>();
372 }
373 }
374 return m_archive_sp.get() != nullptr;
375}
376
378 const FileSpec &parentFileSpec) {
379 llvm::SmallString<128> FullPath;
380 if (llvm::sys::path::is_absolute(childPath)) {
381 FullPath = childPath;
382 } else {
383 FullPath = parentFileSpec.GetDirectory();
384 llvm::sys::path::append(FullPath, childPath);
385 }
386 FileSpec child = FileSpec(FullPath.str(), llvm::sys::path::Style::posix);
387 return child;
388}
389
391 ModuleSP module_sp(GetModule());
392 if (module_sp) {
393 if (module_sp->GetObjectName() && m_archive_sp) {
394 Object *object = m_archive_sp->FindObject(
395 module_sp->GetObjectName(), module_sp->GetObjectModificationTime());
396 if (object) {
398 // Set file to child object file
399 FileSpec child =
401 lldb::offset_t file_offset = 0;
402 lldb::offset_t file_size = object->size;
404 child, file_size, file_offset);
405 if (!child_data_sp ||
406 child_data_sp->GetByteSize() != object->file_size)
407 return ObjectFileSP();
408 lldb::offset_t data_offset = 0;
409 DataExtractorSP extractor_sp =
410 std::make_shared<DataExtractor>(child_data_sp);
412 module_sp, &child, m_offset + object->file_offset,
413 object->file_size, extractor_sp, data_offset);
414 }
415 lldb::offset_t data_offset = object->file_offset;
416 // Create a new DataExtractor object, its DataBuffer will be shared.
417 DataExtractorSP extractor_sp =
418 std::make_shared<DataExtractor>(m_archive_sp->GetData());
420 module_sp, file, m_offset + object->file_offset, object->file_size,
421 extractor_sp, data_offset);
422 }
423 }
424 }
425 return ObjectFileSP();
426}
427
429 const FileSpec &file, lldb::DataExtractorSP &extractor_sp,
430 lldb::offset_t file_offset, lldb::offset_t file_size) {
431
432 if (!file || !extractor_sp)
433 return {};
434
435 // We have data, which means this is the first 512 bytes of the file Check to
436 // see if the magic bytes match and if they do, read the entire table of
437 // contents for the archive and cache it
438 ArchiveType archive_type = MagicBytesMatch(*extractor_sp);
439 if (archive_type == ArchiveType::Invalid)
440 return {};
441
442 llvm::sys::TimePoint<> file_mod_time =
444 ArchiveSP archive_sp(
445 Archive::FindCachedArchive(file, ArchSpec(), file_mod_time, file_offset));
446 bool set_archive_arch = false;
447 if (!archive_sp) {
448 set_archive_arch = true;
449 DataBufferSP data_sp =
450 FileSystem::Instance().CreateDataBuffer(file, file_size, file_offset);
451 if (data_sp) {
452 extractor_sp->SetData(data_sp);
454 file, ArchSpec(), file_mod_time, file_offset, extractor_sp,
455 archive_type);
456 }
457 }
458
459 ModuleSpecList specs;
460 if (archive_sp) {
461 const size_t num_objects = archive_sp->GetNumObjects();
462 for (size_t idx = 0; idx < num_objects; ++idx) {
463 const Object *object = archive_sp->GetObjectAtIndex(idx);
464 if (object) {
465 if (archive_sp->GetArchiveType() == ArchiveType::ThinArchive) {
466 if (object->ar_name.empty())
467 continue;
468 FileSpec child =
469 GetChildFileSpecificationsFromThin(object->ar_name, file);
470 ModuleSpecList object_specs =
472 child, 0, object->file_size);
473 if (object_specs.GetSize() > 0) {
474 ModuleSpec &spec = object_specs.GetModuleSpecRefAtIndex(
475 object_specs.GetSize() - 1);
476 llvm::sys::TimePoint<> object_mod_time(
477 std::chrono::seconds(object->modification_time));
478 spec.GetObjectName() = ConstString(object->ar_name);
479 spec.SetObjectOffset(0);
480 spec.SetObjectSize(object->file_size);
481 spec.GetObjectModificationTime() = object_mod_time;
482 specs.Append(spec);
483 }
484 continue;
485 }
486 const lldb::offset_t object_file_offset =
487 file_offset + object->file_offset;
488 if (object->file_offset < file_size && file_size > object_file_offset) {
489 ModuleSpecList object_specs =
491 file, object_file_offset, file_size - object_file_offset);
492 if (object_specs.GetSize() > 0) {
493 ModuleSpec &spec = object_specs.GetModuleSpecRefAtIndex(
494 object_specs.GetSize() - 1);
495 llvm::sys::TimePoint<> object_mod_time(
496 std::chrono::seconds(object->modification_time));
497 spec.GetObjectName() = ConstString(object->ar_name);
498 spec.SetObjectOffset(object_file_offset);
499 spec.SetObjectSize(object->file_size);
500 spec.GetObjectModificationTime() = object_mod_time;
501 specs.Append(spec);
502 }
503 }
504 }
505 }
506 }
507 const size_t end_count = specs.GetSize();
508 if (set_archive_arch && specs.GetSize() > 0) {
509 // The archive was created but we didn't have an architecture so we need to
510 // set it
511 for (size_t i = 0; i < end_count; ++i) {
512 ModuleSpec module_spec;
513 if (specs.GetModuleSpecAtIndex(i, module_spec)) {
514 if (module_spec.GetArchitecture().IsValid()) {
515 archive_sp->SetArchitecture(module_spec.GetArchitecture());
516 break;
517 }
518 }
519 }
520 }
521 return specs;
522}
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
FileSpec GetChildFileSpecificationsFromThin(llvm::StringRef childPath, const FileSpec &parentFileSpec)
#define LLDB_PLUGIN_DEFINE(PluginName)
#define LLDB_SCOPED_TIMERF(...)
Definition Timer.h:86
Object * FindObject(llvm::StringRef object_name, const llvm::sys::TimePoint<> &object_mod_time)
lldb::DataExtractorSP m_extractor_sp
The data for this object container so we don't lose data if the .a files gets modified.
static std::recursive_mutex & GetArchiveCacheMutex()
std::multimap< lldb_private::FileSpec, ArchiveSP > Map
static ArchiveSP FindCachedArchive(const lldb_private::FileSpec &file, const lldb_private::ArchSpec &arch, const llvm::sys::TimePoint<> &mod_time, lldb::offset_t file_offset)
static ArchiveSP ParseAndCacheArchiveForFile(const lldb_private::FileSpec &file, const lldb_private::ArchSpec &arch, const llvm::sys::TimePoint<> &mod_time, lldb::offset_t file_offset, lldb::DataExtractorSP extractor_sp, ArchiveType archive_type)
Archive(const lldb_private::ArchSpec &arch, const llvm::sys::TimePoint<> &mod_time, lldb::offset_t file_offset, lldb::DataExtractorSP extractor_sp, ArchiveType archive_type)
static lldb_private::ObjectContainer * CreateInstance(const lldb::ModuleSP &module_sp, lldb::DataBufferSP &data_sp, lldb::offset_t data_offset, const lldb_private::FileSpec *file, lldb::offset_t offset, lldb::offset_t length)
static llvm::StringRef GetPluginNameStatic()
static lldb_private::ModuleSpecList GetModuleSpecifications(const lldb_private::FileSpec &file, lldb::DataExtractorSP &extractor_sp, lldb::offset_t file_offset, lldb::offset_t length)
lldb::ObjectFileSP GetObjectFile(const lldb_private::FileSpec *file) override
Selects an architecture in an object file.
bool ParseHeader() override
Attempts to parse the object header.
void SetArchive(ArchiveSP &archive_sp)
static llvm::StringRef GetPluginDescriptionStatic()
static ArchiveType MagicBytesMatch(const lldb_private::DataExtractor &extractor)
~ObjectContainerBSDArchive() override
std::shared_ptr< Archive > ArchiveSP
ObjectContainerBSDArchive(const lldb::ModuleSP &module_sp, lldb::DataBufferSP &data_sp, lldb::offset_t data_offset, const lldb_private::FileSpec *file, lldb::offset_t offset, lldb::offset_t length, ArchiveType archive_type)
An architecture specification class.
Definition ArchSpec.h:32
bool IsValid() const
Tests if this ArchSpec is valid.
Definition ArchSpec.h:455
A uniqued constant string class.
Definition ConstString.h:40
An data extractor class.
virtual const uint8_t * PeekData(lldb::offset_t offset, lldb::offset_t length) const
Peek at a bytes at offset.
virtual lldb::offset_t SetData(const void *bytes, lldb::offset_t length, lldb::ByteOrder byte_order)
Set data with a buffer that is caller owned.
A file utility class.
Definition FileSpec.h:56
llvm::StringRef GetDirectory() const
Directory string const get accessor.
Definition FileSpec.h:233
llvm::sys::TimePoint GetModificationTime(const FileSpec &file_spec) const
Returns the modification time of the given file.
static FileSystem & Instance()
std::shared_ptr< DataBuffer > CreateDataBuffer(const llvm::Twine &path, uint64_t size=0, uint64_t offset=0)
Create memory buffer from path.
lldb::ModuleSP GetModule() const
Get const accessor for the module pointer.
bool GetModuleSpecAtIndex(size_t i, ModuleSpec &module_spec) const
Definition ModuleSpec.h:387
void Append(const ModuleSpec &spec)
Definition ModuleSpec.h:372
ModuleSpec & GetModuleSpecRefAtIndex(size_t i)
Definition ModuleSpec.h:385
void SetObjectSize(uint64_t object_size)
Definition ModuleSpec.h:120
ConstString & GetObjectName()
Definition ModuleSpec.h:108
ArchSpec & GetArchitecture()
Definition ModuleSpec.h:94
void SetObjectOffset(uint64_t object_offset)
Definition ModuleSpec.h:114
llvm::sys::TimePoint & GetObjectModificationTime()
Definition ModuleSpec.h:131
lldb::DataExtractorSP m_extractor_sp
The data for this object file so things can be parsed lazily.
FileSpec m_file
The file that represents this container objects (which can be different from the module's file).
lldb::addr_t m_offset
The offset in bytes into the file, or the address in memory.
ObjectContainer(const lldb::ModuleSP &module_sp, const FileSpec *file, lldb::offset_t file_offset, lldb::offset_t length, lldb::DataBufferSP data_sp, lldb::offset_t data_offset)
Construct with a parent module, offset, and header data.
static lldb::ObjectFileSP FindPlugin(const lldb::ModuleSP &module_sp, const FileSpec *file_spec, lldb::offset_t file_offset, lldb::offset_t file_size, lldb::DataExtractorSP extractor_sp, lldb::offset_t &data_offset)
Find a ObjectFile plug-in that can parse file_spec.
static ModuleSpecList GetModuleSpecifications(const FileSpec &file, lldb::offset_t file_offset, lldb::offset_t file_size, lldb::DataExtractorSP=lldb::DataExtractorSP())
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
#define LLDB_INVALID_OFFSET
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
uint64_t offset_t
Definition lldb-types.h:86
std::shared_ptr< lldb_private::ObjectFile > ObjectFileSP
std::shared_ptr< lldb_private::DataBuffer > DataBufferSP
std::shared_ptr< lldb_private::DataExtractor > DataExtractorSP
std::shared_ptr< lldb_private::Module > ModuleSP
std::string ar_name
Object name in the archive.
uint32_t size
Object size in bytes in the archive.
uint32_t modification_time
Object modification time in the archive.
lldb::offset_t file_size
Length of the object data.
lldb::offset_t file_offset
File offset in bytes from the beginning of the file of the object data.