Add better il2cpp_array_size_t definition for script outputs in versions post 2017.2.1, fix some other cpp gen issues

This commit is contained in:
LukeFZ
2023-12-02 11:22:32 +01:00
parent f1cb0d14a2
commit e9434f4cad
6 changed files with 2815 additions and 2769 deletions

View File

@@ -575,7 +575,7 @@ namespace Il2CppInspector.Cpp
} }
/* Reserve commonly defined C++ symbols for MSVC DLL projects */ /* Reserve commonly defined C++ symbols for MSVC DLL projects */
/* This is not an exhaustive list! (windows.h etc.) */ /* This is not an exhaustive list! (windows.h etc.) */
foreach (var symbol in new[] {"_int32", "DEFAULT_CHARSET", "FILETIME", "NULL", "SYSTEMTIME", "stderr", "stdin", "stdout"}) { foreach (var symbol in new[] {"_int8", "_int16", "_int32", "_int64", "DEFAULT_CHARSET", "FILETIME", "NULL", "SYSTEMTIME", "stderr", "stdin", "stdout"}) {
ns.ReserveName(symbol); ns.ReserveName(symbol);
} }
/* Reserve builtin keywords in IDA */ /* Reserve builtin keywords in IDA */
@@ -586,7 +586,7 @@ namespace Il2CppInspector.Cpp
"__ptr32", "__ptr64", "__pure", "__restrict", "__return_ptr", "__shifted", "__spoils", "__stdcall", "__struct_ptr", "__ptr32", "__ptr64", "__pure", "__restrict", "__return_ptr", "__shifted", "__spoils", "__stdcall", "__struct_ptr",
"__thiscall", "__thread", "__unaligned", "__usercall", "__userpurge", "__thiscall", "__thread", "__unaligned", "__usercall", "__userpurge",
"_cs", "_ds", "_es", "_ss", "far", "flat", "near", "_cs", "_ds", "_es", "_ss", "far", "flat", "near",
"Mask", "Region", "Pointer", "GC" }) { "Mask", "Region", "Pointer", "GC", "Time" /* wtf? */ }) {
ns.ReserveName(keyword); ns.ReserveName(keyword);
} }
/* Reserve builtin keywords for Ghidra */ /* Reserve builtin keywords for Ghidra */

View File

@@ -383,7 +383,7 @@ namespace Il2CppInspector.Cpp
sb.Append(Name + (Name.Length > 0 ? " " : "")); sb.Append(Name + (Name.Length > 0 ? " " : ""));
sb.Append("{"); sb.Append('{');
foreach (var field in Fields.Values.SelectMany(f => f)) { foreach (var field in Fields.Values.SelectMany(f => f)) {
var fieldString = field.ToString(format); var fieldString = field.ToString(format);
var suffix = ";"; var suffix = ";";
@@ -399,18 +399,19 @@ namespace Il2CppInspector.Cpp
suffix = ""; suffix = "";
} }
sb.Append("\n "); var parts = fieldString.Split('\n');
foreach (var fieldStr in fieldString.Split('\n')) foreach (var part in parts)
{ {
sb.Append(fieldStr);
sb.Append("\n "); sb.Append("\n ");
sb.Append(part);
} }
sb.Append(suffix); sb.Append(suffix);
} }
sb.Append($"\n}}{(format == "o"? $" /* Size: 0x{SizeBytes:x2} */" : "")};"); sb.Append($"\n}}{(format == "o"? $" /* Size: 0x{SizeBytes:x2} */" : "")};");
sb.Append("\n"); sb.Append('\n');
return sb.ToString(); return sb.ToString();
} }
} }

View File

