Settings for the decompiler.
Inheritance: INotifyPropertyChanged
Esempio n. 1
0
 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;
         }
     });
 }
Esempio n. 2
0
		public static bool MemberIsHidden(MemberReference member, DecompilerSettings settings)
		{
			MethodDefinition method = member as MethodDefinition;
			if (method != null) {
				if (method.IsGetter || method.IsSetter || method.IsAddOn || method.IsRemoveOn)
					return true;
				if (settings.AnonymousMethods && method.Name.StartsWith("<", StringComparison.Ordinal) && method.IsCompilerGenerated())
					return true;
			}
			TypeDefinition type = member as TypeDefinition;
			if (type != null && type.DeclaringType != null) {
				if (settings.AnonymousMethods && type.Name.StartsWith("<>c__DisplayClass", StringComparison.Ordinal) && type.IsCompilerGenerated())
					return true;
				if (settings.YieldReturn && YieldReturnDecompiler.IsCompilerGeneratorEnumerator(type))
					return true;
			}
			FieldDefinition field = member as FieldDefinition;
			if (field != null && field.IsCompilerGenerated()) {
				if (settings.AnonymousMethods && field.Name.StartsWith("CS$<>", StringComparison.Ordinal))
					return true;
				if (settings.AutomaticProperties && field.Name.StartsWith("<", StringComparison.Ordinal) && field.Name.EndsWith("BackingField", StringComparison.Ordinal))
					return true;
			}
			// event-fields are not [CompilerGenerated]
			if (field != null && settings.AutomaticEvents && field.DeclaringType.Events.Any(ev => ev.Name == field.Name))
				return true;
			return false;
		}
		public static DecompilerSettings LoadDecompilerSettings(ILSpySettings settings)
		{
			XElement e = settings["DecompilerSettings"];
			DecompilerSettings s = new DecompilerSettings();
			s.AnonymousMethods = (bool?)e.Attribute("anonymousMethods") ?? s.AnonymousMethods;
			s.YieldReturn = (bool?)e.Attribute("yieldReturn") ?? s.YieldReturn;
			return s;
		}
		public static DecompilerSettings LoadDecompilerSettings(ILSpySettings settings)
		{
			XElement e = settings["DecompilerSettings"];
			DecompilerSettings s = new DecompilerSettings();
			s.AnonymousMethods = (bool?)e.Attribute("anonymousMethods") ?? s.AnonymousMethods;
			s.YieldReturn = (bool?)e.Attribute("yieldReturn") ?? s.YieldReturn;
			s.QueryExpressions = (bool?)e.Attribute("queryExpressions") ?? s.QueryExpressions;
			s.UseDebugSymbols = (bool?)e.Attribute("useDebugSymbols") ?? s.UseDebugSymbols;
			return s;
		}
