Inheritance: ICustomAttributeProvider, ISecurityDeclarationProvider
Exemple #1
0
        public void Start(string assemblyFilename)
        {
            // TODO: Current assembly is not (and probably should not be?) used
            // later. Instead use methodHashes and methodBodies to see which
            // methods should be replaced.
            currentAssembly = Cecil.AssemblyDefinition.ReadAssembly(assemblyFilename);

            bool instrumented = IsInstruemnted(currentAssembly);

            InitialLoadSignatures();

            if (!instrumented)
            {
                //Load assembly again, instrument, save and let unity use it
                var asmToInstrument = Cecil.AssemblyDefinition.ReadAssembly(assemblyFilename);
                Instrument.InstrumentAssembly(asmToInstrument);
                asmToInstrument.Write(assemblyFilename);

                Debug.Log("HotPatcher: Assembly instrumented.");
            }
            else
            {
                Debug.Log("HotPatcher: Assembly was already instrumented.");
            }
        }
        /// <summary>
        /// Discovers the tests in the Assembly.
        /// </summary>
        /// <param name="dllPath">The path to the DLL.</param>
        /// <param name="assembly">The loaded Assembly.</param>
        /// <returns>Tests in the Assembly</returns>
        protected override List<TestClass> DiscoverTestsInAssembly(string dll, AssemblyDefinition assembly)
        {
            var classes2 = new List<TestClass>();
            foreach (var type in assembly.MainModule.Types)
            {
                bool isMSTest = false;

                try
                {
                    var customAttributes = type.CustomAttributes;
                    if (customAttributes != null)
                    {
                        isMSTest = customAttributes.Any(attribute => attribute.AttributeType.FullName == typeof(TestClassAttribute).FullName);
                    }
                }
                catch { }

                if (isMSTest)
                {
                    var TestClass = new TestClass
                    {
                        DLLPath = dll,
                        Name = type.Name,
                        Namespace = type.Namespace,
                        TestType = TestType.MSTest
                    };

                    TestClass.TestMethods = DiscoverTestsInClass(type, TestClass);
                    classes2.Add(TestClass);
                }
            }
            return classes2;
        }
Exemple #3
0
        public void Init()
        {
            CurrentAssembly = CecilExtensions.CurrentAssembly;
            ThisType        = CurrentAssembly.FindRuntimeType(GetType());

            Recompiler = new ILDynaRec.Recompiler();
        }
		public AssemblyTypeInfoGenerator(string assembly, string[] searchDirs)
		{
			this.assembly_ = AssemblyDefinition.ReadAssembly(assembly, new ReaderParameters
			{
				AssemblyResolver = AssemblyTypeInfoGenerator.AssemblyResolver.WithSearchDirs(searchDirs)
			});
		}
 public Tuple<TypeDefinition, AssemblyDefinition> this[TypeReference typ, AssemblyDefinition assembly]
 {
     get
       {
     return this[typ, assembly.Name];
       }
 }
        public bool Process(AssemblyDefinition def)
        {
            foreach (var type in def.MainModule.Types)
                ProcessType(def, type);

            return true;
        }
Exemple #7
0
        public JSAssembly(AssemblyDefinition assembly)
        {
            if (assembly == null)
                throw new ArgumentNullException("assembly");

            Assembly = assembly;
        }
Exemple #8
0
		public static Instruction FindInstruction(AssemblyDefinition assembly, string typeName, string testMethodName, OpCode testInstruction)
		{
			MethodDefinition testMethod = FindMethod(assembly, typeName, testMethodName);
			Assert.IsNotNull(testMethod);

			return FindInstruction(testMethod, testInstruction);
		}
		public BaseMergeReflectionVisitor (MergeContext context, AssemblyDefinition target, AssemblyDefinition source)
		{
			this.context = context;
			this.target = target;
			this.source = source;
			module = target.MainModule;
		}
Exemple #10
0
        public void Init()
        {
            CurrentAssembly = Cecil.AssemblyDefinition.ReadAssembly(Reflection.Assembly.GetExecutingAssembly().Location);
            ThisType        = CurrentAssembly.FindRuntimeType(GetType());

            Recompiler = new ILDynaRec.Recompiler();
        }
Exemple #11
0
        public void LoadAssemblies()
        {
            /**
             * We first load the PhiScript assembly containing the static
             * methods that must be called
             */
            if (File.Exists(this.PhiAssemblyPath))
            {
                try
                {
                    this.PhiAssembly = AssemblyDefinition.ReadAssembly(this.PhiAssemblyPath);
                }
                catch (FileNotFoundException)
                {
                    Console.WriteLine("Can't find file " + this.PhiAssemblyPath);
                    Console.Read();
                    return;
                }
                catch
                {
                    Console.WriteLine("Couldn't load " + this.PhiAssemblyPath);
                    Console.Read();
                    return;
                }

                ModuleDefinition phiModule = this.PhiAssembly.MainModule;
            }

            /**
             * We then load the Assembly-CSharp assembly that contains the
             * vanilla code
             * If it is the first use, we read Assembly-CSharp.dll, but if it is
             * not we read Assembly-CSharp.original.dll
             */
            try
            {
                if (this.AlreadyPatched)
                {
                    this.CSharpAssembly = AssemblyDefinition.ReadAssembly(this.MovedAssemblyPath);
                }
                else
                {
                    this.CSharpAssembly = AssemblyDefinition.ReadAssembly(this.AssemblyPath);
                }
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine("Can't find file " + this.AssemblyPath);
                Console.Read();
                return;
            }
            catch
            {
                Console.WriteLine("Couldn't load " + this.AssemblyPath);
                Console.Read();
                return;
            }

            this.CSharpModule = this.CSharpAssembly.MainModule;
        }
        public static Cecil.TypeDefinition FindRuntimeType(
            this Cecil.AssemblyDefinition assembly, Type runtimeType)
        {
            var typename = runtimeType.FullName.Replace('+', '/');

            return(assembly.IterateTypes().FirstOrDefault(type => type.FullName == typename));
        }
        private AssemblyDefinition ResolveInternal(string refName, Version minVersion, ReaderParameters parameters)
        {
            if (KnownAssemblies.TryGetValue(refName, out var loadedAsms))
            {
                var loadedAsm = loadedAsms.First(asm => asm.GetName().Version >= minVersion);
                var path      = new Uri(loadedAsm.CodeBase).LocalPath;
                if (File.Exists(path))
                {
                    return(parameters == null
                                                ? AssemblyDefinition.ReadAssembly(path, new ReaderParameters { AssemblyResolver = this })
                                                : AssemblyDefinition.ReadAssembly(path, parameters));
                }
            }
            try {
                var newlyLoadedAsm = Assembly.Load(new AssemblyName(refName));
                AddNewKnownAssembly(newlyLoadedAsm);

                var path = new Uri(newlyLoadedAsm.CodeBase).LocalPath;
                if (!File.Exists(path))
                {
                    throw new DllNotFoundException($"Could not locate {refName}");
                }

                return(parameters == null
                                        ? AssemblyDefinition.ReadAssembly(path)
                                        : AssemblyDefinition.ReadAssembly(path, parameters));
            }
            catch {
                throw new DllNotFoundException($"Could not resolve {refName}");
            }
        }
        public override void Process(Instrumentor instrumentor, Mono.Cecil.AssemblyDefinition assdef)
        {
            //Lets find some stuff
            var module = assdef.MainModule;

            //Stage 1: Acquiring vanilla enum index
            foreach (var typedef in module.Types)
            {
                if (typedef.Name == "StaticPrefabType")
                {
                    foreach (var fieldef in typedef.Fields)
                    {
                        if (fieldef.Name == "value__")
                        {
                            continue;
                        }
                        string val = fieldef.Name.Replace("_", "").ToUpperInvariant();
                        int    key = (int)fieldef.Constant;//No idea if this will work, derp ^_^
                        _enumIndex.Add(key, val);
                    }
                }
            }
            //Stage 2: Collecting index
            foreach (var typedef in module.Types)
            {
                if (typedef.Name == "StaticPrefab")
                {
                    var           instantiator = FindEntryToInstantiator(typedef);
                    List <String> typelist     = CollectAllCTORCalls(instantiator);
                    instrumentor.Workspace.SaveAllLines(typelist.ToArray(), "vanillaprojects");
                    return;//No need to look for others
                }
            }
            throw new InstrumentationFailureException("SP Registry type is unreachable!");
        }
