using System.Buffers.Binary; using System.Text; using EvilEngine.Mounts; namespace EvilEngine.Adapters.EaPegasus.Attrib; public sealed record AttribExport(ulong Id, ulong Type, uint Offset, uint Size); public sealed class AttribVault { private const uint Vers = 0x56657273; private const uint DepN = 0x4465704E; private const uint DatN = 0x4461744E; private const uint ExpN = 0x4578704E; private const uint PtrN = 0x5074724E; private const uint StrE = 0x53747245; private const uint EndC = 0x456E6443; private AttribVault(string name, byte[] vlt, byte[] bin) { Name = name; Vlt = vlt; Bin = bin; } public string Name { get; } public ulong Version { get; private set; } public IReadOnlyList Dependencies { get; private set; } = []; public IReadOnlyList Exports { get; private set; } = []; public IReadOnlyList Strings { get; private set; } = []; public int Fixups { get; private set; } internal byte[] Vlt { get; } internal byte[] Bin { get; } public static ReadOnlySpan Signature => "Vers"u8; public static bool IsSignature(ReadOnlySpan head) { return head.Length >= 4 && head[..4].SequenceEqual(Signature); } public IEnumerable ExportsOf(ulong type) { return Exports.Where(export => export.Type == type); } public static AttribVault Open(IFileSource files, VirtualPath vlt) { var bin = VirtualPath.Parse($"{vlt.WithoutExtension.Value}.bin"); return Read(files.ReadAllBytes(vlt), files.ReadAllBytes(bin), vlt.Value); } public static AttribVault Read(ReadOnlySpan vlt, ReadOnlySpan bin, string name) { var vault = new AttribVault(name, vlt.ToArray(), bin.ToArray()); try { vault.ReadVlt(); vault.ReadBin(); } catch (InvalidDataException error) { throw new InvalidDataException($"'{name}' isn't a vault Skate's Attrib reads: {error.Message}.", error); } return vault; } private void ReadVlt() { var chunks = Chunks(Vlt, "the .vlt", out var end); if (end != Vlt.Length) throw new InvalidDataException($"the .vlt has {Vlt.Length - end} bytes after its end chunk"); string[] order = ["Vers", "StrN", "DepN", "DatN", "ExpN", "PtrN", "EndC"]; var tags = chunks.Select(chunk => Tag(chunk.Tag)).ToArray(); if (!tags.SequenceEqual(order)) throw new InvalidDataException( $"the .vlt's chunks are {string.Join(' ', tags)} rather than {string.Join(' ', order)}"); var (versAt, versSize) = Payload(chunks, Vers); if (versSize < 8) throw new InvalidDataException("the version chunk is too short"); Version = BigEndian.U64(Vlt, versAt, "the version"); var (depAt, _) = Payload(chunks, DepN); Dependencies = ReadDependencies(depAt); var (expAt, expSize) = Payload(chunks, ExpN); var (datAt, datSize) = Payload(chunks, DatN); Exports = ReadExports(expAt, expSize, datAt, datAt + datSize); var (ptrAt, ptrSize) = Payload(chunks, PtrN); ApplyFixups(ptrAt, ptrSize); } private void ReadBin() { var chunks = Chunks(Bin, "the .bin", out _); if (chunks.Count != 2 || chunks[0].Tag != StrE || chunks[1].Tag != EndC) throw new InvalidDataException( $"the .bin's chunks are {string.Join(' ', chunks.Select(chunk => Tag(chunk.Tag)))} rather than StrE EndC"); var strings = new List(); var at = chunks[0].At + 8L; var end = chunks[0].At + chunks[0].Size; while (at < end && Bin[at] != 0) { var text = BigEndian.Text(Bin.AsSpan(0, (int)end), at, "a string"); strings.Add(text); at += Encoding.UTF8.GetByteCount(text) + 1; } Strings = strings; } private List ReadDependencies(long at) { var count = BigEndian.U64(Vlt, at, "the dependency count"); if (count > 16) throw new InvalidDataException($"it names {count} dependencies"); var names = BigEndian.Align(at + 8 + (long)count * 12, 8); var dependencies = new List(); for (var i = 0; i < (int)count; i++) { var hash = BigEndian.U64(Vlt, at + 8 + i * 8L, "a dependency hash"); var offset = BigEndian.U32(Vlt, at + 8 + (long)count * 8 + i * 4L, "a dependency name"); var name = BigEndian.Text(Vlt, names + offset, "a dependency name"); if (AttribHash.Of(name) != hash) throw new InvalidDataException($"dependency '{name}' doesn't match its hash {hash:X16}"); dependencies.Add(name); } return dependencies; } private List ReadExports(long at, long size, long dataStart, long dataEnd) { var count = BigEndian.U64(Vlt, at, "the export count"); if (count > (ulong)(size - 8) / 24) throw new InvalidDataException($"it declares {count} exports in {size} bytes"); var exports = new List((int)count); for (var i = 0; i < (int)count; i++) { var entry = at + 8 + i * 24L; var export = new AttribExport( BigEndian.U64(Vlt, entry, "an export"), BigEndian.U64(Vlt, entry + 8, "an export"), BigEndian.U32(Vlt, entry + 20, "an export"), BigEndian.U32(Vlt, entry + 16, "an export")); if (export.Offset < dataStart || export.Offset + (long)export.Size > dataEnd) throw new InvalidDataException( $"export {export.Id:X16} at 0x{export.Offset:X} lies outside the data chunk"); exports.Add(export); } return exports; } private void ApplyFixups(long at, long size) { var target = Bin; for (var entry = at; entry + 16 <= at + size; entry += 16) { var offset = BigEndian.U32(Vlt, entry, "a pointer"); var kind = BigEndian.U16(Vlt, entry + 4, "a pointer"); var index = BigEndian.U16(Vlt, entry + 6, "a pointer"); var destination = BigEndian.U64(Vlt, entry + 8, "a pointer"); switch (kind) { case 0: return; case 1: Write(target, offset, 0); break; case 2: target = index switch { 0 => Vlt, 1 => Bin, _ => throw new InvalidDataException( $"a pointer fixes up dependency {index}, which isn't the .vlt or the .bin") }; break; case 3: if (destination >= (ulong)Bin.Length) throw new InvalidDataException( $"a pointer at 0x{offset:X} points to 0x{destination:X}, past the .bin"); Write(target, offset, (uint)destination); break; default: throw new InvalidDataException($"a pointer at 0x{offset:X} has kind {kind}, which isn't known yet"); } } throw new InvalidDataException("the pointer table never ends"); } private void Write(byte[] target, uint offset, uint value) { if (offset > target.Length - 4) throw new InvalidDataException($"a pointer fixes up 0x{offset:X}, past the end"); BinaryPrimitives.WriteUInt32BigEndian(target.AsSpan((int)offset), value); Fixups++; } private static List<(uint Tag, int At, uint Size)> Chunks(byte[] data, string what, out int end) { var chunks = new List<(uint, int, uint)>(); var at = 0; while (true) { var tag = BigEndian.U32(data, at, $"a chunk of {what}"); var size = BigEndian.U32(data, at + 4, $"a chunk of {what}"); if (size < 8 || size > data.Length - at) throw new InvalidDataException($"{what}'s {Tag(tag)} chunk at 0x{at:X} declares {size} bytes"); chunks.Add((tag, at, size)); at += (int)size; if (tag == EndC) break; } end = at; return chunks; } private static (long At, long Size) Payload(List<(uint Tag, int At, uint Size)> chunks, uint tag) { var chunk = chunks.First(chunk => chunk.Tag == tag); return (chunk.At + 8L, chunk.Size - 8L); } private static string Tag(uint tag) { return string.Create(4, tag, (span, value) => { for (var i = 0; i < 4; i++) span[i] = (char)((value >> (24 - i * 8)) & 0xFF); }); } }