Exemplo n.º 1
1
        public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream)
        {
            Mixin.CheckModule (module);
            Mixin.CheckStream (symbolStream);

            return new PdbReader (Disposable.NotOwned (symbolStream));
        }
Exemplo n.º 2
0
 public static ImageWriter CreateDebugWriter(ModuleDefinition module, MetadataBuilder metadata, Disposable<Stream> stream)
 {
     var writer = new ImageWriter (module, "PDB V1.0", metadata, stream, metadataOnly: true);
     var length = metadata.text_map.GetLength ();
     writer.text = new Section { SizeOfRawData = length, VirtualSize = length };
     return writer;
 }
Exemplo n.º 3
0
    public void ReadModule()
    {
        if (pdbFound)
        {
            using (var symbolStream = File.OpenRead(pdbPath))
            {
                var readerParameters = new ReaderParameters
                    {
                        AssemblyResolver = this,
                        ReadSymbols = pdbFound || mdbFound,
                        SymbolReaderProvider = debugReaderProvider,
                        SymbolStream = symbolStream
                    };
                ModuleDefinition = ModuleDefinition.ReadModule(AssemblyFilePath, readerParameters);
            }
        }
        else
        {
            var readerParameters = new ReaderParameters
                {
                    AssemblyResolver = this,
                    ReadSymbols = pdbFound || mdbFound,
                    SymbolReaderProvider = debugReaderProvider,

                };
            ModuleDefinition = ModuleDefinition.ReadModule(AssemblyFilePath, readerParameters);
        }
    }
Exemplo n.º 4
0
        public void OtherMethod(ModuleDefinition module)
        {
            var type = module.GetType ("Others");

            Assert.IsTrue (type.HasProperties);

            var properties = type.Properties;

            Assert.AreEqual (1, properties.Count);

            var property = properties [0];

            Assert.IsNotNull (property);
            Assert.AreEqual ("Context", property.Name);
            Assert.IsNotNull (property.PropertyType);
            Assert.AreEqual ("System.String", property.PropertyType.FullName);

            Assert.IsTrue (property.HasOtherMethods);

            Assert.AreEqual (2, property.OtherMethods.Count);

            var other = property.OtherMethods [0];
            Assert.AreEqual ("let_Context", other.Name);

            other = property.OtherMethods [1];
            Assert.AreEqual ("bet_Context", other.Name);
        }
Exemplo n.º 5
0
		internal PdbWriter (SymWriter writer, ModuleDefinition module, string assembly)
		{
			m_writer = writer;
			m_module = module;
			m_documents = new Hashtable ();
			m_assembly = assembly;
		}
		public void TestUseCombinedSkinsSchemaWhenNoDefaultTemplate()
		{
			var templateInfo = new StringTemplateInfo("test", "");
			var templateInfo2 = new StringTemplateInfo("test2", "");
			var schema1 = new JSchema();
            var schema2 = new JSchema();

			var templateSchemaProvider = new Mock<ISchemaProvider>();
			templateSchemaProvider.Setup(f => f.GetSchemaFromTemplateAsync(templateInfo)).Returns(Task.FromResult(schema1));
			templateSchemaProvider.Setup(f => f.GetSchemaFromTemplateAsync(templateInfo2)).Returns(Task.FromResult(schema2));

			var combiner = new Mock<SchemaCombiner>();
			combiner.Setup(c =>
                c.Apply(It.Is<JSchema>(s => s == schema1), It.Is<JSchema>(s => s == schema2), It.IsAny<SchemaComparisionReport>(), It.IsAny<string>()))
                .Returns(new JSchema());

			var moduleDefintion = new ModuleDefinition("testmod", null, new Dictionary<string, TemplateInfo>
            {
				{"skin1", templateInfo},
                {"skin2", templateInfo2}
            });

			var underTest = new DefaultModuleSchemaProvider(combiner.Object, templateSchemaProvider.Object);

			var result = underTest.GetSchemaFromModuleAsync(moduleDefintion);

			Assert.IsNotNull(result);

			combiner.Verify();
		}
Exemplo n.º 7
0
        public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName)
        {
            Mixin.CheckModule (module);
            Mixin.CheckFileName (fileName);

            return new PdbReader (Disposable.Owned (File.OpenRead (Mixin.GetPdbFileName (fileName)) as Stream));
        }
Exemplo n.º 8
0
    public string ReplaceTokens(string template, ModuleDefinition moduleDefinition, Repository repo, string changestring)
    {
        var assemblyVersion = moduleDefinition.Assembly.Name.Version;
        var branch = repo.Head;

        template = template.Replace("%version%", assemblyVersion.ToString());
        template = template.Replace("%version1%", assemblyVersion.ToString(1));
        template = template.Replace("%version2%", assemblyVersion.ToString(2));
        template = template.Replace("%version3%", assemblyVersion.ToString(3));
        template = template.Replace("%version4%", assemblyVersion.ToString(4));

        template = template.Replace("%now%", now.ToShortDateString());
        template = template.Replace("%utcnow%", utcNow.ToShortDateString());

        template = template.Replace("%githash%", branch.Tip.Sha);
        template = template.Replace("%shorthash%", branch.Tip.Sha.Substring(0, 8));
        template = template.Replace("%branch%", branch.FriendlyName);
        template = template.Replace("%haschanges%", repo.IsClean() ? "" : changestring);

        template = template.Replace("%user%", FormatUserName());
        template = template.Replace("%machine%", Environment.MachineName);

        template = reEnvironmentToken.Replace(template, FormatEnvironmentVariable);
        template = reNow.Replace(template, FormatTime);
        template = reUtcNow.Replace(template, FormatUtcTime);

        return template.Trim();
    }
