示例#1
0
        // this method creates a new class for the given namespace
        public NamespaceTypeDefinition createNewClass(String className, IUnitNamespace containingUnitNamespace, bool isPublic,
                                                      bool isStatic)
        {
            // create a new class object
            NamespaceTypeDefinition newClass = new NamespaceTypeDefinition();

            newClass.ContainingUnitNamespace = containingUnitNamespace;
            newClass.InternFactory           = this.host.InternFactory;
            newClass.IsClass         = true;
            newClass.IsForeignObject = false;
            newClass.IsInterface     = false;
            newClass.IsPublic        = isPublic;
            newClass.IsStatic        = isStatic;
            newClass.Methods         = new List <IMethodDefinition>();
            newClass.Name            = this.host.NameTable.GetNameFor(className);

            // create list of base classes (only base class is System.Object)
            newClass.BaseClasses = new List <ITypeReference>();
            newClass.BaseClasses.Add(this.host.PlatformType.SystemObject);

            // add new class to module assembly
            Assembly tempAssembly = (Assembly)this.module;

            tempAssembly.AllTypes.Add(newClass);

            return(newClass);
        }
示例#2
0
        internal static string ModuleQualifiedUnitNamespace(IUnit currentUnit, IUnitNamespace unitNamespace, out bool wasRoot)
        {
            INestedUnitNamespace nestedUnitNamespace = unitNamespace as INestedUnitNamespace;

            if (nestedUnitNamespace != null)
            {
                StringBuilder sb = new StringBuilder(Helper.ModuleQualifiedUnitNamespace(currentUnit, (IUnitNamespace)nestedUnitNamespace.ContainingNamespace, out wasRoot));
                if (!wasRoot)
                {
                    sb.Append(".");
                }
                sb.Append(nestedUnitNamespace.Name.Value);
                wasRoot = false;
                return(sb.ToString());
            }
            else
            {
                wasRoot = true;
                if (!unitNamespace.Unit.Equals(currentUnit))
                {
                    return(Helper.Unit(unitNamespace.Unit));
                }
            }
            return(string.Empty);
        }
示例#3
0
        private INamedTypeDefinition GenerateTypeA(IUnitNamespace rootNamespace)
        {
            var nt    = Host.NameTable;
            var typeA = new NamespaceTypeDefinition
            {
                ContainingUnitNamespace = rootNamespace,
                Name          = nt.GetNameFor("A"),
                InternFactory = Host.InternFactory,
                IsClass       = true
            };
            var typeParameter = new GenericTypeParameter
            {
                Name          = nt.GetNameFor("T"),
                InternFactory = Host.InternFactory,
                DefiningType  = typeA,
            };

            typeA.GenericParameters.Add(typeParameter);

            var baseGetMethod = new MethodDefinition
            {
                Name       = nt.GetNameFor("Get"),
                IsCil      = true,
                IsVirtual  = true,
                Visibility = TypeMemberVisibility.Assembly,
                Type       = typeParameter,
                ContainingTypeDefinition = typeA,
                InternFactory            = Host.InternFactory,
                IsNewSlot = true
            };

            typeA.Methods.Add(baseGetMethod);

            var il       = new ILGenerator(Host);
            var localVar = new LocalDefinition
            {
                Type = typeParameter,
                Name = nt.GetNameFor("local1"),
            };

            // tricky moment, ILGeneratorMethodBody fills internal collection of local vars only in constructor.
            // lines below should not be swapped

            il.AddVariableToCurrentScope(localVar);
            var body = new ILGeneratorMethodBody(il, true, 1)
            {
                MethodDefinition = baseGetMethod
            };

            baseGetMethod.Body = body;


            il.Emit(OperationCode.Ldloca, localVar);
            il.Emit(OperationCode.Initobj, typeParameter);
            il.Emit(OperationCode.Ldloc_0);
            il.Emit(OperationCode.Ret);

            return(typeA);
        }
 public override void Visit(IUnitNamespace unitNamespace)
 {
     if (Process(unitNamespace))
     {
         visitor.Visit(unitNamespace);
     }
     base.Visit(unitNamespace);
 }
示例#5
0
 internal static IGlobalMethodDefinition GetGlobalMethod(IUnitNamespace unitNamespace, IName methodName)
 {
     foreach (INamespaceMember nm in unitNamespace.GetMembersNamed(methodName, false))
     {
         if (nm is IGlobalMethodDefinition)
         {
             return(nm as IGlobalMethodDefinition);
         }
     }
     return(null);
 }
示例#6
0
 internal static INamespaceTypeDefinition GetNamespaceType(IUnitNamespace unitNamespace, IName typeName)
 {
     foreach (INamespaceMember nm in unitNamespace.GetMembersNamed(typeName, false))
     {
         if (nm is INamespaceTypeDefinition)
         {
             return(nm as INamespaceTypeDefinition);
         }
     }
     return(null);
 }