Exemple #15
0
        public override void DecompileAssembly(AssemblyDefinition assembly, string fileName, ITextOutput output, DecompilationOptions options)
        {
            output.WriteLine("// " + fileName);
            output.WriteLine();

            new ReflectionDisassembler(output, detectControlStructure, options.CancellationToken).WriteAssemblyHeader(assembly);
        }
Exemple #16
0
		void SweepAssembly (AssemblyDefinition assembly)
		{
			if (Annotations.GetAction (assembly) != AssemblyAction.Link)
				return;

			if (!IsMarkedAssembly (assembly)) {
				RemoveAssembly (assembly);
				return;
			}

			var types = new List<TypeDefinition> ();

			foreach (TypeDefinition type in assembly.MainModule.Types) {
				if (Annotations.IsMarked (type)) {
					SweepType (type);
					types.Add (type);
					continue;
				}

				if (type.Name == "<Module>")
					types.Add (type);
			}

			assembly.MainModule.Types.Clear ();
			foreach (TypeDefinition type in types)
				assembly.MainModule.Types.Add (type);
		}
Exemple #17
0
        /// <summary>
        ///  Load assemblyname
        /// </summary>
        private void LoadAsmOrigin()
        {
            try
            {
                LoadAssembly = AssemblyDefinition.ReadAssembly(selectedFilename);

                richTextBox_AssemblyInfo.Clear();

                richTextBox_AssemblyInfo.AppendText(Environment.NewLine);
                richTextBox_AssemblyInfo.AppendText(Environment.NewLine);
                richTextBox_AssemblyInfo.AppendText("[Name]::" + LoadAssembly.MainModule.Name.ToString() + Environment.NewLine);
                richTextBox_AssemblyInfo.AppendText("[CLR Runtime]::" + LoadAssembly.MainModule.Runtime.ToString() + Environment.NewLine);
                richTextBox_AssemblyInfo.AppendText("[Full Name]::" + LoadAssembly.MainModule.FullyQualifiedName.ToString() + Environment.NewLine);
                richTextBox_AssemblyInfo.AppendText("[Metadata Token]::" + LoadAssembly.MainModule.MetadataToken.ToString() + Environment.NewLine);
                richTextBox_AssemblyInfo.AppendText("[Architecture]::" + LoadAssembly.MainModule.Architecture.ToString() + Environment.NewLine);
                richTextBox_AssemblyInfo.AppendText("[EntryPoint]::" + LoadAssembly.MainModule.EntryPoint.ToString() + Environment.NewLine);
                richTextBox_AssemblyInfo.AppendText("[Mvid]::" + LoadAssembly.MainModule.Mvid.ToString() + Environment.NewLine);
            }
            catch
            {
                //ResetData();
                MessageBox.Show("Couldn't Read Assembly, it is either Unmanaged or obfuscated");
                status = true;
                return;
            }
        }
 private void Rewrite(AssemblyDefinition assemblyDefinition)
 {
     foreach (ModuleDefinition moduleDefinition in assemblyDefinition.Modules)
     {
         Rewrite(moduleDefinition);
     }
 }
Exemple #19
0
        public static MethodDefinition FindDecryptor(AssemblyDefinition asmDef)
        {
            foreach (var modDef in asmDef.Modules)
                foreach (var typeDef in modDef.Types)
                    foreach (var mDef in typeDef.Methods)
                    {
                        var signature = new ILSignature
                                            {
                                                Start = 1,
                                                StartOpCode = OpCodes.Nop,
                                                Instructions = new List<OpCode>
                                                                   {
                                                                       OpCodes.Callvirt,
                                                                       OpCodes.Stloc_0,
                                                                       OpCodes.Ldloc_0,
                                                                       OpCodes.Newarr,
                                                                       OpCodes.Stloc_1,
                                                                       OpCodes.Ldc_I4_0,
                                                                       OpCodes.Stloc_2
                                                                   }
                                            };

                        if (mDef.HasBody) {
                            if (SignatureFinder.IsMatch(mDef, signature))
                                return mDef;
                        }
                    }

            return null;
        }
    public static void SetHook(
        HookType hookType,
        AssemblyDefinition targetAssembly, string targetTypeName, string targetMethodName,
        AssemblyDefinition calleeAssembly, string calleeTypeName, string calleeMethodName)
    {
#if DEBUG
        Console.WriteLine("SetHook - {0}/{1}|{2} -> {3}/{4}|{5}", targetAssembly.Name.Name, targetTypeName, targetMethodName, calleeAssembly.Name.Name, calleeTypeName, calleeMethodName);
#endif
        TypeDefinition calleeTypeDefinition = calleeAssembly.MainModule.GetType(calleeTypeName);
        if (calleeTypeDefinition == null)
        {
            throw new Exception(string.Format("Error ({0}) : {1} is not found", calleeAssembly.Name, calleeTypeName));
        }

        MethodDefinition calleeMethod = GetMethod(calleeTypeDefinition, calleeMethodName);
        if (calleeMethod == null)
        {
            throw new Exception(string.Format("Error ({0}) : {1}.{2} is not found", calleeAssembly.Name, calleeTypeName, calleeMethodName));
        }

        TypeDefinition targetTypeDefinition = targetAssembly.MainModule.GetType(targetTypeName);
        if (targetTypeDefinition == null)
        {
            throw new Exception(string.Format("Error ({0}) : {1} is not found", targetAssembly.Name, targetTypeName));
        }

        MethodDefinition targetMethod = GetMethod(targetTypeDefinition, targetMethodName);
        if (targetMethod == null)
        {
            throw new Exception(string.Format("Error ({0}) : {1}.{2} is not found", targetAssembly.Name, targetTypeName, targetMethodName));
        }
        HookMethod(hookType, targetAssembly.MainModule, targetMethod, calleeMethod);
    }
