27 Commits
Author SHA1 Message Date
ManlyMarco ca5111a7c7 Version up to 1.2.4 2020-11-26 18:02:03 +01:00
ManlyMarco 79d1671629 Fixed crashing if some types fail to load in an assembly 2020-11-19 14:17:45 +01:00
ManlyMarco b2295174c6 Fixed process filters not ignoring .exe extension 2020-11-18 21:10:48 +01:00
ghorsington e64304a07a Bump version 2020-11-01 20:36:31 +02:00
ghorsington 5c02ca7ff0 Replace lib with NuGet packages 2020-11-01 20:17:15 +02:00
ghorsington 7261a47a3f Move to new csproj format 2020-11-01 20:16:59 +02:00
ghorsington 7a3f8f394e Add BepInEx nuget feed 2020-11-01 20:16:39 +02:00
ghorsington 03c032f2ae Add better check for plugin type check 2020-11-01 19:00:27 +02:00
ghorsington d8ce6f1774 Remove TargetFrameworkAttribute in plugins 2020-01-27 20:40:32 +02:00
ghorsington 739a7e5ba5 Bump version 2020-01-11 21:43:40 +02:00
ghorsington aba54d0ae0 Add shim for older HarmonyInstance void Patch() call 2020-01-11 21:40:51 +02:00
Keelhauled 534e4a22f4 Version up 2019-12-29 19:19:45 +02:00
Keelhauled fafe807087 Include stripped dlls 2019-12-29 18:47:21 +02:00
Keelhauled 6404ae0890 BepInEx 5 update, remove packages 2019-12-29 18:45:38 +02:00
Keelhauled 633b8dcf3b Remove AssemblyResolve logging 2019-10-23 22:53:18 +03:00
DeathWeasel1337 287048f6b8 Update README.md 2019-10-22 13:34:48 -05:00
DeathWeasel1337 6c0811c4c2 Add config data to metadata 2019-10-22 13:23:48 -05:00
DeathWeasel1337 9d5ddeefcd Add shared project, metadata, update AssemblyInfo, increment version number 2019-10-22 13:11:53 -05:00
DeathWeasel1337 14912ebd14 Add IPAPluginsPath config option 2019-09-26 12:37:57 -05:00
DeathWeasel1337 005670fed8 Remove debug spam 2019-09-26 12:20:14 -05:00
DeathWeasel1337 8b68843548 Disable pdb 2019-09-26 12:07:04 -05:00
DeathWeasel1337 19019fa2d3 Fix copy local 2019-09-26 12:06:05 -05:00
DeathWeasel1337 2489960367 Change build path 2019-09-26 12:01:05 -05:00
ghorsington 882ba4097f Disable loader if original IPA is detected 2019-08-22 23:08:46 +03:00
ghorsington 205d5a4c86 Fix indentation 2019-08-22 21:27:43 +03:00
ghorsington 855ef581eb Make assembly name check version agnostic 2019-08-22 21:26:48 +03:00
ghorsington 6057df25c6 Add Harmony shimmer 2019-08-22 21:26:23 +03:00
37 changed files with 3025 additions and 406 deletions

No files matched your search