示例#7
0
        // this method creates an new interface for the given namespace
        public NamespaceTypeDefinition createNewInterface(String className, IUnitNamespace containingUnitNamespace)
        {
            // create a new class object and modify it to be an interface
            NamespaceTypeDefinition newInterface = this.createNewClass(className, containingUnitNamespace, false, false);

            newInterface.IsAbstract  = true;
            newInterface.IsInterface = true;
            newInterface.BaseClasses = null;

            return(newInterface);
        }
示例#8
0
        private static IUnitNamespace GetUnitNamespace(INamespaceDefinition containingNamespace)
        {
            INestedUnitNamespace nestedUnitNamespace = containingNamespace as INestedUnitNamespace;

            if (nestedUnitNamespace != null)
            {
                containingNamespace = nestedUnitNamespace.ContainingUnitNamespace;
            }
            IUnitNamespace unitNamespace = containingNamespace as IUnitNamespace;

            return(unitNamespace);
        }
        private INamedTypeDefinition GenerateTypeA(IUnitNamespace rootNamespace)
        {
            var nt = Host.NameTable;
            var typeA = new NamespaceTypeDefinition
                            {
                                ContainingUnitNamespace = rootNamespace,
                                Name = nt.GetNameFor("A"),
                                InternFactory = Host.InternFactory,
                                IsClass = true
                            };
            var typeParameter = new GenericTypeParameter
                                    {
                                        Name = nt.GetNameFor("T"),
                                        InternFactory = Host.InternFactory,
                                        DefiningType = typeA,
                                    };
            typeA.GenericParameters.Add(typeParameter);

            var baseGetMethod = new MethodDefinition
                                    {
                                        Name = nt.GetNameFor("Get"),
                                        IsCil = true,
                                        IsVirtual = true,
                                        Visibility = TypeMemberVisibility.Assembly,
                                        Type = typeParameter,
                                        ContainingTypeDefinition = typeA,
                                        InternFactory = Host.InternFactory,
                                        IsNewSlot = true
                                    };
            typeA.Methods.Add(baseGetMethod);

            var il = new ILGenerator(Host);
            var localVar = new LocalDefinition
            {
                Type = typeParameter,
                Name = nt.GetNameFor("local1"),
            };

            // tricky moment, ILGeneratorMethodBody fills internal collection of local vars only in constructor.
            // lines below should not be swapped

            il.AddVariableToCurrentScope(localVar);
            var body = new ILGeneratorMethodBody(il, true, 1) {MethodDefinition = baseGetMethod};
            baseGetMethod.Body = body;

            il.Emit(OperationCode.Ldloca, localVar);
            il.Emit(OperationCode.Initobj, typeParameter);
            il.Emit(OperationCode.Ldloc_0);
            il.Emit(OperationCode.Ret);

            return typeA;
        }
示例#10
0
        internal static IUnitNamespace GetNamespace(IUnit unit, params IName[] nameList)
        {
            IUnitNamespace unitNamespace = unit.UnitNamespaceRoot;

            for (int i = 0; i < nameList.Length; ++i)
            {
                foreach (INamespaceMember nsm in unitNamespace.GetMembersNamed(nameList[i], false))
                {
                    unitNamespace = nsm as IUnitNamespace;
                    if (unitNamespace == null)
                    {
                        break;
                    }
                }
            }
            return(unitNamespace);
        }
示例#11
0
        private void MergeNamespaces(UnitNamespace result, IUnitNamespace namespaceToMerge)
        {
            Contract.Requires(result != null);
            Contract.Requires(namespaceToMerge != null);

            foreach (var member in namespaceToMerge.Members)
            {
                var nestedNs = member as NestedUnitNamespace;
                if (nestedNs != null)
                {
                    UnitNamespace nestedResult = null;
                    foreach (var rmember in result.Members)
                    {
                        Contract.Assume(rmember != null);
                        if (rmember.Name != nestedNs.Name)
                        {
                            continue;
                        }
                        nestedResult = rmember as UnitNamespace;
                        if (nestedResult != null)
                        {
                            break;
                        }
                    }
                    if (nestedResult == null)
                    {
                        nestedResult = new NestedUnitNamespace()
                        {
                            ContainingUnitNamespace = result, Name = nestedNs.Name
                        }
                    }
                    ;
                    this.MergeNamespaces(nestedResult, nestedNs);
                    continue;
                }
                result.Members.Add(member);
            }
        }
示例#12
0
        // Walk up the path of defining namespaces and units until we get to the assembly
        public static IAssembly GetDefiningAssembly(IAliasForType aliasForType)
        {
            INamespaceAliasForType namespaceAliasForType = GetAliasForType(aliasForType);

            if (namespaceAliasForType == null)
            {
                return(null);
            }
            INamespaceDefinition containingNamespace = namespaceAliasForType.ContainingNamespace;

            IUnitNamespace unitNamespace = GetUnitNamespace(containingNamespace);

            if (unitNamespace == null)
            {
                return(null);
            }

            IUnit unit = unitNamespace.Unit;

            IAssembly assembly = GetAssembly(unit);

            return(assembly);
        }
