internal FieldInfo GetFieldInfo(Type type, string name) { if (fields.TryGetValue(type, out var fieldsByType) == false) { fieldsByType = new Dictionary <string, FieldInfo>(); fields.Add(type, fieldsByType); } if (fieldsByType.TryGetValue(name, out var field) == false) { field = AccessTools.DeclaredField(type, name); fieldsByType.Add(name, field); } return(field); }
/// <summary>Creates an getter delegate for a field (with a list of possible field names)</summary> /// <typeparam name="T">Type that getter reads field/property from</typeparam> /// <typeparam name="S">Type of the field/property that gets accessed</typeparam> /// <param name="names">A list of possible field names</param> /// <returns>The new getter delegate</returns> /// public static GetterHandler <T, S> CreateFieldGetter <T, S>(params string[] names) { foreach (var name in names) { if (AccessTools.DeclaredField(typeof(T), name) != null) { return(CreateGetterHandler <T, S>(AccessTools.DeclaredField(typeof(T), name))); } if (AccessTools.Property(typeof(T), name) != null) { return(CreateGetterHandler <T, S>(AccessTools.Property(typeof(T), name))); } } return(null); }
void EmitCallParameter(MethodInfo patch, Dictionary <string, LocalBuilder> variables, bool allowFirsParamPassthrough, out LocalBuilder tmpObjectVar) { tmpObjectVar = null; var isInstance = original.IsStatic is 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 is object && AccessTools.IsStruct(original.DeclaringType); var parameterIsRef = patchParam.ParameterType.IsByRef; if (instanceIsRef == parameterIsRef) { emitter.Emit(OpCodes.Ldarg_0); } if (instanceIsRef && parameterIsRef is false) { emitter.Emit(OpCodes.Ldarg_0); emitter.Emit(OpCodes.Ldobj, original.DeclaringType); } if (instanceIsRef is 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 is 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 is 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 && returnType.IsByRef == false) { resultType = resultType.GetElementType(); } if (resultType.IsAssignableFrom(returnType) is 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 && returnType.IsByRef == false ? OpCodes.Ldloca : OpCodes.Ldloc; if (returnType.IsValueType && patchParam.ParameterType == typeof(object).MakeByRefType()) { ldlocCode = OpCodes.Ldloc; } emitter.Emit(ldlocCode, variables[RESULT_VAR]); if (returnType.IsValueType) { if (patchParam.ParameterType == typeof(object)) { emitter.Emit(OpCodes.Box, returnType); } else if (patchParam.ParameterType == typeof(object).MakeByRefType()) { emitter.Emit(OpCodes.Box, returnType); tmpObjectVar = il.DeclareLocal(typeof(object)); emitter.Emit(OpCodes.Stloc, tmpObjectVar); emitter.Emit(OpCodes.Ldloca, tmpObjectVar); } } continue; } // handle __args var special if (patchParam.Name == ARGS_VAR) { if (originalParameters.Length == 0) { emitter.Emit(OpCodes.Ldnull); continue; } int shift = (isInstance ? 1 : 0) + (useStructReturnBuffer ? 1 : 0); emitter.Emit(OpCodes.Ldc_I4, originalParameters.Length); emitter.Emit(OpCodes.Newarr, typeof(object)); for (int i = 0; i < originalParameters.Length; i++) { emitter.Emit(OpCodes.Dup); emitter.Emit(OpCodes.Ldc_I4, i); emitter.Emit(OpCodes.Ldarg, i + shift); if (originalParameters[i].ParameterType.IsValueType) { emitter.Emit(OpCodes.Box, originalParameters[i].ParameterType); } emitter.Emit(OpCodes.Stelem_Ref); } 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) { var harmonyMethod = HarmonyMethodExtensions.GetMergedFromType(patchParam.ParameterType); if (harmonyMethod.methodType is null) // MethodType default is Normal { harmonyMethod.methodType = MethodType.Normal; } var delegateOriginal = harmonyMethod.GetOriginalMethod(); if (delegateOriginal is MethodInfo methodInfo) { var delegateConstructor = patchParam.ParameterType.GetConstructor(new[] { typeof(object), typeof(IntPtr) }); if (delegateConstructor is object) { var originalType = original.DeclaringType; if (methodInfo.IsStatic) { emitter.Emit(OpCodes.Ldnull); } else { emitter.Emit(OpCodes.Ldarg_0); if (originalType.IsValueType) { emitter.Emit(OpCodes.Ldobj, originalType); emitter.Emit(OpCodes.Box, originalType); } } if (methodInfo.IsStatic is false && harmonyMethod.nonVirtualDelegate is false) { emitter.Emit(OpCodes.Dup); emitter.Emit(OpCodes.Ldvirtftn, methodInfo); } else { emitter.Emit(OpCodes.Ldftn, methodInfo); } emitter.Emit(OpCodes.Newobj, delegateConstructor); continue; } } 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 is false && originalParameters[idx].ParameterType.IsByRef is false; var patchIsNormal = patchParam.IsOut is false && patchParam.ParameterType.IsByRef is 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 is false) { emitter.Emit(OpCodes.Ldarga, patchArgIndex); continue; } // Case 3 emitter.Emit(OpCodes.Ldarg, patchArgIndex); emitter.Emit(LoadIndOpCodeFor(originalParameters[idx].ParameterType)); }
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)); } }