Esempio n. 5
0
		public void Reset()
		{
			this.CurrentModule = null;
			this.CancellationToken = CancellationToken.None;
			this.CurrentType = null;
			this.CurrentMethod = null;
			this.Settings = new DecompilerSettings();
			this.CurrentMethodIsAsync = false;
			this.Cache.Reset();
		}
 public void Decompile()
 {
     AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly("Salient.JsonSchemaUtilities.dll");
     DecompilerSettings settings = new DecompilerSettings();
     settings.FullyQualifyAmbiguousTypeNames = false;
     AstBuilder decompiler = new AstBuilder(new DecompilerContext(assembly.MainModule) { Settings = settings });
     decompiler.AddAssembly(assembly);
     //new Helpers.RemoveCompilerAttribute().Run(decompiler.CompilationUnit);
     StringWriter output = new StringWriter();
     decompiler.GenerateCode(new PlainTextOutput(output));
     var code = output.ToString();
 }
		public static DecompilerSettings LoadDecompilerSettings(ILSpySettings settings)
		{
			XElement e = settings["DecompilerSettings"];
			DecompilerSettings s = new DecompilerSettings();
			s.AnonymousMethods = (bool?)e.Attribute("anonymousMethods") ?? s.AnonymousMethods;
			s.YieldReturn = (bool?)e.Attribute("yieldReturn") ?? s.YieldReturn;
			s.AsyncAwait = (bool?)e.Attribute("asyncAwait") ?? s.AsyncAwait;
			s.QueryExpressions = (bool?)e.Attribute("queryExpressions") ?? s.QueryExpressions;
			s.UseDebugSymbols = (bool?)e.Attribute("useDebugSymbols") ?? s.UseDebugSymbols;
			s.ShowXmlDocumentation = (bool?)e.Attribute("xmlDoc") ?? s.ShowXmlDocumentation;
			s.FoldBraces = (bool?)e.Attribute("foldBraces") ?? s.FoldBraces;
			return s;
		}
 public static string ToSource(MethodDefinition methodDefinition)
 {
     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();
 }
        public DecompilationOptions(LanguageVersion version, Decompiler.DecompilerSettings settings, Options.DisplaySettings displaySettings)
        {
            if (!Enum.TryParse(version.Version, out Decompiler.CSharp.LanguageVersion languageVersion))
            {
                languageVersion = Decompiler.CSharp.LanguageVersion.Latest;
            }
            var newSettings = this.DecompilerSettings = settings.Clone();

            newSettings.SetLanguageVersion(languageVersion);
            newSettings.ExpandMemberDefinitions = displaySettings.ExpandMemberDefinitions;
            newSettings.ExpandUsingDeclarations = displaySettings.ExpandUsingDeclarations;
            newSettings.FoldBraces    = displaySettings.FoldBraces;
            newSettings.ShowDebugInfo = displaySettings.ShowDebugInfo;
            newSettings.CSharpFormattingOptions.IndentationString = GetIndentationString(displaySettings);
        }
		public void Save(XElement root)
		{
			DecompilerSettings s = (DecompilerSettings)this.DataContext;
			XElement section = new XElement("DecompilerSettings");
			section.SetAttributeValue("anonymousMethods", s.AnonymousMethods);
			section.SetAttributeValue("yieldReturn", s.YieldReturn);
			
			XElement existingElement = root.Element("DecompilerSettings");
			if (existingElement != null)
				existingElement.ReplaceWith(section);
			else
				root.Add(section);
			
			currentDecompilerSettings = null; // invalidate cached settings
		}
		public static DecompilerSettings LoadDecompilerSettings(ILSpySettings settings)
		{
			XElement e = settings["DecompilerSettings"];
			DecompilerSettings s = new DecompilerSettings();
			s.AnonymousMethods = (bool?)e.Attribute("anonymousMethods") ?? s.AnonymousMethods;
			s.YieldReturn = (bool?)e.Attribute("yieldReturn") ?? s.YieldReturn;
			s.AsyncAwait = (bool?)e.Attribute("asyncAwait") ?? s.AsyncAwait;
			s.QueryExpressions = (bool?)e.Attribute("queryExpressions") ?? s.QueryExpressions;
			s.ExpressionTrees = (bool?)e.Attribute("expressionTrees") ?? s.ExpressionTrees;
			s.UseDebugSymbols = (bool?)e.Attribute("useDebugSymbols") ?? s.UseDebugSymbols;
			s.ShowXmlDocumentation = (bool?)e.Attribute("xmlDoc") ?? s.ShowXmlDocumentation;
			s.AddILComments = (bool?)e.Attribute("addILComments") ?? s.AddILComments;
			s.RemoveEmptyDefaultConstructors = (bool?)e.Attribute("removeEmptyDefaultConstructors") ?? s.RemoveEmptyDefaultConstructors;
			return s;
		}
        public void DecompileMethod(MethodDefinition method, ITextOutput output)
        {
            DecompilerSettings settings = new DecompilerSettings();

            //WriteCommentLine(output, TypeToString(method.DeclaringType, includeNamespace: true));
            AstBuilder codeDomBuilder = CreateAstBuilder(settings, currentType: method.DeclaringType, isSingleMember: true);
            if (method.IsConstructor && !method.IsStatic && !method.DeclaringType.IsValueType)
            {
                // also fields and other ctors so that the field initializers can be shown as such
                AddFieldsAndCtors(codeDomBuilder, method.DeclaringType, method.IsStatic);
                RunTransformsAndGenerateCode(codeDomBuilder, output, settings, new SelectCtorTransform(method));
            }
            else
            {
                codeDomBuilder.AddMethod(method);
                RunTransformsAndGenerateCode(codeDomBuilder, output, settings);
            }
        }
		public void Save(XElement root)
		{
			DecompilerSettings s = (DecompilerSettings)this.DataContext;
			XElement section = new XElement("DecompilerSettings");
			section.SetAttributeValue("anonymousMethods", s.AnonymousMethods);
			section.SetAttributeValue("yieldReturn", s.YieldReturn);
			section.SetAttributeValue("queryExpressions", s.QueryExpressions);
			section.SetAttributeValue("useDebugSymbols", s.UseDebugSymbols);
			section.SetAttributeValue("xmlDoc", s.ShowXmlDocumentation);
			
			XElement existingElement = root.Element("DecompilerSettings");
			if (existingElement != null)
				existingElement.ReplaceWith(section);
			else
				root.Add(section);
			
			currentDecompilerSettings = null; // invalidate cached settings
		}
        AstBuilder CreateAstBuilder(DecompilerSettings settings, ModuleDefinition currentModule = null, TypeDefinition currentType = null, bool isSingleMember = false)
        {
            if (currentModule == null)
                currentModule = currentType.Module;

            if (isSingleMember)
            {
                settings = settings.Clone();
                settings.UsingDeclarations = false;
            }

            return new AstBuilder(
                new DecompilerContext(currentModule)
                {
                    //CancellationToken = options.CancellationToken,
                    CurrentType = currentType,
                    Settings = settings
                });
        }
