using System.Buffers.Binary; using System.Text; using EvilEngine.Mounts; namespace EvilEngine.Adapters.Unity; public sealed record SerializedObject(long PathId, long Offset, uint Size, int ClassId); public sealed class SerializedFile { public const int MonoBehaviourClass = 114; public const int PlayerSettingsClass = 129; private const int SmallHeader = 20; private const int LargeHeader = 48; public static readonly IReadOnlyList Formats = [21, 22]; private SerializedFile(int format, bool bigEndian, long dataOffset, long fileSize) { Format = format; BigEndian = bigEndian; DataOffset = dataOffset; FileSize = fileSize; } public int Format { get; } public bool BigEndian { get; } public long DataOffset { get; } public long FileSize { get; } public string UnityVersion { get; private set; } = ""; public int Platform { get; private set; } public bool TypeTrees { get; private set; } public IReadOnlyList Classes { get; private set; } = []; public IReadOnlyList Objects { get; private set; } = []; public IReadOnlyList Externals { get; private set; } = []; public static SerializedFile Read(IRandomAccess file) { if (file.Length < SmallHeader) throw new InvalidDataException($"{file.Length} bytes is too short for a serialized file's header."); Span header = stackalloc byte[LargeHeader]; header = header[..(int)Math.Min(LargeHeader, file.Length)]; file.ReadExactly(0, header); var format = BinaryPrimitives.ReadInt32BigEndian(header[8..]); if (!Formats.Contains(format)) throw new InvalidDataException($"Format {format} isn't one the unity reader knows."); long metadataSize = BinaryPrimitives.ReadUInt32BigEndian(header); long fileSize = BinaryPrimitives.ReadUInt32BigEndian(header[4..]); long dataOffset = BinaryPrimitives.ReadUInt32BigEndian(header[12..]); var bigEndian = header[16] != 0; var metadataAt = SmallHeader; if (format >= 22) { if (header.Length < LargeHeader) throw new InvalidDataException($"{file.Length} bytes is too short for a format {format} header."); metadataSize = BinaryPrimitives.ReadUInt32BigEndian(header[20..]); fileSize = BinaryPrimitives.ReadInt64BigEndian(header[24..]); dataOffset = BinaryPrimitives.ReadInt64BigEndian(header[32..]); metadataAt = LargeHeader; } if (fileSize != file.Length) throw new InvalidDataException($"The header says {fileSize} bytes, but the file is {file.Length}."); if (metadataSize <= 0 || metadataAt + metadataSize > fileSize || dataOffset > fileSize || dataOffset < metadataAt + metadataSize) throw new InvalidDataException( $"The header's metadata ({metadataSize} bytes) and data ({dataOffset}) don't fit {fileSize} bytes."); var metadata = new byte[metadataSize]; file.ReadExactly(metadataAt, metadata); var result = new SerializedFile(format, bigEndian, dataOffset, fileSize); result.ReadMetadata(new Reader(metadata, bigEndian)); return result; } public byte[] ReadObject(IRandomAccess file, SerializedObject item) { var at = DataOffset + item.Offset; if (at < DataOffset || at + item.Size > FileSize) throw new InvalidDataException($"Object {item.PathId} runs past the end of the file."); var bytes = new byte[item.Size]; file.ReadExactly(at, bytes); return bytes; } private void ReadMetadata(Reader reader) { UnityVersion = reader.CString(); Platform = reader.Int32(); TypeTrees = reader.Byte() != 0; var classes = new int[reader.Count(23)]; for (var index = 0; index < classes.Length; index++) { var classId = reader.Int32(); reader.Skip(3); if (classId == MonoBehaviourClass) reader.Skip(16); reader.Skip(16); if (TypeTrees) { var nodes = reader.Count(32); var strings = reader.Int32(); if (strings < 0) throw new InvalidDataException($"A type tree has {strings} bytes of strings."); reader.Skip(nodes * 32L + strings); reader.Skip(reader.Count(4) * 4L); } classes[index] = classId; } var objects = new SerializedObject[reader.Count(20)]; for (var index = 0; index < objects.Length; index++) { reader.Align(); var pathId = reader.Int64(); var offset = Format >= 22 ? reader.Int64() : reader.UInt32(); var size = reader.UInt32(); var type = reader.Int32(); if (type < 0 || type >= classes.Length) throw new InvalidDataException($"Object {pathId} names type {type} of {classes.Length}."); objects[index] = new SerializedObject(pathId, offset, size, classes[type]); } var scripts = reader.Count(12); for (var index = 0; index < scripts; index++) { reader.Align(); reader.Skip(12); } var externals = new string[reader.Count(22)]; for (var index = 0; index < externals.Length; index++) { reader.CString(); reader.Skip(20); externals[index] = reader.CString(); } Classes = classes; Objects = objects; Externals = externals; } private sealed class Reader(byte[] data, bool bigEndian) { private int _at; public byte Byte() { Need(1); return data[_at++]; } public int Int32() { Need(4); var span = data.AsSpan(_at, 4); _at += 4; return bigEndian ? BinaryPrimitives.ReadInt32BigEndian(span) : BinaryPrimitives.ReadInt32LittleEndian(span); } public uint UInt32() { return unchecked((uint)Int32()); } public long Int64() { Need(8); var span = data.AsSpan(_at, 8); _at += 8; return bigEndian ? BinaryPrimitives.ReadInt64BigEndian(span) : BinaryPrimitives.ReadInt64LittleEndian(span); } public int Count(int smallest) { var count = Int32(); if (count < 0 || (long)count * smallest > data.Length - _at) throw new InvalidDataException($"A count of {count} doesn't fit the metadata's {data.Length} bytes."); return count; } public string CString() { var end = Array.IndexOf(data, (byte)0, _at); if (end < 0) throw new InvalidDataException("A string runs past the end of the metadata."); var text = Encoding.UTF8.GetString(data, _at, end - _at); _at = end + 1; return text; } public void Skip(long bytes) { if (bytes < 0 || bytes > data.Length - _at) throw new InvalidDataException($"Skipping {bytes} bytes runs past the end of the metadata."); _at += (int)bytes; } public void Align() { Skip((4 - _at % 4) % 4); } private void Need(int bytes) { if (bytes > data.Length - _at) throw new InvalidDataException("The metadata ends early."); } } }