本文整理汇总了C#中Mono.Cecil.MethodDefinition类的典型用法代码示例。如果您正苦于以下问题:C# MethodDefinition类的具体用法?C# MethodDefinition怎么用?C# MethodDefinition使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
MethodDefinition类属于Mono.Cecil命名空间,在下文中一共展示了MethodDefinition类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SwapParameterTypes
private static void SwapParameterTypes(MethodDefinition method,
TypeDefinition targetDependency,
TypeReference interfaceType,
HashSet<MethodReference> modifiedMethods)
{
if (method.IsAbstract || !method.HasBody)
return;
bool modified = false;
var parameters = method.Parameters.Cast<ParameterDefinition>();
foreach (var parameter in parameters)
{
var parameterType = parameter.ParameterType;
if (parameterType != targetDependency)
continue;
parameter.ParameterType = interfaceType;
modified = true;
}
if (!modified)
return;
modifiedMethods.Add(method);
}
示例2: MemberIsCalled
private bool MemberIsCalled (TypeDefinition type, MethodDefinition method)
{
bool isCalled = false;
if (TypeIsInternal (type) && TypeIsPrivate (type) && MemberIsInternal (method))
isCalled = PrivateMemberIsCalled (type, method);
if (TypeIsInternal (type) && TypeIsPrivate (type) && MemberIsPrivate (method))
isCalled = PrivateMemberIsCalled (type, method);
if (TypeIsInternal (type) && !TypeIsPrivate (type) && MemberIsInternal (method))
isCalled = InternalMemberIsCalled (method);
if (TypeIsInternal (type) && !TypeIsPrivate (type) && MemberIsPrivate (method))
isCalled = PrivateMemberIsCalled (type, method);
if (!TypeIsInternal (type) && TypeIsPrivate (type) && MemberIsInternal (method))
isCalled = PrivateMemberIsCalled (type, method);
if (!TypeIsInternal (type) && TypeIsPrivate (type) && MemberIsPrivate (method))
isCalled = PrivateMemberIsCalled (type, method);
if (!TypeIsInternal (type) && !TypeIsPrivate (type) && MemberIsInternal (method))
isCalled = InternalMemberIsCalled (method);
if (!TypeIsInternal (type) && !TypeIsPrivate (type) && MemberIsPrivate (method))
isCalled = PrivateMemberIsCalled (type, method);
if (TypeIsInternal (type) && TypeIsPrivate (type) && !MemberIsInternal (method) && !MemberIsPrivate (method))
isCalled = PrivateMemberIsCalled (type, method);
if (TypeIsInternal (type) && !TypeIsPrivate (type) && !MemberIsInternal (method) && !MemberIsPrivate (method))
isCalled = InternalMemberIsCalled (method);
if (!TypeIsInternal (type) && TypeIsPrivate (type) && !MemberIsInternal (method) && !MemberIsPrivate (method))
isCalled = PrivateMemberIsCalled (type, method);
if (!TypeIsInternal (type) && !TypeIsPrivate (type) && !MemberIsInternal (method) && !MemberIsPrivate (method))
isCalled = true;
}
示例3: CreateDefaultCtor
/// <summary>
/// Create the Ctor
/// </summary>
private static void CreateDefaultCtor(ReachableContext reachableContext, TypeDefinition type)
{
var typeSystem = type.Module.TypeSystem;
var ctor = new MethodDefinition(".ctor", MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName, typeSystem.Void);
ctor.DeclaringType = type;
var body = new MethodBody(ctor);
body.InitLocals = true;
ctor.Body = body;
// Prepare code
var seq = new ILSequence();
seq.Emit(OpCodes.Nop);
seq.Emit(OpCodes.Ret);
// Append ret sequence
seq.AppendTo(body);
// Update offsets
body.ComputeOffsets();
// Add ctor
type.Methods.Add(ctor);
ctor.SetReachable(reachableContext);
}
示例4: CheckMethod
public RuleResult CheckMethod (MethodDefinition method)
{
// rule only applies to visible methods with parameters
// we also exclude all p/invokes since we have a rule for them not to be visible
if (method.IsPInvokeImpl || !method.HasParameters || !method.IsVisible ())
return RuleResult.DoesNotApply;
foreach (ParameterDefinition parameter in method.Parameters) {
string how = null;
if (parameter.IsOut) {
// out is permitted for the "bool Try* (...)" pattern
if ((method.ReturnType.FullName == "System.Boolean") &&
method.Name.StartsWith ("Try", StringComparison.Ordinal)) {
continue;
}
how = "out";
} else if (parameter.IsRef ()) {
how = "ref";
}
if (how != null) {
// goal is to keep the API as simple as possible so this is more severe for public than protected methods
Severity severity = method.IsPublic ? Severity.Medium : Severity.Low;
string msg = String.Format ("Parameter '{0}' passed by reference ({1}).", parameter.Name, how);
Runner.Report (parameter, severity, Confidence.Total, msg);
}
}
return Runner.CurrentRuleResult;
}
示例5: CreateMethodBody
HashSet<ILVariable> localVariablesToDefine = new HashSet<ILVariable>(); // local variables that are missing a definition
/// <summary>
/// Creates the body for the method definition.
/// </summary>
/// <param name="methodDef">Method definition to decompile.</param>
/// <param name="context">Decompilation context.</param>
/// <param name="parameters">Parameter declarations of the method being decompiled.
/// These are used to update the parameter names when the decompiler generates names for the parameters.</param>
/// <param name="localVariables">Local variables storage that will be filled/updated with the local variables.</param>
/// <returns>Block for the method body</returns>
public static BlockStatement CreateMethodBody(MethodDefinition methodDef,
DecompilerContext context,
IEnumerable<ParameterDeclaration> parameters = null,
ConcurrentDictionary<int, IEnumerable<ILVariable>> localVariables = null)
{
if (localVariables == null)
localVariables = new ConcurrentDictionary<int, IEnumerable<ILVariable>>();
MethodDefinition oldCurrentMethod = context.CurrentMethod;
Debug.Assert(oldCurrentMethod == null || oldCurrentMethod == methodDef);
context.CurrentMethod = methodDef;
try {
AstMethodBodyBuilder builder = new AstMethodBodyBuilder();
builder.methodDef = methodDef;
builder.context = context;
builder.typeSystem = methodDef.Module.TypeSystem;
if (Debugger.IsAttached) {
return builder.CreateMethodBody(parameters, localVariables);
} else {
try {
return builder.CreateMethodBody(parameters, localVariables);
} catch (OperationCanceledException) {
throw;
} catch (Exception ex) {
throw new ICSharpCode.Decompiler.DecompilerException(methodDef, ex);
}
}
} finally {
context.CurrentMethod = oldCurrentMethod;
}
}
示例6: AddDefaultConstructor
/// <summary>
/// Adds a default constructor to the target type.
/// </summary>
/// <param name="parentType">The base class that contains the default constructor that will be used for constructor chaining..</param>
/// <param name="targetType">The type that will contain the default constructor.</param>
/// <returns>The default constructor.</returns>
public static MethodDefinition AddDefaultConstructor(this TypeDefinition targetType, Type parentType)
{
var module = targetType.Module;
var voidType = module.Import(typeof(void));
var methodAttributes = MethodAttributes.Public | MethodAttributes.HideBySig
| MethodAttributes.SpecialName | MethodAttributes.RTSpecialName;
var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
var objectConstructor = parentType.GetConstructor(flags, null, new Type[0], null);
// Revert to the System.Object constructor
// if the parent type does not have a default constructor
if (objectConstructor == null)
objectConstructor = typeof(object).GetConstructor(new Type[0]);
var baseConstructor = module.Import(objectConstructor);
// Define the default constructor
var ctor = new MethodDefinition(".ctor", methodAttributes, voidType)
{
CallingConvention = MethodCallingConvention.StdCall,
ImplAttributes = (MethodImplAttributes.IL | MethodImplAttributes.Managed)
};
var IL = ctor.Body.CilWorker;
// Call the constructor for System.Object, and exit
IL.Emit(OpCodes.Ldarg_0);
IL.Emit(OpCodes.Call, baseConstructor);
IL.Emit(OpCodes.Ret);
targetType.Constructors.Add(ctor);
return ctor;
}
示例7: ILBlockTranslator
public ILBlockTranslator(AssemblyTranslator translator, DecompilerContext context, MethodReference methodReference, MethodDefinition methodDefinition, ILBlock ilb, IEnumerable<ILVariable> parameters, IEnumerable<ILVariable> allVariables)
{
Translator = translator;
Context = context;
ThisMethodReference = methodReference;
ThisMethod = methodDefinition;
Block = ilb;
SpecialIdentifiers = new JSIL.SpecialIdentifiers(TypeSystem);
if (methodReference.HasThis)
Variables.Add("this", JSThisParameter.New(methodReference.DeclaringType, methodReference));
foreach (var parameter in parameters) {
if ((parameter.Name == "this") && (parameter.OriginalParameter.Index == -1))
continue;
ParameterNames.Add(parameter.Name);
Variables.Add(parameter.Name, new JSParameter(parameter.Name, parameter.Type, methodReference));
}
foreach (var variable in allVariables) {
var v = JSVariable.New(variable, methodReference);
if (Variables.ContainsKey(v.Identifier)) {
v = new JSVariable(variable.OriginalVariable.Name, variable.Type, methodReference);
RenamedVariables[variable] = v;
Variables.Add(v.Identifier, v);
} else {
Variables.Add(v.Identifier, v);
}
}
}
示例8: AddStaticPrototypeCall
private static void AddStaticPrototypeCall(MethodDefinition method, FieldDefinition delegateField, FieldDefinition prototypeField)
{
Debug.Assert(prototypeField.IsStatic);
var firstOpcode = method.Body.Instructions.First();
var il = method.Body.GetILProcessor();
TypeDefinition delegateType = delegateField.FieldType.Resolve();
var invokeMethod = delegateType.Methods.Single(m => m.Name == "Invoke");
int allParamsCount = method.Parameters.Count + (method.IsStatic ? 0 : 1); //all params and maybe this
var instructions = new[]
{
il.Create(OpCodes.Ldsflda, prototypeField),
il.Create(OpCodes.Ldfld, delegateField),
il.Create(OpCodes.Brfalse, firstOpcode),
il.Create(OpCodes.Ldsflda, prototypeField),
il.Create(OpCodes.Ldfld, delegateField),
}.Concat(
Enumerable.Range(0, allParamsCount).Select(i => il.Create(OpCodes.Ldarg, i))
).Concat(new[]
{
il.Create(OpCodes.Callvirt, invokeMethod),
il.Create(OpCodes.Ret),
});
foreach (var instruction in instructions)
il.InsertBefore(firstOpcode, instruction);
}
示例9: CopyMethod
/// <summary>
///
/// </summary>
/// <param name="yourMethod"></param>
/// <param name="targetName"></param>
/// <returns></returns>
private MethodDefinition CopyMethod(MethodDefinition yourMethod, string targetName)
{
var targetMethod = new MethodDefinition(targetName, yourMethod.Attributes,
yourMethod.ReturnType) {
ImplAttributes = yourMethod.ImplAttributes,
SemanticsAttributes = yourMethod.SemanticsAttributes,
CallingConvention = yourMethod.CallingConvention,
//all the Attributes and Conventions take care of most of the IsX/HasY properties, except for a few.
//this can be seen by looking at the Cecil code, where you can see which fields MethodDefinition has.
HasThis = yourMethod.HasThis,
ExplicitThis = yourMethod.ExplicitThis,
NoInlining = yourMethod.NoInlining,
NoOptimization = yourMethod.NoOptimization,
ReturnType = yourMethod.ReturnType //<---- this is temporary (setting it again to emphasize)
};
targetMethod.SecurityDeclarations.AddRange(yourMethod.SecurityDeclarations.Select(x => new SecurityDeclaration(x.Action, x.GetBlob())));
foreach (var yourTypeParam in yourMethod.GenericParameters) {
var targetTypeParam = new GenericParameter(yourTypeParam.Name, targetMethod) {
Attributes = yourTypeParam.Attributes //includes non-type constraints
};
targetMethod.GenericParameters.Add(targetTypeParam);
}
//we do this so we can perform collision detection later on.
foreach (var yourParam in yourMethod.Parameters) {
targetMethod.Parameters.Add(new ParameterDefinition(yourParam.ParameterType));
}
return targetMethod;
}
示例10: MethodMatch
public static bool MethodMatch(MethodDefinition candidate, MethodDefinition method)
{
if (!candidate.IsVirtual)
{
return false;
}
if (candidate.Name != method.Name)
{
return false;
}
if (!Helpers.TypeMatch(candidate.ReturnType, method.ReturnType))
{
return false;
}
if (candidate.Parameters.Count != method.Parameters.Count)
{
return false;
}
for (int i = 0; i < candidate.Parameters.Count; i++)
{
if (!Helpers.TypeMatch(candidate.Parameters[i].ParameterType, method.Parameters[i].ParameterType))
{
return false;
}
}
return true;
}
示例11: GetWeaver
public override IWeaver GetWeaver(MethodDefinition method, FieldDefinition mixin)
{
if (method.CustomAttributes.Any (a => a.AttributeType.FullName == Constants.AsyncStateMachineAttribute))
return GetAsyncMethodWeaver (method, mixin);
return new FakeWeaver ();
throw new NotImplementedException ();
}
示例12: CheckMethod
public RuleResult CheckMethod (MethodDefinition method)
{
if (!method.HasBody)
return RuleResult.DoesNotApply;
// check if the method contains a Isinst, Ldnull *and* Ceq instruction
if (!bitmask.IsSubsetOf (OpCodeEngine.GetBitmask (method)))
return RuleResult.DoesNotApply;
IList<Instruction> instructions = method.Body.Instructions;
int n = instructions.Count - 2;
for (int i = 0; i < n; i++) {
Code code0 = instructions [i].OpCode.Code;
if (code0 != Code.Isinst)
continue;
Code code1 = instructions [i + 1].OpCode.Code;
if (code1 != Code.Ldnull)
continue;
Code code2 = instructions [i + 2].OpCode.Code;
if (code2 != Code.Ceq)
continue;
Runner.Report (method, instructions[i], Severity.High, Confidence.High);
}
return Runner.CurrentRuleResult;
}
示例13: Build
public List<ILNode> Build(MethodDefinition methodDef)
{
this.methodDef = methodDef;
// Make editable copy
List<Instruction> body = new List<Instruction>(methodDef.Body.Instructions);
if (body.Count == 0) return new List<ILNode>();
StackAnalysis(body, methodDef);
// Create branch labels for instructins; use the labels as branch operands
foreach (Instruction inst in body) {
if (inst.Operand is Instruction[]) {
foreach(Instruction target in (Instruction[])inst.Operand) {
if (!labels.ContainsKey(target)) {
labels[target] = new ILLabel() { Name = "IL_" + target.Offset.ToString("X2") };
}
}
} else if (inst.Operand is Instruction) {
Instruction target = (Instruction)inst.Operand;
if (!labels.ContainsKey(target)) {
labels[target] = new ILLabel() { Name = "IL_" + target.Offset.ToString("X2") };
}
}
}
List<ILNode> ast = ConvertToAst(body, methodDef.Body.ExceptionHandlers);
return ast;
}
示例14: createMethod
public MethodDefinition createMethod(String sMethodName, MethodAttributes maMethodAttributes,
TypeReference trReturnType)
{
var newMethod = new MethodDefinition(sMethodName, maMethodAttributes, trReturnType);
newMethod.Body.CilWorker.Emit(OpCodes.Ret);
return newMethod;
}
示例15: CopyMethodData
private static void CopyMethodData(MethodDefinition templateMethod, MethodDefinition newMethod)
{
foreach (var parameterDefinition in templateMethod.Parameters)
{
newMethod.Parameters.Add(parameterDefinition);
}
if (templateMethod.HasBody)
{
newMethod.Body.InitLocals = true;
foreach (var variableDefinition in templateMethod.Body.Variables)
{
newMethod.Body.Variables.Add(variableDefinition);
}
foreach (ExceptionHandler exceptionHandler in templateMethod.Body.ExceptionHandlers)
{
newMethod.Body.ExceptionHandlers.Add(exceptionHandler);
}
foreach (var instruction in templateMethod.Body.Instructions)
{
newMethod.Body.Instructions.Add(instruction);
}
newMethod.Body.OptimizeMacros();
}
}