Exemple #21
0
        public static byte[] Patch(byte[] code)
        {
            var contractAsmDef = AssemblyDefinition.ReadAssembly(new MemoryStream(code));

            // Get the specific version of the SDK referenced by the contract
            var nameRefSdk = contractAsmDef.MainModule.AssemblyReferences.Single(r => r.Name == Sdk);

            // May cache all versions not to keep reloading for every contract deployment
            var refSdk = AssemblyDefinition.ReadAssembly(Assembly.Load(nameRefSdk.FullName).Location);

            // Get the type definitions mapped for target methods from SDK
            var sdkTypes    = TargetMethods.Select(kv => kv.Value).Distinct();
            var sdkTypeDefs = sdkTypes
                              .Select(t => contractAsmDef.MainModule.ImportReference(refSdk.MainModule.GetType(t)).Resolve())
                              .ToDictionary(def => def.FullName);

            // Patch the types
            foreach (var typ in contractAsmDef.MainModule.Types)
            {
                PatchType(contractAsmDef, typ, sdkTypeDefs);
            }

            var newCode = new MemoryStream();

            contractAsmDef.Write(newCode);
            return(newCode.ToArray());
        }
        private IEnumerable<Change> Compare(AssemblyDefinition source, AssemblyDefinition target)
        {
            var sourceTypes = GetPublicTypes(source);
            var targetTypes = GetPublicTypes(target);

            // First detect all new types in the newer assembly.
            var addedTypes = targetTypes.Except(sourceTypes, CecilComparer.TypeByFullName).ToList();
            foreach (var addedType in addedTypes)
                yield return new TypeChange(ChangeType.TypeAdded, ChangeCategory.NonBreaking, CompatibilityLevel.Binary, addedType);
            targetTypes.RemoveAll(addedTypes);

            // Now detect all removed types in the newer assembly.
            var removedTypes = sourceTypes.Except(targetTypes, CecilComparer.TypeByFullName).ToList();
            foreach (var removedType in removedTypes)
                yield return new TypeChange(ChangeType.TypeRemoved, ChangeCategory.Breaking, CompatibilityLevel.None, removedType);
            sourceTypes.RemoveAll(removedTypes);

            // We have now reduced the input to the types that occur in both assemblies, now we will need
            // to compare those one by one...
            foreach (var targetType in targetTypes)
            {
                var sourceType = sourceTypes.Single(t => CecilComparer.TypeByFullName.Equals(t, targetType));
                TypeComparer comparer = new TypeComparer();
                foreach (var change in comparer.Compare(sourceType, targetType))
                    yield return change;
            }
        }
		protected override void ProcessAssembly (AssemblyDefinition assembly)
		{
			if (Annotations.GetAction (assembly) != AssemblyAction.Link)
				return;

			ProcessTypes (assembly.MainModule.Types);
		}
        private static IList <Tuple <IUnresolvedAssembly, IList <string>, Assembly> > LoadReferences(IEnumerable <string> references, IErrorReporter er)
        {
            var loader = new CecilLoader {
                IncludeInternalMembers = true
            };
            var assemblies = references.Select(r => AssemblyDefinition.ReadAssembly(r)).ToList();             // Shouldn't result in errors because mcs would have caught it.

            var indirectReferences = (from a in assemblies
                                      from m in a.Modules
                                      from r in m.AssemblyReferences
                                      select r.Name)
                                     .Distinct();

            var directReferences = from a in assemblies select a.Name.Name;

            var missingReferences = indirectReferences.Except(directReferences).ToList();

            if (missingReferences.Count > 0)
            {
                er.Region = DomRegion.Empty;
                foreach (var r in missingReferences)
                {
                    er.Message(Messages._7996, r);
                }
                return(null);
            }

            return(assemblies.Select(asm => Tuple.Create(loader.LoadAssembly(asm), GetReferencedAssemblyNames(asm), LoadPlugin(asm))).ToList());
        }
Exemple #25
0
        private SourceFile(IApkFile apk, JarFile jar, ISpySettings settings, MapFileLookup mapFile, string singleFilePath = null)
        {
            this.apk = apk;
            this.jar = jar;
            this.settings = settings;
            this.mapFile = mapFile;
            this.singleFilePath = singleFilePath;

#if DEBUG  || ENABLE_SHOW_AST
            classLoader = new AssemblyClassLoader(module.OnClassLoaded);
            var modParams = new ModuleParameters
            {
                AssemblyResolver = new AssemblyResolver(new[] { Frameworks.Instance.FirstOrDefault().Folder }, classLoader, module.OnAssemblyLoaded),
                Kind = ModuleKind.Dll
            };
            assembly = AssemblyDefinition.CreateAssembly(new AssemblyNameDefinition("spy", Version.Parse("1.0.0.0")), "main", modParams);
            classLoader.LoadAssembly(assembly);

            var dot42Assembly = modParams.AssemblyResolver.Resolve("dot42");

            // Force loading of classes
            if (jar != null)
            {
                foreach (var fileName in jar.ClassFileNames)
                {
                    OpenClass(fileName);
                }
            }
#endif
        }