Esempio n. 15
0
        /// <summary>
        /// Returns the code for a specific algorithm.
        /// </summary>
        /// <returns>The algorithm code.</returns>
        /// <param name="algorithmType">Algorithm type.</param>
        public static MethodDeclaration GetMethodCode(Type algorithmType, out AstBuilder astBuilder, string methodName)
        {
            var resolver = new DefaultAssemblyResolver();
            resolver.AddSearchDirectory(new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName);
            var parameters = new ReaderParameters
            {
                AssemblyResolver = resolver,
            };

            // Load Tychaia.ProceduralGeneration into Mono.Cecil.
            var module = AssemblyDefinition.ReadAssembly(
                Assembly.GetExecutingAssembly().Location,
                parameters).MainModule;

            // Now we have a reference to the method we want to decompile.
            TypeDefinition cecilType;
            MethodDefinition processCell;
            FindMethodName(module, algorithmType, methodName, out processCell, out cecilType);
            var decompilerSettings = new DecompilerSettings();
            astBuilder =
                new AstBuilder(new DecompilerContext(module) { CurrentType = cecilType, Settings = decompilerSettings });
            astBuilder.AddMethod(processCell);
            try
            {
                astBuilder.RunTransformations();
            }
            catch (AssemblyResolutionException ex)
            {
                throw new Exception(
                    "Unable to decompile algorithm source code for " + algorithmType.FullName + ".",
                    ex);
            }

            astBuilder.CompilationUnit.AcceptVisitor(new InsertParenthesesVisitor
            {
                InsertParenthesesForReadability = true
            });

            // Return.
            return
                astBuilder.CompilationUnit.Members.Where(v => v is MethodDeclaration).Cast<MethodDeclaration>().First();
        }
Esempio n. 16
0
        private static string Decompile(string name, MethodDefinition mtd)
        {
            var decompilerSettings = new ICSharpCode.Decompiler.DecompilerSettings {
                ShowXmlDocumentation = false,
                UsingDeclarations    = false,
            };
            var output     = new ICSharpCode.Decompiler.PlainTextOutput();
            var method     = mtd;
            var astBuilder = new AstBuilder(new DecompilerContext(method.DeclaringType.Module)
            {
                CancellationToken = new CancellationToken(),
                CurrentType       = method.DeclaringType,
                Settings          = decompilerSettings,
            });

            astBuilder.AddMethod(method);
            astBuilder.GenerateCode(output);
            var methodCode = output.ToString();

            // remove top comment line
            //if (methodCode.StartsWith("//")) {
            //	methodCode = methodCode.Substring(methodCode.IndexOf('\n') + 1);
            //}


            var attrRE = new Regex(@"^(?:\[[^]]+]\s*){1,}");

            methodCode = attrRE.Replace(methodCode, "", 1);

            // change the method name to the mod's name for the method, and replace parameter names with game names
            var methodName   = mtd.Name;
            var nameLocation = methodCode.IndexOf(" " + methodName) + 1;
            var nameEnd      = nameLocation + methodName.Length;

            // Prepend "void " if this was a constructor (since methodCode won't have a return type)
            var correctName = mtd.IsConstructor ? ("void " + name) : name;

            methodCode = methodCode.Substring(0, nameLocation) + correctName + methodCode.Substring(nameEnd);
            return(methodCode);
        }
Esempio n. 17
0
 public static async Task<string> GetSourceCode(TypeDefinition typeDefinition)
 {
     return await Task.Run(() =>
     {
         try
         {
             var settings = new DecompilerSettings { UsingDeclarations = true };
             var context = new DecompilerContext(typeDefinition.Module)
             {
                 CurrentType = typeDefinition,
                 Settings = settings
             };
             var astBuilder = new AstBuilder(context);
             var textOutput = new PlainTextOutput();
             astBuilder.GenerateCode(textOutput);
             return textOutput.ToString();
         }
         catch (Exception ex)
         {
             return "Error in creating source code from Type: " + ex.Message + ex.Message + Environment.NewLine + ex.StackTrace;
         }
     });
 }