Exemplo n.º 9
0
		public ReflectionController (ModuleDefinition module)
		{
			m_reader = new AggressiveReflectionReader (module);
			m_writer = new ReflectionWriter (module);
			m_helper = new ReflectionHelper (module);
			m_importer = new DefaultImporter (module);
		}
Exemplo n.º 10
0
    public virtual void ReadModule()
    {
        string symbolsPath;
        if (pdbFound)
        {
            symbolsPath = pdbPath;
        }
        else
        {
            symbolsPath = mdbPath;
        }

        var tempAssembly = $"{AssemblyFilePath}.tmp";
        var tempSymbols = $"{symbolsPath}.tmp";
        File.Copy(AssemblyFilePath, tempAssembly,true);
        File.Copy(symbolsPath, tempSymbols, true);
        SymbolStream = File.OpenRead(tempSymbols);
        var readerParameters = new ReaderParameters
        {
            AssemblyResolver = this,
            ReadSymbols = true,
            SymbolReaderProvider = debugReaderProvider,
            SymbolStream = SymbolStream,
        };
        ModuleDefinition = ModuleDefinition.ReadModule(tempAssembly, readerParameters);
    }
 internal TypeReference GetTypeReference(ModuleDefinition module)
 {
     var ret = _type as Type;
     return ret != null 
         ? module.SafeImport(ret) 
         : module.SafeImport(_type as TypeReference);
 }
Exemplo n.º 12
0
 internal PdbWriter(ISymbolWriter writer, ModuleDefinition module, string pdb)
 {
     m_writer = writer;
     m_module = module;
     m_documents = new Hashtable ();
     m_pdb = pdb;
 }
Exemplo n.º 13
0
 internal PortablePdbReader(Image image, ModuleDefinition module)
 {
     this.image = image;
     this.module = module;
     this.reader = module.reader;
     this.debug_reader = new MetadataReader (image, module, this.reader);
 }
Exemplo n.º 14
0
 private void IdentifyModule(ModuleDefinition module)
 {
     if (_allMethods.ContainsKey(module)) return;
     _allMethods.Add(module, new Dictionary<ClassDecl, List<Method>>());
     foreach (var decl in module.TopLevelDecls)
         IdentifyTopLevelDecl(decl);
 }
Exemplo n.º 15
0
 public RefinementToken(IToken tok, ModuleDefinition m)
     : base(tok)
 {
     Contract.Requires(tok != null);
       Contract.Requires(m != null);
       this.InheritingModule = m;
 }
Exemplo n.º 16
0
 public ExportedType(string @namespace, string name, ModuleDefinition module, IMetadataScope scope)
 {
     this.@namespace = @namespace;
     this.name = name;
     this.scope = scope;
     this.module = module;
 }
        public async Task<JSchema> GetSchemaFromModuleAsync(ModuleDefinition module)
        {
            IEnumerable<TemplateInfo> templates;
            if (module.Skins != null)
                templates = module.Skins.Values;
            else
                templates = Enumerable.Empty<TemplateInfo>();

            if (module.DefaultTemplate != null)
                templates = templates.Union(new[] {module.DefaultTemplate});

            var enumerator = templates.GetEnumerator();
            if (!enumerator.MoveNext())
                return null;

            var result = await _schemaProvider.GetSchemaFromTemplateAsync(enumerator.Current).ConfigureAwait(false);
            
            var report = new SchemaComparisionReport();
	        while (enumerator.MoveNext())
	        {
				var schema = await _schemaProvider.GetSchemaFromTemplateAsync(enumerator.Current).ConfigureAwait(false);
				result = _schemaCombiner.Apply(result, schema, report);
	        }

            return result;
        }
Exemplo n.º 18
0
        private static ModuleDefinition GetClrBasicsFor(string file, PEFile pe)
        {
            var stream = new MemoryStream(File.ReadAllBytes(file));
            var reader = new BinaryStreamReader(stream, new byte[1024]);
            pe.ReadFrom(reader);

            var clrDirectory = pe.OptionalHeader.DataDirectories[(int)DataDirectoryKind.Clr];

            var rvaStream = new RvaStream(
                stream,
                pe.SectionHeaders.Select(
                s => new RvaStream.Range
                {
                    PhysicalAddress = s.PointerToRawData,
                    Size = s.VirtualSize,
                    VirtualAddress = s.VirtualAddress
                })
                .ToArray());

            rvaStream.Position = clrDirectory.VirtualAddress;

            var sectionReader = new BinaryStreamReader(rvaStream, new byte[32]);

            var clrmod = new ModuleDefinition();
            ClrModuleReader.Read(sectionReader, clrmod);

            return clrmod;
        }