Exemple #26
0
		void OutputAssembly (AssemblyDefinition assembly)
		{
			string directory = Context.OutputDirectory;

			CopyConfigFileIfNeeded (assembly, directory);

			switch (Annotations.GetAction (assembly)) {
			case AssemblyAction.Link:
				assembly.Write (GetAssemblyFileName (assembly, directory), SaveSymbols (assembly));
				break;
			case AssemblyAction.Copy:
				CloseSymbols (assembly);
				CopyAssembly (GetOriginalAssemblyFileInfo (assembly), directory, Context.LinkSymbols);
				break;
			case AssemblyAction.Delete:
				CloseSymbols (assembly);
				var target = GetAssemblyFileName (assembly, directory);
				if (File.Exists (target))
					File.Delete (target);
				break;
			default:
				CloseSymbols (assembly);
				break;
			}
		}
Exemple #27
0
		protected override void ProcessAssembly (AssemblyDefinition assembly)
		{
			if (Annotations.GetAction (assembly) != AssemblyAction.Link)
				return;

			assembly.MainModule.Attributes = ModuleAttributes.ILOnly;
		}
		void SweepAssembly (AssemblyDefinition assembly)
		{
			if (Annotations.GetAction (assembly) != AssemblyAction.Link)
				return;

			if (!IsMarkedAssembly (assembly)) {
				RemoveAssembly (assembly);
				return;
			}

			var types = assembly.MainModule.Types;
			var cloned_types = Clone (types);

			types.Clear ();

			foreach (TypeDefinition type in cloned_types) {
				if (Annotations.IsMarked (type)) {
					SweepType (type);
					types.Add (type);
					continue;
				}

				SweepReferences (assembly, type);
			}
		}
Exemple #29
0
 public IAssemblyEmitter MakeAssemblyEmitter(AssemblyTranslator translator, AssemblyDefinition assembly, JavascriptFormatter formatter)
 {
     if (translator.IsStubbed(assembly) || translator.IsIgnored(assembly))
         return new NullAssemblyEmitter();
     else
         return new WasmSExprAssemblyEmitter(translator, assembly, formatter);
 }
Exemple #30
0
		public override void VisitAssemblyDefinition (AssemblyDefinition asm)
		{
			if (asm.Kind != AssemblyKind.Dll && asm.EntryPoint == null)
				throw new ReflectionException ("Assembly does not have an entry point defined");

			if ((asm.MainModule.Image.CLIHeader.Flags & RuntimeImage.ILOnly) == 0)
				throw new NotSupportedException ("Can not write a mixed mode assembly");

			foreach (ModuleDefinition module in asm.Modules)
				if (module.Image.CLIHeader.Metadata.VirtualAddress != RVA.Zero)
					ResetImage (module);

			asm.MetadataToken = new MetadataToken (TokenType.Assembly, 1);
			ReflectionWriter rw = asm.MainModule.Controller.Writer;
			rw.StructureWriter = this;

			m_mdWriter = rw.MetadataWriter;
			m_tableWriter = rw.MetadataTableWriter;
			m_rowWriter = rw.MetadataRowWriter;

			if (!rw.SaveSymbols)
				return;

			FileStream fs = m_binaryWriter.BaseStream as FileStream;
			if (fs != null)
				rw.OutputFile = fs.Name;
		}
Exemple #31
0
        private void VerifyIL(AssemblyDefinition assembly) {
            string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "ar_test.exe");
            assembly.Write(path);

            string peverify = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
                @"Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools\PEVerify.exe"
            );

            var process = Process.Start(new ProcessStartInfo {
                FileName = peverify,
                Arguments = $"\"{path}\"",
                CreateNoWindow = true,
                UseShellExecute = false,
                RedirectStandardOutput = true
            });

            string output = process.StandardOutput.ReadToEnd();

            process.WaitForExit();

            if(process.ExitCode != 0) {
                throw new VerifyFailedException(process.ExitCode, output);
            }
        }
 private void CreateAssemblyDefinition(String sAssemblyName, AssemblyKind akAssemblyKind)
 {
     assemblyName = sAssemblyName;
     assemblyKind = akAssemblyKind;
     assemblyDefinition = AssemblyFactory.DefineAssembly(sAssemblyName, TargetRuntime.NET_2_0, akAssemblyKind);
     mainModule = assemblyDefinition.MainModule;
 }
Exemple #33
0
        public Emitter(Compiler compiler)
        {
            Compiler = compiler;

              // create assembly object
              var name = new AssemblyNameDefinition("MirelleCompiled", new Version(1, 0, 0, 0));
              Assembly = AssemblyDefinition.CreateAssembly(name, "MirelleCompiled", ModuleKind.Console);

              var attr = typeof(STAThreadAttribute).GetConstructor(new Type[] { } );

              // register global method
              GlobalBody = new MethodDefinition("main", MethodAttributes.Static | MethodAttributes.Private | MethodAttributes.HideBySig, Assembly.MainModule.TypeSystem.Void);
              GlobalBody.CustomAttributes.Add(new CustomAttribute(AssemblyImport(attr)));
              RootNode.GlobalMethod = new MethodNode("main", new SignatureNode("void"), true, false, GlobalBody);
              RootNode.GlobalMethod.Scope = new Utils.Scope(GlobalBody);

              // register global type
              GlobalType = new TypeDefinition("MirelleCompiled", ".program", TypeAttributes.AutoClass | TypeAttributes.Public | TypeAttributes.SpecialName | TypeAttributes.BeforeFieldInit, Assembly.MainModule.TypeSystem.Object);
              Assembly.MainModule.Types.Add(GlobalType);
              GlobalType.Methods.Add(GlobalBody);
              Assembly.EntryPoint = GlobalBody;

              // register marker interfaces
              MirelleTypeInterface = AssemblyImport(typeof(MirelleStdlib.IMirelleType));
              MirelleEnumInterface = AssemblyImport(typeof(MirelleStdlib.IMirelleEnum));
        }
		public DerivedTypesEntryNode(TypeDefinition def, AssemblyDefinition[] assemblies)
		{
			this.def = def;
			this.assemblies = assemblies;
			this.LazyLoading = true;
			threading = new ThreadingSupport();
		}