Esempio n. 18
0
 public static DecompilerSettings LoadDecompilerSettings(ILSpySettings settings)
 {
     XElement e = settings["DecompilerSettings"];
     DecompilerSettings s = new DecompilerSettings();
     s.AnonymousMethods = (bool?)e.Attribute("anonymousMethods") ?? s.AnonymousMethods;
     s.YieldReturn = (bool?)e.Attribute("yieldReturn") ?? s.YieldReturn;
     s.AsyncAwait = (bool?)e.Attribute("asyncAwait") ?? s.AsyncAwait;
     s.QueryExpressions = (bool?)e.Attribute("queryExpressions") ?? s.QueryExpressions;
     s.ExpressionTrees = (bool?)e.Attribute("expressionTrees") ?? s.ExpressionTrees;
     s.UseDebugSymbols = (bool?)e.Attribute("useDebugSymbols") ?? s.UseDebugSymbols;
     s.ShowXmlDocumentation = (bool?)e.Attribute("xmlDoc") ?? s.ShowXmlDocumentation;
     s.ShowILComments = (bool?)e.Attribute("showILComments") ?? s.ShowILComments;
     s.RemoveEmptyDefaultConstructors = (bool?)e.Attribute("removeEmptyDefaultConstructors") ?? s.RemoveEmptyDefaultConstructors;
     s.ShowTokenAndRvaComments = (bool?)e.Attribute("showTokenAndRvaComments") ?? s.ShowTokenAndRvaComments;
     s.ShowILBytes = (bool?)e.Attribute("showILBytes") ?? s.ShowILBytes;
     s.DecompilationObject0 = (DecompilationObject)((int?)e.Attribute("decompilationObject0") ?? (int)s.DecompilationObject0);
     s.DecompilationObject1 = (DecompilationObject)((int?)e.Attribute("decompilationObject1") ?? (int)s.DecompilationObject1);
     s.DecompilationObject2 = (DecompilationObject)((int?)e.Attribute("decompilationObject2") ?? (int)s.DecompilationObject2);
     s.DecompilationObject3 = (DecompilationObject)((int?)e.Attribute("decompilationObject3") ?? (int)s.DecompilationObject3);
     s.DecompilationObject4 = (DecompilationObject)((int?)e.Attribute("decompilationObject4") ?? (int)s.DecompilationObject4);
     s.SortMembers = (bool?)e.Attribute("sortMembers") ?? s.SortMembers;
     return s;
 }
Esempio n. 19
0
		private static string Decompile(string name, MethodDefinition mtd) {
			
			var decompilerSettings = new ICSharpCode.Decompiler.DecompilerSettings {
				ShowXmlDocumentation = false,
				UsingDeclarations = false,
			};
			var output = new ICSharpCode.Decompiler.PlainTextOutput();
			var method = mtd;
			var astBuilder = new AstBuilder(new DecompilerContext(method.DeclaringType.Module) {
				CancellationToken = new CancellationToken(),
				CurrentType = method.DeclaringType,
				Settings = decompilerSettings,
			});

			astBuilder.AddMethod(method);
			astBuilder.GenerateCode(output);
			var methodCode = output.ToString();

			// remove top comment line
			//if (methodCode.StartsWith("//")) {
			//	methodCode = methodCode.Substring(methodCode.IndexOf('\n') + 1);
			//}


		    var attrRE = new Regex(@"^(?:\[[^]]+]\s*){1,}");
			methodCode = attrRE.Replace(methodCode, "", 1);

			// change the method name to the mod's name for the method, and replace parameter names with game names
			var methodName = mtd.Name;
			var nameLocation = methodCode.IndexOf(" " + methodName) + 1;
			var nameEnd = nameLocation + methodName.Length;

			// Prepend "void " if this was a constructor (since methodCode won't have a return type)
			var correctName = mtd.IsConstructor ? ("void " + name) : name;
			methodCode = methodCode.Substring(0, nameLocation) + correctName + methodCode.Substring(nameEnd);
			return methodCode;
		}
Esempio n. 20
0
 public DecompileRun(DecompilerSettings settings)
 {
     this.Settings = settings ?? throw new ArgumentNullException(nameof(settings));
 }
Esempio n. 21
0
		public DecompilationOptions()
		{
			this.DecompilerSettings = DecompilerSettingsPanel.CurrentDecompilerSettings;
		}
 void RunTransformsAndGenerateCode(AstBuilder astBuilder, ITextOutput output, DecompilerSettings settings, IAstTransform additionalTransform = null)
 {
     astBuilder.RunTransformations();//transformAbortCondition);
     if (additionalTransform != null)
     {
         additionalTransform.Run(astBuilder.CompilationUnit);
     }
     if (settings.ShowXmlDocumentation)
     {
         //AddXmlDocTransform.Run(astBuilder.CompilationUnit);
     }
     astBuilder.GenerateCode(output);
 }
		public List<ReferenceSegment> Decompile (TextEditorData data, ITreeNavigator navigator, bool publicOnly)
		{
			if (DomMethodNodeBuilder.HandleSourceCodeEntity (navigator, data)) 
				return null;
			var type = CecilLoader.GetCecilObject ((IUnresolvedTypeDefinition)navigator.DataItem);
			if (type == null)
				return null;
			var types = DesktopService.GetMimeTypeInheritanceChain (data.Document.MimeType);
			var codePolicy = MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy<MonoDevelop.CSharp.Formatting.CSharpFormattingPolicy> (types);
			var settings = new DecompilerSettings () {
				AnonymousMethods = true,
				AutomaticEvents  = true,
				AutomaticProperties = true,
				ForEachStatement = true,
				LockStatement = true,
				CSharpFormattingOptions = codePolicy.CreateOptions (),
				HideNonPublicMembers = publicOnly
			};
			return DomMethodNodeBuilder.Decompile (data, DomMethodNodeBuilder.GetModule (navigator), type, builder => {
				builder.AddType (type);
			}, settings);
		}
		public CSharpVBDecompilerSettings(DecompilerSettings decompilerSettings = null) {
			this.decompilerSettings = decompilerSettings ?? new DecompilerSettings();
			options = CreateOptions().ToArray();
		}
