| ... | @@ -1,6 +1,8 @@ | ... | @@ -1,6 +1,8 @@ |
| 1 | const std = @import("../../std.zig"); | 1 | const std = @import("../../std.zig"); |
| 2 | const builtin = @import("builtin"); | 2 | const builtin = @import("builtin"); |
| 3 | const linux = std.os.linux; | 3 | const linux = std.os.linux; |
| | 4 | const mem = std.mem; |
| | 5 | const elf = std.elf; |
| 4 | const expect = std.testing.expect; | 6 | const expect = std.testing.expect; |
| 5 | | 7 | |
| 6 | test "getpid" { | 8 | test "getpid" { |
| ... | @@ -42,3 +44,42 @@ test "timer" { | ... | @@ -42,3 +44,42 @@ test "timer" { |
| 42 | // TODO implicit cast from *[N]T to [*]T | 44 | // TODO implicit cast from *[N]T to [*]T |
| 43 | err = linux.epoll_wait(@intCast(i32, epoll_fd), @ptrCast([*]linux.epoll_event, &events), 8, -1); | 45 | err = linux.epoll_wait(@intCast(i32, epoll_fd), @ptrCast([*]linux.epoll_event, &events), 8, -1); |
| 44 | } | 46 | } |
| | 47 | |
| | 48 | export fn iter_fn(info: *linux.dl_phdr_info, size: usize, data: ?*usize) i32 { |
| | 49 | var counter = data.?; |
| | 50 | // Count how many libraries are loaded |
| | 51 | counter.* += usize(1); |
| | 52 | |
| | 53 | // The image should contain at least a PT_LOAD segment |
| | 54 | if (info.dlpi_phnum < 1) return -1; |
| | 55 | |
| | 56 | // Quick & dirty validation of the phdr pointers, make sure we're not |
| | 57 | // pointing to some random gibberish |
| | 58 | var i: usize = 0; |
| | 59 | var found_load = false; |
| | 60 | while (i < info.dlpi_phnum) : (i += 1) { |
| | 61 | const phdr = info.dlpi_phdr[i]; |
| | 62 | |
| | 63 | if (phdr.p_type != elf.PT_LOAD) continue; |
| | 64 | |
| | 65 | // Find the ELF header |
| | 66 | const elf_header = @intToPtr(*elf.Ehdr, phdr.p_vaddr - phdr.p_offset); |
| | 67 | // Validate the magic |
| | 68 | if (!mem.eql(u8, elf_header.e_ident[0..], "\x7fELF")) return -1; |
| | 69 | // Consistency check |
| | 70 | if (elf_header.e_phnum != info.dlpi_phnum) return -1; |
| | 71 | |
| | 72 | found_load = true; |
| | 73 | break; |
| | 74 | } |
| | 75 | |
| | 76 | if (!found_load) return -1; |
| | 77 | |
| | 78 | return 42; |
| | 79 | } |
| | 80 | |
| | 81 | test "dl_iterate_phdr" { |
| | 82 | var counter: usize = 0; |
| | 83 | expect(linux.dl_iterate_phdr(usize, iter_fn, &counter) != 0); |
| | 84 | expect(counter != 0); |
| | 85 | } |