Exemple #35
0
        public void EmitAssemblyEntryPoint (AssemblyDefinition assembly, MethodDefinition entryMethod, MethodSignature signature) {
            Formatter.WriteRaw("JSIL.SetEntryPoint");
            Formatter.LPar();

            Formatter.AssemblyReference(assembly);

            Formatter.Comma();

            var context = new TypeReferenceContext();
            Formatter.TypeReference(entryMethod.DeclaringType, context);

            Formatter.Comma();

            Formatter.Value(entryMethod.Name);

            Formatter.Comma();

            Formatter.MethodSignature(
                entryMethod, signature, context
            );

            Formatter.RPar();
            Formatter.Semicolon(true);

            Formatter.NewLine();
        }
 public IEnumerable<Change<MethodReference>> GetChangesBetween(AssemblyDefinition oldAssembly, AssemblyDefinition newAssembly)
 {
     var changeDetector = new MethodILChangeDetector();
     var oldCache = AssemblyTypeMethodMapBuilder.BuildFor(oldAssembly);
     var newCache = AssemblyTypeMethodMapBuilder.BuildFor(newAssembly);
     var differences = MapKeyDifferenceFinder.GetChangesBetween(oldCache, newCache);
     foreach (var method in newAssembly.AllNonIgnoredMethods())
     {
         var current = oldAssembly.MainModule.GetType(method.DeclaringType.FullName);
         if (current == null) continue;
         if (method.ContainsIgnoreAttribute()) continue;
         foreach (var oldMethod in current.Methods)
         {
             if (oldMethod.GetChangeCacheName() == method.GetChangeCacheName())
             {
                 if (changeDetector.AreDifferentIL(oldMethod,
                                                   method))
                 {
                     differences.Add(
                                     new Change<MethodReference>(
                         ChangeType.Modify, method.ThreadSafeResolve()));
                     break;
                 }
             }
         }
     }
     differences = IEnumerableResolver.ResolveCompilerGeneratedCode(differences);
     return differences;
 }
		public void VisitAssembly(AssemblyDefinition assembly)
		{						
			Log.DebugLine(this, "-----------------------------------"); 
			Log.DebugLine(this, "checking {0}", assembly.Name);				

			if (Aspell.Instance != null)
			{				
				string details = string.Empty;
				foreach (CustomAttribute attr in assembly.CustomAttributes)
				{
					foreach (object o in attr.ConstructorParameters)
					{
						string text = o.ToString();
						Unused.Value = CheckSpelling.Text(text, ref details);
					}
				}
				
				if (details.Length > 0)
				{
					details = "Words: " + details;
					Log.DebugLine(this, details);
					Reporter.AssemblyFailed(assembly, CheckID, details);
				}
			}
		}
 public AssemblyResult ProcessAssembly(AssemblyDefinition assembly, ModuleResult[] moduleResults)
 {
     AssemblyResult result = new AssemblyResult(assembly.Name.Name);
     result.ModuleResults = moduleResults;
     result.Result = moduleResults.Sum(r => r.Result);
     return result;
 }
Exemple #39
0
        public override bool ApplyPatch(AssemblyDefinition assembly, MethodDefinition original, ILWeaver weaver, AssemblyDefinition oxideassembly, Patching.Patcher patcher = null)
        {
            // Get the call hook method (only grab object parameters: ignore the object[] hook)
            List <MethodDefinition> callhookmethods = oxideassembly.MainModule.Types
                                                      .Single(t => t.FullName == "Oxide.Core.Interface")
                                                      .Methods.Where(m => m.IsStatic && m.Name == "CallHook" && m.HasParameters && m.Parameters.Any(p => p.ParameterType.IsArray) == false)
                                                      .OrderBy(x => x.Parameters.Count)
                                                      .ToList();

            // Start injecting where requested
            weaver.Pointer = InjectionIndex;

            // Get the existing instruction we're going to inject behind
            Instruction existing;

            try
            {
                existing = weaver.Instructions[weaver.Pointer];
            }
            catch (ArgumentOutOfRangeException)
            {
                ShowMsg($"The injection index specified for {Name} is invalid!", "Invalid Index", patcher);
                return(false);
            }

            // Load the hook name
            Instruction hookname = weaver.Add(Instruction.Create(OpCodes.Ldstr, HookName));

            // Push the arguments array to the stack and make the call
            //VariableDefinition argsvar; //This is the object array

            // Create an object array and load all arguments into it
            Instruction firstinjected = PushArgsArray(original, weaver, out int argCount, patcher) ?? hookname;

            /*if (argsvar != null)
             * weaver.Ldloc(argsvar);
             * else
             * weaver.Add(Instruction.Create(OpCodes.Ldnull));*/
            weaver.Add(Instruction.Create(OpCodes.Call, original.Module.Import(callhookmethods[argCount])));

            // Deal with the return value
            DealWithReturnValue(original, null, weaver);
            //DealWithReturnValue(original, argsvar, weaver);

            // Find all instructions which pointed to the existing and redirect them
            for (int i = 0; i < weaver.Instructions.Count; i++)
            {
                Instruction ins = weaver.Instructions[i];
                if (ins.Operand != null && ins.Operand.Equals(existing))
                {
                    // Check if the instruction lies within our injection range
                    // If it does, it's an instruction we just injected so we don't want to edit it
                    if (i < InjectionIndex || i > weaver.Pointer)
                    {
                        ins.Operand = firstinjected;
                    }
                }
            }
            return(true);
        }
		public RuleResult CheckAssembly (AssemblyDefinition assembly)
		{
			// assembly must have an entry point to be examined
			MethodDefinition entry_point = assembly.EntryPoint;
			if (entry_point == null)
				return RuleResult.DoesNotApply;

			// RULE APPLIES

			// we have to check declaringType's visibility so 
			// if we can't get access to it (is this possible?) we abandon
			// also, if it is not public, we don't have to continue our work
			// - we can't reach Main () anyways
			TypeDefinition type = entry_point.DeclaringType.Resolve ();
			if (type == null || !type.IsPublic)
				return RuleResult.Success;

			// at last, if Main () is not public, then it's okay
			if (!entry_point.IsPublic)
				return RuleResult.Success;

			if (assembly.References (VisualBasic)) {
				Runner.Report (type, Severity.Medium, Confidence.High, "Reduce class or module visibility (from public).");
			} else {
				Runner.Report (entry_point, Severity.Medium, Confidence.Total, "Change method visibility to private or internal.");
			}
			return RuleResult.Failure;
		}
Exemple #41
0
        public static void InstrumentAssembly(Cecil.AssemblyDefinition assembly)
        {
            var typeCount = assembly.Modules.Sum(mod => mod.Types.Count);

            foreach (var module in assembly.Modules)
            {
                foreach (var type in module.Types)
                {
                    InstrumentType(type);
                }
            }
        }
Exemple #42
0
        /// <summary>
        /// PrePatches this hook into the target weaver
        /// </summary>
        /// <param name="weaver"></param>
        /// <param name="oxidemodule"></param>
        /// <param name="original"></param>
        /// <param name="patcher"></param>
        public override bool PreparePatch(AssemblyDefinition assembly, MethodDefinition original, ILWeaver weaver, AssemblyDefinition oxidemodule, Patching.Patcher patcher = null)
        {
            if (DependsOnField != null)
            {
                if (!DependsOnField.Apply(assembly))
                {
                    return(false);
                }
            }

            return(base.PreparePatch(assembly, original, weaver, oxidemodule, patcher));
        }
