Inheritance: ITextOutput
Exemplo 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;
         }
     });
 }
Exemplo n.º 2
0
 public static string Disassemble(this MethodBody body)
 {
     var writer = new PlainTextOutput();
     var dasm = new MethodBodyDisassembler(writer);
     dasm.Disassemble(body);
     return writer.ToString();
 }
Exemplo n.º 3
0
        public void Execute(CommandExecutionContext context)
        {
            _context = context;
            _output = new PlainTextOutput();

            if (!String.IsNullOrEmpty(AssemblyName))
            {
                ClrModule module = context.Runtime.Modules.SingleOrDefault(
                    m => Path.GetFileNameWithoutExtension(m.FileName).Equals(
                        Path.GetFileNameWithoutExtension(AssemblyName),
                        StringComparison.InvariantCultureIgnoreCase
                        )
                    );
                if (module == null)
                {
                    context.WriteErrorLine("Could not find the assembly '{0}'.", AssemblyName);
                    return;
                }
                if (!String.IsNullOrEmpty(TypeName))
                {
                    DecompileTypeFromModule(TypeName, module.FileName);
                }
                else
                {
                    DecompileModule(module);
                }
            }
            else if (!String.IsNullOrEmpty(TypeName))
            {
                ClrType type = context.Heap.GetTypeByName(TypeName);
                if (type == null)
                {
                    context.WriteErrorLine(
                        "Could not find the type '{0}' on the heap. Try specifying the assembly name.",
                        TypeName);
                    return;
                }
                if (!String.IsNullOrEmpty(MethodName))
                {
                    var methods = type.Methods.Where(m => m.Name == MethodName).ToArray();
                    if (methods.Length == 0)
                    {
                        context.WriteErrorLine("Could not find the method '{0}'.", MethodName);
                        return;
                    }
                    DecompileMethods(methods);
                }
                else
                {
                    DecompileType(type);
                }
            }
            else
            {
                context.WriteErrorLine("At least one of --assembly or --type must be specified.");
            }
        }
Exemplo n.º 4
0
		UISyntaxHighlighter(bool highlight) {
			if (highlight) {
				this.simpleHighlighter = new SimpleHighlighter();
				this.output = null;
			}
			else {
				this.simpleHighlighter = null;
				this.output = new PlainTextOutput();
			}
		}
 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();
 }
Exemplo n.º 6
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);
        }
Exemplo n.º 7
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;
         }
     });
 }
Exemplo n.º 8
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;
		}
Exemplo n.º 9
0
        private string GetCSharpCode(IMemberDefinition member, bool debug)
        {
            PlainTextOutput output = new PlainTextOutput();
            CSharpLanguage csharp = new CSharpLanguage();
            DecompilationOptions options = new DecompilationOptions();
            options.DecompilerSettings = LoadDecompilerSettings();

            if (member is TypeDefinition)
            {
                DecomplieType(csharp, (TypeDefinition)member, output, options);
                return output.ToString();
            }
            else
            {
                MessageBox.Show("Not TypeDefinition");
            }
            return null;
        }