Exemplo n.º 19
0
		public void Main (ModuleDefinition module)
		{
			var type = module.GetType ("Program");
			var main = type.GetMethod ("Main");

			AssertCode (@"
	.locals init (System.Int32 i)
	.line 7,7:0,0 'C:\sources\cecil\symbols\Mono.Cecil.Mdb\Test\Resources\assemblies\hello.cs'
	IL_0000: ldc.i4.0
	IL_0001: stloc.0
	.line 7,7:0,0 'C:\sources\cecil\symbols\Mono.Cecil.Mdb\Test\Resources\assemblies\hello.cs'
	IL_0002: br IL_0013
	.line 8,8:0,0 'C:\sources\cecil\symbols\Mono.Cecil.Mdb\Test\Resources\assemblies\hello.cs'
	IL_0007: ldarg.0
	IL_0008: ldloc.0
	IL_0009: ldelem.ref
	IL_000a: call System.Void Program::Print(System.String)
	.line 7,7:0,0 'C:\sources\cecil\symbols\Mono.Cecil.Mdb\Test\Resources\assemblies\hello.cs'
	IL_000f: ldloc.0
	IL_0010: ldc.i4.1
	IL_0011: add
	IL_0012: stloc.0
	IL_0013: ldloc.0
	IL_0014: ldarg.0
	IL_0015: ldlen
	IL_0016: conv.i4
	IL_0017: blt IL_0007
	.line 10,10:0,0 'C:\sources\cecil\symbols\Mono.Cecil.Mdb\Test\Resources\assemblies\hello.cs'
	IL_001c: ldc.i4.0
	IL_001d: ret
", main);
		}
Exemplo n.º 20
0
		public static Collection<GenericParameter> GetGenericParameters (
			this IGenericParameterProvider self,
			ModuleDefinition module)
		{
			return module.HasImage ()
				? module.Read (self, (provider, reader) => reader.ReadGenericParameters (provider))
				: new Collection<GenericParameter> ();
		}
		public static bool GetHasGenericParameters (
			this IGenericParameterProvider self,
			ModuleDefinition module)
		{
			return module.HasImage ()
				? module.Read (self, (provider, reader) => reader.HasGenericParameters (provider))
				: false;
		}
Exemplo n.º 22
0
		public ISymbolReader CreateReader (ModuleDefinition module, string assemblyFileName)
		{
#if NATIVE_READER
			return new PdbReader (PdbHelper.CreateReader (assemblyFileName));
#else
			return new PdbCciReader (module, GetPdbFileName (assemblyFileName));
#endif
		}
Exemplo n.º 23
0
		public static bool GetHasMarshalInfo (
			this IMarshalInfoProvider self,
			ModuleDefinition module)
		{
			return module.HasImage ()
				? module.Read (self, (provider, reader) => reader.HasMarshalInfo (provider))
				: false;
		}
Exemplo n.º 24
0
		public static Collection<CustomAttribute> GetCustomAttributes (
			this ICustomAttributeProvider self,
			ModuleDefinition module)
		{
			return module.HasImage ()
				? module.Read (self, (provider, reader) => reader.ReadCustomAttributes (provider))
				: new Collection<CustomAttribute> ();
		}
Exemplo n.º 25
0
	    public Task UpdateModelForModuleAsync(ModuleDefinition moduleDefinition, string dataId, object content)
	    {
            var filePath = GetPath(moduleDefinition, dataId != null ? PathInfo.Create(dataId) : DefaultFilename);
			if (!_fileSystem.DirectoryExists(_fileSystem.Path.GetDirectoryName(filePath)))
				_fileSystem.CreateDirectory(_fileSystem.Path.GetDirectoryName(filePath));

		    return Update(content, filePath);
	    }
Exemplo n.º 26
0
		public static MarshalInfo GetMarshalInfo (
			this IMarshalInfoProvider self,
			ModuleDefinition module)
		{
			return module.HasImage ()
				? module.Read (self, (provider, reader) => reader.ReadMarshalInfo (provider))
				: null;
		}
Exemplo n.º 27
0
		public static bool GetHasCustomAttributes (
			this ICustomAttributeProvider self,
			ModuleDefinition module)
		{
			return module.HasImage ()
				? module.Read (self, (provider, reader) => reader.HasCustomAttributes (provider))
				: false;
		}
    private static void AddICollectionTProxy(ModuleDefinition moduleDefinition, TypeDefinition type, GenericInstanceType collectionT)
    {
        var itemType = collectionT.GenericArguments[0];
        var itemArray = itemType.MakeArrayType();

        var proxyType = CreateProxy(moduleDefinition, type);
        TypeReference proxyTypeRef = proxyType;
        if (type.HasGenericParameters)
            proxyTypeRef = proxyType.MakeGenericInstanceType(type.GenericParameters.Select(gp => new GenericParameter(gp.Position, gp.Type, gp.Module)).ToArray());

        var field = proxyType.Fields[0];
        var fieldRef = new FieldReference(field.Name, field.FieldType, proxyTypeRef);

        var countProperty = type.Properties.First(p => p.Name == "Count" || p.Name == "System.Collections.ICollection.Count");
        MethodReference countMethod = countProperty.GetMethod;
        MethodReference copyToMethod = type.Methods.First(p => p.Name == "CopyTo" || p.Name == "System.Collections.ICollection.CopyTo");

        if (type.HasGenericParameters)
        {
            countMethod = countMethod.MakeHostInstanceGeneric(type.GenericParameters.Select(gp => new GenericParameter(gp.Position, gp.Type, gp.Module)).ToArray());
            copyToMethod = copyToMethod.MakeHostInstanceGeneric(type.GenericParameters.Select(gp => new GenericParameter(gp.Position, gp.Type, gp.Module)).ToArray());
        }

        var getMethod = new MethodDefinition("get_Items", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName, itemArray);
        var getMethodBody = getMethod.Body;

        var localItems = new VariableDefinition("items", itemArray);
        getMethodBody.Variables.Add(localItems);

        getMethodBody.SimplifyMacros();
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Ldfld, fieldRef));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Callvirt, countMethod));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Newarr, itemType));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Stloc, localItems));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Ldfld, fieldRef));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Ldloc, localItems));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Ldloc, localItems));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Ldlen));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Conv_I4));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Callvirt, copyToMethod));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Ldloc, localItems));
        getMethodBody.Instructions.Add(Instruction.Create(OpCodes.Ret));
        getMethodBody.InitLocals = true;
        getMethodBody.OptimizeMacros();

        proxyType.Methods.Add(getMethod);

        var property = new PropertyDefinition("Items", PropertyAttributes.None, itemArray);
        property.GetMethod = getMethod;
        var debuggerBrowsableAttribute = new CustomAttribute(ReferenceFinder.DebuggerBrowsableAttributeCtor);
        debuggerBrowsableAttribute.ConstructorArguments.Add(new CustomAttributeArgument(ReferenceFinder.DebuggerBrowsableStateType, DebuggerBrowsableState.RootHidden));
        property.CustomAttributes.Add(debuggerBrowsableAttribute);
        proxyType.Properties.Add(property);

        AddDebuggerTypeProxyAttribute(type, proxyType);
    }