@@ -1,237 +1,239 @@
/* /*
Copyright 2017-2021 Katy Coe - http://www.djkaty.com - https://github.com/djkaty Copyright 2017-2021 Katy Coe - http://www.djkaty.com - https://github.com/djkaty
Copyright 2020 Robert Xiao - https://robertxiao.ca Copyright 2020 Robert Xiao - https://robertxiao.ca
Copyright 2023 LukeFZ - https://github.com/LukeFZ
All rights reserved. All rights reserved.
*/ */
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using NoisyCowStudios.Bin2Object;
namespace Il2CppInspector.Cpp.UnityHeaders
namespace Il2CppInspector.Cpp.UnityHeaders {
{ // Parsed representation of a Unity version number, such as 5.3.0f1 or 2019.3.7.
// Parsed representation of a Unity version number, such as 5.3.0f1 or 2019.3.7. public partial class UnityVersion : IComparable<UnityVersion>, IEquatable<UnityVersion>
public class UnityVersion : IComparable<UnityVersion>, IEquatable<UnityVersion> {
{ // A sorted enumeration of build types, in order of maturity
// A sorted enumeration of build types, in order of maturity public enum BuildTypeEnum
public enum BuildTypeEnum {
{ Unspecified,
Unspecified, Alpha,
Alpha, Beta,
Beta, ReleaseCandidate,
ReleaseCandidate, Final,
Final, Patch,
Patch, }
}
public static string BuildTypeToString(BuildTypeEnum buildType) => buildType switch
public static string BuildTypeToString(BuildTypeEnum buildType) => buildType switch {
{ BuildTypeEnum.Unspecified => "",
BuildTypeEnum.Unspecified => "", BuildTypeEnum.Alpha => "a",
BuildTypeEnum.Alpha => "a", BuildTypeEnum.Beta => "b",
BuildTypeEnum.Beta => "b", BuildTypeEnum.ReleaseCandidate => "rc",
BuildTypeEnum.ReleaseCandidate => "rc", BuildTypeEnum.Final => "f",
BuildTypeEnum.Final => "f", BuildTypeEnum.Patch => "p",
BuildTypeEnum.Patch => "p", _ => throw new ArgumentException(),
_ => throw new ArgumentException(), };
};
public static BuildTypeEnum StringToBuildType(string s) => s switch
public static BuildTypeEnum StringToBuildType(string s) => s switch {
{ "" => BuildTypeEnum.Unspecified,
"" => BuildTypeEnum.Unspecified, "a" => BuildTypeEnum.Alpha,
"a" => BuildTypeEnum.Alpha, "b" => BuildTypeEnum.Beta,
"b" => BuildTypeEnum.Beta, "rc" => BuildTypeEnum.ReleaseCandidate,
"rc" => BuildTypeEnum.ReleaseCandidate, "f" => BuildTypeEnum.Final,
"f" => BuildTypeEnum.Final, "p" => BuildTypeEnum.Patch,
"p" => BuildTypeEnum.Patch, _ => throw new ArgumentException("Unknown build type " + s),
_ => throw new ArgumentException("Unknown build type " + s), };
};
// Unity version number is of the form <Major>.<Minor>.<Update>[<BuildType><BuildNumber>]
// Unity version number is of the form <Major>.<Minor>.<Update>[<BuildType><BuildNumber>] public int Major { get; }
public int Major { get; } public int Minor { get; }
public int Minor { get; } public int Update { get; }
public int Update { get; } public BuildTypeEnum BuildType { get; }
public BuildTypeEnum BuildType { get; } public int BuildNumber { get; }
public int BuildNumber { get; }
public UnityVersion(string versionString) {
public UnityVersion(string versionString) { var match = VersionRegex().Match(versionString);
var match = Regex.Match(versionString, @"^(\d+)\.(\d+)(?:\.(\d+))?(?:([a-zA-Z]+)(\d+))?$"); if (!match.Success)
if (!match.Success) throw new ArgumentException($"'${versionString}' is not a valid Unity version number.");
throw new ArgumentException($"'${versionString}' is not a valid Unity version number."); Major = int.Parse(match.Groups[1].Value);
Major = int.Parse(match.Groups[1].Value); Minor = int.Parse(match.Groups[2].Value);
Minor = int.Parse(match.Groups[2].Value); Update = match.Groups[3].Success ? int.Parse(match.Groups[3].Value) : 0;
Update = match.Groups[3].Success ? int.Parse(match.Groups[3].Value) : 0; BuildType = match.Groups[4].Success ? StringToBuildType(match.Groups[4].Value) : BuildTypeEnum.Unspecified;
BuildType = match.Groups[4].Success ? StringToBuildType(match.Groups[4].Value) : BuildTypeEnum.Unspecified; BuildNumber = match.Groups[5].Success ? int.Parse(match.Groups[5].Value) : 0;
BuildNumber = match.Groups[5].Success ? int.Parse(match.Groups[5].Value) : 0; }
}
// Get a Unity version from a Unity asset file
// Get a Unity version from a Unity asset file public static UnityVersion FromAssetFile(string filePath) {
public static UnityVersion FromAssetFile(string filePath) { // Don't use BinaryObjectStream because we'd have to read the entire file into memory
// Don't use BinaryObjectStream because we'd have to read the entire file into memory using var file = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
using var file = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); using var reader = new BinaryReader(file, System.Text.Encoding.UTF8);
using var reader = new BinaryReader(file, System.Text.Encoding.UTF8);
// Position of Unity version string in asset files
// Position of Unity version string in asset files file.Position = 0x14;
file.Position = 0x14;
// Read null-terminated string
// Read null-terminated string var bytes = new List<byte>();
var bytes = new List<byte>(); var maxLength = 15;
var maxLength = 15; byte b;
byte b; while ((b = reader.ReadByte()) != 0 && bytes.Count < maxLength)
while ((b = reader.ReadByte()) != 0 && bytes.Count < maxLength) bytes.Add(b);
bytes.Add(b);
var unityString = System.Text.Encoding.UTF8.GetString(bytes.ToArray());
var unityString = System.Text.Encoding.UTF8.GetString(bytes.ToArray()); return new UnityVersion(unityString);
return new UnityVersion(unityString); }
}
public static implicit operator UnityVersion(string versionString) => new(versionString);
public static implicit operator UnityVersion(string versionString) => new UnityVersion(versionString);
public override string ToString() {
public override string ToString() { var res = $"{Major}.{Minor}.{Update}";
var res = $"{Major}.{Minor}.{Update}"; if (BuildType != BuildTypeEnum.Unspecified)
if (BuildType != BuildTypeEnum.Unspecified) res += $"{BuildTypeToString(BuildType)}{BuildNumber}";
res += $"{BuildTypeToString(BuildType)}{BuildNumber}"; return res;
return res; }
}
// Compare two version numbers, intransitively (due to the Unspecified build type)
// Compare two version numbers, intransitively (due to the Unspecified build type) public int CompareTo(UnityVersion other) {
public int CompareTo(UnityVersion other) { // null means maximum possible version
// null means maximum possible version if (other == null)
if (other == null) return -1;
return -1; int res;
int res; if (0 != (res = Major.CompareTo(other.Major)))
if (0 != (res = Major.CompareTo(other.Major))) return res;
return res; if (0 != (res = Minor.CompareTo(other.Minor)))
if (0 != (res = Minor.CompareTo(other.Minor))) return res;
return res; if (0 != (res = Update.CompareTo(other.Update)))
if (0 != (res = Update.CompareTo(other.Update))) return res;
return res; // same major.minor.update - if one of these is suffix-less, they compare equal
// same major.minor.update - if one of these is suffix-less, they compare equal // yes, this makes the compare function non-transitive; don't use it to sort things
// yes, this makes the compare function non-transitive; don't use it to sort things if (BuildType == BuildTypeEnum.Unspecified || other.BuildType == BuildTypeEnum.Unspecified)
if (BuildType == BuildTypeEnum.Unspecified || other.BuildType == BuildTypeEnum.Unspecified) return 0;
return 0; if (0 != (res = BuildType.CompareTo(other.BuildType)))
if (0 != (res = BuildType.CompareTo(other.BuildType))) return res;
return res; if (0 != (res = BuildNumber.CompareTo(other.BuildNumber)))
if (0 != (res = BuildNumber.CompareTo(other.BuildNumber))) return res;
return res; return 0;
return 0; }
}
// Equality comparisons
// Equality comparisons public static bool operator ==(UnityVersion first, UnityVersion second) {
public static bool operator ==(UnityVersion first, UnityVersion second) { if (ReferenceEquals(first, second))
if (ReferenceEquals(first, second)) return true;
return true; if (ReferenceEquals(first, null) || ReferenceEquals(second, null))
if (ReferenceEquals(first, null) || ReferenceEquals(second, null)) return false;
return false; return first.Equals(second);
return first.Equals(second); }
}
public static bool operator !=(UnityVersion first, UnityVersion second) => !(first == second);
public static bool operator !=(UnityVersion first, UnityVersion second) => !(first == second);
public override bool Equals(object obj) => Equals(obj as UnityVersion);
public override bool Equals(object obj) => Equals(obj as UnityVersion);
public bool Equals(UnityVersion other) {
public bool Equals(UnityVersion other) { return other != null &&
return other != null && Major == other.Major &&
Major == other.Major && Minor == other.Minor &&
Minor == other.Minor && Update == other.Update &&
Update == other.Update && BuildType == other.BuildType &&
BuildType == other.BuildType && BuildNumber == other.BuildNumber;
BuildNumber == other.BuildNumber; }
}
public override int GetHashCode() => HashCode.Combine(Major, Minor, Update, BuildType, BuildNumber);
public override int GetHashCode() => HashCode.Combine(Major, Minor, Update, BuildType, BuildNumber);
} [GeneratedRegex(@"^(\d+)\.(\d+)(?:\.(\d+))?(?:([a-zA-Z]+)(\d+))?$")]
private static partial Regex VersionRegex();
// A range of Unity versions }
public class UnityVersionRange : IComparable<UnityVersionRange>, IEquatable<UnityVersionRange>
{ // A range of Unity versions
// Minimum and maximum Unity version numbers for this range. Both endpoints are inclusive public class UnityVersionRange : IComparable<UnityVersionRange>, IEquatable<UnityVersionRange>
// Max can be null to specify no upper bound {
public UnityVersion Min { get; } // Minimum and maximum Unity version numbers for this range. Both endpoints are inclusive
public UnityVersion Max { get; } // Max can be null to specify no upper bound
public UnityVersion Min { get; }
// Determine if this range contains the specified version public UnityVersion Max { get; }
public bool Contains(UnityVersion version) => version.CompareTo(Min) >= 0 && (Max == null || version.CompareTo(Max) <= 0);
// Determine if this range contains the specified version
public UnityVersionRange(UnityVersion min, UnityVersion max) { public bool Contains(UnityVersion version) => version.CompareTo(Min) >= 0 && (Max == null || version.CompareTo(Max) <= 0);
Min = min;
Max = max; public UnityVersionRange(UnityVersion min, UnityVersion max) {
} Min = min;
Max = max;
// Create a version range from a string, in the format "[Il2CppInspector.Cpp.<namespace-leaf>.][metadataVersion-]<min>-[max].h" }
public static UnityVersionRange FromFilename(string headerFilename) {
var baseNamespace = "Il2CppInspector.Cpp."; // Create a version range from a string, in the format "[Il2CppInspector.Cpp.<namespace-leaf>.][metadataVersion-]<min>-[max].h"
headerFilename = headerFilename.Replace(".h", ""); public static UnityVersionRange FromFilename(string headerFilename) {
var baseNamespace = "Il2CppInspector.Cpp.";
if (headerFilename.StartsWith(baseNamespace)) { headerFilename = headerFilename.Replace(".h", "");
headerFilename = headerFilename.Substring(baseNamespace.Length);
headerFilename = headerFilename.Substring(headerFilename.IndexOf(".") + 1); if (headerFilename.StartsWith(baseNamespace)) {
} headerFilename = headerFilename.Substring(baseNamespace.Length);
headerFilename = headerFilename.Substring(headerFilename.IndexOf(".") + 1);
var bits = headerFilename.Split("-"); }
// Metadata version supplied var bits = headerFilename.Split("-");
// Note: This relies on the metadata version being either 2 or 4 characters,
// and that the smallest Unity version must be 5 characters or more // Metadata version supplied
if (headerFilename[2] == '-' || headerFilename[4] == '-') // Note: This relies on the metadata version being either 2 or 4 characters,
bits = bits.Skip(1).ToArray(); // and that the smallest Unity version must be 5 characters or more
if (headerFilename[2] == '-' || headerFilename[4] == '-')
var Min = new UnityVersion(bits[0]); bits = bits.Skip(1).ToArray();
UnityVersion Max = null;
var Min = new UnityVersion(bits[0]);
if (bits.Length == 1) UnityVersion Max = null;
Max = Min;
if (bits.Length == 2 && bits[1] != "") if (bits.Length == 1)
Max = new UnityVersion(bits[1]); Max = Min;
if (bits.Length == 2 && bits[1] != "")
return new UnityVersionRange(Min, Max); Max = new UnityVersion(bits[1]);
}
return new UnityVersionRange(Min, Max);
// Compare and sort based on the lowest version number }
public int CompareTo(UnityVersionRange other) => Min.CompareTo(other.Min);
// Compare and sort based on the lowest version number
// Intersect two ranges to find the smallest shared set of versions public int CompareTo(UnityVersionRange other) => Min.CompareTo(other.Min);
// Returns null if the two ranges do not intersect
// Max == null means no upper bound on version // Intersect two ranges to find the smallest shared set of versions
public UnityVersionRange Intersect(UnityVersionRange other) { // Returns null if the two ranges do not intersect
var highestLow = Min.CompareTo(other.Min) > 0 ? Min : other.Min; // Max == null means no upper bound on version
var lowestHigh = Max == null? other.Max : Max.CompareTo(other.Max) < 0 ? Max : other.Max; public UnityVersionRange Intersect(UnityVersionRange other) {
var highestLow = Min.CompareTo(other.Min) > 0 ? Min : other.Min;
if (highestLow.CompareTo(lowestHigh) > 0) var lowestHigh = Max == null? other.Max : Max.CompareTo(other.Max) < 0 ? Max : other.Max;
return null;
if (highestLow.CompareTo(lowestHigh) > 0)
return new UnityVersionRange(highestLow, lowestHigh); return null;
}
return new UnityVersionRange(highestLow, lowestHigh);
public override string ToString() { }
var res = $"{Min}";
if (Max == null) public override string ToString() {
res += "+"; var res = $"{Min}";
else if (!Max.Equals(Min)) if (Max == null)
res += $" - {Max}"; res += "+";
return res; else if (!Max.Equals(Min))
} res += $" - {Max}";
return res;
// Equality comparisons }
public static bool operator ==(UnityVersionRange first, UnityVersionRange second) {
if (ReferenceEquals(first, second)) // Equality comparisons
return true; public static bool operator ==(UnityVersionRange first, UnityVersionRange second) {
if (ReferenceEquals(first, null) || ReferenceEquals(second, null)) if (ReferenceEquals(first, second))
return false; return true;
return first.Equals(second); if (ReferenceEquals(first, null) || ReferenceEquals(second, null))
} return false;
return first.Equals(second);
public static bool operator !=(UnityVersionRange first, UnityVersionRange second) => !(first == second); }
public override bool Equals(object obj) => Equals(obj as UnityVersionRange); public static bool operator !=(UnityVersionRange first, UnityVersionRange second) => !(first == second);
public bool Equals(UnityVersionRange other) => Min.Equals(other?.Min) public override bool Equals(object obj) => Equals(obj as UnityVersionRange);
&& ((Max != null && Max.Equals(other?.Max))
|| (Max == null && other != null && other.Max == null)); public bool Equals(UnityVersionRange other) => Min.Equals(other?.Min)
&& ((Max != null && Max.Equals(other?.Max))
public override int GetHashCode() => HashCode.Combine(Min, Max); || (Max == null && other != null && other.Max == null));
}
public override int GetHashCode() => HashCode.Combine(Min, Max);
}
} }