示例#13
0
        private NamespaceTypeDefinition GenerateTypeB(IUnitNamespace rootNamespace, ITypeReference baseType)
        {
            var nt    = Host.NameTable;
            var typeB = new NamespaceTypeDefinition
            {
                ContainingUnitNamespace = rootNamespace,
                Name          = nt.GetNameFor("B"),
                InternFactory = Host.InternFactory,
                IsClass       = true,
                BaseClasses   = { baseType }
            };

            var overrideGetMethod = new MethodDefinition
            {
                Name       = nt.GetNameFor("Get"),
                IsCil      = true,
                IsVirtual  = true,
                Visibility = TypeMemberVisibility.Assembly,
                Type       = Host.PlatformType.SystemString,
                ContainingTypeDefinition = typeB,
                InternFactory            = Host.InternFactory
            };

            typeB.Methods.Add(overrideGetMethod);
            var il   = new ILGenerator(Host);
            var body = new ILGeneratorMethodBody(il, true, 1)
            {
                MethodDefinition = overrideGetMethod
            };

            overrideGetMethod.Body = body;

            il.Emit(OperationCode.Ldstr, "1");
            il.Emit(OperationCode.Ret);
            return(typeB);
        }
示例#14
0
        public GraphTransformer(IModule module, PeReader.DefaultHost host, Log.Log logger, Random prng, IUnitNamespace targetNamespace, NamespaceTypeDefinition targetClass, int depth, int dimension, bool debugging = false) {
            this.host = host;
            this.logger = logger;
            this.module = module;
            this.prng = prng;
            this.helperClass = new Helper(module, host, logger);
            this.cfgBuilder = new Cfg.CfgBuilder(module, host, logger);

            this.targetClass = targetClass;

            this.graphDepth = depth;
            this.graphDimension = dimension;

            this.debugging = debugging;
            this.debuggingNumber = 0;

            // create iNode interface
            this.createNodeInterface(targetNamespace);

            // add created iNode interface to the given target class
            this.addNodeInterfaceToTargetClass(this.targetClass);
        }
示例#15
0
 public override void Visit(IUnitNamespace unitNamespace)
 {
     allElements.Add(new InvokInfo(Traverser, "IUnitNamespace", unitNamespace));
 }
示例#16
0
 /// <summary>
 /// Traverses the specified unit namespace definition.
 /// </summary>
 public virtual void TraverseChildren(IUnitNamespace namespaceDefinition)
 {
     Contract.Requires(namespaceDefinition != null);
       this.TraverseChildren((INamespaceDefinition)namespaceDefinition);
 }
示例#17
0
 public FilteredNamespace(IUnitNamespace ns, IFilterAssembly filter)
 {
     _ns     = ns;
     _filter = filter;
 }
 internal static string ModuleQualifiedUnitNamespace(IUnit currentUnit, IUnitNamespace unitNamespace, out bool wasRoot) {
   INestedUnitNamespace nestedUnitNamespace = unitNamespace as INestedUnitNamespace;
   if (nestedUnitNamespace != null) {
     StringBuilder sb = new StringBuilder(Helper.ModuleQualifiedUnitNamespace(currentUnit, (IUnitNamespace)nestedUnitNamespace.ContainingNamespace, out wasRoot));
     if (!wasRoot) {
       sb.Append(".");
     }
     sb.Append(nestedUnitNamespace.Name.Value);
     wasRoot = false;
     return sb.ToString();
   } else {
     wasRoot = true;
     if (!unitNamespace.Unit.Equals(currentUnit))
       return Helper.Unit(unitNamespace.Unit);
   }
   return string.Empty;
 }
示例#19
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="containingUnitNamespace"></param>
 /// <param name="name"></param>
 /// <param name="unit"></param>
 public NestedUnitNamespace(IUnitNamespace containingUnitNamespace, IName name, IUnit unit)
     : base(name, unit)
     //^ requires containingUnitNamespace is RootUnitNamespace || containingUnitNamespace is NestedUnitNamespace;
 {
     this.containingUnitNamespace = containingUnitNamespace;
 }
        public override void TraverseChildren(IUnitNamespace namespaceDefinition)
{ MethodEnter(namespaceDefinition);
            base.TraverseChildren(namespaceDefinition);
     MethodExit();   }
示例#21
0
 public FilteredNamespace(IUnitNamespace ns, IFilterAssembly filter)
 {
     _ns = ns;
     _filter = filter;
 }
 public override void Visit(IUnitNamespace unitNamespace)
 {
     if(Process(unitNamespace)){visitor.Visit(unitNamespace);}
     base.Visit(unitNamespace);
 }
