void EmitCallParameter(MethodInfo patch, Dictionary <string, LocalBuilder> variables, bool allowFirsParamPassthrough) { var isInstance = original.IsStatic == false; var originalParameters = original.GetParameters(); var originalParameterNames = originalParameters.Select(p => p.Name).ToArray(); // check for passthrough using first parameter (which must have same type as return type) var parameters = patch.GetParameters().ToList(); if (allowFirsParamPassthrough && patch.ReturnType != typeof(void) && parameters.Count > 0 && parameters[0].ParameterType == patch.ReturnType) { parameters.RemoveRange(0, 1); } foreach (var patchParam in parameters) { if (patchParam.Name == ORIGINAL_METHOD_PARAM) { if (EmitOriginalBaseMethod()) { continue; } emitter.Emit(OpCodes.Ldnull); continue; } if (patchParam.Name == INSTANCE_PARAM) { if (original.IsStatic) { emitter.Emit(OpCodes.Ldnull); } else { var instanceIsRef = original.DeclaringType != null && AccessTools.IsStruct(original.DeclaringType); var parameterIsRef = patchParam.ParameterType.IsByRef; if (instanceIsRef == parameterIsRef) { emitter.Emit(OpCodes.Ldarg_0); } if (instanceIsRef && parameterIsRef == false) { emitter.Emit(OpCodes.Ldarg_0); emitter.Emit(OpCodes.Ldobj, original.DeclaringType); } if (instanceIsRef == false && parameterIsRef) { emitter.Emit(OpCodes.Ldarga, 0); } } continue; } if (patchParam.Name.StartsWith(INSTANCE_FIELD_PREFIX, StringComparison.Ordinal)) { var fieldName = patchParam.Name.Substring(INSTANCE_FIELD_PREFIX.Length); FieldInfo fieldInfo; if (fieldName.All(char.IsDigit)) { // field access by index only works for declared fields fieldInfo = AccessTools.DeclaredField(original.DeclaringType, int.Parse(fieldName)); if (fieldInfo == null) { throw new ArgumentException($"No field found at given index in class {original.DeclaringType.FullName}", fieldName); } } else { fieldInfo = AccessTools.Field(original.DeclaringType, fieldName); if (fieldInfo == null) { throw new ArgumentException($"No such field defined in class {original.DeclaringType.FullName}", fieldName); } } if (fieldInfo.IsStatic) { emitter.Emit(patchParam.ParameterType.IsByRef ? OpCodes.Ldsflda : OpCodes.Ldsfld, fieldInfo); } else { emitter.Emit(OpCodes.Ldarg_0); emitter.Emit(patchParam.ParameterType.IsByRef ? OpCodes.Ldflda : OpCodes.Ldfld, fieldInfo); } continue; } // state is special too since each patch has its own local var if (patchParam.Name == STATE_VAR) { var ldlocCode = patchParam.ParameterType.IsByRef ? OpCodes.Ldloca : OpCodes.Ldloc; if (variables.TryGetValue(patch.DeclaringType.FullName, out var stateVar)) { emitter.Emit(ldlocCode, stateVar); } else { emitter.Emit(OpCodes.Ldnull); } continue; } // treat __result var special if (patchParam.Name == RESULT_VAR) { var returnType = AccessTools.GetReturnedType(original); if (returnType == typeof(void)) { throw new Exception($"Cannot get result from void method {original.FullDescription()}"); } var resultType = patchParam.ParameterType; if (resultType.IsByRef) { resultType = resultType.GetElementType(); } if (resultType.IsAssignableFrom(returnType) == false) { throw new Exception($"Cannot assign method return type {returnType.FullName} to {RESULT_VAR} type {resultType.FullName} for method {original.FullDescription()}"); } var ldlocCode = patchParam.ParameterType.IsByRef ? OpCodes.Ldloca : OpCodes.Ldloc; emitter.Emit(ldlocCode, variables[RESULT_VAR]); continue; } // any other declared variables if (variables.TryGetValue(patchParam.Name, out var localBuilder)) { var ldlocCode = patchParam.ParameterType.IsByRef ? OpCodes.Ldloca : OpCodes.Ldloc; emitter.Emit(ldlocCode, localBuilder); continue; } int idx; if (patchParam.Name.StartsWith(PARAM_INDEX_PREFIX, StringComparison.Ordinal)) { var val = patchParam.Name.Substring(PARAM_INDEX_PREFIX.Length); if (!int.TryParse(val, out idx)) { throw new Exception($"Parameter {patchParam.Name} does not contain a valid index"); } if (idx < 0 || idx >= originalParameters.Length) { throw new Exception($"No parameter found at index {idx}"); } } else { idx = patch.GetArgumentIndex(originalParameterNames, patchParam); if (idx == -1) { throw new Exception($"Parameter \"{patchParam.Name}\" not found in method {original.FullDescription()}"); } } // original -> patch opcode // -------------------------------------- // 1 normal -> normal : LDARG // 2 normal -> ref/out : LDARGA // 3 ref/out -> normal : LDARG, LDIND_x // 4 ref/out -> ref/out : LDARG // var originalIsNormal = originalParameters[idx].IsOut == false && originalParameters[idx].ParameterType.IsByRef == false; var patchIsNormal = patchParam.IsOut == false && patchParam.ParameterType.IsByRef == false; var patchArgIndex = idx + (isInstance ? 1 : 0) + (useStructReturnBuffer ? 1 : 0); // Case 1 + 4 if (originalIsNormal == patchIsNormal) { emitter.Emit(OpCodes.Ldarg, patchArgIndex); continue; } // Case 2 if (originalIsNormal && patchIsNormal == false) { emitter.Emit(OpCodes.Ldarga, patchArgIndex); continue; } // Case 3 emitter.Emit(OpCodes.Ldarg, patchArgIndex); emitter.Emit(LoadIndOpCodeFor(originalParameters[idx].ParameterType)); } }
internal static DynamicMethodDefinition CreateDynamicMethod(MethodBase original, string suffix, bool debug) { if (original == null) { throw new ArgumentNullException(nameof(original)); } var useStructReturnBuffer = StructReturnBuffer.NeedsFix(original); var patchName = original.Name + suffix; patchName = patchName.Replace("<>", ""); var parameters = original.GetParameters(); var parameterTypes = new List <Type>(); parameterTypes.AddRange(parameters.Types()); if (useStructReturnBuffer) { parameterTypes.Insert(0, typeof(IntPtr)); } if (original.IsStatic == false) { if (AccessTools.IsStruct(original.DeclaringType)) { parameterTypes.Insert(0, original.DeclaringType.MakeByRefType()); } else { parameterTypes.Insert(0, original.DeclaringType); } } var returnType = useStructReturnBuffer ? typeof(void) : AccessTools.GetReturnedType(original); var method = new DynamicMethodDefinition( patchName, returnType, parameterTypes.ToArray() ) { OwnerType = original.DeclaringType }; var offset = (original.IsStatic ? 0 : 1) + (useStructReturnBuffer ? 1 : 0); if (useStructReturnBuffer) { method.Definition.Parameters[original.IsStatic ? 0 : 1].Name = "retbuf"; } if (!original.IsStatic) { method.Definition.Parameters[0].Name = "this"; } for (var i = 0; i < parameters.Length; i++) { var param = method.Definition.Parameters[i + offset]; param.Attributes = (Mono.Cecil.ParameterAttributes)parameters[i].Attributes; param.Name = parameters[i].Name; } if (debug) { var parameterStrings = parameterTypes.Select(p => p.FullDescription()).ToList(); if (parameterTypes.Count == method.Definition.Parameters.Count) { for (var i = 0; i < parameterTypes.Count; i++) { parameterStrings[i] += $" {method.Definition.Parameters[i].Name}"; } } FileLog.Log($"### Replacement: static {returnType.FullDescription()} {original.DeclaringType.FullName}::{patchName}({parameterStrings.Join()})"); } return(method); }
/// <summary> /// Get the member specified by the <paramref name="attribute"/>. Throws if the member was not found. /// </summary> /// <exception cref="ArgumentException">Thrown if the member described in the <paramref name="attribute"/> couldn't be found.</exception> /// <exception cref="ArgumentNullException"><paramref name="attribute"/> is <see langword="null"/></exception> internal static MethodBase GetOriginalMethod(HarmonyMethod attribute) { if (attribute == null) throw new ArgumentNullException(nameof(attribute)); string GetPatchName() { return attribute.method?.FullDescription() ?? "Unknown patch"; } MethodBase MakeFailure(string reason) { Logger.Log(Logger.LogChannel.Error, () => $"Failed to process patch {GetPatchName()} - {reason}"); return null; } if (attribute.declaringType == null) return MakeFailure("declaringType cannot be null"); switch (attribute.methodType) { case MethodType.Normal: { if (string.IsNullOrEmpty(attribute.methodName)) return MakeFailure("methodName can't be empty"); if (attribute.methodName == ".ctor") { Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - MethodType.Constructor should be used instead of setting methodName to .ctor"); goto case MethodType.Constructor; } if (attribute.methodName == ".cctor") { Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - MethodType.StaticConstructor should be used instead of setting methodName to .cctor"); goto case MethodType.StaticConstructor; } if (attribute.methodName.StartsWith("get_") || attribute.methodName.StartsWith("set_")) Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + " - MethodType.Getter and MethodType.Setter should be used instead adding get_ and set_ to property names"); var result = AccessTools.DeclaredMethod(attribute.declaringType, attribute.methodName, attribute.argumentTypes); if (result != null) return result; result = AccessTools.Method(attribute.declaringType, attribute.methodName, attribute.argumentTypes); if (result != null) { Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + $" - Could not find method {attribute.methodName} with {attribute.argumentTypes?.Length ?? 0} parameters in type {attribute.declaringType.FullDescription()}, but it was found in base class of this type {result.DeclaringType.FullDescription()}"); return result; } return MakeFailure($"Could not find method {attribute.methodName} with {attribute.argumentTypes.Description()} parameters in type {attribute.declaringType.FullDescription()}"); } case MethodType.Getter: { if (string.IsNullOrEmpty(attribute.methodName)) return MakeFailure("methodName can't be empty"); var result = AccessTools.DeclaredProperty(attribute.declaringType, attribute.methodName); if (result != null) { var getter = result.GetGetMethod(true); if (getter == null) return MakeFailure($"Property {attribute.methodName} does not have a Getter"); return getter; } result = AccessTools.Property(attribute.declaringType, attribute.methodName); if (result != null) { Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + $" - Could not find property {attribute.methodName} in type {attribute.declaringType.FullDescription()}, but it was found in base class of this type: {result.DeclaringType.FullDescription()}"); var getter = result.GetGetMethod(true); if (getter == null) return MakeFailure($"Property {attribute.methodName} does not have a Getter"); return getter; } return MakeFailure($"Could not find property {attribute.methodName} in type {attribute.declaringType.FullDescription()}"); } case MethodType.Setter: { if (string.IsNullOrEmpty(attribute.methodName)) return MakeFailure("methodName can't be empty"); var result = AccessTools.DeclaredProperty(attribute.declaringType, attribute.methodName); if (result != null) { var getter = result.GetSetMethod(true); if (getter == null) return MakeFailure($"Property {attribute.methodName} does not have a Setter"); return getter; } result = AccessTools.Property(attribute.declaringType, attribute.methodName); if (result != null) { Logger.LogText(Logger.LogChannel.Warn, GetPatchName() + $" - Could not find property {attribute.methodName} in type {attribute.declaringType.FullDescription()}, but it was found in base class of this type: {result.DeclaringType.FullDescription()}"); var getter = result.GetSetMethod(true); if (getter == null) return MakeFailure($"Property {attribute.methodName} does not have a Setter"); return getter; } return MakeFailure($"Could not find property {attribute.methodName} in type {attribute.declaringType.FullDescription()}"); } case MethodType.Constructor: { var constructor = AccessTools.DeclaredConstructor(attribute.declaringType, attribute.argumentTypes); if (constructor != null) return constructor; return MakeFailure($"Could not find constructor with {attribute.argumentTypes.Description()} parameters in type {attribute.declaringType.FullDescription()}"); } case MethodType.StaticConstructor: { var constructor = AccessTools.GetDeclaredConstructors(attribute.declaringType).FirstOrDefault(c => c.IsStatic); if (constructor != null) return constructor; return MakeFailure($"Could not find static constructor in type {attribute.declaringType.FullDescription()}"); } default: throw new ArgumentOutOfRangeException(nameof(attribute.methodType), attribute.methodType, "Unknown method type"); } }
/// <summary>Searches an assembly for Harmony annotations and uses them to create patches</summary> /// <param name="assembly">The assembly</param> /// public void PatchAll(Assembly assembly) { AccessTools.GetTypesFromAssembly(assembly).Do(type => CreateClassProcessor(type).Patch()); }
private void PrepareType() { var mainPrepareResult = RunMethod<HarmonyPrepare, bool>(true); if (mainPrepareResult == false) return; var originalMethodType = containerAttributes.methodType; // MethodType default is Normal if (containerAttributes.methodType == null) containerAttributes.methodType = MethodType.Normal; var reversePatchAttr = typeof(HarmonyReversePatch).FullName; var reversePatchMethods = container.GetMethods(AccessTools.all).Where(m => m.GetCustomAttributes(true).Any(a => a.GetType().FullName == reversePatchAttr)).ToList(); foreach (var reversePatchMethod in reversePatchMethods) { var attr = containerAttributes.Merge(new HarmonyMethod(reversePatchMethod)); var originalMethod = GetOriginalMethod(attr); var reversePatcher = instance.CreateReversePatcher(originalMethod, reversePatchMethod); reversePatcher.Patch(); } var customOriginals = RunMethod<HarmonyTargetMethods, IEnumerable<MethodBase>>(null); if (customOriginals != null) { originals.Clear(); originals.AddRange(customOriginals); } else { var isPatchAll = container.GetCustomAttributes(true).Any(a => a.GetType().FullName == typeof(HarmonyPatchAll).FullName); if (isPatchAll) { var type = containerAttributes.declaringType; originals.AddRange(AccessTools.GetDeclaredConstructors(type).Cast<MethodBase>()); originals.AddRange(AccessTools.GetDeclaredMethods(type).Cast<MethodBase>()); var props = AccessTools.GetDeclaredProperties(type); originals.AddRange(props.Select(prop => prop.GetGetMethod(true)).Where(method => method != null) .Cast<MethodBase>()); originals.AddRange(props.Select(prop => prop.GetSetMethod(true)).Where(method => method != null) .Cast<MethodBase>()); } else { var original = RunMethod<HarmonyTargetMethod, MethodBase>(null) ?? GetOriginalMethod(containerAttributes); 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); } } GetPatches(container, out var prefixMethod, out var postfixMethod, out var transpilerMethod, out var finalizerMethod); if (prefix != null) prefix.method = prefixMethod; if (postfix != null) postfix.method = postfixMethod; if (transpiler != null) transpiler.method = transpilerMethod; if (finalizer != null) finalizer.method = finalizerMethod; if (prefixMethod != null) { if (prefixMethod.IsStatic == false) throw new ArgumentException($"Patch method {prefixMethod.GetID()} must be static"); var prefixAttributes = HarmonyMethodExtensions.GetFromMethod(prefixMethod); containerAttributes.Merge(HarmonyMethod.Merge(prefixAttributes)).CopyTo(prefix); } if (postfixMethod != null) { if (postfixMethod.IsStatic == false) throw new ArgumentException($"Patch method {postfixMethod.GetID()} must be static"); var postfixAttributes = HarmonyMethodExtensions.GetFromMethod(postfixMethod); containerAttributes.Merge(HarmonyMethod.Merge(postfixAttributes)).CopyTo(postfix); } if (transpilerMethod != null) { if (transpilerMethod.IsStatic == false) throw new ArgumentException($"Patch method {transpilerMethod.GetID()} must be static"); var transpilerAttributes = HarmonyMethodExtensions.GetFromMethod(transpilerMethod); containerAttributes.Merge(HarmonyMethod.Merge(transpilerAttributes)).CopyTo(transpiler); } if (finalizerMethod != null) { if (finalizerMethod.IsStatic == false) throw new ArgumentException($"Patch method {finalizerMethod.GetID()} must be static"); var finalizerAttributes = HarmonyMethodExtensions.GetFromMethod(finalizerMethod); containerAttributes.Merge(HarmonyMethod.Merge(finalizerAttributes)).CopyTo(finalizer); } }