Esempio n. 25
0
		public override void Load(ILSpySettings settings) {
			this.settings = LoadDecompilerSettings(settings);
		}
Esempio n. 26
0
		public override RefreshFlags Save(XElement root) {
			DecompilerSettings s = this.settings;
			var flags = RefreshFlags.None;

			if (CurrentDecompilerSettings.AnonymousMethods != s.AnonymousMethods) flags |= RefreshFlags.ILAst | RefreshFlags.TreeViewNodes;
			if (CurrentDecompilerSettings.ExpressionTrees != s.ExpressionTrees) flags |= RefreshFlags.ILAst;
			if (CurrentDecompilerSettings.YieldReturn != s.YieldReturn) flags |= RefreshFlags.ILAst | RefreshFlags.TreeViewNodes;
			if (CurrentDecompilerSettings.AsyncAwait != s.AsyncAwait) flags |= RefreshFlags.ILAst | RefreshFlags.TreeViewNodes;
			if (CurrentDecompilerSettings.AutomaticProperties != s.AutomaticProperties) flags |= RefreshFlags.CSharp | RefreshFlags.TreeViewNodes;
			if (CurrentDecompilerSettings.AutomaticEvents != s.AutomaticEvents) flags |= RefreshFlags.CSharp | RefreshFlags.TreeViewNodes;
			if (CurrentDecompilerSettings.UsingStatement != s.UsingStatement) flags |= RefreshFlags.CSharp;
			if (CurrentDecompilerSettings.ForEachStatement != s.ForEachStatement) flags |= RefreshFlags.CSharp;
			if (CurrentDecompilerSettings.LockStatement != s.LockStatement) flags |= RefreshFlags.CSharp;
			if (CurrentDecompilerSettings.SwitchStatementOnString != s.SwitchStatementOnString) flags |= RefreshFlags.CSharp | RefreshFlags.TreeViewNodes;
			if (CurrentDecompilerSettings.UsingDeclarations != s.UsingDeclarations) flags |= RefreshFlags.CSharp;
			if (CurrentDecompilerSettings.QueryExpressions != s.QueryExpressions) flags |= RefreshFlags.CSharp;
			if (CurrentDecompilerSettings.FullyQualifyAmbiguousTypeNames != s.FullyQualifyAmbiguousTypeNames) flags |= RefreshFlags.CSharp;
			if (CurrentDecompilerSettings.UseDebugSymbols != s.UseDebugSymbols) flags |= RefreshFlags.DecompileAll;
			if (CurrentDecompilerSettings.ObjectOrCollectionInitializers != s.ObjectOrCollectionInitializers) flags |= RefreshFlags.ILAst;
			if (CurrentDecompilerSettings.ShowXmlDocumentation != s.ShowXmlDocumentation) flags |= RefreshFlags.DecompileAll;
			if (CurrentDecompilerSettings.ShowILComments != s.ShowILComments) flags |= RefreshFlags.IL;
			if (CurrentDecompilerSettings.RemoveEmptyDefaultConstructors != s.RemoveEmptyDefaultConstructors) flags |= RefreshFlags.CSharp;
			if (CurrentDecompilerSettings.IntroduceIncrementAndDecrement != s.IntroduceIncrementAndDecrement) flags |= RefreshFlags.ILAst;
			if (CurrentDecompilerSettings.MakeAssignmentExpressions != s.MakeAssignmentExpressions) flags |= RefreshFlags.ILAst;
			if (CurrentDecompilerSettings.AlwaysGenerateExceptionVariableForCatchBlocks != s.AlwaysGenerateExceptionVariableForCatchBlocks) flags |= RefreshFlags.ILAst;
			if (CurrentDecompilerSettings.ShowTokenAndRvaComments != s.ShowTokenAndRvaComments) flags |= RefreshFlags.DecompileAll;
			if (CurrentDecompilerSettings.ShowILBytes != s.ShowILBytes) flags |= RefreshFlags.IL;
			if (CurrentDecompilerSettings.DecompilationObject0 != s.DecompilationObject0) flags |= RefreshFlags.CSharp;
			if (CurrentDecompilerSettings.DecompilationObject1 != s.DecompilationObject1) flags |= RefreshFlags.CSharp;
			if (CurrentDecompilerSettings.DecompilationObject2 != s.DecompilationObject2) flags |= RefreshFlags.CSharp;
			if (CurrentDecompilerSettings.DecompilationObject3 != s.DecompilationObject3) flags |= RefreshFlags.CSharp;
			if (CurrentDecompilerSettings.DecompilationObject4 != s.DecompilationObject4) flags |= RefreshFlags.CSharp;
			if (CurrentDecompilerSettings.SortMembers != s.SortMembers) flags |= RefreshFlags.IL | RefreshFlags.CSharp;
			if (CurrentDecompilerSettings.ForceShowAllMembers != s.ForceShowAllMembers) flags |= RefreshFlags.CSharp | RefreshFlags.TreeViewNodes;
			if (CurrentDecompilerSettings.SortSystemUsingStatementsFirst != s.SortSystemUsingStatementsFirst) flags |= RefreshFlags.CSharp;

			XElement section = new XElement("DecompilerSettings");
			section.SetAttributeValue("anonymousMethods", s.AnonymousMethods);
			section.SetAttributeValue("yieldReturn", s.YieldReturn);
			section.SetAttributeValue("asyncAwait", s.AsyncAwait);
			section.SetAttributeValue("queryExpressions", s.QueryExpressions);
			section.SetAttributeValue("expressionTrees", s.ExpressionTrees);
			section.SetAttributeValue("useDebugSymbols", s.UseDebugSymbols);
			section.SetAttributeValue("xmlDoc", s.ShowXmlDocumentation);
			section.SetAttributeValue("showILComments", s.ShowILComments);
			section.SetAttributeValue("removeEmptyDefaultConstructors", s.RemoveEmptyDefaultConstructors);
			section.SetAttributeValue("showTokenAndRvaComments", s.ShowTokenAndRvaComments);
			section.SetAttributeValue("showILBytes", s.ShowILBytes);
			section.SetAttributeValue("decompilationObject0", (int)s.DecompilationObject0);
			section.SetAttributeValue("decompilationObject1", (int)s.DecompilationObject1);
			section.SetAttributeValue("decompilationObject2", (int)s.DecompilationObject2);
			section.SetAttributeValue("decompilationObject3", (int)s.DecompilationObject3);
			section.SetAttributeValue("decompilationObject4", (int)s.DecompilationObject4);
			section.SetAttributeValue("sortMembers", s.SortMembers);
			section.SetAttributeValue("forceShowAllMembers", s.ForceShowAllMembers);
			section.SetAttributeValue("sortSystemUsingStatementsFirst", s.SortSystemUsingStatementsFirst);

			XElement existingElement = root.Element("DecompilerSettings");
			if (existingElement != null)
				existingElement.ReplaceWith(section);
			else
				root.Add(section);

			currentDecompilerSettings = null; // invalidate cached settings
			return flags;
		}
