Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

elf: add support for -static -pie #66

Merged
merged 4 commits into from
Jul 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,5 @@ jobs:
version: master
- run: zig version
- run: zig fmt --check src
- run: zig build test --summary all -Dhas_static
- run: zig build test --summary all -Dhas-static -Dhas-static-pie

4 changes: 3 additions & 1 deletion build.zig
Original file line number Diff line number Diff line change
Expand Up @@ -68,11 +68,13 @@ pub fn build(b: *std.Build.Builder) void {
});
symlinks.step.dependOn(&install.step);

const has_static = b.option(bool, "has_static", "Whether the system compiler supports '-static' flag") orelse false;
const has_static = b.option(bool, "has-static", "Whether the system compiler supports '-static' flag") orelse false;
const has_static_pie = b.option(bool, "has-static-pie", "Whether the system compiler supports '-static -pie' flags") orelse false;

const test_step = b.step("test", "Run tests");
test_step.dependOn(@import("test/test.zig").addTests(b, exe, .{
.has_static = has_static,
.has_static_pie = has_static_pie,
}));
}

Expand Down
31 changes: 17 additions & 14 deletions src/Elf.zig
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ hash: HashSection = .{},
gnu_hash: GnuHashSection = .{},
got: GotSection = .{},
plt: PltSection = .{},
got_plt: GotPltSection = .{},
plt_got: PltGotSection = .{},
copy_rel: CopyRelSection = .{},
rela_dyn: std.ArrayListUnmanaged(elf.Elf64_Rela) = .{},
Expand Down Expand Up @@ -475,6 +476,13 @@ fn initSections(self: *Elf) !void {
.flags = elf.SHF_ALLOC | elf.SHF_WRITE,
.addralign = @alignOf(u64),
});

self.got_plt_sect_index = try self.addSection(.{
.name = ".got.plt",
.type = elf.SHT_PROGBITS,
.flags = elf.SHF_ALLOC | elf.SHF_WRITE,
.addralign = @alignOf(u64),
});
}