Exemple #43
0
        private Assembly LoadProcessorsAssembly(string path, Mono.Cecil.AssemblyDefinition assemblyDefinition)
        {
            path = filePathResolver.ResolveFilePath(path);

            var loadedAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName == assemblyDefinition.FullName);

            if (loadedAssembly != null)
            {
                return(loadedAssembly);
            }

            return(Assembly.Load(File.ReadAllBytes(path)));
        }
Exemple #44
0
        private static void PatchType(AssemblyDefinition contractAsmDef, TypeDefinition typ, Dictionary <string, TypeDefinition> sdkTypeDefs)
        {
            // Patch the methods in the type
            foreach (var method in typ.Methods)
            {
                PatchMethod(contractAsmDef, method, sdkTypeDefs);
            }

            // Patch if there is any nested type within the type
            foreach (var nestedType in typ.NestedTypes)
            {
                PatchType(contractAsmDef, nestedType, sdkTypeDefs);
            }
        }
Exemple #45
0
        public void PrepareAssembly(AssemblyDefinition assembly)
        {
            this.assembly = assembly;

            RegisterExternalTypes();

            // Resolve corlib assembly
            corlib = assembly.MainModule.Import(typeof(void)).Resolve().Module.Assembly;

            // Prepare LLVM context, module and data layouts
            context = LLVM.GetGlobalContext();
            module  = LLVM.ModuleCreateWithName(assembly.Name.Name);

            // Prepare system types, for easier access
            InitializeCommonTypes();

            // TODO: Choose appropriate triple depending on target
            var target = LLVM.GetTarget(runtimeModule);

            LLVM.SetTarget(module, target);

            // Initialize ABI
            abi = new DefaultABI(context, targetData);

            // Prepare LLVM builders
            builder       = LLVM.CreateBuilderInContext(context);
            builder2      = LLVM.CreateBuilderInContext(context);
            builderAlloca = LLVM.CreateBuilderInContext(context);

            InitializeDebug();

            if (!TestMode)
            {
                // Register SharpLangModule objects for each module
                metadataPerModule = new Dictionary <Mono.Cecil.ModuleDefinition, ValueRef>();
                var mangledModuleName     = Regex.Replace(assembly.Name.Name + ".sharplangmodule", @"(\W)", "_");
                var sharpLangModuleGlobal = LLVM.AddGlobal(module, sharpLangModuleType.ObjectTypeLLVM, mangledModuleName);
                metadataPerModule[assembly.MainModule] = sharpLangModuleGlobal;

                // Generate extern globals for SharpLangModule instances of other modules
                foreach (var referencedAssembly in referencedAssemblies)
                {
                    mangledModuleName = Regex.Replace(referencedAssembly.Name.Name + ".sharplangmodule", @"(\W)", "_");
                    var externalSharpLangModuleGlobal = LLVM.AddGlobal(module, sharpLangModuleType.ObjectTypeLLVM, mangledModuleName);
                    LLVM.SetLinkage(externalSharpLangModuleGlobal, Linkage.ExternalLinkage);
                    metadataPerModule[referencedAssembly.MainModule] = externalSharpLangModuleGlobal;
                }
            }
        }
Exemple #46
0
        public static Method ReverseEngineer(System.Reflection.MethodInfo _method)
        {
            Method method = new Method();

            //decompile method body
            if (!_method.IsAbstract && !_method.IsCompilerGenerated())
            {
                Mono.Cecil.AssemblyDefinition ass = Decompiler.LoadAssembly(_method.DeclaringType.Module.Assembly.Location);
                MethodDefinition md = ass.MainModule.GetType(_method.DeclaringType.FullName).Methods.Where(md2 => md2.Name == _method.Name).Select(md2 => md2).First();
                method.MethodCode = Decompiler.GetSourceCode(md);
            }

            method.Name       = _method.Name;
            method.Type       = ReverseEngineer(_method.DeclaringType);
            method.ReturnType = ReverseEngineer(_method.ReturnType);
            method.IsStatic   = _method.IsStatic;
            method.IsAbstract = _method.IsAbstract;
            method.IsVirtual  = _method.IsVirtual;
            method.Access     = _method.GetAccessModifier();

            DataBase.Current.Set <Method>().Add(method);

            foreach (System.Reflection.ParameterInfo _param in _method.GetParameters())
            {
                MethodArgument ma = new MethodArgument();
                ma.Method = method;
                ma.Name   = _param.Name;
                ma.Type   = ReverseEngineer(_param.ParameterType);

                DataBase.Current.Set <MethodArgument>().Add(ma);
            }

            if (_method.IsGenericMethod || _method.IsGenericMethodDefinition || _method.ContainsGenericParameters)
            {
                foreach (System.Type _genericArg in _method.GetGenericArguments())
                {
                    MethodGenericArgument genericArg = new MethodGenericArgument();

                    genericArg.ArgumentType = ReverseEngineer(_genericArg);
                    genericArg.Position     = _genericArg.GenericParameterPosition;
                    genericArg.AppliedTo    = method;

                    DataBase.Current.Set <MethodGenericArgument>().Add(genericArg);
                }
            }

            return(method);
        }
        private List <PropertyTypeNode> Parse(Mono.Cecil.AssemblyDefinition assembly)
        {
            _typesBeingSerialized.Clear();
            _parsedContainerTypeNodesCache.Clear();

            // 1. Collect all the types to be looked at (all being Ipropertycontainers)

            foreach (var type in CollectPropertyContainers(assembly.Modules.SelectMany(m => m.GetTypes()).ToList()))
            {
                _typesBeingSerialized[type.FullName] = type;
            }

            // 2. Create the type tree (taking nested classes into account)

            return(TypeDefinitionsToPropertyTypes(_typesBeingSerialized));
        }
        public static IEnumerable <Cecil.TypeDefinition> IterateTypes(
            this Cecil.AssemblyDefinition assembly)
        {
            foreach (var module in assembly.Modules)
            {
                foreach (var type in module.Types)
                {
                    yield return(type);

                    foreach (var nestedType in IterateNestedTypes(type))
                    {
                        yield return(nestedType);
                    }
                }
            }
        }
