Dream of my own C compiler
This commit is contained in:
34
packages/cjit/src/Sections.zig
Normal file
34
packages/cjit/src/Sections.zig
Normal file
@@ -0,0 +1,34 @@
|
||||
const std = @import("std");
|
||||
|
||||
text: Section = .{ .read_only = true, .executable = true },
|
||||
data: Section = .{ .read_only = false, .executable = false },
|
||||
rodata: Section = .{ .read_only = true, .executable = false },
|
||||
bss: usize,
|
||||
|
||||
pub const Section = struct {
|
||||
data: std.ArrayList(u8) = .{},
|
||||
read_only: bool,
|
||||
executable: bool,
|
||||
|
||||
pub fn writeValue(self: *Section, value: anytype, allocator: std.mem.Allocator) !void {
|
||||
const T = @TypeOf(value);
|
||||
std.debug.assert(std.meta.hasUniqueRepresentation(T));
|
||||
const bytes = std.mem.asBytes(&value);
|
||||
const alignment = @alignOf(T);
|
||||
|
||||
try self.alignForward(alignment, allocator);
|
||||
try self.writeBytes(bytes, allocator);
|
||||
}
|
||||
|
||||
pub fn writeBytes(self: *Section, data: []const u8, allocator: std.mem.Allocator) !void {
|
||||
try self.data.appendSlice(allocator, data);
|
||||
}
|
||||
|
||||
pub fn alignForward(self: *Section, alignment: u16, allocator: std.mem.Allocator) !void {
|
||||
const ptr = self.data.items.len;
|
||||
const ptr_aligned = std.mem.alignForward(usize, ptr, alignment);
|
||||
const padding = ptr_aligned - ptr;
|
||||
|
||||
try self.data.appendNTimes(allocator, 0, padding);
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user