const needs_rela_dyn = blk: {
Expand All @@ -501,12 +509,6 @@ fn initSections(self: *Elf) !void {
.flags = elf.SHF_ALLOC | elf.SHF_EXECINSTR,
.addralign = 16,
});
self.got_plt_sect_index = try self.addSection(.{
.name = ".got.plt",
.type = elf.SHT_PROGBITS,
.flags = elf.SHF_ALLOC | elf.SHF_WRITE,
.addralign = @alignOf(u64),
});
self.rela_plt_sect_index = try self.addSection(.{
.name = ".rela.plt",
.type = elf.SHT_RELA,
Expand Down Expand Up @@ -667,13 +669,13 @@ fn calcSectionSizes(self: *Elf) !void {

if (self.plt_sect_index) |index| {
const shdr = &self.sections.items(.shdr)[index];
shdr.sh_size = self.plt.sizePlt();
shdr.sh_size = self.plt.size();
shdr.sh_addralign = 16;
}

if (self.got_plt_sect_index) |index| {
const shdr = &self.sections.items(.shdr)[index];
shdr.sh_size = self.plt.sizeGotPlt();
shdr.sh_size = self.got_plt.size(self);
shdr.sh_addralign = @alignOf(u64);
}

Expand Down Expand Up @@ -2107,17 +2109,17 @@ fn writeSyntheticSections(self: *Elf) !void {

if (self.plt_sect_index) |shndx| {
const shdr = self.sections.items(.shdr)[shndx];
var buffer = try std.ArrayList(u8).initCapacity(gpa, self.plt.sizePlt());
var buffer = try std.ArrayList(u8).initCapacity(gpa, self.plt.size());
defer buffer.deinit();
try self.plt.writePlt(self, buffer.writer());
try self.plt.write(self, buffer.writer());
try self.base.file.pwriteAll(buffer.items, shdr.sh_offset);
}

if (self.got_plt_sect_index) |shndx| {
const shdr = self.sections.items(.shdr)[shndx];
var buffer = try std.ArrayList(u8).initCapacity(gpa, self.plt.sizeGotPlt());
var buffer = try std.ArrayList(u8).initCapacity(gpa, self.got_plt.size(self));
defer buffer.deinit();
try self.plt.writeGotPlt(self, buffer.writer());
try self.got_plt.write(self, buffer.writer());
try self.base.file.pwriteAll(buffer.items, shdr.sh_offset);
}

Expand Down Expand Up @@ -2480,11 +2482,11 @@ pub inline fn getGotEntryAddress(self: *Elf, index: u32) u64 {
}

pub inline fn getPltEntryAddress(self: *Elf, index: u32) u64 {
return self.getSectionAddress(self.plt_sect_index.?) + PltSection.plt_preamble_size + index * 16;
return self.getSectionAddress(self.plt_sect_index.?) + PltSection.preamble_size + index * 16;
}

pub inline fn getGotPltEntryAddress(self: *Elf, index: u32) u64 {
return self.getSectionAddress(self.got_plt_sect_index.?) + PltSection.got_plt_preamble_size + index * @sizeOf(u64);
return self.getSectionAddress(self.got_plt_sect_index.?) + GotPltSection.preamble_size + index * @sizeOf(u64);
}

pub inline fn getPltGotEntryAddress(self: *Elf, index: u32) u64 {
Expand Down Expand Up @@ -2722,6 +2724,7 @@ const Elf = @This();
const File = @import("Elf/file.zig").File;
const GnuHashSection = synthetic.GnuHashSection;
const GotSection = synthetic.GotSection;
const GotPltSection = synthetic.GotPltSection;
const HashSection = synthetic.HashSection;
const InternalObject = @import("Elf/InternalObject.zig");
const LdScript = @import("Elf/LdScript.zig");
Expand Down
22 changes: 17 additions & 5 deletions src/Elf/Atom.zig
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,12 @@ pub fn scanRelocs(self: Atom, elf_file: *Elf) !void {
self.scanReloc(symbol, rel, getAbsRelocAction(symbol, elf_file), elf_file);
},

elf.R_X86_64_GOT32,
elf.R_X86_64_GOT64,
elf.R_X86_64_GOTPC32,
elf.R_X86_64_GOTPC64,
elf.R_X86_64_GOTPCREL,
elf.R_X86_64_GOTPCREL64,
elf.R_X86_64_GOTPCRELX,
elf.R_X86_64_REX_GOTPCRELX,
=> {
Expand Down Expand Up @@ -522,10 +527,15 @@ pub fn resolveRelocsAlloc(self: Atom, elf_file: *Elf, writer: anytype) !void {
// Address of the target symbol - can be address of the symbol within an atom or address of PLT stub.
const S = @as(i64, @intCast(target.getAddress(.{}, elf_file)));
// Address of the global offset table.
const GOT = if (elf_file.got_sect_index) |shndx|
@as(i64, @intCast(elf_file.getSectionAddress(shndx)))
else
0;
const GOT = blk: {
const shndx = if (elf_file.got_plt_sect_index) |shndx|
shndx
else if (elf_file.got_sect_index) |shndx|
shndx
else
null;
break :blk if (shndx) |index| @as(i64, @intCast(elf_file.getSectionAddress(index))) else 0;
};
// Relative offset to the start of the global offset table.
const G = @as(i64, @intCast(target.getGotAddress(elf_file))) - GOT;
// Address of the thread pointer.
Expand Down Expand Up @@ -561,10 +571,12 @@ pub fn resolveRelocsAlloc(self: Atom, elf_file: *Elf, writer: anytype) !void {
=> try cwriter.writeIntLittle(i32, @as(i32, @intCast(S + A - P))),

elf.R_X86_64_GOTPCREL => try cwriter.writeIntLittle(i32, @as(i32, @intCast(G + GOT + A - P))),
elf.R_X86_64_GOTPC32 => try cwriter.writeIntLittle(i32, @as(i32, @intCast(GOT + A - P))),
elf.R_X86_64_GOTPC64 => try cwriter.writeIntLittle(i64, GOT + A - P),

elf.R_X86_64_GOTPCRELX => {
if (!target.flags.import and !target.isIFunc(elf_file) and !target.isAbs(elf_file)) blk: {
relaxGotpcrelx(code[rel.r_offset - 3 ..]) catch break :blk;
relaxGotpcrelx(code[rel.r_offset - 2 ..]) catch break :blk;
try cwriter.writeIntLittle(i32, @as(i32, @intCast(S + A - P)));
continue;
}
Expand Down
67 changes: 35 additions & 32 deletions src/Elf/synthetic.zig
Original file line number Diff line number Diff line change
Expand Up @@ -649,12 +649,8 @@ pub const GotSection = struct {
var num: usize = 0;
for (got.symbols.items) |sym_index| {
const sym = elf_file.getSymbol(sym_index);
if (sym.flags.import) {
if (sym.flags.import or sym.isIFunc(elf_file) or (elf_file.options.pic and !sym.isAbs(elf_file)))
num += 1;
continue;
}
if (sym.isIFunc(elf_file)) num += 1;
if (elf_file.options.pic and !sym.isAbs(elf_file)) num += 1;
}
return num;
}
Expand Down Expand Up @@ -715,8 +711,7 @@ pub const PltSection = struct {
symbols: std.ArrayListUnmanaged(u32) = .{},
output_symtab_size: Elf.SymtabSize = .{},

pub const plt_preamble_size = 32;
pub const got_plt_preamble_size = 24;
pub const preamble_size = 32;

pub fn deinit(plt: *PltSection, allocator: Allocator) void {
plt.symbols.deinit(allocator);
Expand All @@ -733,15 +728,11 @@ pub const PltSection = struct {
try plt.symbols.append(elf_file.base.allocator, sym_index);
}

pub fn sizePlt(plt: PltSection) usize {
return plt_preamble_size + plt.symbols.items.len * 16;
}

pub fn sizeGotPlt(plt: PltSection) usize {
return got_plt_preamble_size + plt.symbols.items.len * 8;
pub fn size(plt: PltSection) usize {
return preamble_size + plt.symbols.items.len * 16;
}

pub fn writePlt(plt: PltSection, elf_file: *Elf, writer: anytype) !void {
pub fn write(plt: PltSection, elf_file: *Elf, writer: anytype) !void {
const plt_addr = elf_file.getSectionAddress(elf_file.plt_sect_index.?);
const got_plt_addr = elf_file.getSectionAddress(elf_file.got_plt_sect_index.?);
var preamble = [_]u8{
Expand All @@ -755,7 +746,7 @@ pub const PltSection = struct {
disp = @as(i64, @intCast(got_plt_addr + 16)) - @as(i64, @intCast(plt_addr + 14)) - 4;
mem.writeIntLittle(i32, preamble[14..][0..4], @as(i32, @intCast(disp)));
try writer.writeAll(&preamble);
try writer.writeByteNTimes(0xcc, plt_preamble_size - preamble.len);
try writer.writeByteNTimes(0xcc, preamble_size - preamble.len);

for (0..plt.symbols.items.len) |i| {
const target_addr = elf_file.getGotPltEntryAddress(@as(u32, @intCast(i)));
Expand All @@ -772,23 +763,6 @@ pub const PltSection = struct {
}
}

pub fn writeGotPlt(plt: PltSection, elf_file: *Elf, writer: anytype) !void {
{
// [0]: _DYNAMIC
const symbol = elf_file.getSymbol(elf_file.dynamic_index.?);
try writer.writeIntLittle(u64, symbol.value);
}
// [1]: 0x0
// [2]: 0x0
try writer.writeIntLittle(u64, 0x0);
try writer.writeIntLittle(u64, 0x0);
const plt_addr = elf_file.getSectionAddress(elf_file.plt_sect_index.?);
for (0..plt.symbols.items.len) |_| {
// [N]: .plt
try writer.writeIntLittle(u64, plt_addr);
}
}

pub fn addRela(plt: PltSection, elf_file: *Elf) !void {
try elf_file.rela_plt.ensureUnusedCapacity(elf_file.base.allocator, plt.numRela());
for (plt.symbols.items, 0..) |sym_index, i| {
Expand Down Expand Up @@ -844,6 +818,35 @@ pub const PltSection = struct {
}
};

pub const GotPltSection = struct {
pub const preamble_size = 24;

pub fn size(got_plt: GotPltSection, elf_file: *Elf) usize {
_ = got_plt;
return preamble_size + elf_file.plt.symbols.items.len * 8;
}

pub fn write(got_plt: GotPltSection, elf_file: *Elf, writer: anytype) !void {
_ = got_plt;
{
// [0]: _DYNAMIC
const symbol = elf_file.getSymbol(elf_file.dynamic_index.?);
try writer.writeIntLittle(u64, symbol.value);
}
// [1]: 0x0
// [2]: 0x0
try writer.writeIntLittle(u64, 0x0);
try writer.writeIntLittle(u64, 0x0);
if (elf_file.plt_sect_index) |shndx| {
const plt_addr = elf_file.getSectionAddress(shndx);
for (0..elf_file.plt.symbols.items.len) |_| {
// [N]: .plt
try writer.writeIntLittle(u64, plt_addr);
}
}
}
};

pub const PltGotSection = struct {
symbols: std.ArrayListUnmanaged(u32) = .{},
output_symtab_size: Elf.SymtabSize = .{},
Expand Down
32 changes: 32 additions & 0 deletions test/elf.zig
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pub fn addElfTests(b: *Build, opts: Options) *Step {
elf_step.dependOn(testDsoIfunc(b, opts));
elf_step.dependOn(testDsoPlt(b, opts));
elf_step.dependOn(testIfuncDynamic(b, opts));
elf_step.dependOn(testIfuncStaticPie(b, opts));
elf_step.dependOn(testHelloDynamic(b, opts));
elf_step.dependOn(testHelloStatic(b, opts));
elf_step.dependOn(testTlsStatic(b, opts));
Expand Down Expand Up @@ -232,6 +233,37 @@ fn testIfuncDynamic(b: *Build, opts: Options) *Step {
return test_step;
}

fn testIfuncStaticPie(b: *Build, opts: Options) *Step {
const test_step = b.step("test-elf-ifunc-static-pie", "");

if (!opts.has_static_pie) {
skipTestStep(test_step);
return test_step;
}

const exe = cc(b, null, opts);
exe.addSourceBytes(
\\void foo() __attribute__((ifunc("resolve_foo")));
\\void hello() {
\\ printf("Hello world\n");
\\}
\\void *resolve_foo() {
\\ return hello;
\\}
\\int main() {
\\ foo();
\\ return 0;
\\}
, "main.c");
exe.addArgs(&.{ "-fPIC", "-static", "-pie" });

const run = exe.run();
run.expectStdOutEqual("Hello world\n");
test_step.dependOn(run.step());

return test_step;
}

fn testHelloStatic(b: *Build, opts: Options) *Step {
const test_step = b.step("test-elf-hello-static", "");

Expand Down
3 changes: 3 additions & 0 deletions test/test.zig
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
pub fn addTests(b: *Build, comp: *Compile, build_opts: struct {
has_static: bool,
has_static_pie: bool,
}) *Step {
const test_step = b.step("test-system-tools", "Run all system tools tests");
test_step.dependOn(&comp.step);
Expand All @@ -14,6 +15,7 @@ pub fn addTests(b: *Build, comp: *Compile, build_opts: struct {
.zld = zld,
.sdk_path = sdk_path,
.has_static = build_opts.has_static,
.has_static_pie = build_opts.has_static_pie,
};

test_step.dependOn(macho.addMachOTests(b, opts));
Expand All @@ -26,6 +28,7 @@ pub const Options = struct {
zld: FileSourceWithDir,
sdk_path: ?std.zig.system.darwin.DarwinSDK = null,
has_static: bool = false,
has_static_pie: bool = false,
};

/// A system command that tracks the command itself via `cmd` Step.Run and output file
Expand Down