Esempio n. 27
0
		public DecompilationOptions()
		{
			this.DecompilerSettings = new DecompilerSettings();
		}
Esempio n. 28
0
		public List<ReferenceSegment> Decompile (TextEditorData data, ITreeNavigator navigator, bool publicOnly)
		{
			if (DomMethodNodeBuilder.HandleSourceCodeEntity (navigator, data)) 
				return null;
			var type = CecilLoader.GetCecilObject ((IUnresolvedTypeDefinition)navigator.DataItem);
			if (type == null)
				return null;
			var settings = new DecompilerSettings () {
				AnonymousMethods = true,
				AutomaticEvents  = true,
				AutomaticProperties = true,
				ForEachStatement = true,
				LockStatement = true,
				HideNonPublicMembers = publicOnly
			};
			return DomMethodNodeBuilder.Decompile (data, DomMethodNodeBuilder.GetModule (navigator), type, builder => {
				builder.AddType (type);
			}, settings);
		}
Esempio n. 29
0
		public static bool praseDecompileSetting(char c, DecompilerSettings ds)
		{
			switch (c) {
			case 'a':
				ds.YieldReturn = false;
				break;
			case 'b':
				ds.AnonymousMethods = false;
				break;
			case 'c':
				ds.AsyncAwait = false;
				break;
			case 'd':
				ds.AutomaticEvents = false;
				break;


			case 'e':
				ds.ExpressionTrees = false;
				break;

			case 'f':
				ds.AutomaticProperties = false;
				break;

			case 'g':
				ds.UsingStatement = false;
				break;
			case 'h':
				ds.ForEachStatement = false;
				break;
			
			case 'i':
				ds.LockStatement = false;
				break;
			case 'j':
				ds.SwitchStatementOnString = false;
				break;
			case 'k':
				ds.UsingDeclarations = false;
				break;
			case 'r':
				ds.QueryExpressions = false;
				break;

			case 's':
				ds.FullyQualifyAmbiguousTypeNames = false;
				break;
			case 'p':
				ds.UseDebugSymbols = false;
				break;
			case 'x':
				ds.ObjectOrCollectionInitializers = false;
				break;
			case 'y':
				ds.ShowXmlDocumentation = false;
				break;
			case 'z':
				ds.FoldBraces = true;
				break;
			default:
				return false;
			}

			return true;
		}
