summaryrefslogtreecommitdiff
path: root/src/StardewModdingAPI/Framework
diff options
context:
space:
mode:
authorJesse Plamondon-Willard <github@jplamondonw.com>2016-12-12 11:52:34 -0500
committerJesse Plamondon-Willard <github@jplamondonw.com>2016-12-12 11:52:34 -0500
commit28e2695a19f7babf35d177367840a82b798beb55 (patch)
tree591b2badd77a7c9c0c36b8e09abdb6a323513307 /src/StardewModdingAPI/Framework
parentaaf354761f18a18b0bcb81c9bd32819bb28deac9 (diff)
parenta3376e2a6257c01c52a3c64c4f5f1f8de9a9c906 (diff)
downloadSMAPI-28e2695a19f7babf35d177367840a82b798beb55.tar.gz
SMAPI-28e2695a19f7babf35d177367840a82b798beb55.tar.bz2
SMAPI-28e2695a19f7babf35d177367840a82b798beb55.zip
Merge branch 'develop' into stable
Diffstat (limited to 'src/StardewModdingAPI/Framework')
-rw-r--r--src/StardewModdingAPI/Framework/AssemblyRewriting/AssemblyTypeRewriter.cs6
-rw-r--r--src/StardewModdingAPI/Framework/AssemblyRewriting/CacheEntry.cs46
-rw-r--r--src/StardewModdingAPI/Framework/AssemblyRewriting/CachePaths.cs10
-rw-r--r--src/StardewModdingAPI/Framework/AssemblyRewriting/RewriteResult.cs49
-rw-r--r--src/StardewModdingAPI/Framework/InternalExtensions.cs10
-rw-r--r--src/StardewModdingAPI/Framework/ModAssemblyLoader.cs120
-rw-r--r--src/StardewModdingAPI/Framework/Reflection/PrivateField.cs93
-rw-r--r--src/StardewModdingAPI/Framework/Reflection/PrivateMethod.cs99
-rw-r--r--src/StardewModdingAPI/Framework/Reflection/ReflectionHelper.cs239
9 files changed, 605 insertions, 67 deletions
diff --git a/src/StardewModdingAPI/Framework/AssemblyRewriting/AssemblyTypeRewriter.cs b/src/StardewModdingAPI/Framework/AssemblyRewriting/AssemblyTypeRewriter.cs
index 3459488e..9d4d6b11 100644
--- a/src/StardewModdingAPI/Framework/AssemblyRewriting/AssemblyTypeRewriter.cs
+++ b/src/StardewModdingAPI/Framework/AssemblyRewriting/AssemblyTypeRewriter.cs
@@ -54,7 +54,8 @@ namespace StardewModdingAPI.Framework.AssemblyRewriting
/// <summary>Rewrite the types referenced by an assembly.</summary>
/// <param name="assembly">The assembly to rewrite.</param>
- public void RewriteAssembly(AssemblyDefinition assembly)
+ /// <returns>Returns whether the assembly was modified.</returns>
+ public bool RewriteAssembly(AssemblyDefinition assembly)
{
ModuleDefinition module = assembly.Modules.Single(); // technically an assembly can have multiple modules, but none of the build tools (including MSBuild) support it; simplify by assuming one module
@@ -71,7 +72,7 @@ namespace StardewModdingAPI.Framework.AssemblyRewriting
}
}
if (!shouldRewrite)
- return;
+ return false;
// add target assembly references
foreach (AssemblyNameReference target in this.AssemblyMap.TargetReferences.Values)
@@ -117,6 +118,7 @@ namespace StardewModdingAPI.Framework.AssemblyRewriting
}
method.Body.OptimizeMacros();
}
+ return true;
}
diff --git a/src/StardewModdingAPI/Framework/AssemblyRewriting/CacheEntry.cs b/src/StardewModdingAPI/Framework/AssemblyRewriting/CacheEntry.cs
new file mode 100644
index 00000000..3dfbc78c
--- /dev/null
+++ b/src/StardewModdingAPI/Framework/AssemblyRewriting/CacheEntry.cs
@@ -0,0 +1,46 @@
+using System.IO;
+
+namespace StardewModdingAPI.Framework.AssemblyRewriting
+{
+ /// <summary>Represents cached metadata for a rewritten assembly.</summary>
+ internal class CacheEntry
+ {
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The MD5 hash for the original assembly.</summary>
+ public readonly string Hash;
+
+ /// <summary>The SMAPI version used to rewrite the assembly.</summary>
+ public readonly string ApiVersion;
+
+ /// <summary>Whether to use the cached assembly instead of the original assembly.</summary>
+ public readonly bool UseCachedAssembly;
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="hash">The MD5 hash for the original assembly.</param>
+ /// <param name="apiVersion">The SMAPI version used to rewrite the assembly.</param>
+ /// <param name="useCachedAssembly">Whether to use the cached assembly instead of the original assembly.</param>
+ public CacheEntry(string hash, string apiVersion, bool useCachedAssembly)
+ {
+ this.Hash = hash;
+ this.ApiVersion = apiVersion;
+ this.UseCachedAssembly = useCachedAssembly;
+ }
+
+ /// <summary>Get whether the cache entry is up-to-date for the given assembly hash.</summary>
+ /// <param name="paths">The paths for the cached assembly.</param>
+ /// <param name="hash">The MD5 hash of the original assembly.</param>
+ /// <param name="currentVersion">The current SMAPI version.</param>
+ public bool IsUpToDate(CachePaths paths, string hash, Version currentVersion)
+ {
+ return hash == this.Hash
+ && this.ApiVersion == currentVersion.ToString()
+ && (!this.UseCachedAssembly || File.Exists(paths.Assembly));
+ }
+ }
+} \ No newline at end of file
diff --git a/src/StardewModdingAPI/Framework/AssemblyRewriting/CachePaths.cs b/src/StardewModdingAPI/Framework/AssemblyRewriting/CachePaths.cs
index 17c4d188..18861873 100644
--- a/src/StardewModdingAPI/Framework/AssemblyRewriting/CachePaths.cs
+++ b/src/StardewModdingAPI/Framework/AssemblyRewriting/CachePaths.cs
@@ -12,8 +12,8 @@ namespace StardewModdingAPI.Framework.AssemblyRewriting
/// <summary>The file path of the assembly file.</summary>
public string Assembly { get; }
- /// <summary>The file path containing the MD5 hash for the assembly.</summary>
- public string Hash { get; }
+ /// <summary>The file path containing the assembly metadata.</summary>
+ public string Metadata { get; }
/*********
@@ -22,12 +22,12 @@ namespace StardewModdingAPI.Framework.AssemblyRewriting
/// <summary>Construct an instance.</summary>
/// <param name="directory">The directory path which contains the assembly.</param>
/// <param name="assembly">The file path of the assembly file.</param>
- /// <param name="hash">The file path containing the MD5 hash for the assembly.</param>
- public CachePaths(string directory, string assembly, string hash)
+ /// <param name="metadata">The file path containing the assembly metadata.</param>
+ public CachePaths(string directory, string assembly, string metadata)
{
this.Directory = directory;
this.Assembly = assembly;
- this.Hash = hash;
+ this.Metadata = metadata;
}
}
} \ No newline at end of file
diff --git a/src/StardewModdingAPI/Framework/AssemblyRewriting/RewriteResult.cs b/src/StardewModdingAPI/Framework/AssemblyRewriting/RewriteResult.cs
new file mode 100644
index 00000000..8f34bb20
--- /dev/null
+++ b/src/StardewModdingAPI/Framework/AssemblyRewriting/RewriteResult.cs
@@ -0,0 +1,49 @@
+namespace StardewModdingAPI.Framework.AssemblyRewriting
+{
+ /// <summary>Metadata about a preprocessed assembly.</summary>
+ internal class RewriteResult
+ {
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The original assembly path.</summary>
+ public readonly string OriginalAssemblyPath;
+
+ /// <summary>The cache paths.</summary>
+ public readonly CachePaths CachePaths;
+
+ /// <summary>The rewritten assembly bytes.</summary>
+ public readonly byte[] AssemblyBytes;
+
+ /// <summary>The MD5 hash for the original assembly.</summary>
+ public readonly string Hash;
+
+ /// <summary>Whether to use the cached assembly instead of the original assembly.</summary>
+ public readonly bool UseCachedAssembly;
+
+ /// <summary>Whether this data is newer than the cache.</summary>
+ public readonly bool IsNewerThanCache;
+
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="originalAssemblyPath"></param>
+ /// <param name="cachePaths">The cache paths.</param>
+ /// <param name="assemblyBytes">The rewritten assembly bytes.</param>
+ /// <param name="hash">The MD5 hash for the original assembly.</param>
+ /// <param name="useCachedAssembly">Whether to use the cached assembly instead of the original assembly.</param>
+ /// <param name="isNewerThanCache">Whether this data is newer than the cache.</param>
+ public RewriteResult(string originalAssemblyPath, CachePaths cachePaths, byte[] assemblyBytes, string hash, bool useCachedAssembly, bool isNewerThanCache)
+ {
+ this.OriginalAssemblyPath = originalAssemblyPath;
+ this.CachePaths = cachePaths;
+ this.Hash = hash;
+ this.AssemblyBytes = assemblyBytes;
+ this.UseCachedAssembly = useCachedAssembly;
+ this.IsNewerThanCache = isNewerThanCache;
+ }
+ }
+}
diff --git a/src/StardewModdingAPI/Framework/InternalExtensions.cs b/src/StardewModdingAPI/Framework/InternalExtensions.cs
index 71f70fd5..415785d9 100644
--- a/src/StardewModdingAPI/Framework/InternalExtensions.cs
+++ b/src/StardewModdingAPI/Framework/InternalExtensions.cs
@@ -70,15 +70,21 @@ namespace StardewModdingAPI.Framework
/// <param name="exception">The error to summarise.</param>
public static string GetLogSummary(this Exception exception)
{
- string summary = exception.ToString();
+ // type load exception
+ if (exception is TypeLoadException)
+ return $"Failed loading type: {((TypeLoadException)exception).TypeName}: {exception}";
+ // reflection type load exception
if (exception is ReflectionTypeLoadException)
{
+ string summary = exception.ToString();
foreach (Exception childEx in ((ReflectionTypeLoadException)exception).LoaderExceptions)
summary += $"\n\n{childEx.GetLogSummary()}";
+ return summary;
}
- return summary;
+ // anything else
+ return exception.ToString();
}
}
}
diff --git a/src/StardewModdingAPI/Framework/ModAssemblyLoader.cs b/src/StardewModdingAPI/Framework/ModAssemblyLoader.cs
index 51018b0b..1ceb8ad2 100644
--- a/src/StardewModdingAPI/Framework/ModAssemblyLoader.cs
+++ b/src/StardewModdingAPI/Framework/ModAssemblyLoader.cs
@@ -1,9 +1,11 @@
using System;
+using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
using Mono.Cecil;
+using Newtonsoft.Json;
using StardewModdingAPI.AssemblyRewriters;
using StardewModdingAPI.Framework.AssemblyRewriting;
@@ -15,8 +17,8 @@ namespace StardewModdingAPI.Framework
/*********
** Properties
*********/
- /// <summary>The directory in which to cache data.</summary>
- private readonly string CacheDirPath;
+ /// <summary>The name of the directory containing a mod's cached data.</summary>
+ private readonly string CacheDirName;
/// <summary>Metadata for mapping assemblies to the current <see cref="Platform"/>.</summary>
private readonly PlatformAssemblyMap AssemblyMap;
@@ -32,74 +34,76 @@ namespace StardewModdingAPI.Framework
** Public methods
*********/
/// <summary>Construct an instance.</summary>
- /// <param name="cacheDirPath">The cache directory.</param>
+ /// <param name="cacheDirName">The name of the directory containing a mod's cached data.</param>
/// <param name="targetPlatform">The current game platform.</param>
/// <param name="monitor">Encapsulates monitoring and logging.</param>
- public ModAssemblyLoader(string cacheDirPath, Platform targetPlatform, IMonitor monitor)
+ public ModAssemblyLoader(string cacheDirName, Platform targetPlatform, IMonitor monitor)
{
- this.CacheDirPath = cacheDirPath;
+ this.CacheDirName = cacheDirName;
this.Monitor = monitor;
this.AssemblyMap = Constants.GetAssemblyMap(targetPlatform);
this.AssemblyTypeRewriter = new AssemblyTypeRewriter(this.AssemblyMap, monitor);
}
- /// <summary>Preprocess an assembly and cache the modified version.</summary>
+ /// <summary>Preprocess an assembly unless the cache is up to date.</summary>
/// <param name="assemblyPath">The assembly file path.</param>
- public void ProcessAssembly(string assemblyPath)
+ /// <returns>Returns the rewrite metadata for the preprocessed assembly.</returns>
+ public RewriteResult ProcessAssemblyUnlessCached(string assemblyPath)
{
// read assembly data
- string assemblyFileName = Path.GetFileName(assemblyPath);
- string assemblyDir = Path.GetDirectoryName(assemblyPath);
byte[] assemblyBytes = File.ReadAllBytes(assemblyPath);
- string hash = $"SMAPI {Constants.Version}|" + string.Join("", MD5.Create().ComputeHash(assemblyBytes).Select(p => p.ToString("X2")));
+ string hash = string.Join("", MD5.Create().ComputeHash(assemblyBytes).Select(p => p.ToString("X2")));
- // check cache
- CachePaths cachePaths = this.GetCacheInfo(assemblyPath);
- bool canUseCache = File.Exists(cachePaths.Assembly) && File.Exists(cachePaths.Hash) && hash == File.ReadAllText(cachePaths.Hash);
-
- // process assembly if not cached
- if (!canUseCache)
+ // get cached result if current
+ CachePaths cachePaths = this.GetCachePaths(assemblyPath);
+ {
+ CacheEntry cacheEntry = File.Exists(cachePaths.Metadata) ? JsonConvert.DeserializeObject<CacheEntry>(File.ReadAllText(cachePaths.Metadata)) : null;
+ if (cacheEntry != null && cacheEntry.IsUpToDate(cachePaths, hash, Constants.Version))
+ return new RewriteResult(assemblyPath, cachePaths, assemblyBytes, cacheEntry.Hash, cacheEntry.UseCachedAssembly, isNewerThanCache: false); // no rewrite needed
+ }
+ this.Monitor.Log($"Preprocessing {Path.GetFileName(assemblyPath)} for compatibility...", LogLevel.Trace);
+
+ // rewrite assembly
+ AssemblyDefinition assembly;
+ using (Stream readStream = new MemoryStream(assemblyBytes))
+ assembly = AssemblyDefinition.ReadAssembly(readStream);
+ bool modified = this.AssemblyTypeRewriter.RewriteAssembly(assembly);
+ using (MemoryStream outStream = new MemoryStream())
{
- this.Monitor.Log($"Loading {assemblyFileName} for the first time; preprocessing...", LogLevel.Trace);
-
- // read assembly definition
- AssemblyDefinition assembly;
- using (Stream readStream = new MemoryStream(assemblyBytes))
- assembly = AssemblyDefinition.ReadAssembly(readStream);
-
- // rewrite assembly to match platform
- this.AssemblyTypeRewriter.RewriteAssembly(assembly);
-
- // write cache
- using (MemoryStream outStream = new MemoryStream())
- {
- // get assembly bytes
- assembly.Write(outStream);
- byte[] outBytes = outStream.ToArray();
-
- // write assembly data
- Directory.CreateDirectory(cachePaths.Directory);
- File.WriteAllBytes(cachePaths.Assembly, outBytes);
- File.WriteAllText(cachePaths.Hash, hash);
-
- // copy any mdb/pdb files
- foreach (string path in Directory.GetFiles(assemblyDir, "*.mdb").Concat(Directory.GetFiles(assemblyDir, "*.pdb")))
- {
- string filename = Path.GetFileName(path);
- File.Copy(path, Path.Combine(cachePaths.Directory, filename), overwrite: true);
- }
- }
+ assembly.Write(outStream);
+ byte[] outBytes = outStream.ToArray();
+ return new RewriteResult(assemblyPath, cachePaths, outBytes, hash, useCachedAssembly: modified, isNewerThanCache: true);
}
}
- /// <summary>Load a preprocessed assembly.</summary>
- /// <param name="assemblyPath">The assembly file path.</param>
- public Assembly LoadCachedAssembly(string assemblyPath)
+ /// <summary>Write rewritten assembly metadata to the cache for a mod.</summary>
+ /// <param name="results">The rewrite results.</param>
+ /// <param name="forceCacheAssemblies">Whether to write all assemblies to the cache, even if they weren't modified.</param>
+ /// <exception cref="InvalidOperationException">There are no results to write, or the results are not all for the same directory.</exception>
+ public void WriteCache(IEnumerable<RewriteResult> results, bool forceCacheAssemblies)
{
- CachePaths cachePaths = this.GetCacheInfo(assemblyPath);
- if (!File.Exists(cachePaths.Assembly))
- throw new InvalidOperationException($"The assembly {assemblyPath} doesn't exist in the preprocessed cache.");
- return Assembly.UnsafeLoadFrom(cachePaths.Assembly); // unsafe load allows DLLs downloaded from the Internet without the user needing to 'unblock' them
+ results = results.ToArray();
+
+ // get cache directory
+ if (!results.Any())
+ throw new InvalidOperationException("There are no assemblies to cache.");
+ if (results.Select(p => p.CachePaths.Directory).Distinct().Count() > 1)
+ throw new InvalidOperationException("The assemblies can't be cached together because they have different source directories.");
+ string cacheDir = results.Select(p => p.CachePaths.Directory).First();
+
+ // reset cache
+ if (Directory.Exists(cacheDir))
+ Directory.Delete(cacheDir, recursive: true);
+ Directory.CreateDirectory(cacheDir);
+
+ // cache all results
+ foreach (RewriteResult result in results)
+ {
+ CacheEntry cacheEntry = new CacheEntry(result.Hash, Constants.Version.ToString(), forceCacheAssemblies || result.UseCachedAssembly);
+ File.WriteAllText(result.CachePaths.Metadata, JsonConvert.SerializeObject(cacheEntry));
+ if (forceCacheAssemblies || result.UseCachedAssembly)
+ File.WriteAllBytes(result.CachePaths.Assembly, result.AssemblyBytes);
+ }
}
/// <summary>Resolve an assembly from its name.</summary>
@@ -124,13 +128,13 @@ namespace StardewModdingAPI.Framework
*********/
/// <summary>Get the cache details for an assembly.</summary>
/// <param name="assemblyPath">The assembly file path.</param>
- private CachePaths GetCacheInfo(string assemblyPath)
+ private CachePaths GetCachePaths(string assemblyPath)
{
- string key = Path.GetFileNameWithoutExtension(assemblyPath);
- string dirPath = Path.Combine(this.CacheDirPath, new DirectoryInfo(Path.GetDirectoryName(assemblyPath)).Name);
- string cacheAssemblyPath = Path.Combine(dirPath, $"{key}.dll");
- string cacheHashPath = Path.Combine(dirPath, $"{key}.hash");
- return new CachePaths(dirPath, cacheAssemblyPath, cacheHashPath);
+ string fileName = Path.GetFileName(assemblyPath);
+ string dirPath = Path.Combine(Path.GetDirectoryName(assemblyPath), this.CacheDirName);
+ string cacheAssemblyPath = Path.Combine(dirPath, fileName);
+ string metadataPath = Path.Combine(dirPath, $"{fileName}.json");
+ return new CachePaths(dirPath, cacheAssemblyPath, metadataPath);
}
}
}
diff --git a/src/StardewModdingAPI/Framework/Reflection/PrivateField.cs b/src/StardewModdingAPI/Framework/Reflection/PrivateField.cs
new file mode 100644
index 00000000..0bf45969
--- /dev/null
+++ b/src/StardewModdingAPI/Framework/Reflection/PrivateField.cs
@@ -0,0 +1,93 @@
+using System;
+using System.Reflection;
+
+namespace StardewModdingAPI.Framework.Reflection
+{
+ /// <summary>A private field obtained through reflection.</summary>
+ /// <typeparam name="TValue">The field value type.</typeparam>
+ internal class PrivateField<TValue> : IPrivateField<TValue>
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>The type that has the field.</summary>
+ private readonly Type ParentType;
+
+ /// <summary>The object that has the instance field (if applicable).</summary>
+ private readonly object Parent;
+
+ /// <summary>The display name shown in error messages.</summary>
+ private string DisplayName => $"{this.ParentType.FullName}::{this.FieldInfo.Name}";
+
+
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The reflection metadata.</summary>
+ public FieldInfo FieldInfo { get; }
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="parentType">The type that has the field.</param>
+ /// <param name="obj">The object that has the instance field (if applicable).</param>
+ /// <param name="field">The reflection metadata.</param>
+ /// <param name="isStatic">Whether the field is static.</param>
+ /// <exception cref="ArgumentNullException">The <paramref name="parentType"/> or <paramref name="field"/> is null.</exception>
+ /// <exception cref="ArgumentException">The <paramref name="obj"/> is null for a non-static field, or not null for a static field.</exception>
+ public PrivateField(Type parentType, object obj, FieldInfo field, bool isStatic)
+ {
+ // validate
+ if (parentType == null)
+ throw new ArgumentNullException(nameof(parentType));
+ if (field == null)
+ throw new ArgumentNullException(nameof(field));
+ if (isStatic && obj != null)
+ throw new ArgumentException("A static field cannot have an object instance.");
+ if (!isStatic && obj == null)
+ throw new ArgumentException("A non-static field must have an object instance.");
+
+ // save
+ this.ParentType = parentType;
+ this.Parent = obj;
+ this.FieldInfo = field;
+ }
+
+ /// <summary>Get the field value.</summary>
+ public TValue GetValue()
+ {
+ try
+ {
+ return (TValue)this.FieldInfo.GetValue(this.Parent);
+ }
+ catch (InvalidCastException)
+ {
+ throw new InvalidCastException($"Can't convert the private {this.DisplayName} field from {this.FieldInfo.FieldType.FullName} to {typeof(TValue).FullName}.");
+ }
+ catch (Exception ex)
+ {
+ throw new Exception($"Couldn't get the value of the private {this.DisplayName} field", ex);
+ }
+ }
+
+ /// <summary>Set the field value.</summary>
+ //// <param name="value">The value to set.</param>
+ public void SetValue(TValue value)
+ {
+ try
+ {
+ this.FieldInfo.SetValue(this.Parent, value);
+ }
+ catch (InvalidCastException)
+ {
+ throw new InvalidCastException($"Can't assign the private {this.DisplayName} field a {typeof(TValue).FullName} value, must be compatible with {this.FieldInfo.FieldType.FullName}.");
+ }
+ catch (Exception ex)
+ {
+ throw new Exception($"Couldn't set the value of the private {this.DisplayName} field", ex);
+ }
+ }
+ }
+}
diff --git a/src/StardewModdingAPI/Framework/Reflection/PrivateMethod.cs b/src/StardewModdingAPI/Framework/Reflection/PrivateMethod.cs
new file mode 100644
index 00000000..ba2374f4
--- /dev/null
+++ b/src/StardewModdingAPI/Framework/Reflection/PrivateMethod.cs
@@ -0,0 +1,99 @@
+using System;
+using System.Reflection;
+
+namespace StardewModdingAPI.Framework.Reflection
+{
+ /// <summary>A private method obtained through reflection.</summary>
+ internal class PrivateMethod : IPrivateMethod
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>The type that has the method.</summary>
+ private readonly Type ParentType;
+
+ /// <summary>The object that has the instance method (if applicable).</summary>
+ private readonly object Parent;
+
+ /// <summary>The display name shown in error messages.</summary>
+ private string DisplayName => $"{this.ParentType.FullName}::{this.MethodInfo.Name}";
+
+
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>The reflection metadata.</summary>
+ public MethodInfo MethodInfo { get; }
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="parentType">The type that has the method.</param>
+ /// <param name="obj">The object that has the instance method(if applicable).</param>
+ /// <param name="method">The reflection metadata.</param>
+ /// <param name="isStatic">Whether the field is static.</param>
+ /// <exception cref="ArgumentNullException">The <paramref name="parentType"/> or <paramref name="method"/> is null.</exception>
+ /// <exception cref="ArgumentException">The <paramref name="obj"/> is null for a non-static method, or not null for a static method.</exception>
+ public PrivateMethod(Type parentType, object obj, MethodInfo method, bool isStatic)
+ {
+ // validate
+ if (parentType == null)
+ throw new ArgumentNullException(nameof(parentType));
+ if (method == null)
+ throw new ArgumentNullException(nameof(method));
+ if (isStatic && obj != null)
+ throw new ArgumentException("A static method cannot have an object instance.");
+ if (!isStatic && obj == null)
+ throw new ArgumentException("A non-static method must have an object instance.");
+
+ // save
+ this.ParentType = parentType;
+ this.Parent = obj;
+ this.MethodInfo = method;
+ }
+
+ /// <summary>Invoke the method.</summary>
+ /// <typeparam name="TValue">The return type.</typeparam>
+ /// <param name="arguments">The method arguments to pass in.</param>
+ public TValue Invoke<TValue>(params object[] arguments)
+ {
+ // invoke method
+ object result;
+ try
+ {
+ result = this.MethodInfo.Invoke(this.Parent, arguments);
+ }
+ catch (Exception ex)
+ {
+ throw new Exception($"Couldn't invoke the private {this.DisplayName} field", ex);
+ }
+
+ // cast return value
+ try
+ {
+ return (TValue)result;
+ }
+ catch (InvalidCastException)
+ {
+ throw new InvalidCastException($"Can't convert the return value of the private {this.DisplayName} method from {this.MethodInfo.ReturnType.FullName} to {typeof(TValue).FullName}.");
+ }
+ }
+
+ /// <summary>Invoke the method.</summary>
+ /// <param name="arguments">The method arguments to pass in.</param>
+ public void Invoke(params object[] arguments)
+ {
+ // invoke method
+ try
+ {
+ this.MethodInfo.Invoke(this.Parent, arguments);
+ }
+ catch (Exception ex)
+ {
+ throw new Exception($"Couldn't invoke the private {this.DisplayName} field", ex);
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/src/StardewModdingAPI/Framework/Reflection/ReflectionHelper.cs b/src/StardewModdingAPI/Framework/Reflection/ReflectionHelper.cs
new file mode 100644
index 00000000..38b4e357
--- /dev/null
+++ b/src/StardewModdingAPI/Framework/Reflection/ReflectionHelper.cs
@@ -0,0 +1,239 @@
+using System;
+using System.Linq;
+using System.Reflection;
+using System.Runtime.Caching;
+
+namespace StardewModdingAPI.Framework.Reflection
+{
+ /// <summary>Provides helper methods for accessing private game code.</summary>
+ /// <remarks>This implementation searches up the type hierarchy, and caches the reflected fields and methods with a sliding expiry (to optimise performance without unnecessary memory usage).</remarks>
+ internal class ReflectionHelper : IReflectionHelper
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>The cached fields and methods found via reflection.</summary>
+ private readonly MemoryCache Cache = new MemoryCache(typeof(ReflectionHelper).FullName);
+
+ /// <summary>The sliding cache expiration time.</summary>
+ private readonly TimeSpan SlidingCacheExpiry = TimeSpan.FromMinutes(5);
+
+
+ /*********
+ ** Public methods
+ *********/
+ /****
+ ** Fields
+ ****/
+ /// <summary>Get a private instance field.</summary>
+ /// <typeparam name="TValue">The field type.</typeparam>
+ /// <param name="obj">The object which has the field.</param>
+ /// <param name="name">The field name.</param>
+ /// <param name="required">Whether to throw an exception if the private field is not found.</param>
+ /// <returns>Returns the field wrapper, or <c>null</c> if the field doesn't exist and <paramref name="required"/> is <c>false</c>.</returns>
+ public IPrivateField<TValue> GetPrivateField<TValue>(object obj, string name, bool required = true)
+ {
+ // validate
+ if (obj == null)
+ throw new ArgumentNullException(nameof(obj), "Can't get a private instance field from a null object.");
+
+ // get field from hierarchy
+ IPrivateField<TValue> field = this.GetFieldFromHierarchy<TValue>(obj.GetType(), obj, name, BindingFlags.Instance | BindingFlags.NonPublic);
+ if (required && field == null)
+ throw new InvalidOperationException($"The {obj.GetType().FullName} object doesn't have a private '{name}' instance field.");
+ return field;
+ }
+
+ /// <summary>Get a private static field.</summary>
+ /// <typeparam name="TValue">The field type.</typeparam>
+ /// <param name="type">The type which has the field.</param>
+ /// <param name="name">The field name.</param>
+ /// <param name="required">Whether to throw an exception if the private field is not found.</param>
+ public IPrivateField<TValue> GetPrivateField<TValue>(Type type, string name, bool required = true)
+ {
+ // get field from hierarchy
+ IPrivateField<TValue> field = this.GetFieldFromHierarchy<TValue>(type, null, name, BindingFlags.NonPublic | BindingFlags.Static);
+ if (required && field == null)
+ throw new InvalidOperationException($"The {type.FullName} object doesn't have a private '{name}' static field.");
+ return field;
+ }
+
+ /****
+ ** Field values
+ ** (shorthand since this is the most common case)
+ ****/
+ /// <summary>Get the value of a private instance field.</summary>
+ /// <typeparam name="TValue">The field type.</typeparam>
+ /// <param name="obj">The object which has the field.</param>
+ /// <param name="name">The field name.</param>
+ /// <param name="required">Whether to throw an exception if the private field is not found.</param>
+ /// <remarks>This is a shortcut for <see cref="GetPrivateField{TValue}(object,string,bool)"/> followed by <see cref="IPrivateField{TValue}.GetValue"/>.</remarks>
+ public TValue GetPrivateValue<TValue>(object obj, string name, bool required = true)
+ {
+ return this.GetPrivateField<TValue>(obj, name, required).GetValue();
+ }
+
+ /// <summary>Get the value of a private static field.</summary>
+ /// <typeparam name="TValue">The field type.</typeparam>
+ /// <param name="type">The type which has the field.</param>
+ /// <param name="name">The field name.</param>
+ /// <param name="required">Whether to throw an exception if the private field is not found.</param>
+ /// <remarks>This is a shortcut for <see cref="GetPrivateField{TValue}(Type,string,bool)"/> followed by <see cref="IPrivateField{TValue}.GetValue"/>.</remarks>
+ public TValue GetPrivateValue<TValue>(Type type, string name, bool required = true)
+ {
+ return this.GetPrivateField<TValue>(type, name, required).GetValue();
+ }
+
+ /****
+ ** Methods
+ ****/
+ /// <summary>Get a private instance method.</summary>
+ /// <param name="obj">The object which has the method.</param>
+ /// <param name="name">The field name.</param>
+ /// <param name="required">Whether to throw an exception if the private field is not found.</param>
+ public IPrivateMethod GetPrivateMethod(object obj, string name, bool required = true)
+ {
+ // validate
+ if (obj == null)
+ throw new ArgumentNullException(nameof(obj), "Can't get a private instance method from a null object.");
+
+ // get method from hierarchy
+ IPrivateMethod method = this.GetMethodFromHierarchy(obj.GetType(), obj, name, BindingFlags.Instance | BindingFlags.NonPublic);
+ if (required && method == null)
+ throw new InvalidOperationException($"The {obj.GetType().FullName} object doesn't have a private '{name}' instance method.");
+ return method;
+ }
+
+ /// <summary>Get a private static method.</summary>
+ /// <param name="type">The type which has the method.</param>
+ /// <param name="name">The field name.</param>
+ /// <param name="required">Whether to throw an exception if the private field is not found.</param>
+ public IPrivateMethod GetPrivateMethod(Type type, string name, bool required = true)
+ {
+ // get method from hierarchy
+ IPrivateMethod method = this.GetMethodFromHierarchy(type, null, name, BindingFlags.NonPublic | BindingFlags.Static);
+ if (required && method == null)
+ throw new InvalidOperationException($"The {type.FullName} object doesn't have a private '{name}' static method.");
+ return method;
+ }
+
+ /****
+ ** Methods by signature
+ ****/
+ /// <summary>Get a private instance method.</summary>
+ /// <param name="obj">The object which has the method.</param>
+ /// <param name="name">The field name.</param>
+ /// <param name="argumentTypes">The argument types of the method signature to find.</param>
+ /// <param name="required">Whether to throw an exception if the private field is not found.</param>
+ public IPrivateMethod GetPrivateMethod(object obj, string name, Type[] argumentTypes, bool required = true)
+ {
+ // validate parent
+ if (obj == null)
+ throw new ArgumentNullException(nameof(obj), "Can't get a private instance method from a null object.");
+
+ // get method from hierarchy
+ PrivateMethod method = this.GetMethodFromHierarchy(obj.GetType(), obj, name, BindingFlags.Instance | BindingFlags.NonPublic, argumentTypes);
+ if (required && method == null)
+ throw new InvalidOperationException($"The {obj.GetType().FullName} object doesn't have a private '{name}' instance method with that signature.");
+ return method;
+ }
+
+ /// <summary>Get a private static method.</summary>
+ /// <param name="type">The type which has the method.</param>
+ /// <param name="name">The field name.</param>
+ /// <param name="argumentTypes">The argument types of the method signature to find.</param>
+ /// <param name="required">Whether to throw an exception if the private field is not found.</param>
+ public IPrivateMethod GetPrivateMethod(Type type, string name, Type[] argumentTypes, bool required = true)
+ {
+ // get field from hierarchy
+ PrivateMethod method = this.GetMethodFromHierarchy(type, null, name, BindingFlags.NonPublic | BindingFlags.Static, argumentTypes);
+ if (required && method == null)
+ throw new InvalidOperationException($"The {type.FullName} object doesn't have a private '{name}' static method with that signature.");
+ return method;
+ }
+
+
+ /*********
+ ** Private methods
+ *********/
+ /// <summary>Get a field from the type hierarchy.</summary>
+ /// <typeparam name="TValue">The expected field type.</typeparam>
+ /// <param name="type">The type which has the field.</param>
+ /// <param name="obj">The object which has the field.</param>
+ /// <param name="name">The field name.</param>
+ /// <param name="bindingFlags">The reflection binding which flags which indicates what type of field to find.</param>
+ private IPrivateField<TValue> GetFieldFromHierarchy<TValue>(Type type, object obj, string name, BindingFlags bindingFlags)
+ {
+ bool isStatic = bindingFlags.HasFlag(BindingFlags.Static);
+ FieldInfo field = this.GetCached<FieldInfo>($"field::{isStatic}::{type.FullName}::{name}", () =>
+ {
+ FieldInfo fieldInfo = null;
+ for (; type != null && fieldInfo == null; type = type.BaseType)
+ fieldInfo = type.GetField(name, bindingFlags);
+ return fieldInfo;
+ });
+
+ return field != null
+ ? new PrivateField<TValue>(type, obj, field, isStatic)
+ : null;
+ }
+
+ /// <summary>Get a method from the type hierarchy.</summary>
+ /// <param name="type">The type which has the method.</param>
+ /// <param name="obj">The object which has the method.</param>
+ /// <param name="name">The method name.</param>
+ /// <param name="bindingFlags">The reflection binding which flags which indicates what type of method to find.</param>
+ private IPrivateMethod GetMethodFromHierarchy(Type type, object obj, string name, BindingFlags bindingFlags)
+ {
+ bool isStatic = bindingFlags.HasFlag(BindingFlags.Static);
+ MethodInfo method = this.GetCached($"method::{isStatic}::{type.FullName}::{name}", () =>
+ {
+ MethodInfo methodInfo = null;
+ for (; type != null && methodInfo == null; type = type.BaseType)
+ methodInfo = type.GetMethod(name, bindingFlags);
+ return methodInfo;
+ });
+
+ return method != null
+ ? new PrivateMethod(type, obj, method, isStatic: bindingFlags.HasFlag(BindingFlags.Static))
+ : null;
+ }
+
+ /// <summary>Get a method from the type hierarchy.</summary>
+ /// <param name="type">The type which has the method.</param>
+ /// <param name="obj">The object which has the method.</param>
+ /// <param name="name">The method name.</param>
+ /// <param name="bindingFlags">The reflection binding which flags which indicates what type of method to find.</param>
+ /// <param name="argumentTypes">The argument types of the method signature to find.</param>
+ private PrivateMethod GetMethodFromHierarchy(Type type, object obj, string name, BindingFlags bindingFlags, Type[] argumentTypes)
+ {
+ bool isStatic = bindingFlags.HasFlag(BindingFlags.Static);
+ MethodInfo method = this.GetCached($"method::{isStatic}::{type.FullName}::{name}({string.Join(",", argumentTypes.Select(p => p.FullName))})", () =>
+ {
+ MethodInfo methodInfo = null;
+ for (; type != null && methodInfo == null; type = type.BaseType)
+ methodInfo = type.GetMethod(name, bindingFlags, null, argumentTypes, null);
+ return methodInfo;
+ });
+ return method != null
+ ? new PrivateMethod(type, obj, method, isStatic)
+ : null;
+ }
+
+ /// <summary>Get a method or field through the cache.</summary>
+ /// <typeparam name="TMemberInfo">The expected <see cref="MemberInfo"/> type.</typeparam>
+ /// <param name="key">The cache key.</param>
+ /// <param name="fetch">Fetches a new value to cache.</param>
+ private TMemberInfo GetCached<TMemberInfo>(string key, Func<TMemberInfo> fetch) where TMemberInfo : MemberInfo
+ {
+ // get from cache
+ if (this.Cache.Contains(key))
+ return (TMemberInfo)this.Cache[key];
+
+ // fetch & cache new value
+ TMemberInfo result = fetch();
+ this.Cache.Add(key, result, new CacheItemPolicy { SlidingExpiration = this.SlidingCacheExpiry });
+ return result;
+ }
+ }
+} \ No newline at end of file