-63
View File
@@ -1,63 +0,0 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain
+1 -2
View File
@@ -258,5 +258,4 @@ paket-files/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
/lib
*.pyc
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net35</TargetFramework>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<DebugType>none</DebugType>
<OutputPath>..\bin\patchers\</OutputPath>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BepInEx.Core" Version="5.3.0.4" IncludeAssets="compile" />
</ItemGroup>
<Import Project="..\Shared\Shared.projitems" Label="Shared" />
</Project>
@@ -0,0 +1,96 @@
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Harmony
{
public class AccessCache
{
Dictionary<Type, Dictionary<string, FieldInfo>> fields = new Dictionary<Type, Dictionary<string, FieldInfo>>();
Dictionary<Type, Dictionary<string, PropertyInfo>> properties = new Dictionary<Type, Dictionary<string, PropertyInfo>>();
readonly Dictionary<Type, Dictionary<string, Dictionary<int, MethodBase>>> methods = new Dictionary<Type, Dictionary<string, Dictionary<int, MethodBase>>>();
[UpgradeToLatestVersion(1)]
public FieldInfo GetFieldInfo(Type type, string name)
{
Dictionary<string, FieldInfo> fieldsByType = null;
if (fields.TryGetValue(type, out fieldsByType) == false)
{
fieldsByType = new Dictionary<string, FieldInfo>();
fields.Add(type, fieldsByType);
}
FieldInfo field = null;
if (fieldsByType.TryGetValue(name, out field) == false)
{
field = AccessTools.Field(type, name);
fieldsByType.Add(name, field);
}
return field;
}
public PropertyInfo GetPropertyInfo(Type type, string name)
{
Dictionary<string, PropertyInfo> propertiesByType = null;
if (properties.TryGetValue(type, out propertiesByType) == false)
{
propertiesByType = new Dictionary<string, PropertyInfo>();
properties.Add(type, propertiesByType);
}
PropertyInfo property = null;
if (propertiesByType.TryGetValue(name, out property) == false)
{
property = AccessTools.Property(type, name);
propertiesByType.Add(name, property);
}
return property;
}
static int CombinedHashCode(IEnumerable<object> objects)
{
var hash1 = (5381 << 16) + 5381;
var hash2 = hash1;
var i = 0;
foreach (var obj in objects)
{
if (i % 2 == 0)
hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ obj.GetHashCode();
else
hash2 = ((hash2 << 5) + hash2 + (hash2 >> 27)) ^ obj.GetHashCode();
++i;
}
return hash1 + (hash2 * 1566083941);
}
public MethodBase GetMethodInfo(Type type, string name, Type[] arguments)
{
Dictionary<string, Dictionary<int, MethodBase>> methodsByName = null;
methods.TryGetValue(type, out methodsByName);
if (methodsByName == null)
{
methodsByName = new Dictionary<string, Dictionary<int, MethodBase>>();
methods.Add(type, methodsByName);
}
Dictionary<int, MethodBase> methodsByArguments = null;
methodsByName.TryGetValue(name, out methodsByArguments);
if (methodsByArguments == null)
{
methodsByArguments = new Dictionary<int, MethodBase>();
methodsByName.Add(name, methodsByArguments);
}
MethodBase method = null;
var argumentsHash = CombinedHashCode(arguments);
methodsByArguments.TryGetValue(argumentsHash, out method);
if (method == null)
{
method = AccessTools.Method(type, name, arguments);
methodsByArguments.Add(argumentsHash, method);
}
return method;
}
}
}
@@ -0,0 +1,398 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.Serialization;
namespace Harmony
{
public static class AccessTools
{
public static BindingFlags all = BindingFlags.Public
| BindingFlags.NonPublic
| BindingFlags.Instance
| BindingFlags.Static
| BindingFlags.GetField
| BindingFlags.SetField
| BindingFlags.GetProperty
| BindingFlags.SetProperty;
public static Type TypeByName(string name)
{
var type = Type.GetType(name, false);
if (type == null)
type = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(x => x.GetTypes())
.FirstOrDefault(x => x.FullName == name);
if (type == null)
type = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(x => x.GetTypes())
.FirstOrDefault(x => x.Name == name);
return type;
}
public static T FindIncludingBaseTypes<T>(Type type, Func<Type, T> action)
{
while (true)
{
var result = action(type);
if (result != null) return result;
if (type == typeof(object)) return default(T);
type = type.BaseType;
}
}
public static T FindIncludingInnerTypes<T>(Type type, Func<Type, T> action)
{
var result = action(type);
if (result != null) return result;
foreach (var subType in type.GetNestedTypes(all))
{
result = FindIncludingInnerTypes(subType, action);
if (result != null)
break;
}
return result;
}
public static FieldInfo Field(Type type, string name)
{
if (type == null || name == null) return null;
return FindIncludingBaseTypes(type, t => t.GetField(name, all));
}
public static FieldInfo Field(Type type, int idx)
{
return GetDeclaredFields(type).ElementAtOrDefault(idx);
}
public static PropertyInfo DeclaredProperty(Type type, string name)
{
if (type == null || name == null) return null;
return type.GetProperty(name, all);
}
public static PropertyInfo Property(Type type, string name)
{
if (type == null || name == null) return null;
return FindIncludingBaseTypes(type, t => t.GetProperty(name, all));
}
public static MethodInfo DeclaredMethod(Type type, string name, Type[] parameters = null, Type[] generics = null)
{
if (type == null || name == null) return null;
MethodInfo result;
var modifiers = new ParameterModifier[] { };
if (parameters == null)
result = type.GetMethod(name, all);
else
result = type.GetMethod(name, all, null, parameters, modifiers);
if (result == null) return null;
if (generics != null) result = result.MakeGenericMethod(generics);
return result;
}
public static MethodInfo Method(Type type, string name, Type[] parameters = null, Type[] generics = null)
{
if (type == null || name == null) return null;
MethodInfo result;
var modifiers = new ParameterModifier[] { };
if (parameters == null)
{
try
{
result = FindIncludingBaseTypes(type, t => t.GetMethod(name, all));
}
catch (AmbiguousMatchException)
{
result = FindIncludingBaseTypes(type, t => t.GetMethod(name, all, null, new Type[0], modifiers));
}
}
else
{
result = FindIncludingBaseTypes(type, t => t.GetMethod(name, all, null, parameters, modifiers));
}
if (result == null) return null;
if (generics != null) result = result.MakeGenericMethod(generics);
return result;
}
public static MethodInfo Method(string typeColonMethodname, Type[] parameters = null, Type[] generics = null)
{
if (typeColonMethodname == null) return null;
var parts = typeColonMethodname.Split(':');
if (parts.Length != 2)
throw new ArgumentException("Method must be specified as 'Namespace.Type1.Type2:MethodName", nameof(typeColonMethodname));
var type = TypeByName(parts[0]);
return Method(type, parts[1], parameters, generics);
}
public static List<string> GetMethodNames(Type type)
{
if (type == null) return new List<string>();
return type.GetMethods(all).Select(m => m.Name).ToList();
}
public static List<string> GetMethodNames(object instance)
{
if (instance == null) return new List<string>();
return GetMethodNames(instance.GetType());
}
public static ConstructorInfo DeclaredConstructor(Type type, Type[] parameters = null)
{
if (type == null) return null;
if (parameters == null) parameters = new Type[0];
return type.GetConstructor(all, null, parameters, new ParameterModifier[] { });
}
public static ConstructorInfo Constructor(Type type, Type[] parameters = null)
{
if (type == null) return null;
if (parameters == null) parameters = new Type[0];
return FindIncludingBaseTypes(type, t => t.GetConstructor(all, null, parameters, new ParameterModifier[] { }));
}
public static List<ConstructorInfo> GetDeclaredConstructors(Type type)
{
return type.GetConstructors(all).Where(method => method.DeclaringType == type).ToList();
}
public static List<MethodInfo> GetDeclaredMethods(Type type)
{
return type.GetMethods(all).Where(method => method.DeclaringType == type).ToList();
}
public static List<PropertyInfo> GetDeclaredProperties(Type type)
{
return type.GetProperties(all).Where(property => property.DeclaringType == type).ToList();
}
public static List<FieldInfo> GetDeclaredFields(Type type)
{
return type.GetFields(all).Where(field => field.DeclaringType == type).ToList();
}
public static Type GetReturnedType(MethodBase method)
{
var constructor = method as ConstructorInfo;
if (constructor != null) return typeof(void);
return ((MethodInfo)method).ReturnType;
}
public static Type Inner(Type type, string name)
{
if (type == null || name == null) return null;
return FindIncludingBaseTypes(type, t => t.GetNestedType(name, all));
}
public static Type FirstInner(Type type, Func<Type, bool> predicate)
{
if (type == null || predicate == null) return null;
return type.GetNestedTypes(all).FirstOrDefault(subType => predicate(subType));
}
public static MethodInfo FirstMethod(Type type, Func<MethodInfo, bool> predicate)
{
if (type == null || predicate == null) return null;
return type.GetMethods(all).FirstOrDefault(method => predicate(method));
}
public static ConstructorInfo FirstConstructor(Type type, Func<ConstructorInfo, bool> predicate)
{
if (type == null || predicate == null) return null;
return type.GetConstructors(all).FirstOrDefault(constructor => predicate(constructor));
}
public static PropertyInfo FirstProperty(Type type, Func<PropertyInfo, bool> predicate)
{
if (type == null || predicate == null) return null;
return type.GetProperties(all).FirstOrDefault(property => predicate(property));
}
public static Type[] GetTypes(object[] parameters)
{
if (parameters == null) return new Type[0];
return parameters.Select(p => p == null ? typeof(object) : p.GetType()).ToArray();
}
public static List<string> GetFieldNames(Type type)
{
if (type == null) return new List<string>();
return type.GetFields(all).Select(f => f.Name).ToList();
}
public static List<string> GetFieldNames(object instance)
{
if (instance == null) return new List<string>();
return GetFieldNames(instance.GetType());
}
public static List<string> GetPropertyNames(Type type)
{
if (type == null) return new List<string>();
return type.GetProperties(all).Select(f => f.Name).ToList();
}
public static List<string> GetPropertyNames(object instance)
{
if (instance == null) return new List<string>();
return GetPropertyNames(instance.GetType());
}
public delegate ref U FieldRef<T, U>(T obj);
public static FieldRef<T, U> FieldRefAccess<T, U>(string fieldName)
{
const BindingFlags bf = BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.DeclaredOnly;
var fi = typeof(T).GetField(fieldName, bf);
if (fi == null)
throw new MissingFieldException(typeof(T).Name, fieldName);
var s_name = "__refget_" + typeof(T).Name + "_fi_" + fi.Name;
// workaround for using ref-return with DynamicMethod:
// a.) initialize with dummy return value
var dm = new DynamicMethod(s_name, typeof(U), new[] { typeof(T) }, typeof(T), true);
// b.) replace with desired 'ByRef' return value
var trv = Traverse.Create(dm);
trv.Field("returnType").SetValue(typeof(U).MakeByRefType());
trv.Field("m_returnType").SetValue(typeof(U).MakeByRefType());
var il = dm.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldflda, fi);
il.Emit(OpCodes.Ret);
return (FieldRef<T, U>)dm.CreateDelegate(typeof(FieldRef<T, U>));
}
public static ref U FieldRefAccess<T, U>(T instance, string fieldName)
{
return ref FieldRefAccess<T, U>(fieldName)(instance);
}
public static void ThrowMissingMemberException(Type type, params string[] names)
{
var fields = string.Join(",", GetFieldNames(type).ToArray());
var properties = string.Join(",", GetPropertyNames(type).ToArray());
throw new MissingMemberException(string.Join(",", names) + "; available fields: " + fields + "; available properties: " + properties);
}
public static object GetDefaultValue(Type type)
{
if (type == null) return null;
if (type == typeof(void)) return null;
if (type.IsValueType)
return Activator.CreateInstance(type);
return null;
}
public static object CreateInstance(Type type)
{
if (type == null)
throw new NullReferenceException("Cannot create instance for NULL type");
var ctor = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance, null, CallingConventions.Any, new Type[0], null);
if (ctor != null)
return Activator.CreateInstance(type);
return FormatterServices.GetUninitializedObject(type);
}
public static object MakeDeepCopy(object source, Type resultType, Func<string, Traverse, Traverse, object> processor = null, string pathRoot = "")
{
if (source == null)
return null;
var type = source.GetType();
if (type.IsPrimitive)
return source;
if (type.IsEnum)
return Enum.ToObject(resultType, (int)source);
if (type.IsGenericType && resultType.IsGenericType)
{
var addOperation = FirstMethod(resultType, m => m.Name == "Add" && m.GetParameters().Count() == 1);
if (addOperation != null)
{
var addableResult = Activator.CreateInstance(resultType);
var addInvoker = MethodInvoker.GetHandler(addOperation);
var newElementType = resultType.GetGenericArguments()[0];
var i = 0;
foreach (var element in source as IEnumerable)
{
var iStr = (i++).ToString();
var path = pathRoot.Length > 0 ? pathRoot + "." + iStr : iStr;
var newElement = MakeDeepCopy(element, newElementType, processor, path);
addInvoker(addableResult, new object[] { newElement });
}
return addableResult;
}
// TODO: add dictionaries support
// maybe use methods in Dictionary<KeyValuePair<TKey,TVal>>
}
if (type.IsArray && resultType.IsArray)
{
var elementType = resultType.GetElementType();
var length = ((Array)source).Length;
var arrayResult = Activator.CreateInstance(resultType, new object[] { length }) as object[];
var originalArray = source as object[];
for (var i = 0; i < length; i++)
{
var iStr = i.ToString();
var path = pathRoot.Length > 0 ? pathRoot + "." + iStr : iStr;
arrayResult[i] = MakeDeepCopy(originalArray[i], elementType, processor, path);
}
return arrayResult;
}
var ns = type.Namespace;
if (ns == "System" || (ns?.StartsWith("System.") ?? false))
return source;
var result = CreateInstance(resultType);
Traverse.IterateFields(source, result, (name, src, dst) =>
{
var path = pathRoot.Length > 0 ? pathRoot + "." + name : name;
var value = processor != null ? processor(path, src, dst) : src.GetValue();
dst.SetValue(MakeDeepCopy(value, dst.GetValueType(), processor, path));
});
return result;
}
public static void MakeDeepCopy<T>(object source, out T result, Func<string, Traverse, Traverse, object> processor = null, string pathRoot = "")
{
result = (T)MakeDeepCopy(source, typeof(T), processor, pathRoot);
}
public static bool IsStruct(Type type)
{
return type.IsValueType && !IsValue(type) && !IsVoid(type);
}
public static bool IsClass(Type type)
{
return !type.IsValueType;
}
public static bool IsValue(Type type)
{
return type.IsPrimitive || type.IsEnum;
}
public static bool IsVoid(Type type)
{
return type == typeof(void);
}
}
}
@@ -0,0 +1,325 @@
using System;
using System.Collections.Generic;
namespace Harmony
{
public enum MethodType
{
Normal,
Getter,
Setter,
Constructor,
StaticConstructor
}
[Obsolete("This enum will be removed in the next major version. To define special methods, use MethodType")]
public enum PropertyMethod
{
Getter,
Setter
}
public enum ArgumentType
{
Normal,
Ref,
Out,
Pointer
}
public enum HarmonyPatchType
{
All,
Prefix,
Postfix,
Transpiler
}
public class HarmonyAttribute : Attribute
{
public HarmonyMethod info = new HarmonyMethod();
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class HarmonyPatch : HarmonyAttribute
{
// no argument (for use with TargetMethod)
public HarmonyPatch()
{
}
// starting with 'Type'
public HarmonyPatch(Type declaringType)
{
info.declaringType = declaringType;
}
public HarmonyPatch(Type declaringType, Type[] argumentTypes)
{
info.declaringType = declaringType;
info.argumentTypes = argumentTypes;
}
public HarmonyPatch(Type declaringType, string methodName)
{
info.declaringType = declaringType;
info.methodName = methodName;
}
public HarmonyPatch(Type declaringType, string methodName, params Type[] argumentTypes)
{
info.declaringType = declaringType;
info.methodName = methodName;
info.argumentTypes = argumentTypes;
}
public HarmonyPatch(Type declaringType, string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
{
info.declaringType = declaringType;
info.methodName = methodName;
ParseSpecialArguments(argumentTypes, argumentVariations);
}
public HarmonyPatch(Type declaringType, MethodType methodType)
{
info.declaringType = declaringType;
info.methodType = methodType;
}
public HarmonyPatch(Type declaringType, MethodType methodType, params Type[] argumentTypes)
{
info.declaringType = declaringType;
info.methodType = methodType;
info.argumentTypes = argumentTypes;
}
public HarmonyPatch(Type declaringType, MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations)
{
info.declaringType = declaringType;
info.methodType = methodType;
ParseSpecialArguments(argumentTypes, argumentVariations);
}
public HarmonyPatch(Type declaringType, string propertyName, MethodType methodType)
{
info.declaringType = declaringType;
info.methodName = propertyName;
info.methodType = methodType;
}
// starting with 'string'
public HarmonyPatch(string methodName)
{
info.methodName = methodName;
}
public HarmonyPatch(string methodName, params Type[] argumentTypes)
{
info.methodName = methodName;
info.argumentTypes = argumentTypes;
}
public HarmonyPatch(string methodName, Type[] argumentTypes, ArgumentType[] argumentVariations)
{
info.methodName = methodName;
ParseSpecialArguments(argumentTypes, argumentVariations);
}
public HarmonyPatch(string propertyName, MethodType methodType)
{
info.methodName = propertyName;
info.methodType = methodType;
}
// starting with 'MethodType'
public HarmonyPatch(MethodType methodType)
{
info.methodType = methodType;
}
public HarmonyPatch(MethodType methodType, params Type[] argumentTypes)
{
info.methodType = methodType;
info.argumentTypes = argumentTypes;
}
public HarmonyPatch(MethodType methodType, Type[] argumentTypes, ArgumentType[] argumentVariations)
{
info.methodType = methodType;
ParseSpecialArguments(argumentTypes, argumentVariations);
}
// starting with 'Type[]'
public HarmonyPatch(Type[] argumentTypes)
{
info.argumentTypes = argumentTypes;
}
public HarmonyPatch(Type[] argumentTypes, ArgumentType[] argumentVariations)
{
ParseSpecialArguments(argumentTypes, argumentVariations);
}
// Obsolete attributes
[Obsolete("This attribute will be removed in the next major version. Use HarmonyPatch together with MethodType.Getter or MethodType.Setter instead")]
public HarmonyPatch(string propertyName, PropertyMethod type)
{
info.methodName = propertyName;
info.methodType = type == PropertyMethod.Getter ? MethodType.Getter : MethodType.Setter;
}
//
private void ParseSpecialArguments(Type[] argumentTypes, ArgumentType[] argumentVariations)
{
if (argumentVariations == null || argumentVariations.Length == 0)
{
info.argumentTypes = argumentTypes;
return;
}
if (argumentTypes.Length < argumentVariations.Length)
throw new ArgumentException("argumentVariations contains more elements than argumentTypes", nameof(argumentVariations));
var types = new List<Type>();
for (var i = 0; i < argumentTypes.Length; i++)
{
var type = argumentTypes[i];
switch (argumentVariations[i])
{
case ArgumentType.Ref:
case ArgumentType.Out:
type = type.MakeByRefType();
break;
case ArgumentType.Pointer:
type = type.MakePointerType();
break;
}
types.Add(type);
}
info.argumentTypes = types.ToArray();
}
}
[AttributeUsage(AttributeTargets.Class)]
public class HarmonyPatchAll : HarmonyAttribute
{
public HarmonyPatchAll()
{
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class HarmonyPriority : HarmonyAttribute
{
public HarmonyPriority(int prioritiy)
{
info.prioritiy = prioritiy;
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class HarmonyBefore : HarmonyAttribute
{
public HarmonyBefore(params string[] before)
{
info.before = before;
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class HarmonyAfter : HarmonyAttribute
{
public HarmonyAfter(params string[] after)
{
info.after = after;
}
}
// If you don't want to use the special method names you can annotate
// using the following attributes:
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyPrepare : Attribute
{
}
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyCleanup : Attribute
{
}
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyTargetMethod : Attribute
{
}
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyTargetMethods : Attribute
{
}
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyPrefix : Attribute
{
}
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyPostfix : Attribute
{
}
[AttributeUsage(AttributeTargets.Method)]
public class HarmonyTranspiler : Attribute
{
}
[AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = true)]
public class HarmonyArgument : Attribute
{
public string OriginalName { get; private set; }
public int Index { get; private set; }
public string NewName { get; private set; }
public HarmonyArgument(string originalName) : this(originalName, null)
{
}
public HarmonyArgument(int index) : this(index, null)
{
}
public HarmonyArgument(string originalName, string newName)
{
OriginalName = originalName;
Index = -1;
NewName = newName;
}
public HarmonyArgument(int index, string name)
{
OriginalName = null;
Index = index;
NewName = name;
}
}
// This attribute is for Harmony patching itself to the latest
//
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor)]
internal class UpgradeToLatestVersion : Attribute
{
public int version;
public UpgradeToLatestVersion(int version)
{
this.version = version;
}
}
}
@@ -0,0 +1,82 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
namespace Harmony
{
public static class GeneralExtensions
{
public static string Join<T>(this IEnumerable<T> enumeration, Func<T, string> converter = null, string delimiter = ", ")
{
if (converter == null) converter = t => t.ToString();
return enumeration.Aggregate("", (prev, curr) => prev + (prev != "" ? delimiter : "") + converter(curr));
}
public static string Description(this Type[] parameters)
{
if (parameters == null) return "NULL";
var pattern = @", \w+, Version=[0-9.]+, Culture=neutral, PublicKeyToken=[0-9a-f]+";
return "(" + parameters.Join(p => p?.FullName == null ? "null" : Regex.Replace(p.FullName, pattern, "")) + ")";
}
public static string FullDescription(this MethodBase method)
{
var parameters = method.GetParameters().Select(p => p.ParameterType).ToArray();
return method.DeclaringType.FullName + "." + method.Name + parameters.Description();
}
public static Type[] Types(this ParameterInfo[] pinfo)
{
return pinfo.Select(pi => pi.ParameterType).ToArray();
}
public static T GetValueSafe<S, T>(this Dictionary<S, T> dictionary, S key)
{
T result;
if (dictionary.TryGetValue(key, out result))
return result;
return default(T);
}
public static T GetTypedValue<T>(this Dictionary<string, object> dictionary, string key)
{
object result;
if (dictionary.TryGetValue(key, out result))
if (result is T)
return (T)result;
return default(T);
}
}
public static class CollectionExtensions
{
public static void Do<T>(this IEnumerable<T> sequence, Action<T> action)
{
if (sequence == null) return;
var enumerator = sequence.GetEnumerator();
while (enumerator.MoveNext()) action(enumerator.Current);
}
public static void DoIf<T>(this IEnumerable<T> sequence, Func<T, bool> condition, Action<T> action)
{
sequence.Where(condition).Do(action);
}
public static IEnumerable<T> Add<T>(this IEnumerable<T> sequence, T item)
{
return (sequence ?? Enumerable.Empty<T>()).Concat(new[] { item });
}
public static T[] AddRangeToArray<T>(this T[] sequence, T[] items)
{
return (sequence ?? Enumerable.Empty<T>()).Concat(items).ToArray();
}
public static T[] AddToArray<T>(this T[] sequence, T item)
{
return Add(sequence, item).ToArray();
}
}
}
@@ -0,0 +1,120 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
namespace Harmony
{
public static class FileLog
{
public static string logPath;
public static char indentChar = '\t';
public static int indentLevel = 0;
static List<string> buffer = new List<string>();
[UpgradeToLatestVersion(1)]
static FileLog()
{
logPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + Path.DirectorySeparatorChar + "harmony.log.txt";
}
static string IndentString()
{
return new string(indentChar, indentLevel);
}
public static void ChangeIndent(int delta)
{
indentLevel = Math.Max(0, indentLevel + delta);
}
// use this method only if you are sure that FlushBuffer will be called
// or else logging information is incomplete in case of a crash
//
public static void LogBuffered(string str)
{
lock (logPath)
{
buffer.Add(IndentString() + str);
}
}
public static void FlushBuffer()
{
lock (logPath)
{
if (buffer.Count > 0)
{
using (var writer = File.AppendText(logPath))
{
foreach (var str in buffer)
writer.WriteLine(str);
}
buffer.Clear();
}
}
}
// this is the slower method that flushes changes directly to the file
// to prevent missing information in case of a cache
//
public static void Log(string str)
{
lock (logPath)
{
using (var writer = File.AppendText(logPath))
{
writer.WriteLine(IndentString() + str);
}
}
}
public static void Reset()
{
lock (logPath)
{
var path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + Path.DirectorySeparatorChar + "harmony.log.txt";
File.Delete(path);
}
}
public static unsafe void LogBytes(long ptr, int len)
{
lock (logPath)
{
var p = (byte*)ptr;
var s = "";
for (var i = 1; i <= len; i++)
{
if (s == "") s = "# ";
s = s + (*p).ToString("X2") + " ";
if (i > 1 || len == 1)
{
if (i % 8 == 0 || i == len)
{
Log(s);
s = "";
}
else if (i % 4 == 0)
s = s + " ";
}
p++;
}
var arr = new byte[len];
Marshal.Copy((IntPtr)ptr, arr, 0, len);
var md5Hash = MD5.Create();
var hash = md5Hash.ComputeHash(arr);
#pragma warning disable XS0001
var sBuilder = new StringBuilder();
#pragma warning restore XS0001
for (var i = 0; i < hash.Length; i++)
sBuilder.Append(hash[i].ToString("X2"));
Log("HASH: " + sBuilder);
}
}
}
}
@@ -0,0 +1,188 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using HarmonyLib;
namespace Harmony
{
public class HarmonyInstance
{
readonly string id;
public string Id => id;
public static bool DEBUG = false;
//private static bool selfPatchingDone = false;
HarmonyInstance(string id)
{
if (DEBUG)
{
var assembly = typeof(HarmonyInstance).Assembly;
var version = assembly.GetName().Version;
var location = assembly.Location;
if (location == null || location == "") location = new Uri(assembly.CodeBase).LocalPath;
FileLog.Log("### Harmony id=" + id + ", version=" + version + ", location=" + location);
var callingMethod = GetOutsideCaller();
var callingAssembly = callingMethod.DeclaringType.Assembly;
location = callingAssembly.Location;
if (location == null || location == "") location = new Uri(callingAssembly.CodeBase).LocalPath;
FileLog.Log("### Started from " + callingMethod.FullDescription() + ", location " + location);
FileLog.Log("### At " + DateTime.Now.ToString("yyyy-MM-dd hh.mm.ss"));
}
this.id = id;
//if (!selfPatchingDone)
//{
// selfPatchingDone = true;
// SelfPatching.PatchOldHarmonyMethods();
//}
}
public static HarmonyInstance Create(string id)
{
if (id == null) throw new Exception("id cannot be null");
return new HarmonyInstance(id);
}
private MethodBase GetOutsideCaller()
{
var trace = new StackTrace(true);
foreach (var frame in trace.GetFrames())
{
var method = frame.GetMethod();
if (method.DeclaringType.Namespace != typeof(HarmonyInstance).Namespace)
return method;
}
throw new Exception("Unexpected end of stack trace");
}
//
public void PatchAll()
{
var method = new StackTrace().GetFrame(1).GetMethod();
var assembly = method.ReflectedType.Assembly;
PatchAll(assembly);
}
public void PatchAll(Assembly assembly)
{
assembly.GetTypes().Do(type =>
{
var parentMethodInfos = type.GetHarmonyMethods();
if (parentMethodInfos != null && parentMethodInfos.Count() > 0)
{
var info = HarmonyMethod.Merge(parentMethodInfos);
var processor = new PatchProcessor(this, type, info);
processor.Patch();
}
});
}
public void PatchAll(Type type)
{
CollectionExtensions.Do(type.GetMethods(BindingFlags.Static | BindingFlags.Public), delegate (MethodInfo method)
{
var harmonyMethods = method.GetHarmonyMethods();
if (harmonyMethods != null && harmonyMethods.Any())
{
var original = HarmonyMethod.Merge(harmonyMethods);
HarmonyMethod prefix = null;
HarmonyMethod transpiler = null;
HarmonyMethod postfix = null;
if (method.GetCustomAttributes(true).Any(x => x is HarmonyPrefix))
prefix = new HarmonyMethod(method);
if (method.GetCustomAttributes(true).Any(x => x is HarmonyTranspiler))
transpiler = new HarmonyMethod(method);
if (method.GetCustomAttributes(true).Any(x => x is HarmonyPostfix))
postfix = new HarmonyMethod(method);
new PatchProcessor(this, original, prefix, postfix, transpiler).Patch();
}
});
}
public DynamicMethod Patch(MethodBase original, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null)
{
var processor = new PatchProcessor(this, new List<MethodBase> { original }, prefix, postfix, transpiler);
return processor.Patch().FirstOrDefault();
}
public void PatchVoid(MethodBase original, HarmonyMethod prefix, HarmonyMethod postfix, HarmonyMethod transpiler)
{
var processor = new PatchProcessor(this, new List<MethodBase> { original }, prefix, postfix, transpiler);
processor.Patch();
}
public void UnpatchAll(string harmonyID = null)
{
bool IDCheck(Patch patchInfo) => harmonyID == null || patchInfo.owner == harmonyID;
var originals = GetPatchedMethods().ToList();
foreach (var original in originals)
{
var info = GetPatchInfo(original);
info.Prefixes.DoIf(IDCheck, patchInfo => Unpatch(original, patchInfo.patch));
info.Postfixes.DoIf(IDCheck, patchInfo => Unpatch(original, patchInfo.patch));
info.Transpilers.DoIf(IDCheck, patchInfo => Unpatch(original, patchInfo.patch));
}
}
public void Unpatch(MethodBase original, HarmonyPatchType type, string harmonyID = null)
{
var processor = new PatchProcessor(this, new List<MethodBase> { original });
processor.Unpatch(type, harmonyID);
}
public void Unpatch(MethodBase original, MethodInfo patch)
{
var processor = new PatchProcessor(this, new List<MethodBase> { original });
processor.Unpatch(patch);
}
//
public bool HasAnyPatches(string harmonyID)
{
return GetPatchedMethods()
.Select(original => GetPatchInfo(original))
.Any(info => info.Owners.Contains(harmonyID));
}
public Patches GetPatchInfo(MethodBase method)
{
return PatchProcessor.GetPatchInfo(method);
}
public IEnumerable<MethodBase> GetPatchedMethods()
{
return HarmonySharedState.GetPatchedMethods();
}
public Dictionary<string, Version> VersionInfo(out Version currentVersion)
{
currentVersion = typeof(HarmonyInstance).Assembly.GetName().Version;
var assemblies = new Dictionary<string, Assembly>();
CollectionExtensions.Do(GetPatchedMethods(), method =>
{
var info = HarmonySharedState.GetPatchInfo(method);
info.prefixes.Do(fix => assemblies[fix.owner] = fix.patch.DeclaringType.Assembly);
info.postfixes.Do(fix => assemblies[fix.owner] = fix.patch.DeclaringType.Assembly);
info.transpilers.Do(fix => assemblies[fix.owner] = fix.patch.DeclaringType.Assembly);
});
var result = new Dictionary<string, Version>();
assemblies.Do(info =>
{
var assemblyName = info.Value.GetReferencedAssemblies().FirstOrDefault(a => a.FullName.StartsWith("0Harmony, Version"));
if (assemblyName != null)
result[info.Key] = assemblyName.Version;
});
return result;
}
}
}
@@ -0,0 +1,141 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
namespace Harmony
{
public class HarmonyMethod
{
public MethodInfo method; // need to be called 'method'
public Type declaringType;
public string methodName;
public MethodType? methodType;
public Type[] argumentTypes;
public int prioritiy = -1;
public string[] before;
public string[] after;
public HarmonyMethod()
{
}
void ImportMethod(MethodInfo theMethod)
{
method = theMethod;
if (method != null)
{
var infos = method.GetHarmonyMethods();
if (infos != null)
Merge(infos).CopyTo(this);
}
}
public HarmonyMethod(MethodInfo method)
{
ImportMethod(method);
}
public HarmonyMethod(Type type, string name, Type[] parameters = null)
{
var method = AccessTools.Method(type, name, parameters);
ImportMethod(method);
}
public static List<string> HarmonyFields()
{
return AccessTools
.GetFieldNames(typeof(HarmonyMethod))
.Where(s => s != "method")
.ToList();
}
public static HarmonyMethod Merge(List<HarmonyMethod> attributes)
{
var result = new HarmonyMethod();
if (attributes == null) return result;
var resultTrv = Traverse.Create(result);
attributes.ForEach(attribute =>
{
var trv = Traverse.Create(attribute);
HarmonyFields().ForEach(f =>
{
var val = trv.Field(f).GetValue();
if (val != null)
resultTrv.Field(f).SetValue(val);
});
});
return result;
}
public override string ToString()
{
var result = "HarmonyMethod[";
var trv = Traverse.Create(this);
HarmonyFields().ForEach(f =>
{
result += f + '=' + trv.Field(f).GetValue();
});
return result + "]";
}
}
public static class HarmonyMethodExtensions
{
public static void CopyTo(this HarmonyMethod from, HarmonyMethod to)
{
if (to == null) return;
var fromTrv = Traverse.Create(from);
var toTrv = Traverse.Create(to);
HarmonyMethod.HarmonyFields().ForEach(f =>
{
var val = fromTrv.Field(f).GetValue();
if (val != null) toTrv.Field(f).SetValue(val);
});
}
public static HarmonyMethod Clone(this HarmonyMethod original)
{
var result = new HarmonyMethod();
original.CopyTo(result);
return result;
}
public static HarmonyMethod Merge(this HarmonyMethod master, HarmonyMethod detail)
{
if (detail == null) return master;
var result = new HarmonyMethod();
var resultTrv = Traverse.Create(result);
var masterTrv = Traverse.Create(master);
var detailTrv = Traverse.Create(detail);
HarmonyMethod.HarmonyFields().ForEach(f =>
{
var baseValue = masterTrv.Field(f).GetValue();
var detailValue = detailTrv.Field(f).GetValue();
resultTrv.Field(f).SetValue(detailValue ?? baseValue);
});
return result;
}
public static List<HarmonyMethod> GetHarmonyMethods(this Type type)
{
return type.GetCustomAttributes(true)
.Where(attr => attr is HarmonyAttribute)
.Cast<HarmonyAttribute>()
.Select(attr => attr.info)
.ToList();
}
public static List<HarmonyMethod> GetHarmonyMethods(this MethodBase method)
{
if (method is DynamicMethod) return new List<HarmonyMethod>();
return method.GetCustomAttributes(true)
.Where(attr => attr is HarmonyAttribute)
.Cast<HarmonyAttribute>()
.Select(attr => attr.info)
.ToList();
}
}
}
@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using HarmonyLib;
using ShimHelpers;
namespace Harmony
{
public static class HarmonySharedState
{
private static Type harmonyLibSharedState =
typeof(HarmonyLib.Harmony).Assembly.GetType("HarmonyLib.HarmonySharedState");
internal static readonly int internalVersion = 100;
internal static int actualVersion = -1;
internal static Func<MethodBase, PatchInfo> GetPatchInfo = ShimUtil.MakeDelegate<Func<MethodBase, PatchInfo>>(harmonyLibSharedState, nameof(GetPatchInfo));
internal static Func<IEnumerable<MethodBase>> GetPatchedMethods = ShimUtil.MakeDelegate<Func<IEnumerable<MethodBase>>>(harmonyLibSharedState, nameof(GetPatchedMethods));
internal static Action<MethodBase, PatchInfo> UpdatePatchInfo = ShimUtil.MakeDelegate<Action<MethodBase, PatchInfo>>(harmonyLibSharedState, nameof(UpdatePatchInfo));
}
}
@@ -0,0 +1,179 @@
using System;
using System.Reflection;
using System.Reflection.Emit;
namespace Harmony
{
// Based on https://www.codeproject.com/Articles/14593/A-General-Fast-Method-Invoker
public delegate object FastInvokeHandler(object target, object[] paramters);
public class MethodInvoker
{
public static FastInvokeHandler GetHandler(DynamicMethod methodInfo, Module module)
{
return Handler(methodInfo, module);
}
public static FastInvokeHandler GetHandler(MethodInfo methodInfo)
{
return Handler(methodInfo, methodInfo.DeclaringType.Module);
}
static FastInvokeHandler Handler(MethodInfo methodInfo, Module module, bool directBoxValueAccess = false)
{
var dynamicMethod = new DynamicMethod("FastInvoke_" + methodInfo.Name + "_" + (directBoxValueAccess ? "direct" : "indirect"), typeof(object), new Type[] { typeof(object), typeof(object[]) }, module, true);
var il = dynamicMethod.GetILGenerator();
if (!methodInfo.IsStatic)
{
il.Emit(OpCodes.Ldarg_0);
EmitUnboxIfNeeded(il, methodInfo.DeclaringType);
}
var generateLocalBoxValuePtr = true;
var ps = methodInfo.GetParameters();
for (var i = 0; i < ps.Length; i++)
{
var argType = ps[i].ParameterType;
var argIsByRef = argType.IsByRef;
if (argIsByRef)
argType = argType.GetElementType();
var argIsValueType = argType.IsValueType;
if (argIsByRef && argIsValueType && !directBoxValueAccess)
{
// used later when storing back the reference to the new box in the array.
il.Emit(OpCodes.Ldarg_1);
EmitFastInt(il, i);
}
il.Emit(OpCodes.Ldarg_1);
EmitFastInt(il, i);
if (argIsByRef && !argIsValueType)
{
il.Emit(OpCodes.Ldelema, typeof(object));
}
else
{
il.Emit(OpCodes.Ldelem_Ref);
if (argIsValueType)
{
if (!argIsByRef || !directBoxValueAccess)
{
// if !directBoxValueAccess, create a new box if required
il.Emit(OpCodes.Unbox_Any, argType);
if (argIsByRef)
{
// box back
il.Emit(OpCodes.Box, argType);
// store new box value address to local 0
il.Emit(OpCodes.Dup);
il.Emit(OpCodes.Unbox, argType);
if (generateLocalBoxValuePtr)
{
generateLocalBoxValuePtr = false;
// Yes, you're seeing this right - a local of type void* to store the box value address!
il.DeclareLocal(typeof(void*), true);
}
il.Emit(OpCodes.Stloc_0);
// arr and index set up already
il.Emit(OpCodes.Stelem_Ref);
// load address back to stack
il.Emit(OpCodes.Ldloc_0);
}
}
else
{
// if directBoxValueAccess, emit unbox (get value address)
il.Emit(OpCodes.Unbox, argType);
}
}
}
}
#pragma warning disable XS0001
if (methodInfo.IsStatic)
il.EmitCall(OpCodes.Call, methodInfo, null);
else
il.EmitCall(OpCodes.Callvirt, methodInfo, null);
#pragma warning restore XS0001
if (methodInfo.ReturnType == typeof(void))
il.Emit(OpCodes.Ldnull);
else
EmitBoxIfNeeded(il, methodInfo.ReturnType);
il.Emit(OpCodes.Ret);
var invoder = (FastInvokeHandler)dynamicMethod.CreateDelegate(typeof(FastInvokeHandler));
return invoder;
}
static void EmitCastToReference(ILGenerator il, Type type)
{
if (type.IsValueType)
il.Emit(OpCodes.Unbox_Any, type);
else
il.Emit(OpCodes.Castclass, type);
}
static void EmitUnboxIfNeeded(ILGenerator il, Type type)
{
if (type.IsValueType)
il.Emit(OpCodes.Unbox_Any, type);
}
static void EmitBoxIfNeeded(ILGenerator il, Type type)
{
if (type.IsValueType)
il.Emit(OpCodes.Box, type);
}
static void EmitFastInt(ILGenerator il, int value)
{
switch (value)
{
case -1:
il.Emit(OpCodes.Ldc_I4_M1);
return;
case 0:
il.Emit(OpCodes.Ldc_I4_0);
return;
case 1:
il.Emit(OpCodes.Ldc_I4_1);
return;
case 2:
il.Emit(OpCodes.Ldc_I4_2);
return;
case 3:
il.Emit(OpCodes.Ldc_I4_3);
return;
case 4:
il.Emit(OpCodes.Ldc_I4_4);
return;
case 5:
il.Emit(OpCodes.Ldc_I4_5);
return;
case 6:
il.Emit(OpCodes.Ldc_I4_6);
return;
case 7:
il.Emit(OpCodes.Ldc_I4_7);
return;
case 8:
il.Emit(OpCodes.Ldc_I4_8);
return;
}
if (value > -129 && value < 128)
il.Emit(OpCodes.Ldc_I4_S, (sbyte)value);
else
il.Emit(OpCodes.Ldc_I4, value);
}
}
}
@@ -0,0 +1,68 @@
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using HarmonyLib;
namespace Harmony
{
public static class PatchInfoSerialization
{
class Binder : SerializationBinder
{
public override Type BindToType(string assemblyName, string typeName)
{
var types = new Type[] {
typeof(PatchInfo),
typeof(Patch[]),
typeof(Patch)
};
foreach (var type in types)
if (typeName == type.FullName)
return type;
var typeToDeserialize = Type.GetType(string.Format("{0}, {1}", typeName, assemblyName));
return typeToDeserialize;
}
}
public static byte[] Serialize(this PatchInfo patchInfo)
{
#pragma warning disable XS0001
using (var streamMemory = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(streamMemory, patchInfo);
return streamMemory.GetBuffer();
}
#pragma warning restore XS0001
}
public static PatchInfo Deserialize(byte[] bytes)
{
var formatter = new BinaryFormatter { Binder = new Binder() };
#pragma warning disable XS0001
var streamMemory = new MemoryStream(bytes);
#pragma warning restore XS0001
return (PatchInfo)formatter.Deserialize(streamMemory);
}
// general sorting by (in that order): before, after, priority and index
public static int PriorityComparer(object obj, int index, int priority, string[] before, string[] after)
{
var trv = Traverse.Create(obj);
var theirOwner = trv.Field("owner").GetValue<string>();
var theirPriority = trv.Field("priority").GetValue<int>();
var theirIndex = trv.Field("index").GetValue<int>();
if (before != null && Array.IndexOf(before, theirOwner) > -1)
return -1;
if (after != null && Array.IndexOf(after, theirOwner) > -1)
return 1;
if (priority != theirPriority)
return -(priority.CompareTo(theirPriority));
return index.CompareTo(theirIndex);
}
}
}
@@ -0,0 +1,81 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using HarmonyLib;
using ShimHelpers;
namespace Harmony
{
public static class PatchFunctions
{
private static readonly Type patchFunctionsNew =
typeof(HarmonyLib.Harmony).Assembly.GetType("HarmonyLib.PatchFunctions");
public static Func<MethodBase, PatchInfo, string, DynamicMethod> UpdateWrapper =
ShimUtil.MakeDelegate<Func<MethodBase, PatchInfo, string, DynamicMethod>>(patchFunctionsNew, nameof(UpdateWrapper));
public static void AddPrefix(PatchInfo patchInfo, string owner, HarmonyMethod info)
{
if (info == null || info.method == null) return;
var priority = info.prioritiy == -1 ? Priority.Normal : info.prioritiy;
var before = info.before ?? new string[0];
var after = info.after ?? new string[0];
patchInfo.AddPrefix(info.method, owner, priority, before, after);
}
public static void RemovePrefix(PatchInfo patchInfo, string owner)
{
patchInfo.RemovePrefix(owner);
}
public static void AddPostfix(PatchInfo patchInfo, string owner, HarmonyMethod info)
{
if (info == null || info.method == null) return;
var priority = info.prioritiy == -1 ? Priority.Normal : info.prioritiy;
var before = info.before ?? new string[0];
var after = info.after ?? new string[0];
patchInfo.AddPostfix(info.method, owner, priority, before, after);
}
public static void RemovePostfix(PatchInfo patchInfo, string owner)
{
patchInfo.RemovePostfix(owner);
}
public static void AddTranspiler(PatchInfo patchInfo, string owner, HarmonyMethod info)
{
if (info == null || info.method == null) return;
var priority = info.prioritiy == -1 ? Priority.Normal : info.prioritiy;
var before = info.before ?? new string[0];
var after = info.after ?? new string[0];
patchInfo.AddTranspiler(info.method, owner, priority, before, after);
}
public static void RemoveTranspiler(PatchInfo patchInfo, string owner)
{
patchInfo.RemoveTranspiler(owner);
}
public static void RemovePatch(PatchInfo patchInfo, MethodInfo patch)
{
patchInfo.RemovePatch(patch);
}
public static List<MethodInfo> GetSortedPatchMethods(MethodBase original, Patch[] patches)
{
return patches
.Where(p => p.patch != null)
.OrderBy(p => p)
.Select(p => p.GetMethod(original))
.ToList();
}
}
}
@@ -0,0 +1,320 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using HarmonyLib;
namespace Harmony
{
public class PatchProcessor
{
static object locker = new object();
readonly HarmonyInstance instance;
readonly Type container;
readonly HarmonyMethod containerAttributes;
List<MethodBase> originals = new List<MethodBase>();
HarmonyMethod prefix;
HarmonyMethod postfix;
HarmonyMethod transpiler;
public PatchProcessor(HarmonyInstance instance, Type type, HarmonyMethod attributes)
{
this.instance = instance;
container = type;
containerAttributes = attributes ?? new HarmonyMethod(null);
prefix = containerAttributes.Clone();
postfix = containerAttributes.Clone();
transpiler = containerAttributes.Clone();
PrepareType();
}
public PatchProcessor(HarmonyInstance instance, List<MethodBase> originals, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null)
{
this.instance = instance;
this.originals = originals;
this.prefix = prefix ?? new HarmonyMethod(null);
this.postfix = postfix ?? new HarmonyMethod(null);
this.transpiler = transpiler ?? new HarmonyMethod(null);
}
public PatchProcessor(HarmonyInstance instance, HarmonyMethod original, HarmonyMethod prefix = null,
HarmonyMethod postfix = null, HarmonyMethod transpiler = null)
{
this.instance = instance;
containerAttributes = original;
originals = new List<MethodBase>(new[]
{
GetOriginalMethod()
});
this.prefix = prefix ?? new HarmonyMethod(null);
this.postfix = postfix ?? new HarmonyMethod(null);
this.transpiler = transpiler ?? new HarmonyMethod(null);
}
public static Patches GetPatchInfo(MethodBase method)
{
lock (locker)
{
var patchInfo = HarmonySharedState.GetPatchInfo(method);
if (patchInfo == null) return null;
return new Patches(patchInfo.prefixes, patchInfo.postfixes, patchInfo.transpilers, patchInfo.finalizers);
}
}
public static IEnumerable<MethodBase> AllPatchedMethods()
{
lock (locker)
{
return HarmonySharedState.GetPatchedMethods();
}
}
public List<DynamicMethod> Patch()
{
lock (locker)
{
var dynamicMethods = new List<DynamicMethod>();
foreach (var original in originals)
{
if (original == null)
throw new NullReferenceException("original");
var individualPrepareResult = RunMethod<HarmonyPrepare, bool>(true, original);
if (individualPrepareResult)
{
var patchInfo = HarmonySharedState.GetPatchInfo(original);
if (patchInfo == null) patchInfo = new PatchInfo();
PatchFunctions.AddPrefix(patchInfo, instance.Id, prefix);
PatchFunctions.AddPostfix(patchInfo, instance.Id, postfix);
PatchFunctions.AddTranspiler(patchInfo, instance.Id, transpiler);
dynamicMethods.Add(PatchFunctions.UpdateWrapper(original, patchInfo, instance.Id));
HarmonySharedState.UpdatePatchInfo(original, patchInfo);
RunMethod<HarmonyCleanup>(original);
}
}
return dynamicMethods;
}
}
public void Unpatch(HarmonyPatchType type, string harmonyID)
{
lock (locker)
{
foreach (var original in originals)
{
var patchInfo = HarmonySharedState.GetPatchInfo(original);
if (patchInfo == null) patchInfo = new PatchInfo();
if (type == HarmonyPatchType.All || type == HarmonyPatchType.Prefix)
PatchFunctions.RemovePrefix(patchInfo, harmonyID);
if (type == HarmonyPatchType.All || type == HarmonyPatchType.Postfix)
PatchFunctions.RemovePostfix(patchInfo, harmonyID);
if (type == HarmonyPatchType.All || type == HarmonyPatchType.Transpiler)
PatchFunctions.RemoveTranspiler(patchInfo, harmonyID);
PatchFunctions.UpdateWrapper(original, patchInfo, instance.Id);
HarmonySharedState.UpdatePatchInfo(original, patchInfo);
}
}
}
public void Unpatch(MethodInfo patch)
{
lock (locker)
{
foreach (var original in originals)
{
var patchInfo = HarmonySharedState.GetPatchInfo(original);
if (patchInfo == null) patchInfo = new PatchInfo();
PatchFunctions.RemovePatch(patchInfo, patch);
PatchFunctions.UpdateWrapper(original, patchInfo, instance.Id);
HarmonySharedState.UpdatePatchInfo(original, patchInfo);
}
}
}
void PrepareType()
{
var mainPrepareResult = RunMethod<HarmonyPrepare, bool>(true);
if (mainPrepareResult == false)
return;
var customOriginals = RunMethod<HarmonyTargetMethods, IEnumerable<MethodBase>>(null);
if (customOriginals != null)
{
originals = customOriginals.ToList();
}
else
{
var originalMethodType = containerAttributes.methodType;
// MethodType default is Normal
if (containerAttributes.methodType == null)
containerAttributes.methodType = MethodType.Normal;
var isPatchAll = Attribute.GetCustomAttribute(container, typeof(HarmonyPatchAll)) != null;
if (isPatchAll)
{
var type = containerAttributes.declaringType;
originals.AddRange(AccessTools.GetDeclaredConstructors(type).Cast<MethodBase>());
originals.AddRange(AccessTools.GetDeclaredMethods(type).Cast<MethodBase>());
}
else
{
var original = RunMethod<HarmonyTargetMethod, MethodBase>(null);
if (original == null)
original = GetOriginalMethod();
if (original == null)
{
var info = "(";
info += "declaringType=" + containerAttributes.declaringType + ", ";
info += "methodName =" + containerAttributes.methodName + ", ";
info += "methodType=" + originalMethodType + ", ";
info += "argumentTypes=" + containerAttributes.argumentTypes.Description();
info += ")";
throw new ArgumentException("No target method specified for class " + container.FullName + " " + info);
}
originals.Add(original);
}
}
PatchTools.GetPatches(container, out prefix.method, out postfix.method, out transpiler.method);
if (prefix.method != null)
{
if (prefix.method.IsStatic == false)
throw new ArgumentException("Patch method " + prefix.method.FullDescription() + " must be static");
var prefixAttributes = prefix.method.GetHarmonyMethods();
containerAttributes.Merge(HarmonyMethod.Merge(prefixAttributes)).CopyTo(prefix);
}
if (postfix.method != null)
{
if (postfix.method.IsStatic == false)
throw new ArgumentException("Patch method " + postfix.method.FullDescription() + " must be static");
var postfixAttributes = postfix.method.GetHarmonyMethods();
containerAttributes.Merge(HarmonyMethod.Merge(postfixAttributes)).CopyTo(postfix);
}
if (transpiler.method != null)
{
if (transpiler.method.IsStatic == false)
throw new ArgumentException("Patch method " + transpiler.method.FullDescription() + " must be static");
var infixAttributes = transpiler.method.GetHarmonyMethods();
containerAttributes.Merge(HarmonyMethod.Merge(infixAttributes)).CopyTo(transpiler);
}
}
MethodBase GetOriginalMethod()
{
var attr = containerAttributes;
if (attr.declaringType == null) return null;
switch (attr.methodType)
{
case MethodType.Normal:
if (attr.methodName == null)
return null;
return AccessTools.DeclaredMethod(attr.declaringType, attr.methodName, attr.argumentTypes);
case MethodType.Getter:
if (attr.methodName == null)
return null;
return AccessTools.DeclaredProperty(attr.declaringType, attr.methodName).GetGetMethod(true);
case MethodType.Setter:
if (attr.methodName == null)
return null;
return AccessTools.DeclaredProperty(attr.declaringType, attr.methodName).GetSetMethod(true);
case MethodType.Constructor:
return AccessTools.DeclaredConstructor(attr.declaringType, attr.argumentTypes);
case MethodType.StaticConstructor:
return AccessTools.GetDeclaredConstructors(attr.declaringType)
.Where(c => c.IsStatic)
.FirstOrDefault();
}
return null;
}
T RunMethod<S, T>(T defaultIfNotExisting, params object[] parameters)
{
if (container == null)
return defaultIfNotExisting;
var methodName = typeof(S).Name.Replace("Harmony", "");
var paramList = new List<object> { instance };
paramList.AddRange(parameters);
var paramTypes = AccessTools.GetTypes(paramList.ToArray());
var method = PatchTools.GetPatchMethod<S>(container, methodName, paramTypes);
if (method != null && typeof(T).IsAssignableFrom(method.ReturnType))
return (T)method.Invoke(null, paramList.ToArray());
method = PatchTools.GetPatchMethod<S>(container, methodName, new Type[] { typeof(HarmonyInstance) });
if (method != null && typeof(T).IsAssignableFrom(method.ReturnType))
return (T)method.Invoke(null, new object[] { instance });
method = PatchTools.GetPatchMethod<S>(container, methodName, Type.EmptyTypes);
if (method != null)
{
if (typeof(T).IsAssignableFrom(method.ReturnType))
return (T)method.Invoke(null, Type.EmptyTypes);
method.Invoke(null, Type.EmptyTypes);
return defaultIfNotExisting;
}
return defaultIfNotExisting;
}
void RunMethod<S>(params object[] parameters)
{
if (container == null)
return;
var methodName = typeof(S).Name.Replace("Harmony", "");
var paramList = new List<object> { instance };
paramList.AddRange(parameters);
var paramTypes = AccessTools.GetTypes(paramList.ToArray());
var method = PatchTools.GetPatchMethod<S>(container, methodName, paramTypes);
if (method != null)
{
method.Invoke(null, paramList.ToArray());
return;
}
method = PatchTools.GetPatchMethod<S>(container, methodName, new Type[] { typeof(HarmonyInstance) });
if (method != null)
{
method.Invoke(null, new object[] { instance });
return;
}
method = PatchTools.GetPatchMethod<S>(container, methodName, Type.EmptyTypes);
if (method != null)
{
method.Invoke(null, Type.EmptyTypes);
return;
}
}
}
}
@@ -0,0 +1,33 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Harmony
{
public static class PatchTools
{
// this holds all the objects we want to keep alive so they don't get garbage-collected
static Dictionary<object, object> objectReferences = new Dictionary<object, object>();
public static void RememberObject(object key, object value)
{
objectReferences[key] = value;
}
public static MethodInfo GetPatchMethod<T>(Type patchType, string name, Type[] parameters = null)
{
var method = patchType.GetMethods(AccessTools.all)
.FirstOrDefault(m => m.GetCustomAttributes(typeof(T), true).Any());
if (method == null)
method = AccessTools.Method(patchType, name, parameters);
return method;
}
public static void GetPatches(Type patchType, out MethodInfo prefix, out MethodInfo postfix, out MethodInfo transpiler)
{
prefix = GetPatchMethod<HarmonyPrefix>(patchType, "Prefix");
postfix = GetPatchMethod<HarmonyPostfix>(patchType, "Postfix");
transpiler = GetPatchMethod<HarmonyTranspiler>(patchType, "Transpiler");
}
}
}
@@ -0,0 +1,15 @@
namespace Harmony
{
public static class Priority
{
public const int Last = 0;
public const int VeryLow = 100;
public const int Low = 200;
public const int LowerThanNormal = 300;
public const int Normal = 400;
public const int HigherThanNormal = 500;
public const int High = 600;
public const int VeryHigh = 700;
public const int First = 800;
}
}
@@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace ShimHelpers
{
internal static class ShimUtil
{
public static T MakeDelegate<T>(Type t, string method) where T : class
{
var m = t.GetMethod(method, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
return Delegate.CreateDelegate(typeof(T), m) as T;
}
public static T MakeGetter<T>(FieldInfo f) where T : class
{
DynamicMethod dm = new DynamicMethod($"shimutil_field_{f.DeclaringType.Name}_{f.Name}_get", f.FieldType, f.IsStatic ? null : new []{f.DeclaringType}, typeof(ShimUtil), true);
var il = dm.GetILGenerator();
if (f.IsStatic)
il.Emit(OpCodes.Ldsfld, f);
else
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, f);
}
il.Emit(OpCodes.Ret);
return dm.CreateDelegate(typeof(T)) as T;
}
public static T MakeSetter<T>(FieldInfo f) where T : class
{
var l = new List<Type>();
if(f.IsStatic)
l.Add(f.DeclaringType);
l.Add(f.FieldType);
DynamicMethod dm = new DynamicMethod($"shimutil_field_{f.DeclaringType.Name}_{f.Name}_set", f.FieldType, l.ToArray(), typeof(ShimUtil), true);
var il = dm.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
if (f.IsStatic)
il.Emit(OpCodes.Ldsfld, f);
else
{
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldfld, f);
}
il.Emit(OpCodes.Ret);
return dm.CreateDelegate(typeof(T)) as T;
}
}
}
@@ -0,0 +1,61 @@
using System.Linq.Expressions;
using System.Reflection;
using System;
namespace Harmony
{
public static class SymbolExtensions
{
/// <summary>
/// Given a lambda expression that calls a method, returns the method info.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expression">The expression.</param>
/// <returns></returns>
public static MethodInfo GetMethodInfo(Expression<Action> expression)
{
return GetMethodInfo((LambdaExpression)expression);
}
/// <summary>
/// Given a lambda expression that calls a method, returns the method info.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expression">The expression.</param>
/// <returns></returns>
public static MethodInfo GetMethodInfo<T>(Expression<Action<T>> expression)
{
return GetMethodInfo((LambdaExpression)expression);
}
/// <summary>
/// Given a lambda expression that calls a method, returns the method info.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expression">The expression.</param>
/// <returns></returns>
public static MethodInfo GetMethodInfo<T, TResult>(Expression<Func<T, TResult>> expression)
{
return GetMethodInfo((LambdaExpression)expression);
}
/// <summary>
/// Given a lambda expression that calls a method, returns the method info.
/// </summary>
/// <param name="expression">The expression.</param>
/// <returns></returns>
public static MethodInfo GetMethodInfo(LambdaExpression expression)
{
var outermostExpression = expression.Body as MethodCallExpression;
if (outermostExpression == null)
throw new ArgumentException("Invalid Expression. Expression should consist of a Method call only.");
var method = outermostExpression.Method;
if (method == null)
throw new Exception("Cannot find method for expression " + expression);
return method;
}
}
}
@@ -0,0 +1,298 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace Harmony
{
public class Traverse<T>
{
private Traverse traverse;
Traverse()
{
}
public Traverse(Traverse traverse)
{
this.traverse = traverse;
}
public T Value
{
get => traverse.GetValue<T>();
set => traverse.SetValue(value);
}
}
public class Traverse
{
static AccessCache Cache;
Type _type;
object _root;
MemberInfo _info;
MethodBase _method;
object[] _params;
[MethodImpl(MethodImplOptions.Synchronized)]
static Traverse()
{
if (Cache == null)
Cache = new AccessCache();
}
public static Traverse Create(Type type)
{
return new Traverse(type);
}
public static Traverse Create<T>()
{
return Create(typeof(T));
}
public static Traverse Create(object root)
{
return new Traverse(root);
}
public static Traverse CreateWithType(string name)
{
return new Traverse(AccessTools.TypeByName(name));
}
Traverse()
{
}
public Traverse(Type type)
{
_type = type;
}
public Traverse(object root)
{
_root = root;
_type = root?.GetType();
}
Traverse(object root, MemberInfo info, object[] index)
{
_root = root;
_type = root?.GetType();
_info = info;
_params = index;
}
Traverse(object root, MethodInfo method, object[] parameter)
{
_root = root;
_type = method.ReturnType;
_method = method;
_params = parameter;
}
public object GetValue()
{
if (_info is FieldInfo)
return ((FieldInfo)_info).GetValue(_root);
if (_info is PropertyInfo)
return ((PropertyInfo)_info).GetValue(_root, AccessTools.all, null, _params, CultureInfo.CurrentCulture);
if (_method != null)
return _method.Invoke(_root, _params);
if (_root == null && _type != null) return _type;
return _root;
}
public T GetValue<T>()
{
var value = GetValue();
if (value == null) return default(T);
return (T)value;
}
public object GetValue(params object[] arguments)
{
if (_method == null)
throw new Exception("cannot get method value without method");
return _method.Invoke(_root, arguments);
}
public T GetValue<T>(params object[] arguments)
{
if (_method == null)
throw new Exception("cannot get method value without method");
return (T)_method.Invoke(_root, arguments);
}
public Traverse SetValue(object value)
{
if (_info is FieldInfo)
((FieldInfo)_info).SetValue(_root, value, AccessTools.all, null, CultureInfo.CurrentCulture);
if (_info is PropertyInfo)
((PropertyInfo)_info).SetValue(_root, value, AccessTools.all, null, _params, CultureInfo.CurrentCulture);
if (_method != null)
throw new Exception("cannot set value of method " + _method.FullDescription());
return this;
}
public Type GetValueType()
{
if (_info is FieldInfo)
return ((FieldInfo)_info).FieldType;
if (_info is PropertyInfo)
return ((PropertyInfo)_info).PropertyType;
return null;
}
Traverse Resolve()
{
if (_root == null && _type != null) return this;
return new Traverse(GetValue());
}
public Traverse Type(string name)
{
if (name == null) throw new ArgumentNullException("name cannot be null");
if (_type == null) return new Traverse();
var type = AccessTools.Inner(_type, name);
if (type == null) return new Traverse();
return new Traverse(type);
}
public Traverse Field(string name)
{
if (name == null) throw new ArgumentNullException("name cannot be null");
var resolved = Resolve();
if (resolved._type == null) return new Traverse();
var info = Cache.GetFieldInfo(resolved._type, name);
if (info == null) return new Traverse();
if (info.IsStatic == false && resolved._root == null) return new Traverse();
return new Traverse(resolved._root, info, null);
}
public Traverse<T> Field<T>(string name)
{
return new Traverse<T>(Field(name));
}
public List<string> Fields()
{
var resolved = Resolve();
return AccessTools.GetFieldNames(resolved._type);
}
public Traverse Property(string name, object[] index = null)
{
if (name == null) throw new ArgumentNullException("name cannot be null");
var resolved = Resolve();
if (resolved._root == null || resolved._type == null) return new Traverse();
var info = Cache.GetPropertyInfo(resolved._type, name);
if (info == null) return new Traverse();
return new Traverse(resolved._root, info, index);
}
public Traverse<T> Property<T>(string name, object[] index = null)
{
return new Traverse<T>(Property(name, index));
}
public List<string> Properties()
{
var resolved = Resolve();
return AccessTools.GetPropertyNames(resolved._type);
}
public Traverse Method(string name, params object[] arguments)
{
if (name == null) throw new ArgumentNullException("name cannot be null");
var resolved = Resolve();
if (resolved._type == null) return new Traverse();
var types = AccessTools.GetTypes(arguments);
var method = Cache.GetMethodInfo(resolved._type, name, types);
if (method == null) return new Traverse();
return new Traverse(resolved._root, (MethodInfo)method, arguments);
}
public Traverse Method(string name, Type[] paramTypes, object[] arguments = null)
{
if (name == null) throw new ArgumentNullException("name cannot be null");
var resolved = Resolve();
if (resolved._type == null) return new Traverse();
var method = Cache.GetMethodInfo(resolved._type, name, paramTypes);
if (method == null) return new Traverse();
return new Traverse(resolved._root, (MethodInfo)method, arguments);
}
public List<string> Methods()
{
var resolved = Resolve();
return AccessTools.GetMethodNames(resolved._type);
}
public bool FieldExists()
{
return _info != null;
}
public bool MethodExists()
{
return _method != null;
}
public bool TypeExists()
{
return _type != null;
}
public static void IterateFields(object source, Action<Traverse> action)
{
var sourceTrv = Create(source);
AccessTools.GetFieldNames(source).ForEach(f => action(sourceTrv.Field(f)));
}
public static void IterateFields(object source, object target, Action<Traverse, Traverse> action)
{
var sourceTrv = Create(source);
var targetTrv = Create(target);
AccessTools.GetFieldNames(source).ForEach(f => action(sourceTrv.Field(f), targetTrv.Field(f)));
}
public static void IterateFields(object source, object target, Action<string, Traverse, Traverse> action)
{
var sourceTrv = Create(source);
var targetTrv = Create(target);
AccessTools.GetFieldNames(source).ForEach(f => action(f, sourceTrv.Field(f), targetTrv.Field(f)));
}
public static void IterateProperties(object source, Action<Traverse> action)
{
var sourceTrv = Create(source);
AccessTools.GetPropertyNames(source).ForEach(f => action(sourceTrv.Property(f)));
}
public static void IterateProperties(object source, object target, Action<Traverse, Traverse> action)
{
var sourceTrv = Create(source);
var targetTrv = Create(target);
AccessTools.GetPropertyNames(source).ForEach(f => action(sourceTrv.Property(f), targetTrv.Property(f)));
}
public static void IterateProperties(object source, object target, Action<string, Traverse, Traverse> action)
{
var sourceTrv = Create(source);
var targetTrv = Create(target);
AccessTools.GetPropertyNames(source).ForEach(f => action(f, sourceTrv.Property(f), targetTrv.Property(f)));
}
public static Action<Traverse, Traverse> CopyFields = (from, to) => { to.SetValue(from.GetValue()); };
public override string ToString()
{
var value = _method ?? GetValue();
return value?.ToString();
}
}
}
+203
View File
@@ -0,0 +1,203 @@
using BepInEx.Configuration;
using BepInEx.IPALoader;
using BepInEx.Logging;
using HarmonyLib;
using Mono.Cecil;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
namespace BepInEx.IPAHarmonyShimmer
{
public static class HarmonyShimmer
{
public const string PluginName = "BepInEx.IPAHarmonyShimmer";
public static IEnumerable<string> TargetDLLs { get; } = new[] { "Assembly-CSharp.dll" };
private static readonly ManualLogSource Logger = Logging.Logger.CreateLogSource("IPAHarmonyShim");
public static ConfigEntry<string> IPAPluginsPath { get; private set; }
public static ConfigFile CfgFile { get; } = new ConfigFile(Path.Combine(Paths.ConfigPath, Metadata.ConfigFileName), false);
private static DefaultAssemblyResolver resolver;
private static ReaderParameters readerParameters;
private static AssemblyDefinition ResolveAssemblies(object sender, AssemblyNameReference reference)
{
var name = new AssemblyName(reference.FullName);
if (Utility.TryResolveDllAssembly(name, Paths.BepInExAssemblyDirectory, readerParameters, out var assembly) || Utility.TryResolveDllAssembly(name, Path.Combine(Paths.GameRootPath, IPAPluginsPath.Value), readerParameters, out assembly) || Utility.TryResolveDllAssembly(name, Paths.ManagedPath, readerParameters, out assembly))
return assembly;
if (reference.Name == "0Harmony_Shim")
return AssemblyDefinition.ReadAssembly(Assembly.GetExecutingAssembly().Location);
return null;
}
private static bool definitionsAreReferences = false;
[HarmonyPatch(typeof(AccessTools), "DeclaredField", typeof(Type), typeof(string))]
[HarmonyPostfix]
private static void DeclaredFieldShim(ref FieldInfo __result, Type type, string name)
{
//wew at harmony for botching compatibility
if (__result == null)
__result = AccessTools.Field(type, name);
}
[HarmonyPatch(typeof(TypeDefinition), "IsDefinition", MethodType.Getter)]
[HarmonyPostfix]
private static void IsDefinitionPatch(TypeDefinition __instance, ref bool __result)
{
if (definitionsAreReferences && __instance.Scope is AssemblyNameReference assRef && assRef.Name.StartsWith("0Harmony"))
__result = false;
}
public static void Initialize()
{
IPAPluginsPath = CfgFile.Bind(Metadata.ConfigSection, Metadata.ConfigKey, Metadata.ConfigDefaultValue, Metadata.ConfigDescription);
HarmonyLib.Harmony.CreateAndPatchAll(typeof(HarmonyShimmer));
resolver = new DefaultAssemblyResolver();
readerParameters = new ReaderParameters { AssemblyResolver = resolver };
resolver.ResolveFailure += ResolveAssemblies;
Logger.LogInfo("Shimming IPA plugins");
string pluginDirectory = Path.Combine(Paths.GameRootPath, IPAPluginsPath.Value);
if (!Directory.Exists(pluginDirectory))
{
Logger.LogInfo("No IPA Plugins folder found! Skipping shimming...");
return;
}
var harmonyFullTypes = new Dictionary<string, string>();
var harmonyTypes = new HashSet<string>();
using (var bepinAss = AssemblyDefinition.ReadAssembly(Assembly.GetExecutingAssembly().Location))
{
foreach (var type in bepinAss.MainModule.Types)
if (type.Namespace.StartsWith("Harmony"))
harmonyTypes.Add(type.FullName);
}
using (var origHarmonyAss = AssemblyDefinition.ReadAssembly(Path.Combine(Paths.BepInExAssemblyDirectory, "0Harmony.dll")))
{
foreach (var type in origHarmonyAss.MainModule.Types)
{
if (type.Namespace.StartsWith("HarmonyLib"))
harmonyFullTypes[type.Name] = type.Namespace;
}
}
var bakDir = Path.Combine(Paths.GameRootPath, IPAPluginsPath.Value) + "_backup";
Directory.CreateDirectory(bakDir);
foreach (string file in Directory.GetFiles(pluginDirectory, "*.dll", SearchOption.AllDirectories))
{
try
{
var ad = AssemblyDefinition.ReadAssembly(new MemoryStream(File.ReadAllBytes(file)));
if (ad.MainModule.AssemblyResolver is DefaultAssemblyResolver pluginResolver)
pluginResolver.ResolveFailure += ResolveAssemblies;
var harmonyShimRef = new AssemblyNameReference("0Harmony_Shim", new Version(1, 1, 0, 0));
var harmony2Ref = new AssemblyNameReference("0Harmony", new Version(2, 0, 0, 0));
var harmonyRef = ad.MainModule.AssemblyReferences.FirstOrDefault(r => r.Name == "0Harmony" && r.Version.Major <= 1);
bool shimmed = false;
// Need to unmerge the assembly
if (ad.MainModule.Types.Any(t => harmonyTypes.Contains(t.FullName)))
{
shimmed = true;
Logger.LogInfo($"Unmerging {Path.GetFileNameWithoutExtension(file)}");
ad.MainModule.AssemblyReferences.Add(harmony2Ref);
ad.MainModule.AssemblyReferences.Add(harmonyShimRef);
foreach (var typeDefinition in ad.MainModule.Types.ToList())
{
string @namespace = null;
if (harmonyTypes.Contains(typeDefinition.FullName) || (typeDefinition.Namespace.StartsWith("Harmony") && harmonyFullTypes.TryGetValue(typeDefinition.Name, out @namespace)))
{
ad.MainModule.Types.Remove(typeDefinition);
typeDefinition.Scope = harmonyTypes.Contains(typeDefinition.FullName) ? harmonyShimRef : harmony2Ref;
typeDefinition.GetType().GetField("module", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(typeDefinition, ad.MainModule);
typeDefinition.MetadataToken = new MetadataToken(TokenType.TypeRef, 0);
if (@namespace != null)
typeDefinition.Namespace = @namespace;
foreach (var typeDefinitionMethod in typeDefinition.Methods)
typeDefinitionMethod.MetadataToken = new MetadataToken(TokenType.MemberRef, 0);
foreach (var typeDefinitionField in typeDefinition.Fields)
typeDefinitionField.MetadataToken = new MetadataToken(TokenType.MemberRef, 0);
}
}
}
// Otherwise just shim Harmony
else if (harmonyRef != null)
{
shimmed = true;
Logger.LogInfo($"Shimming {Path.GetFileNameWithoutExtension(file)}");
harmonyRef.Name = "0Harmony_Shim";
ad.MainModule.AssemblyReferences.Add(harmony2Ref);
foreach (var tr in ad.MainModule.GetTypeReferences())
if (tr.Namespace.StartsWith("Harmony"))
{
if (harmonyTypes.Contains(tr.FullName) || !harmonyFullTypes.TryGetValue(tr.Name, out var @namespace))
continue;
tr.Namespace = @namespace;
tr.Scope = harmony2Ref;
}
foreach (var memberReference in ad.MainModule.GetMemberReferences())
{
if (memberReference is MethodReference mref &&
mref.DeclaringType.Name == "HarmonyInstance" &&
mref.DeclaringType.Scope == harmonyRef &&
mref.Name == "Patch" &&
mref.ReturnType.FullName == "System.Void")
mref.Name = "PatchVoid";
}
}
// Toss .NET 4 attribute in case mono is doesn't support it
var tfa = ad.CustomAttributes.FirstOrDefault(c => c.AttributeType.FullName == "System.Runtime.Versioning.TargetFrameworkAttribute");
if (tfa != null)
{
shimmed = true;
ad.CustomAttributes.Remove(tfa);
}
if (shimmed)
{
var pathPart = file.Substring(pluginDirectory.Length + 1);
var bakPath = Path.Combine(bakDir, pathPart);
Logger.LogInfo($"Path part: {pathPart}; Bak dir: {bakDir}; Backup path: {bakPath}; original path: {file}");
Directory.CreateDirectory(Path.GetDirectoryName(bakPath));
File.Copy(file, bakPath, true);
definitionsAreReferences = true;
ad.Write(file);
definitionsAreReferences = false;
}
}
catch (Exception e)
{
Logger.LogWarning($"Failed to shim {Path.GetFileName(file)}. Reason: {e.Message}");
}
}
}
public static void Patch(AssemblyDefinition ad) { }
public static void Finish() => AppDomain.CurrentDomain.AssemblyResolve += (sender, args) => new AssemblyName(args.Name).Name == "0Harmony_Shim" ? Assembly.GetExecutingAssembly() : null;
}
}
@@ -0,0 +1,5 @@
using System.Reflection;
[assembly: AssemblyTitle(BepInEx.IPAHarmonyShimmer.HarmonyShimmer.PluginName)]
[assembly: AssemblyProduct(BepInEx.IPAHarmonyShimmer.HarmonyShimmer.PluginName)]
[assembly: AssemblyDescription(BepInEx.IPAHarmonyShimmer.HarmonyShimmer.PluginName)]
+18 -4
View File
@@ -1,13 +1,23 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.168
# Visual Studio Version 16
VisualStudioVersion = 16.0.29215.179
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BepInEx.IPALoader", "BepInEx.IPALoader\BepInEx.IPALoader.csproj", "{780F5E83-2A6B-4EA0-9476-449F5D96D56F}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BepInEx.IPALoader", "BepInEx.IPALoader\BepInEx.IPALoader.csproj", "{780F5E83-2A6B-4EA0-9476-449F5D96D56F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BepInEx.IPAVirtualizer", "BepInEx.IPAVirtualizer\BepInEx.IPAVirtualizer.csproj", "{4E636178-ADD9-4306-BE77-357ADFB13AAB}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BepInEx.IPAVirtualizer", "BepInEx.IPAVirtualizer\BepInEx.IPAVirtualizer.csproj", "{4E636178-ADD9-4306-BE77-357ADFB13AAB}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BepInEx.IPAHarmonyShimmer", "BepInEx.IPAHarmonyShimmer\BepInEx.IPAHarmonyShimmer.csproj", "{B022796F-A80E-41FE-AECF-D5BF2FDB0196}"
EndProject
Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Shared", "Shared\Shared.shproj", "{840C3CF7-696A-4998-8BF1-9510D1C9A3E2}"
EndProject
Global
GlobalSection(SharedMSBuildProjectFiles) = preSolution
Shared\Shared.projitems*{4e636178-add9-4306-be77-357adfb13aab}*SharedItemsImports = 5
Shared\Shared.projitems*{780f5e83-2a6b-4ea0-9476-449f5d96d56f}*SharedItemsImports = 5
Shared\Shared.projitems*{840c3cf7-696a-4998-8bf1-9510d1c9a3e2}*SharedItemsImports = 13
Shared\Shared.projitems*{b022796f-a80e-41fe-aecf-d5bf2fdb0196}*SharedItemsImports = 5
EndGlobalSection
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
@@ -21,6 +31,10 @@ Global
{4E636178-ADD9-4306-BE77-357ADFB13AAB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4E636178-ADD9-4306-BE77-357ADFB13AAB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4E636178-ADD9-4306-BE77-357ADFB13AAB}.Release|Any CPU.Build.0 = Release|Any CPU
{B022796F-A80E-41FE-AECF-D5BF2FDB0196}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B022796F-A80E-41FE-AECF-D5BF2FDB0196}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B022796F-A80E-41FE-AECF-D5BF2FDB0196}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B022796F-A80E-41FE-AECF-D5BF2FDB0196}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
+8 -55
View File
@@ -1,61 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{780F5E83-2A6B-4EA0-9476-449F5D96D56F}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>BepInEx.IPALoader</RootNamespace>
<AssemblyName>BepInEx.IPALoader</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>false</DebugSymbols>
<TargetFramework>net35</TargetFramework>
<DebugType>none</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\bin\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>none</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\bin\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<OutputPath>..\bin\plugins\</OutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
</PropertyGroup>
<ItemGroup>
<Reference Include="BepInEx">
<HintPath>..\lib\BepInEx.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="System" />
<Reference Include="UnityEngine">
<HintPath>..\lib\UnityEngine.dll</HintPath>
<Private>False</Private>
</Reference>
<PackageReference Include="BepInEx.BaseLib" Version="5.3.0" IncludeAssets="compile" />
<PackageReference Include="UnityEngine.Core" Version="5.6.0" IncludeAssets="compile" />
</ItemGroup>
<ItemGroup>
<Compile Include="IllusionInjector\Bootstrapper.cs" />
<Compile Include="IllusionInjector\CompositePlugin.cs" />
<Compile Include="IllusionInjector\ConsoleWindow.cs" />
<Compile Include="IllusionInjector\Injector.cs" />
<Compile Include="IllusionInjector\PluginComponent.cs" />
<Compile Include="IllusionInjector\PluginManager.cs" />
<Compile Include="IllusionPlugin\IEnhancedPlugin.cs" />
<Compile Include="IllusionPlugin\IniFile.cs" />
<Compile Include="IllusionPlugin\IPlugin.cs" />
<Compile Include="IllusionPlugin\ModPrefs.cs" />
<Compile Include="IPALoader.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\Shared\Shared.projitems" Label="Shared" />
</Project>
+43 -23
View File
@@ -1,33 +1,53 @@
using System;
using System.Reflection;
using BepInEx.Configuration;
using BepInEx.Logging;
using IllusionInjector;
using System;
using System.IO;
using System.Reflection;
namespace BepInEx.IPALoader
{
[BepInPlugin("keelhauled.ipaloader", "IPALoader", "1.1.1")]
public class IPALoader : BaseUnityPlugin
{
internal new static ManualLogSource Logger;
[BepInPlugin(PluginName, PluginName, Metadata.PluginsVersion)]
public class IPALoader : BaseUnityPlugin
{
public const string PluginName = "BepInEx.IPALoader";
internal static new ManualLogSource Logger;
private readonly bool run = true;
private IPALoader()
{
Logger = base.Logger;
public static ConfigEntry<string> IPAPluginsPath { get; private set; }
public static ConfigFile CfgFile { get; } = new ConfigFile(Path.Combine(Paths.ConfigPath, Metadata.ConfigFileName), false);
// Redirect missing assembly requests to this assembly, since we have all the emulated code
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
if (args.Name == "IllusionPlugin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" ||
args.Name == "IllusionInjector, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")
return Assembly.GetExecutingAssembly();
private IPALoader()
{
IPAPluginsPath = CfgFile.Bind(Metadata.ConfigSection, Metadata.ConfigKey, Metadata.ConfigDefaultValue, Metadata.ConfigDescription);
Logger = base.Logger;
return null;
};
}
foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
var name = assembly.GetName().Name;
if (name == "IllusionInjector" || name == "IllusionPlugin")
{
Logger.LogWarning($"Detected that IPA is already installed! Please either uninstall IPA or disable this loader.");
run = false;
return;
}
}
private void Awake()
{
Injector.Inject();
}
}
// Redirect missing assembly requests to this assembly, since we have all the emulated code
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
var name = new AssemblyName(args.Name).Name;
if (name == "IllusionPlugin" || name == "IllusionInjector")
return Assembly.GetExecutingAssembly();
return null;
};
}
private void Awake()
{
if (run)
Injector.Inject();
}
}
}
@@ -1,107 +1,129 @@
using System;
using BepInEx;
using BepInEx.IPALoader;
using IllusionPlugin;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using BepInEx;
using BepInEx.IPALoader;
using IllusionPlugin;
namespace IllusionInjector
{
public static class PluginManager
{
private static List<IPlugin> _Plugins;
public static class PluginManager
{
private static List<IPlugin> _Plugins;
/// <summary>
/// Gets the list of loaded plugins and loads them if necessary.
/// </summary>
public static IEnumerable<IPlugin> Plugins
{
get
{
if (_Plugins == null)
LoadPlugins();
return _Plugins;
}
}
/// <summary>
/// Gets the list of loaded plugins and loads them if necessary.
/// </summary>
public static IEnumerable<IPlugin> Plugins
{
get
{
if (_Plugins == null)
LoadPlugins();
return _Plugins;
}
}
private static void LoadPlugins()
{
// Use the same Plugins folder path as in IPA for perfect emulation
string pluginDirectory = Path.Combine(Paths.GameRootPath, "Plugins");
private static void LoadPlugins()
{
string pluginDirectory = Path.Combine(Paths.GameRootPath, IPALoader.IPAPluginsPath.Value);
_Plugins = new List<IPlugin>();
_Plugins = new List<IPlugin>();
if (!Directory.Exists(pluginDirectory))
return;
if (!Directory.Exists(pluginDirectory))
return;
var files = Directory.GetFiles(pluginDirectory, "*.dll");
foreach (string s in files)
_Plugins.AddRange(LoadPluginsFromFile(Path.Combine(pluginDirectory, s), Paths.ProcessName));
var files = Directory.GetFiles(pluginDirectory, "*.dll");
foreach (string s in files)
_Plugins.AddRange(LoadPluginsFromFile(Path.Combine(pluginDirectory, s), Paths.ProcessName));
IPALoader.Logger.LogInfo(new string('-', 40));
IPALoader.Logger.LogInfo($"IPALoader found {_Plugins.Count} plugins in \"{pluginDirectory}\"");
foreach (var plugin in _Plugins)
IPALoader.Logger.LogInfo($"{plugin.Name}: {plugin.Version}");
IPALoader.Logger.LogInfo(new string('-', 40));
}
IPALoader.Logger.LogInfo(new string('-', 40));
IPALoader.Logger.LogInfo($"IPALoader found {_Plugins.Count} plugins in \"{pluginDirectory}\"");
foreach (var plugin in _Plugins)
IPALoader.Logger.LogInfo($"{plugin?.Name}: {plugin?.Version}");
IPALoader.Logger.LogInfo(new string('-', 40));
}
private static IEnumerable<IPlugin> LoadPluginsFromFile(string file, string exeName)
{
var plugins = new List<IPlugin>();
private static IEnumerable<IPlugin> LoadPluginsFromFile(string file, string exeName)
{
var plugins = new List<IPlugin>();
if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
return plugins;
if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
return plugins;
try
{
var assembly = Assembly.LoadFrom(file);
try
{
var assembly = Assembly.LoadFrom(file);
foreach (var t in assembly.GetTypes())
if (t.GetInterface("IPlugin") != null)
try
{
var pluginInstance = Activator.CreateInstance(t) as IPlugin;
string[] filter = null;
foreach (var t in GetTypesSafe(assembly))
if (typeof(IPlugin).IsAssignableFrom(t))
try
{
var pluginInstance = Activator.CreateInstance(t) as IPlugin;
if (pluginInstance is IEnhancedPlugin plugin)
filter = plugin.Filter;
if (pluginInstance == null)
{
IPALoader.Logger.LogWarning($"[WRN] Could not load {t.FullName} because types mismatch. Please check if you have multiple instances of IPA installed.");
continue;
}
if (filter == null || filter.Contains(exeName, StringComparer.OrdinalIgnoreCase))
plugins.Add(pluginInstance);
}
catch (Exception e)
{
IPALoader.Logger.LogWarning($"[WARN] Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {e}");
}
}
catch (Exception e)
{
IPALoader.Logger.LogError($"[ERROR] Could not load {Path.GetFileName(file)}! {e}");
}
string[] filter = null;
return plugins;
}
if (pluginInstance is IEnhancedPlugin plugin)
filter = plugin.Filter;
public class AppInfo
{
private static readonly HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
var exeNameTrimmed = exeName.ToLower().Replace(".exe", "").Trim();
if (filter == null || filter.Any(f => f.ToLower().Replace(".exe", "").Trim() == exeNameTrimmed))
plugins.Add(pluginInstance);
}
catch (Exception e)
{
IPALoader.Logger.LogWarning($"[WARN] Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {e}");
}
}
catch (Exception e)
{
IPALoader.Logger.LogError($"[ERROR] Could not load {Path.GetFileName(file)}! {e}");
}
public static string StartupPath
{
get
{
var stringBuilder = new StringBuilder(260);
GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
return stringBuilder.ToString();
}
}
return plugins;
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = false)]
private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
}
}
private static IEnumerable<Type> GetTypesSafe(Assembly assembly)
{
try
{
return assembly.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
IPALoader.Logger.LogWarning("Could not load some types from assembly " + assembly.FullName + " - check debug log for details");
foreach (var eLoaderException in e.LoaderExceptions)
IPALoader.Logger.LogDebug(eLoaderException);
return e.Types.Where(x => x != null);
}
}
public class AppInfo
{
private static readonly HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
public static string StartupPath
{
get
{
var stringBuilder = new StringBuilder(260);
GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
return stringBuilder.ToString();
}
}
[DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = false)]
private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
}
}
}
+3 -33
View File
@@ -1,35 +1,5 @@
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("IPALoader")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IPALoader")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("780f5e83-2a6b-4ea0-9476-449f5d96d56f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyTitle(BepInEx.IPALoader.IPALoader.PluginName)]
[assembly: AssemblyProduct(BepInEx.IPALoader.IPALoader.PluginName)]
[assembly: AssemblyDescription(BepInEx.IPALoader.IPALoader.PluginName)]
@@ -1,52 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{4E636178-ADD9-4306-BE77-357ADFB13AAB}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>BepInEx.IPAVirtualizer</RootNamespace>
<AssemblyName>BepInEx.IPAVirtualizer</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>false</DebugSymbols>
<TargetFramework>net35</TargetFramework>
<DebugType>none</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\bin\patchers\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>none</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\bin\patchers\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
</PropertyGroup>
<ItemGroup>
<Reference Include="BepInEx">
<HintPath>..\lib\BepInEx.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="Mono.Cecil, Version=0.10.3.0, Culture=neutral, PublicKeyToken=50cebf1cceb9d05e, processorArchitecture=MSIL">
<HintPath>..\packages\Mono.Cecil.0.10.3\lib\net35\Mono.Cecil.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="System" />
<PackageReference Include="BepInEx.BaseLib" Version="5.3.0" IncludeAssets="compile" />
<PackageReference Include="Mono.Cecil" Version="0.10.4" IncludeAssets="compile" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="IPAVirtualizer.cs" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\Shared\Shared.projitems" Label="Shared" />
</Project>
+58 -60
View File
@@ -1,75 +1,73 @@
using System.Collections.Generic;
using BepInEx.Logging;
using BepInEx.Logging;
using Mono.Cecil;
using System.Collections.Generic;
namespace BepInEx.IPAVirtualizer
{
public static class IPAVirtualizer
{
public static IEnumerable<string> TargetDLLs { get; } = new[]
{
"Assembly-CSharp.dll"
};
public static class IPAVirtualizer
{
public const string PluginName = "BepInEx.IPAVirtualizer";
public static IEnumerable<string> TargetDLLs { get; } = new[]
{
"Assembly-CSharp.dll"
};
private static ManualLogSource Logger;
private static ManualLogSource Logger;
public static void Patch(AssemblyDefinition ass)
{
Logger = Logging.Logger.CreateLogSource("IPAVirtualizer");
public static void Patch(AssemblyDefinition ass)
{
Logger = Logging.Logger.CreateLogSource("IPAVirtualizer");
try
{
foreach (var type in ass.MainModule.Types)
VirtualizeType(type);
}
finally
{
{
foreach (var type in ass.MainModule.Types)
VirtualizeType(type);
}
finally
{
Logging.Logger.Sources.Remove(Logger);
}
}
}
}
public static void VirtualizeType(TypeDefinition type)
{
if (type.IsSealed)
type.IsSealed = false;
public static void VirtualizeType(TypeDefinition type)
{
if (type.IsSealed)
type.IsSealed = false;
if (type.IsInterface)
return;
if (type.IsAbstract)
return;
if (type.IsInterface)
return;
if (type.IsAbstract)
return;
// These two don't seem to work.
if (type.Name == "SceneControl" || type.Name == "ConfigUI")
return;
// These two don't seem to work.
if (type.Name == "SceneControl" || type.Name == "ConfigUI")
return;
// Write to debug to not spam the console by default
Logger.LogDebug($"Virtualizing {type.Name}");
// Take care of sub types
foreach (var subType in type.NestedTypes)
VirtualizeType(subType);
// Take care of sub types
foreach (var subType in type.NestedTypes)
VirtualizeType(subType);
foreach (var method in type.Methods)
if (method.IsManaged
&& method.IsIL
&& !method.IsStatic
&& !method.IsVirtual
&& !method.IsAbstract
&& !method.IsAddOn
&& !method.IsConstructor
&& !method.IsSpecialName
&& !method.IsGenericInstance
&& !method.HasOverrides)
{
method.IsVirtual = true;
method.IsPublic = true;
method.IsPrivate = false;
method.IsNewSlot = true;
method.IsHideBySig = true;
}
foreach (var method in type.Methods)
if (method.IsManaged
&& method.IsIL
&& !method.IsStatic
&& !method.IsVirtual
&& !method.IsAbstract
&& !method.IsAddOn
&& !method.IsConstructor
&& !method.IsSpecialName
&& !method.IsGenericInstance
&& !method.HasOverrides)
{
method.IsVirtual = true;
method.IsPublic = true;
method.IsPrivate = false;
method.IsNewSlot = true;
method.IsHideBySig = true;
}
foreach (var field in type.Fields)
if (field.IsPrivate)
field.IsFamily = true;
}
}
foreach (var field in type.Fields)
if (field.IsPrivate)
field.IsFamily = true;
}
}
}
@@ -1,35 +1,5 @@
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("IPAVirtualizer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IPAVirtualizer")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4e636178-add9-4306-be77-357adfb13aab")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyTitle(BepInEx.IPAVirtualizer.IPAVirtualizer.PluginName)]
[assembly: AssemblyProduct(BepInEx.IPAVirtualizer.IPAVirtualizer.PluginName)]
[assembly: AssemblyDescription(BepInEx.IPAVirtualizer.IPAVirtualizer.PluginName)]
-5
View File
@@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Mono.Cecil" version="0.10.3" targetFramework="net35" />
</packages>
+3 -2
View File
@@ -9,6 +9,7 @@ This plugin is an improved version of the original [IPALoader](https://github.co
* Integration with BepInEx logger
* Parts of IPA rewritten for simplicity
* Allows virtualization via a preloader plugin
* Patches IPA plugins with Harmony ILMerged to use the BepInEx's Harmony
While IPALoaderX aims to emulate IPA as closely as possible, I can't guarantee absolutely every plugin will work.
If you suspect some plugin is not handled correctly by IPALoaderX, don't hesitate to make a new issue on this github page.
@@ -21,7 +22,7 @@ For example, this plugin allows for BepInEx to be used in Honey Select in order
## How to use
1. Install [BepInEx](https://github.com/BepInEx/BepInEx#readme) to your game (you may need to edit the BepInEx entrypoint for it to work).
2. Download the latest IPALoaderX release from [here](https://github.com/Keelhauled/IPALoaderX/releases).
3. Place IPALoaderX.dll in the `BepInEx` folder and IPAVirtualizer.dll in the `patchers` folder.
2. Download the latest IPALoaderX release from [here](https://github.com/BepInEx/IPALoaderX/releases).
3. Place BepInEx.IPALoader.dll in the `BepInEx\plugins` folder and BepInEx.IPAVirtualizer.dll and BepInEx.IPAHarmonyShimmer.dll in the `BepInEx\patchers` folder.
4. Make `Plugins` folder in your game folder (just like with original IPA).
5. Put IPA plugins into `Plugins` folder, just like with IPA.
+18
View File
@@ -0,0 +1,18 @@
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("https://github.com/BepInEx/IPALoaderX")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
#if DEBUG
[assembly: AssemblyConfiguration("DEBUG")]
#else
[assembly: AssemblyConfiguration("RELEASE")]
#endif
[assembly: ComVisible(false)]
[assembly: AssemblyVersion(BepInEx.IPALoader.Metadata.PluginsVersion)]
[assembly: AssemblyFileVersion(BepInEx.IPALoader.Metadata.PluginsVersion)]
+13
View File
@@ -0,0 +1,13 @@
namespace BepInEx.IPALoader
{
public static class Metadata
{
public const string PluginsVersion = "1.2.4";
internal const string ConfigFileName = "BepInEx.IPALoader.cfg";
internal const string ConfigSection = "Config";
internal const string ConfigKey = "Plugins Path";
internal const string ConfigDescription = "Folder from which to load IPA plugins relative to the game root directory";
internal const string ConfigDefaultValue = "Plugins";
}
}
+15
View File
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
<HasSharedItems>true</HasSharedItems>
<SharedGUID>840c3cf7-696a-4998-8bf1-9510d1c9a3e2</SharedGUID>
</PropertyGroup>
<PropertyGroup Label="Configuration">
<Import_RootNamespace>Shared</Import_RootNamespace>
</PropertyGroup>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)AssemblyInfo.cs" />
<Compile Include="$(MSBuildThisFileDirectory)Metadata.cs" />
</ItemGroup>
</Project>
+13
View File
@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Label="Globals">
<ProjectGuid>840c3cf7-696a-4998-8bf1-9510d1c9a3e2</ProjectGuid>
<MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
</PropertyGroup>
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.Default.props" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.Common.props" />
<PropertyGroup />
<Import Project="Shared.projitems" Label="Shared" />
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)\CodeSharing\Microsoft.CodeSharing.CSharp.targets" />
</Project>
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="BepInExLibs" value="https://pkgs.dev.azure.com/bepinex/BepInEx/_packaging/BepInExLibs/nuget/v3/index.json" />
</packageSources>
</configuration>