public MethodDefinition GetVirtualizedAttribute(AssemblyDefinition assembly, IAssemblyTracker tracker) { if (!_useAttribute) { return(null); } if (_attributeCtor == null) { var attributeCtorID = _infoProvider.GetVirtualizedAttribute(); _attributeCtor = CecilResolver.ResolveToMethodDefinition(attributeCtorID, tracker, out _customAttributeAssembly); if (_attributeCtor == null) { _useAttribute = false; return(null); } if (_attributeCtor.Parameters.Count != 1) { throw new ArgumentException("MethodVirtualizer: The given custom attribute does not have one (string) ctor parameter."); } } if (_customAttributeAssembly != null) { tracker.TrackNewReference(assembly, _customAttributeAssembly); } return(_attributeCtor); }
public ITargetSelectionStrategy CreateSelector(IAssemblyTracker tracker) { ArgumentUtility.CheckNotNull("tracker", tracker); var strategies = new List <ITargetSelectionStrategy> (); var visitorStrategies = new List <IVisitorTargetSelectionStrategy> (); if (_regex != null) { strategies.Add(new RegularExpressionSelectionStrategy(_regex)); } if (_classNames.Count > 0) { visitorStrategies.Add(new ClassNameSelectionStrategy(_classNames)); } if (_attributeName != null) { visitorStrategies.Add(new AttributeNameSelectionStrategy(_attributeName)); } if (visitorStrategies.Count > 0) { strategies.Add(new ClassHierarchyVisitorStrategy(tracker, visitorStrategies)); } return(new TargetSelector(strategies)); }
/// <summary> /// Resolves the given memberID to a monocecil methodDefinition. The out parameter is null if the assembly containing the method is an untracked assembly /// and does not need to be tracked. In case it is tracked, the out parameter contains the containing assembly and a new reference has to be added. /// </summary> public static MethodDefinition ResolveToMethodDefinition(MemberID member, IAssemblyTracker tracker, out AssemblyNameReference containingTrackedAssembly) { if (member == null) { containingTrackedAssembly = null; return(null); } if (!_cachedMethods.ContainsKey(member)) { var containingType = ResolveToTypeDefinition(member, tracker, out containingTrackedAssembly); if (containingType == null) { return(null); } foreach (var md in containingType.Methods) { if (md.MetadataToken.ToInt32() == member.Token) { _cachedMethods[member] = new Tuple <MethodDefinition, AssemblyNameReference>(md, containingTrackedAssembly); return(_cachedMethods[member].Item1); } } containingTrackedAssembly = null; return(null); } containingTrackedAssembly = _cachedMethods[member].Item2; return(_cachedMethods[member].Item1); }
public void Transform(IAssemblyTracker tracker) { ArgumentUtility.CheckNotNull("tracker", tracker); _selectionStrategy = _selectionFactory.CreateSelector(tracker); var modifiedMethods = from assemblyDefinition in tracker.GetAssemblies() from typeDefinition in assemblyDefinition.LoadAllTypes() from methodDefinition in typeDefinition.Methods where _selectionStrategy.IsTarget(methodDefinition, assemblyDefinition) select new { Assembly = assemblyDefinition, Method = methodDefinition }; foreach (var modifiedMethodDefinition in modifiedMethods.ToList()) { if (!modifiedMethodDefinition.Method.IsVirtual && !modifiedMethodDefinition.Method.IsStatic && !modifiedMethodDefinition.Method.IsConstructor && !modifiedMethodDefinition.Method.CustomAttributes.Any(ca => ca.AttributeType.Namespace == "System.Runtime.Serialization")) { tracker.MarkModified(modifiedMethodDefinition.Assembly); var virtualMethod = _codeGenerator.GenerateMethodAndMoveBody(modifiedMethodDefinition.Method); modifiedMethodDefinition.Method.DeclaringType.Methods.Add(virtualMethod); AddAttributes(virtualMethod); _markingAttributeStrategy.AddCustomAttribute(modifiedMethodDefinition.Method, modifiedMethodDefinition.Assembly); } } }
public ClassHierarchyVisitorStrategy(IAssemblyTracker tracker, IList<IVisitorTargetSelectionStrategy> visitorStrategies) { _visitorStrategies = visitorStrategies; _targetTypes = new Dictionary<Tuple<TypeDefinition, AssemblyDefinition>, bool>(); _tracker = tracker; InitTargetTypes(_tracker); }
public void SetUp() { _verifier = PEVerifier.CreateDefault(); Directory.CreateDirectory(TempPath); foreach (var file in Directory.EnumerateFiles(@AssemblyPath, "*.dll", SearchOption.TopDirectoryOnly)) { Console.WriteLine(@TempPath + file.Substring(file.IndexOf("integration") + 11)); File.Copy(file, @TempPath + file.Substring(file.IndexOf("integration") + 11), true); } var allFiles = Directory.EnumerateFiles(@TempPath, "*.dll", SearchOption.AllDirectories) .Concat(Directory.EnumerateFiles(@TempPath, "*.exe", SearchOption.AllDirectories)); List <AssemblyDefinition> assemblies = allFiles.Select(AssemblyDefinition.ReadAssembly).ToList(); _tracker = new AssemblyTracker(assemblies, new TypeDefinitionCache()); var options = new OptionSet(); var selectorFactory = new TargetSelectorFactory(); selectorFactory.AddOptions(options); options.Parse(new[] { "--regex:(.*)Locked(.*)" }); _transformator = new AssemblyMethodsVirtualizer.AssemblyMethodsVirtualizer( new GeneratedMarkingAttributeStrategy("test", "nonVirtual"), new TargetSelectorFactory(), new ILCodeGenerator("<>unspeakable_")); _signer = new AssemblySigner(new ModuleDefinitionWriter(new FileSystem.FileSystem(), null, new List <StrongNameKeyPair>())); }
public void Transform(IAssemblyTracker tracker) { ArgumentUtility.CheckNotNull("tracker", tracker); MethodDefinition customAttributeCtor; var modifiedMethods = from assemblyDefinition in tracker.GetAssemblies() from typeDefinition in assemblyDefinition.LoadAllTypes() where _wrapper.ShouldVirtualizeType(typeDefinition) from methodDefinition in typeDefinition.Methods where _wrapper.ShouldVirtualizeMethod(methodDefinition) select new { Assembly = assemblyDefinition, Method = methodDefinition }; foreach (var modifiedMethodDefinition in modifiedMethods.ToList()) { if (!modifiedMethodDefinition.Method.IsVirtual && !modifiedMethodDefinition.Method.IsStatic && !modifiedMethodDefinition.Method.IsConstructor && !modifiedMethodDefinition.Method.CustomAttributes.Any(ca => ca.AttributeType.Namespace == "System.Runtime.Serialization")) { tracker.MarkModified(modifiedMethodDefinition.Assembly); var virtualMethod = _codeGenerator.GenerateMethodAndMoveBody( modifiedMethodDefinition.Method, _wrapper.GetUnspeakableMethodName(modifiedMethodDefinition.Method) ); modifiedMethodDefinition.Method.DeclaringType.Methods.Add(virtualMethod); if ((customAttributeCtor = _wrapper.GetVirtualizedAttribute(modifiedMethodDefinition.Assembly, tracker)) != null) { AddAttributes(modifiedMethodDefinition.Method, virtualMethod, customAttributeCtor); } } } }
public MethodReference GetCallableObjectFactoryCreateMethod(AssemblyDefinition assemblyDef, ModuleDefinition moduleDefinition, TypeReference instantiatedType, IAssemblyTracker tracker) { MethodReference reference; if (assemblyDef.FullName == _remotionInterfacesAssemblyName && (reference = SearchObjectFactoryMethod (assemblyDef)) != null) { ((GenericInstanceMethod) reference).GenericArguments.Add (instantiatedType); return reference; } var tempRef = GetOrCreateRemotionInterfacesReference (assemblyDef, moduleDefinition, tracker); var objectFactoryReference = new TypeReference (_objectFactoryNamespace, _objectFactoryName, moduleDefinition, tempRef); var paramListReference = new TypeReference (_paramListNamespace, _paramListName, moduleDefinition, tempRef); var createReference = new MethodReference ("Create", moduleDefinition.TypeSystem.Void, objectFactoryReference); var createTypeParam = new GenericParameter ("T", createReference); createReference.GenericParameters.Add (createTypeParam); createReference.ReturnType = createTypeParam; createReference.Parameters.Add (new ParameterDefinition (moduleDefinition.TypeSystem.Boolean)); createReference.Parameters.Add (new ParameterDefinition (paramListReference)); createReference.Parameters.Add (new ParameterDefinition (new ArrayType (moduleDefinition.TypeSystem.Object))); var instanceMethod = new GenericInstanceMethod (createReference); instanceMethod.GenericArguments.Add (instantiatedType); return instanceMethod; }
public void Transform(IAssemblyTracker tracker) { ArgumentUtility.CheckNotNull ("tracker", tracker); MethodDefinition customAttributeCtor; var modifiedMethods = from assemblyDefinition in tracker.GetAssemblies () from typeDefinition in assemblyDefinition.LoadAllTypes () where _wrapper.ShouldVirtualizeType (typeDefinition) from methodDefinition in typeDefinition.Methods where _wrapper.ShouldVirtualizeMethod (methodDefinition) select new { Assembly = assemblyDefinition, Method = methodDefinition }; foreach (var modifiedMethodDefinition in modifiedMethods.ToList ()) { if (!modifiedMethodDefinition.Method.IsVirtual && !modifiedMethodDefinition.Method.IsStatic && !modifiedMethodDefinition.Method.IsConstructor && !modifiedMethodDefinition.Method.CustomAttributes.Any (ca => ca.AttributeType.Namespace == "System.Runtime.Serialization")) { tracker.MarkModified (modifiedMethodDefinition.Assembly); var virtualMethod = _codeGenerator.GenerateMethodAndMoveBody ( modifiedMethodDefinition.Method, _wrapper.GetUnspeakableMethodName (modifiedMethodDefinition.Method) ); modifiedMethodDefinition.Method.DeclaringType.Methods.Add (virtualMethod); if ((customAttributeCtor = _wrapper.GetVirtualizedAttribute (modifiedMethodDefinition.Assembly, tracker)) != null) AddAttributes (modifiedMethodDefinition.Method, virtualMethod, customAttributeCtor); } } }
private void InitTargetTypes(IAssemblyTracker tracker) { foreach (var assembly in tracker.GetAssemblies()) { foreach (var module in assembly.Modules) { foreach (var typ in module.Types) { if (_visitorStrategies.Any(strategy => strategy.AreAllMethodsOfTypeTarget(typ))) { _targetTypes.Add(Tuple.Create(typ, assembly), true); } } } } foreach (var assembly in tracker.GetAssemblies()) { foreach (var module in assembly.Modules) { foreach (var typ in module.Types) { _targetTypes[Tuple.Create(typ, assembly)] = IsTargetRecursive(Tuple.Create(typ, assembly)); } } } }
public ClassHierarchyVisitorStrategy(IAssemblyTracker tracker, IList <IVisitorTargetSelectionStrategy> visitorStrategies) { _visitorStrategies = visitorStrategies; _targetTypes = new Dictionary <Tuple <TypeDefinition, AssemblyDefinition>, bool>(); _tracker = tracker; InitTargetTypes(_tracker); }
public void InitializeCache(IAssemblyTracker tracker) { _cachedTypes.Clear(); foreach (var assembly in tracker.GetAssemblies()) foreach (var type in assembly.LoadAllTypes()) _cachedTypes.Add (assembly.Name.BuildAssemblyQualifiedName (type), Tuple.Create (type, assembly)); IsInitialized = true; }
public bool CreateNewObjectMethod(AssemblyDefinition assembly, MethodDefinition templateMethod, IAssemblyTracker tracker, INewTransformerInfoWrapper infoWrapper) { MethodDefinition factoryMethod = null; if ((factoryMethod = infoWrapper.GetFactoryMethod (templateMethod, assembly, tracker)) != null) { if (factoryMethod.GenericParameters.Count != 1 || factoryMethod.Parameters.Count != 1 || !factoryMethod.IsStatic) throw new ArgumentException ("Factory method to create object does not have correct signature [public static T Create<T> (ParamList)]"); TypeReference returnType = templateMethod.DeclaringType; if (templateMethod.DeclaringType.HasGenericParameters) { returnType = new GenericInstanceType (templateMethod.DeclaringType); foreach (var a in templateMethod.DeclaringType.GenericParameters.ToArray ()) { returnType.GenericParameters.Add (a); ((GenericInstanceType) returnType).GenericArguments.Add (a); } } var importedFactoryMethod = templateMethod.Module.Import (factoryMethod); var genericInstanceMethod = new GenericInstanceMethod (importedFactoryMethod); genericInstanceMethod.GenericArguments.Add (templateMethod.DeclaringType); var paramlistDef = factoryMethod.Parameters[0].ParameterType.Resolve (); var importedParamListCreateMethod = templateMethod.Module.Import (SearchParamListFactoryMethod (paramlistDef, templateMethod)); if (importedParamListCreateMethod == null) throw new ArgumentException ("Factory method: no corresponding 'create' method could have been found. [argument count]"); var newObjectMethod = new MethodDefinition ( infoWrapper.GetWrapperMethodName (templateMethod), MethodAttributes.Public | MethodAttributes.Static, returnType ); var instructions = newObjectMethod.Body.Instructions; foreach (var param in templateMethod.Parameters) { newObjectMethod.Parameters.Add (param); instructions.Add (Instruction.Create (OpCodes.Ldarg, param)); } instructions.Add(Instruction.Create (OpCodes.Call, importedParamListCreateMethod)); instructions.Add(Instruction.Create (OpCodes.Call, genericInstanceMethod)); instructions.Add (Instruction.Create (OpCodes.Ret)); newObjectMethod.Body.OptimizeMacros (); newObjectMethod.IsHideBySig = true; templateMethod.DeclaringType.Methods.Add (newObjectMethod); return true; } return false; }
public void SetUp() { _fileSystemMock = MockRepository.GenerateStrictMock <IFileSystem> (); _assemblyDefinition1 = AssemblyDefinitionObjectMother.CreateMultiModuleAssemblyWithCtorsAndMethodBody(); _tracker = MockRepository.GenerateStrictMock <IAssemblyTracker> (); _checker = MockRepository.GenerateStrictMock <IMixinChecker>(); _referenceGenerator = MockRepository.GenerateStrictMock <IReferenceGenerator>(); _codeGenerator = new ILCodeGenerator(_referenceGenerator, _checker); }
public void SetUp() { _assemblyDefinition = AssemblyDefinitionObjectMother.CreateMultiModuleAssemblyDefinition(); _tracker = new AssemblyTracker(new [] { _assemblyDefinition }, new TypeDefinitionCache()); _markingAttributeStrategy = MockRepository.GenerateStub <IMarkingAttributeStrategy> (); _codeGenerator = MockRepository.GenerateStub <ICodeGenerator>(); _selectionFactory = new TargetSelectorFactory(); _options = new OptionSet(); _methodsVirtualizer = new AssemblyMethodsVirtualizer(_markingAttributeStrategy, _selectionFactory, _codeGenerator); }
public MethodDefinition GetFactoryMethod(MethodReference ctor, AssemblyDefinition assembly, IAssemblyTracker tracker) { if (!_factoryMethods.ContainsKey (ctor)) { var memberId = CecilResolver.CreateMemberID (ctor.Resolve()); AssemblyNameReference containingTrackedAssembly; _factoryMethods[ctor] = CecilResolver.ResolveToMethodDefinition (_infoProvider.GetFactoryMethodFunc (memberId), tracker, out containingTrackedAssembly); if (containingTrackedAssembly != null) tracker.TrackNewReference (assembly, containingTrackedAssembly); } return _factoryMethods[ctor]; }
public void SetUp() { _trackerMock = MockRepository.GenerateStrictMock <IAssemblyTracker>(); _trackerFactoryMock = MockRepository.GenerateStrictMock <IAssemblyTrackerFactory>(); _transformerMock = MockRepository.GenerateStrictMock <IAssemblyTransformation>(); _transformationFactoryMock = MockRepository.GenerateStrictMock <IAssemblyTransformationFactory>(); _transformerMock2 = MockRepository.GenerateStrictMock <IAssemblyTransformation> (); _transformationFactoryMock2 = MockRepository.GenerateStrictMock <IAssemblyTransformationFactory> (); _signerMock = MockRepository.GenerateStrictMock <IAssemblySigner>(); _signerFactoryMock = MockRepository.GenerateStrictMock <IAssemblySignerFactory>(); _infoBroker = MockRepository.GenerateStub <IAppDomainInfoBroker>(); }
public void InitializeCache(IAssemblyTracker tracker) { _cachedTypes.Clear(); foreach (var assembly in tracker.GetAssemblies()) { foreach (var type in assembly.LoadAllTypes()) { _cachedTypes.Add(assembly.Name.BuildAssemblyQualifiedName(type), Tuple.Create(type, assembly)); } } IsInitialized = true; }
public void SignAndSave(IAssemblyTracker tracker) { ArgumentUtility.CheckNotNull ("tracker", tracker); ICollection<AssemblyDefinition> assembliesToSave = new List<AssemblyDefinition> (tracker.GetModifiedAssemblies ()); while (assembliesToSave.Count != 0) { var modifiedAssembly = assembliesToSave.First(); SignAndSave (tracker, modifiedAssembly, assembliesToSave); tracker.MarkUnmodified (modifiedAssembly); } }
public void SignAndSave(IAssemblyTracker tracker) { ArgumentUtility.CheckNotNull("tracker", tracker); ICollection <AssemblyDefinition> assembliesToSave = new List <AssemblyDefinition> (tracker.GetModifiedAssemblies()); while (assembliesToSave.Count != 0) { var modifiedAssembly = assembliesToSave.First(); SignAndSave(tracker, modifiedAssembly, assembliesToSave); tracker.MarkUnmodified(modifiedAssembly); } }
public void SetUp() { _fileSystemMock = MockRepository.GenerateStrictMock <IFileSystem> (); _assemblyDefinition1 = AssemblyDefinitionObjectMother.CreateMultiModuleAssemblyDefinition(); _tracker = MockRepository.GenerateStrictMock <IAssemblyTracker>(); _checker = MockRepository.GenerateMock <IMixinChecker>(); //_referenceGenerator = MockRepository.GenerateStrictMock<IReferenceGenerator>(); _codeGenerator = MockRepository.GenerateStrictMock <ICodeGenerator>(); _generator = new ConstructorGenerator.ConstructorGenerator(_checker, _codeGenerator); }
public void SetUp() { _fileSystemMock = MockRepository.GenerateStrictMock<IFileSystem> (); _assemblyDefinition1 = AssemblyDefinitionObjectMother.CreateMultiModuleAssemblyDefinition (); _tracker = MockRepository.GenerateStrictMock<IAssemblyTracker>(); _checker = MockRepository.GenerateMock<IMixinChecker>(); //_referenceGenerator = MockRepository.GenerateStrictMock<IReferenceGenerator>(); _codeGenerator = MockRepository.GenerateStrictMock<ICodeGenerator>(); _generator = new ConstructorGenerator.ConstructorGenerator (_checker, _codeGenerator); }
private void InitTargetTypes(IAssemblyTracker tracker) { foreach (var assembly in tracker.GetAssemblies ()) foreach (var module in assembly.Modules) foreach (var typ in module.Types) if (_visitorStrategies.Any (strategy => strategy.AreAllMethodsOfTypeTarget (typ))) _targetTypes.Add (Tuple.Create (typ, assembly), true); foreach (var assembly in tracker.GetAssemblies ()) foreach (var module in assembly.Modules) foreach (var typ in module.Types) _targetTypes[Tuple.Create (typ, assembly)] = IsTargetRecursive (Tuple.Create (typ, assembly)); }
public MethodReference GetCallableParamListCreateMethod(AssemblyDefinition assemblyDef, MethodReference ctor, IAssemblyTracker tracker) { var tempRef = GetOrCreateRemotionInterfacesReference (assemblyDef, ctor.DeclaringType.Module, tracker); var paramListCreateReference = GetOrCreateParamList (ctor.Parameters.Count, ctor.DeclaringType.Module, tempRef); if (ctor.Parameters.Count > 0) { paramListCreateReference = new GenericInstanceMethod (paramListCreateReference); foreach (var param in ctor.Parameters) ((GenericInstanceMethod) paramListCreateReference).GenericArguments.Add (param.ParameterType); } return paramListCreateReference; }
private void SignAndSave(IAssemblyTracker tracker, AssemblyDefinition assembly, ICollection<AssemblyDefinition> assembliesToSave) { // Remove this assembly from the list of assemblies to save before descending into recursive calls - this will avoid an endless loop with // circular references. assembliesToSave.Remove (assembly); // Save all referenced assemblies before saving this assembly. Note that the referenced assemblies will automatically update this assembly's // references if they change their name while saving. foreach (var moduleDefinition in assembly.Modules) { foreach (var assemblyNameReference in moduleDefinition.AssemblyReferences) { var referencedAssembly = tracker.GetAssembliesByReference (assemblyNameReference); foreach (var adef in referencedAssembly) { if (assembliesToSave.Contains (adef)) { SignAndSave (tracker, adef, assembliesToSave); } } } // If a referenced assembly changes this assembly's references, this assembly will be modified again. Mark unmodified before saving. assembliesToSave.Remove (assembly); tracker.MarkUnmodified (assembly); // Keep track of original name of this assembly before saving the module. The writer might change the name. var originalAssemblyName = assembly.Name.Clone(); _writer.WriteModule (moduleDefinition); // If the writer has changed the name of this assembly, all assemblies referencing this assembly must be updated. Because of the recursive // call above, we can be sure that these assemblies will be saved after returning from this method: it is guaranteed that the referenced // assemblies are saved before the referencing assemblies. // The only case where this is not true is with circular references. In this case, the recursion will stop when the first assembly in the // cycle is reached again (because it has been marked unmodified before the recursive step, and the recursion will end when an unmodified // assembly is reached). In that case, it can be assumed that the other SignAndSave method will pick up the still-modified assemblies later. if (!originalAssemblyName.MatchesDefinition (assembly.Name)) { foreach (var assemblyDefinition in tracker.GetReverseReferences (assembly)) { UpdateReferences (assemblyDefinition, originalAssemblyName, assembly.Name); if (!assembliesToSave.Contains (assemblyDefinition)) { assembliesToSave.Add (assemblyDefinition); } } } } }
private void SignAndSave(IAssemblyTracker tracker, AssemblyDefinition assembly, ICollection <AssemblyDefinition> assembliesToSave) { // Remove this assembly from the list of assemblies to save before descending into recursive calls - this will avoid an endless loop with // circular references. assembliesToSave.Remove(assembly); // Save all referenced assemblies before saving this assembly. Note that the referenced assemblies will automatically update this assembly's // references if they change their name while saving. foreach (var moduleDefinition in assembly.Modules) { foreach (var assemblyNameReference in moduleDefinition.AssemblyReferences) { var referencedAssembly = tracker.GetAssembliesByReference(assemblyNameReference); foreach (var adef in referencedAssembly) { if (assembliesToSave.Contains(adef)) { SignAndSave(tracker, adef, assembliesToSave); } } } // If a referenced assembly changes this assembly's references, this assembly will be modified again. Mark unmodified before saving. assembliesToSave.Remove(assembly); tracker.MarkUnmodified(assembly); // Keep track of original name of this assembly before saving the module. The writer might change the name. var originalAssemblyName = assembly.Name.Clone(); _writer.WriteModule(moduleDefinition); // If the writer has changed the name of this assembly, all assemblies referencing this assembly must be updated. Because of the recursive // call above, we can be sure that these assemblies will be saved after returning from this method: it is guaranteed that the referenced // assemblies are saved before the referencing assemblies. // The only case where this is not true is with circular references. In this case, the recursion will stop when the first assembly in the // cycle is reached again (because it has been marked unmodified before the recursive step, and the recursion will end when an unmodified // assembly is reached). In that case, it can be assumed that the other SignAndSave method will pick up the still-modified assemblies later. if (!originalAssemblyName.MatchesDefinition(assembly.Name)) { foreach (var assemblyDefinition in tracker.GetReverseReferences(assembly)) { UpdateReferences(assemblyDefinition, originalAssemblyName, assembly.Name); if (!assembliesToSave.Contains(assemblyDefinition)) { assembliesToSave.Add(assemblyDefinition); } } } } }
public void Transform(IAssemblyTracker tracker) { ArgumentUtility.CheckNotNull ("tracker", tracker); _tracker = tracker; foreach (var assemblyDefinition in tracker.GetAssemblies ()) { foreach (var typeDefinition in assemblyDefinition.LoadAllTypes ()) { ReplaceNewStatement (assemblyDefinition, typeDefinition); if (_factoryMakeProtected) GenerateNewObjectMethods (assemblyDefinition, typeDefinition); } } }
/// <summary> /// Resolves the given memberID to a monocecil typeDefinition. The out parameter is null if the assembly containing the type is an untracked assembly /// and does not need to be tracked. In case it is tracked, the out parameter contains the containing assembly and a new reference has to be added. /// </summary> public static TypeDefinition ResolveToTypeDefinition(MemberID member, IAssemblyTracker tracker, out AssemblyNameReference containingTrackedAssembly) { if (member == null) { containingTrackedAssembly = null; return(null); } containingTrackedAssembly = null; if (!_cachedTypes.ContainsKey(member)) { AssemblyDefinition containingAssembly = null; foreach (var assemblyDefinition in tracker.GetAssemblies()) { if (assemblyDefinition.FullName == member.AssemblyQualifiedTypeName.Substring(member.AssemblyQualifiedTypeName.IndexOf(",") + 1).Trim()) { containingAssembly = assemblyDefinition; } } if (containingAssembly == null) { containingAssembly = AssemblyDefinition.ReadAssembly(member.ModuleName); } else { containingTrackedAssembly = containingAssembly.Name; } foreach (var moduleDefinition in containingAssembly.Modules) { if (moduleDefinition.FullyQualifiedName == member.ModuleName) { foreach (var typeDefinition in moduleDefinition.Types) { if (typeDefinition.FullName == member.AssemblyQualifiedTypeName.Substring(0, member.AssemblyQualifiedTypeName.IndexOf(","))) { _cachedTypes[member] = new Tuple <TypeDefinition, AssemblyNameReference> (typeDefinition, containingAssembly.Name); return(_cachedTypes[member].Item1); } } } } containingTrackedAssembly = null; return(null); } containingTrackedAssembly = _cachedTypes[member].Item2; return(_cachedTypes[member].Item1); }
public void Transform(IAssemblyTracker tracker) { ArgumentUtility.CheckNotNull ("tracker", tracker); _tracker = tracker; var mixinTargetTypes = from assemblyDefinition in tracker.GetAssemblies () from typeDefinition in assemblyDefinition.LoadAllTypes() where _checker.CanBeMixed (assemblyDefinition.Name.BuildReflectionAssemblyQualifiedName(typeDefinition)) select new { Assembly = assemblyDefinition, TypeDef = typeDefinition }; foreach (var mixinTargetType in mixinTargetTypes.ToList ()) GenerateNewObjectMethods (mixinTargetType.Assembly, mixinTargetType.TypeDef); foreach(var assembly in tracker.GetAssemblies()) foreach (var typ in assembly.LoadAllTypes()) ReplaceNewStatement (assembly, typ); }
public void Transform(IAssemblyTracker tracker) { ArgumentUtility.CheckNotNull("tracker", tracker); _tracker = tracker; foreach (var assemblyDefinition in tracker.GetAssemblies()) { foreach (var typeDefinition in assemblyDefinition.LoadAllTypes()) { ReplaceNewStatement(assemblyDefinition, typeDefinition); if (_factoryMakeProtected) { GenerateNewObjectMethods(assemblyDefinition, typeDefinition); } } } }
public ITargetSelectionStrategy CreateSelector(IAssemblyTracker tracker) { ArgumentUtility.CheckNotNull ("tracker", tracker); var strategies = new List<ITargetSelectionStrategy> (); var visitorStrategies = new List<IVisitorTargetSelectionStrategy> (); if (_regex != null) strategies.Add (new RegularExpressionSelectionStrategy (_regex)); if (_classNames.Count > 0) visitorStrategies.Add (new ClassNameSelectionStrategy (_classNames)); if (_attributeName != null) visitorStrategies.Add (new AttributeNameSelectionStrategy (_attributeName)); if (visitorStrategies.Count > 0) strategies.Add (new ClassHierarchyVisitorStrategy(tracker, visitorStrategies)); return new TargetSelector(strategies); }
public MethodDefinition GetVirtualizedAttribute(AssemblyDefinition assembly, IAssemblyTracker tracker) { if (!_useAttribute) return null; if (_attributeCtor == null) { var attributeCtorID = _infoProvider.GetVirtualizedAttribute (); _attributeCtor = CecilResolver.ResolveToMethodDefinition (attributeCtorID, tracker, out _customAttributeAssembly); if (_attributeCtor == null) { _useAttribute = false; return null; } if (_attributeCtor.Parameters.Count != 1) throw new ArgumentException("MethodVirtualizer: The given custom attribute does not have one (string) ctor parameter."); } if (_customAttributeAssembly != null) tracker.TrackNewReference (assembly, _customAttributeAssembly); return _attributeCtor; }
public void SetUp() { AssemblyPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "IntegrationTestFiles"); TempPath = Path.Combine(AssemblyPath, "temp"); if (Directory.Exists(TempPath)) { Directory.Delete(TempPath, true); } Directory.CreateDirectory(TempPath); Thread.Sleep(500); var assemblyFileNames = new[] { "DummyTarget.dll" }; foreach (var assemblyFileName in assemblyFileNames) { File.Copy(Path.Combine(AssemblyPath, assemblyFileName), GetTempPath(assemblyFileName)); } _verifier = PEVerifier.CreateDefault(); AssemblyDefinition[] assemblies = assemblyFileNames.Select(fileName => AssemblyDefinition.ReadAssembly(GetTempPath(fileName))).ToArray(); _tracker = new AssemblyTracker(assemblies, new TypeDefinitionCache()); _checker = MockRepository.GenerateStub <IMixinChecker> (); _checker.Stub(x => x.CanBeMixed(null)).Return(true).IgnoreArguments(); _transformator = new ConstructorGenerator.ConstructorGenerator(_checker, new ILCodeGenerator( new MethodReferenceGenerator("Remotion.Interfaces, Version=1.13.73.1026, Culture=neutral, PublicKeyToken=fee00910d6e5f53b", "Remotion.Mixins.ObjectFactory", "Remotion.Reflection.ParamList"), _checker) ); _signer = new AssemblySigner(new ModuleDefinitionWriter(new FileSystem(), null, new List <StrongNameKeyPair> ())); _fileSystem = new FileSystem(); }
public void CreateNewObjectMethod(AssemblyDefinition containingAssembly, MethodDefinition templateMethod, IAssemblyTracker tracker) { TypeReference returnType = templateMethod.DeclaringType; if (templateMethod.DeclaringType.HasGenericParameters) { returnType = new GenericInstanceType (templateMethod.DeclaringType); foreach (var a in templateMethod.DeclaringType.GenericParameters.ToArray ()) { returnType.GenericParameters.Add (a); ((GenericInstanceType) returnType).GenericArguments.Add (a); } } var objectFactory = _referenceGenerator.GetCallableObjectFactoryCreateMethod (containingAssembly, templateMethod.DeclaringType.Module, returnType, tracker); var paramListCreateReference = _referenceGenerator.GetCallableParamListCreateMethod (containingAssembly, templateMethod, tracker); var newObjectMethod = new MethodDefinition ("NewObject", MethodAttributes.Public | MethodAttributes.Static, returnType); var instructions = newObjectMethod.Body.Instructions; newObjectMethod.Body.InitLocals = true; var paramListLocal = new VariableDefinition ("__paramList", paramListCreateReference.ReturnType); newObjectMethod.Body.Variables.Add (paramListLocal); foreach (var param in templateMethod.Parameters) { newObjectMethod.Parameters.Add (param); instructions.Add (Instruction.Create (OpCodes.Ldarg, param)); } var createInstructions = GetObjectFactoryCreateInstructions (objectFactory, templateMethod.DeclaringType, paramListCreateReference, paramListLocal); foreach (var instruction in createInstructions) instructions.Add (instruction); instructions.Add (Instruction.Create (OpCodes.Ret)); newObjectMethod.Body.OptimizeMacros (); newObjectMethod.IsHideBySig = true; templateMethod.DeclaringType.Methods.Add (newObjectMethod); }
public void Transform(IAssemblyTracker tracker) { ArgumentUtility.CheckNotNull("tracker", tracker); _tracker = tracker; var mixinTargetTypes = from assemblyDefinition in tracker.GetAssemblies() from typeDefinition in assemblyDefinition.LoadAllTypes() where _checker.CanBeMixed(assemblyDefinition.Name.BuildReflectionAssemblyQualifiedName(typeDefinition)) select new { Assembly = assemblyDefinition, TypeDef = typeDefinition }; foreach (var mixinTargetType in mixinTargetTypes.ToList()) { GenerateNewObjectMethods(mixinTargetType.Assembly, mixinTargetType.TypeDef); } foreach (var assembly in tracker.GetAssemblies()) { foreach (var typ in assembly.LoadAllTypes()) { ReplaceNewStatement(assembly, typ); } } }
public void CreateNewObjectMethod(AssemblyDefinition containingAssembly, MethodDefinition templateMethod, IAssemblyTracker tracker) { TypeReference returnType = templateMethod.DeclaringType; if (templateMethod.DeclaringType.HasGenericParameters) { returnType = new GenericInstanceType(templateMethod.DeclaringType); foreach (var a in templateMethod.DeclaringType.GenericParameters.ToArray()) { returnType.GenericParameters.Add(a); ((GenericInstanceType)returnType).GenericArguments.Add(a); } } var objectFactory = _referenceGenerator.GetCallableObjectFactoryCreateMethod(containingAssembly, templateMethod.DeclaringType.Module, returnType, tracker); var paramListCreateReference = _referenceGenerator.GetCallableParamListCreateMethod(containingAssembly, templateMethod, tracker); var newObjectMethod = new MethodDefinition("NewObject", MethodAttributes.Public | MethodAttributes.Static, returnType); var instructions = newObjectMethod.Body.Instructions; newObjectMethod.Body.InitLocals = true; var paramListLocal = new VariableDefinition("__paramList", paramListCreateReference.ReturnType); newObjectMethod.Body.Variables.Add(paramListLocal); foreach (var param in templateMethod.Parameters) { newObjectMethod.Parameters.Add(param); instructions.Add(Instruction.Create(OpCodes.Ldarg, param)); } var createInstructions = GetObjectFactoryCreateInstructions(objectFactory, templateMethod.DeclaringType, paramListCreateReference, paramListLocal); foreach (var instruction in createInstructions) { instructions.Add(instruction); } instructions.Add(Instruction.Create(OpCodes.Ret)); newObjectMethod.Body.OptimizeMacros(); newObjectMethod.IsHideBySig = true; templateMethod.DeclaringType.Methods.Add(newObjectMethod); }
public void Transform(IAssemblyTracker tracker) { ArgumentUtility.CheckNotNull ("tracker", tracker); _selectionStrategy = _selectionFactory.CreateSelector (tracker); var modifiedMethods = from assemblyDefinition in tracker.GetAssemblies () from typeDefinition in assemblyDefinition.LoadAllTypes () from methodDefinition in typeDefinition.Methods where _selectionStrategy.IsTarget (methodDefinition, assemblyDefinition) select new { Assembly = assemblyDefinition, Method = methodDefinition }; foreach (var modifiedMethodDefinition in modifiedMethods.ToList ()) { if (!modifiedMethodDefinition.Method.IsVirtual && !modifiedMethodDefinition.Method.IsStatic && !modifiedMethodDefinition.Method.IsConstructor && !modifiedMethodDefinition.Method.CustomAttributes.Any (ca => ca.AttributeType.Namespace == "System.Runtime.Serialization")) { tracker.MarkModified (modifiedMethodDefinition.Assembly); var virtualMethod = _codeGenerator.GenerateMethodAndMoveBody (modifiedMethodDefinition.Method); modifiedMethodDefinition.Method.DeclaringType.Methods.Add (virtualMethod); AddAttributes (virtualMethod); _markingAttributeStrategy.AddCustomAttribute (modifiedMethodDefinition.Method, modifiedMethodDefinition.Assembly); } } }
private AssemblyNameReference GetOrCreateRemotionInterfacesReference(AssemblyDefinition assemblyDef, ModuleDefinition moduleDefinition, IAssemblyTracker tracker) { var tempRef = moduleDefinition.AssemblyReferences.FirstOrDefault (r => r.FullName == _remotionInterfacesReference.FullName); if (tempRef == null) { var assm = AssemblyDefinition.ReadAssembly (_workingDir + _remotionInterfacesReference.Name + ".dll"); moduleDefinition.AssemblyReferences.Add (_remotionInterfacesReference); tracker.TrackNewReference (assemblyDef, _remotionInterfacesReference); return _remotionInterfacesReference; } return tempRef; }
public void SetUp() { AssemblyPath = Path.Combine (AppDomain.CurrentDomain.BaseDirectory, "IntegrationTestFiles"); TempPath = Path.Combine (AssemblyPath, "temp"); if (Directory.Exists (TempPath)) Directory.Delete (TempPath, true); Directory.CreateDirectory (TempPath); Thread.Sleep (500); var assemblyFileNames = new[] { "DummyTarget.dll" }; foreach (var assemblyFileName in assemblyFileNames) File.Copy (Path.Combine (AssemblyPath, assemblyFileName), GetTempPath (assemblyFileName)); _verifier = PEVerifier.CreateDefault (); AssemblyDefinition[] assemblies = assemblyFileNames.Select (fileName => AssemblyDefinition.ReadAssembly (GetTempPath (fileName))).ToArray(); _tracker = new AssemblyTracker (assemblies, new TypeDefinitionCache()); _checker = MockRepository.GenerateStub<IMixinChecker> (); _checker.Stub (x => x.CanBeMixed (null)).Return (true).IgnoreArguments (); _transformator = new ConstructorGenerator.ConstructorGenerator (_checker, new ILCodeGenerator ( new MethodReferenceGenerator ("Remotion.Interfaces, Version=1.13.73.1026, Culture=neutral, PublicKeyToken=fee00910d6e5f53b", "Remotion.Mixins.ObjectFactory", "Remotion.Reflection.ParamList"), _checker) ); _signer = new AssemblySigner (new ModuleDefinitionWriter (new FileSystem (), null, new List<StrongNameKeyPair> ())); _fileSystem = new FileSystem(); }
public MethodReference GetCallableParamListCreateMethod(AssemblyDefinition assemblyDef, MethodReference ctor, IAssemblyTracker tracker) { MethodReference reference; if (assemblyDef.FullName == _remotionInterfacesAssemblyName && (reference = SearchParamListFactoryMethod(assemblyDef, ctor)) != null) { return(reference); } var tempRef = GetOrCreateRemotionInterfacesReference(assemblyDef, ctor.DeclaringType.Module, tracker); var paramListCreateReference = GetOrCreateParamList(ctor.Parameters.Count, ctor.DeclaringType.Module, tempRef); if (ctor.Parameters.Count > 0) { paramListCreateReference = new GenericInstanceMethod(paramListCreateReference); foreach (var param in ctor.Parameters) { ((GenericInstanceMethod)paramListCreateReference).GenericArguments.Add(param.ParameterType); } } return(paramListCreateReference); }
public bool ReplaceNewStatements(AssemblyDefinition containingAssembly, TypeDefinition containingType, MethodDefinition targetMethod, IAssemblyTracker tracker, INewTransformerInfoWrapper infoWrapper) { var isModified = false; if (targetMethod.HasBody) { var instructions = targetMethod.Body.Instructions; for (int i = 0; i < instructions.Count; i++) { if (instructions[i].OpCode == OpCodes.Newobj) { var constructor = (MethodReference)instructions[i].Operand; MethodDefinition factoryMethod = null; // Expected factory method signature: public static T Create<T> (ParamList) if (!constructor.Parameters.Any(p => p.ParameterType == containingType.Module.TypeSystem.IntPtr) && ((factoryMethod = infoWrapper.GetFactoryMethod(constructor, containingAssembly, tracker)) != null)) { isModified = true; if (factoryMethod.GenericParameters.Count != 1 || factoryMethod.Parameters.Count != 1 || !factoryMethod.IsStatic) { throw new ArgumentException("Factory method to create object does not have correct signature [public static T Create<T> (ParamList)]"); } var importedFactoryMethod = containingType.Module.Import(factoryMethod); var genericInstanceMethod = new GenericInstanceMethod(importedFactoryMethod); genericInstanceMethod.GenericArguments.Add(constructor.DeclaringType); var paramlistDef = factoryMethod.Parameters[0].ParameterType.Resolve(); var importedParamListCreateMethod = containingType.Module.Import(SearchParamListFactoryMethod(paramlistDef, constructor)); if (importedParamListCreateMethod == null) { throw new ArgumentException("Factory method: no corresponding 'Create' method could have been found. [argument count]"); } #region ILsample // 1: ldstr "Test" // 2: newObj // 3: next // ::---- becomes ->> // 1: ldstr "Test" // 2: nop (original call statement - kept as branch target) // 3: call ParamList.Create<string> (string) // 4: call ObjectFactory // 5: next #endregion targetMethod.Body.SimplifyMacros(); instructions[i].OpCode = OpCodes.Nop; instructions.Insert(i + 1, Instruction.Create(OpCodes.Call, importedParamListCreateMethod)); instructions.Insert(i + 2, Instruction.Create(OpCodes.Call, genericInstanceMethod)); targetMethod.Body.OptimizeMacros(); } } } } return(isModified); }
public bool CreateNewObjectMethod(AssemblyDefinition assembly, MethodDefinition templateMethod, IAssemblyTracker tracker, INewTransformerInfoWrapper infoWrapper) { MethodDefinition factoryMethod = null; if ((factoryMethod = infoWrapper.GetFactoryMethod(templateMethod, assembly, tracker)) != null) { if (factoryMethod.GenericParameters.Count != 1 || factoryMethod.Parameters.Count != 1 || !factoryMethod.IsStatic) { throw new ArgumentException("Factory method to create object does not have correct signature [public static T Create<T> (ParamList)]"); } TypeReference returnType = templateMethod.DeclaringType; if (templateMethod.DeclaringType.HasGenericParameters) { returnType = new GenericInstanceType(templateMethod.DeclaringType); foreach (var a in templateMethod.DeclaringType.GenericParameters.ToArray()) { returnType.GenericParameters.Add(a); ((GenericInstanceType)returnType).GenericArguments.Add(a); } } var importedFactoryMethod = templateMethod.Module.Import(factoryMethod); var genericInstanceMethod = new GenericInstanceMethod(importedFactoryMethod); genericInstanceMethod.GenericArguments.Add(templateMethod.DeclaringType); var paramlistDef = factoryMethod.Parameters[0].ParameterType.Resolve(); var importedParamListCreateMethod = templateMethod.Module.Import(SearchParamListFactoryMethod(paramlistDef, templateMethod)); if (importedParamListCreateMethod == null) { throw new ArgumentException("Factory method: no corresponding 'create' method could have been found. [argument count]"); } var newObjectMethod = new MethodDefinition( infoWrapper.GetWrapperMethodName(templateMethod), MethodAttributes.Public | MethodAttributes.Static, returnType ); var instructions = newObjectMethod.Body.Instructions; foreach (var param in templateMethod.Parameters) { newObjectMethod.Parameters.Add(param); instructions.Add(Instruction.Create(OpCodes.Ldarg, param)); } instructions.Add(Instruction.Create(OpCodes.Call, importedParamListCreateMethod)); instructions.Add(Instruction.Create(OpCodes.Call, genericInstanceMethod)); instructions.Add(Instruction.Create(OpCodes.Ret)); newObjectMethod.Body.OptimizeMacros(); newObjectMethod.IsHideBySig = true; templateMethod.DeclaringType.Methods.Add(newObjectMethod); return(true); } return(false); }
public bool ReplaceNewStatements(AssemblyDefinition containingAssembly, TypeDefinition containingType, MethodDefinition targetMethod, IAssemblyTracker tracker) { var isModified = false; if (targetMethod.HasBody) { var instructions = targetMethod.Body.Instructions; VariableDefinition paramListLocal = null; for (int i = 0; i < instructions.Count; i++) { if (instructions[i].OpCode == OpCodes.Newobj) { var constructor = (MethodReference)instructions[i].Operand; var assemblyQualifiedName = containingAssembly.Name.BuildReflectionAssemblyQualifiedName(constructor.DeclaringType); if (!constructor.Parameters.Any(p => p.ParameterType == containingType.Module.TypeSystem.IntPtr) && _checker.IsCached(assemblyQualifiedName) && _checker.CanBeMixed(assemblyQualifiedName)) { targetMethod.Body.SimplifyMacros(); isModified = true; var objectFactory = _referenceGenerator.GetCallableObjectFactoryCreateMethod(containingAssembly, containingType.Module, constructor.DeclaringType, tracker); var paramListCreateReference = _referenceGenerator.GetCallableParamListCreateMethod(containingAssembly, constructor, tracker); if (paramListLocal == null) { targetMethod.Body.InitLocals = true; paramListLocal = new VariableDefinition("__paramList", paramListCreateReference.ReturnType); targetMethod.Body.Variables.Add(paramListLocal); } #region ILsample // 1: ldstr "Test" // 2: newObj // 3: next // ::---- becomes ->> // 1: ldstr "Test" // 2: nop (original call statement - kept as branch target) // 3: call ParamList.Create<string> (string) // 4: stloc tempPList // 5: ldtrue // 6: ldloc tempPList // 7: ldc.i4.0 // 8: newarr object // 9: call ObjectFactory // 10: next #endregion instructions[i].OpCode = OpCodes.Nop; var objectFactoryInstructions = GetObjectFactoryCreateInstructions( objectFactory, containingType, paramListCreateReference, paramListLocal); for (int j = 0; j < objectFactoryInstructions.Length; ++j) { instructions.Insert(i + 1 + j, objectFactoryInstructions[j]); } targetMethod.Body.OptimizeMacros(); } } } } return(isModified); }
public void SetUp() { _fileSystemMock = MockRepository.GenerateStrictMock <IFileSystem> (); _assemblyDefinition1 = AssemblyDefinitionObjectMother.CreateMultiModuleAssemblyWithCtorsAndMethodBody(); _tracker = MockRepository.GenerateStrictMock <IAssemblyTracker> (); }
private AssemblyNameReference GetOrCreateRemotionInterfacesReference(AssemblyDefinition assemblyDef, ModuleDefinition moduleDefinition, IAssemblyTracker tracker) { var tempRef = moduleDefinition.AssemblyReferences.FirstOrDefault(r => r.FullName == _remotionInterfacesReference.FullName); if (tempRef == null) { var assm = AssemblyDefinition.ReadAssembly(_workingDir + _remotionInterfacesReference.Name + ".dll"); moduleDefinition.AssemblyReferences.Add(_remotionInterfacesReference); tracker.TrackNewReference(assemblyDef, _remotionInterfacesReference); return(_remotionInterfacesReference); } return(tempRef); }
public AssemblyNameReference GetOrCreateRemotionInterfacesReference(AssemblyDefinition assemblyDef, ModuleDefinition moduleDefinition, IAssemblyTracker tracker) { var tempRef = moduleDefinition.AssemblyReferences.FirstOrDefault (r => r.FullName == _remotionInterfacesAssemblyName); if (tempRef == null) { tempRef = AssemblyNameReference.Parse (_remotionInterfacesAssemblyName); // ugly workaround for Cecils (wrong) behaviour concerning Culture if (tempRef.Culture == "neutral") tempRef.Culture = null; moduleDefinition.AssemblyReferences.Add (tempRef); tracker.TrackNewReference (assemblyDef, tempRef); } return tempRef; }
public MethodDefinition GetFactoryMethod(MethodReference ctor, AssemblyDefinition assembly, IAssemblyTracker tracker) { if (!_factoryMethods.ContainsKey(ctor)) { var memberId = CecilResolver.CreateMemberID(ctor.Resolve()); AssemblyNameReference containingTrackedAssembly; _factoryMethods[ctor] = CecilResolver.ResolveToMethodDefinition(_infoProvider.GetFactoryMethodFunc(memberId), tracker, out containingTrackedAssembly); if (containingTrackedAssembly != null) { tracker.TrackNewReference(assembly, containingTrackedAssembly); } } return(_factoryMethods[ctor]); }
public bool ReplaceNewStatements(AssemblyDefinition containingAssembly, TypeDefinition containingType, MethodDefinition targetMethod, IAssemblyTracker tracker) { var isModified = false; if (targetMethod.HasBody) { var instructions = targetMethod.Body.Instructions; VariableDefinition paramListLocal = null; for (int i = 0; i < instructions.Count; i++) { if (instructions[i].OpCode == OpCodes.Newobj) { var constructor = (MethodReference) instructions[i].Operand; var assemblyQualifiedName = containingAssembly.Name.BuildReflectionAssemblyQualifiedName (constructor.DeclaringType); if (!constructor.Parameters.Any (p => p.ParameterType == containingType.Module.TypeSystem.IntPtr) && _checker.IsCached (assemblyQualifiedName) && _checker.CanBeMixed (assemblyQualifiedName)) { targetMethod.Body.SimplifyMacros (); isModified = true; var objectFactory = _referenceGenerator.GetCallableObjectFactoryCreateMethod (containingAssembly, containingType.Module, constructor.DeclaringType, tracker); var paramListCreateReference = _referenceGenerator.GetCallableParamListCreateMethod (containingAssembly, constructor, tracker); if (paramListLocal == null) { targetMethod.Body.InitLocals = true; paramListLocal = new VariableDefinition ("__paramList", paramListCreateReference.ReturnType); targetMethod.Body.Variables.Add (paramListLocal); } #region ILsample // 1: ldstr "Test" // 2: newObj // 3: next // ::---- becomes ->> // 1: ldstr "Test" // 2: nop (original call statement - kept as branch target) // 3: call ParamList.Create<string> (string) // 4: stloc tempPList // 5: ldtrue // 6: ldloc tempPList // 7: ldc.i4.0 // 8: newarr object // 9: call ObjectFactory // 10: next #endregion instructions[i].OpCode = OpCodes.Nop; var objectFactoryInstructions = GetObjectFactoryCreateInstructions ( objectFactory, containingType, paramListCreateReference, paramListLocal); for (int j = 0; j < objectFactoryInstructions.Length; ++j) instructions.Insert (i + 1 + j, objectFactoryInstructions[j]); targetMethod.Body.OptimizeMacros (); } } } } return isModified; }
public void SetUp() { _fileSystemMock = MockRepository.GenerateStrictMock<IFileSystem> (); _assemblyDefinition1 = AssemblyDefinitionObjectMother.CreateMultiModuleAssemblyWithCtorsAndMethodBody (); _tracker = MockRepository.GenerateStrictMock<IAssemblyTracker> (); }
public void SetUp() { _fileSystemMock = MockRepository.GenerateStrictMock<IFileSystem> (); _assemblyDefinition1 = AssemblyDefinitionObjectMother.CreateMultiModuleAssemblyWithCtorsAndMethodBody(); _tracker = MockRepository.GenerateStrictMock<IAssemblyTracker> (); _checker = MockRepository.GenerateStrictMock<IMixinChecker>(); _referenceGenerator = MockRepository.GenerateStrictMock<IReferenceGenerator>(); _codeGenerator = new ILCodeGenerator (_referenceGenerator, _checker); }
public bool ReplaceNewStatements(AssemblyDefinition containingAssembly, TypeDefinition containingType, MethodDefinition targetMethod, IAssemblyTracker tracker, INewTransformerInfoWrapper infoWrapper) { var isModified = false; if (targetMethod.HasBody) { var instructions = targetMethod.Body.Instructions; for (int i = 0; i < instructions.Count; i++) { if (instructions[i].OpCode == OpCodes.Newobj) { var constructor = (MethodReference) instructions[i].Operand; MethodDefinition factoryMethod = null; // Expected factory method signature: public static T Create<T> (ParamList) if (!constructor.Parameters.Any (p => p.ParameterType == containingType.Module.TypeSystem.IntPtr) && ((factoryMethod = infoWrapper.GetFactoryMethod (constructor, containingAssembly, tracker)) != null)) { isModified = true; if (factoryMethod.GenericParameters.Count != 1 || factoryMethod.Parameters.Count != 1 || !factoryMethod.IsStatic) throw new ArgumentException ("Factory method to create object does not have correct signature [public static T Create<T> (ParamList)]"); var importedFactoryMethod = containingType.Module.Import (factoryMethod); var genericInstanceMethod = new GenericInstanceMethod (importedFactoryMethod); genericInstanceMethod.GenericArguments.Add (constructor.DeclaringType); var paramlistDef = factoryMethod.Parameters[0].ParameterType.Resolve (); var importedParamListCreateMethod = containingType.Module.Import (SearchParamListFactoryMethod (paramlistDef, constructor)); if (importedParamListCreateMethod == null) throw new ArgumentException ("Factory method: no corresponding 'Create' method could have been found. [argument count]"); #region ILsample // 1: ldstr "Test" // 2: newObj // 3: next // ::---- becomes ->> // 1: ldstr "Test" // 2: nop (original call statement - kept as branch target) // 3: call ParamList.Create<string> (string) // 4: call ObjectFactory // 5: next #endregion targetMethod.Body.SimplifyMacros (); instructions[i].OpCode = OpCodes.Nop; instructions.Insert (i + 1, Instruction.Create (OpCodes.Call, importedParamListCreateMethod)); instructions.Insert (i + 2, Instruction.Create (OpCodes.Call, genericInstanceMethod)); targetMethod.Body.OptimizeMacros (); } } } } return isModified; }
public void SetUp() { _trackerMock = MockRepository.GenerateStrictMock<IAssemblyTracker>(); _trackerFactoryMock = MockRepository.GenerateStrictMock<IAssemblyTrackerFactory>(); _transformerMock = MockRepository.GenerateStrictMock<IAssemblyTransformation>(); _transformationFactoryMock = MockRepository.GenerateStrictMock<IAssemblyTransformationFactory>(); _transformerMock2 = MockRepository.GenerateStrictMock<IAssemblyTransformation> (); _transformationFactoryMock2 = MockRepository.GenerateStrictMock<IAssemblyTransformationFactory> (); _signerMock = MockRepository.GenerateStrictMock<IAssemblySigner>(); _signerFactoryMock = MockRepository.GenerateStrictMock<IAssemblySignerFactory>(); _infoBroker = MockRepository.GenerateStub<IAppDomainInfoBroker>(); }
public void SetUp() { _verifier = PEVerifier.CreateDefault (); Directory.CreateDirectory (TempPath); foreach (var file in Directory.EnumerateFiles (@AssemblyPath, "*.dll", SearchOption.TopDirectoryOnly)) { Console.WriteLine (@TempPath + file.Substring (file.IndexOf ("integration") +11)); File.Copy (file, @TempPath + file.Substring (file.IndexOf ("integration") +11), true); } var allFiles = Directory.EnumerateFiles (@TempPath, "*.dll", SearchOption.AllDirectories) .Concat (Directory.EnumerateFiles (@TempPath, "*.exe", SearchOption.AllDirectories)); List<AssemblyDefinition> assemblies = allFiles.Select (AssemblyDefinition.ReadAssembly).ToList(); _tracker = new AssemblyTracker (assemblies, new TypeDefinitionCache()); var options = new OptionSet(); var selectorFactory = new TargetSelectorFactory(); selectorFactory.AddOptions (options); options.Parse (new[] { "--regex:(.*)Locked(.*)" }); _transformator = new AssemblyMethodsVirtualizer.AssemblyMethodsVirtualizer ( new GeneratedMarkingAttributeStrategy ("test", "nonVirtual"), new TargetSelectorFactory(), new ILCodeGenerator ("<>unspeakable_")); _signer = new AssemblySigner (new ModuleDefinitionWriter (new FileSystem.FileSystem(), null, new List<StrongNameKeyPair>())); }
public AssemblyNameReference GetOrCreateRemotionInterfacesReference(AssemblyDefinition assemblyDef, ModuleDefinition moduleDefinition, IAssemblyTracker tracker) { var tempRef = moduleDefinition.AssemblyReferences.FirstOrDefault(r => r.FullName == _remotionInterfacesAssemblyName); if (tempRef == null) { tempRef = AssemblyNameReference.Parse(_remotionInterfacesAssemblyName); // ugly workaround for Cecils (wrong) behaviour concerning Culture if (tempRef.Culture == "neutral") { tempRef.Culture = null; } moduleDefinition.AssemblyReferences.Add(tempRef); tracker.TrackNewReference(assemblyDef, tempRef); } return(tempRef); }
public MethodReference GetCallableObjectFactoryCreateMethod(AssemblyDefinition assemblyDef, ModuleDefinition moduleDefinition, TypeReference instantiatedType, IAssemblyTracker tracker) { MethodReference reference; if (assemblyDef.FullName == _remotionInterfacesAssemblyName && (reference = SearchObjectFactoryMethod(assemblyDef)) != null) { ((GenericInstanceMethod)reference).GenericArguments.Add(instantiatedType); return(reference); } var tempRef = GetOrCreateRemotionInterfacesReference(assemblyDef, moduleDefinition, tracker); var objectFactoryReference = new TypeReference(_objectFactoryNamespace, _objectFactoryName, moduleDefinition, tempRef); var paramListReference = new TypeReference(_paramListNamespace, _paramListName, moduleDefinition, tempRef); var createReference = new MethodReference("Create", moduleDefinition.TypeSystem.Void, objectFactoryReference); var createTypeParam = new GenericParameter("T", createReference); createReference.GenericParameters.Add(createTypeParam); createReference.ReturnType = createTypeParam; createReference.Parameters.Add(new ParameterDefinition(moduleDefinition.TypeSystem.Boolean)); createReference.Parameters.Add(new ParameterDefinition(paramListReference)); createReference.Parameters.Add(new ParameterDefinition(new ArrayType(moduleDefinition.TypeSystem.Object))); var instanceMethod = new GenericInstanceMethod(createReference); instanceMethod.GenericArguments.Add(instantiatedType); return(instanceMethod); }
public void SetUp() { _assemblyDefinition = AssemblyDefinitionObjectMother.CreateMultiModuleAssemblyDefinition(); _tracker = new AssemblyTracker (new [] { _assemblyDefinition }, new TypeDefinitionCache()); _markingAttributeStrategy = MockRepository.GenerateStub<IMarkingAttributeStrategy> (); _codeGenerator = MockRepository.GenerateStub<ICodeGenerator>(); _selectionFactory = new TargetSelectorFactory (); _options = new OptionSet (); _methodsVirtualizer = new AssemblyMethodsVirtualizer (_markingAttributeStrategy, _selectionFactory, _codeGenerator); }