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 */
/* 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);
}
/* Reserve builtin keywords in IDA */
@@ -586,7 +586,7 @@ namespace Il2CppInspector.Cpp
"__ptr32", "__ptr64", "__pure", "__restrict", "__return_ptr", "__shifted", "__spoils", "__stdcall", "__struct_ptr",
"__thiscall", "__thread", "__unaligned", "__usercall", "__userpurge",
"_cs", "_ds", "_es", "_ss", "far", "flat", "near",
"Mask", "Region", "Pointer", "GC" }) {
"Mask", "Region", "Pointer", "GC", "Time" /* wtf? */ }) {
ns.ReserveName(keyword);
}
/* Reserve builtin keywords for Ghidra */

View File

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

View File

@@ -1,237 +1,239 @@
/*
Copyright 2017-2021 Katy Coe - http://www.djkaty.com - https://github.com/djkaty
Copyright 2020 Robert Xiao - https://robertxiao.ca
All rights reserved.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using NoisyCowStudios.Bin2Object;
namespace Il2CppInspector.Cpp.UnityHeaders
{
// Parsed representation of a Unity version number, such as 5.3.0f1 or 2019.3.7.
public class UnityVersion : IComparable<UnityVersion>, IEquatable<UnityVersion>
{
// A sorted enumeration of build types, in order of maturity
public enum BuildTypeEnum
{
Unspecified,
Alpha,
Beta,
ReleaseCandidate,
Final,
Patch,
}
public static string BuildTypeToString(BuildTypeEnum buildType) => buildType switch
{
BuildTypeEnum.Unspecified => "",
BuildTypeEnum.Alpha => "a",
BuildTypeEnum.Beta => "b",
BuildTypeEnum.ReleaseCandidate => "rc",
BuildTypeEnum.Final => "f",
BuildTypeEnum.Patch => "p",
_ => throw new ArgumentException(),
};
public static BuildTypeEnum StringToBuildType(string s) => s switch
{
"" => BuildTypeEnum.Unspecified,
"a" => BuildTypeEnum.Alpha,
"b" => BuildTypeEnum.Beta,
"rc" => BuildTypeEnum.ReleaseCandidate,
"f" => BuildTypeEnum.Final,
"p" => BuildTypeEnum.Patch,
_ => throw new ArgumentException("Unknown build type " + s),
};
// Unity version number is of the form <Major>.<Minor>.<Update>[<BuildType><BuildNumber>]
public int Major { get; }
public int Minor { get; }
public int Update { get; }
public BuildTypeEnum BuildType { get; }
public int BuildNumber { get; }
public UnityVersion(string versionString) {
var match = Regex.Match(versionString, @"^(\d+)\.(\d+)(?:\.(\d+))?(?:([a-zA-Z]+)(\d+))?$");
if (!match.Success)
throw new ArgumentException($"'${versionString}' is not a valid Unity version number.");
Major = int.Parse(match.Groups[1].Value);
Minor = int.Parse(match.Groups[2].Value);
Update = match.Groups[3].Success ? int.Parse(match.Groups[3].Value) : 0;
BuildType = match.Groups[4].Success ? StringToBuildType(match.Groups[4].Value) : BuildTypeEnum.Unspecified;
BuildNumber = match.Groups[5].Success ? int.Parse(match.Groups[5].Value) : 0;
}
// Get a Unity version from a Unity asset file
public static UnityVersion FromAssetFile(string filePath) {
// 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 reader = new BinaryReader(file, System.Text.Encoding.UTF8);
// Position of Unity version string in asset files
file.Position = 0x14;
// Read null-terminated string
var bytes = new List<byte>();
var maxLength = 15;
byte b;
while ((b = reader.ReadByte()) != 0 && bytes.Count < maxLength)
bytes.Add(b);
var unityString = System.Text.Encoding.UTF8.GetString(bytes.ToArray());
return new UnityVersion(unityString);
}
public static implicit operator UnityVersion(string versionString) => new UnityVersion(versionString);
public override string ToString() {
var res = $"{Major}.{Minor}.{Update}";
if (BuildType != BuildTypeEnum.Unspecified)
res += $"{BuildTypeToString(BuildType)}{BuildNumber}";
return res;
}
// Compare two version numbers, intransitively (due to the Unspecified build type)
public int CompareTo(UnityVersion other) {
// null means maximum possible version
if (other == null)
return -1;
int res;
if (0 != (res = Major.CompareTo(other.Major)))
return res;
if (0 != (res = Minor.CompareTo(other.Minor)))
return res;
if (0 != (res = Update.CompareTo(other.Update)))
return res;
// 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
if (BuildType == BuildTypeEnum.Unspecified || other.BuildType == BuildTypeEnum.Unspecified)
return 0;
if (0 != (res = BuildType.CompareTo(other.BuildType)))
return res;
if (0 != (res = BuildNumber.CompareTo(other.BuildNumber)))
return res;
return 0;
}
// Equality comparisons
public static bool operator ==(UnityVersion first, UnityVersion second) {
if (ReferenceEquals(first, second))
return true;
if (ReferenceEquals(first, null) || ReferenceEquals(second, null))
return false;
return first.Equals(second);
}
public static bool operator !=(UnityVersion first, UnityVersion second) => !(first == second);
public override bool Equals(object obj) => Equals(obj as UnityVersion);
public bool Equals(UnityVersion other) {
return other != null &&
Major == other.Major &&
Minor == other.Minor &&
Update == other.Update &&
BuildType == other.BuildType &&
BuildNumber == other.BuildNumber;
}
public override int GetHashCode() => HashCode.Combine(Major, Minor, Update, BuildType, BuildNumber);
}
// A range of Unity versions
public class UnityVersionRange : IComparable<UnityVersionRange>, IEquatable<UnityVersionRange>
{
// Minimum and maximum Unity version numbers for this range. Both endpoints are inclusive
// Max can be null to specify no upper bound
public UnityVersion Min { get; }
public UnityVersion Max { get; }
// Determine if this range contains the specified version
public bool Contains(UnityVersion version) => version.CompareTo(Min) >= 0 && (Max == null || version.CompareTo(Max) <= 0);
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.";
headerFilename = headerFilename.Replace(".h", "");
if (headerFilename.StartsWith(baseNamespace)) {
headerFilename = headerFilename.Substring(baseNamespace.Length);
headerFilename = headerFilename.Substring(headerFilename.IndexOf(".") + 1);
}
var bits = headerFilename.Split("-");
// Metadata version supplied
// 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
if (headerFilename[2] == '-' || headerFilename[4] == '-')
bits = bits.Skip(1).ToArray();
var Min = new UnityVersion(bits[0]);
UnityVersion Max = null;
if (bits.Length == 1)
Max = Min;
if (bits.Length == 2 && bits[1] != "")
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);
// Intersect two ranges to find the smallest shared set of versions
// Returns null if the two ranges do not intersect
// Max == null means no upper bound on version
public UnityVersionRange Intersect(UnityVersionRange other) {
var highestLow = Min.CompareTo(other.Min) > 0 ? Min : other.Min;
var lowestHigh = Max == null? other.Max : Max.CompareTo(other.Max) < 0 ? Max : other.Max;
if (highestLow.CompareTo(lowestHigh) > 0)
return null;
return new UnityVersionRange(highestLow, lowestHigh);
}
public override string ToString() {
var res = $"{Min}";
if (Max == null)
res += "+";
else if (!Max.Equals(Min))
res += $" - {Max}";
return res;
}
// Equality comparisons
public static bool operator ==(UnityVersionRange first, UnityVersionRange second) {
if (ReferenceEquals(first, second))
return true;
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 bool Equals(UnityVersionRange other) => Min.Equals(other?.Min)
&& ((Max != null && Max.Equals(other?.Max))
|| (Max == null && other != null && other.Max == null));
public override int GetHashCode() => HashCode.Combine(Min, Max);
}
/*
Copyright 2017-2021 Katy Coe - http://www.djkaty.com - https://github.com/djkaty
Copyright 2020 Robert Xiao - https://robertxiao.ca
Copyright 2023 LukeFZ - https://github.com/LukeFZ
All rights reserved.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace Il2CppInspector.Cpp.UnityHeaders
{
// Parsed representation of a Unity version number, such as 5.3.0f1 or 2019.3.7.
public partial class UnityVersion : IComparable<UnityVersion>, IEquatable<UnityVersion>
{
// A sorted enumeration of build types, in order of maturity
public enum BuildTypeEnum
{
Unspecified,
Alpha,
Beta,
ReleaseCandidate,
Final,
Patch,
}
public static string BuildTypeToString(BuildTypeEnum buildType) => buildType switch
{
BuildTypeEnum.Unspecified => "",
BuildTypeEnum.Alpha => "a",
BuildTypeEnum.Beta => "b",
BuildTypeEnum.ReleaseCandidate => "rc",
BuildTypeEnum.Final => "f",
BuildTypeEnum.Patch => "p",
_ => throw new ArgumentException(),
};
public static BuildTypeEnum StringToBuildType(string s) => s switch
{
"" => BuildTypeEnum.Unspecified,
"a" => BuildTypeEnum.Alpha,
"b" => BuildTypeEnum.Beta,
"rc" => BuildTypeEnum.ReleaseCandidate,
"f" => BuildTypeEnum.Final,
"p" => BuildTypeEnum.Patch,
_ => throw new ArgumentException("Unknown build type " + s),
};
// Unity version number is of the form <Major>.<Minor>.<Update>[<BuildType><BuildNumber>]
public int Major { get; }
public int Minor { get; }
public int Update { get; }
public BuildTypeEnum BuildType { get; }
public int BuildNumber { get; }
public UnityVersion(string versionString) {
var match = VersionRegex().Match(versionString);
if (!match.Success)
throw new ArgumentException($"'${versionString}' is not a valid Unity version number.");
Major = int.Parse(match.Groups[1].Value);
Minor = int.Parse(match.Groups[2].Value);
Update = match.Groups[3].Success ? int.Parse(match.Groups[3].Value) : 0;
BuildType = match.Groups[4].Success ? StringToBuildType(match.Groups[4].Value) : BuildTypeEnum.Unspecified;
BuildNumber = match.Groups[5].Success ? int.Parse(match.Groups[5].Value) : 0;
}
// Get a Unity version from a Unity asset file
public static UnityVersion FromAssetFile(string filePath) {
// 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 reader = new BinaryReader(file, System.Text.Encoding.UTF8);
// Position of Unity version string in asset files
file.Position = 0x14;
// Read null-terminated string
var bytes = new List<byte>();
var maxLength = 15;
byte b;
while ((b = reader.ReadByte()) != 0 && bytes.Count < maxLength)
bytes.Add(b);
var unityString = System.Text.Encoding.UTF8.GetString(bytes.ToArray());
return new UnityVersion(unityString);
}
public static implicit operator UnityVersion(string versionString) => new(versionString);
public override string ToString() {
var res = $"{Major}.{Minor}.{Update}";
if (BuildType != BuildTypeEnum.Unspecified)
res += $"{BuildTypeToString(BuildType)}{BuildNumber}";
return res;
}
// Compare two version numbers, intransitively (due to the Unspecified build type)
public int CompareTo(UnityVersion other) {
// null means maximum possible version
if (other == null)
return -1;
int res;
if (0 != (res = Major.CompareTo(other.Major)))
return res;
if (0 != (res = Minor.CompareTo(other.Minor)))
return res;
if (0 != (res = Update.CompareTo(other.Update)))
return res;
// 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
if (BuildType == BuildTypeEnum.Unspecified || other.BuildType == BuildTypeEnum.Unspecified)
return 0;
if (0 != (res = BuildType.CompareTo(other.BuildType)))
return res;
if (0 != (res = BuildNumber.CompareTo(other.BuildNumber)))
return res;
return 0;
}
// Equality comparisons
public static bool operator ==(UnityVersion first, UnityVersion second) {
if (ReferenceEquals(first, second))
return true;
if (ReferenceEquals(first, null) || ReferenceEquals(second, null))
return false;
return first.Equals(second);
}
public static bool operator !=(UnityVersion first, UnityVersion second) => !(first == second);
public override bool Equals(object obj) => Equals(obj as UnityVersion);
public bool Equals(UnityVersion other) {
return other != null &&
Major == other.Major &&
Minor == other.Minor &&
Update == other.Update &&
BuildType == other.BuildType &&
BuildNumber == other.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>
{
// Minimum and maximum Unity version numbers for this range. Both endpoints are inclusive
// Max can be null to specify no upper bound
public UnityVersion Min { get; }
public UnityVersion Max { get; }
// Determine if this range contains the specified version
public bool Contains(UnityVersion version) => version.CompareTo(Min) >= 0 && (Max == null || version.CompareTo(Max) <= 0);
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.";
headerFilename = headerFilename.Replace(".h", "");
if (headerFilename.StartsWith(baseNamespace)) {
headerFilename = headerFilename.Substring(baseNamespace.Length);
headerFilename = headerFilename.Substring(headerFilename.IndexOf(".") + 1);
}
var bits = headerFilename.Split("-");
// Metadata version supplied
// 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
if (headerFilename[2] == '-' || headerFilename[4] == '-')
bits = bits.Skip(1).ToArray();
var Min = new UnityVersion(bits[0]);
UnityVersion Max = null;
if (bits.Length == 1)
Max = Min;
if (bits.Length == 2 && bits[1] != "")
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);
// Intersect two ranges to find the smallest shared set of versions
// Returns null if the two ranges do not intersect
// Max == null means no upper bound on version
public UnityVersionRange Intersect(UnityVersionRange other) {
var highestLow = Min.CompareTo(other.Min) > 0 ? Min : other.Min;
var lowestHigh = Max == null? other.Max : Max.CompareTo(other.Max) < 0 ? Max : other.Max;
if (highestLow.CompareTo(lowestHigh) > 0)
return null;
return new UnityVersionRange(highestLow, lowestHigh);
}
public override string ToString() {
var res = $"{Min}";
if (Max == null)
res += "+";
else if (!Max.Equals(Min))
res += $" - {Max}";
return res;
}
// Equality comparisons
public static bool operator ==(UnityVersionRange first, UnityVersionRange second) {
if (ReferenceEquals(first, second))
return true;
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 bool Equals(UnityVersionRange other) => Min.Equals(other?.Min)
&& ((Max != null && Max.Equals(other?.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 (c) 2020-2021 Katy Coe - http://www.djkaty.com - https://github.com/djkaty
// All rights reserved
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Il2CppInspector.Reflection;
using Il2CppInspector.Cpp;
using Il2CppInspector.Cpp.UnityHeaders;
using Il2CppInspector.Model;
using Il2CppInspector.Properties;
namespace Il2CppInspector.Outputs
{
public class CppScaffolding
{
private readonly AppModel model;
private StreamWriter writer;
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*?\)");
public CppScaffolding(AppModel model) => this.model = model;
// Write the type header
// This can be used by other output modules
public void WriteTypes(string typeHeaderFile) {
using var fs = new FileStream(typeHeaderFile, FileMode.Create);
writer = new StreamWriter(fs, Encoding.ASCII);
writeHeader();
// Write primitive type definitions for when we're not including other headers
writeCode($@"#if defined(_GHIDRA_) || defined(_IDA_)
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
typedef __int8 int8_t;
typedef __int16 int16_t;
typedef __int32 int32_t;
typedef __int64 int64_t;
#endif
#if defined(_GHIDRA_)
typedef __int{model.Package.BinaryImage.Bits} size_t;
typedef size_t intptr_t;
typedef size_t uintptr_t;
#endif
#if !defined(_GHIDRA_) && !defined(_IDA_)
#define _CPLUSPLUS_
#endif
");
writeSectionHeader("IL2CPP internal types");
writeCode(model.UnityHeaders.GetTypeHeaderText(model.WordSizeBits));
// Stop MSVC complaining about out-of-bounds enum values
if (model.TargetCompiler == CppCompilerType.MSVC)
writeCode("#pragma warning(disable : 4369)");
// Stop MSVC complaining about constant truncation of enum values
if (model.TargetCompiler == CppCompilerType.MSVC)
writeCode("#pragma warning(disable : 4309)");
// MSVC will (rightly) throw a compiler warning when compiling for 32-bit architectures
// 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
// safe to ignore them if they are too small, so we just disable the warning
if (model.TargetCompiler == CppCompilerType.MSVC)
writeCode("#pragma warning(disable : 4359)");
// C does not support namespaces
writeCode("#if !defined(_GHIDRA_) && !defined(_IDA_)");
writeCode("namespace app {");
writeCode("#endif");
writeLine("");
writeTypesForGroup("Application types from method calls", "types_from_methods");
writeTypesForGroup("Application types from generic methods", "types_from_generic_methods");
writeTypesForGroup("Application types from usages", "types_from_usages");
writeTypesForGroup("Application unused value types", "unused_concrete_types");
writeCode("#if !defined(_GHIDRA_) && !defined(_IDA_)");
writeCode("}");
writeCode("#endif");
writer.Close();
}
public void Write(string projectPath) {
// Ensure output directory exists and is not a file
// A System.IOException will be thrown if it's a file'
var srcUserPath = Path.Combine(projectPath, "user");
var srcFxPath = Path.Combine(projectPath, "framework");
var srcDataPath = Path.Combine(projectPath, "appdata");
Directory.CreateDirectory(projectPath);
Directory.CreateDirectory(srcUserPath);
Directory.CreateDirectory(srcFxPath);
Directory.CreateDirectory(srcDataPath);
// Write type definitions to il2cpp-types.h
WriteTypes(Path.Combine(srcDataPath, "il2cpp-types.h"));
// Write selected Unity API function file to il2cpp-api-functions.h
// (this is a copy of the header file from an actual Unity install)
var il2cppApiFile = Path.Combine(srcDataPath, "il2cpp-api-functions.h");
var apiHeaderText = model.UnityHeaders.GetAPIHeaderText();
using var fsApi = new FileStream(il2cppApiFile, FileMode.Create);
writer = new StreamWriter(fsApi, Encoding.ASCII);
writeHeader();
// Elide APIs that aren't in the binary to avoid compile errors
foreach (var line in apiHeaderText.Split('\n')) {
var fnName = UnityHeaders.GetFunctionNameFromAPILine(line);
if (string.IsNullOrEmpty(fnName))
writer.WriteLine(line);
else if (model.AvailableAPIs.ContainsKey(fnName))
writer.WriteLine(line);
}
writer.Close();
// Write API function pointers to il2cpp-api-functions-ptr.h
var il2cppFnPtrFile = Path.Combine(srcDataPath, "il2cpp-api-functions-ptr.h");
using var fs2 = new FileStream(il2cppFnPtrFile, FileMode.Create);
writer = new StreamWriter(fs2, Encoding.ASCII);
writeHeader();
writeSectionHeader("IL2CPP API function pointers");
// 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,
// so although it doesn't affect the C++ compilation, we use GetAPIExports() instead for completeness
var exports = model.Package.Binary.APIExports;
foreach (var export in exports) {
writeCode($"#define {export.Key}_ptr 0x{model.Package.BinaryImage.MapVATR(export.Value):X8}");
}
writer.Close();
// Write application type definition addresses to il2cpp-types-ptr.h
var il2cppTypeInfoFile = Path.Combine(srcDataPath, "il2cpp-types-ptr.h");
using var fs3 = new FileStream(il2cppTypeInfoFile, FileMode.Create);
writer = new StreamWriter(fs3, Encoding.ASCII);
writeHeader();
writeSectionHeader("IL2CPP application-specific type definition addresses");
foreach (var type in model.Types.Values.Where(t => t.TypeClassAddress != 0xffffffff_ffffffff)) {
writeCode($"DO_TYPEDEF(0x{type.TypeClassAddress - model.Package.BinaryImage.ImageBase:X8}, {type.Name});");
}
writer.Close();
// Write method pointers and signatures to il2cpp-functions.h
var methodFile = Path.Combine(srcDataPath, "il2cpp-functions.h");
using var fs4 = new FileStream(methodFile, FileMode.Create);
writer = new StreamWriter(fs4, Encoding.ASCII);
writeHeader();
writeSectionHeader("IL2CPP application-specific method definition addresses and signatures");
writeCode("using namespace app;");
writeLine("");
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)));
writeCode($"DO_APP_FUNC(0x{method.MethodCodeAddress - model.Package.BinaryImage.ImageBase:X8}, {method.CppFnPtrType.ReturnType.Name}, "
+ $"{method.CppFnPtrType.Name}, ({arguments}));");
}
if (method.HasMethodInfo) {
writeCode($"DO_APP_FUNC_METHODINFO(0x{method.MethodInfoPtrAddress - model.Package.BinaryImage.ImageBase:X8}, {method.CppFnPtrType.Name}__MethodInfo);");
}
}
writer.Close();
// Write metadata version
var versionFile = Path.Combine(srcDataPath, "il2cpp-metadata-version.h");
using var fs5 = new FileStream(versionFile, FileMode.Create);
writer = new StreamWriter(fs5, Encoding.ASCII);
writeHeader();
writeCode($"#define __IL2CPP_METADATA_VERSION {model.Package.Version * 10:F0}");
writer.Close();
// Write boilerplate code
File.WriteAllText(Path.Combine(srcFxPath, "dllmain.cpp"), Resources.Cpp_DLLMainCpp);
File.WriteAllText(Path.Combine(srcFxPath, "helpers.cpp"), Resources.Cpp_HelpersCpp);
File.WriteAllText(Path.Combine(srcFxPath, "helpers.h"), Resources.Cpp_HelpersH);
File.WriteAllText(Path.Combine(srcFxPath, "il2cpp-appdata.h"), Resources.Cpp_Il2CppAppDataH);
File.WriteAllText(Path.Combine(srcFxPath, "il2cpp-init.cpp"), Resources.Cpp_Il2CppInitCpp);
File.WriteAllText(Path.Combine(srcFxPath, "il2cpp-init.h"), Resources.Cpp_Il2CppInitH);
File.WriteAllText(Path.Combine(srcFxPath, "pch-il2cpp.cpp"), Resources.Cpp_PCHIl2Cpp);
File.WriteAllText(Path.Combine(srcFxPath, "pch-il2cpp.h"), Resources.Cpp_PCHIl2CppH);
// Write user code without overwriting existing code
void WriteIfNotExists(string path, string contents) { if (!File.Exists(path)) File.WriteAllText(path, contents); }
WriteIfNotExists(Path.Combine(srcUserPath, "main.cpp"), Resources.Cpp_MainCpp);
WriteIfNotExists(Path.Combine(srcUserPath, "main.h"), Resources.Cpp_MainH);
// Write Visual Studio project and solution files
var projectGuid = Guid.NewGuid();
var projectName = "IL2CppDLL";
var projectFile = projectName + ".vcxproj";
WriteIfNotExists(Path.Combine(projectPath, projectFile),
Resources.CppProjTemplate.Replace("%PROJECTGUID%", projectGuid.ToString()));
var guid1 = Guid.NewGuid();
var guid2 = Guid.NewGuid();
var guid3 = Guid.NewGuid();
var filtersFile = projectFile + ".filters";
var filters = Resources.CppProjFilters
.Replace("%GUID1%", guid1.ToString())
.Replace("%GUID2%", guid2.ToString())
.Replace("%GUID3%", guid3.ToString());
WriteIfNotExists(Path.Combine(projectPath, filtersFile), filters);
var solutionGuid = Guid.NewGuid();
var solutionFile = projectName + ".sln";
var sln = Resources.CppSlnTemplate
.Replace("%PROJECTGUID%", projectGuid.ToString())
.Replace("%PROJECTNAME%", projectName)
.Replace("%PROJECTFILE%", projectFile)
.Replace("%SOLUTIONGUID%", solutionGuid.ToString());
WriteIfNotExists(Path.Combine(projectPath, solutionFile), sln);
}
private void writeHeader() {
writeLine("// Generated C++ file by Il2CppInspector - http://www.djkaty.com - https://github.com/djkaty");
writeLine("// Target Unity version: " + model.UnityHeaders);
writeLine("");
}
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 = rgxGCCalign.Replace(text, @"__declspec(align($1))");
if (model.TargetCompiler == CppCompilerType.GCC)
text = rgxMSVCalign.Replace(text, @"__attribute__((aligned($1)))");
var lines = text.Replace("\r", "").Split('\n');
var cleanLines = lines.Select(s => s.ToEscapedString());
var declString = string.Join('\n', cleanLines);
if (declString != "")
writeLine(declString);
}
private void writeSectionHeader(string name) {
writeLine("// ******************************************************************************");
writeLine("// * " + name);
writeLine("// ******************************************************************************");
writeLine("");
}
private void writeLine(string line) => writer.WriteLine(line);
}
}
// Copyright 2020 Robert Xiao - https://robertxiao.ca/
// Copyright (c) 2020-2021 Katy Coe - http://www.djkaty.com - https://github.com/djkaty
// Copyright (c) 2023 LukeFZ https://github.com/LukeFZ
// All rights reserved
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using Il2CppInspector.Reflection;
using Il2CppInspector.Cpp;
using Il2CppInspector.Cpp.UnityHeaders;
using Il2CppInspector.Model;
using Il2CppInspector.Properties;
namespace Il2CppInspector.Outputs
{
public partial class CppScaffolding(AppModel model, bool useBetterArraySize = false)
{
private readonly AppModel _model = model;
/*
* 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.
* 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.
*/
private readonly bool _useBetterArraySize =
model.UnityVersion.CompareTo("2017.2.1") >= 0
&& model.Package.BinaryImage.Bits == 64
&& useBetterArraySize;
private StreamWriter _writer;
// Write the type header
// This can be used by other output modules
public void WriteTypes(string typeHeaderFile) {
using var fs = new FileStream(typeHeaderFile, FileMode.Create);
_writer = new StreamWriter(fs, Encoding.ASCII);
using (_writer)
{
writeHeader();
// Write primitive type definitions for when we're not including other headers
writeCode($$"""
#if defined(_GHIDRA_) || defined(_IDA_)
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
typedef __int8 int8_t;
typedef __int16 int16_t;
typedef __int32 int32_t;
typedef __int64 int64_t;
#endif
#if defined(_GHIDRA_)
typedef __int{{_model.Package.BinaryImage.Bits}} size_t;
typedef size_t intptr_t;
typedef size_t uintptr_t;
#endif
#if !defined(_GHIDRA_) && !defined(_IDA_)
#define _CPLUSPLUS_
#endif
""");
if (_useBetterArraySize)
writeCode("#define il2cpp_array_size_t actual_il2cpp_array_size_t");
writeSectionHeader("IL2CPP internal types");
writeCode(_model.UnityHeaders.GetTypeHeaderText(_model.WordSizeBits));
if (_useBetterArraySize)
writeCode("""
#undef il2cpp_array_size_t
typedef union better_il2cpp_array_size_t
{
int32_t size;
actual_il2cpp_array_size_t value;
} better_il2cpp_array_size_t;
#define il2cpp_array_size_t better_il2cpp_array_size_t
""");
if (_model.TargetCompiler == CppCompilerType.MSVC)
{
// Stop MSVC complaining about out-of-bounds enum values
writeCode("#pragma warning(disable : 4369)");
// Stop MSVC complaining about constant truncation of enum values
writeCode("#pragma warning(disable : 4309)");
// MSVC will (rightly) throw a compiler warning when compiling for 32-bit architectures
// 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
// safe to ignore them if they are too small, so we just disable the warning
writeCode("#pragma warning(disable : 4359)");
}
// C does not support namespaces
writeCode("#if !defined(_GHIDRA_) && !defined(_IDA_)");
writeCode("namespace app {");
writeCode("#endif");
writeLine("");
writeTypesForGroup("Application types from method calls", "types_from_methods");
writeTypesForGroup("Application types from generic methods", "types_from_generic_methods");
writeTypesForGroup("Application types from usages", "types_from_usages");
writeTypesForGroup("Application unused value types", "unused_concrete_types");
writeCode("#if !defined(_GHIDRA_) && !defined(_IDA_)");
writeCode("}");
writeCode("#endif");
}
}
public void Write(string projectPath) {
// Ensure output directory exists and is not a file
// A System.IOException will be thrown if it's a file'
var srcUserPath = Path.Combine(projectPath, "user");
var srcFxPath = Path.Combine(projectPath, "framework");
var srcDataPath = Path.Combine(projectPath, "appdata");
Directory.CreateDirectory(projectPath);
Directory.CreateDirectory(srcUserPath);
Directory.CreateDirectory(srcFxPath);
Directory.CreateDirectory(srcDataPath);
// Write type definitions to il2cpp-types.h
WriteTypes(Path.Combine(srcDataPath, "il2cpp-types.h"));
// Write selected Unity API function file to il2cpp-api-functions.h
// (this is a copy of the header file from an actual Unity install)
var il2cppApiFile = Path.Combine(srcDataPath, "il2cpp-api-functions.h");
var apiHeaderText = _model.UnityHeaders.GetAPIHeaderText();
using var fsApi = new FileStream(il2cppApiFile, FileMode.Create);
_writer = new StreamWriter(fsApi, Encoding.ASCII);
using (_writer)
{
writeHeader();
// Elide APIs that aren't in the binary to avoid compile errors
foreach (var line in apiHeaderText.Split('\n'))
{
var fnName = UnityHeaders.GetFunctionNameFromAPILine(line);
if (string.IsNullOrEmpty(fnName))
_writer.WriteLine(line);
else if (_model.AvailableAPIs.ContainsKey(fnName))
_writer.WriteLine(line);
}
}
// Write API function pointers to il2cpp-api-functions-ptr.h
var il2cppFnPtrFile = Path.Combine(srcDataPath, "il2cpp-api-functions-ptr.h");
using var fs2 = new FileStream(il2cppFnPtrFile, FileMode.Create);
_writer = new StreamWriter(fs2, Encoding.ASCII);
using (_writer)
{
writeHeader();
writeSectionHeader("IL2CPP API function pointers");
// 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,
// so although it doesn't affect the C++ compilation, we use GetAPIExports() instead for completeness
var exports = _model.Package.Binary.APIExports;
foreach (var export in exports)
{
writeCode($"#define {export.Key}_ptr 0x{_model.Package.BinaryImage.MapVATR(export.Value):X8}");
}
}
// Write application type definition addresses to il2cpp-types-ptr.h
var il2cppTypeInfoFile = Path.Combine(srcDataPath, "il2cpp-types-ptr.h");
using var fs3 = new FileStream(il2cppTypeInfoFile, FileMode.Create);
_writer = new StreamWriter(fs3, Encoding.ASCII);
using (_writer)
{
writeHeader();
writeSectionHeader("IL2CPP application-specific type definition addresses");
foreach (var type in _model.Types.Values.Where(t => t.TypeClassAddress != 0xffffffff_ffffffff))
{
writeCode($"DO_TYPEDEF(0x{type.TypeClassAddress - _model.Package.BinaryImage.ImageBase:X8}, {type.Name});");
}
}
// Write method pointers and signatures to il2cpp-functions.h
var methodFile = Path.Combine(srcDataPath, "il2cpp-functions.h");
using var fs4 = new FileStream(methodFile, FileMode.Create);
_writer = new StreamWriter(fs4, Encoding.ASCII);
using (_writer)
{
writeHeader();
writeSectionHeader("IL2CPP application-specific method definition addresses and signatures");
writeCode("using namespace app;");
writeLine("");
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)));
writeCode($"DO_APP_FUNC(0x{method.MethodCodeAddress - _model.Package.BinaryImage.ImageBase:X8}, {method.CppFnPtrType.ReturnType.Name}, "
+ $"{method.CppFnPtrType.Name}, ({arguments}));");
}
if (method.HasMethodInfo)
{
writeCode($"DO_APP_FUNC_METHODINFO(0x{method.MethodInfoPtrAddress - _model.Package.BinaryImage.ImageBase:X8}, {method.CppFnPtrType.Name}__MethodInfo);");
}
}
}
// Write metadata version
var versionFile = Path.Combine(srcDataPath, "il2cpp-metadata-version.h");
using var fs5 = new FileStream(versionFile, FileMode.Create);
_writer = new StreamWriter(fs5, Encoding.ASCII);
using (_writer)
{
writeHeader();
writeCode($"#define __IL2CPP_METADATA_VERSION {_model.Package.Version * 10:F0}");
}
// Write boilerplate code
File.WriteAllText(Path.Combine(srcFxPath, "dllmain.cpp"), Resources.Cpp_DLLMainCpp);
File.WriteAllText(Path.Combine(srcFxPath, "helpers.cpp"), Resources.Cpp_HelpersCpp);
File.WriteAllText(Path.Combine(srcFxPath, "helpers.h"), Resources.Cpp_HelpersH);
File.WriteAllText(Path.Combine(srcFxPath, "il2cpp-appdata.h"), Resources.Cpp_Il2CppAppDataH);
File.WriteAllText(Path.Combine(srcFxPath, "il2cpp-init.cpp"), Resources.Cpp_Il2CppInitCpp);
File.WriteAllText(Path.Combine(srcFxPath, "il2cpp-init.h"), Resources.Cpp_Il2CppInitH);
File.WriteAllText(Path.Combine(srcFxPath, "pch-il2cpp.cpp"), Resources.Cpp_PCHIl2Cpp);
File.WriteAllText(Path.Combine(srcFxPath, "pch-il2cpp.h"), Resources.Cpp_PCHIl2CppH);
// Write user code without overwriting existing code
void WriteIfNotExists(string path, string contents) { if (!File.Exists(path)) File.WriteAllText(path, contents); }
WriteIfNotExists(Path.Combine(srcUserPath, "main.cpp"), Resources.Cpp_MainCpp);
WriteIfNotExists(Path.Combine(srcUserPath, "main.h"), Resources.Cpp_MainH);
// Write Visual Studio project and solution files
var projectGuid = Guid.NewGuid();
var projectName = "IL2CppDLL";
var projectFile = projectName + ".vcxproj";
WriteIfNotExists(Path.Combine(projectPath, projectFile),
Resources.CppProjTemplate.Replace("%PROJECTGUID%", projectGuid.ToString()));
var guid1 = Guid.NewGuid();
var guid2 = Guid.NewGuid();
var guid3 = Guid.NewGuid();
var filtersFile = projectFile + ".filters";
var filters = Resources.CppProjFilters
.Replace("%GUID1%", guid1.ToString())
.Replace("%GUID2%", guid2.ToString())
.Replace("%GUID3%", guid3.ToString());
WriteIfNotExists(Path.Combine(projectPath, filtersFile), filters);
var solutionGuid = Guid.NewGuid();
var solutionFile = projectName + ".sln";
var sln = Resources.CppSlnTemplate
.Replace("%PROJECTGUID%", projectGuid.ToString())
.Replace("%PROJECTNAME%", projectName)
.Replace("%PROJECTFILE%", projectFile)
.Replace("%SOLUTIONGUID%", solutionGuid.ToString());
WriteIfNotExists(Path.Combine(projectPath, solutionFile), sln);
}
private void writeHeader() {
writeLine("// Generated C++ file by Il2CppInspector - http://www.djkaty.com - https://github.com/djkaty");
writeLine("// Target Unity version: " + _model.UnityHeaders);
writeLine("");
}
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) 2020-2021 Katy Coe - http://www.djkaty.com - https://github.com/djkaty
// Copyright 2020 Robert Xiao - https://robertxiao.ca/
// All rights reserved
using System.Linq;
using System.IO;
using Il2CppInspector.Reflection;
using Il2CppInspector.Model;
using System.Collections.Generic;
using System;
namespace Il2CppInspector.Outputs
{
public class PythonScript
{
private readonly AppModel model;
public PythonScript(AppModel model) => this.model = model;
// Get list of available script targets
public static IEnumerable<string> GetAvailableTargets() {
var ns = typeof(PythonScript).Namespace + ".ScriptResources.Targets";
var res = ResourceHelper.GetNamesForNamespace(ns);
return res.Select(s => Path.GetFileNameWithoutExtension(s.Substring(ns.Length + 1))).OrderBy(s => s);
}
// Output script file
public void WriteScriptToFile(string outputFile, string target, string existingTypeHeaderFIle = null, string existingJsonMetadataFile = null) {
// Check that target script API is valid
if (!GetAvailableTargets().Contains(target))
throw new InvalidOperationException("Unknown script API target: " + target);
// Write types file first if it hasn't been specified
var typeHeaderFile = Path.Combine(Path.GetDirectoryName(outputFile), Path.GetFileNameWithoutExtension(outputFile) + ".h");
if (string.IsNullOrEmpty(existingTypeHeaderFIle))
writeTypes(typeHeaderFile);
else
typeHeaderFile = existingTypeHeaderFIle;
var typeHeaderRelativePath = getRelativePath(outputFile, typeHeaderFile);
// Write JSON metadata if it hasn't been specified
var jsonMetadataFile = Path.Combine(Path.GetDirectoryName(outputFile), Path.GetFileNameWithoutExtension(outputFile) + ".json");
if (string.IsNullOrEmpty(existingJsonMetadataFile))
writeJsonMetadata(jsonMetadataFile);
else
jsonMetadataFile = existingJsonMetadataFile;
var jsonMetadataRelativePath = getRelativePath(outputFile, jsonMetadataFile);
var ns = typeof(PythonScript).Namespace + ".ScriptResources";
var preamble = ResourceHelper.GetText(ns + ".shared-preamble.py");
var main = ResourceHelper.GetText(ns + ".shared-main.py");
var api = ResourceHelper.GetText($"{ns}.Targets.{target}.py");
var script = string.Join("\n", new [] { preamble, api, main })
.Replace("%SCRIPTFILENAME%", Path.GetFileName(outputFile))
.Replace("%TYPE_HEADER_RELATIVE_PATH%", typeHeaderRelativePath.ToEscapedString())
.Replace("%JSON_METADATA_RELATIVE_PATH%", jsonMetadataRelativePath.ToEscapedString())
.Replace("%TARGET_UNITY_VERSION%", model.UnityHeaders.ToString())
.Replace("%IMAGE_BASE%", model.Package.BinaryImage.ImageBase.ToAddressString());
File.WriteAllText(outputFile, script);
}
private void writeTypes(string typeHeaderFile) => new CppScaffolding(model).WriteTypes(typeHeaderFile);
private void writeJsonMetadata(string jsonMetadataFile) => new JSONMetadata(model).Write(jsonMetadataFile);
private string getRelativePath(string from, string to) =>
Path.GetRelativePath(Path.GetDirectoryName(Path.GetFullPath(from)),
Path.GetDirectoryName(Path.GetFullPath(to)))
+ Path.DirectorySeparatorChar
+ Path.GetFileName(to);
}
}
// 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 2020 Robert Xiao - https://robertxiao.ca/
// All rights reserved
using System.Linq;
using System.IO;
using Il2CppInspector.Reflection;
using Il2CppInspector.Model;
using System.Collections.Generic;
using System;
namespace Il2CppInspector.Outputs
{
public class PythonScript
{
private readonly AppModel model;
public PythonScript(AppModel model) => this.model = model;
// Get list of available script targets
public static IEnumerable<string> GetAvailableTargets() {
var ns = typeof(PythonScript).Namespace + ".ScriptResources.Targets";
var res = ResourceHelper.GetNamesForNamespace(ns);
return res.Select(s => Path.GetFileNameWithoutExtension(s.Substring(ns.Length + 1))).OrderBy(s => s);
}
// Output script file
public void WriteScriptToFile(string outputFile, string target, string existingTypeHeaderFIle = null, string existingJsonMetadataFile = null) {
// Check that target script API is valid
if (!GetAvailableTargets().Contains(target))
throw new InvalidOperationException("Unknown script API target: " + target);
// Write types file first if it hasn't been specified
var typeHeaderFile = Path.Combine(Path.GetDirectoryName(outputFile), Path.GetFileNameWithoutExtension(outputFile) + ".h");
if (string.IsNullOrEmpty(existingTypeHeaderFIle))
writeTypes(typeHeaderFile);
else
typeHeaderFile = existingTypeHeaderFIle;
var typeHeaderRelativePath = getRelativePath(outputFile, typeHeaderFile);
// Write JSON metadata if it hasn't been specified
var jsonMetadataFile = Path.Combine(Path.GetDirectoryName(outputFile), Path.GetFileNameWithoutExtension(outputFile) + ".json");
if (string.IsNullOrEmpty(existingJsonMetadataFile))
writeJsonMetadata(jsonMetadataFile);
else
jsonMetadataFile = existingJsonMetadataFile;
var jsonMetadataRelativePath = getRelativePath(outputFile, jsonMetadataFile);
var ns = typeof(PythonScript).Namespace + ".ScriptResources";
var preamble = ResourceHelper.GetText(ns + ".shared-preamble.py");
var main = ResourceHelper.GetText(ns + ".shared-main.py");
var api = ResourceHelper.GetText($"{ns}.Targets.{target}.py");
var script = string.Join("\n", new [] { preamble, api, main })
.Replace("%SCRIPTFILENAME%", Path.GetFileName(outputFile))
.Replace("%TYPE_HEADER_RELATIVE_PATH%", typeHeaderRelativePath.ToEscapedString())
.Replace("%JSON_METADATA_RELATIVE_PATH%", jsonMetadataRelativePath.ToEscapedString())
.Replace("%TARGET_UNITY_VERSION%", model.UnityHeaders.ToString())
.Replace("%IMAGE_BASE%", model.Package.BinaryImage.ImageBase.ToAddressString());
File.WriteAllText(outputFile, script);
}
private void writeTypes(string typeHeaderFile) => new CppScaffolding(model, useBetterArraySize: true).WriteTypes(typeHeaderFile);
private void writeJsonMetadata(string jsonMetadataFile) => new JSONMetadata(model).Write(jsonMetadataFile);
private string getRelativePath(string from, string to) =>
Path.GetRelativePath(Path.GetDirectoryName(Path.GetFullPath(from)),
Path.GetDirectoryName(Path.GetFullPath(to)))
+ Path.DirectorySeparatorChar
+ Path.GetFileName(to);
}
}