Debian Codegraph @

debug/image/open.ha

raw
1 // SPDX-License-Identifier: MPL-2.0
2 // (c) Hare authors <https://harelang.org>
3
4 use format::elf;
5 use format::elf::{shn};
6 use io;
7
8 export type image = struct {
9 fd: io::file,
10 data: []u8,
11 header: *elf::header64,
12 // Cached sections
13 shstrtab: nullable *elf::section64,
14 symtab: nullable *elf::section64,
15 strtab: nullable *elf::section64,
16 debug_abbr: nullable *elf::section64,
17 debug_aranges: nullable *elf::section64,
18 debug_info: nullable *elf::section64,
19 debug_line: nullable *elf::section64,
20 debug_str: nullable *elf::section64,
21 };
22
23 // Opens an [[io::file]] as a program image.
24 export fn open(
25 file: io::file,
26 ) (image | io::error) = {
27 const orig = io::tell(file)?;
28 io::seek(file, 0, io::whence::END)?;
29 const length = io::tell(file)?: size;
30 io::seek(file, orig, io::whence::SET)?;
31
32 const base = io::mmap(null, length,
33 io::prot::READ,
34 io::mflag::PRIVATE,
35 file, 0z)?;
36
37 const data = (base: *[*]u8)[..length];
38 const head = base: *elf::header64;
39
40 let shstrtab: nullable *elf::section64 = null;
41 if (head.e_shstrndx != shn::UNDEF) {
42 const shoffs = head.e_shoff + head.e_shstrndx * head.e_shentsize;
43 shstrtab = &data[shoffs]: *elf::section64;
44 };
45
46 return image {
47 fd = file,
48 data = data,
49 header = head,
50 shstrtab = shstrtab,
51 ...
52 };
53 };
54
55 // Closes a program [[image]].
56 export fn close(image: *image) void = {
57 io::munmap(&image.data[0], len(image.data))!;
58 io::close(image.fd)!;
59 };