Exemplo n.º 29
0
        public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName)
        {
            Mixin.CheckModule (module);
            Mixin.CheckFileName (fileName);

            return IsPortablePdb (Mixin.GetPdbFileName (fileName))
                ? new PortablePdbReaderProvider ().GetSymbolReader (module, fileName)
                : new NativePdbReaderProvider ().GetSymbolReader (module, fileName);
        }
Exemplo n.º 30
0
 public static MarshalInfo GetMarshalInfo(
     IMarshalInfoProvider self,
     ref MarshalInfo variable,
     ModuleDefinition module)
 {
     return Mixin.HasImage(module)
         ? module.Read(ref variable, self, (provider, reader) => reader.ReadMarshalInfo(provider))
         : null;
 }
Exemplo n.º 31
0
 public IMetadataImporter GetMetadataImporter(ModuleDefinition module)
 {
     return(new CoreLibMetadataImporter(module));
 }
Exemplo n.º 32
0
 public void VisitModuleDefinition(ModuleDefinition module)
 {
 }
        public static TypeReference GetBindablePropertyTypeConverter(this FieldReference bpRef, ModuleDefinition module)
        {
            TypeReference _;
            var           owner        = bpRef.DeclaringType;
            var           bpName       = bpRef.Name.EndsWith("Property", StringComparison.Ordinal) ? bpRef.Name.Substring(0, bpRef.Name.Length - 8) : bpRef.Name;
            var           property     = owner.GetProperty(pd => pd.Name == bpName, out _);
            var           staticGetter = owner.GetMethods(md => md.Name == $"Get{bpName}" &&
                                                          md.IsStatic &&
                                                          md.IsPublic &&
                                                          md.Parameters.Count == 1 &&
                                                          md.Parameters[0].ParameterType.InheritsFromOrImplements(module.ImportReference(typeof(BindableObject))), module).SingleOrDefault()?.Item1;

            var attributes = new List <CustomAttribute>();

            if (property != null && property.HasCustomAttributes)
            {
                attributes.AddRange(property.CustomAttributes);
            }
            if (property != null && property.PropertyType.Resolve().HasCustomAttributes)
            {
                attributes.AddRange(property.PropertyType.Resolve().CustomAttributes);
            }
            if (staticGetter != null && staticGetter.HasCustomAttributes)
            {
                attributes.AddRange(staticGetter.CustomAttributes);
            }
            if (staticGetter != null && staticGetter.ReturnType.Resolve().HasCustomAttributes)
            {
                attributes.AddRange(staticGetter.ReturnType.Resolve().CustomAttributes);
            }

            return(attributes.FirstOrDefault(cad => TypeConverterAttribute.TypeConvertersType.Contains(cad.AttributeType.FullName))?.ConstructorArguments [0].Value as TypeReference);
        }