Exemple #49
0
        public void ProcessAssembly(AssemblyDefinition assembly)
        {
            // Transfom all types in this assembly into SharpLang types.
            foreach (var assemblyModule in assembly.Modules)
            {
                var typeReferences = assemblyModule.GetTypeReferences();
                foreach (var type in typeReferences)
                {
                    GetType(type, TypeState.TypeComplete);
                }

                var memberReferences = assemblyModule.GetMemberReferences();
                foreach (var member in memberReferences)
                {
                    var method = member as MethodReference;
                    if (member.DeclaringType.ContainsGenericParameter)
                    {
                        continue;
                    }
                    GetType(member.DeclaringType, TypeState.TypeComplete);
                    if (method != null)
                    {
                        if (!method.HasGenericParameters)
                        {
                            CreateFunction(method);
                        }
                    }
                }

                foreach (var type in assemblyModule.Types)
                {
                    if (!type.HasGenericParameters && type.FullName != typeof(void).FullName)
                    {
                        GetClass(type);
                    }

                    foreach (var nestedType in type.NestedTypes)
                    {
                        if (!nestedType.HasGenericParameters)
                        {
                            GetClass(nestedType);
                        }
                    }
                }
            }
        }
Exemple #50
0
        /// <summary>
        /// Check if assembly is instrumented
        /// </summary>
        static bool IsInstruemnted(Cecil.AssemblyDefinition assembly)
        {
            foreach (var module in assembly.Modules)
            {
                foreach (var type in module.Types)
                {
                    foreach (var field in type.Fields)
                    {
                        if (field.IsHotpatchField())
                        {
                            return(true);
                        }
                    }
                }
            }

            return(false);
        }
Exemple #51
0
        IEnumerable <Cecil.MethodDefinition> IterateMethods(Cecil.AssemblyDefinition asm)
        {
            foreach (var module in asm.Modules)
            {
                foreach (var type in module.Types)
                {
                    foreach (var method in type.Methods)
                    {
                        if (!method.HasBody)
                        {
                            continue;
                        }

                        yield return(method);
                    }
                }
            }
        }
Exemple #52
0
        protected virtual void ExtractResourceAndWriteToFile(string outputPath, AssemblyDefinition assembly, string resourceName, string fileName, Func <string, string> preHandler = null)
        {
            var res = assembly.MainModule.Resources.FirstOrDefault(r => r.Name == resourceName);

            var file = CreateFileDirectory(outputPath, fileName);

            string resourcesStr = null;

            using (var resourcesStream = ((EmbeddedResource)res).GetResourceStream())
            {
                using (StreamReader reader = new StreamReader(resourcesStream))
                {
                    resourcesStr = reader.ReadToEnd();
                }
            }
            var content = preHandler != null?preHandler(resourcesStr) : resourcesStr;

            this.SaveToFile(file.FullName, content);
        }
Exemple #53
0
        private IList <AssemblyDefinition> GetParentAssemblies(AssemblyDefinition asm, List <AssemblyDefinition> list = null)
        {
            bool endPoint = list == null;

            if (endPoint)
            {
                activeAssemblies = new Stack <AssemblyDefinition>();
                list             = new List <AssemblyDefinition>();
            }

            if (activeAssemblies.Any(r => r.FullName == asm.FullName))
            {
                return(list);
            }

            activeAssemblies.Push(asm);

            foreach (var assemblyReferenceName in asm.MainModule.AssemblyReferences)
            {
                if (assemblyReferenceName.Name.Contains(SystemAssemblyName))
                {
                    continue;
                }

                var assemblyReference = asm.MainModule.AssemblyResolver.Resolve(assemblyReferenceName);

                if (assemblyReference.MainModule.Kind != ModuleKind.Dll)
                {
                    continue;
                }

                if (list.All(r => r.FullName != assemblyReference.FullName))
                {
                    list.Add(assemblyReference);
                }

                GetParentAssemblies(assemblyReference, list);
            }

            activeAssemblies.Pop();

            return(list);
        }
        private static Assembly LoadPlugin(AssemblyDefinition def)
        {
            foreach (var r in def.Modules.SelectMany(m => m.Resources).OfType <EmbeddedResource>())
            {
                if (r.Name.EndsWith(".dll", StringComparison.InvariantCultureIgnoreCase))
                {
                    var data = r.GetResourceData();
                    var asm  = AssemblyDefinition.ReadAssembly(new MemoryStream(data));

                    var result = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.GetName().Name == asm.Name.Name);
                    if (result == null)
                    {
                        result = Assembly.Load(data);
                    }
                    return(result);
                }
            }
            return(null);
        }
Exemple #55
0
        private static void PatchMethod(AssemblyDefinition contractAsmDef, MethodDefinition method, Dictionary <string, TypeDefinition> sdkTypeDefs)
        {
            if (!method.HasBody)
            {
                return;
            }

            var ilProcessor = method.Body.GetILProcessor();

            var instructionsToReplace = method.Body.Instructions.Where(i =>
                                                                       i.OpCode.Code == Code.Call && TargetMethods.Any(m => ((MethodReference)i.Operand).FullName.Contains(m.Key)))
                                        .ToList();

            foreach (var instruction in instructionsToReplace)
            {
                var sysMethodRef = (MethodReference)instruction.Operand;
                var newMethodRef = contractAsmDef.MainModule.ImportReference(GetSdkMethodReference(sdkTypeDefs, sysMethodRef));

                ilProcessor.InsertBefore(instruction, ilProcessor.Create(OpCodes.Call, newMethodRef));
                ilProcessor.Remove(instruction);
            }
        }
Exemple #56
0
        private void CopyAndPrepareCoreAssembly(IFile originalAssemblyFile, IDirectory tempDirectory)
        {
            var newLocation = tempDirectory.GetFile(originalAssemblyFile.Name);

            originalAssemblyFile.CopyTo(newLocation.FullName);

            AssemblyDefinition newAssembly;

            using (var stream = newLocation.OpenRead()) {
                newAssembly = AssemblyDefinition.ReadAssembly(stream);
            }
            foreach (var reference in newAssembly.MainModule.AssemblyReferences)
            {
                var fileInTemp = GetAssemblyFile(tempDirectory, reference);
                if (!fileInTemp.Exists)
                {
                    continue;
                }

                var assemblyName = AssemblyName.GetAssemblyName(fileInTemp.FullName);
                if (assemblyName.GetPublicKey() != null)
                {
                    // ReSharper disable once RedundantCheckBeforeAssignment (in case of change tracking)
                    if (reference.Version != assemblyName.Version)
                    {
                        reference.Version = assemblyName.Version;
                    }

                    continue;
                }

                reference.PublicKey      = null;
                reference.PublicKeyToken = null;
                reference.HasPublicKey   = false;
            }
            using (var stream = newLocation.Open(FileMode.Create)) {
                newAssembly.Write(stream);
            }
        }