Esempio n. 30
0
 /// <summary>
 ///     Gets/sets an optional state of a decompiler text view.
 /// </summary>
 /// <remarks>
 ///     This state is used to restore test view's state when decompilation is started by Go Back/Forward action.
 /// </remarks>
 //public ICSharpCode.ILSpy.TextView.DecompilerTextViewState TextViewState { get; set; }
 public DecompilationOptions()
 {
     //this.DecompilerSettings = DecompilerSettingsPanel.CurrentDecompilerSettings;
     DecompilerSettings = new DecompilerSettings();
     FullDecompilation = false;
 }
		public static List<ReferenceSegment> Decompile (TextEditorData data, ModuleDefinition module, TypeDefinition currentType, Action<AstBuilder> setData)
		{
			var types = DesktopService.GetMimeTypeInheritanceChain (data.Document.MimeType);
			var codePolicy = MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy<MonoDevelop.CSharp.Formatting.CSharpFormattingPolicy> (types);
			DecompilerSettings settings = new DecompilerSettings () {
				AnonymousMethods = true,
				AutomaticEvents  = true,
				AutomaticProperties = true,
				ForEachStatement = true,
				LockStatement = true,
				ShowXmlDocumentation = true,
				CSharpFormattingOptions = codePolicy.CreateOptions ()
			};
			return Decompile (data, module, currentType, setData, settings);
		}
		public static List<ReferenceSegment> Decompile (TextEditorData data, ModuleDefinition module, TypeDefinition currentType, Action<AstBuilder> setData, DecompilerSettings settings)
		{
			try {

				var context = new DecompilerContext (module);
				var source = new CancellationTokenSource ();
				
				context.CancellationToken = source.Token;
				context.CurrentType = currentType;
				
				context.Settings = settings;
				
				AstBuilder astBuilder = new AstBuilder (context);
				
				setData (astBuilder);
				
				astBuilder.RunTransformations (o => false);
				GeneratedCodeSettings.Default.Apply (astBuilder.CompilationUnit);
				var output = new ColoredCSharpFormatter (data.Document);
				astBuilder.GenerateCode (output);
				output.SetDocumentData ();
				return output.ReferencedSegments;
			} catch (Exception e) {
				data.Text = "Decompilation failed: \n" + e;
			}
			return null;
		}