Exemplo n.º 34
0
 public PortablePdbWriter(MetadataBuilder pdb_metadata, ModuleDefinition module, ImageWriter writer)
     : this(pdb_metadata, module)
 {
     this.writer = writer;
 }
Exemplo n.º 35
0
        public void MatchDifferentCorLibTypeSignatures()
        {
            var module = ModuleDefinition.FromBytes(Properties.Resources.HelloWorld);

            Assert.NotEqual(module.CorLibTypeFactory.Byte, module.CorLibTypeFactory.Boolean, _comparer);
        }
Exemplo n.º 36
0
        /// <inheritdoc/>
        public async Task <bool?> TryEvaluateModuleAsync(IEvaluationScheduler scheduler, ModuleDefinition module, QualifierId qualifierId)
        {
            Contract.Requires(scheduler != null);
            Contract.Requires(module != null);
            Contract.Requires(qualifierId.IsValid);

            Contract.Assert(m_resolverState == State.ResolverInitialized);
            Contract.Assert(m_owningModules != null, "Owning modules should not be null if the instance is initialized.");

            var moduleDefinition = (ModuleDefinition)module;

            if (!m_owningModules.TryGetValue(moduleDefinition.Descriptor.Id, out Package package))
            {
                // Current resolver doesn't own the given module.
                return(null);
            }

            return(await DoTryEvaluateModuleAsync(scheduler, moduleDefinition, qualifierId));
        }
Exemplo n.º 37
0
 public ISymbolReader GetSymbolReader(ModuleDefinition module, string fileName)
 {
     return(IsPortablePdb(GetPdbFileName(fileName))
         ? new PortablePdbReaderProvider().GetSymbolReader(module, fileName)
         : new NativePdbReaderProvider().GetSymbolReader(module, fileName));
 }
Exemplo n.º 38
0
 // Called after the patching process and after scripts are compiled.
 // Used to link references between both assemblies
 // Return true if successful
 public bool Link(ModuleDefinition gameModule, ModuleDefinition modModule)
 {
     return(true);
 }
Exemplo n.º 39
0
        private async Task <bool> DoTryEvaluateModuleAsync(IEvaluationScheduler scheduler, ModuleDefinition module, QualifierId qualifierId)
        {
            var qualifier = QualifierValue.Create(qualifierId, QualifierValueCache, Context.QualifierTable, Context.StringTable);

            // We don't want to evaluate the transitive closure of the import/export relationship, just the package.
            var evalJobs = module.Specs.Select(
                spec => EvaluateAsync(scheduler, spec, qualifier, asPackageEvaluation: false));

            var allTasks = await Task.WhenAll(evalJobs);

            var result = allTasks.All(t => t.Success);

            if (m_evaluationDecorator != null)
            {
                foreach (var evaluationResult in allTasks)
                {
                    m_evaluationResults.Enqueue(evaluationResult);
                }
            }

            return(result);
        }
