45 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
Keelhauled b1f0375149 Version up 2019-08-05 19:06:40 +03:00
Keelhauled baa20b2d0b Fix for bepinex logging change 2019-07-22 01:43:05 +03:00
Geoffrey Horsington 9bb4b58b73 Update README.md 2019-03-26 19:10:12 +02:00
ghorsington ccbc223282 Bump version 2019-03-18 20:51:54 +02:00
Geoffrey Horsington 1de484a6f9 Merge pull request #1 from BepInEx/feature-bepin5
Move codebase to BepInEx 5
2019-03-18 20:41:24 +02:00
ghorsington 987d117b5c Update README 2019-03-18 20:40:33 +02:00
ghorsington 49b093a384 Move build output to /bin 2019-03-18 20:25:33 +02:00
ghorsington 110349d9be Refactor some minor code 2019-03-18 19:58:46 +02:00
ghorsington 273a63b91f Fix virtualizer logger not getting disabled 2019-02-14 20:56:42 +02:00
ghorsington d427d9adbd Replace Trace in virtualizer with Logger to reduce console spam 2019-02-14 20:52:42 +02:00
ghorsington ba1d01864c Refactor common code 2019-02-14 20:52:07 +02:00
ghorsington 51eb0c7d80 Reformat all code according to BepInEx style 2019-02-14 20:34:23 +02:00
ghorsington f0450478de Rename all projects to match organization naming style 2019-02-14 20:30:52 +02:00
ghorsington b3d2af42aa Move codebase to BepInEx 5 2019-02-14 20:15:57 +02:00
Keelhauled 571fdc88f4 Create LICENSE 2019-01-27 23:54:01 +02:00
Keelhauled 72575c3b44 Remove useless code 2018-12-27 04:48:38 +02:00
Keelhauled d913ab2ba7 Why did I just not do this right away 2018-12-27 02:55:27 +02:00
Keelhauled a6c08eeb50 Fix error when 0 plugins and add IllusionInjector 2018-12-25 04:22:08 +02:00
59 changed files with 4560 additions and 716 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
@@ -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)]
+45
View File
@@ -0,0 +1,45 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29215.179
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BepInEx.IPALoader", "BepInEx.IPALoader\BepInEx.IPALoader.csproj", "{780F5E83-2A6B-4EA0-9476-449F5D96D56F}"
EndProject
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
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{780F5E83-2A6B-4EA0-9476-449F5D96D56F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{780F5E83-2A6B-4EA0-9476-449F5D96D56F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{780F5E83-2A6B-4EA0-9476-449F5D96D56F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{780F5E83-2A6B-4EA0-9476-449F5D96D56F}.Release|Any CPU.Build.0 = Release|Any CPU
{4E636178-ADD9-4306-BE77-357ADFB13AAB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{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
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {EA1E8267-32CE-4454-8AC6-B6CD0E592CDE}
EndGlobalSection
EndGlobal
+215
View File
@@ -0,0 +1,215 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/CodeEditing/Intellisense/CodeCompletion/IntelliSenseCompletingCharacters/CSharpCompletingCharacters/UpgradedFromVSSettings/@EntryValue">True</s:Boolean>
<s:String x:Key="/Default/CodeEditing/Intellisense/CodeCompletion/TabKeyInsertType/@EntryValue">Insert</s:String>
<s:String x:Key="/Default/CodeStyle/CodeCleanup/RecentlyUsedProfile/@EntryValue">Built-in: Reformat Code</s:String>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/ALIGN_MULTILINE_CALLS_CHAIN/@EntryValue">True</s:Boolean>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/ALIGNMENT_TAB_FILL_STYLE/@EntryValue">OPTIMAL_FILL</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/EMPTY_BLOCK_STYLE/@EntryValue">TOGETHER_SAME_LINE</s:String>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/INDENT_NESTED_FOR_STMT/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/INDENT_NESTED_FOREACH_STMT/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/INDENT_NESTED_WHILE_STMT/@EntryValue">True</s:Boolean>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/INDENT_STYLE/@EntryValue">Tab</s:String>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_EXISTING_EMBEDDED_ARRANGEMENT/@EntryValue">False</s:Boolean>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_ACCESSOR_ATTRIBUTE_ON_SAME_LINE_EX/@EntryValue">NEVER</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_ACCESSORHOLDER_ATTRIBUTE_ON_SAME_LINE_EX/@EntryValue">NEVER</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_FIELD_ATTRIBUTE_ON_SAME_LINE_EX/@EntryValue">NEVER</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_SIMPLE_EMBEDDED_STATEMENT_ON_SAME_LINE/@EntryValue">NEVER</s:String>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/SPACE_AFTER_TYPECAST_PARENTHESES/@EntryValue">False</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/SPACE_WITHIN_SINGLE_LINE_ARRAY_INITIALIZER_BRACES/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/USE_INDENT_FROM_VS/@EntryValue">False</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/WRAP_LINES/@EntryValue">False</s:Boolean>
<s:String x:Key="/Default/CodeStyle/CSharpFileLayoutPatterns/Pattern/@EntryValue">&lt;?xml version="1.0" encoding="utf-16"?&gt;&#xD;
&lt;Patterns xmlns="urn:schemas-jetbrains-com:member-reordering-patterns"&gt;&#xD;
&lt;TypePattern DisplayName="Non-reorderable types"&gt;&#xD;
&lt;TypePattern.Match&gt;&#xD;
&lt;Or&gt;&#xD;
&lt;And&gt;&#xD;
&lt;Kind Is="Interface" /&gt;&#xD;
&lt;Or&gt;&#xD;
&lt;HasAttribute Name="System.Runtime.InteropServices.InterfaceTypeAttribute" /&gt;&#xD;
&lt;HasAttribute Name="System.Runtime.InteropServices.ComImport" /&gt;&#xD;
&lt;/Or&gt;&#xD;
&lt;/And&gt;&#xD;
&lt;Kind Is="Struct" /&gt;&#xD;
&lt;HasAttribute Name="JetBrains.Annotations.NoReorderAttribute" /&gt;&#xD;
&lt;HasAttribute Name="JetBrains.Annotations.NoReorder" /&gt;&#xD;
&lt;/Or&gt;&#xD;
&lt;/TypePattern.Match&gt;&#xD;
&lt;/TypePattern&gt;&#xD;
&lt;TypePattern DisplayName="xUnit.net Test Classes" RemoveRegions="All"&gt;&#xD;
&lt;TypePattern.Match&gt;&#xD;
&lt;And&gt;&#xD;
&lt;Kind Is="Class" /&gt;&#xD;
&lt;HasMember&gt;&#xD;
&lt;And&gt;&#xD;
&lt;Kind Is="Method" /&gt;&#xD;
&lt;HasAttribute Name="Xunit.FactAttribute" Inherited="True" /&gt;&#xD;
&lt;/And&gt;&#xD;
&lt;/HasMember&gt;&#xD;
&lt;/And&gt;&#xD;
&lt;/TypePattern.Match&gt;&#xD;
&lt;Entry DisplayName="Setup/Teardown Methods"&gt;&#xD;
&lt;Entry.Match&gt;&#xD;
&lt;Or&gt;&#xD;
&lt;Kind Is="Constructor" /&gt;&#xD;
&lt;And&gt;&#xD;
&lt;Kind Is="Method" /&gt;&#xD;
&lt;ImplementsInterface Name="System.IDisposable" /&gt;&#xD;
&lt;/And&gt;&#xD;
&lt;/Or&gt;&#xD;
&lt;/Entry.Match&gt;&#xD;
&lt;Entry.SortBy&gt;&#xD;
&lt;Kind Order="Constructor" /&gt;&#xD;
&lt;/Entry.SortBy&gt;&#xD;
&lt;/Entry&gt;&#xD;
&lt;Entry DisplayName="All other members" /&gt;&#xD;
&lt;Entry Priority="100" DisplayName="Test Methods"&gt;&#xD;
&lt;Entry.Match&gt;&#xD;
&lt;And&gt;&#xD;
&lt;Kind Is="Method" /&gt;&#xD;
&lt;HasAttribute Name="Xunit.FactAttribute" /&gt;&#xD;
&lt;/And&gt;&#xD;
&lt;/Entry.Match&gt;&#xD;
&lt;Entry.SortBy&gt;&#xD;
&lt;Name /&gt;&#xD;
&lt;/Entry.SortBy&gt;&#xD;
&lt;/Entry&gt;&#xD;
&lt;/TypePattern&gt;&#xD;
&lt;TypePattern DisplayName="NUnit Test Fixtures" RemoveRegions="All"&gt;&#xD;
&lt;TypePattern.Match&gt;&#xD;
&lt;And&gt;&#xD;
&lt;Kind Is="Class" /&gt;&#xD;
&lt;HasAttribute Name="NUnit.Framework.TestFixtureAttribute" Inherited="True" /&gt;&#xD;
&lt;/And&gt;&#xD;
&lt;/TypePattern.Match&gt;&#xD;
&lt;Entry DisplayName="Setup/Teardown Methods"&gt;&#xD;
&lt;Entry.Match&gt;&#xD;
&lt;And&gt;&#xD;
&lt;Kind Is="Method" /&gt;&#xD;
&lt;Or&gt;&#xD;
&lt;HasAttribute Name="NUnit.Framework.SetUpAttribute" Inherited="True" /&gt;&#xD;
&lt;HasAttribute Name="NUnit.Framework.TearDownAttribute" Inherited="True" /&gt;&#xD;
&lt;HasAttribute Name="NUnit.Framework.FixtureSetUpAttribute" Inherited="True" /&gt;&#xD;
&lt;HasAttribute Name="NUnit.Framework.FixtureTearDownAttribute" Inherited="True" /&gt;&#xD;
&lt;/Or&gt;&#xD;
&lt;/And&gt;&#xD;
&lt;/Entry.Match&gt;&#xD;
&lt;/Entry&gt;&#xD;
&lt;Entry DisplayName="All other members" /&gt;&#xD;
&lt;Entry Priority="100" DisplayName="Test Methods"&gt;&#xD;
&lt;Entry.Match&gt;&#xD;
&lt;And&gt;&#xD;
&lt;Kind Is="Method" /&gt;&#xD;
&lt;HasAttribute Name="NUnit.Framework.TestAttribute" /&gt;&#xD;
&lt;/And&gt;&#xD;
&lt;/Entry.Match&gt;&#xD;
&lt;Entry.SortBy&gt;&#xD;
&lt;Name /&gt;&#xD;
&lt;/Entry.SortBy&gt;&#xD;
&lt;/Entry&gt;&#xD;
&lt;/TypePattern&gt;&#xD;
&lt;TypePattern DisplayName="Default Pattern"&gt;&#xD;
&lt;Entry DisplayName="Static Fields and Constants"&gt;&#xD;
&lt;Entry.Match&gt;&#xD;
&lt;Or&gt;&#xD;
&lt;Kind Is="Constant" /&gt;&#xD;
&lt;And&gt;&#xD;
&lt;Kind Is="Field" /&gt;&#xD;
&lt;Static /&gt;&#xD;
&lt;/And&gt;&#xD;
&lt;/Or&gt;&#xD;
&lt;/Entry.Match&gt;&#xD;
&lt;Entry.SortBy&gt;&#xD;
&lt;Kind Order="Constant Field" /&gt;&#xD;
&lt;/Entry.SortBy&gt;&#xD;
&lt;/Entry&gt;&#xD;
&lt;Entry DisplayName="Fields"&gt;&#xD;
&lt;Entry.Match&gt;&#xD;
&lt;And&gt;&#xD;
&lt;Kind Is="Field" /&gt;&#xD;
&lt;Not&gt;&#xD;
&lt;Static /&gt;&#xD;
&lt;/Not&gt;&#xD;
&lt;/And&gt;&#xD;
&lt;/Entry.Match&gt;&#xD;
&lt;Entry.SortBy&gt;&#xD;
&lt;Readonly /&gt;&#xD;
&lt;Name /&gt;&#xD;
&lt;/Entry.SortBy&gt;&#xD;
&lt;/Entry&gt;&#xD;
&lt;Entry Priority="100" DisplayName="Public Delegates"&gt;&#xD;
&lt;Entry.Match&gt;&#xD;
&lt;And&gt;&#xD;
&lt;Access Is="Public" /&gt;&#xD;
&lt;Kind Is="Delegate" /&gt;&#xD;
&lt;/And&gt;&#xD;
&lt;/Entry.Match&gt;&#xD;
&lt;Entry.SortBy&gt;&#xD;
&lt;Name /&gt;&#xD;
&lt;/Entry.SortBy&gt;&#xD;
&lt;/Entry&gt;&#xD;
&lt;Entry Priority="100" DisplayName="Public Enums"&gt;&#xD;
&lt;Entry.Match&gt;&#xD;
&lt;And&gt;&#xD;
&lt;Access Is="Public" /&gt;&#xD;
&lt;Kind Is="Enum" /&gt;&#xD;
&lt;/And&gt;&#xD;
&lt;/Entry.Match&gt;&#xD;
&lt;Entry.SortBy&gt;&#xD;
&lt;Name /&gt;&#xD;
&lt;/Entry.SortBy&gt;&#xD;
&lt;/Entry&gt;&#xD;
&lt;Entry DisplayName="Properties, Indexers"&gt;&#xD;
&lt;Entry.Match&gt;&#xD;
&lt;Or&gt;&#xD;
&lt;Kind Is="Property" /&gt;&#xD;
&lt;Kind Is="Indexer" /&gt;&#xD;
&lt;/Or&gt;&#xD;
&lt;/Entry.Match&gt;&#xD;
&lt;/Entry&gt;&#xD;
&lt;Entry DisplayName="Constructors"&gt;&#xD;
&lt;Entry.Match&gt;&#xD;
&lt;Kind Is="Constructor" /&gt;&#xD;
&lt;/Entry.Match&gt;&#xD;
&lt;Entry.SortBy&gt;&#xD;
&lt;Static /&gt;&#xD;
&lt;/Entry.SortBy&gt;&#xD;
&lt;/Entry&gt;&#xD;
&lt;Entry Priority="100" DisplayName="Interface Implementations"&gt;&#xD;
&lt;Entry.Match&gt;&#xD;
&lt;And&gt;&#xD;
&lt;Kind Is="Member" /&gt;&#xD;
&lt;ImplementsInterface /&gt;&#xD;
&lt;/And&gt;&#xD;
&lt;/Entry.Match&gt;&#xD;
&lt;Entry.SortBy&gt;&#xD;
&lt;ImplementsInterface Immediate="True" /&gt;&#xD;
&lt;/Entry.SortBy&gt;&#xD;
&lt;/Entry&gt;&#xD;
&lt;Entry DisplayName="All other members" /&gt;&#xD;
&lt;Entry DisplayName="Nested Types"&gt;&#xD;
&lt;Entry.Match&gt;&#xD;
&lt;Kind Is="Type" /&gt;&#xD;
&lt;/Entry.Match&gt;&#xD;
&lt;/Entry&gt;&#xD;
&lt;/TypePattern&gt;&#xD;
&lt;/Patterns&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/CSharpVarKeywordUsage/ForBuiltInTypes/@EntryValue">UseVarWhenEvident</s:String>
<s:Boolean x:Key="/Default/CodeStyle/EncapsulateField/MakeFieldPrivate/@EntryValue">False</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/EncapsulateField/UpdateExternalUsagesOnly/@EntryValue">False</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/Generate/=EqualityMembers/@KeyIndexDefined">True</s:Boolean>
<s:String x:Key="/Default/CodeStyle/Generate/=EqualityMembers/Options/=ChangeEquals/@EntryIndexedValue">Skip</s:String>
<s:String x:Key="/Default/CodeStyle/Generate/=EqualityMembers/Options/=EqualityOperators/@EntryIndexedValue">False</s:String>
<s:String x:Key="/Default/CodeStyle/Generate/=EqualityMembers/Options/=ImplementIEquatable/@EntryIndexedValue">False</s:String>
<s:Boolean x:Key="/Default/CodeStyle/Generate/=Implementations/@KeyIndexDefined">True</s:Boolean>
<s:String x:Key="/Default/CodeStyle/Generate/=Implementations/Options/=Async/@EntryIndexedValue">False</s:String>
<s:String x:Key="/Default/CodeStyle/Generate/=Implementations/Options/=Mutable/@EntryIndexedValue">False</s:String>
<s:Boolean x:Key="/Default/Environment/InjectedLayers/FileInjectedLayer/=2873BCACE542AE46A9AD6DC42B704221/@KeyIndexDefined">True</s:Boolean>
<s:String x:Key="/Default/Environment/InjectedLayers/FileInjectedLayer/=2873BCACE542AE46A9AD6DC42B704221/RelativePath/@EntryValue"></s:String>
<s:Boolean x:Key="/Default/Environment/InjectedLayers/InjectedLayerCustomization/=File2873BCACE542AE46A9AD6DC42B704221/@KeyIndexDefined">True</s:Boolean>
<s:Double x:Key="/Default/Environment/InjectedLayers/InjectedLayerCustomization/=File2873BCACE542AE46A9AD6DC42B704221/RelativePriority/@EntryValue">1</s:Double>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpKeepExistingMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpPlaceEmbeddedOnSameLineMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpUseContinuousIndentInsideBracesMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EAlwaysTreatStructAsNotReorderableMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateBlankLinesAroundFieldToBlankLinesAroundProperty/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net35</TargetFramework>
<DebugType>none</DebugType>
<OutputPath>..\bin\plugins\</OutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BepInEx.BaseLib" Version="5.3.0" IncludeAssets="compile" />
<PackageReference Include="UnityEngine.Core" Version="5.6.0" IncludeAssets="compile" />
</ItemGroup>
<Import Project="..\Shared\Shared.projitems" Label="Shared" />
</Project>
+53
View File
@@ -0,0 +1,53 @@
using BepInEx.Configuration;
using BepInEx.Logging;
using IllusionInjector;
using System;
using System.IO;
using System.Reflection;
namespace BepInEx.IPALoader
{
[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;
public static ConfigEntry<string> IPAPluginsPath { get; private set; }
public static ConfigFile CfgFile { get; } = new ConfigFile(Path.Combine(Paths.ConfigPath, Metadata.ConfigFileName), false);
private IPALoader()
{
IPAPluginsPath = CfgFile.Bind(Metadata.ConfigSection, Metadata.ConfigKey, Metadata.ConfigDefaultValue, Metadata.ConfigDescription);
Logger = base.Logger;
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;
}
}
// 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();
}
}
}
@@ -0,0 +1,20 @@
using System;
using UnityEngine;
namespace IllusionInjector
{
internal class Bootstrapper : MonoBehaviour
{
public event Action Destroyed = delegate { };
private void Start()
{
Destroy(gameObject);
}
private void OnDestroy()
{
Destroyed();
}
}
}
@@ -0,0 +1,91 @@
using System;
using System.Collections.Generic;
using BepInEx.IPALoader;
using IllusionPlugin;
namespace IllusionInjector
{
public class CompositePlugin : IPlugin
{
private readonly IEnumerable<IPlugin> plugins;
public CompositePlugin(IEnumerable<IPlugin> plugins)
{
this.plugins = plugins;
}
public void OnApplicationStart()
{
Invoke(plugin => plugin.OnApplicationStart());
}
public void OnApplicationQuit()
{
Invoke(plugin => plugin.OnApplicationQuit());
}
public void OnLevelWasLoaded(int level)
{
foreach (var plugin in plugins)
try
{
plugin.OnLevelWasLoaded(level);
}
catch (Exception ex)
{
IPALoader.Logger.LogError($"{plugin.Name} : {ex}");
}
}
public void OnLevelWasInitialized(int level)
{
foreach (var plugin in plugins)
try
{
plugin.OnLevelWasInitialized(level);
}
catch (Exception ex)
{
IPALoader.Logger.LogError($"{plugin.Name}: {ex}");
}
}
public void OnUpdate()
{
Invoke(plugin => plugin.OnUpdate());
}
public void OnFixedUpdate()
{
Invoke(plugin => plugin.OnFixedUpdate());
}
public string Name => throw new NotImplementedException();
public string Version => throw new NotImplementedException();
private void Invoke(CompositeCall callback)
{
foreach (var plugin in plugins)
try
{
callback(plugin);
}
catch (Exception ex)
{
IPALoader.Logger.LogError($"{plugin.Name}: {ex}");
}
}
public void OnLateUpdate()
{
Invoke(plugin =>
{
if (plugin is IEnhancedPlugin enhancedPlugin)
enhancedPlugin.OnLateUpdate();
});
}
private delegate void CompositeCall(IPlugin plugin);
}
}
@@ -0,0 +1,77 @@
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace Windows
{
internal class GuiConsole
{
private static bool hasConsole;
private static IntPtr conOut;
private static IntPtr oldOut;
public static void CreateConsole()
{
if (hasConsole)
return;
if (oldOut == IntPtr.Zero)
oldOut = GetStdHandle(-11);
if (!AllocConsole())
throw new Exception("AllocConsole() failed");
conOut = CreateFile("CONOUT$", 0x40000000, 2, IntPtr.Zero, 3, 0, IntPtr.Zero);
if (!SetStdHandle(-11, conOut))
throw new Exception("SetStdHandle() failed");
StreamToConsole();
hasConsole = true;
}
public static void ReleaseConsole()
{
if (!hasConsole)
return;
if (!CloseHandle(conOut))
throw new Exception("CloseHandle() failed");
conOut = IntPtr.Zero;
if (!FreeConsole())
throw new Exception("FreeConsole() failed");
if (!SetStdHandle(-11, oldOut))
throw new Exception("SetStdHandle() failed");
StreamToConsole();
hasConsole = false;
}
private static void StreamToConsole()
{
var cstm = Console.OpenStandardOutput();
var cstw = new StreamWriter(cstm, Encoding.Default) { AutoFlush = true };
Console.SetOut(cstw);
Console.SetError(cstw);
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool AllocConsole();
[DllImport("kernel32.dll", SetLastError = false)]
private static extern bool FreeConsole();
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool SetStdHandle(int nStdHandle, IntPtr hConsoleOutput);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern IntPtr CreateFile(
string fileName,
int desiredAccess,
int shareMode,
IntPtr securityAttributes,
int creationDisposition,
int flagsAndAttributes,
IntPtr templateFile);
[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true)]
private static extern bool CloseHandle(IntPtr handle);
}
}
@@ -0,0 +1,24 @@
using UnityEngine;
namespace IllusionInjector
{
public static class Injector
{
private static bool injected;
public static void Inject()
{
if (injected)
return;
injected = true;
var bootstrapper = new GameObject("Bootstrapper").AddComponent<Bootstrapper>();
bootstrapper.Destroyed += Bootstrapper_Destroyed;
}
private static void Bootstrapper_Destroyed()
{
PluginComponent.Create();
}
}
}
@@ -0,0 +1,69 @@
using UnityEngine;
namespace IllusionInjector
{
public class PluginComponent : MonoBehaviour
{
private bool freshlyLoaded;
private CompositePlugin plugins;
private bool quitting;
public static PluginComponent Create()
{
return new GameObject("IPA_PluginManager").AddComponent<PluginComponent>();
}
private void Awake()
{
DontDestroyOnLoad(gameObject);
plugins = new CompositePlugin(PluginManager.Plugins);
plugins.OnApplicationStart();
}
private void Start()
{
OnLevelWasLoaded(Application.loadedLevel);
}
private void Update()
{
if (freshlyLoaded)
{
freshlyLoaded = false;
plugins.OnLevelWasInitialized(Application.loadedLevel);
}
plugins.OnUpdate();
}
private void LateUpdate()
{
plugins.OnLateUpdate();
}
private void FixedUpdate()
{
plugins.OnFixedUpdate();
}
private void OnDestroy()
{
if (!quitting)
Create();
}
private void OnApplicationQuit()
{
plugins.OnApplicationQuit();
quitting = true;
}
private void OnLevelWasLoaded(int level)
{
plugins.OnLevelWasLoaded(level);
freshlyLoaded = true;
}
}
}
@@ -0,0 +1,129 @@
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;
namespace IllusionInjector
{
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;
}
}
private static void LoadPlugins()
{
string pluginDirectory = Path.Combine(Paths.GameRootPath, IPALoader.IPAPluginsPath.Value);
_Plugins = new List<IPlugin>();
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));
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>();
if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
return plugins;
try
{
var assembly = Assembly.LoadFrom(file);
foreach (var t in GetTypesSafe(assembly))
if (typeof(IPlugin).IsAssignableFrom(t))
try
{
var pluginInstance = Activator.CreateInstance(t) as IPlugin;
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;
}
string[] filter = null;
if (pluginInstance is IEnhancedPlugin plugin)
filter = plugin.Filter;
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}");
}
return plugins;
}
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);
}
}
}
@@ -0,0 +1,13 @@
namespace IllusionPlugin
{
public interface IEnhancedPlugin : IPlugin
{
/// <summary>
/// Gets a list of executables this plugin should be excuted on (without the file ending)
/// </summary>
/// <example>{ "PlayClub", "PlayClubStudio" }</example>
string[] Filter { get; }
void OnLateUpdate();
}
}
@@ -0,0 +1,53 @@
namespace IllusionPlugin
{
/// <summary>
/// Interface for generic Illusion unity plugins. Every class that implements this will be loaded if the DLL is placed
/// at
/// data/Managed/Plugins.
/// </summary>
public interface IPlugin
{
/// <summary>
/// Gets the name of the plugin.
/// </summary>
string Name { get; }
/// <summary>
/// Gets the version of the plugin.
/// </summary>
string Version { get; }
/// <summary>
/// Gets invoked when the application is started.
/// </summary>
void OnApplicationStart();
/// <summary>
/// Gets invoked when the application is closed.
/// </summary>
void OnApplicationQuit();
/// <summary>
/// Gets invoked whenever a level is loaded.
/// </summary>
/// <param name="level"></param>
void OnLevelWasLoaded(int level);
/// <summary>
/// Gets invoked after the first update cycle after a level was loaded.
/// </summary>
/// <param name="level"></param>
void OnLevelWasInitialized(int level);
/// <summary>
/// Gets invoked on every graphic update.
/// </summary>
void OnUpdate();
/// <summary>
/// Gets invoked on ever physics update.
/// </summary>
void OnFixedUpdate();
}
}
@@ -0,0 +1,85 @@
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
namespace IllusionPlugin
{
/// <summary>
/// Create a New INI file to store or load data
/// </summary>
internal class IniFile
{
private string _path = "";
public string Path
{
get => _path;
set
{
if (!File.Exists(value))
File.WriteAllText(value, "", Encoding.Unicode);
_path = value;
}
}
/// <summary>
/// INIFile Constructor.
/// </summary>
/// <PARAM name="INIPath"></PARAM>
public IniFile(string INIPath)
{
Path = INIPath;
}
[DllImport("KERNEL32.DLL", EntryPoint = "GetPrivateProfileStringW",
SetLastError = true,
CharSet = CharSet.Unicode, ExactSpelling = true,
CallingConvention = CallingConvention.StdCall)]
private static extern int GetPrivateProfileString(
string lpSection,
string lpKey,
string lpDefault,
StringBuilder lpReturnString,
int nSize,
string lpFileName);
[DllImport("KERNEL32.DLL", EntryPoint = "WritePrivateProfileStringW",
SetLastError = true,
CharSet = CharSet.Unicode, ExactSpelling = true,
CallingConvention = CallingConvention.StdCall)]
private static extern int WritePrivateProfileString(
string lpSection,
string lpKey,
string lpValue,
string lpFileName);
/// <summary>
/// Write Data to the INI File
/// </summary>
/// <PARAM name="Section"></PARAM>
/// Section name
/// <PARAM name="Key"></PARAM>
/// Key Name
/// <PARAM name="Value"></PARAM>
/// Value Name
public void IniWriteValue(string Section, string Key, string Value)
{
WritePrivateProfileString(Section, Key, Value, Path);
}
/// <summary>
/// Read Data Value From the Ini File
/// </summary>
/// <PARAM name="Section"></PARAM>
/// <PARAM name="Key"></PARAM>
/// <PARAM name="Path"></PARAM>
/// <returns></returns>
public string IniReadValue(string Section, string Key)
{
const int MAX_CHARS = 1023;
var result = new StringBuilder(MAX_CHARS);
GetPrivateProfileString(Section, Key, "", result, MAX_CHARS, Path);
return result.ToString();
}
}
}
@@ -0,0 +1,148 @@
using System;
using System.Globalization;
using System.IO;
namespace IllusionPlugin
{
/// <summary>
/// Allows to get and set preferences for your mod.
/// </summary>
public static class ModPrefs
{
private static IniFile _instance;
private static IniFile Instance => _instance ?? (_instance = new IniFile(Path.Combine(Environment.CurrentDirectory, "UserData/modprefs.ini")));
/// <summary>
/// Gets a string from the ini.
/// </summary>
/// <param name="section">Section of the key.</param>
/// <param name="name">Name of the key.</param>
/// <param name="defaultValue">Value that should be used when no value is found.</param>
/// <param name="autoSave">Whether or not the default value should be written if no value is found.</param>
/// <returns></returns>
public static string GetString(string section, string name, string defaultValue = "", bool autoSave = false)
{
string value = Instance.IniReadValue(section, name);
if (value != "")
return value;
if (autoSave)
SetString(section, name, defaultValue);
return defaultValue;
}
/// <summary>
/// Gets an int from the ini.
/// </summary>
/// <param name="section">Section of the key.</param>
/// <param name="name">Name of the key.</param>
/// <param name="defaultValue">Value that should be used when no value is found.</param>
/// <param name="autoSave">Whether or not the default value should be written if no value is found.</param>
/// <returns></returns>
public static int GetInt(string section, string name, int defaultValue = 0, bool autoSave = false)
{
if (int.TryParse(Instance.IniReadValue(section, name), out var value))
return value;
if (autoSave)
SetInt(section, name, defaultValue);
return defaultValue;
}
/// <summary>
/// Gets a float from the ini.
/// </summary>
/// <param name="section">Section of the key.</param>
/// <param name="name">Name of the key.</param>
/// <param name="defaultValue">Value that should be used when no value is found.</param>
/// <param name="autoSave">Whether or not the default value should be written if no value is found.</param>
/// <returns></returns>
public static float GetFloat(string section, string name, float defaultValue = 0f, bool autoSave = false)
{
if (float.TryParse(Instance.IniReadValue(section, name), out var value))
return value;
if (autoSave)
SetFloat(section, name, defaultValue);
return defaultValue;
}
/// <summary>
/// Gets a bool from the ini.
/// </summary>
/// <param name="section">Section of the key.</param>
/// <param name="name">Name of the key.</param>
/// <param name="defaultValue">Value that should be used when no value is found.</param>
/// <param name="autoSave">Whether or not the default value should be written if no value is found.</param>
/// <returns></returns>
public static bool GetBool(string section, string name, bool defaultValue = false, bool autoSave = false)
{
string sVal = GetString(section, name, null);
if (sVal == "1" || sVal == "0")
return sVal == "1";
if (autoSave)
SetBool(section, name, defaultValue);
return defaultValue;
}
/// <summary>
/// Checks whether or not a key exists in the ini.
/// </summary>
/// <param name="section">Section of the key.</param>
/// <param name="name">Name of the key.</param>
/// <returns></returns>
public static bool HasKey(string section, string name)
{
return Instance.IniReadValue(section, name) != null;
}
/// <summary>
/// Sets a float in the ini.
/// </summary>
/// <param name="section">Section of the key.</param>
/// <param name="name">Name of the key.</param>
/// <param name="value">Value that should be written.</param>
public static void SetFloat(string section, string name, float value)
{
Instance.IniWriteValue(section, name, value.ToString(CultureInfo.InvariantCulture));
}
/// <summary>
/// Sets an int in the ini.
/// </summary>
/// <param name="section">Section of the key.</param>
/// <param name="name">Name of the key.</param>
/// <param name="value">Value that should be written.</param>
public static void SetInt(string section, string name, int value)
{
Instance.IniWriteValue(section, name, value.ToString());
}
/// <summary>
/// Sets a string in the ini.
/// </summary>
/// <param name="section">Section of the key.</param>
/// <param name="name">Name of the key.</param>
/// <param name="value">Value that should be written.</param>
public static void SetString(string section, string name, string value)
{
Instance.IniWriteValue(section, name, value);
}
/// <summary>
/// Sets a bool in the ini.
/// </summary>
/// <param name="section">Section of the key.</param>
/// <param name="name">Name of the key.</param>
/// <param name="value">Value that should be written.</param>
public static void SetBool(string section, string name, bool value)
{
Instance.IniWriteValue(section, name, value ? "1" : "0");
}
}
}
@@ -0,0 +1,5 @@
using System.Reflection;
[assembly: AssemblyTitle(BepInEx.IPALoader.IPALoader.PluginName)]
[assembly: AssemblyProduct(BepInEx.IPALoader.IPALoader.PluginName)]
[assembly: AssemblyDescription(BepInEx.IPALoader.IPALoader.PluginName)]
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net35</TargetFramework>
<DebugType>none</DebugType>
<OutputPath>..\bin\patchers\</OutputPath>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BepInEx.BaseLib" Version="5.3.0" IncludeAssets="compile" />
<PackageReference Include="Mono.Cecil" Version="0.10.4" IncludeAssets="compile" />
</ItemGroup>
<Import Project="..\Shared\Shared.projitems" Label="Shared" />
</Project>
@@ -1,48 +1,53 @@
using System;
using System.Collections.Generic;
using BepInEx.Logging;
using Mono.Cecil;
using System.Collections.Generic;
namespace IPAVirtualizer
namespace BepInEx.IPAVirtualizer
{
public static class IPAVirtualizer
{
public static IEnumerable<string> TargetDLLs { get; } = new string[]
public const string PluginName = "BepInEx.IPAVirtualizer";
public static IEnumerable<string> TargetDLLs { get; } = new[]
{
"Assembly-CSharp.dll"
};
private static ManualLogSource Logger;
public static void Patch(AssemblyDefinition ass)
{
foreach(var type in ass.MainModule.Types)
Logger = Logging.Logger.CreateLogSource("IPAVirtualizer");
try
{
VirtualizeType(type);
foreach (var type in ass.MainModule.Types)
VirtualizeType(type);
}
finally
{
Logging.Logger.Sources.Remove(Logger);
}
}
public static void VirtualizeType(TypeDefinition type)
{
if(type.IsSealed)
{
// Unseal
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;
if (type.Name == "SceneControl" || type.Name == "ConfigUI")
return;
Console.WriteLine("Virtualizing {0}", type.Name);
// Take care of sub types
foreach(var subType in type.NestedTypes)
{
foreach (var subType in type.NestedTypes)
VirtualizeType(subType);
}
foreach(var method in type.Methods)
{
if(method.IsManaged
foreach (var method in type.Methods)
if (method.IsManaged
&& method.IsIL
&& !method.IsStatic
&& !method.IsVirtual
@@ -59,12 +64,10 @@ namespace IPAVirtualizer
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;
}
}
}
}
@@ -0,0 +1,5 @@
using System.Reflection;
[assembly: AssemblyTitle(BepInEx.IPAVirtualizer.IPAVirtualizer.PluginName)]
[assembly: AssemblyProduct(BepInEx.IPAVirtualizer.IPAVirtualizer.PluginName)]
[assembly: AssemblyDescription(BepInEx.IPAVirtualizer.IPAVirtualizer.PluginName)]
-31
View File
@@ -1,31 +0,0 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.28307.168
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IPALoaderX", "IPALoaderX\IPALoaderX.csproj", "{780F5E83-2A6B-4EA0-9476-449F5D96D56F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IPAVirtualizer", "IPAVirtualizer\IPAVirtualizer.csproj", "{4E636178-ADD9-4306-BE77-357ADFB13AAB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{780F5E83-2A6B-4EA0-9476-449F5D96D56F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{780F5E83-2A6B-4EA0-9476-449F5D96D56F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{780F5E83-2A6B-4EA0-9476-449F5D96D56F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{780F5E83-2A6B-4EA0-9476-449F5D96D56F}.Release|Any CPU.Build.0 = Release|Any CPU
{4E636178-ADD9-4306-BE77-357ADFB13AAB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{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
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {EA1E8267-32CE-4454-8AC6-B6CD0E592CDE}
EndGlobalSection
EndGlobal
-20
View File
@@ -1,20 +0,0 @@
using System;
using UnityEngine;
namespace IPALoaderX
{
class Bootstrapper : MonoBehaviour
{
public event Action Destroyed = delegate {};
void Start()
{
Destroy(gameObject);
}
void OnDestroy()
{
Destroyed();
}
}
}
-101
View File
@@ -1,101 +0,0 @@
using IllusionPlugin;
using System;
using System.Collections.Generic;
namespace IPALoaderX
{
public class CompositePlugin : IPlugin
{
IEnumerable<IPlugin> plugins;
delegate void CompositeCall(IPlugin plugin);
public CompositePlugin(IEnumerable<IPlugin> plugins)
{
this.plugins = plugins;
}
public void OnApplicationStart()
{
Invoke(plugin => plugin.OnApplicationStart());
}
public void OnApplicationQuit()
{
Invoke(plugin => plugin.OnApplicationQuit());
}
public void OnLevelWasLoaded(int level)
{
foreach (var plugin in plugins)
{
try
{
plugin.OnLevelWasLoaded(level);
}
catch (Exception ex)
{
Console.WriteLine("{0}: {1}", plugin.Name, ex);
}
}
}
void Invoke(CompositeCall callback)
{
foreach (var plugin in plugins)
{
try
{
callback(plugin);
}
catch (Exception ex)
{
Console.WriteLine("{0}: {1}", plugin.Name, ex);
}
}
}
public void OnLevelWasInitialized(int level)
{
foreach (var plugin in plugins)
{
try
{
plugin.OnLevelWasInitialized(level);
}
catch (Exception ex)
{
Console.WriteLine("{0}: {1}", plugin.Name, ex);
}
}
}
public void OnUpdate()
{
Invoke(plugin => plugin.OnUpdate());
}
public void OnFixedUpdate()
{
Invoke(plugin => plugin.OnFixedUpdate());
}
public string Name
{
get { throw new NotImplementedException(); }
}
public string Version
{
get { throw new NotImplementedException(); }
}
public void OnLateUpdate()
{
Invoke(plugin =>
{
if (plugin is IEnhancedPlugin)
((IEnhancedPlugin)plugin).OnLateUpdate();
});
}
}
}
-67
View File
@@ -1,67 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<!-- -->
<!-- ILMerge project-specific settings. Almost never need to be set explicitly. -->
<!-- for details, see http://research.microsoft.com/en-us/people/mbarnett/ilmerge.aspx -->
<!-- -->
<!-- *** set this file to Type=None, CopyToOutput=Never *** -->
<!-- If True, all copy local dependencies will also be merged from referenced projects whether they are referenced in the current project explicitly or not -->
<ILMergeTransitive>false</ILMergeTransitive>
<!-- Extra ILMerge library paths (semicolon-separated). Dont put your package dependencies here, they will be added automagically -->
<ILMergeLibraryPath></ILMergeLibraryPath>
<!-- The solution NuGet package directory if not standard 'SOLUTION\packages' -->
<ILMergePackagesPath></ILMergePackagesPath>
<!-- The merge order file name if differs from standard 'ILMergeOrder.txt' -->
<ILMergeOrderFile></ILMergeOrderFile>
<!-- The strong key file name if not specified in the project -->
<ILMergeKeyFile></ILMergeKeyFile>
<!-- The assembly version if differs for the version of the main assembly -->
<ILMergeAssemblyVersion></ILMergeAssemblyVersion>
<!-- added in Version 1.0.4 -->
<ILMergeFileAlignment></ILMergeFileAlignment>
<!-- added in Version 1.0.4, default=none -->
<ILMergeAllowDuplicateType></ILMergeAllowDuplicateType>
<!-- If the <see cref="CopyAttributes"/> is also set, any assembly-level attributes names that have the same type are copied over into the target assembly -->
<ILMergeAllowMultipleAssemblyLevelAttributes></ILMergeAllowMultipleAssemblyLevelAttributes>
<!-- See ILMerge documentation -->
<ILMergeAllowZeroPeKind></ILMergeAllowZeroPeKind>
<!-- The assembly level attributes of each input assembly are copied over into the target assembly -->
<ILMergeCopyAttributes></ILMergeCopyAttributes>
<!-- Creates a .pdb file for the output assembly and merges into it any .pdb files found for input assemblies, default=true -->
<ILMergeDebugInfo>false</ILMergeDebugInfo>
<!-- Target assembly will be delay signed -->
<ILMergeDelaySign></ILMergeDelaySign>
<!-- Types in assemblies other than the primary assembly have their visibility modified -->
<ILMergeInternalize></ILMergeInternalize>
<!-- The path name of the file that will be used to identify types that are not to have their visibility modified -->
<ILMergeInternalizeExcludeFile></ILMergeInternalizeExcludeFile>
<!-- XML documentation files are merged to produce an XML documentation file for the target assembly -->
<ILMergeXmlDocumentation></ILMergeXmlDocumentation>
<!-- External assembly references in the manifest of the target assembly will use full public keys (false) or public key tokens (true, default value) -->
<ILMergePublicKeyTokens></ILMergePublicKeyTokens>
<!-- Types with the same name are all merged into a single type in the target assembly -->
<ILMergeUnionMerge></ILMergeUnionMerge>
<!-- The version of the target framework, default 40 (works for 45 too) -->
<ILTargetPlatform>20</ILTargetPlatform>
</PropertyGroup>
</Project>
-4
View File
@@ -1,4 +0,0 @@
# this file contains the partial list of the merged assemblies in the merge order
# you can fill it from the obj\CONFIG\PROJECT.ilmerge generated on every build
# and finetune merge order to your satisfaction
-34
View File
@@ -1,34 +0,0 @@
using System;
using System.Reflection;
using BepInEx;
using UnityEngine;
namespace IPALoaderX
{
[BepInPlugin("keelhauled.ipaloaderx", "IPALoaderX", "1.0.0")]
public class IPALoaderX : BaseUnityPlugin
{
IPALoaderX()
{
//only required for ILMerge
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
if(args.Name == "IllusionPlugin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")
return Assembly.GetExecutingAssembly();
return null;
};
}
void Awake()
{
var bootstrapper = new GameObject("Bootstrapper").AddComponent<Bootstrapper>();
bootstrapper.Destroyed += Bootstrapper_Destroyed;
}
static void Bootstrapper_Destroyed()
{
PluginComponent.Create();
}
}
}
-80
View File
@@ -1,80 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="..\packages\MSBuild.ILMerge.Task.1.0.5\build\MSBuild.ILMerge.Task.props" Condition="Exists('..\packages\MSBuild.ILMerge.Task.1.0.5\build\MSBuild.ILMerge.Task.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<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>IPALoaderX</RootNamespace>
<AssemblyName>IPALoaderX</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>false</DebugSymbols>
<DebugType>none</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\..\..\BepInEx\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Assembly-CSharp">
<HintPath>..\..\..\StudioNEO_64_Data\Managed\Assembly-CSharp.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="BepInEx">
<HintPath>..\..\..\BepInEx\core\BepInEx.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="IllusionPlugin">
<HintPath>..\..\IPA\IllusionInjector\bin\Debug\IllusionPlugin.dll</HintPath>
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Xml" />
<Reference Include="UnityEngine">
<HintPath>..\..\..\StudioNEO_64_Data\Managed\UnityEngine.dll</HintPath>
<Private>False</Private>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Bootstrapper.cs" />
<Compile Include="CompositePlugin.cs" />
<Compile Include="IPALoaderX.cs" />
<Compile Include="PluginComponent.cs" />
<Compile Include="PluginManager.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="ILMerge.props" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Content Include="ILMergeOrder.txt" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\MSBuild.ILMerge.Task.1.0.5\build\MSBuild.ILMerge.Task.props')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\MSBuild.ILMerge.Task.1.0.5\build\MSBuild.ILMerge.Task.props'))" />
<Error Condition="!Exists('..\packages\MSBuild.ILMerge.Task.1.0.5\build\MSBuild.ILMerge.Task.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\MSBuild.ILMerge.Task.1.0.5\build\MSBuild.ILMerge.Task.targets'))" />
</Target>
<Import Project="..\packages\MSBuild.ILMerge.Task.1.0.5\build\MSBuild.ILMerge.Task.targets" Condition="Exists('..\packages\MSBuild.ILMerge.Task.1.0.5\build\MSBuild.ILMerge.Task.targets')" />
</Project>
-69
View File
@@ -1,69 +0,0 @@
using UnityEngine;
using UnityEngine.SceneManagement;
namespace IPALoaderX
{
public class PluginComponent : MonoBehaviour
{
CompositePlugin plugins;
bool freshlyLoaded = false;
bool quitting = false;
public static void Create()
{
new GameObject("IPA_PluginManager").AddComponent<PluginComponent>();
}
void Awake()
{
DontDestroyOnLoad(gameObject);
plugins = new CompositePlugin(PluginManager.Plugins);
plugins.OnApplicationStart();
}
void Start()
{
OnLevelWasLoaded(SceneManager.GetActiveScene().buildIndex);
}
void Update()
{
if (freshlyLoaded)
{
freshlyLoaded = false;
plugins.OnLevelWasInitialized(SceneManager.GetActiveScene().buildIndex);
}
plugins.OnUpdate();
}
void LateUpdate()
{
plugins.OnLateUpdate();
}
void FixedUpdate()
{
plugins.OnFixedUpdate();
}
void OnDestroy()
{
if (!quitting)
Create();
}
void OnApplicationQuit()
{
plugins.OnApplicationQuit();
quitting = true;
}
void OnLevelWasLoaded(int level)
{
plugins.OnLevelWasLoaded(level);
freshlyLoaded = true;
}
}
}
-94
View File
@@ -1,94 +0,0 @@
using IllusionPlugin;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using BepInEx;
namespace IPALoaderX
{
public static class PluginManager
{
static List<IPlugin> _Plugins = null;
public static IEnumerable<IPlugin> Plugins
{
get
{
if(_Plugins == null)
LoadPlugins();
return _Plugins;
}
}
static void LoadPlugins()
{
string pluginDirectory = Path.Combine(Paths.GameRootPath, "Plugins");
if(!Directory.Exists(pluginDirectory))
return;
string exeName = Path.GetFileNameWithoutExtension(Paths.ExecutablePath);
_Plugins = new List<IPlugin>();
foreach(var s in Directory.GetFiles(pluginDirectory, "*.dll"))
{
_Plugins.AddRange(LoadPluginsFromFile(Path.Combine(pluginDirectory, s), exeName));
}
Console.WriteLine(new string('-', 40));
Console.WriteLine($"Loading plugins from {pluginDirectory} and found {_Plugins.Count}");
foreach (var plugin in _Plugins)
{
Console.WriteLine($" {plugin.Name}: {plugin.Version}");
}
Console.WriteLine(new string('-', 40));
}
static IEnumerable<IPlugin> LoadPluginsFromFile(string file, string exeName)
{
List<IPlugin> plugins = new List<IPlugin>();
if (!File.Exists(file) || !file.EndsWith(".dll", true, null))
return plugins;
try
{
Assembly assembly = Assembly.LoadFrom(file);
foreach(Type t in assembly.GetTypes())
{
if(t.GetInterface("IPlugin") != null)
{
try
{
IPlugin pluginInstance = Activator.CreateInstance(t) as IPlugin;
string[] filter = null;
if(pluginInstance is IEnhancedPlugin)
{
filter = ((IEnhancedPlugin)pluginInstance).Filter;
}
if(filter == null || Enumerable.Contains(filter, exeName, StringComparer.OrdinalIgnoreCase))
plugins.Add(pluginInstance);
}
catch(Exception ex)
{
Console.WriteLine($"[WARN] Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {ex}");
}
}
}
}
catch(Exception ex)
{
Console.WriteLine($"[ERROR] Could not load {Path.GetFileName(file)}! {ex}");
}
return plugins;
}
}
}
-36
View File
@@ -1,36 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
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("IPALoaderX")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("IPALoaderX")]
[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.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
-5
View File
@@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="ILMerge" version="2.13.0307" targetFramework="net35" />
<package id="MSBuild.ILMerge.Task" version="1.0.5" targetFramework="net35" />
</packages>
-45
View File
@@ -1,45 +0,0 @@
<?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')" />
<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>IPAVirtualizer</RootNamespace>
<AssemblyName>IPAVirtualizer</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>false</DebugSymbols>
<DebugType>none</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\..\..\BepInEx\patchers\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Mono.Cecil">
<HintPath>..\..\..\BepInEx\core\Mono.Cecil.dll</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="System" />
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="IPAVirtualizer.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
-36
View File
@@ -1,36 +0,0 @@
using System.Reflection;
using System.Runtime.CompilerServices;
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.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+19 -5
View File
@@ -1,14 +1,28 @@
# IPALoaderX
An improved version of the IPALoader from [BepisPlugins](https://github.com/bbepis/BepisPlugins#ipaloader). Most of the code was copied from the [IPA github page](https://github.com/Eusth/IPA).
IPALoaderX is a plugin for BepInEx that allows to load plugins made for [Illusion Plugin Architecture](https://github.com/Eusth/IPA) without installing it.
This plugin lets you load IPA plugins while using BepInEx and attempts to do that in the most accurate way possible to allow for every plugin to work without modification. I can't guarantee absolutely every plugin will work because testing that would be impossible for one person. So if you suspect some plugin is not handled correctly by IPALoaderX, don't hesitate to make a new issue on this github page.
This plugin is an improved version of the original [IPALoader](https://github.com/bbepis/BepisPlugins#ipaloader).
Using this you could potentially be able to move away from using IPA in any moddable Unity game and still benefit from the old plugins made for the game.
## Differences from IPALoader
* 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.
## Why IPA for BepInEx
Using this you could potentially be able to move away from using IPA in any moddable Unity game and still benefit from the old plugins made for the game.
For example, this plugin allows for BepInEx to be used in Honey Select in order to benefit from the many well established IPA plugins, useful new BepInEx plugins such as the [automatic translator](https://github.com/bbepis/XUnity.AutoTranslator#readme) and the [runtime unity editor](https://github.com/ManlyMarco/RuntimeUnityEditor#readme) and the patchless nature of BepInEx, all at the same time.
## 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>