Exemple #57
0
        public void Visit(Mono.Cecil.AssemblyDefinition assembly)
        {
            foreach (var module in assembly.Modules)
            {
                Analyser = new StackAnalyser(module);

                foreach (var type in module.GetTypes())
                {
                    foreach (var method in type.Methods)
                    {
                        if (method.HasBody || !definitionsOnly)
                        {
                            Visit(method);
                        }
                    }
                    foreach (var property in type.Properties)
                    {
                        Visit(property);
                    }
                }
            }
        }
Exemple #58
0
        protected virtual void ExtractResourceAndWriteToFile(string outputPath, AssemblyDefinition assembly, string resourceName, string fileName, Func <string, string> preHandler = null)
        {
            var res = assembly.MainModule.Resources.FirstOrDefault(r => r.Name == resourceName);

            if (res == null)
            {
                throw new InvalidOperationException("Could not read resource " + resourceName + " in " + assembly.FullName);
            }

            var file = CreateFileDirectory(outputPath, fileName);

            string content = null;

            byte[] binary = null;

            using (var resourcesStream = ((EmbeddedResource)res).GetResourceStream())
            {
                if (FileHelper.IsJS(file.FullName) || preHandler != null)
                {
                    using (var reader = new StreamReader(resourcesStream))
                    {
                        content = reader.ReadToEnd();
                    }
                }
                else
                {
                    binary = ReadStream(resourcesStream);
                }
            }

            if (preHandler != null)
            {
                content = preHandler(content);
            }

            this.SaveToFile(file.FullName, content, binary);
        }
Exemple #59
0
        /// <summary>
        ///
        /// </summary>
        private void LoadAsmContents()
        {
            this.treeview_Definitions.Nodes.Clear();
            LoadAssembly = AssemblyDefinition.ReadAssembly(selectedFilename);
            TreeNode    tn         = null;
            IEnumerator enumerator = LoadAssembly.MainModule.Types.GetEnumerator();

            while (enumerator.MoveNext())
            {
                TypeDefinition td = (TypeDefinition)enumerator.Current;

                tn = this.treeview_Definitions.Nodes.Add(td.Name.ToString());
                IEnumerator enumerator2 = td.Methods.GetEnumerator();
                while (enumerator2.MoveNext())
                {
                    MethodDefinition method_definition = (MethodDefinition)enumerator2.Current;
                    if (method_definition.IsConstructor)
                    {
                        tn.Nodes.Add(method_definition.Name.ToString());
                    }
                    tn.Nodes.Add(method_definition.Name.ToString());
                }
            }
        }
        static string GetExeLocation(string toolsVersion)
        {
            FilePath sourceExe = typeof(ProjectBuilder).Assembly.Location;

            if (toolsVersion == REFERENCED_MSBUILD_TOOLS)
            {
                return(sourceExe);
            }

            var    newVersions = new Dictionary <string, string[]> ();
            string version;

            Mono.Cecil.TargetRuntime runtime;

            switch (toolsVersion)
            {
            case "2.0":
                version = "2.0.0.0";
                newVersions.Add("Microsoft.Build.Engine", new string[] { "Microsoft.Build.Engine", version });
                newVersions.Add("Microsoft.Build.Framework", new string[] { "Microsoft.Build.Framework", version });
                newVersions.Add(REFERENCED_MSBUILD_UTILS, new string[] { "Microsoft.Build.Utilities", version });
                runtime = Mono.Cecil.TargetRuntime.Net_2_0;
                break;

            case "3.5":
                version = "3.5.0.0";
                newVersions.Add("Microsoft.Build.Engine", new string[] { "Microsoft.Build.Engine", version });
                newVersions.Add("Microsoft.Build.Framework", new string[] { "Microsoft.Build.Framework", version });
                newVersions.Add(REFERENCED_MSBUILD_UTILS, new string[] { "Microsoft.Build.Utilities.v3.5", version });
                runtime = Mono.Cecil.TargetRuntime.Net_2_0;
                break;

            case "4.0":
                version = "4.0.0.0";
                newVersions.Add("Microsoft.Build.Engine", new string[] { "Microsoft.Build.Engine", version });
                newVersions.Add("Microsoft.Build.Framework", new string[] { "Microsoft.Build.Framework", version });
                newVersions.Add(REFERENCED_MSBUILD_UTILS, new string[] { "Microsoft.Build.Utilities.v4.0", version });
                runtime = Mono.Cecil.TargetRuntime.Net_4_0;
                break;

            default:
                throw new InvalidOperationException("Unknown MSBuild ToolsVersion '" + toolsVersion + "'");
            }

            FilePath p = FilePath.Build(PropertyService.Locations.Cache, "xbuild", toolsVersion, "MonoDevelop.Projects.Formats.MSBuild.exe");

            if (!File.Exists(p) || File.GetLastWriteTime(p) < File.GetLastWriteTime(sourceExe))
            {
                if (!Directory.Exists(p.ParentDirectory))
                {
                    Directory.CreateDirectory(p.ParentDirectory);
                }

                // Update the references to msbuild
                Cecil.AssemblyDefinition asm = Cecil.AssemblyDefinition.ReadAssembly(sourceExe);
                foreach (Cecil.AssemblyNameReference ar in asm.MainModule.AssemblyReferences)
                {
                    string[] replacement;
                    if (newVersions.TryGetValue(ar.Name, out replacement))
                    {
                        ar.Name    = replacement[0];
                        ar.Version = new Version(replacement[1]);
                    }
                }
                asm.MainModule.Runtime = runtime;

                //run in 32-bit mode because usually msbuild targets are installed for 32-bit only
                asm.MainModule.Attributes |= Mono.Cecil.ModuleAttributes.Required32Bit;

                // Workaround to a bug in mcs. The ILOnly flag is not emitted when using /platform:x86
                asm.MainModule.Attributes |= Mono.Cecil.ModuleAttributes.ILOnly;

                asm.Write(p);
            }

            FilePath configFile = p + ".config";
            FilePath configSrc  = typeof(ProjectBuilder).Assembly.Location + ".config";

            if (!File.Exists(configFile) || File.GetLastWriteTime(configFile) < File.GetLastWriteTime(configSrc))
            {
                var config = File.ReadAllText(configSrc);
                config = config.Replace(REFERENCED_MSBUILD_TOOLS + ".0.0", version);
                File.WriteAllText(p + ".config", config);
            }
            return(p);
        }