Exemplo n.º 40
0
        /// <summary>
        /// Executes this property weaver.
        /// </summary>
        public void Execute()
        {
            var reactiveUI = ModuleDefinition.AssemblyReferences.Where(x => x.Name == "ReactiveUI").OrderByDescending(x => x.Version).FirstOrDefault();

            if (reactiveUI == null)
            {
                LogInfo("Could not find assembly: ReactiveUI (" + string.Join(", ", ModuleDefinition.AssemblyReferences.Select(x => x.Name)) + ")");
                return;
            }

            LogInfo($"{reactiveUI.Name} {reactiveUI.Version}");
            var helpers = ModuleDefinition.AssemblyReferences.Where(x => x.Name == "ReactiveUI.Fody.Helpers").OrderByDescending(x => x.Version).FirstOrDefault();

            if (helpers == null)
            {
                LogInfo("Could not find assembly: ReactiveUI.Fody.Helpers (" + string.Join(", ", ModuleDefinition.AssemblyReferences.Select(x => x.Name)) + ")");
                return;
            }

            LogInfo($"{helpers.Name} {helpers.Version}");

            var reactiveObject = ModuleDefinition.FindType("ReactiveUI", "ReactiveObject", reactiveUI);

            // The types we will scan are subclasses of ReactiveObject
            var targetTypes = ModuleDefinition.GetAllTypes().Where(x => x.BaseType != null && reactiveObject.IsAssignableFrom(x.BaseType));

            var observableAsPropertyHelper         = ModuleDefinition.FindType("ReactiveUI", "ObservableAsPropertyHelper`1", reactiveUI, "T");
            var observableAsPropertyAttribute      = ModuleDefinition.FindType("ReactiveUI.Fody.Helpers", "ObservableAsPropertyAttribute", helpers);
            var observableAsPropertyHelperGetValue = ModuleDefinition.ImportReference(observableAsPropertyHelper.Resolve().Properties.Single(x => x.Name == "Value").GetMethod);
            var exceptionDefinition   = FindType(typeof(Exception).FullName);
            var constructorDefinition = exceptionDefinition.GetConstructors().Single(x => x.Parameters.Count == 1);
            var exceptionConstructor  = ModuleDefinition.ImportReference(constructorDefinition);

            foreach (var targetType in targetTypes)
            {
                foreach (var property in targetType.Properties.Where(x => x.IsDefined(observableAsPropertyAttribute) || (x.GetMethod?.IsDefined(observableAsPropertyAttribute) ?? false)).ToArray())
                {
                    var genericObservableAsPropertyHelper         = observableAsPropertyHelper.MakeGenericInstanceType(property.PropertyType);
                    var genericObservableAsPropertyHelperGetValue = observableAsPropertyHelperGetValue.Bind(genericObservableAsPropertyHelper);
                    ModuleDefinition.ImportReference(genericObservableAsPropertyHelperGetValue);

                    // Declare a field to store the property value
                    var field = new FieldDefinition("$" + property.Name, FieldAttributes.Private, genericObservableAsPropertyHelper);
                    targetType.Fields.Add(field);

                    // It's an auto-property, so remove the generated field
                    if (property.SetMethod != null && property.SetMethod.HasBody)
                    {
                        // Remove old field (the generated backing field for the auto property)
                        var oldField           = (FieldReference)property.GetMethod.Body.Instructions.Where(x => x.Operand is FieldReference).Single().Operand;
                        var oldFieldDefinition = oldField.Resolve();
                        targetType.Fields.Remove(oldFieldDefinition);

                        // Re-implement setter to throw an exception
                        property.SetMethod.Body = new MethodBody(property.SetMethod);
                        property.SetMethod.Body.Emit(il =>
                        {
                            il.Emit(OpCodes.Ldstr, "Never call the setter of an ObservabeAsPropertyHelper property.");
                            il.Emit(OpCodes.Newobj, exceptionConstructor);
                            il.Emit(OpCodes.Throw);
                            il.Emit(OpCodes.Ret);
                        });
                    }

                    property.GetMethod.Body = new MethodBody(property.GetMethod);
                    property.GetMethod.Body.Emit(il =>
                    {
                        var isValid = il.Create(OpCodes.Nop);
                        il.Emit(OpCodes.Ldarg_0);                                               // this
                        il.Emit(OpCodes.Ldfld, field.BindDefinition(targetType));               // pop -> this.$PropertyName
                        il.Emit(OpCodes.Dup);                                                   // Put an extra copy of this.$PropertyName onto the stack
                        il.Emit(OpCodes.Brtrue, isValid);                                       // If the helper is null, return the default value for the property
                        il.Emit(OpCodes.Pop);                                                   // Drop this.$PropertyName
                        EmitDefaultValue(property.GetMethod.Body, il, property.PropertyType);   // Put the default value onto the stack
                        il.Emit(OpCodes.Ret);                                                   // Return that default value
                        il.Append(isValid);                                                     // Add a marker for if the helper is not null
                        il.Emit(OpCodes.Callvirt, genericObservableAsPropertyHelperGetValue);   // pop -> this.$PropertyName.Value
                        il.Emit(OpCodes.Ret);                                                   // Return the value that is on the stack
                    });
                }
            }
        }
Exemplo n.º 41
0
 public static TypeDefinition InjectClassDefinition(ModuleDefinition mdef, string name, TypeReference baseType)
 {
     return(InjectTypeDefinition(mdef, name, baseType));
 }
 public XUnitInstrumentator(ModuleDefinition testModule, InstrumentatorParameters parameters) : base(testModule, parameters)
 {
 }
