2020-07-09 06:31:15 +02:00
|
|
|
using Ryujinx.Common.Logging;
|
|
|
|
using System;
|
|
|
|
using System.IO;
|
|
|
|
using System.Text;
|
|
|
|
|
|
|
|
namespace Ryujinx.HLE.Loaders.Mods
|
|
|
|
{
|
|
|
|
class IpsPatcher
|
|
|
|
{
|
|
|
|
MemPatch _patches;
|
|
|
|
|
|
|
|
public IpsPatcher(BinaryReader reader)
|
|
|
|
{
|
|
|
|
_patches = ParseIps(reader);
|
|
|
|
if (_patches != null)
|
|
|
|
{
|
2020-08-04 01:32:53 +02:00
|
|
|
Logger.Info?.Print(LogClass.ModLoader, "IPS patch loaded successfully");
|
2020-07-09 06:31:15 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private static MemPatch ParseIps(BinaryReader reader)
|
|
|
|
{
|
2022-11-16 20:30:12 +01:00
|
|
|
ReadOnlySpan<byte> IpsHeaderMagic = "PATCH"u8;
|
|
|
|
ReadOnlySpan<byte> IpsTailMagic = "EOF"u8;
|
|
|
|
ReadOnlySpan<byte> Ips32HeaderMagic = "IPS32"u8;
|
|
|
|
ReadOnlySpan<byte> Ips32TailMagic = "EEOF"u8;
|
2020-07-09 06:31:15 +02:00
|
|
|
|
|
|
|
MemPatch patches = new MemPatch();
|
|
|
|
var header = reader.ReadBytes(IpsHeaderMagic.Length).AsSpan();
|
|
|
|
|
|
|
|
if (header.Length != IpsHeaderMagic.Length)
|
|
|
|
{
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
bool is32;
|
2022-11-16 20:30:12 +01:00
|
|
|
ReadOnlySpan<byte> tailSpan;
|
2020-07-09 06:31:15 +02:00
|
|
|
|
|
|
|
if (header.SequenceEqual(IpsHeaderMagic))
|
|
|
|
{
|
|
|
|
is32 = false;
|
|
|
|
tailSpan = IpsTailMagic;
|
|
|
|
}
|
|
|
|
else if (header.SequenceEqual(Ips32HeaderMagic))
|
|
|
|
{
|
|
|
|
is32 = true;
|
|
|
|
tailSpan = Ips32TailMagic;
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
byte[] buf = new byte[tailSpan.Length];
|
|
|
|
|
|
|
|
bool ReadNext(int size) => reader.Read(buf, 0, size) != size;
|
|
|
|
|
|
|
|
while (true)
|
|
|
|
{
|
|
|
|
if (ReadNext(buf.Length))
|
|
|
|
{
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (buf.AsSpan().SequenceEqual(tailSpan))
|
|
|
|
{
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
|
|
|
int patchOffset = is32 ? buf[0] << 24 | buf[1] << 16 | buf[2] << 8 | buf[3]
|
2021-09-15 01:24:49 +02:00
|
|
|
: buf[0] << 16 | buf[1] << 8 | buf[2];
|
2020-07-09 06:31:15 +02:00
|
|
|
|
|
|
|
if (ReadNext(2))
|
|
|
|
{
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
int patchSize = buf[0] << 8 | buf[1];
|
|
|
|
|
|
|
|
if (patchSize == 0) // RLE/Fill mode
|
|
|
|
{
|
|
|
|
if (ReadNext(2))
|
|
|
|
{
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
int fillLength = buf[0] << 8 | buf[1];
|
|
|
|
|
|
|
|
if (ReadNext(1))
|
|
|
|
{
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
patches.AddFill((uint)patchOffset, fillLength, buf[0]);
|
|
|
|
}
|
|
|
|
else // Copy mode
|
|
|
|
{
|
|
|
|
var patch = reader.ReadBytes(patchSize);
|
|
|
|
|
|
|
|
if (patch.Length != patchSize)
|
|
|
|
{
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
patches.Add((uint)patchOffset, patch);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return patches;
|
|
|
|
}
|
|
|
|
|
|
|
|
public void AddPatches(MemPatch patches)
|
|
|
|
{
|
|
|
|
patches.AddFrom(_patches);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|