This repository has been archived by the owner on Sep 11, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
/
Object.cpp
424 lines (357 loc) · 12.4 KB
/
Object.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
/* SPDX-License-Identifier: GPL-3.0-or-later */
/* Copyright © 2016-2024 Byteduck */
#include "Object.h"
#include <cstring>
#include <libduck/Log.h>
#include <map>
#include <sys/mman.h>
#include "Loader.h"
using Duck::Log;
using namespace Exec;
// TODO: We just gotta redo most of this. It's pretty gross.
Object::~Object() {
close(fd);
munmap(mapped_file, mapped_size);
}
int Object::load(Loader& loader, const char* name_cstr) {
if(loaded)
return 0;
name = name_cstr;
//Read the headers
if(read_headers() < 0) {
Log::err("Failed to read header of ", name_cstr, ": ", strerror(errno));
return -1;
}
//Calculate the object size
if(calculate_memsz() < 0) {
Log::err("Failed to calculate size of ", name_cstr);
errno = ENOEXEC;
return -1;
}
//Allocate memory to hold the object
memloc = loader.get_memloc_for(this);
//Read the dynamic table and figure out the required libraries
if(load_dynamic_table() < 0) {
Log::err("Failed to read dynamic table of ", name_cstr, ": ", strerror(errno));
return -1;
}
// Unmap the file from memory
if(munmap(mapped_file, mapped_size) < 0)
Duck::Log::warnf("ld: Failed to unmap object {}!", name);
mapped_file = nullptr;
mapped_size = 0;
// Load the object
if(load_sections() < 0) {
Log::err("Failed to load ", name_cstr, " into memory: ", strerror(errno));
return -1;
}
// Close the object
close(fd);
// Read the dynamic table
read_dynamic_table([&] (size_t val) { return memloc + val; });
//Read the copy relocations of the main executable
if(this == loader.main_executable() && read_copy_relocations(loader) < 0) {
Log::err("Failed to read copy relocations of ", name_cstr, ": ", strerror(errno));
return -1;
}
//Load the required libraries
for(auto& library_name : required_libraries) {
//Open the library
auto* library = loader.open_library(library_name);
if(library == nullptr) {
Log::err("Failed to open required library ", library_name, ": ", strerror(errno));
return -1;
}
//Load the library
if(library->load(loader, library_name) < 0) {
Log::err("Failed to load required library ", library_name, ": ", strerror(errno));
}
}
loaded = true;
return 0;
}
Duck::Result Object::load_for_debugger() {
if(loaded)
return Duck::Result("Already loaded");
if(read_headers() < 0)
return Duck::Result("Failed to read headers");
if (calculate_memsz() < 0)
return Duck::Result("Failed to calculate memsize");
if (load_dynamic_table() < 0)
return Duck::Result("Failed to load dynamic table");
read_section_headers();
return Duck::Result::SUCCESS;
}
int Object::read_headers() {
header = (elf32_ehdr*) mapped_file;
if(*((uint32_t*)header->e_ident) != ELF_MAGIC) {
errno = ENOEXEC;
return -1;
}
pheaders.resize(header->e_phnum);
for(size_t i = 0; i < pheaders.size(); i++)
pheaders[i] = *((elf32_pheader*) (mapped_file + header->e_phoff + i * header->e_phentsize));
sheaders.resize(header->e_shnum);
for(size_t i = 0; i < sheaders.size(); i++)
sheaders[i] = *((elf32_sheader*) (mapped_file + header->e_shoff + i * header->e_shentsize));
entry = reinterpret_cast<main_t>(header->e_entry);
return 0;
}
int Object::calculate_memsz() {
size_t base = -1;
size_t brk = 0;
for(auto& pheader : pheaders) {
if(pheader.p_type != PT_LOAD)
continue;
if(pheader.p_vaddr < base)
base = pheader.p_vaddr;
if(pheader.p_vaddr + pheader.p_memsz > brk)
brk = pheader.p_vaddr + pheader.p_memsz;
}
if(base == (size_t) -1)
return -ENOEXEC;
memsz = brk - base;
calculated_base = base;
return 0;
}
int Object::load_dynamic_table() {
bool did_read = false;
for(auto& pheader : pheaders) {
if(pheader.p_type != PT_DYNAMIC)
continue;
did_read = true;
size_t num_dyn = pheader.p_filesz / sizeof(elf32_dynamic);
size_t original_size = dynamic_table.size();
dynamic_table.resize(original_size + num_dyn);
memcpy(dynamic_table.data() + original_size, (elf32_dynamic*) (mapped_file + pheader.p_offset), pheader.p_filesz);
}
return did_read ? 0 : -1;
}
void Object::read_dynamic_table(std::function<size_t(size_t)> lookup) {
for(auto& dynamic : dynamic_table) {
switch(dynamic.d_tag) {
case DT_HASH:
hash = (uint32_t*) lookup(dynamic.d_val);
//Size of symbol table should be the same as the number of entries in the symbol hash table
dsym_table_size = hash[1];
break;
case DT_STRTAB:
dstring_table = (char*) lookup(dynamic.d_val);
break;
case DT_SYMTAB:
dsym_table = (elf32_sym*) lookup(dynamic.d_val);
break;
case DT_STRSZ:
dstring_table_size = dynamic.d_val;
break;
case DT_INIT:
init_func = (void(*)()) lookup(dynamic.d_val);
break;
case DT_INIT_ARRAY:
init_array = (void(**)()) lookup(dynamic.d_val);
break;
case DT_INIT_ARRAYSZ:
init_array_size = dynamic.d_val / sizeof(uintptr_t);
default:
break;
}
}
//Now that the string table is loaded, we can iterate again and find the required libraries
required_libraries.resize(0);
for(auto& dynamic : dynamic_table) {
if(dynamic.d_tag == DT_NEEDED)
required_libraries.push_back(dstring_table + dynamic.d_val);
}
}
void Object::read_section_headers() {
if (header->e_shstrndx != 0) {
auto& sh = sheaders[header->e_shstrndx];
section_header_string_table = (char*) (mapped_file + sh.sh_offset);
section_header_string_table_size = sh.sh_size;
}
for(size_t i = 0; i < sheaders.size(); i++) {
auto& sh = sheaders[i];
switch(sh.sh_type) {
case SHT_SYMTAB:
sym_table = (elf32_sym*) (mapped_file + sh.sh_offset);
sym_table_size = sh.sh_size / sh.sh_entsize;
break;
case SHT_STRTAB:
if (i == header->e_shstrndx)
break;
if (!section_header_string_table || strcmp(§ion_header_string_table[sh.sh_name], ".strtab"))
break;
string_table = (char*) (mapped_file + sh.sh_offset);
string_table_size = sh.sh_size;
break;
default:
break;
}
}
}
int Object::load_sections() {
for(auto& pheader : pheaders) {
if(pheader.p_type != PT_LOAD)
continue;
// Allocate memory for the section
size_t vaddr_mod = pheader.p_vaddr % PAGE_SIZE;
size_t round_memloc = memloc + pheader.p_vaddr - vaddr_mod;
size_t round_size = ((pheader.p_memsz + vaddr_mod + PAGE_SIZE - 1) / PAGE_SIZE) * PAGE_SIZE;
// if(mmap((void*) round_memloc, round_size, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_FIXED, 0, 0) == MAP_FAILED)
// Duck::Log::errf("ld: Failed to allocate memory for section at {#x}->{#x}: {}", pheader.p_vaddr, pheader.p_vaddr + pheader.p_memsz, strerror(errno));
// lseek(fd, pheader.p_offset, SEEK_SET);
// read(fd, (void*) (memloc + pheader.p_vaddr), pheader.p_filesz);
// Map the section into memory
size_t round_offset = pheader.p_offset - vaddr_mod;
size_t round_filesz = ((pheader.p_filesz + vaddr_mod + PAGE_SIZE - 1) / PAGE_SIZE) * PAGE_SIZE;
if(mmap((void*) round_memloc, round_filesz, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_PRIVATE, fd, round_offset) == MAP_FAILED)
Duck::Log::errf("ld: Failed to allocate memory for section at {#x}->{#x}: {}", pheader.p_vaddr, pheader.p_vaddr + pheader.p_memsz, strerror(errno));
if(pheader.p_memsz != pheader.p_filesz)
if(mmap_named((void*) (round_memloc + round_filesz), round_size - round_filesz, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_FIXED, 0, 0, name.c_str()) == MAP_FAILED)
Duck::Log::errf("ld: Failed to allocate memory for section at {#x}->{#x}: {}", pheader.p_vaddr, pheader.p_vaddr + pheader.p_memsz, strerror(errno));
// Zero out the remaining bytes
size_t bytes_left = pheader.p_memsz - pheader.p_filesz;
if(bytes_left)
memset((void*) (memloc + pheader.p_vaddr + pheader.p_filesz), 0, bytes_left);
}
return 0;
}
void Object::mprotect_sections() {
for(auto& pheader : pheaders) {
if(pheader.p_type != PT_LOAD)
continue;
size_t vaddr_mod = pheader.p_vaddr % PAGE_SIZE;
size_t round_memloc = memloc + pheader.p_vaddr - vaddr_mod;
size_t round_size = ((pheader.p_memsz + vaddr_mod + PAGE_SIZE - 1) / PAGE_SIZE) * PAGE_SIZE;
int mmap_prot =
((pheader.p_flags & PF_R) ? PROT_READ : 0) |
((pheader.p_flags & PF_W) ? PROT_WRITE : 0) |
((pheader.p_flags & PF_X) ? PROT_EXEC : 0);
mprotect((void*) round_memloc, round_size, mmap_prot);
}
}
int Object::read_copy_relocations(Loader& loader) {
//In the relocation table, find all of the copy relocations (ELF32_R_TYPE == STT_COMMON) and put them in the global symbols
for(auto& shdr : sheaders) {
if(shdr.sh_type != SHT_REL)
continue;
auto* rel_table = (elf32_rel*) (shdr.sh_addr + memloc);
for(size_t i = 0; i < shdr.sh_size / sizeof(elf32_rel); i++) {
auto& rel = rel_table[i];
if(ELF32_R_TYPE(rel.r_info) == R_386_COPY) {
auto& symbol = dsym_table[ELF32_R_SYM(rel.r_info)];
auto* symbol_name = (char*)((uintptr_t)dstring_table + symbol.st_name);
loader.set_global_symbol(symbol_name, rel.r_offset);
}
}
}
return 0;
}
int Object::read_symbols(Loader& loader) {
//Put all the symbols into the symbols map if they aren't there already
for(size_t i = 0; i < dsym_table_size; i++) {
auto* symbol = &dsym_table[i];
char* symbol_name = (char*)((uintptr_t) dstring_table + symbol->st_name);
if(symbol->st_shndx && !loader.get_symbol(symbol_name)) {
loader.set_symbol(symbol_name, symbol->st_value + memloc);
}
}
return 0;
}
int Object::relocate(Loader& loader) {
//Relocate the symbols
for(auto& shdr : sheaders) {
if(shdr.sh_type != SHT_REL)
continue;
auto* rel_table = (elf32_rel*) (shdr.sh_addr + memloc);
for(size_t i = 0; i < shdr.sh_size / sizeof(elf32_rel); i++) {
auto& rel = rel_table[i];
uint8_t rel_type = ELF32_R_TYPE(rel.r_info);
uint32_t rel_symbol = ELF32_R_SYM(rel.r_info);
if(rel_type == R_386_NONE)
continue;
auto& symbol = dsym_table[rel_symbol];
uintptr_t symbol_loc = memloc + symbol.st_value;
char* symbol_name = (char *)((uintptr_t) dstring_table + symbol.st_name);
//If this kind of relocation is a symbol, look it up
if(rel_type == R_386_32 || rel_type == R_386_PC32 || rel_type == R_386_COPY || rel_type == R_386_GLOB_DAT || rel_type == R_386_JMP_SLOT) {
if(symbol_name) {
auto sym = loader.get_symbol(symbol_name);
if(!sym) {
if(loader.debug_mode())
Log::warn("Symbol ", symbol_name, " not found for ", name);
symbol_loc = 0x0;
} else {
symbol_loc = sym;
}
}
}
//If this is a global symbol or weak, try finding it in the global symbol table
if(rel_type == R_386_GLOB_DAT || (ELF32_ST_BIND(symbol.st_info) == STB_WEAK && !symbol_loc)) {
if(symbol_name) {
auto sym = loader.get_global_symbol(symbol_name);
if(sym) {
symbol_loc = sym;
}
}
}
//Perform the actual relocation
auto* reloc_loc = (void*) (memloc + rel.r_offset);
switch(rel_type) {
case R_386_32:
symbol_loc += *((ssize_t*) reloc_loc);
*((uintptr_t*)reloc_loc) = (uintptr_t) symbol_loc;
break;
case R_386_PC32:
symbol_loc += *((ssize_t*) reloc_loc);
symbol_loc -= memloc + rel.r_offset;
*((uintptr_t*)reloc_loc) = (uintptr_t) symbol_loc;
break;
case R_386_COPY:
memcpy(reloc_loc, (const void*) symbol_loc, symbol.st_size);
break;
case R_386_GLOB_DAT:
case R_386_JMP_SLOT:
*((uintptr_t*) reloc_loc) = (uintptr_t) symbol_loc;
break;
case R_386_RELATIVE:
symbol_loc = memloc + *((ssize_t*) reloc_loc);
*((uintptr_t*) reloc_loc) = (uintptr_t) symbol_loc;
break;
default:
if(loader.debug_mode())
Log::warn("Unknown relocation type ", (int) rel_type, " for ", (int) rel_symbol);
break;
}
}
}
return 0;
}
uintptr_t Object::get_dynamic_symbol(const char* name) {
for(size_t i = 0; i < dsym_table_size; i++) {
auto* symbol = &dsym_table[i];
char* symbol_name = (char*)((uintptr_t) dstring_table + symbol->st_name);
if (!strcmp(symbol_name, name))
return symbol->st_value + memloc;
}
return 0;
}
Object::SymbolInfo Object::symbolicate(uintptr_t offset) {
// Symbols in executables have an absolute address
if (header->e_type == ET_EXEC)
offset += memloc;
elf32_sym* best_match = nullptr;
for(size_t i = 0; i < sym_table_size; i++) {
auto* symbol = &sym_table[i];
if (symbol->st_value > offset || ELF32_ST_TYPE(symbol->st_info) == STT_SECTION || *(const char*)((uintptr_t) string_table + symbol->st_name) == '.')
continue;
if (!best_match || symbol->st_value > best_match->st_value)
best_match = symbol;
}
if (!best_match)
return {.name = nullptr, .offset = 0};
return {
.name = (const char*)((uintptr_t) string_table + best_match->st_name),
.offset = offset - best_match->st_value
};
}