Exemplo n.º 43
0
        public override void Execute()
        {
            foreach (var definitionType in ModuleDefinition.Types.Where(x => x.Properties.Any()))
            {
                var equals =
                    new MethodDefinition(
                        nameof(object.Equals),
                        MethodAttributes.Public
                        | MethodAttributes.HideBySig
                        | MethodAttributes.Virtual,
                        ModuleDefinition.TypeSystem.Boolean)
                {
                    Body =
                    {
                        MaxStackSize = 2,
                        InitLocals   = true
                    }
                };

                // Init arguments.
                var argumentObj = new ParameterDefinition("other", ParameterAttributes.None, ModuleDefinition.TypeSystem.Object);
                equals.Parameters.Add(argumentObj);

                equals.Body.Variables.Add(new VariableDefinition(definitionType));
                equals.Body.Variables.Add(new VariableDefinition(ModuleDefinition.TypeSystem.Boolean));
                equals.Body.Variables.Add(new VariableDefinition(ModuleDefinition.TypeSystem.Int32));
                equals.Body.Variables.Add(new VariableDefinition(ModuleDefinition.TypeSystem.Boolean));

                // Labels for goto.
                var labelReturnFalse = Instruction.Create(OpCodes.Nop);

                var processor = equals.Body.GetILProcessor();

                // Foo foo = other as Foo;
                processor.Append(Instruction.Create(OpCodes.Ldarg_1));
                processor.Append(Instruction.Create(OpCodes.Isinst, definitionType));
                processor.Append(Instruction.Create(OpCodes.Stloc_0));

                // if (foo != null)
                processor.Append(Instruction.Create(OpCodes.Ldloc_0));
                processor.Append(Instruction.Create(OpCodes.Ldnull));
                processor.Append(Instruction.Create(OpCodes.Cgt_Un));
                processor.Append(Instruction.Create(OpCodes.Stloc_1));
                processor.Append(Instruction.Create(OpCodes.Ldloc_1));
                processor.Append(Instruction.Create(OpCodes.Brfalse_S, labelReturnFalse));

                // return Identify.Equals(foo.Identify);
                var property = definitionType.Properties.First();
                processor.Append(Instruction.Create(OpCodes.Ldarg_0));
                processor.Append(Instruction.Create(OpCodes.Call, property.GetMethod));
                processor.Append(Instruction.Create(OpCodes.Stloc_2));
                processor.Append(Instruction.Create(OpCodes.Ldloca_S, equals.Body.Variables[2]));
                processor.Append(Instruction.Create(OpCodes.Ldloc_0));
                processor.Append(Instruction.Create(OpCodes.Callvirt, property.GetMethod));

                var intDefinition = ModuleDefinition.TypeSystem.Int32.Resolve();
                var equalsByInt   = intDefinition
                                    .Methods
                                    .Single(x =>
                                            x.Name == nameof(int.Equals) &&
                                            x.Parameters.Count == 1 &&
                                            x.Parameters.Single().ParameterType.FullName == intDefinition.FullName);
                processor.Append(Instruction.Create(OpCodes.Call, ModuleDefinition.ImportReference(equalsByInt)));
                processor.Append(Instruction.Create(OpCodes.Ret));


                // return false;
                processor.Append(labelReturnFalse);
                processor.Append(Instruction.Create(OpCodes.Ldc_I4_0));
                processor.Append(Instruction.Create(OpCodes.Ret));


                definitionType.Methods.Add(equals);
            }
        }
Exemplo n.º 44
0
 /*********
 ** Public methods
 *********/
 /// <summary>Construct an instance.</summary>
 /// <param name="module">The module to rewrite.</param>
 /// <param name="rewriteType">Handle or rewrite a type reference if needed.</param>
 /// <param name="rewriteInstruction">Handle or rewrite a CIL instruction if needed.</param>
 public RecursiveRewriter(ModuleDefinition module, RewriteTypeDelegate rewriteType, RewriteInstructionDelegate rewriteInstruction)
 {
     this.Module                 = module;
     this.RewriteTypeImpl        = rewriteType;
     this.RewriteInstructionImpl = rewriteInstruction;
 }
Exemplo n.º 45
0
 public ISymbolReader GetSymbolReader(ModuleDefinition module, Stream symbolStream)
 {
     return(IsPortablePdb(symbolStream)
         ? new PortablePdbReaderProvider().GetSymbolReader(module, symbolStream)
         : new NativePdbReaderProvider().GetSymbolReader(module, symbolStream));
 }
Exemplo n.º 46
0
        static bool SetterValueIsCollection(FieldReference bindablePropertyReference, ModuleDefinition module, BaseNode node, ILContext context)
        {
            var items = (node as IElementNode)?.CollectionItems;

            if (items == null || items.Count <= 0)
            {
                return(false);
            }

            // Is this a generic type ?
            var generic = bindablePropertyReference.GetBindablePropertyType(node, module) as GenericInstanceType;

            // With a single generic argument?
            if (generic?.GenericArguments.Count != 1)
            {
                return(false);
            }

            // Is the generic argument assignable from this value?
            var genericType = generic.GenericArguments[0];

            if (!(items[0] is IElementNode firstItem))
            {
                return(false);
            }

            return(context.Variables[firstItem].VariableType.InheritsFromOrImplements(genericType));
        }
Exemplo n.º 47
0
 ISymbolReader GetSymbolReader(ModuleDefinition module, Disposable <Stream> symbolStream, string fileName)
 {
     return(new PortablePdbReader(ImageReader.ReadPortablePdb(symbolStream, fileName), module));
 }
