本文整理汇总了C#中ICSharpCode.Decompiler.DecompilerContext类的典型用法代码示例。如果您正苦于以下问题:C# DecompilerContext类的具体用法?C# DecompilerContext怎么用?C# DecompilerContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
DecompilerContext类属于ICSharpCode.Decompiler命名空间,在下文中一共展示了DecompilerContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetClass
public string GetClass(TypeIdentity identity)
{
// Before we attempt to fetch it just try a decompilation.
GetAssembly(identity.AssemblyPath);
ModuleDefinition moduleDef;
if (!this.loadedModules.TryGetValue(identity.AssemblyPath, out moduleDef))
{
// Can't find the assembly, just return nothing.
return string.Empty;
}
TypeDefinition typeDef = moduleDef.GetType(identity.FullyQualifiedName);
if (typeDef == null)
{
// If we can't find our type just return as well.
return string.Empty;
}
DecompilerContext context = new DecompilerContext(moduleDef);
AstBuilder astBuilder = new AstBuilder(context);
astBuilder.AddType(typeDef);
PlainTextOutput textOutput = new PlainTextOutput();
astBuilder.GenerateCode(textOutput);
return textOutput.ToString();
}
示例2: DecompileMethod
public override void DecompileMethod(MethodDefinition method, ITextOutput output, DecompilationOptions options)
{
if (!method.HasBody) {
return;
}
ILAstBuilder astBuilder = new ILAstBuilder();
ILBlock ilMethod = new ILBlock();
ilMethod.Body = astBuilder.Build(method, inlineVariables);
if (abortBeforeStep != null) {
DecompilerContext context = new DecompilerContext(method.Module) { CurrentType = method.DeclaringType, CurrentMethod = method };
new ILAstOptimizer().Optimize(context, ilMethod, abortBeforeStep.Value);
}
var allVariables = ilMethod.GetSelfAndChildrenRecursive<ILExpression>().Select(e => e.Operand as ILVariable)
.Where(v => v != null && !v.IsParameter).Distinct();
foreach (ILVariable v in allVariables) {
output.WriteDefinition(v.Name, v);
if (v.Type != null) {
output.Write(" : ");
if (v.IsPinned)
output.Write("pinned ");
v.Type.WriteTo(output, ILNameSyntax.ShortTypeName);
}
output.WriteLine();
}
output.WriteLine();
foreach (ILNode node in ilMethod.Body) {
node.WriteTo(output);
output.WriteLine();
}
}
示例3: Decompile
public void Decompile(Stream assemblyStream, TextWriter resultWriter)
{
// ReSharper disable once AgentHeisenbug.CallToNonThreadSafeStaticMethodInThreadSafeType
var module = ModuleDefinition.ReadModule(assemblyStream);
((BaseAssemblyResolver)module.AssemblyResolver).AddSearchDirectory(
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
);
var context = new DecompilerContext(module) {
Settings = {
AnonymousMethods = false,
YieldReturn = false,
AsyncAwait = false,
AutomaticProperties = false,
ExpressionTrees = false
}
};
var ast = new AstBuilder(context);
ast.AddAssembly(module.Assembly);
RunTransforms(ast, context);
// I cannot use GenerateCode as it re-runs all the transforms
var userCode = GetUserCode(ast);
WriteResult(resultWriter, userCode, context);
}
示例4: 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);
}
}
}
示例5: Transform
/// <summary>
/// Public translation interface.
/// Translates the given method to GLSL
/// </summary>
/// <param name="s">Shader type definition.</param>
/// <param name="m">A method representing a shader to translate.</param>
/// <param name="attr">The shader type as attribute (either FragmentShaderAttribute or VertexShaderAttribute</param>
/// <param name="type">The shader type as ShaderType</param>
/// <returns>The translated GLSL shader source</returns>
public FunctionDescription Transform(TypeDefinition s, MethodDefinition m, CustomAttribute attr,
ShaderType type)
{
if (s == null)
throw new ArgumentNullException("s");
if (m == null)
throw new ArgumentNullException("m");
if (attr == null)
throw new ArgumentNullException("attr");
var ctx = new DecompilerContext(s.Module)
{
CurrentType = s,
CurrentMethod = m,
CancellationToken = CancellationToken.None
};
var d = AstMethodBodyBuilder.CreateMethodBody(m, ctx);
var glsl = new GlslVisitor(d, attr, ctx);
_functions.UnionWith(glsl.Functions);
var entry = (bool)attr.ConstructorArguments.FirstOrDefault().Value;
var sig = entry ? "void main()" : GlslVisitor.GetSignature(m);
var code = glsl.Result;
var desc = new FunctionDescription(entry ? "main" : Shader.GetMethodName(m), sig + code, entry, type);
_dependencies.UnionWith(glsl.Dependencies);
return desc;
}
示例6: DecompileOnDemand
public void DecompileOnDemand(TypeDefinition type)
{
if (type == null)
return;
if (CheckMappings(type.MetadataToken.ToInt32()))
return;
try {
DecompilerContext context = new DecompilerContext(type.Module);
AstBuilder astBuilder = new AstBuilder(context);
astBuilder.AddType(type);
astBuilder.GenerateCode(new PlainTextOutput());
int token = type.MetadataToken.ToInt32();
var info = new DecompileInformation {
CodeMappings = astBuilder.CodeMappings,
LocalVariables = astBuilder.LocalVariables,
DecompiledMemberReferences = astBuilder.DecompiledMemberReferences
};
// save the data
DebugInformation.AddOrUpdate(token, info, (k, v) => info);
} catch {
return;
}
}
示例7: GetSourceCode
public static async Task<string> GetSourceCode(MethodDefinition methodDefinition, ILWeaver weaver = null)
{
return await Task.Run(() =>
{
try
{
if (weaver != null) weaver.Apply(methodDefinition.Body);
var settings = new DecompilerSettings { UsingDeclarations = false };
var context = new DecompilerContext(methodDefinition.Module)
{
CurrentType = methodDefinition.DeclaringType,
Settings = settings
};
var astBuilder = new AstBuilder(context);
astBuilder.AddMethod(methodDefinition);
var textOutput = new PlainTextOutput();
astBuilder.GenerateCode(textOutput);
return textOutput.ToString();
}
catch (Exception ex)
{
return "Error in creating source code from IL: " + ex.Message + Environment.NewLine + ex.StackTrace;
}
finally
{
if (weaver != null) methodDefinition.Body = null;
}
});
}
示例8: DecompileMethod
public override void DecompileMethod(MethodDef method, ITextOutput output, DecompilationOptions options)
{
WriteComment(output, "Method: ");
output.WriteDefinition(IdentifierEscaper.Escape(method.FullName), method, TextTokenType.Comment, false);
output.WriteLine();
if (!method.HasBody) {
return;
}
StartKeywordBlock(output, ".body", method);
ILAstBuilder astBuilder = new ILAstBuilder();
ILBlock ilMethod = new ILBlock();
DecompilerContext context = new DecompilerContext(method.Module) { CurrentType = method.DeclaringType, CurrentMethod = method };
ilMethod.Body = astBuilder.Build(method, inlineVariables, context);
if (abortBeforeStep != null) {
new ILAstOptimizer().Optimize(context, ilMethod, abortBeforeStep.Value);
}
if (context.CurrentMethodIsAsync) {
output.Write("async", TextTokenType.Keyword);
output.Write('/', TextTokenType.Operator);
output.WriteLine("await", TextTokenType.Keyword);
}
var allVariables = ilMethod.GetSelfAndChildrenRecursive<ILExpression>().Select(e => e.Operand as ILVariable)
.Where(v => v != null && !v.IsParameter).Distinct();
foreach (ILVariable v in allVariables) {
output.WriteDefinition(IdentifierEscaper.Escape(v.Name), v, v.IsParameter ? TextTokenType.Parameter : TextTokenType.Local);
if (v.Type != null) {
output.WriteSpace();
output.Write(':', TextTokenType.Operator);
output.WriteSpace();
if (v.IsPinned) {
output.Write("pinned", TextTokenType.Keyword);
output.WriteSpace();
}
v.Type.WriteTo(output, ILNameSyntax.ShortTypeName);
}
if (v.IsGenerated) {
output.WriteSpace();
output.Write('[', TextTokenType.Operator);
output.Write("generated", TextTokenType.Keyword);
output.Write(']', TextTokenType.Operator);
}
output.WriteLine();
}
var memberMapping = new MemberMapping(method);
foreach (ILNode node in ilMethod.Body) {
node.WriteTo(output, memberMapping);
if (!node.WritesNewLine)
output.WriteLine();
}
output.AddDebugSymbols(memberMapping);
EndKeywordBlock(output);
}
示例9: TextTokenWriter
public TextTokenWriter(ITextOutput output, DecompilerContext context)
{
if (output == null)
throw new ArgumentNullException("output");
if (context == null)
throw new ArgumentNullException("context");
this.output = output;
this.context = context;
}
示例10: AstBuilder
public AstBuilder(DecompilerContext context)
{
if (context == null)
throw new ArgumentNullException("context");
this.context = context;
this.DecompileMethodBodies = true;
this.LocalVariables = new ConcurrentDictionary<int, IEnumerable<ILVariable>>();
}
示例11: RunTransforms
//private IEnumerable<AstNode> FlattenScript(TypeDeclaration scriptClass) {
// foreach (var member in scriptClass.Members) {
// var constructor = member as ConstructorDeclaration;
// if (constructor != null) {
// foreach (var statement in constructor.Body.Statements) {
// yield return statement;
// }
// }
// else {
// yield return member;
// }
// }
//}
private void RunTransforms(AstBuilder ast, DecompilerContext context)
{
var transforms = TransformationPipeline.CreatePipeline(context).ToList();
transforms[transforms.FindIndex(t => t is ConvertConstructorCallIntoInitializer)] = new RoslynFriendlyConvertConstructorCallIntoInitializer();
foreach (var transform in transforms) {
transform.Run(ast.SyntaxTree);
}
}
示例12: CreateBuilder
AstBuilder CreateBuilder(IDnlibDef item, CancellationToken token) {
ModuleDef moduleDef;
DecompilerContext ctx;
AstBuilder builder;
if (item is ModuleDef) {
var def = (ModuleDef)item;
moduleDef = def;
builder = new AstBuilder(ctx = new DecompilerContext(moduleDef) { CancellationToken = token });
builder.AddAssembly(def, true);
}
else if (item is TypeDef) {
var def = (TypeDef)item;
moduleDef = def.Module;
builder = new AstBuilder(ctx = new DecompilerContext(moduleDef) { CancellationToken = token });
builder.DecompileMethodBodies = false;
ctx.CurrentType = def;
builder.AddType(def);
}
else if (item is MethodDef) {
var def = (MethodDef)item;
moduleDef = def.Module;
builder = new AstBuilder(ctx = new DecompilerContext(moduleDef) { CancellationToken = token });
ctx.CurrentType = def.DeclaringType;
builder.AddMethod(def);
}
else if (item is FieldDef) {
var def = (FieldDef)item;
moduleDef = def.Module;
builder = new AstBuilder(ctx = new DecompilerContext(moduleDef) { CancellationToken = token });
ctx.CurrentType = def.DeclaringType;
builder.AddField(def);
}
else if (item is PropertyDef) {
var def = (PropertyDef)item;
moduleDef = def.Module;
builder = new AstBuilder(ctx = new DecompilerContext(moduleDef) { CancellationToken = token });
ctx.CurrentType = def.DeclaringType;
builder.AddProperty(def);
}
else if (item is EventDef) {
var def = (EventDef)item;
moduleDef = def.Module;
builder = new AstBuilder(ctx = new DecompilerContext(moduleDef) { CancellationToken = token });
ctx.CurrentType = def.DeclaringType;
builder.AddEvent(def);
}
else
return null;
ctx.Settings = new DecompilerSettings {
UsingDeclarations = false
};
return builder;
}
示例13: WriteResult
protected override void WriteResult(TextWriter writer, IEnumerable<AstNode> ast, DecompilerContext context)
{
var visitor = new DecompiledPseudoCSharpOutputVisitor(
new TextWriterOutputFormatter(writer) {
IndentationString = " "
},
context.Settings.CSharpFormattingOptions
);
foreach (var node in ast) {
node.AcceptVisitor(visitor);
}
}
示例14: GlslVisitor
public GlslVisitor(BlockStatement block, CustomAttribute attr, DecompilerContext ctx)
: this()
{
_attr = attr;
var trans1 = new ReplaceMethodCallsWithOperators(ctx);
var trans2 = new RenameLocals();
((IAstTransform)trans1).Run(block);
trans2.Run(block);
Result = block.AcceptVisitor(this, 0).ToString();
Result += Environment.NewLine;
}
示例15: EmitField
public void EmitField(DecompilerContext context, IAstEmitter astEmitter, FieldDefinition field, JSRawOutputIdentifier dollar, JSExpression defaultValue)
{
var fieldInfo = Translator.TypeInfoProvider.GetField(field);
var typeKeyword = WasmUtil.PickTypeKeyword(fieldInfo.FieldType);
// Unhandled type
if (typeKeyword == null)
return;
Switch(PrecedingType.Global);
Formatter.WriteRaw("(global ${0} {1})", WasmUtil.EscapeIdentifier(fieldInfo.Name), typeKeyword);
Formatter.ConditionalNewLine();
}