Skip to content

Commit

Permalink
Basic PE parser
Browse files Browse the repository at this point in the history
  • Loading branch information
Arnau478 committed May 12, 2024
1 parent 1ae8f13 commit 9bd92a7
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/parser.zig
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const PaletteColor = @import("main.zig").PaletteColor;

pub const parsers = &.{
@import("parsers/elf.zig"),
@import("parsers/pe.zig"),
@import("parsers/data.zig"),
};

Expand Down Expand Up @@ -34,3 +35,9 @@ pub fn getColors(allocator: std.mem.Allocator, reader: std.io.AnyReader, options

@panic("No parser matched");
}

test {
inline for (parsers) |parser| {
_ = parser;
}
}
57 changes: 57 additions & 0 deletions src/parsers/pe.zig
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
const std = @import("std");
const PaletteColor = @import("../main.zig").PaletteColor;

const DosHeader = packed struct(u512) {
magic: u16,
cblp: u16,
cp: u16,
crlc: u16,
cparhdr: u16,
minalloc: u16,
maxalloc: u16,
ss: u16,
sp: u16,
csum: u16,
ip: u16,
cs: u16,
lfarlc: u16,
ovno: u16,
rsv_a: u64 = 0,
oemid: u16,
oeminfo: u16,
rsv_b: u160 = 0,
lfanew: u32,
};

const PeHeader = extern struct {
signature: u32,
file_header: std.coff.CoffHeader,
};

pub fn matches(data: []const u8) bool {
return std.mem.startsWith(u8, data, "MZ");
}

fn setRange(colors: []PaletteColor, offset: usize, len: usize, color: PaletteColor) void {
@memset(colors[offset .. offset + len], color);
}

pub fn getColors(colors: []PaletteColor, data: []const u8) void {
@memset(colors, .normal_alt);

var fbs = std.io.fixedBufferStream(data);
const reader = fbs.reader();

const dos_header = reader.readStruct(DosHeader) catch return;
setRange(colors, 0, @sizeOf(DosHeader), .c1);

fbs.pos = dos_header.lfanew;

setRange(colors, fbs.pos, @sizeOf(PeHeader), .c2_alt);
setRange(colors, fbs.pos + @offsetOf(PeHeader, "file_header"), @sizeOf(std.coff.CoffHeader), .c2);

const pe_header = reader.readStruct(PeHeader) catch return;
_ = pe_header;

setRange(colors, 0, 64, .c1);
}

0 comments on commit 9bd92a7

Please sign in to comment.