示例#23
0
 /// <summary>
 /// Visits the specified unit namespace.
 /// </summary>
 public virtual void Visit(IUnitNamespace unitNamespace) {
   Contract.Requires(unitNamespace != null);
   this.Visit((INamespaceDefinition)unitNamespace);
 }
 /// <summary>
 /// Visits the specified unit namespace.
 /// </summary>
 public virtual void Visit(IUnitNamespace unitNamespace)
 {
     Contract.Requires(unitNamespace != null);
     
 }
        private NamespaceTypeDefinition GenerateTypeB(IUnitNamespace rootNamespace, ITypeReference baseType)
        {
            var nt = Host.NameTable;
            var typeB = new NamespaceTypeDefinition
                            {
                                ContainingUnitNamespace = rootNamespace,
                                Name = nt.GetNameFor("B"),
                                InternFactory = Host.InternFactory,
                                IsClass = true,
                                BaseClasses = { baseType }
                            };

            var overrideGetMethod = new MethodDefinition
                                        {
                                            Name = nt.GetNameFor("Get"),
                                            IsCil = true,
                                            IsVirtual = true,
                                            Visibility = TypeMemberVisibility.Assembly,
                                            Type = Host.PlatformType.SystemString,
                                            ContainingTypeDefinition = typeB,
                                            InternFactory = Host.InternFactory
                                        };
            typeB.Methods.Add(overrideGetMethod);
            var il = new ILGenerator(Host);
            var body = new ILGeneratorMethodBody(il, true, 1) {MethodDefinition = overrideGetMethod};
            overrideGetMethod.Body = body;

            il.Emit(OperationCode.Ldstr, "1");
            il.Emit(OperationCode.Ret);
            return typeB;
        }
 /// <summary>
 /// Rewrites the specified unit namespace.
 /// </summary>
 public virtual IUnitNamespace Rewrite(IUnitNamespace unitNamespace)
 {
     return unitNamespace;
 }
 void QualifiedUnitNamespace(IUnitNamespace unitNamespace, out bool wasRoot) {
   INestedUnitNamespace nestedUnitNamespace = unitNamespace as INestedUnitNamespace;
   if (nestedUnitNamespace != null) {
     this.QualifiedUnitNamespace((IUnitNamespace)nestedUnitNamespace.ContainingNamespace, out wasRoot);
     if (!wasRoot) {
       this.ILDasmPaper.Symbol(".");
     }
     this.ILDasmPaper.Identifier(nestedUnitNamespace.Name.Value);
     wasRoot = false;
     return;
   }
   wasRoot = true;
   return;
 }
 void SimpleUnitNamespace(IUnitNamespace unitNamespace, out bool wasRoot) {
   INestedUnitNamespace nestedUnitNamespace = unitNamespace as INestedUnitNamespace;
   if (nestedUnitNamespace != null) {
     this.ILDasmPaper.Identifier(nestedUnitNamespace.Name.Value);
     wasRoot = false;
     return;
   }
   wasRoot = true;
   return;
 }
示例#29
0
 /// <summary>
 /// Traverses the specified unit namespace definition.
 /// </summary>
 public virtual void TraverseChildren(IUnitNamespace namespaceDefinition)
 {
     this.TraverseChildren((INamespaceDefinition)namespaceDefinition);
 }
示例#30
0
        /// <summary>
        /// Returns a unit namespace definition, nested in the given unitNamespace if possible,
        /// otherwise nested in the given unit if possible, otherwise nested in the given host if possible, otherwise it returns Dummy.UnitNamespace.
        /// If unitNamespaceReference is a root namespace, the result is equal to the given unitNamespace if not null,
        /// otherwise the result is the root namespace of the given unit if not null,
        /// otherwise the result is root namespace of unitNamespaceReference.Unit, if that can be resolved via the given host,
        /// otherwise the result is Dummy.UnitNamespace.
        /// </summary>
        public static IUnitNamespace Resolve(IUnitNamespaceReference unitNamespaceReference, IMetadataHost host, IUnit unit = null, IUnitNamespace unitNamespace = null)
        {
            Contract.Requires(unitNamespaceReference != null);
            Contract.Requires(host != null);
            Contract.Requires(unit != null || unitNamespace == null);
            Contract.Ensures(Contract.Result <IUnitNamespace>() != null);

            var rootNsRef = unitNamespaceReference as IRootUnitNamespaceReference;

            if (rootNsRef != null)
            {
                if (unitNamespace != null)
                {
                    return(unitNamespace);
                }
                if (unit != null)
                {
                    return(unit.UnitNamespaceRoot);
                }
                unit = UnitHelper.Resolve(unitNamespaceReference.Unit, host);
                if (unit is Dummy)
                {
                    return(Dummy.UnitNamespace);
                }
                return(unit.UnitNamespaceRoot);
            }
            var nestedNsRef = unitNamespaceReference as INestedUnitNamespaceReference;

            if (nestedNsRef == null)
            {
                return(Dummy.UnitNamespace);
            }
            var containingNsDef = UnitHelper.Resolve(nestedNsRef.ContainingUnitNamespace, host, unit, unitNamespace);

            if (containingNsDef is Dummy)
            {
                return(Dummy.UnitNamespace);
            }
            foreach (var nsMem in containingNsDef.GetMembersNamed(nestedNsRef.Name, ignoreCase: false))
            {
                var neNsDef = nsMem as INestedUnitNamespace;
                if (neNsDef != null)
                {
                    return(neNsDef);
                }
            }
            return(Dummy.UnitNamespace);
        }