Exemplo n.º 10
0
        void Run(Config config)
        {
            if (config.ShowHelp) {
                Console.WriteLine ("Netjs compiler, Copyright 2014 Frank A. Krueger");
                Console.WriteLine ("netjs [options] assembly-file");
                return;
            }

            if (string.IsNullOrEmpty (config.MainAssembly)) {
                throw new Exception ("No assembly specified.");
            }

            var asmPath = Path.GetFullPath (config.MainAssembly);
            asmDir = Path.GetDirectoryName (asmPath);
            var outPath = Path.ChangeExtension (asmPath, ".ts");

            Step ("Reading IL");
            var parameters = new ReaderParameters {
                AssemblyResolver = this,
            };
            var asm = AssemblyDefinition.ReadAssembly (asmPath, parameters);
            mscorlib = AssemblyDefinition.ReadAssembly (typeof(String).Assembly.Location, parameters);
            system = AssemblyDefinition.ReadAssembly (typeof(INotifyPropertyChanged).Assembly.Location, parameters);
            systemCore = AssemblyDefinition.ReadAssembly (typeof(Enumerable).Assembly.Location, parameters);

            Step ("Decompiling IL to C#");
            var context = new DecompilerContext (asm.MainModule);
            context.Settings.ForEachStatement = false;
            context.Settings.ObjectOrCollectionInitializers = false;
            context.Settings.UsingStatement = false;
            context.Settings.AsyncAwait = false;
            context.Settings.AutomaticProperties = true;
            context.Settings.AutomaticEvents = true;
            context.Settings.QueryExpressions = false;
            context.Settings.AlwaysGenerateExceptionVariableForCatchBlocks = true;
            context.Settings.UsingDeclarations = false;
            context.Settings.FullyQualifyAmbiguousTypeNames = true;
            context.Settings.YieldReturn = false;
            var builder = new AstBuilder (context);
            builder.AddAssembly (asm);
            foreach (var a in referencedAssemblies.Values) {
                if (a != null)
                    builder.AddAssembly (a);
            }
            builder.RunTransformations ();

            Step ("Translating C# to TypeScript");
            new CsToTs ().Run (builder.SyntaxTree);

            Step ("Writing");
            using (var outputWriter = new StreamWriter (outPath)) {
                var output = new PlainTextOutput (outputWriter);
                builder.GenerateCode (output, (s, e) => new TsOutputVisitor (s, e));
            }

            Step ("Done");
        }
        public string getSourceCode(MethodDefinition methodDefinition)
        {
            try
            {
	            var csharpLanguage = new CSharpLanguage();
				var textOutput = new PlainTextOutput();
				var decompilationOptions = new DecompilationOptions();
 				decompilationOptions.FullDecompilation = true;
				csharpLanguage.DecompileMethod(methodDefinition, textOutput, decompilationOptions);
				return textOutput.ToString();
            	
             /*   ILanguage language = CSharp.GetLanguage(CSharpVersion.V1);
                language.GetWriter(new PlainTextFormatter(writer)).Write(method);
                MemoryStream stream = new MemoryStream();
                StreamWriter writer3 = new StreamWriter(stream);
                language.GetWriter(new PlainTextFormatter(writer3)).Write(method);
                stream.Flush();*/
                
            }
            catch (Exception exception)
            {
                PublicDI.log.error("in getSourceCode: {0}", new object[] { exception.Message });
                return ("Error in creating source code from IL: " + exception.Message);
            }
        }
		public string getSourceCode(TypeDefinition typeDefinition)
        {
            try
            {
	            var csharpLanguage = new CSharpLanguage();
				var textOutput = new PlainTextOutput();
				var decompilationOptions = new DecompilationOptions();
 				decompilationOptions.FullDecompilation = true;
				csharpLanguage.DecompileType(typeDefinition, textOutput, decompilationOptions);
				return textOutput.ToString();
			}
			catch (Exception exception)
            {
                PublicDI.log.error("in getSourceCode: {0}", new object[] { exception.Message });
                return ("Error in creating source code from Type: " + exception.Message);
            }
        }		