Exemplo n.º 48
0
        public IEnumerable <Instruction> ProvideValue(VariableDefinitionReference vardefref, ModuleDefinition module, BaseNode node, ILContext context)
        {
            INode valueNode = null;

            if (!((IElementNode)node).Properties.TryGetValue(new XmlName("", "Value"), out valueNode) &&
                !((IElementNode)node).Properties.TryGetValue(new XmlName(XamlParser.XFUri, "Value"), out valueNode) &&
                ((IElementNode)node).CollectionItems.Count == 1)
            {
                valueNode = ((IElementNode)node).CollectionItems[0];
            }

            var bpNode = ((ValueNode)((IElementNode)node).Properties[new XmlName("", "Property")]);
            var bpRef  = (new BindablePropertyConverter()).GetBindablePropertyFieldReference((string)bpNode.Value, module, bpNode);

            if (SetterValueIsCollection(bpRef, module, node, context))
            {
                yield break;
            }

            if (valueNode == null)
            {
                throw new XamlParseException("Missing Value for Setter", (IXmlLineInfo)node);
            }

            //if it's an elementNode, there's probably no need to convert it
            if (valueNode is IElementNode)
            {
                yield break;
            }

            var value      = ((string)((ValueNode)valueNode).Value);
            var setterType = ("Microsoft.Maui.Controls", "Microsoft.Maui.Controls", "Setter");

            //push the setter
            foreach (var instruction in vardefref.VariableDefinition.LoadAs(module.GetTypeDefinition(setterType), module))
            {
                yield return(instruction);
            }

            //push the value
            foreach (var instruction in ((ValueNode)valueNode).PushConvertedValue(context, bpRef, valueNode.PushServiceProvider(context, bpRef: bpRef), boxValueTypes: true, unboxValueTypes: false))
            {
                yield return(instruction);
            }

            //set the value
            yield return(Instruction.Create(OpCodes.Callvirt, module.ImportPropertySetterReference(setterType, propertyName: "Value")));
        }
Exemplo n.º 49
0
 public PortablePdbWriter(MetadataBuilder pdb_metadata, ModuleDefinition module)
 {
     this.pdb_metadata = pdb_metadata;
     this.module       = module;
 }
 private static void UpdateModuleDictionary(ModuleDefinition module, string moduleFilePath)
 {
     moduleDictionary[moduleFilePath.CleanFileName()] = new Tuple <DateTime, ModuleDefinition>(File.GetLastWriteTime(moduleFilePath), module);
 }
Exemplo n.º 51
0
 public void TerminateModuleDefinition(ModuleDefinition module)
 {
 }
Exemplo n.º 52
0
 public ClientRpcProcessor(ModuleDefinition module, Readers readers, Writers writers, IWeaverLogger logger) : base(module, readers, writers, logger)
 {
 }
Exemplo n.º 53
0
 public MemberReferenceConverter(ModuleDefinition module)
 {
     this.module = module;
 }
Exemplo n.º 54
0
        public static FieldReference CreateImportedType(this FieldReference fieldRef, ModuleDefinition module)
        {
            var declaringType = fieldRef.DeclaringType.CreateImportedType(module);
            var fieldType     = fieldRef.FieldType.CreateImportedType(module);
            var importedField = new FieldReference(fieldRef.Name, fieldType, declaringType);

            return(module.ImportReference(importedField));
        }
        public static TypeReference GetBindablePropertyType(this FieldReference bpRef, IXmlLineInfo iXmlLineInfo, ModuleDefinition module)
        {
            if (!bpRef.Name.EndsWith("Property", StringComparison.InvariantCulture))
            {
                throw new XamlParseException($"The name of the bindable property {bpRef.Name} does not ends with \"Property\". This is the kind of convention the world is build upon, a bit like Planck's constant.", iXmlLineInfo);
            }
            var           bpName = bpRef.Name.Substring(0, bpRef.Name.Length - 8);
            var           owner  = bpRef.DeclaringType;
            TypeReference _;

            var getter = owner.GetProperty(pd => pd.Name == bpName, out _)?.GetMethod;

            if (getter == null || getter.IsStatic || !getter.IsPublic)
            {
                getter = null;
            }
            getter = getter ?? owner.GetMethods(md => md.Name == $"Get{bpName}" &&
                                                md.IsStatic &&
                                                md.IsPublic &&
                                                md.Parameters.Count == 1 &&
                                                md.Parameters[0].ParameterType.InheritsFromOrImplements(module.ImportReference(typeof(BindableObject))), module).SingleOrDefault()?.Item1;

            if (getter == null)
            {
                throw new XamlParseException($"Missing a public static Get{bpName} or a public instance property getter for the attached property \"{bpRef.DeclaringType}.{bpRef.Name}\"", iXmlLineInfo);
            }
            return(getter.ReturnType);
        }
Exemplo n.º 56
0
 public CommonTypeSystem(ModuleDefinition module)
     : base(module)
 {
 }
Exemplo n.º 57
0
 public CoreLibMetadataImporter(ModuleDefinition module)
 {
     _module = module;
     _defaultMetadataImporter = new DefaultMetadataImporter(module);
 }
Exemplo n.º 58
0
 TypeSystem(ModuleDefinition module)
 {
     this.module = module;
 }
Exemplo n.º 59
0
 public ModuleDefinition reload(byte[] newModuleData, DumpedMethods dumpedMethods)
 {
     AssemblyResolver.Instance.removeModule(module);
     DotNetUtils.typeCaches.invalidate(module);
     return(setModule(ModuleDefinition.ReadModule(new MemoryStream(newModuleData), getReaderParameters(), dumpedMethods)));
 }
Exemplo n.º 60
0
 public static MethodReference ImportMethod <T>(ModuleDefinition module, string name)
 {
     return(module.ImportReference(typeof(T).GetMethod(name, Type.EmptyTypes)));
 }