View File

@@ -1,295 +1,338 @@
// Copyright 2020 Robert Xiao - https://robertxiao.ca/ // Copyright 2020 Robert Xiao - https://robertxiao.ca/
// Copyright (c) 2020-2021 Katy Coe - http://www.djkaty.com - https://github.com/djkaty // Copyright (c) 2020-2021 Katy Coe - http://www.djkaty.com - https://github.com/djkaty
// All rights reserved // Copyright (c) 2023 LukeFZ https://github.com/LukeFZ
// All rights reserved
using System;
using System.Linq; using System;
using System.IO; using System.Linq;
using System.Text; using System.IO;
using System.Text.RegularExpressions; using System.Text;
using Il2CppInspector.Reflection; using System.Text.RegularExpressions;
using Il2CppInspector.Cpp; using Il2CppInspector.Reflection;
using Il2CppInspector.Cpp.UnityHeaders; using Il2CppInspector.Cpp;
using Il2CppInspector.Model; using Il2CppInspector.Cpp.UnityHeaders;
using Il2CppInspector.Properties; using Il2CppInspector.Model;
using Il2CppInspector.Properties;
namespace Il2CppInspector.Outputs
{ namespace Il2CppInspector.Outputs
public class CppScaffolding {
{ public partial class CppScaffolding(AppModel model, bool useBetterArraySize = false)
private readonly AppModel model; {
private StreamWriter writer; private readonly AppModel _model = model;
private readonly Regex rgxGCCalign = new Regex(@"__attribute__\s*?\(\s*?\(\s*?aligned\s*?\(\s*?([0-9]+)\s*?\)\s*?\)\s*?\)"); /*
private readonly Regex rgxMSVCalign = new Regex(@"__declspec\s*?\(\s*?align\s*?\(\s*?([0-9]+)\s*?\)\s*?\)"); * 2017.2.1 changed the type of il2cpp_array_size_t to uintptr_t from int32_t. The code, however, uses static_cast<int32_t>(maxLength) to access this value,
* which makes decompilation a bit unpleasant due to it only ever checking the lower 32 bits.
public CppScaffolding(AppModel model) => this.model = model; * The better array size type is a union of the actual size (int32_t) and the actual value (uintptr_t) which should hopefully improve decompilation.
*/
// Write the type header private readonly bool _useBetterArraySize =
// This can be used by other output modules model.UnityVersion.CompareTo("2017.2.1") >= 0
public void WriteTypes(string typeHeaderFile) { && model.Package.BinaryImage.Bits == 64
using var fs = new FileStream(typeHeaderFile, FileMode.Create); && useBetterArraySize;
writer = new StreamWriter(fs, Encoding.ASCII);
private StreamWriter _writer;
writeHeader();
// Write the type header
// Write primitive type definitions for when we're not including other headers // This can be used by other output modules
writeCode($@"#if defined(_GHIDRA_) || defined(_IDA_) public void WriteTypes(string typeHeaderFile) {
typedef unsigned __int8 uint8_t; using var fs = new FileStream(typeHeaderFile, FileMode.Create);
typedef unsigned __int16 uint16_t; _writer = new StreamWriter(fs, Encoding.ASCII);
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t; using (_writer)
typedef __int8 int8_t; {
typedef __int16 int16_t; writeHeader();
typedef __int32 int32_t;
typedef __int64 int64_t; // Write primitive type definitions for when we're not including other headers
#endif writeCode($$"""
#if defined(_GHIDRA_) || defined(_IDA_)
#if defined(_GHIDRA_) typedef unsigned __int8 uint8_t;
typedef __int{model.Package.BinaryImage.Bits} size_t; typedef unsigned __int16 uint16_t;
typedef size_t intptr_t; typedef unsigned __int32 uint32_t;
typedef size_t uintptr_t; typedef unsigned __int64 uint64_t;
#endif typedef __int8 int8_t;
typedef __int16 int16_t;
#if !defined(_GHIDRA_) && !defined(_IDA_) typedef __int32 int32_t;
#define _CPLUSPLUS_ typedef __int64 int64_t;
#endif #endif
");
#if defined(_GHIDRA_)
writeSectionHeader("IL2CPP internal types"); typedef __int{{_model.Package.BinaryImage.Bits}} size_t;
writeCode(model.UnityHeaders.GetTypeHeaderText(model.WordSizeBits)); typedef size_t intptr_t;
typedef size_t uintptr_t;
// Stop MSVC complaining about out-of-bounds enum values #endif
if (model.TargetCompiler == CppCompilerType.MSVC)
writeCode("#pragma warning(disable : 4369)"); #if !defined(_GHIDRA_) && !defined(_IDA_)
#define _CPLUSPLUS_
// Stop MSVC complaining about constant truncation of enum values #endif
if (model.TargetCompiler == CppCompilerType.MSVC) """);
writeCode("#pragma warning(disable : 4309)");
if (_useBetterArraySize)
// MSVC will (rightly) throw a compiler warning when compiling for 32-bit architectures writeCode("#define il2cpp_array_size_t actual_il2cpp_array_size_t");
// if the specified alignment of a type is smaller than the size of its largest element.
// We keep the alignments in to make them match Il2CppObject wherever possible, but it is writeSectionHeader("IL2CPP internal types");
// safe to ignore them if they are too small, so we just disable the warning writeCode(_model.UnityHeaders.GetTypeHeaderText(_model.WordSizeBits));
if (model.TargetCompiler == CppCompilerType.MSVC)
writeCode("#pragma warning(disable : 4359)"); if (_useBetterArraySize)
writeCode("""
// C does not support namespaces #undef il2cpp_array_size_t
writeCode("#if !defined(_GHIDRA_) && !defined(_IDA_)");
writeCode("namespace app {"); typedef union better_il2cpp_array_size_t
writeCode("#endif"); {
writeLine(""); int32_t size;
actual_il2cpp_array_size_t value;
writeTypesForGroup("Application types from method calls", "types_from_methods"); } better_il2cpp_array_size_t;
writeTypesForGroup("Application types from generic methods", "types_from_generic_methods");
writeTypesForGroup("Application types from usages", "types_from_usages"); #define il2cpp_array_size_t better_il2cpp_array_size_t
writeTypesForGroup("Application unused value types", "unused_concrete_types"); """);
writeCode("#if !defined(_GHIDRA_) && !defined(_IDA_)"); if (_model.TargetCompiler == CppCompilerType.MSVC)
writeCode("}"); {
writeCode("#endif"); // Stop MSVC complaining about out-of-bounds enum values
writeCode("#pragma warning(disable : 4369)");
writer.Close();
} // Stop MSVC complaining about constant truncation of enum values
writeCode("#pragma warning(disable : 4309)");
public void Write(string projectPath) {
// Ensure output directory exists and is not a file // MSVC will (rightly) throw a compiler warning when compiling for 32-bit architectures
// A System.IOException will be thrown if it's a file' // if the specified alignment of a type is smaller than the size of its largest element.
var srcUserPath = Path.Combine(projectPath, "user"); // We keep the alignments in to make them match Il2CppObject wherever possible, but it is
var srcFxPath = Path.Combine(projectPath, "framework"); // safe to ignore them if they are too small, so we just disable the warning
var srcDataPath = Path.Combine(projectPath, "appdata"); writeCode("#pragma warning(disable : 4359)");
}
Directory.CreateDirectory(projectPath);
Directory.CreateDirectory(srcUserPath); // C does not support namespaces
Directory.CreateDirectory(srcFxPath); writeCode("#if !defined(_GHIDRA_) && !defined(_IDA_)");
Directory.CreateDirectory(srcDataPath); writeCode("namespace app {");
writeCode("#endif");
// Write type definitions to il2cpp-types.h writeLine("");
WriteTypes(Path.Combine(srcDataPath, "il2cpp-types.h"));
writeTypesForGroup("Application types from method calls", "types_from_methods");
// Write selected Unity API function file to il2cpp-api-functions.h writeTypesForGroup("Application types from generic methods", "types_from_generic_methods");
// (this is a copy of the header file from an actual Unity install) writeTypesForGroup("Application types from usages", "types_from_usages");
var il2cppApiFile = Path.Combine(srcDataPath, "il2cpp-api-functions.h"); writeTypesForGroup("Application unused value types", "unused_concrete_types");
var apiHeaderText = model.UnityHeaders.GetAPIHeaderText();
writeCode("#if !defined(_GHIDRA_) && !defined(_IDA_)");
using var fsApi = new FileStream(il2cppApiFile, FileMode.Create); writeCode("}");
writer = new StreamWriter(fsApi, Encoding.ASCII); writeCode("#endif");
}
writeHeader(); }
// Elide APIs that aren't in the binary to avoid compile errors public void Write(string projectPath) {
foreach (var line in apiHeaderText.Split('\n')) { // Ensure output directory exists and is not a file
var fnName = UnityHeaders.GetFunctionNameFromAPILine(line); // A System.IOException will be thrown if it's a file'
var srcUserPath = Path.Combine(projectPath, "user");
if (string.IsNullOrEmpty(fnName)) var srcFxPath = Path.Combine(projectPath, "framework");
writer.WriteLine(line); var srcDataPath = Path.Combine(projectPath, "appdata");
else if (model.AvailableAPIs.ContainsKey(fnName))
writer.WriteLine(line); Directory.CreateDirectory(projectPath);
} Directory.CreateDirectory(srcUserPath);
writer.Close(); Directory.CreateDirectory(srcFxPath);
Directory.CreateDirectory(srcDataPath);
// Write API function pointers to il2cpp-api-functions-ptr.h
var il2cppFnPtrFile = Path.Combine(srcDataPath, "il2cpp-api-functions-ptr.h"); // Write type definitions to il2cpp-types.h
WriteTypes(Path.Combine(srcDataPath, "il2cpp-types.h"));
using var fs2 = new FileStream(il2cppFnPtrFile, FileMode.Create);
writer = new StreamWriter(fs2, Encoding.ASCII); // Write selected Unity API function file to il2cpp-api-functions.h
// (this is a copy of the header file from an actual Unity install)
writeHeader(); var il2cppApiFile = Path.Combine(srcDataPath, "il2cpp-api-functions.h");
writeSectionHeader("IL2CPP API function pointers"); var apiHeaderText = _model.UnityHeaders.GetAPIHeaderText();
// We could use model.AvailableAPIs here but that would exclude outputting the address using var fsApi = new FileStream(il2cppApiFile, FileMode.Create);
// of API exports which for some reason aren't defined in our selected API header, _writer = new StreamWriter(fsApi, Encoding.ASCII);
// so although it doesn't affect the C++ compilation, we use GetAPIExports() instead for completeness
var exports = model.Package.Binary.APIExports; using (_writer)
{
foreach (var export in exports) { writeHeader();
writeCode($"#define {export.Key}_ptr 0x{model.Package.BinaryImage.MapVATR(export.Value):X8}");
} // Elide APIs that aren't in the binary to avoid compile errors
foreach (var line in apiHeaderText.Split('\n'))
writer.Close(); {
var fnName = UnityHeaders.GetFunctionNameFromAPILine(line);
// Write application type definition addresses to il2cpp-types-ptr.h
var il2cppTypeInfoFile = Path.Combine(srcDataPath, "il2cpp-types-ptr.h"); if (string.IsNullOrEmpty(fnName))
_writer.WriteLine(line);
using var fs3 = new FileStream(il2cppTypeInfoFile, FileMode.Create); else if (_model.AvailableAPIs.ContainsKey(fnName))
writer = new StreamWriter(fs3, Encoding.ASCII); _writer.WriteLine(line);
}
writeHeader(); }
writeSectionHeader("IL2CPP application-specific type definition addresses");
// Write API function pointers to il2cpp-api-functions-ptr.h
foreach (var type in model.Types.Values.Where(t => t.TypeClassAddress != 0xffffffff_ffffffff)) { var il2cppFnPtrFile = Path.Combine(srcDataPath, "il2cpp-api-functions-ptr.h");
writeCode($"DO_TYPEDEF(0x{type.TypeClassAddress - model.Package.BinaryImage.ImageBase:X8}, {type.Name});");
} using var fs2 = new FileStream(il2cppFnPtrFile, FileMode.Create);
_writer = new StreamWriter(fs2, Encoding.ASCII);
writer.Close();
using (_writer)
// Write method pointers and signatures to il2cpp-functions.h {
var methodFile = Path.Combine(srcDataPath, "il2cpp-functions.h"); writeHeader();
writeSectionHeader("IL2CPP API function pointers");
using var fs4 = new FileStream(methodFile, FileMode.Create);
writer = new StreamWriter(fs4, Encoding.ASCII); // We could use _model.AvailableAPIs here but that would exclude outputting the address
// of API exports which for some reason aren't defined in our selected API header,
writeHeader(); // so although it doesn't affect the C++ compilation, we use GetAPIExports() instead for completeness
writeSectionHeader("IL2CPP application-specific method definition addresses and signatures"); var exports = _model.Package.Binary.APIExports;
writeCode("using namespace app;"); foreach (var export in exports)
writeLine(""); {
writeCode($"#define {export.Key}_ptr 0x{_model.Package.BinaryImage.MapVATR(export.Value):X8}");
foreach (var method in model.Methods.Values) { }
if (method.HasCompiledCode) { }
var arguments = string.Join(", ", method.CppFnPtrType.Arguments.Select(a => a.Type.Name + " " + (a.Name == "this" ? "__this" : a.Name)));
// Write application type definition addresses to il2cpp-types-ptr.h
writeCode($"DO_APP_FUNC(0x{method.MethodCodeAddress - model.Package.BinaryImage.ImageBase:X8}, {method.CppFnPtrType.ReturnType.Name}, " var il2cppTypeInfoFile = Path.Combine(srcDataPath, "il2cpp-types-ptr.h");
+ $"{method.CppFnPtrType.Name}, ({arguments}));");
} using var fs3 = new FileStream(il2cppTypeInfoFile, FileMode.Create);
_writer = new StreamWriter(fs3, Encoding.ASCII);
if (method.HasMethodInfo) {
writeCode($"DO_APP_FUNC_METHODINFO(0x{method.MethodInfoPtrAddress - model.Package.BinaryImage.ImageBase:X8}, {method.CppFnPtrType.Name}__MethodInfo);"); using (_writer)
} {
} writeHeader();
writeSectionHeader("IL2CPP application-specific type definition addresses");
writer.Close();
foreach (var type in _model.Types.Values.Where(t => t.TypeClassAddress != 0xffffffff_ffffffff))
// Write metadata version {
var versionFile = Path.Combine(srcDataPath, "il2cpp-metadata-version.h"); writeCode($"DO_TYPEDEF(0x{type.TypeClassAddress - _model.Package.BinaryImage.ImageBase:X8}, {type.Name});");
}
using var fs5 = new FileStream(versionFile, FileMode.Create); }
writer = new StreamWriter(fs5, Encoding.ASCII);
// Write method pointers and signatures to il2cpp-functions.h
writeHeader(); var methodFile = Path.Combine(srcDataPath, "il2cpp-functions.h");
writeCode($"#define __IL2CPP_METADATA_VERSION {model.Package.Version * 10:F0}");
using var fs4 = new FileStream(methodFile, FileMode.Create);
writer.Close(); _writer = new StreamWriter(fs4, Encoding.ASCII);
// Write boilerplate code using (_writer)
File.WriteAllText(Path.Combine(srcFxPath, "dllmain.cpp"), Resources.Cpp_DLLMainCpp); {
File.WriteAllText(Path.Combine(srcFxPath, "helpers.cpp"), Resources.Cpp_HelpersCpp); writeHeader();
File.WriteAllText(Path.Combine(srcFxPath, "helpers.h"), Resources.Cpp_HelpersH); writeSectionHeader("IL2CPP application-specific method definition addresses and signatures");
File.WriteAllText(Path.Combine(srcFxPath, "il2cpp-appdata.h"), Resources.Cpp_Il2CppAppDataH);
File.WriteAllText(Path.Combine(srcFxPath, "il2cpp-init.cpp"), Resources.Cpp_Il2CppInitCpp); writeCode("using namespace app;");
File.WriteAllText(Path.Combine(srcFxPath, "il2cpp-init.h"), Resources.Cpp_Il2CppInitH); writeLine("");
File.WriteAllText(Path.Combine(srcFxPath, "pch-il2cpp.cpp"), Resources.Cpp_PCHIl2Cpp);
File.WriteAllText(Path.Combine(srcFxPath, "pch-il2cpp.h"), Resources.Cpp_PCHIl2CppH); foreach (var method in _model.Methods.Values)
{
// Write user code without overwriting existing code if (method.HasCompiledCode)
void WriteIfNotExists(string path, string contents) { if (!File.Exists(path)) File.WriteAllText(path, contents); } {
var arguments = string.Join(", ", method.CppFnPtrType.Arguments.Select(a => a.Type.Name + " " + (a.Name == "this" ? "__this" : a.Name)));
WriteIfNotExists(Path.Combine(srcUserPath, "main.cpp"), Resources.Cpp_MainCpp);
WriteIfNotExists(Path.Combine(srcUserPath, "main.h"), Resources.Cpp_MainH); writeCode($"DO_APP_FUNC(0x{method.MethodCodeAddress - _model.Package.BinaryImage.ImageBase:X8}, {method.CppFnPtrType.ReturnType.Name}, "
+ $"{method.CppFnPtrType.Name}, ({arguments}));");
// Write Visual Studio project and solution files }
var projectGuid = Guid.NewGuid();
var projectName = "IL2CppDLL"; if (method.HasMethodInfo)
var projectFile = projectName + ".vcxproj"; {
writeCode($"DO_APP_FUNC_METHODINFO(0x{method.MethodInfoPtrAddress - _model.Package.BinaryImage.ImageBase:X8}, {method.CppFnPtrType.Name}__MethodInfo);");
WriteIfNotExists(Path.Combine(projectPath, projectFile), }
Resources.CppProjTemplate.Replace("%PROJECTGUID%", projectGuid.ToString())); }
}
var guid1 = Guid.NewGuid();
var guid2 = Guid.NewGuid(); // Write metadata version
var guid3 = Guid.NewGuid(); var versionFile = Path.Combine(srcDataPath, "il2cpp-metadata-version.h");
var filtersFile = projectFile + ".filters";
using var fs5 = new FileStream(versionFile, FileMode.Create);
var filters = Resources.CppProjFilters _writer = new StreamWriter(fs5, Encoding.ASCII);
.Replace("%GUID1%", guid1.ToString())
.Replace("%GUID2%", guid2.ToString()) using (_writer)
.Replace("%GUID3%", guid3.ToString()); {
writeHeader();
WriteIfNotExists(Path.Combine(projectPath, filtersFile), filters); writeCode($"#define __IL2CPP_METADATA_VERSION {_model.Package.Version * 10:F0}");
}
var solutionGuid = Guid.NewGuid();
var solutionFile = projectName + ".sln"; // Write boilerplate code
File.WriteAllText(Path.Combine(srcFxPath, "dllmain.cpp"), Resources.Cpp_DLLMainCpp);
var sln = Resources.CppSlnTemplate File.WriteAllText(Path.Combine(srcFxPath, "helpers.cpp"), Resources.Cpp_HelpersCpp);
.Replace("%PROJECTGUID%", projectGuid.ToString()) File.WriteAllText(Path.Combine(srcFxPath, "helpers.h"), Resources.Cpp_HelpersH);
.Replace("%PROJECTNAME%", projectName) File.WriteAllText(Path.Combine(srcFxPath, "il2cpp-appdata.h"), Resources.Cpp_Il2CppAppDataH);
.Replace("%PROJECTFILE%", projectFile) File.WriteAllText(Path.Combine(srcFxPath, "il2cpp-init.cpp"), Resources.Cpp_Il2CppInitCpp);
.Replace("%SOLUTIONGUID%", solutionGuid.ToString()); File.WriteAllText(Path.Combine(srcFxPath, "il2cpp-init.h"), Resources.Cpp_Il2CppInitH);
File.WriteAllText(Path.Combine(srcFxPath, "pch-il2cpp.cpp"), Resources.Cpp_PCHIl2Cpp);
WriteIfNotExists(Path.Combine(projectPath, solutionFile), sln); File.WriteAllText(Path.Combine(srcFxPath, "pch-il2cpp.h"), Resources.Cpp_PCHIl2CppH);
}
// Write user code without overwriting existing code
private void writeHeader() { void WriteIfNotExists(string path, string contents) { if (!File.Exists(path)) File.WriteAllText(path, contents); }
writeLine("// Generated C++ file by Il2CppInspector - http://www.djkaty.com - https://github.com/djkaty");
writeLine("// Target Unity version: " + model.UnityHeaders); WriteIfNotExists(Path.Combine(srcUserPath, "main.cpp"), Resources.Cpp_MainCpp);
writeLine(""); WriteIfNotExists(Path.Combine(srcUserPath, "main.h"), Resources.Cpp_MainH);
}
// Write Visual Studio project and solution files
private void writeTypesForGroup(string header, string group) { var projectGuid = Guid.NewGuid();
writeSectionHeader(header); var projectName = "IL2CppDLL";
foreach (var cppType in model.GetDependencyOrderedCppTypeGroup(group)) var projectFile = projectName + ".vcxproj";
if (cppType is CppEnumType) {
// Ghidra can't process C++ enum base types WriteIfNotExists(Path.Combine(projectPath, projectFile),
writeCode("#if defined(_CPLUSPLUS_)"); Resources.CppProjTemplate.Replace("%PROJECTGUID%", projectGuid.ToString()));
writeCode(cppType.ToString());
writeCode("#else"); var guid1 = Guid.NewGuid();
writeCode(cppType.ToString("c")); var guid2 = Guid.NewGuid();
writeCode("#endif"); var guid3 = Guid.NewGuid();
} else { var filtersFile = projectFile + ".filters";
writeCode(cppType.ToString());
} var filters = Resources.CppProjFilters
} .Replace("%GUID1%", guid1.ToString())
.Replace("%GUID2%", guid2.ToString())
private void writeCode(string text) { .Replace("%GUID3%", guid3.ToString());
if (model.TargetCompiler == CppCompilerType.MSVC)
text = rgxGCCalign.Replace(text, @"__declspec(align($1))"); WriteIfNotExists(Path.Combine(projectPath, filtersFile), filters);
if (model.TargetCompiler == CppCompilerType.GCC)
text = rgxMSVCalign.Replace(text, @"__attribute__((aligned($1)))"); var solutionGuid = Guid.NewGuid();
var solutionFile = projectName + ".sln";
var lines = text.Replace("\r", "").Split('\n');
var cleanLines = lines.Select(s => s.ToEscapedString()); var sln = Resources.CppSlnTemplate
var declString = string.Join('\n', cleanLines); .Replace("%PROJECTGUID%", projectGuid.ToString())
if (declString != "") .Replace("%PROJECTNAME%", projectName)
writeLine(declString); .Replace("%PROJECTFILE%", projectFile)
} .Replace("%SOLUTIONGUID%", solutionGuid.ToString());
private void writeSectionHeader(string name) { WriteIfNotExists(Path.Combine(projectPath, solutionFile), sln);
writeLine("// ******************************************************************************"); }
writeLine("// * " + name);
writeLine("// ******************************************************************************"); private void writeHeader() {
writeLine(""); writeLine("// Generated C++ file by Il2CppInspector - http://www.djkaty.com - https://github.com/djkaty");
} writeLine("// Target Unity version: " + _model.UnityHeaders);
writeLine("");
private void writeLine(string line) => writer.WriteLine(line); }
}
} private void writeTypesForGroup(string header, string group) {
writeSectionHeader(header);
foreach (var cppType in _model.GetDependencyOrderedCppTypeGroup(group))
if (cppType is CppEnumType) {
// Ghidra can't process C++ enum base types
writeCode("#if defined(_CPLUSPLUS_)");
writeCode(cppType.ToString());
writeCode("#else");
writeCode(cppType.ToString("c"));
writeCode("#endif");
} else {
writeCode(cppType.ToString());
}
}
private void writeCode(string text) {
if (_model.TargetCompiler == CppCompilerType.MSVC)
text = GccAlignRegex().Replace(text, @"__declspec(align($1))");
else if (_model.TargetCompiler == CppCompilerType.GCC)
text = MsvcAlignRegex().Replace(text, @"__attribute__((aligned($1)))");
var lines = text.Replace("\r", "").Split('\n');
//var cleanLines = lines.Select(s => s.ToEscapedString()); Not sure if this is necessary? maybe for some obfuscated assemblies, but those would just fail on other steps
foreach (var line in lines)
writeLine(line);
}
private void writeSectionHeader(string name) {
writeLine("// ******************************************************************************");
writeLine("// * " + name);
writeLine("// ******************************************************************************");
writeLine("");
}
private void writeLine(string line) => _writer.WriteLine(line);
[GeneratedRegex(@"__attribute__\s*?\(\s*?\(\s*?aligned\s*?\(\s*?([0-9]+)\s*?\)\s*?\)\s*?\)")]
private static partial Regex GccAlignRegex();
[GeneratedRegex(@"__declspec\s*?\(\s*?align\s*?\(\s*?([0-9]+)\s*?\)\s*?\)")]
private static partial Regex MsvcAlignRegex();
}
}

View File

@@ -1,80 +1,80 @@
// Copyright (c) 2019-2020 Carter Bush - https://github.com/carterbush // Copyright (c) 2019-2020 Carter Bush - https://github.com/carterbush
// Copyright (c) 2020-2021 Katy Coe - http://www.djkaty.com - https://github.com/djkaty // Copyright (c) 2020-2021 Katy Coe - http://www.djkaty.com - https://github.com/djkaty
// Copyright 2020 Robert Xiao - https://robertxiao.ca/ // Copyright 2020 Robert Xiao - https://robertxiao.ca/
// All rights reserved // All rights reserved
using System.Linq; using System.Linq;
using System.IO; using System.IO;
using Il2CppInspector.Reflection; using Il2CppInspector.Reflection;
using Il2CppInspector.Model; using Il2CppInspector.Model;
using System.Collections.Generic; using System.Collections.Generic;
using System; using System;
namespace Il2CppInspector.Outputs namespace Il2CppInspector.Outputs
{ {
public class PythonScript public class PythonScript
{ {
private readonly AppModel model; private readonly AppModel model;
public PythonScript(AppModel model) => this.model = model; public PythonScript(AppModel model) => this.model = model;
// Get list of available script targets // Get list of available script targets
public static IEnumerable<string> GetAvailableTargets() { public static IEnumerable<string> GetAvailableTargets() {
var ns = typeof(PythonScript).Namespace + ".ScriptResources.Targets"; var ns = typeof(PythonScript).Namespace + ".ScriptResources.Targets";
var res = ResourceHelper.GetNamesForNamespace(ns); var res = ResourceHelper.GetNamesForNamespace(ns);
return res.Select(s => Path.GetFileNameWithoutExtension(s.Substring(ns.Length + 1))).OrderBy(s => s); return res.Select(s => Path.GetFileNameWithoutExtension(s.Substring(ns.Length + 1))).OrderBy(s => s);
} }
// Output script file // Output script file
public void WriteScriptToFile(string outputFile, string target, string existingTypeHeaderFIle = null, string existingJsonMetadataFile = null) { public void WriteScriptToFile(string outputFile, string target, string existingTypeHeaderFIle = null, string existingJsonMetadataFile = null) {
// Check that target script API is valid // Check that target script API is valid
if (!GetAvailableTargets().Contains(target)) if (!GetAvailableTargets().Contains(target))
throw new InvalidOperationException("Unknown script API target: " + target); throw new InvalidOperationException("Unknown script API target: " + target);
// Write types file first if it hasn't been specified // Write types file first if it hasn't been specified
var typeHeaderFile = Path.Combine(Path.GetDirectoryName(outputFile), Path.GetFileNameWithoutExtension(outputFile) + ".h"); var typeHeaderFile = Path.Combine(Path.GetDirectoryName(outputFile), Path.GetFileNameWithoutExtension(outputFile) + ".h");
if (string.IsNullOrEmpty(existingTypeHeaderFIle)) if (string.IsNullOrEmpty(existingTypeHeaderFIle))
writeTypes(typeHeaderFile); writeTypes(typeHeaderFile);
else else
typeHeaderFile = existingTypeHeaderFIle; typeHeaderFile = existingTypeHeaderFIle;
var typeHeaderRelativePath = getRelativePath(outputFile, typeHeaderFile); var typeHeaderRelativePath = getRelativePath(outputFile, typeHeaderFile);
// Write JSON metadata if it hasn't been specified // Write JSON metadata if it hasn't been specified
var jsonMetadataFile = Path.Combine(Path.GetDirectoryName(outputFile), Path.GetFileNameWithoutExtension(outputFile) + ".json"); var jsonMetadataFile = Path.Combine(Path.GetDirectoryName(outputFile), Path.GetFileNameWithoutExtension(outputFile) + ".json");
if (string.IsNullOrEmpty(existingJsonMetadataFile)) if (string.IsNullOrEmpty(existingJsonMetadataFile))
writeJsonMetadata(jsonMetadataFile); writeJsonMetadata(jsonMetadataFile);
else else
jsonMetadataFile = existingJsonMetadataFile; jsonMetadataFile = existingJsonMetadataFile;
var jsonMetadataRelativePath = getRelativePath(outputFile, jsonMetadataFile); var jsonMetadataRelativePath = getRelativePath(outputFile, jsonMetadataFile);
var ns = typeof(PythonScript).Namespace + ".ScriptResources"; var ns = typeof(PythonScript).Namespace + ".ScriptResources";
var preamble = ResourceHelper.GetText(ns + ".shared-preamble.py"); var preamble = ResourceHelper.GetText(ns + ".shared-preamble.py");
var main = ResourceHelper.GetText(ns + ".shared-main.py"); var main = ResourceHelper.GetText(ns + ".shared-main.py");
var api = ResourceHelper.GetText($"{ns}.Targets.{target}.py"); var api = ResourceHelper.GetText($"{ns}.Targets.{target}.py");
var script = string.Join("\n", new [] { preamble, api, main }) var script = string.Join("\n", new [] { preamble, api, main })
.Replace("%SCRIPTFILENAME%", Path.GetFileName(outputFile)) .Replace("%SCRIPTFILENAME%", Path.GetFileName(outputFile))
.Replace("%TYPE_HEADER_RELATIVE_PATH%", typeHeaderRelativePath.ToEscapedString()) .Replace("%TYPE_HEADER_RELATIVE_PATH%", typeHeaderRelativePath.ToEscapedString())
.Replace("%JSON_METADATA_RELATIVE_PATH%", jsonMetadataRelativePath.ToEscapedString()) .Replace("%JSON_METADATA_RELATIVE_PATH%", jsonMetadataRelativePath.ToEscapedString())
.Replace("%TARGET_UNITY_VERSION%", model.UnityHeaders.ToString()) .Replace("%TARGET_UNITY_VERSION%", model.UnityHeaders.ToString())
.Replace("%IMAGE_BASE%", model.Package.BinaryImage.ImageBase.ToAddressString()); .Replace("%IMAGE_BASE%", model.Package.BinaryImage.ImageBase.ToAddressString());
File.WriteAllText(outputFile, script); File.WriteAllText(outputFile, script);
} }
private void writeTypes(string typeHeaderFile) => new CppScaffolding(model).WriteTypes(typeHeaderFile); private void writeTypes(string typeHeaderFile) => new CppScaffolding(model, useBetterArraySize: true).WriteTypes(typeHeaderFile);
private void writeJsonMetadata(string jsonMetadataFile) => new JSONMetadata(model).Write(jsonMetadataFile); private void writeJsonMetadata(string jsonMetadataFile) => new JSONMetadata(model).Write(jsonMetadataFile);
private string getRelativePath(string from, string to) => private string getRelativePath(string from, string to) =>
Path.GetRelativePath(Path.GetDirectoryName(Path.GetFullPath(from)), Path.GetRelativePath(Path.GetDirectoryName(Path.GetFullPath(from)),
Path.GetDirectoryName(Path.GetFullPath(to))) Path.GetDirectoryName(Path.GetFullPath(to)))
+ Path.DirectorySeparatorChar + Path.DirectorySeparatorChar
+ Path.GetFileName(to); + Path.GetFileName(to);
} }
} }