Exemplo n.º 13
0
		public bool Compile()
		{
			LogLine(1, "Compiling Xaml");
			LogLine(1, "\nAssembly: {0}", Assembly);
			if (!string.IsNullOrEmpty(DependencyPaths))
				LogLine(1, "DependencyPaths: \t{0}", DependencyPaths);
			if (!string.IsNullOrEmpty(ReferencePath))
				LogLine(1, "ReferencePath: \t{0}", ReferencePath.Replace("//", "/"));
			LogLine(3, "DebugSymbols:\"{0}\"", DebugSymbols);
			var skipassembly = true; //change this to false to enable XamlC by default
			bool success = true;

			if (!File.Exists(Assembly))
			{
				LogLine(1, "Assembly file not found. Skipping XamlC.");
				return true;
			}

			var resolver = new XamlCAssemblyResolver();
			if (!string.IsNullOrEmpty(DependencyPaths))
			{
				foreach (var dep in DependencyPaths.Split(';'))
				{
					LogLine(3, "Adding searchpath {0}", dep);
					resolver.AddSearchDirectory(dep);
				}
			}

			if (!string.IsNullOrEmpty(ReferencePath))
			{
				var paths = ReferencePath.Replace("//", "/").Split(';');
				foreach (var p in paths)
				{
					var searchpath = Path.GetDirectoryName(p);
					LogLine(3, "Adding searchpath {0}", searchpath);
					resolver.AddSearchDirectory(searchpath);
					//					LogLine (3, "Referencing {0}", p);
					//					resolver.AddAssembly (p);
				}
			}

			var assemblyDefinition = AssemblyDefinition.ReadAssembly(Path.GetFullPath(Assembly), new ReaderParameters
			{
				AssemblyResolver = resolver,
				ReadSymbols = DebugSymbols
			});

			CustomAttribute xamlcAttr;
			if (assemblyDefinition.HasCustomAttributes &&
			    (xamlcAttr =
				    assemblyDefinition.CustomAttributes.FirstOrDefault(
					    ca => ca.AttributeType.FullName == "Xamarin.Forms.Xaml.XamlCompilationAttribute")) != null)
			{
				var options = (XamlCompilationOptions)xamlcAttr.ConstructorArguments[0].Value;
				if ((options & XamlCompilationOptions.Skip) == XamlCompilationOptions.Skip)
					skipassembly = true;
				if ((options & XamlCompilationOptions.Compile) == XamlCompilationOptions.Compile)
					skipassembly = false;
			}

			foreach (var module in assemblyDefinition.Modules)
			{
				var skipmodule = skipassembly;
				if (module.HasCustomAttributes &&
				    (xamlcAttr =
					    module.CustomAttributes.FirstOrDefault(
						    ca => ca.AttributeType.FullName == "Xamarin.Forms.Xaml.XamlCompilationAttribute")) != null)
				{
					var options = (XamlCompilationOptions)xamlcAttr.ConstructorArguments[0].Value;
					if ((options & XamlCompilationOptions.Skip) == XamlCompilationOptions.Skip)
						skipmodule = true;
					if ((options & XamlCompilationOptions.Compile) == XamlCompilationOptions.Compile)
						skipmodule = false;
				}

				LogLine(2, " Module: {0}", module.Name);
				var resourcesToPrune = new List<EmbeddedResource>();
				foreach (var resource in module.Resources.OfType<EmbeddedResource>())
				{
					Log(2, "  Resource: {0}... ", resource.Name);
					string classname;
					if (!resource.IsXaml(out classname))
					{
						LogLine(2, "skipped.");
						continue;
					}
					TypeDefinition typeDef = module.GetType(classname);
					if (typeDef == null)
					{
						LogLine(2, "no type found... skipped.");
						continue;
					}
					var skiptype = skipmodule;
					if (typeDef.HasCustomAttributes &&
					    (xamlcAttr =
						    typeDef.CustomAttributes.FirstOrDefault(
							    ca => ca.AttributeType.FullName == "Xamarin.Forms.Xaml.XamlCompilationAttribute")) != null)
					{
						var options = (XamlCompilationOptions)xamlcAttr.ConstructorArguments[0].Value;
						if ((options & XamlCompilationOptions.Skip) == XamlCompilationOptions.Skip)
							skiptype = true;
						if ((options & XamlCompilationOptions.Compile) == XamlCompilationOptions.Compile)
							skiptype = false;
					}
					if (skiptype)
					{
						LogLine(2, "Has XamlCompilationAttribute set to Skip and not Compile... skipped");
						continue;
					}

					var initComp = typeDef.Methods.FirstOrDefault(md => md.Name == "InitializeComponent");
					if (initComp == null)
					{
						LogLine(2, "no InitializeComponent found... skipped.");
						continue;
					}
					LogLine(2, "");

					Log(2, "   Parsing Xaml... ");
					var rootnode = ParseXaml(resource.GetResourceStream(), typeDef);
					if (rootnode == null)
					{
						LogLine(2, "failed.");
						continue;
					}
					LogLine(2, "done.");

					hasCompiledXamlResources = true;

					try
					{
						Log(2, "   Replacing {0}.InitializeComponent ()... ", typeDef.Name);
						var body = new MethodBody(initComp);
						var il = body.GetILProcessor();
						il.Emit(OpCodes.Nop);
						var visitorContext = new ILContext(il, body);

						rootnode.Accept(new XamlNodeVisitor((node, parent) => node.Parent = parent), null);
						rootnode.Accept(new ExpandMarkupsVisitor(visitorContext), null);
						rootnode.Accept(new CreateObjectVisitor(visitorContext), null);
						rootnode.Accept(new SetNamescopesAndRegisterNamesVisitor(visitorContext), null);
						rootnode.Accept(new SetFieldVisitor(visitorContext), null);
						rootnode.Accept(new SetResourcesVisitor(visitorContext), null);
						rootnode.Accept(new SetPropertiesVisitor(visitorContext, true), null);

						il.Emit(OpCodes.Ret);
						initComp.Body = body;
					}
					catch (XamlParseException xpe)
					{
						LogLine(2, "failed.");
						LogError(null, null, null, resource.Name, xpe.XmlInfo.LineNumber, xpe.XmlInfo.LinePosition, 0, 0, xpe.Message,
							xpe.HelpLink, xpe.Source);
						LogLine(4, xpe.StackTrace);
						success = false;
						continue;
					}
					catch (XmlException xe)
					{
						LogLine(2, "failed.");
						LogError(null, null, null, resource.Name, xe.LineNumber, xe.LinePosition, 0, 0, xe.Message, xe.HelpLink, xe.Source);
						LogLine(4, xe.StackTrace);
						success = false;
						continue;
					}
					catch (Exception e)
					{
						LogLine(2, "failed.");
						LogError(null, null, null, resource.Name, 0, 0, 0, 0, e.Message, e.HelpLink, e.Source);
						LogLine(4, e.StackTrace);
						success = false;
						continue;
					}
					LogLine(2, "done.");

					if (OptimizeIL)
					{
						Log(2, "   Optimizing IL... ");
						initComp.Body.OptimizeMacros();
						LogLine(2, "done");
					}

					if (OutputGeneratedILAsCode)
					{
						var filepath = Path.Combine(Path.GetDirectoryName(Assembly), typeDef.FullName + ".decompiled.cs");
						Log(2, "   Decompiling {0} into {1}...", typeDef.FullName, filepath);
						var decompilerContext = new DecompilerContext(module);
						using (var writer = new StreamWriter(filepath))
						{
							var output = new PlainTextOutput(writer);

							var codeDomBuilder = new AstBuilder(decompilerContext);
							codeDomBuilder.AddType(typeDef);
							codeDomBuilder.GenerateCode(output);
						}

						LogLine(2, "done");
					}
					resourcesToPrune.Add(resource);
				}
				if (!KeepXamlResources)
				{
					if (resourcesToPrune.Any())
						LogLine(2, "  Removing compiled xaml resources");
					foreach (var resource in resourcesToPrune)
					{
						Log(2, "   Removing {0}... ", resource.Name);
						module.Resources.Remove(resource);
						LogLine(2, "done");
					}
				}

				LogLine(2, "");
			}

			if (!hasCompiledXamlResources)
			{
				LogLine(1, "No compiled resources. Skipping writing assembly.");
				return success;
			}

			Log(1, "Writing the assembly... ");
			try
			{
				assemblyDefinition.Write(Assembly, new WriterParameters
				{
					WriteSymbols = DebugSymbols
				});
				LogLine(1, "done.");
			}
			catch (Exception e)
			{
				LogLine(1, "failed.");
				LogError(null, null, null, null, 0, 0, 0, 0, e.Message, e.HelpLink, e.Source);
				LogLine(4, e.StackTrace);
				success = false;
			}

			return success;
		}
