add unit tests for padding

This commit is contained in:
Motiejus Jakštys 2022-02-19 16:04:13 +02:00 committed by Motiejus Jakštys
parent 623060dac3
commit ca28332126
3 changed files with 16 additions and 9 deletions

View File

@ -1,7 +1,7 @@
const std = @import("std");
const shell = @import("shell.zig");
const HeaderSize = @sizeOf(Header);
const HeaderSize = @divExact(@bitSizeOf(Header), 8);
const Magic = [4]u8{ 0xf0, 0x9f, 0xa4, 0xb7 };
const Version = 0;
const Bom = 0x1234;
@ -73,10 +73,6 @@ const Header = packed struct {
const testing = std.testing;
test "header is byte-aligned" {
try testing.expectEqual(HeaderSize * 8, @bitSizeOf(Header));
}
test "Section length is a power of two" {
try testing.expect(std.math.isPowerOfTwo(SectionLength));
}

View File

@ -170,7 +170,12 @@ pub const ShellWriter = struct {
// rounds up a u12 to the nearest factor of 4 and returns the difference
// (padding)
inline fn roundUp4Padding(n: u12) u12 {
return ((n + 3) & ~@intCast(u12, 3)) - n;
return roundUp4(n) - n;
}
// rounds up a u12 to the nearest factor of 4.
inline fn roundUp4(n: u12) u12 {
return ((n + 3) & ~@intCast(u12, 3));
}
// ShellIndex is an index to the shell strings. As shell can be up to 64 bytes
@ -192,12 +197,12 @@ test "basic shellpopcon" {
const bash = "/bin/bash"; // 9 chars
const zsh = "/bin/zsh"; // 8 chars
const long = "/bin/very-long-shell-name-ought-to-be-first"; // 43 chars
const nobody = "/bin/nobody"; // only 1 instance, ought to ignore
const long = "/bin/very-long-shell-name-ought-to-be-first";
const input = [_][]const u8{
zsh, zsh, zsh, zsh, // zsh score 8*4=32
bash, bash, bash, nobody, // bash score 3*9=27
long, long, // long score 2*42=84
long, long, // long score 2*43=86
};
for (input) |shell| {
@ -212,6 +217,10 @@ test "basic shellpopcon" {
try testing.expectEqual(sections.getIndex(zsh).?, 1);
try testing.expectEqual(sections.getIndex(bash).?, 2);
try testing.expectEqual(sections.getIndex(nobody), null);
try testing.expectEqual(
sections.sectionBlob().len,
roundUp4(bash.len) + roundUp4(zsh.len) + roundUp4(long.len),
);
const shellReader = ShellReader.init(
sections.sectionIndex(),
@ -220,6 +229,8 @@ test "basic shellpopcon" {
try testing.expectEqualStrings(shellReader.get(0), long);
try testing.expectEqualStrings(shellReader.get(1), zsh);
try testing.expectEqualStrings(shellReader.get(2), bash);
try testing.expectEqual(shellReader.sectionIndex.len, 3);
}
test "padding" {

View File

@ -3,7 +3,7 @@ const std = @import("std");
const Allocator = std.mem.Allocator;
const cast = std.math.cast;
pub const PackedUserSize = @sizeOf(PackedUser);
pub const PackedUserSize = @divExact(@bitSizeOf(PackedUser), 8);
pub const PackedUser = packed struct {
uid: u32,
gid: u32,