Skip to content
0.2.0-dev Download ZIP
246 lines ·8.8 KB Raw
1using System.Buffers.Binary;
2using System.Text;
3using EvilEngine.Mounts;
4
5namespace EvilEngine.Adapters.EaPegasus.Attrib;
6
7public sealed record AttribExport(ulong Id, ulong Type, uint Offset, uint Size);
8
9public sealed class AttribVault
10{
11 private const uint Vers = 0x56657273;
12 private const uint DepN = 0x4465704E;
13 private const uint DatN = 0x4461744E;
14 private const uint ExpN = 0x4578704E;
15 private const uint PtrN = 0x5074724E;
16 private const uint StrE = 0x53747245;
17 private const uint EndC = 0x456E6443;
18
19 private AttribVault(string name, byte[] vlt, byte[] bin)
20 {
21 Name = name;
22 Vlt = vlt;
23 Bin = bin;
24 }
25
26 public string Name { get; }
27
28 public ulong Version { get; private set; }
29
30 public IReadOnlyList<string> Dependencies { get; private set; } = [];
31
32 public IReadOnlyList<AttribExport> Exports { get; private set; } = [];
33
34 public IReadOnlyList<string> Strings { get; private set; } = [];
35
36 public int Fixups { get; private set; }
37
38 internal byte[] Vlt { get; }
39
40 internal byte[] Bin { get; }
41
42 public static ReadOnlySpan<byte> Signature => "Vers"u8;
43
44 public static bool IsSignature(ReadOnlySpan<byte> head)
45 {
46 return head.Length >= 4 && head[..4].SequenceEqual(Signature);
47 }
48
49 public IEnumerable<AttribExport> ExportsOf(ulong type)
50 {
51 return Exports.Where(export => export.Type == type);
52 }
53
54 public static AttribVault Open(IFileSource files, VirtualPath vlt)
55 {
56 var bin = VirtualPath.Parse($"{vlt.WithoutExtension.Value}.bin");
57 return Read(files.ReadAllBytes(vlt), files.ReadAllBytes(bin), vlt.Value);
58 }
59
60 public static AttribVault Read(ReadOnlySpan<byte> vlt, ReadOnlySpan<byte> bin, string name)
61 {
62 var vault = new AttribVault(name, vlt.ToArray(), bin.ToArray());
63 try
64 {
65 vault.ReadVlt();
66 vault.ReadBin();
67 }
68 catch (InvalidDataException error)
69 {
70 throw new InvalidDataException($"'{name}' isn't a vault Skate's Attrib reads: {error.Message}.", error);
71 }
72
73 return vault;
74 }
75
76 private void ReadVlt()
77 {
78 var chunks = Chunks(Vlt, "the .vlt", out var end);
79 if (end != Vlt.Length)
80 throw new InvalidDataException($"the .vlt has {Vlt.Length - end} bytes after its end chunk");
81 string[] order = ["Vers", "StrN", "DepN", "DatN", "ExpN", "PtrN", "EndC"];
82 var tags = chunks.Select(chunk => Tag(chunk.Tag)).ToArray();
83 if (!tags.SequenceEqual(order))
84 throw new InvalidDataException(
85 $"the .vlt's chunks are {string.Join(' ', tags)} rather than {string.Join(' ', order)}");
86
87 var (versAt, versSize) = Payload(chunks, Vers);
88 if (versSize < 8)
89 throw new InvalidDataException("the version chunk is too short");
90 Version = BigEndian.U64(Vlt, versAt, "the version");
91
92 var (depAt, _) = Payload(chunks, DepN);
93 Dependencies = ReadDependencies(depAt);
94
95 var (expAt, expSize) = Payload(chunks, ExpN);
96 var (datAt, datSize) = Payload(chunks, DatN);
97 Exports = ReadExports(expAt, expSize, datAt, datAt + datSize);
98
99 var (ptrAt, ptrSize) = Payload(chunks, PtrN);
100 ApplyFixups(ptrAt, ptrSize);
101 }
102
103 private void ReadBin()
104 {
105 var chunks = Chunks(Bin, "the .bin", out _);
106 if (chunks.Count != 2 || chunks[0].Tag != StrE || chunks[1].Tag != EndC)
107 throw new InvalidDataException(
108 $"the .bin's chunks are {string.Join(' ', chunks.Select(chunk => Tag(chunk.Tag)))} rather than StrE EndC");
109 var strings = new List<string>();
110 var at = chunks[0].At + 8L;
111 var end = chunks[0].At + chunks[0].Size;
112 while (at < end && Bin[at] != 0)
113 {
114 var text = BigEndian.Text(Bin.AsSpan(0, (int)end), at, "a string");
115 strings.Add(text);
116 at += Encoding.UTF8.GetByteCount(text) + 1;
117 }
118
119 Strings = strings;
120 }
121
122 private List<string> ReadDependencies(long at)
123 {
124 var count = BigEndian.U64(Vlt, at, "the dependency count");
125 if (count > 16)
126 throw new InvalidDataException($"it names {count} dependencies");
127 var names = BigEndian.Align(at + 8 + (long)count * 12, 8);
128 var dependencies = new List<string>();
129 for (var i = 0; i < (int)count; i++)
130 {
131 var hash = BigEndian.U64(Vlt, at + 8 + i * 8L, "a dependency hash");
132 var offset = BigEndian.U32(Vlt, at + 8 + (long)count * 8 + i * 4L, "a dependency name");
133 var name = BigEndian.Text(Vlt, names + offset, "a dependency name");
134 if (AttribHash.Of(name) != hash)
135 throw new InvalidDataException($"dependency '{name}' doesn't match its hash {hash:X16}");
136 dependencies.Add(name);
137 }
138
139 return dependencies;
140 }
141
142 private List<AttribExport> ReadExports(long at, long size, long dataStart, long dataEnd)
143 {
144 var count = BigEndian.U64(Vlt, at, "the export count");
145 if (count > (ulong)(size - 8) / 24)
146 throw new InvalidDataException($"it declares {count} exports in {size} bytes");
147 var exports = new List<AttribExport>((int)count);
148 for (var i = 0; i < (int)count; i++)
149 {
150 var entry = at + 8 + i * 24L;
151 var export = new AttribExport(
152 BigEndian.U64(Vlt, entry, "an export"),
153 BigEndian.U64(Vlt, entry + 8, "an export"),
154 BigEndian.U32(Vlt, entry + 20, "an export"),
155 BigEndian.U32(Vlt, entry + 16, "an export"));
156 if (export.Offset < dataStart || export.Offset + (long)export.Size > dataEnd)
157 throw new InvalidDataException(
158 $"export {export.Id:X16} at 0x{export.Offset:X} lies outside the data chunk");
159 exports.Add(export);
160 }
161
162 return exports;
163 }
164
165 private void ApplyFixups(long at, long size)
166 {
167 var target = Bin;
168 for (var entry = at; entry + 16 <= at + size; entry += 16)
169 {
170 var offset = BigEndian.U32(Vlt, entry, "a pointer");
171 var kind = BigEndian.U16(Vlt, entry + 4, "a pointer");
172 var index = BigEndian.U16(Vlt, entry + 6, "a pointer");
173 var destination = BigEndian.U64(Vlt, entry + 8, "a pointer");
174 switch (kind)
175 {
176 case 0:
177 return;
178 case 1:
179 Write(target, offset, 0);
180 break;
181 case 2:
182 target = index switch
183 {
184 0 => Vlt,
185 1 => Bin,
186 _ => throw new InvalidDataException(
187 $"a pointer fixes up dependency {index}, which isn't the .vlt or the .bin")
188 };
189 break;
190 case 3:
191 if (destination >= (ulong)Bin.Length)
192 throw new InvalidDataException(
193 $"a pointer at 0x{offset:X} points to 0x{destination:X}, past the .bin");
194 Write(target, offset, (uint)destination);
195 break;
196 default:
197 throw new InvalidDataException($"a pointer at 0x{offset:X} has kind {kind}, which isn't known yet");
198 }
199 }
200
201 throw new InvalidDataException("the pointer table never ends");
202 }
203
204 private void Write(byte[] target, uint offset, uint value)
205 {
206 if (offset > target.Length - 4)
207 throw new InvalidDataException($"a pointer fixes up 0x{offset:X}, past the end");
208 BinaryPrimitives.WriteUInt32BigEndian(target.AsSpan((int)offset), value);
209 Fixups++;
210 }
211
212 private static List<(uint Tag, int At, uint Size)> Chunks(byte[] data, string what, out int end)
213 {
214 var chunks = new List<(uint, int, uint)>();
215 var at = 0;
216 while (true)
217 {
218 var tag = BigEndian.U32(data, at, $"a chunk of {what}");
219 var size = BigEndian.U32(data, at + 4, $"a chunk of {what}");
220 if (size < 8 || size > data.Length - at)
221 throw new InvalidDataException($"{what}'s {Tag(tag)} chunk at 0x{at:X} declares {size} bytes");
222 chunks.Add((tag, at, size));
223 at += (int)size;
224 if (tag == EndC)
225 break;
226 }
227
228 end = at;
229 return chunks;
230 }
231
232 private static (long At, long Size) Payload(List<(uint Tag, int At, uint Size)> chunks, uint tag)
233 {
234 var chunk = chunks.First(chunk => chunk.Tag == tag);
235 return (chunk.At + 8L, chunk.Size - 8L);
236 }
237
238 private static string Tag(uint tag)
239 {
240 return string.Create(4, tag, (span, value) =>
241 {
242 for (var i = 0; i < 4; i++)
243 span[i] = (char)((value >> (24 - i * 8)) & 0xFF);
244 });
245 }
246}