Exemplo n.º 14
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 ());
			}
		

		}
Exemplo n.º 15
0
		public override string TypeToString(TypeReference t, bool includeNamespace, ICustomAttributeProvider attributeProvider = null)
		{
			PlainTextOutput output = new PlainTextOutput();
			t.WriteTo(output, includeNamespace ? ILNameSyntax.TypeName : ILNameSyntax.ShortTypeName);
			return output.ToString();
		}
Exemplo n.º 16
0
        private static CudafyModule DoCudafy(CudafyModule cm, params Type[] types)
        {
            MemoryStream output = new MemoryStream();
            var outputSw = new StreamWriter(output);
            
            MemoryStream structs = new MemoryStream();
            var structsSw = new StreamWriter(structs);
            var structsPto = new PlainTextOutput(structsSw);
            
            MemoryStream declarations = new MemoryStream();
            var declarationsSw = new StreamWriter(declarations);
            var declarationsPto = new PlainTextOutput(declarationsSw);

            MemoryStream code = new MemoryStream();
            var codeSw = new StreamWriter(code);
            var codePto = new PlainTextOutput(codeSw);

            bool isDummy = false;
            eCudafyDummyBehaviour behaviour = eCudafyDummyBehaviour.Default;

            Dictionary<string, ModuleDefinition> modules = new Dictionary<string,ModuleDefinition>();

            var compOpts = new DecompilationOptions { FullDecompilation = true };

            CUDALanguage.Reset();
            bool firstPass = true;
            if(cm == null)
                cm = new CudafyModule();// #######!!!
            else
                firstPass = false;
            
            // Test structs
            //foreach (var strct in types.Where(t => !t.IsClass))
            //    if (strct.GetCustomAttributes(typeof(CudafyAttribute), false).Length == 0)
            //        throw new CudafyLanguageException(CudafyLanguageException.csCUDAFY_ATTRIBUTE_IS_MISSING_ON_X, strct.Name);

            IEnumerable<Type> typeList = GetWithNestedTypes(types);
            foreach (var type in typeList)
            {
                if(!modules.ContainsKey(type.Assembly.Location))
                    modules.Add(type.Assembly.Location, ModuleDefinition.ReadModule(type.Assembly.Location));                
            }
            
            // Additional loop to compile in order
            foreach (var requestedType in typeList)
            {
                foreach (var kvp in modules)
                {
                    foreach (var td in kvp.Value.Types)
                    {
                        List<TypeDefinition> tdList = new List<TypeDefinition>();
                        tdList.Add(td);
                        tdList.AddRange(td.NestedTypes);

                        Type type = null;
                        foreach (var t in tdList)
                        {
                            //type = typeList.Where(tt => tt.FullName.Replace("+", "") == t.FullName.Replace("/", "")).FirstOrDefault();
                            // Only select type if this matches the requested type (to ensure order is maintained).
                            type = requestedType.FullName.Replace("+", "") == t.FullName.Replace("/", "") ? requestedType : null;

                            if (type == null)
                                continue;
                            Debug.WriteLine(t.FullName);
                            // Types                      
                            var attr = t.GetCudafyType(out isDummy, out behaviour);
                            if (attr != null)
                            {
                                _cl.DecompileType(t, structsPto, compOpts);
                                if (firstPass)
                                    cm.Types.Add(type.FullName.Replace("+", ""), new KernelTypeInfo(type, isDummy, behaviour));// #######!!!
                            }
                            else if (t.Name == td.Name)
                            {
                                // Fields
                                foreach (var fi in td.Fields)
                                {
                                    attr = fi.GetCudafyType(out isDummy, out behaviour);
                                    if (attr != null)
                                    {
                                        VerifyMemberName(fi.Name);
                                        System.Reflection.FieldInfo fieldInfo = type.GetField(fi.Name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                                        if (fieldInfo == null)
                                            throw new CudafyLanguageException(CudafyLanguageException.csX_ARE_NOT_SUPPORTED, "Non-static fields");
                                        int[] dims = _cl.GetFieldInfoDimensions(fieldInfo);
                                        _cl.DecompileCUDAConstantField(fi, dims, codePto, compOpts);
                                        var kci = new KernelConstantInfo(fi.Name, fieldInfo, isDummy);
                                        if (firstPass)
                                            cm.Constants.Add(fi.Name, kci);// #######!!!
                                        CUDALanguage.AddConstant(kci);
                                    }
                                }
#warning TODO Only Global Methods can be called from host
#warning TODO For OpenCL may need to do Methods once all Constants have been handled
                                // Methods
                                foreach (var med in td.Methods)
                                {
                                    attr = med.GetCudafyType(out isDummy, out behaviour);
                                    if (attr != null)
                                    {
                                        if (!med.IsStatic)
                                            throw new CudafyLanguageException(CudafyLanguageException.csX_ARE_NOT_SUPPORTED, "Non-static methods");
                                        _cl.DecompileMethodDeclaration(med, declarationsPto, new DecompilationOptions { FullDecompilation = false });
                                        _cl.DecompileMethod(med, codePto, compOpts);
                                        MethodInfo mi = type.GetMethod(med.Name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
                                        if (mi == null)
                                            continue;
                                        VerifyMemberName(med.Name);
                                        eKernelMethodType kmt = eKernelMethodType.Device;
                                        kmt = GetKernelMethodType(attr, mi);
                                        if (firstPass)
                                            cm.Functions.Add(med.Name, new KernelMethodInfo(type, mi, kmt, isDummy, behaviour, cm));// #######!!!
                                    }
                                }
                            }
                        }
                    }
                }
            }

            codeSw.Flush();

            if (CudafyTranslator.Language == eLanguage.OpenCL)
            {
                outputSw.WriteLine("#if defined(cl_khr_fp64)");
                outputSw.WriteLine("#pragma OPENCL EXTENSION cl_khr_fp64: enable");
                outputSw.WriteLine("#elif defined(cl_amd_fp64)");
                outputSw.WriteLine("#pragma OPENCL EXTENSION cl_amd_fp64: enable");
                outputSw.WriteLine("#endif");
            }

            foreach (var oh in CUDALanguage.OptionalHeaders)
            {
                if (oh.Used && !oh.AsResource)
                    outputSw.WriteLine(oh.IncludeLine);
                else if (oh.Used)
                    outputSw.WriteLine(GetResourceString(oh.IncludeLine));
            }
            foreach (var oh in CUDALanguage.OptionalFunctions)
            {
                if (oh.Used)
                    outputSw.WriteLine(oh.Code);
            }

            declarationsSw.WriteLine();
            declarationsSw.Flush();

            structsSw.WriteLine();
            structsSw.Flush();

            foreach (var def in cm.GetDummyDefines())
                outputSw.WriteLine(def);
            foreach (var inc in cm.GetDummyStructIncludes())
                outputSw.WriteLine(inc);
            foreach (var inc in cm.GetDummyIncludes())
                outputSw.WriteLine(inc);
            outputSw.Flush();

            output.Write(structs.GetBuffer(), 0, (int)structs.Length);
            output.Write(declarations.GetBuffer(), 0, (int)declarations.Length);
            output.Write(code.GetBuffer(), 0, (int)code.Length);
            outputSw.Flush();
#if DEBUG
            using (FileStream fs = new FileStream("output.cu", FileMode.Create))
            {
                fs.Write(output.GetBuffer(), 0, (int)output.Length);
            }
#endif
            String s = Encoding.UTF8.GetString(output.GetBuffer(), 0, (int)output.Length);
            //cm.SourceCode = s;// #######!!!
            var scf = new SourceCodeFile(s, Language, _architecture);
            cm.AddSourceCodeFile(scf);
            return cm;
        }
Exemplo n.º 17
0
 public override string TypeToString(TypeReference t)
 {
     PlainTextOutput output = new PlainTextOutput();
     t.WriteTo(output, true, true);
     return output.ToString();
 }
Exemplo n.º 18
0
        void Run(Config config)
        {
            if (config.AssembliesToDecompile.Count == 0) {
                config.ShowHelp = true;
            }

            if (config.ShowHelp) {
                Console.WriteLine ("Netjs compiler, Copyright 2014-2016 Frank A. Krueger");
                Console.WriteLine ("netjs [options] assembly-files");
                Console.WriteLine ("   --help, -h           Show usage information");
                Console.WriteLine ("   --includerefs, -r    Decompile referenced assemblies");
                return;
            }

            string outPath = "";
            var asmPaths = new List<string> ();

            foreach (var asmRelPath in config.AssembliesToDecompile) {
                var asmPath = Path.GetFullPath (asmRelPath);
                asmPaths.Add (asmPath);

                if (string.IsNullOrEmpty (outPath)) {
                    outPath = Path.ChangeExtension (asmPath, ".ts");
                }

                var asmDir = Path.GetDirectoryName (asmPath);
                if (!asmSearchPaths.Exists (x => x.Item1 == asmDir)) {
                    asmSearchPaths.Add (Tuple.Create (asmDir, config.IncludeRefs));
                }
            }

            Step ("Reading IL");
            globalReaderParameters.AssemblyResolver = this;
            globalReaderParameters.ReadingMode = ReadingMode.Immediate;

            var libDir = Path.GetDirectoryName (typeof (String).Assembly.Location);
            asmSearchPaths.Add (Tuple.Create(libDir, false));
            asmSearchPaths.Add (Tuple.Create(Path.Combine (libDir, "Facades"), false));

            AssemblyDefinition firstAsm = null;
            foreach (var asmPath in asmPaths) {
                var asm = AssemblyDefinition.ReadAssembly (asmPath, globalReaderParameters);
                if (firstAsm == null)
                    firstAsm = asm;
                referencedAssemblies[asm.Name.Name] = asm;
                decompileAssemblies.Add (asm);
            }

            Step ("Decompiling IL to C#");
            var context = new DecompilerContext (firstAsm.MainModule);
            context.Settings.ForEachStatement = false;
            context.Settings.ObjectOrCollectionInitializers = false;
            context.Settings.UsingStatement = false;
            context.Settings.AsyncAwait = false;
            context.Settings.AutomaticProperties = true;
            context.Settings.AutomaticEvents = true;
            context.Settings.QueryExpressions = false;
            context.Settings.AlwaysGenerateExceptionVariableForCatchBlocks = true;
            context.Settings.UsingDeclarations = false;
            context.Settings.FullyQualifyAmbiguousTypeNames = true;
            context.Settings.YieldReturn = false;
            var builder = new AstBuilder (context);
            var decompiled = new HashSet<string> ();
            for (;;) {
                var a = decompileAssemblies.FirstOrDefault (x => !decompiled.Contains (x.FullName));
                if (a != null) {
                    Info ("  Decompiling {0}", a.FullName);
                    builder.AddAssembly (a);
                    decompiled.Add (a.FullName);
                }
                else {
                    break;
                }
            }
            builder.RunTransformations ();

            Step ("Translating C# to TypeScript");
            new CsToTs ().Run (builder.SyntaxTree);

            Step ("Writing");
            using (var outputWriter = new StreamWriter (outPath)) {
                var output = new PlainTextOutput (outputWriter);
                builder.GenerateCode (output, (s, e) => new TsOutputVisitor (s, e));
            }

            Step ("Done");
        }
Exemplo n.º 19
0
 public override string TypeToString(TypeReference t, bool includeNamespace, ICustomAttributeProvider attributeProvider)
 {
     PlainTextOutput output = new PlainTextOutput();
     t.WriteTo(output, true, shortName: !includeNamespace);
     return output.ToString();
 }
Exemplo n.º 20
0
		/// <summary>
		/// Converts a type reference into a string. This method is used by the member tree node for parameter and return types.
		/// </summary>
		public string TypeToString(ITypeDefOrRef type, bool includeNamespace, IHasCustomAttribute typeAttributes = null)
		{
			var writer = new StringWriter();
			var output = new PlainTextOutput(writer);
			TypeToString(output, type, includeNamespace, typeAttributes);
			return writer.ToString();
		}
Exemplo n.º 21
0
		private void SetupDecompilerAndOriginalSource(MethodDefinition method)
		{
			_cSharpDecompiler = new CSharpLanguage();
            var decompilationOutput = new PlainTextOutput();
            _decompilationOptions = new DecompilationOptions();
            _cSharpDecompiler.DecompileMethod(method, decompilationOutput, _decompilationOptions);
            _oldText = decompilationOutput.ToString();
            _differ = new SideBySideDiffBuilder(new Differ());
		}
Exemplo n.º 22
0
		public string ToString(Language language)
		{
			var output = new PlainTextOutput();
			Write(output, language);
			return output.ToString();
		}
Exemplo n.º 23
0
 private string ConstructEstimateCodeDiff(MethodDefinition method)
 {
     var decompilationOutput = new PlainTextOutput();
     try
     {
         _cSharpDecompiler.DecompileMethod(method, decompilationOutput, _decompilationOptions);
     }
     catch
     {
         return "\t\tNo decompilation available for mutated version.\n";
     }
     string newText = decompilationOutput.ToString();
     var model = _differ.BuildDiffModel(_oldText, newText);
     string diffOutput = "\t\tApproximate source code difference from IL decompilation:\n";
     var lines = new SortedSet<int>();
     for (int i = 0; i < Math.Max(model.OldText.Lines.Count, model.NewText.Lines.Count); i++)
     {
         if ((i < model.OldText.Lines.Count && model.OldText.Lines[i].Type != ChangeType.Unchanged)
             || (i < model.NewText.Lines.Count && model.NewText.Lines[i].Type != ChangeType.Unchanged))
         {
             lines.Add(i - 2);
             lines.Add(i - 1);
             lines.Add(i);
             lines.Add(i + 1);
             lines.Add(i + 2);
         }
     }
     int lastLine = -1;
     string adds = "";
     string takes = "";
     foreach (var line in lines)
     {
         if (line < 0) continue;
         if (line > lastLine + 1)
         {
             diffOutput += string.Format("{1}{2}\t\t@@ {0} @@\n", line,
                 takes, adds);
             takes = "";
             adds = "";
         }
         if (line < model.OldText.Lines.Count)
         {
             takes += string.Format("\t\t- {0}\n",
                 (model.OldText.Lines[line].Text ?? "").Replace("\t", "  "));
         }
         if (line < model.NewText.Lines.Count)
         {
             adds += string.Format("\t\t+ {0}\n",
                 (model.NewText.Lines[line].Text ?? "").Replace("\t", "  "));
         }
         lastLine = line;
     }
     if (!string.IsNullOrEmpty(adds) || !string.IsNullOrEmpty(takes))
     {
         diffOutput += takes + adds;
     }
     return diffOutput;
 }
Exemplo n.º 24
-1
        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();
        }