示例#31
0
        // this method creates a new class for the given namespace
        public NamespaceTypeDefinition createNewClass(String className, IUnitNamespace containingUnitNamespace, bool isPublic,
            bool isStatic)
        {
            // create a new class object
            NamespaceTypeDefinition newClass = new NamespaceTypeDefinition();
            newClass.ContainingUnitNamespace = containingUnitNamespace;
            newClass.InternFactory = this.host.InternFactory;
            newClass.IsClass = true;
            newClass.IsForeignObject = false;
            newClass.IsInterface = false;
            newClass.IsPublic = isPublic;
            newClass.IsStatic = isStatic;
            newClass.Methods = new List<IMethodDefinition>();
            newClass.Name = this.host.NameTable.GetNameFor(className);

            // create list of base classes (only base class is System.Object)
            newClass.BaseClasses = new List<ITypeReference>();
            newClass.BaseClasses.Add(this.host.PlatformType.SystemObject);

            // add new class to module assembly
            Assembly tempAssembly = (Assembly)this.module;
            tempAssembly.AllTypes.Add(newClass);

            return newClass;
        }
 internal static INamespaceTypeDefinition GetNamespaceType(IUnitNamespace unitNamespace, IName typeName) {
   foreach (INamespaceMember nm in unitNamespace.GetMembersNamed(typeName, false)) {
     if (nm is INamespaceTypeDefinition)
       return nm as INamespaceTypeDefinition;
   }
   return null;
 }
示例#33
0
        // this method creates an new interface for the given namespace
        public NamespaceTypeDefinition createNewInterface(String className, IUnitNamespace containingUnitNamespace)
        {

            // create a new class object and modify it to be an interface
            NamespaceTypeDefinition newInterface = this.createNewClass(className, containingUnitNamespace, false, false);
            newInterface.IsAbstract = true;
            newInterface.IsInterface = true;
            newInterface.BaseClasses = null;

            return newInterface;
        }
 internal static IGlobalFieldDefinition GetGlobalField(IUnitNamespace unitNamespace, IName fieldName) {
   foreach (INamespaceMember nm in unitNamespace.GetMembersNamed(fieldName, false)) {
     if (nm is IGlobalFieldDefinition)
       return nm as IGlobalFieldDefinition;
   }
   return null;
 }
示例#35
0
        private void createNodeInterface(IUnitNamespace targetNamespace) {

            this.nodeInterface = this.helperClass.createNewInterface("iNode", targetNamespace); // TODO: interface name

            // create getter and setter for the startPointer variable
            this.interfaceStartPointerGet = this.helperClass.createNewMethod("startPointer_get", this.nodeInterface, this.nodeInterface, TypeMemberVisibility.Public, null, CallingConvention.HasThis, false, true, true); // TODO: method name

            List<IParameterDefinition> parameters = new List<IParameterDefinition>();
            ParameterDefinition parameter = new ParameterDefinition();
            parameter.IsIn = false;
            parameter.IsOptional = false;
            parameter.IsOut = false;
            parameter.Name = host.NameTable.GetNameFor("value");
            parameter.Type = this.nodeInterface;
            parameters.Add(parameter);
            this.interfaceStartPointerSet = this.helperClass.createNewMethod("startPointer_set", this.nodeInterface, host.PlatformType.SystemVoid, TypeMemberVisibility.Public, parameters, CallingConvention.HasThis, false, true, true); // TODO: method name

            // create getter and setter for the childNodes array variable
            parameters = new List<IParameterDefinition>();
            // int parameter
            parameter = new ParameterDefinition();
            parameter.IsIn = false;
            parameter.IsOptional = false;
            parameter.IsOut = false;
            parameter.Type = this.host.PlatformType.SystemInt32;
            parameters.Add(parameter);
            this.interfaceChildNodesGet = this.helperClass.createNewMethod("childNodes_get", this.nodeInterface, this.nodeInterface, TypeMemberVisibility.Public, parameters, CallingConvention.HasThis, false, true, true); // TODO: method name

            parameters = new List<IParameterDefinition>();
            // iNode parameter
            parameter = new ParameterDefinition();
            parameter.IsIn = false;
            parameter.IsOptional = false;
            parameter.IsOut = false;
            parameter.Type = this.nodeInterface;
            parameters.Add(parameter);
            // int parameter
            parameter = new ParameterDefinition();
            parameter.IsIn = false;
            parameter.IsOptional = false;
            parameter.IsOut = false;
            parameter.Type = this.host.PlatformType.SystemInt32;
            parameters.Add(parameter);
            this.interfaceChildNodesSet = this.helperClass.createNewMethod("childNodes_set", this.nodeInterface, host.PlatformType.SystemVoid, TypeMemberVisibility.Public, parameters, CallingConvention.HasThis, false, true, true); // TODO: method name

            // when debugging is activated
            // => create getter for the id variable that distinct identifies the object
            if (this.debugging) {

                this.logger.writeLine("Debugging activated: Adding getter for unique object id to node interface");

                this.debuggingInterfaceIdGet = this.helperClass.createNewMethod("DEBUG_objectId_get", this.nodeInterface, this.host.PlatformType.SystemString, TypeMemberVisibility.Public, null, CallingConvention.HasThis, false, true, true); // TODO: method name
            }

        }
