zig/lib/std/dynamic_library.zig

351 lines
11 KiB
Zig
Raw Normal View History

const builtin = @import("builtin");
2018-09-27 14:51:22 -07:00
2019-03-02 13:46:04 -08:00
const std = @import("std.zig");
const mem = std.mem;
2018-09-27 14:51:22 -07:00
const os = std.os;
const assert = std.debug.assert;
const testing = std.testing;
2018-09-27 14:51:22 -07:00
const elf = std.elf;
2019-05-26 20:35:26 -07:00
const windows = std.os.windows;
const system = std.os.system;
const maxInt = std.math.maxInt;
pub const DynLib = switch (builtin.os) {
.linux => if (builtin.link_libc) DlDynlib else LinuxDynLib,
2019-05-24 19:52:07 -07:00
.windows => WindowsDynLib,
.macosx, .tvos, .watchos, .ios => DlDynlib,
else => void,
};
2019-05-05 03:14:53 -07:00
// The link_map structure is not completely specified beside the fields
// reported below, any libc is free to store additional data in the remaining
// space.
// An iterator is provided in order to traverse the linked list in a idiomatic
// fashion.
2019-04-24 11:54:17 -07:00
const LinkMap = extern struct {
l_addr: usize,
2019-05-05 03:14:53 -07:00
l_name: [*]const u8,
l_ld: ?*elf.Dyn,
l_next: ?*LinkMap,
l_prev: ?*LinkMap,
2019-04-24 11:54:17 -07:00
pub const Iterator = struct {
2019-05-05 03:14:53 -07:00
current: ?*LinkMap,
2019-04-24 11:54:17 -07:00
2019-05-05 03:14:53 -07:00
fn end(self: *Iterator) bool {
return self.current == null;
2019-04-24 11:54:17 -07:00
}
fn next(self: *Iterator) ?*LinkMap {
2019-05-05 03:14:53 -07:00
if (self.current) |it| {
self.current = it.l_next;
return it;
2019-04-24 11:54:17 -07:00
}
return null;
}
};
};
const RDebug = extern struct {
r_version: i32,
2019-05-05 03:14:53 -07:00
r_map: ?*LinkMap,
2019-04-24 11:54:17 -07:00
r_brk: usize,
r_ldbase: usize,
};
fn elf_get_va_offset(phdrs: []elf.Phdr) !usize {
for (phdrs) |*phdr| {
if (phdr.p_type == elf.PT_LOAD) {
return @ptrToInt(phdr) - phdr.p_vaddr;
}
}
return error.InvalidExe;
}
pub fn linkmap_iterator(phdrs: []elf.Phdr) !LinkMap.Iterator {
const va_offset = try elf_get_va_offset(phdrs);
const dyn_table = init: {
for (phdrs) |*phdr| {
if (phdr.p_type == elf.PT_DYNAMIC) {
const ptr = @intToPtr([*]elf.Dyn, va_offset + phdr.p_vaddr);
2019-05-12 09:56:01 -07:00
break :init ptr[0 .. phdr.p_memsz / @sizeOf(elf.Dyn)];
2019-04-24 11:54:17 -07:00
}
}
// No PT_DYNAMIC means this is either a statically-linked program or a
// badly corrupted one
2019-05-12 09:56:01 -07:00
return LinkMap.Iterator{ .current = null };
2019-04-24 11:54:17 -07:00
};
const link_map_ptr = init: {
for (dyn_table) |*dyn| {
switch (dyn.d_tag) {
elf.DT_DEBUG => {
const r_debug = @intToPtr(*RDebug, dyn.d_un.d_ptr);
if (r_debug.r_version != 1) return error.InvalidExe;
break :init r_debug.r_map;
},
elf.DT_PLTGOT => {
const got_table = @intToPtr([*]usize, dyn.d_un.d_ptr);
// The address to the link_map structure is stored in the
// second slot
2019-05-05 03:14:53 -07:00
break :init @intToPtr(?*LinkMap, got_table[1]);
2019-04-24 11:54:17 -07:00
},
2019-05-12 09:56:01 -07:00
else => {},
2019-04-24 11:54:17 -07:00
}
}
return error.InvalidExe;
};
2019-05-12 09:56:01 -07:00
return LinkMap.Iterator{ .current = link_map_ptr };
2019-04-24 11:54:17 -07:00
}
pub const LinuxDynLib = struct {
pub const Error = ElfLib.Error;
elf_lib: ElfLib,
fd: i32,
2019-05-26 20:35:26 -07:00
memory: []align(mem.page_size) u8,
/// Trusts the file
pub fn open(path: []const u8) !LinuxDynLib {
2019-05-28 09:18:30 -07:00
const fd = try os.open(path, 0, os.O_RDONLY | os.O_CLOEXEC);
errdefer os.close(fd);
// TODO remove this @intCast
2019-05-26 20:35:26 -07:00
const size = @intCast(usize, (try os.fstat(fd)).size);
2019-05-26 20:35:26 -07:00
const bytes = try os.mmap(
null,
mem.alignForward(size, mem.page_size),
2019-05-24 19:52:07 -07:00
os.PROT_READ | os.PROT_EXEC,
2019-05-23 00:06:34 -07:00
os.MAP_PRIVATE,
fd,
0,
);
2019-05-26 20:35:26 -07:00
errdefer os.munmap(bytes);
return LinuxDynLib{
.elf_lib = try ElfLib.init(bytes),
.fd = fd,
2019-05-26 20:35:26 -07:00
.memory = bytes,
};
}
pub fn close(self: *LinuxDynLib) void {
2019-05-26 20:35:26 -07:00
os.munmap(self.memory);
os.close(self.fd);
self.* = undefined;
}
pub fn lookup(self: *LinuxDynLib, comptime T: type, name: []const u8) ?T {
if (self.elf_lib.lookup("", name)) |symbol| {
return @ptrCast(T, symbol);
} else {
return null;
}
}
};
pub const ElfLib = struct {
strings: [*:0]u8,
pub const Error = error{
NotElfFile,
NotDynamicLibrary,
MissingDynamicLinkingInformation,
BaseNotFound,
ElfStringSectionNotFound,
ElfSymSectionNotFound,
ElfHashTableNotFound,
};
strings: [*]u8,
syms: [*]elf.Sym,
2019-05-24 19:52:07 -07:00
hashtab: [*]os.Elf_Symndx,
versym: ?[*]u16,
verdef: ?*elf.Verdef,
base: usize,
// Trusts the memory
pub fn init(bytes: []align(@alignOf(elf.Ehdr)) u8) !ElfLib {
const eh = @ptrCast(*elf.Ehdr, bytes.ptr);
if (!mem.eql(u8, eh.e_ident[0..4], "\x7fELF")) return error.NotElfFile;
if (eh.e_type != elf.ET.DYN) return error.NotDynamicLibrary;
const elf_addr = @ptrToInt(bytes.ptr);
var ph_addr: usize = elf_addr + eh.e_phoff;
var base: usize = maxInt(usize);
var maybe_dynv: ?[*]usize = null;
{
var i: usize = 0;
while (i < eh.e_phnum) : ({
i += 1;
ph_addr += eh.e_phentsize;
}) {
const ph = @intToPtr(*elf.Phdr, ph_addr);
switch (ph.p_type) {
elf.PT_LOAD => base = elf_addr + ph.p_offset - ph.p_vaddr,
elf.PT_DYNAMIC => maybe_dynv = @intToPtr([*]usize, elf_addr + ph.p_offset),
else => {},
}
}
}
const dynv = maybe_dynv orelse return error.MissingDynamicLinkingInformation;
if (base == maxInt(usize)) return error.BaseNotFound;
var maybe_strings: ?[*:0]u8 = null;
var maybe_syms: ?[*]elf.Sym = null;
2019-05-24 19:52:07 -07:00
var maybe_hashtab: ?[*]os.Elf_Symndx = null;
var maybe_versym: ?[*]u16 = null;
var maybe_verdef: ?*elf.Verdef = null;
{
var i: usize = 0;
while (dynv[i] != 0) : (i += 2) {
const p = base + dynv[i + 1];
switch (dynv[i]) {
elf.DT_STRTAB => maybe_strings = @intToPtr([*:0]u8, p),
elf.DT_SYMTAB => maybe_syms = @intToPtr([*]elf.Sym, p),
2019-05-24 19:52:07 -07:00
elf.DT_HASH => maybe_hashtab = @intToPtr([*]os.Elf_Symndx, p),
elf.DT_VERSYM => maybe_versym = @intToPtr([*]u16, p),
elf.DT_VERDEF => maybe_verdef = @intToPtr(*elf.Verdef, p),
else => {},
}
}
}
return ElfLib{
.base = base,
.strings = maybe_strings orelse return error.ElfStringSectionNotFound,
.syms = maybe_syms orelse return error.ElfSymSectionNotFound,
.hashtab = maybe_hashtab orelse return error.ElfHashTableNotFound,
.versym = maybe_versym,
.verdef = maybe_verdef,
};
}
/// Returns the address of the symbol
pub fn lookup(self: *const ElfLib, vername: []const u8, name: []const u8) ?usize {
const maybe_versym = if (self.verdef == null) null else self.versym;
const OK_TYPES = (1 << elf.STT_NOTYPE | 1 << elf.STT_OBJECT | 1 << elf.STT_FUNC | 1 << elf.STT_COMMON);
const OK_BINDS = (1 << elf.STB_GLOBAL | 1 << elf.STB_WEAK | 1 << elf.STB_GNU_UNIQUE);
var i: usize = 0;
while (i < self.hashtab[1]) : (i += 1) {
2019-11-06 20:25:57 -08:00
if (0 == (@as(u32, 1) << @intCast(u5, self.syms[i].st_info & 0xf) & OK_TYPES)) continue;
if (0 == (@as(u32, 1) << @intCast(u5, self.syms[i].st_info >> 4) & OK_BINDS)) continue;
if (0 == self.syms[i].st_shndx) continue;
2019-05-26 10:17:34 -07:00
if (!mem.eql(u8, name, mem.toSliceConst(u8, self.strings + self.syms[i].st_name))) continue;
if (maybe_versym) |versym| {
if (!checkver(self.verdef.?, versym[i], vername, self.strings))
continue;
}
return self.base + self.syms[i].st_value;
}
return null;
}
};
fn checkver(def_arg: *elf.Verdef, vsym_arg: i32, vername: []const u8, strings: [*:0]u8) bool {
var def = def_arg;
const vsym = @bitCast(u32, vsym_arg) & 0x7fff;
while (true) {
if (0 == (def.vd_flags & elf.VER_FLG_BASE) and (def.vd_ndx & 0x7fff) == vsym)
break;
if (def.vd_next == 0)
return false;
def = @intToPtr(*elf.Verdef, @ptrToInt(def) + def.vd_next);
}
const aux = @intToPtr(*elf.Verdaux, @ptrToInt(def) + def.vd_aux);
2019-05-26 10:17:34 -07:00
return mem.eql(u8, vername, mem.toSliceConst(u8, strings + aux.vda_name));
}
pub const WindowsDynLib = struct {
pub const Error = error{FileNotFound};
dll: windows.HMODULE,
2019-05-27 08:12:07 -07:00
pub fn open(path: []const u8) !WindowsDynLib {
2019-05-28 09:18:30 -07:00
const wpath = try windows.sliceToPrefixedFileW(path);
return WindowsDynLib{
2019-05-28 09:18:30 -07:00
.dll = try windows.LoadLibraryW(&wpath),
};
}
pub fn close(self: *WindowsDynLib) void {
2019-05-26 20:35:26 -07:00
windows.FreeLibrary(self.dll);
self.* = undefined;
}
pub fn lookupC(self: *WindowsDynLib, comptime T: type, name: [*:0]const u8) ?T {
if (windows.kernel32.GetProcAddress(self.dll, name)) |addr| {
return @ptrCast(T, addr);
} else {
return null;
}
}
pub fn lookup(self: *DlDynlib, comptime T: type, comptime max_name_len: usize, name: []const u8) ?T {
const c_name: [max_name_len]u8 = undefined;
mem.copy(&c_name, name);
c_name[name.len] = 0;
return self.lookupC(T, &c_name);
}
};
pub const DlDynlib = struct {
pub const Error = error{FileNotFound};
handle: *c_void,
pub fn open(path: []const u8) !DlDynlib {
if (!builtin.link_libc and !os.darwin.is_the_target) {
@compileError("DlDynlib requires libc");
}
return DlDynlib{
.handle = system.dlopen(path.ptr, system.RTLD_LAZY) orelse {
return error.FileNotFound;
},
};
}
pub fn close(self: *DlDynlib) void {
_ = system.dlclose(self.handle);
self.* = undefined;
}
pub fn lookupC(self: *DlDynlib, comptime T: type, name: [*:0]const u8) ?T {
if (system.dlsym(self.handle, name)) |symbol| {
return @ptrCast(T, symbol);
} else {
return null;
}
}
pub fn lookup(self: *DlDynlib, comptime T: type, comptime max_name_len: usize, name: []const u8) ?T {
const c_name: [max_name_len]u8 = undefined;
mem.copy(&c_name, name);
c_name[name.len] = 0;
return self.lookupC(T, &c_name);
}
};
2018-09-27 14:51:22 -07:00
test "dynamic_library" {
const libname = switch (builtin.os) {
2019-05-24 19:52:07 -07:00
.linux => "invalid_so.so",
.windows => "invalid_dll.dll",
.macosx, .tvos, .watchos, .ios => "invalid_dylib.dylib",
else => return,
2018-09-27 14:51:22 -07:00
};
2019-05-27 08:12:07 -07:00
const dynlib = DynLib.open(libname) catch |err| {
testing.expect(err == error.FileNotFound);
2018-09-27 14:51:22 -07:00
return;
};
}