1
1
mirror of https://github.com/rui314/mold.git synced 2024-09-23 02:49:12 +03:00
mold/output_chunks.cc

82 lines
2.3 KiB
C++
Raw Normal View History

2020-10-20 08:54:35 +03:00
#include "mold.h"
2020-10-13 14:35:35 +03:00
2020-10-16 10:38:03 +03:00
using namespace llvm::ELF;
2020-10-17 07:24:48 +03:00
OutputEhdr *out::ehdr;
OutputShdr *out::shdr;
OutputPhdr *out::phdr;
2020-10-22 10:35:17 +03:00
std::vector<OutputSection *> OutputSection::all_instances;
2020-10-17 07:00:53 +03:00
void OutputEhdr::relocate(uint8_t *buf) {
auto *hdr = (ELF64LE::Ehdr *)buf;
memcpy(&hdr->e_ident, "\177ELF", 4);
hdr->e_ident[EI_CLASS] = ELFCLASS64;
hdr->e_ident[EI_DATA] = ELFDATA2LSB;
hdr->e_ident[EI_VERSION] = EV_CURRENT;
hdr->e_ident[EI_OSABI] = 0;
hdr->e_ident[EI_ABIVERSION] = 0;
hdr->e_machine = EM_X86_64;
hdr->e_version = EV_CURRENT;
hdr->e_entry = 0;
2020-10-17 07:24:48 +03:00
hdr->e_phoff = out::phdr->get_offset();
hdr->e_shoff = out::shdr->get_offset();
2020-10-17 07:00:53 +03:00
hdr->e_flags = 0;
hdr->e_ehsize = sizeof(ELF64LE::Ehdr);
hdr->e_phentsize = sizeof(ELF64LE::Phdr);
2020-10-17 07:24:48 +03:00
hdr->e_phnum = out::phdr->hdr.size();
2020-10-17 07:00:53 +03:00
hdr->e_shentsize = sizeof(ELF64LE::Shdr);
2020-10-17 07:24:48 +03:00
hdr->e_shnum = out::shdr->hdr.size();
2020-10-17 07:00:53 +03:00
hdr->e_shstrndx = 0;
2020-10-14 10:27:45 +03:00
}
2020-10-15 13:27:35 +03:00
void OutputSection::set_offset(uint64_t off) {
offset = off;
2020-10-20 09:32:55 +03:00
for (InputChunk *chunk : chunks) {
chunk->offset = off;
off += chunk->get_size();
2020-10-14 10:27:45 +03:00
}
2020-10-15 13:27:35 +03:00
size = off - offset;
2020-10-14 10:27:45 +03:00
}
2020-10-22 10:35:17 +03:00
static StringRef get_output_name(StringRef name) {
static StringRef common_names[] = {
".text.", ".data.rel.ro.", ".data.", ".rodata.", ".bss.rel.ro.",
".bss.", ".init_array.", ".fini_array.", ".tbss.", ".tdata.",
};
for (StringRef s : common_names)
if (name.startswith(s) || name == s.drop_back())
return s.drop_back();
return name;
}
OutputSection *OutputSection::get_instance(InputSection *isec) {
StringRef iname = get_output_name(isec->name);
uint64_t iflags = isec->hdr->sh_flags & ~SHF_GROUP;
auto find = [&]() -> OutputSection * {
for (OutputSection *osec : OutputSection::all_instances)
if (iname == osec->name && iflags == (osec->hdr.sh_flags & ~SHF_GROUP) &&
isec->hdr->sh_type == osec->hdr.sh_type)
return osec;
return nullptr;
};
// Search for an exiting output section.
static std::shared_mutex mu;
std::shared_lock shared_lock(mu);
if (OutputSection *osec = find())
return osec;
shared_lock.unlock();
// Create a new output section.
std::unique_lock unique_lock(mu);
if (OutputSection *osec = find())
return osec;
OutputSection *osec = new OutputSection(iname, iflags, isec->hdr->sh_type);
OutputSection::all_instances.push_back(osec);
return osec;
}