示例#36
0
 /// <summary>
 /// Traverses the specified unit namespace definition.
 /// </summary>
 public void Traverse(IUnitNamespace namespaceDefinition)
 {
     Contract.Requires(namespaceDefinition != null);
       namespaceDefinition.Dispatch(this.dispatchingVisitor);
 }
 /// <summary>
 /// Visits the specified unit namespace.
 /// </summary>
 public virtual void Visit(IUnitNamespace unitNamespace)
 {
     Contract.Requires(unitNamespace != null);
 }
示例#38
0
 /// <summary>
 /// Visits the specified unit namespace.
 /// </summary>
 public void Visit(IUnitNamespace unitNamespace)
 {
     this.Visit((INamespaceDefinition)unitNamespace);
 }
示例#39
0
        static void Main(string[] args)
        {
            String inputFile;
            String targetFile;
            String targetNamespace;
            String targetClass;
            String targetMethod;
            int    depth;
            int    dimension;
            int    numberValidPaths;
            int    duplicateBasicBlockWeight;
            int    duplicateBasicBlockCorrectionValue;
            int    stateChangeWeight;
            int    stateChangeCorrectionValue;
            int    insertOpaquePredicateWeight;
            int    seed;

            // Add debugging code into the obfuscated method (dump obfuscation graphs and so on)
            bool graphTransformerDebug = false;

            // Should the obfuscated code contain information to trace the control flow?
            bool basicBlockTrace = false;

            // When debugging is active, should the whole obfuscation graph be dumped or only the vpaths in it?
            bool graphOnlyDumpVPaths = true;

            // The number of random interfaces that are added to the program
            int numberRandomInterfaces = 100;

            if (args.Length != 14)
            {
                System.Console.WriteLine("Needed parameters: <inputBinary> <outputBinary> <namespace> <class> <method> <depth> <dimension> <numberValidPaths> <duplicateBasicBlockWeight> <duplicateBasicBlockCorrectionValue> <stateChangeWeight> <stateChangeCorrectionValue> <insertOpaquePredicateWeight> <seed>");
                return;
            }
            else
            {
                inputFile                          = args[0];
                targetFile                         = args[1];
                targetNamespace                    = args[2];
                targetClass                        = args[3];
                targetMethod                       = args[4];
                depth                              = Convert.ToInt32(args[5]);
                dimension                          = Convert.ToInt32(args[6]);
                numberValidPaths                   = Convert.ToInt32(args[7]);
                duplicateBasicBlockWeight          = Convert.ToInt32(args[8]);
                duplicateBasicBlockCorrectionValue = Convert.ToInt32(args[9]);
                stateChangeWeight                  = Convert.ToInt32(args[10]);
                stateChangeCorrectionValue         = Convert.ToInt32(args[11]);
                insertOpaquePredicateWeight        = Convert.ToInt32(args[12]);
                seed = Convert.ToInt32(args[13]);
            }

            String logDir = Path.GetDirectoryName(targetFile);

            Log.Log logger = new Log.Log(logDir, "probfuscation_logfile.txt");

            System.Console.WriteLine("Obfuscating: " + inputFile);
            logger.writeLine("Obfuscating: " + inputFile);
            System.Console.WriteLine("Output file: " + targetFile);
            logger.writeLine("Output file: " + targetFile);
            System.Console.WriteLine("Target namespace: " + targetNamespace);
            logger.writeLine("Target namespace: " + targetNamespace);
            System.Console.WriteLine("Target class: " + targetClass);
            logger.writeLine("Target class: " + targetClass);
            System.Console.WriteLine("Target method: " + targetMethod);
            logger.writeLine("Target method: " + targetMethod);
            System.Console.WriteLine("Depth: " + depth);
            logger.writeLine("Depth: " + depth);
            System.Console.WriteLine("Dimension: " + dimension);
            logger.writeLine("Dimension: " + dimension);
            System.Console.WriteLine("Number of vpaths: " + numberValidPaths);
            logger.writeLine("Number of vpaths: " + numberValidPaths);
            System.Console.WriteLine("Basic Block duplication weight: " + duplicateBasicBlockWeight);
            logger.writeLine("Basic Block duplication weight: " + duplicateBasicBlockWeight);
            System.Console.WriteLine("Basic Block duplication correction value: " + duplicateBasicBlockCorrectionValue);
            logger.writeLine("Basic Block duplication correction value: " + duplicateBasicBlockCorrectionValue);
            System.Console.WriteLine("State change weight: " + stateChangeWeight);
            logger.writeLine("State change weight: " + stateChangeWeight);
            System.Console.WriteLine("State change correction value: " + stateChangeCorrectionValue);
            logger.writeLine("State change correction value: " + stateChangeCorrectionValue);
            System.Console.WriteLine("Opaque predicate weight: " + insertOpaquePredicateWeight);
            logger.writeLine("Opaque predicate weight: " + insertOpaquePredicateWeight);
            System.Console.WriteLine("Seed: " + seed);
            logger.writeLine("Seed: " + seed);

            // Seed PRNG for interfaces
            PRNGRandomInterfaces = new Random(seed);

            using (var host = new PeReader.DefaultHost()) {
                IModule /*?*/ module = host.LoadUnitFrom(inputFile) as IModule;

                if (module == null || module == Dummy.Module || module == Dummy.Assembly)
                {
                    Console.WriteLine(inputFile + " is not a PE file containing a CLR module or assembly.");
                    return;
                }

                module = new MetadataDeepCopier(host).Copy(module);

                if (module as Assembly == null)
                {
                    logger.writeLine("File does not have CIL assembly");
                    return;
                }

                // create analyzer object object
                CfgBuilder analyze = new Cfg.CfgBuilder(module, host, logger);

                PdbReader /*?*/ pdbReader = null;
                string          pdbFile   = Path.ChangeExtension(module.Location, "pdb");
                if (File.Exists(pdbFile))
                {
                    using (var pdbStream = File.OpenRead(pdbFile)) {
                        pdbReader = new PdbReader(pdbStream, host);
                    }
                }
                else
                {
                    logger.writeLine("Could not load the PDB file for '" + module.Name.Value + "' . Proceeding anyway.");
                }

                using (pdbReader) {
                    Microsoft.Cci.ILGenerator.LocalScopeProvider localScopeProvider = null;
                    if (pdbReader != null)
                    {
                        localScopeProvider = new ILGenerator.LocalScopeProvider(pdbReader);
                    }

                    // search the namespace the interface should be added to
                    IUnitNamespace foundNamespace = null;
                    foreach (var tempMember in module.UnitNamespaceRoot.Members)
                    {
                        if ((tempMember as IUnitNamespace) == null)
                        {
                            continue;
                        }

                        IUnitNamespace tempNamespace = (tempMember as IUnitNamespace);

                        if (tempNamespace.ToString() == targetNamespace)
                        {
                            foundNamespace = tempNamespace;
                            break;
                        }
                    }
                    if (foundNamespace == null)
                    {
                        throw new ArgumentException("Not able to find target namespace.");
                    }

                    // add created interface (and implemented methods) to all classes
                    bool classFound = false;
                    foreach (var tempClass in module.GetAllTypes())
                    {
                        if ((tempClass as NamespaceTypeDefinition) == null ||
                            tempClass.IsAbstract)
                        {
                            continue;
                        }

                        NamespaceTypeDefinition foundClass = (tempClass as NamespaceTypeDefinition);

                        if (foundClass.ContainingUnitNamespace.ToString() == "")
                        {
                            continue;
                        }
                        if (foundClass.ToString() != targetNamespace + "." + targetClass)
                        {
                            continue;
                        }
                        classFound = true;

                        Random           prng             = new Random();
                        GraphTransformer graphTransformer = new GraphTransformer(module, host, logger, prng, foundNamespace, foundClass, depth, dimension, graphTransformerDebug);

                        graphTransformer.duplicateBasicBlockWeight          = duplicateBasicBlockWeight;
                        graphTransformer.duplicateBasicBlockCorrectionValue = duplicateBasicBlockCorrectionValue;
                        graphTransformer.stateChangeWeight           = stateChangeWeight;
                        graphTransformer.stateChangeCorrectionValue  = stateChangeCorrectionValue;
                        graphTransformer.insertOpaquePredicateWeight = insertOpaquePredicateWeight;
                        graphTransformer.trace = basicBlockTrace;
                        graphTransformer.graphOnlyDumpVPaths   = graphOnlyDumpVPaths;
                        graphTransformer.debuggingDumpLocation = logDir;

                        // Add 100 random interfaces to the namespace
                        Helper testHelper = new Helper(module, host, logger);
                        List <NamespaceTypeDefinition> randomInterfaces = new List <NamespaceTypeDefinition>();
                        for (int i = 0; i < numberRandomInterfaces; i++)
                        {
                            String randName = randomString(20);
                            NamespaceTypeDefinition temp = testHelper.createNewInterface(randName, foundNamespace);
                            randomInterfaces.Add(temp);
                        }

                        InterfaceTransformer interfaceTransformer = new InterfaceTransformer(module, host, logger);
                        foreach (var classToAdd in module.GetAllTypes())
                        {
                            if ((classToAdd as NamespaceTypeDefinition) == null ||
                                classToAdd.IsAbstract ||
                                classToAdd.IsInterface ||
                                classToAdd.IsEnum ||
                                classToAdd.IsDelegate ||
                                classToAdd.IsGeneric ||
                                classToAdd.IsStruct)
                            {
                                continue;
                            }

                            if (((NamespaceTypeDefinition)classToAdd).ContainingUnitNamespace.ToString() == "")
                            {
                                continue;
                            }

                            /*
                             * // Use this code if you want to add standard interfaces to the target class
                             * interfaceTransformer.addStdInterfacesGivenByFile(@"e:\code\dotnet_standard_interfaces.txt");
                             *
                             * // add std interfaces to class
                             * if (foundClass != (classToAdd as NamespaceTypeDefinition)) {
                             *  foreach (ITypeDefinition temp in interfaceTransformer.getInterfacesList()) {
                             *      interfaceTransformer.addInterface((classToAdd as NamespaceTypeDefinition), temp);
                             *  }
                             * }
                             */

                            // Add random interfaces to the classes
                            List <NamespaceTypeDefinition> alreadyAdded = new List <NamespaceTypeDefinition>();
                            int max = PRNGRandomInterfaces.Next(numberRandomInterfaces);
                            NamespaceTypeDefinition interfaceClass = (classToAdd as NamespaceTypeDefinition);
                            logger.writeLine("Adding " + max + " random interfaces to class \"" + interfaceClass.ToString() + "\"");
                            for (int i = 0; i < max; i++)
                            {
                                NamespaceTypeDefinition randInterface = randomInterfaces.ElementAt(PRNGRandomInterfaces.Next(randomInterfaces.Count));
                                if (alreadyAdded.Contains(randInterface))
                                {
                                    continue;
                                }
                                alreadyAdded.Add(randInterface);
                                logger.writeLine("Adding interface: \"" + randInterface.ToString() + "\"");

                                // add nodes interface to class
                                if (interfaceClass.Interfaces != null)
                                {
                                    interfaceClass.Interfaces.Add(randInterface);
                                }
                                else
                                {
                                    interfaceClass.Interfaces = new List <ITypeReference>();
                                    interfaceClass.Interfaces.Add(randInterface);
                                }
                            }
                            logger.writeLine("");

                            // Add special interface for the obfuscation scheme to the class
                            // (makes sure that all needed attributes and methods are implemented)
                            graphTransformer.addNodeInterfaceToTargetClass((classToAdd as NamespaceTypeDefinition));
                        }

                        // Prepare obfuscation graph
                        graphTransformer.generateGraph(numberValidPaths);
                        graphTransformer.createGraphMethods();

                        // Search method to obfuscate
                        MethodDefinition methodToObfu = null;
                        foreach (MethodDefinition tempMethod in foundClass.Methods)
                        {
                            if (tempMethod.Name.ToString() == targetMethod)
                            {
                                methodToObfu = tempMethod;
                                break;
                            }
                        }
                        if (methodToObfu == null)
                        {
                            throw new ArgumentException("Not able to find target method.");
                        }

                        // Obfuscate target method
                        MethodCfg cfg = analyze.buildCfgForMethod(methodToObfu);
                        logger.dumpMethodCfg(cfg, "before");
                        graphTransformer.addObfuscationToMethod(cfg);
                        analyze.createMethodFromCfg(cfg);
                        logger.dumpMethodCfg(cfg, "after");

                        break;
                    }
                    if (!classFound)
                    {
                        throw new ArgumentException("Not able to find target class.");
                    }


                    /*
                     * This code can be used if not only one specific method should be obfuscated,
                     * but the whole class.
                     * List<ClassCfg> classCfgList = new List<ClassCfg>();
                     * foreach (var tempClass in module.GetAllTypes()) {
                     *  if ((tempClass as NamespaceTypeDefinition) == null
                     || tempClass.IsAbstract) {
                     ||     continue;
                     || }
                     ||
                     || // create basic blocks
                     || NamespaceTypeDefinition foundClass = (tempClass as NamespaceTypeDefinition);
                     ||
                     || logger.writeLine("Create CFG for class \"" + foundClass.Name.ToString() + "\"");
                     || ClassCfg temp = analyze.buildCfgForClass(foundClass);
                     || classCfgList.Add(temp);
                     || logger.writeLine("\n---------------------------------\n");
                     ||}
                     ||
                     ||// transform each function
                     ||NopTransformer transformator = new NopTransformer(module, host, logger);
                     ||foreach (ClassCfg tempClassCfg in classCfgList) {
                     || foreach (MethodCfg tempMethodCfg in tempClassCfg.methodCfgs) {
                     ||     logger.writeLine("Transform method CFG of \"" + tempMethodCfg.method.ToString() + "\"");
                     ||     transformator.addNopsToCfg(tempMethodCfg);
                     ||     logger.writeLine("\n---------------------------------\n");
                     || }
                     ||}
                     ||
                     ||foreach (ClassCfg tempClassCfg in classCfgList) {
                     || logger.writeLine("Create class from CFG for \"" + tempClassCfg.classObj.Name.ToString() + "\"");
                     || analyze.createClassFromCfg(tempClassCfg);
                     || logger.writeLine("\n---------------------------------\n");
                     ||}
                     */

                    using (var peStream = File.Create(targetFile)) {
                        using (var pdbWriter = new PdbWriter(Path.ChangeExtension(targetFile, ".pdb"), pdbReader)) {
                            PeWriter.WritePeToStream(module, host, peStream, pdbReader, localScopeProvider, pdbWriter);
                        }
                    }
                }
            }
        }
示例#40
0
 public override void TraverseChildren(IUnitNamespace namespaceDefinition)
 {
     MethodEnter(namespaceDefinition);
     base.TraverseChildren(namespaceDefinition);
     MethodExit();
 }
示例#41
0
 /// <summary>
 /// Traverses the specified unit namespace definition.
 /// </summary>
 public void Traverse(IUnitNamespace namespaceDefinition)
 {
     namespaceDefinition.Dispatch(this.dispatchingVisitor);
 }