Esempio n. 33
0
		public static void Main (string[] args)
		{

			string appPath = null;
			string slnName = null;
			string libPath = null;
			string expOpt = null;
			string outLanguageType = LAN_TYPE_CSHARP;
			DecompilerSettings ds = new DecompilerSettings ();
			ds.AnonymousMethods = true;
			ds.AsyncAwait = true;
			ds.YieldReturn = true;
			string onlyDecomileClassName = null;

			List<string> onlyDecompilingFileNameList = new List<string> ();
			//parsing args
			foreach (string x in args) {

				if (x.StartsWith ("-")) {
					switch (x) {
					case "-n":
					case "-l":
					case "-t":
					case "-C":
					case "-D":
						expOpt = x;
						continue;
					
					default:

						if (x.StartsWith ("-")) {

							if (x.Length < 2) {
								Console.WriteLine (" Unexpected options " + x);
								showUsage ();
								return;
							}

							for (int i = 0; i < x.Length; i++) {
								if (!praseDecompileSetting (x [i], ds)) {
									Console.WriteLine (" Unexpected options " + x);
									showUsage ();
									return;
								}

							}
							continue;
						} 

						break;
					}

				} else if (expOpt != null) {

					switch (expOpt) {
					case "-n":
						slnName = x;
						expOpt = null;
						break;
					case "-l":
						libPath = x;
						expOpt = null;
						break;
					case "-t":
						if (x != LAN_TYPE_CSHARP && x != LAN_TYPE_IL) {
							Console.WriteLine (" Unexpected Output language type: " + x);
							showUsage ();
							return;
						}
						outLanguageType = x;
						expOpt = null;
						break;
					case "-C":
						onlyDecomileClassName = x;
						expOpt = null;
						break;
					case "-D":
						onlyDecompilingFileNameList.Add (x);
						break;
					default:
						showUsage ();
						expOpt = null;
						return;
					
					}


				} else {
					if (appPath == null) {
						appPath = x;
						continue;
					} else {
						Console.WriteLine (" Unexpected options " + x);
						showUsage ();
						return;
					}
				}
					
			}


			if (appPath == null) {
			
				Console.WriteLine ("directory/to/all/your/dll missing");
				showUsage ();
				return;
			}

			if (slnName == null && outLanguageType==LAN_TYPE_CSHARP) {

				Console.WriteLine ("Solution Name missing");
				showUsage ();
				return;
			}


			Console.WriteLine ("Decompiling all dll in  " + appPath);
			Console.WriteLine ("Please wait...");

			DirectoryInfo di = new DirectoryInfo(appPath);
			appPath = di.FullName;
			FileInfo[] dllFileInfoList = di.GetFiles("*.dll");
			FileInfo[] exeFileInfoList = di.GetFiles ("*.exe");


			AssemblyList asmlist = new AssemblyList ("mylistname");

			foreach (var dllfile in dllFileInfoList)
			{
				bool bDecompile = isDecompilingFile (dllfile.FullName, onlyDecompilingFileNameList);
				asmlist.OpenAssembly (dllfile.FullName,!bDecompile);
			}

			foreach (var dllfile in exeFileInfoList)
			{
				bool bDecompile = isDecompilingFile (dllfile.FullName, onlyDecompilingFileNameList);

				asmlist.OpenAssembly (dllfile.FullName,!bDecompile);
			}


			if (libPath != null) {
				di = new DirectoryInfo(libPath);
				libPath = di.FullName;
				dllFileInfoList = di.GetFiles("*.dll");
				foreach (var dllfile in dllFileInfoList) {
					asmlist.OpenAssembly (dllfile.FullName,true);
				}
			}
			


			StringBuilder projSln = new StringBuilder ();
			projSln.Append ("Microsoft Visual Studio Solution File, Format Version 11.00\n# Visual Studio 2010\n");

			StringBuilder globSec = new StringBuilder ();
			Guid slnProjGuid =  Guid.NewGuid();

			int num = 0;
			LoadedAssembly [] ls = asmlist.GetAssemblies ();
			var decompilationOptions = new DecompilationOptions ();
			decompilationOptions.FullDecompilation = true;
			decompilationOptions.assenmlyList = asmlist;
			decompilationOptions.DecompilerSettings = ds;
			decompilationOptions.IncludedClassName = onlyDecomileClassName;

			if(outLanguageType==LAN_TYPE_CSHARP)
			{
				foreach (LoadedAssembly asm in ls) {
					if (asm.IsAutoLoaded)
						continue;




					string projectPath = appPath + "/"+ asm.ShortName;
					if(!Directory.Exists(projectPath))
					{
						Directory.CreateDirectory (projectPath);
					}
					string projectFileName = projectPath + "/" + asm.ShortName + ".csproj";
					asm.ProjectGuid = Guid.NewGuid();
					asm.ProjectFileName = projectFileName;
				}
			}



			foreach (LoadedAssembly asm in ls) {
				num++;
				Console.WriteLine(asm.FileName + " " + num+"/"+ls.Length);
				if (asm.IsAutoLoaded)
					continue;

				if(outLanguageType==LAN_TYPE_CSHARP)
				{
					var csharpLanguage = new CSharpLanguage ();
					var textOutput = new PlainTextOutput ();
					decompilationOptions.SaveAsProjectDirectory =  appPath + "/"+ asm.ShortName;

					csharpLanguage.DecompileAssembly (asm, textOutput, decompilationOptions);
					File.WriteAllText (asm.ProjectFileName, textOutput.ToString ());

					
					Guid createdProjGuid = asm.ProjectGuid;
					
					projSln.Append("   Project(\"{");
					projSln.Append (slnProjGuid.ToString());
					projSln.Append ("}\") = \"");
					projSln.Append (asm.ShortName);
					projSln.Append ("\", \"");
					projSln.Append (asm.ShortName+"/"+ asm.ShortName + ".csproj");
					projSln.Append ("\", \"{");
					projSln.Append (createdProjGuid.ToString());
					projSln.Append ("}\"\n");
					projSln.Append("EndProject\n");

					globSec.Append ("   {"+createdProjGuid.ToString()+"}.Debug|Any CPU.ActiveCfg = Debug|Any CPU\n");
					globSec.Append ("   {"+createdProjGuid.ToString()+"}.Debug|Any CPU.Build.0 = Debug|Any CPU\n");
					globSec.Append ("   {"+createdProjGuid.ToString()+"}.Release|Any CPU.ActiveCfg = Release|Any CPU\n");
					globSec.Append ("   {"+createdProjGuid.ToString()+"}.Release|Any CPU.Build.0 = Release|Any CPU\n");
				}
				else
				{
					var ilLanguage = new ILLanguage(true);
					var textOutput = new PlainTextOutput ();
					ilLanguage.DecompileAssembly (asm, textOutput, decompilationOptions);
					string ilFileName = appPath + "/"+ asm.ShortName+".il";
					File.WriteAllText(ilFileName,textOutput.ToString());
				}

			}

			if (outLanguageType == LAN_TYPE_CSHARP) {
				projSln.Append ("Global\n");
				projSln.Append ("GlobalSection(SolutionConfigurationPlatforms) = preSolution\n");
				projSln.Append ("\t\t\t\tDebug|Any CPU = Debug|Any CPU\n");
				projSln.Append ("\t\t\t\tRelease|Any CPU = Release|Any CPU\n");
				projSln.Append ("EndGlobalSection\n");

				projSln.Append ("GlobalSection(ProjectConfigurationPlatforms) = postSolution\n");
				projSln.Append (globSec.ToString ());
				projSln.Append ("EndGlobalSection\n");

				projSln.Append ("GlobalSection(MonoDevelopProperties) = preSolution\n");
				projSln.Append ("\nEndGlobalSection\n");
				projSln.Append ("EndGlobal\n\t\t");

				string slnFileName = appPath + "/" + slnName + ".sln";
				File.WriteAllText (slnFileName, projSln.ToString ());
			}
		

		}