Fix leaky error handling + Zig fmt

This commit is contained in:
ktkk 2026-11-03 16:29:08 +00:00
parent 8e2cd4d7a2
commit 7bd22b7b80
8 changed files with 344 additions and 227 deletions

View file

@ -33,14 +33,14 @@ pub const ClassAccessFlags = EnumFlags(enum(u16) {
module = 0x8000,
});
pub const ParseError = std.Io.Reader.Error || std.mem.Allocator.Error || error {
pub const ParseError = std.Io.Reader.Error || std.mem.Allocator.Error || error{
InvalidMagicNumber,
InvalidTag,
InvalidOp,
InvalidArrayType,
};
pub const ResolveError = error {
pub const ResolveError = error{
InvalidConstantPoolIndex,
InvalidConstantType,
};
@ -121,8 +121,12 @@ fn parseFields(input: *std.Io.Reader, constant_pool: ConstantPool, allocator: st
const fields = try allocator.alloc(FieldInfo, fields_count);
errdefer allocator.free(fields);
var parsed: usize = 0;
errdefer for (0..parsed) |i| fields[i].deinit(allocator);
for (0..fields_count) |i| {
fields[i] = try FieldInfo.parse(input, constant_pool, allocator);
fields[i] = try .parse(input, constant_pool, allocator);
parsed += 1;
}
return fields;
@ -133,8 +137,12 @@ fn parseMethods(input: *std.Io.Reader, constant_pool: ConstantPool, allocator: s
const methods = try allocator.alloc(MethodInfo, methods_count);
errdefer allocator.free(methods);
var parsed: usize = 0;
errdefer for (0..parsed) |i| methods[i].deinit(allocator);
for (0..methods_count) |i| {
methods[i] = try .parse(input, constant_pool, allocator);
parsed += 1;
}
return methods;
@ -145,8 +153,12 @@ pub fn parseAttributes(input: *std.Io.Reader, constant_pool: ConstantPool, alloc
const attributes = try allocator.alloc(AttributeInfo, attributes_count);
errdefer allocator.free(attributes);
var parsed: usize = 0;
errdefer for (0..parsed) |i| attributes[i].deinit(allocator);
for (0..attributes_count) |i| {
attributes[i] = try AttributeInfo.parse(input, constant_pool, allocator);
attributes[i] = try .parse(input, constant_pool, allocator);
parsed += 1;
}
return attributes;
@ -154,58 +166,34 @@ pub fn parseAttributes(input: *std.Io.Reader, constant_pool: ConstantPool, alloc
pub fn deinit(self: *Self, allocator: std.mem.Allocator) void {
self.constant_pool.deinit(allocator);
self.freeInterfaces(allocator);
self.freeFields(allocator);
self.freeMethods(allocator);
self.freeAttributes(allocator);
}
fn freeInterfaces(self: *Self, allocator: std.mem.Allocator) void {
allocator.free(self.interfaces);
}
fn freeFields(self: *Self, allocator: std.mem.Allocator) void {
for (self.fields) |*field_info| {
field_info.deinit(allocator);
}
allocator.free(self.fields);
}
fn freeMethods(self: *Self, allocator: std.mem.Allocator) void {
for (self.methods) |*method_info| {
method_info.deinit(allocator);
}
allocator.free(self.methods);
}
fn freeAttributes(self: *Self, allocator: std.mem.Allocator) void {
for (self.attributes) |*attr| {
attr.deinit(allocator);
}
allocator.free(self.attributes);
}
pub fn jsonStringify(self: *const Self, jws: *std.json.Stringify) !void {
try jws.beginObject();
inline for (std.meta.fields(Self)) |field| {
if (comptime std.mem.eql(u8, field.name, "allocator")) continue;
try jws.objectField(field.name);
try jws.write(@field(self, field.name));
}
try jws.endObject();
}
pub fn format(self: *const Self, w: *std.Io.Writer) std.Io.Writer.Error!void {
const depth = 2;
var indent: u8 = 0;
try w.print("magic: 0x{X}\n", .{ self.magic });
try w.print("magic: 0x{X}\n", .{self.magic});
try w.print("version: {d}.{d}\n", .{ self.major_version, self.minor_version });
try w.print("flags: {f}\n", .{ self.access_flags });
try w.print("flags: {f}\n", .{self.access_flags});
const this_class = self.thisClass() catch return error.WriteFailed;
_ = try w.write("this class:\n");
@ -224,7 +212,7 @@ pub fn format(self: *const Self, w: *std.Io.Writer) std.Io.Writer.Error!void {
const info = self.constant_pool.getTag(interface, .class) catch return error.WriteFailed;
try w.splatByteAll(' ', depth * indent);
try w.print("{d}:\n", .{ i });
try w.print("{d}:\n", .{i});
try info.indentedFormat(w, depth, indent + 1, self.constant_pool);
}
@ -234,7 +222,7 @@ pub fn format(self: *const Self, w: *std.Io.Writer) std.Io.Writer.Error!void {
defer indent -= 1;
try w.splatByteAll(' ', depth * indent);
try w.print("{d}:\n", .{ i });
try w.print("{d}:\n", .{i});
try field.indentedFormat(w, depth, indent + 1, self.constant_pool);
}
@ -244,7 +232,7 @@ pub fn format(self: *const Self, w: *std.Io.Writer) std.Io.Writer.Error!void {
defer indent -= 1;
try w.splatByteAll(' ', depth * indent);
try w.print("{d}:\n", .{ i });
try w.print("{d}:\n", .{i});
try method.indentedFormat(w, depth, indent + 1, self.constant_pool);
}
@ -254,7 +242,7 @@ pub fn format(self: *const Self, w: *std.Io.Writer) std.Io.Writer.Error!void {
defer indent -= 1;
try w.splatByteAll(' ', depth * indent);
try w.print("{d}:\n", .{ i });
try w.print("{d}:\n", .{i});
try attribute.indentedFormat(w, depth, indent + 1, self.constant_pool);
}
}
@ -266,4 +254,3 @@ pub fn thisClass(self: *const Self) ResolveError!ConstantPool.Info {
pub fn superClass(self: *const Self) ResolveError!?ConstantPool.Info {
return self.constant_pool.getTagOptional(self.super_class, .class);
}

File diff suppressed because it is too large Load diff

View file

@ -341,6 +341,7 @@ const LookupSwitch = struct {
const pairs_length: usize = @intCast(try input.takeInt(i32, .big));
const pairs = try allocator.alloc(Pair, pairs_length);
errdefer allocator.free(pairs);
for (pairs) |*pair| {
pair.* = .{
.match = try input.takeInt(i32, .big),
@ -437,6 +438,7 @@ const TableSwitch = struct {
const offsets_length: usize = @intCast(high - low + 1);
const offsets = try allocator.alloc(i32, offsets_length);
errdefer allocator.free(offsets);
for (offsets) |*o| {
o.* = try input.takeInt(i32, .big);
}
@ -748,7 +750,7 @@ pub const Instruction = union(Op) {
.athrow => .athrow,
.baload => .baload,
.bastore => .bastore,
.bipush => .{
.bipush => .{
.bipush = try .parse(input, byte_index),
},
.caload => .caload,
@ -1054,12 +1056,12 @@ pub const Instruction = union(Op) {
constant_pool: ConstantPool,
) std.Io.Writer.Error!void {
try w.splatByteAll(' ', depth * indent);
try w.print("type: {t}\n", .{ self.* });
try w.print("type: {t}\n", .{self.*});
switch (self.*) {
.aload, .astore, .dload, .dstore, .fload, .fstore, .iload, .istore, .lload, .lstore => |load_store| {
try w.splatByteAll(' ', depth * indent);
try w.print("index: {d}\n", .{ load_store.index });
try w.print("index: {d}\n", .{load_store.index});
},
.anewarray, .checkcast, .instanceof => |constant| {
const @"type" = constant_pool.get(constant.index) catch return error.WriteFailed;
@ -1070,7 +1072,7 @@ pub const Instruction = union(Op) {
},
.bipush => |bipush| {
try w.splatByteAll(' ', depth * indent);
try w.print("byte: 0x{X}\n", .{ bipush.byte });
try w.print("byte: 0x{X}\n", .{bipush.byte});
},
.getfield, .getstatic, .putfield, .putstatic => |get_set_field| {
const field = constant_pool.get(get_set_field.index) catch return error.WriteFailed;
@ -1081,18 +1083,18 @@ pub const Instruction = union(Op) {
},
.goto, .if_acmpeq, .if_acmpne, .if_icmpeq, .if_icmpne, .if_icmplt, .if_icmpge, .if_icmpgt, .if_icmple, .ifeq, .ifne, .iflt, .ifge, .ifgt, .ifle, .ifnonnull, .ifnull, .jsr => |branch| {
try w.splatByteAll(' ', depth * indent);
try w.print("branch_offset: {d}\n", .{ branch.branch_offset });
try w.print("branch_offset: {d}\n", .{branch.branch_offset});
},
.goto_w, .jsr_w => |branch_w| {
try w.splatByteAll(' ', depth * indent);
try w.print("branch_offset: {d}\n", .{ branch_w.branch_offset });
try w.print("branch_offset: {d}\n", .{branch_w.branch_offset});
},
.iinc => |iinc| {
try w.splatByteAll(' ', depth * indent);
try w.print("index: {d}\n", .{ iinc.index });
try w.print("index: {d}\n", .{iinc.index});
try w.splatByteAll(' ', depth * indent);
try w.print("const: {d}\n", .{ iinc.@"const" });
try w.print("const: {d}\n", .{iinc.@"const"});
},
.invokedynamic => |invokedynamic| {
const call_site_specifier = constant_pool.get(invokedynamic.index) catch return error.WriteFailed;
@ -1109,7 +1111,7 @@ pub const Instruction = union(Op) {
try interface_method.indentedFormat(w, depth, indent + 1, constant_pool);
try w.splatByteAll(' ', depth * indent);
try w.print("count: {d}\n", .{ invokeinterface.count });
try w.print("count: {d}\n", .{invokeinterface.count});
},
.invokespecial, .invokestatic, .invokevirtual => |invokespecial| {
const method = constant_pool.get(invokespecial.index) catch return error.WriteFailed;
@ -1134,7 +1136,7 @@ pub const Instruction = union(Op) {
},
.lookupswitch => |lookupswitch| {
try w.splatByteAll(' ', depth * indent);
try w.print("default: {d}\n", .{ lookupswitch.default });
try w.print("default: {d}\n", .{lookupswitch.default});
try w.splatByteAll(' ', depth * indent);
_ = try w.write("pairs:\n");
@ -1144,16 +1146,16 @@ pub const Instruction = union(Op) {
defer pairs_indent -= 1;
try w.splatByteAll(' ', depth * pairs_indent);
try w.print("{d}:\n", .{ i });
try w.print("{d}:\n", .{i});
{
pairs_indent += 1;
defer pairs_indent -= 1;
try w.splatByteAll(' ', depth * pairs_indent);
try w.print("match: {d}\n", .{ pair.match });
try w.print("match: {d}\n", .{pair.match});
try w.splatByteAll(' ', depth * pairs_indent);
try w.print("offset: {d}\n", .{ pair.offset });
try w.print("offset: {d}\n", .{pair.offset});
}
}
},
@ -1165,7 +1167,7 @@ pub const Instruction = union(Op) {
try @"type".indentedFormat(w, depth, indent + 1, constant_pool);
try w.splatByteAll(' ', depth * indent);
try w.print("dimensions: {d}\n", .{ multianewarray.dimensions });
try w.print("dimensions: {d}\n", .{multianewarray.dimensions});
},
.new => |new| {
const @"type" = constant_pool.get(new.index) catch return error.WriteFailed;
@ -1176,19 +1178,19 @@ pub const Instruction = union(Op) {
},
.newarray => |newarray| {
try w.splatByteAll(' ', depth * indent);
try w.print("type: {t}\n", .{ newarray.array_type });
try w.print("type: {t}\n", .{newarray.array_type});
},
.ret => |ret| {
try w.splatByteAll(' ', depth * indent);
try w.print("index: {d}\n", .{ ret.index });
try w.print("index: {d}\n", .{ret.index});
},
.sipush => |sipush| {
try w.splatByteAll(' ', depth * indent);
try w.print("short: 0x{X}\n", .{ sipush.short });
try w.print("short: 0x{X}\n", .{sipush.short});
},
.tableswitch => |tableswitch| {
try w.splatByteAll(' ', depth * indent);
try w.print("default: {d}\n", .{ tableswitch.default });
try w.print("default: {d}\n", .{tableswitch.default});
try w.splatByteAll(' ', depth * indent);
_ = try w.write("offsets:\n");
@ -1204,24 +1206,23 @@ pub const Instruction = union(Op) {
.wide => |wide| switch (wide) {
.form1 => |form1| {
try w.splatByteAll(' ', depth * indent);
try w.print("opcode: {t}\n", .{ form1.opcode });
try w.print("opcode: {t}\n", .{form1.opcode});
try w.splatByteAll(' ', depth * indent);
try w.print("index: {d}\n", .{ form1.index });
try w.print("index: {d}\n", .{form1.index});
},
.form2 => |form2| {
try w.splatByteAll(' ', depth * indent);
try w.print("opcode: {t}\n", .{ form2.opcode });
try w.print("opcode: {t}\n", .{form2.opcode});
try w.splatByteAll(' ', depth * indent);
try w.print("index: {d}\n", .{ form2.index });
try w.print("index: {d}\n", .{form2.index});
try w.splatByteAll(' ', depth * indent);
try w.print("const: {d}\n", .{ form2.@"const" });
try w.print("const: {d}\n", .{form2.@"const"});
},
},
else => {},
}
}
};

View file

@ -355,23 +355,23 @@ pub const Info = union(Info.Tag) {
pub fn format(self: *const Info, w: *std.Io.Writer) std.Io.Writer.Error!void {
switch (self.*) {
.class => |class| try w.print("#{d}", .{ class.name_index }),
.class => |class| try w.print("#{d}", .{class.name_index}),
.field_ref => |field_ref| try w.print("#{d}.#{d}", .{ field_ref.class_index, field_ref.name_and_type_index }),
.method_ref => |method_ref| try w.print("#{d}.#{d}", .{ method_ref.class_index, method_ref.name_and_type_index }),
.interface_method_ref => |interface_method_ref| try w.print("#{d}.#{d}", .{ interface_method_ref.class_index, interface_method_ref.name_and_type_index }),
.string => |string| try w.print("#{d}", .{ string.string_index }),
.integer => |integer| try w.print("{d}", .{ integer.bytes }),
.float => |float| try w.print("{d}", .{ float.float() }),
.long => |long| try w.print("{d}", .{ long.long() }),
.double => |double| try w.print("{d}", .{ double.double() }),
.string => |string| try w.print("#{d}", .{string.string_index}),
.integer => |integer| try w.print("{d}", .{integer.bytes}),
.float => |float| try w.print("{d}", .{float.float()}),
.long => |long| try w.print("{d}", .{long.long()}),
.double => |double| try w.print("{d}", .{double.double()}),
.name_and_type => |name_and_type| try w.print("#{d}:#{d}", .{ name_and_type.name_index, name_and_type.descriptor_index }),
.utf8 => |utf8| try w.print("\"{s}\"", .{ utf8.bytes }),
.utf8 => |utf8| try w.print("\"{s}\"", .{utf8.bytes}),
.method_handle => |method_handle| try w.print("{t} #{d}", .{ method_handle.reference_kind, method_handle.reference_index }),
.method_type => |method_type| try w.print("#{d}", .{ method_type.descriptor_index }),
.method_type => |method_type| try w.print("#{d}", .{method_type.descriptor_index}),
.dynamic => |dynamic| try w.print("#{d} #{d}", .{ dynamic.bootstrap_method_attr_index, dynamic.name_and_type_index }),
.invoke_dynamic => |invoke_dynamic| try w.print("#{d} #{d}", .{ invoke_dynamic.bootstrap_method_attr_index, invoke_dynamic.name_and_type_index }),
.module => |module| try w.print("#{d}", .{ module.name_index }),
.package => |package| try w.print("#{d}", .{ package.name_index }),
.module => |module| try w.print("#{d}", .{module.name_index}),
.package => |package| try w.print("#{d}", .{package.name_index}),
}
}
@ -383,7 +383,7 @@ pub const Info = union(Info.Tag) {
constant_pool: Self,
) std.Io.Writer.Error!void {
try w.splatByteAll(' ', depth * indent);
try w.print("constant_value_type: {t}\n", .{ self.* });
try w.print("constant_value_type: {t}\n", .{self.*});
switch (self.*) {
.class => |*class| {
@ -409,19 +409,19 @@ pub const Info = union(Info.Tag) {
},
.integer => |*integer| {
try w.splatByteAll(' ', depth * indent);
try w.print("integer: {d}\n", .{ integer.bytes });
try w.print("integer: {d}\n", .{integer.bytes});
},
.float => |*float| {
try w.splatByteAll(' ', depth * indent);
try w.print("float: {d}\n", .{ float.float() });
try w.print("float: {d}\n", .{float.float()});
},
.long => |*long| {
try w.splatByteAll(' ', depth * indent);
try w.print("long: {d}\n", .{ long.long() });
try w.print("long: {d}\n", .{long.long()});
},
.double => |*double| {
try w.splatByteAll(' ', depth * indent);
try w.print("double: {d}\n", .{ double.double() });
try w.print("double: {d}\n", .{double.double()});
},
.name_and_type => |*name_and_type| {
try formatInfo(w, depth, indent, "name", name_and_type, .name, constant_pool);
@ -430,11 +430,11 @@ pub const Info = union(Info.Tag) {
},
.utf8 => |*utf8| {
try w.splatByteAll(' ', depth * indent);
try w.print("bytes: \"{s}\"\n", .{ utf8.bytes });
try w.print("bytes: \"{s}\"\n", .{utf8.bytes});
},
.method_handle => |*method_handle| {
try w.splatByteAll(' ', depth * indent);
try w.print("kind: {t}\n", .{ method_handle.reference_kind });
try w.print("kind: {t}\n", .{method_handle.reference_kind});
try formatInfo(w, depth, indent, "descriptor", method_handle, .reference, constant_pool);
},
@ -466,8 +466,18 @@ pub fn parse(input: *std.Io.Reader, allocator: std.mem.Allocator) ParseError!Sel
const constant_pool = try allocator.alloc(?Info, constant_pool_size - 1);
errdefer allocator.free(constant_pool);
var parsed: usize = 0;
errdefer {
for (0..parsed) |i| {
if (constant_pool[i]) |*info| {
info.deinit(allocator);
}
}
}
var i: usize = 0;
while (i < constant_pool_size - 1) {
defer parsed = i;
defer i += 1;
const info: Info = try .parse(input, allocator);

View file

@ -54,7 +54,7 @@ pub fn indentedFormat(
constant_pool: ConstantPool,
) std.Io.Writer.Error!void {
try w.splatByteAll(' ', depth * indent);
try w.print("flags: {f}\n", .{ self.access_flags });
try w.print("flags: {f}\n", .{self.access_flags});
try w.splatByteAll(' ', depth * indent);
_ = try w.write("name:\n");
@ -74,7 +74,7 @@ pub fn indentedFormat(
defer attr_indent -= 1;
try w.splatByteAll(' ', depth * attr_indent);
try w.print("{d}:\n", .{ j });
try w.print("{d}:\n", .{j});
try attribute.indentedFormat(w, depth, attr_indent + 1, constant_pool);
}
@ -87,4 +87,3 @@ pub fn name(self: *const Self, constant_pool: ConstantPool) ResolveError!Constan
pub fn descriptor(self: *const Self, constant_pool: ConstantPool) ResolveError!ConstantPool.Info {
return constant_pool.getTag(self.descriptor_index, .utf8);
}

View file

@ -57,7 +57,7 @@ pub fn indentedFormat(
constant_pool: ConstantPool,
) std.Io.Writer.Error!void {
try w.splatByteAll(' ', depth * indent);
try w.print("flags: {f}\n", .{ self.access_flags });
try w.print("flags: {f}\n", .{self.access_flags});
try w.splatByteAll(' ', depth * indent);
_ = try w.write("name:\n");
@ -77,7 +77,7 @@ pub fn indentedFormat(
defer attr_indent -= 1;
try w.splatByteAll(' ', depth * attr_indent);
try w.print("{d}:\n", .{ j });
try w.print("{d}:\n", .{j});
try attribute.indentedFormat(w, depth, attr_indent + 1, constant_pool);
}

View file

@ -17,19 +17,19 @@ pub fn EnumFlags(comptime E: type) type {
}
pub fn contains(self: Self, flag: E) bool {
return (self.mask & @intFromEnum(flag)) != 0;
return (self.mask & @backingInt(flag)) != 0;
}
pub fn insert(self: *Self, flag: E) void {
self.mask |= @intFromEnum(flag);
self.mask |= @backingInt(flag);
}
pub fn remove(self: *Self, flag: E) void {
self.mask &= ~@intFromEnum(flag);
self.mask &= ~@backingInt(flag);
}
pub fn toggle(self: *Self, flag: E) void {
self.mask ^= @intFromEnum(flag);
self.mask ^= @backingInt(flag);
}
pub fn format(self: *const Self, w: *std.Io.Writer) std.Io.Writer.Error!void {
@ -40,11 +40,10 @@ pub fn EnumFlags(comptime E: type) type {
if (index > 0) {
_ = try w.write(" | ");
}
try w.print("{s}", .{ field });
try w.print("{s}", .{field});
index += 1;
}
}
}
};
}

View file

@ -19,17 +19,17 @@ pub fn main(init: std.process.Init) !void {
std.debug.assert(args.skip());
const file_path = if (args.next()) |fp| fp else {
try stderr.writeAll("No file argument provided.\n");
return;
std.process.exit(1);
};
const file = std.Io.Dir.cwd().openFile(io, file_path, .{}) catch |err| switch (err) {
error.FileNotFound => {
try stderr.writeAll("File not found.\n");
return;
std.process.exit(1);
},
error.IsDir => {
try stderr.writeAll("Path is a directory.\n");
return;
std.process.exit(1);
},
else => return err,
};
@ -42,17 +42,17 @@ pub fn main(init: std.process.Init) !void {
var class = Class.parse(reader, allocator) catch |err| switch (err) {
error.InvalidMagicNumber => {
try stderr.writeAll("Invalid magic number.\n");
return;
std.process.exit(1);
},
error.InvalidTag => {
try stderr.writeAll("Unrecognized tag type.\n");
return;
std.process.exit(1);
},
else => return err,
};
defer class.deinit(allocator);
try stdout.print("{f}", .{ class });
try stdout.print("{f}", .{class});
try stdout.flush();
}