public static byte [] GetPublicKey(byte [] snk)
        {
            var snkp = new System.Reflection.StrongNameKeyPair(snk);

            byte [] publicKey = snkp.PublicKey;
            return(publicKey);
        }
        public static byte [] GetPublicKey(string container)
        {
            var snkp = new System.Reflection.StrongNameKeyPair(container);

            byte [] publicKey = snkp.PublicKey;
            return(publicKey);
        }
Esempio n. 3
0
        void Initialize(out System.Reflection.StrongNameKeyPair sn)
        {
            sn = null;
            if (string.IsNullOrEmpty(param.StrongNameKeyPath))
            {
                param.Logger.Log("Strong name key not specified.");
            }
            else if (!File.Exists(param.StrongNameKeyPath))
            {
                param.Logger.Log("Strong name key not found. Output assembly will not be signed.");
            }
            else
            {
                sn = new System.Reflection.StrongNameKeyPair(new FileStream(param.StrongNameKeyPath, FileMode.Open));
            }

            Marker mkr = param.Marker;

            GlobalAssemblyResolver.Instance.AssemblyCache.Clear();
            GlobalAssemblyResolver.Instance.ClearSearchDirectories();
            GlobalAssemblyResolver.Instance.AddSearchDirectory(param.ReferencesPath);

            param.Logger.Log(string.Format("Analysing assemblies..."));
            mkr.Initalize(param.Confusions, param.Packers);
            assemblies = new List <AssemblyDefinition>(mkr.GetAssemblies(param.SourceAssembly, param.DefaultPreset, this, (sender, e) => param.Logger.Log(e.Message)));

            helpers = new Dictionary <IMemberDefinition, HelperAttribute>();

            engines = new List <IEngine>();
            foreach (IConfusion cion in param.Confusions)
            {
                foreach (Phase phase in cion.Phases)
                {
                    if (phase.GetEngine() != null)
                    {
                        engines.Add(phase.GetEngine());
                    }
                }
            }
            for (int i = 0; i < engines.Count; i++)
            {
                engines[i].Analysis(param.Logger, assemblies);
                param.Logger.Progress((double)(i + 1) / engines.Count);
            }
        }
Esempio n. 4
0
		public StrongNameKeyPair(byte[] keyPairArray)
		{
			this.keyPair = new System.Reflection.StrongNameKeyPair(keyPairArray);
		}
Esempio n. 5
0
		public StrongNameKeyPair(string keyPairContainer)
		{
			this.keyPair = new System.Reflection.StrongNameKeyPair(keyPairContainer);
		}
Esempio n. 6
0
		internal StrongNameKeyPair(System.Reflection.StrongNameKeyPair keyPair)
		{
			this.keyPair = keyPair;
		}
Esempio n. 7
0
 public virtual System.Reflection.Emit.AssemblyBuilder ConvertTypeLibToAssembly(object typeLib, string asmFileName, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, byte[] publicKey, System.Reflection.StrongNameKeyPair keyPair, string asmNamespace, System.Version asmVersion)
 {
 }
Esempio n. 8
0
        public static int Main(string[] args)
        {
            for (; null != args;)
            {
                try {
                    var fileName = args?[0];
                    if (null == fileName)
                    {
                        return((int)ExitStatus.UserCanceled);
                    }
                    var dirName       = Path.GetDirectoryName(fileName);
                    var fileNameShort = Path.GetFileNameWithoutExtension(fileName);
                    var fileNameExt   = Path.GetExtension(fileName);

                    var fileName_Original = Path.Combine(dirName, fileNameShort + fileNameExt);
                    var fileName_Modified = Path.Combine(dirName, fileNameShort + @".tmp");
                    var fileName_Backup   = Path.Combine(dirName, fileNameShort + @".bak");
                    var fullpath          = Path.GetFullPath(fileName_Original);
                    var rm = new ReaderParameters()
                    {
                        ThrowIfSymbolsAreNotMatching = true, ReadSymbols = true
                    };
                    rm.InMemory = true;
                    var assembly = AssemblyDefinition.ReadAssembly(fileName_Original, rm);
                    var module   = assembly.MainModule;
                    var modified = 0;
                    {
                        var sdfsdaf = typeof(OpCodes).GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
                        var sdafsd  = sdfsdaf.ToDictionary(x => x.Name.ToUpperInvariant());
                        sdafsd.Add("Ldelem".ToUpperInvariant(), typeof(OpCodes).GetField(nameof(OpCodes.Ldelem_Any), System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static));
                        sdafsd.Add("Stelem".ToUpperInvariant(), typeof(OpCodes).GetField(nameof(OpCodes.Stelem_Any), System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static));

                        foreach (var typeref in module.GetTypes())
                        {
                            if (typeref is TypeDefinition type)
                            {
                                foreach (var method in type.Methods)
                                {
                                    if (!method.HasCustomAttributes)
                                    {
                                        continue;
                                    }
                                    var sdafds = default(string);

                                    var sdfsdf = default(CustomAttribute);
                                    foreach (var customAttribute in method.CustomAttributes)
                                    {
                                        if ("ILMethodBodyAttribute" == customAttribute.AttributeType.Name)
                                        {
                                            var aaa = customAttribute.ConstructorArguments[0];

                                            sdafds = aaa.Value as string;
                                            sdfsdf = customAttribute;
                                            break;
                                        }
                                    }

                                    if (null == sdafds)
                                    {
                                        continue;
                                    }


                                    using (var sdfsdfas = new StringReader(sdafds)) {
                                        var ts = method.GenericParameters;
                                        if (!method.HasBody)
                                        {
                                            continue;
                                        }
                                        {
                                            var bd  = method.Body;
                                            var ins = bd.Instructions;
                                            var ilg = (ILProcessor)null;
                                            ilg = bd.GetILProcessor();
                                            var insa = ins.ToArray();
                                            for (var i = 0; insa.Length > i; ++i)
                                            {
                                                ilg.Remove(insa[i]);
                                            }
                                            {
                                                string sdfdasff;
                                                for (; null != (sdfdasff = sdfsdfas.ReadLine());)
                                                {
                                                    Console.Out.WriteLine($@"method {method.Name}");
                                                    Console.Out.WriteLine($@"  ""{sdfdasff}""");
                                                    var sdfasd = sdfdasff.Split(new[] { ' ', '\t', }, StringSplitOptions.RemoveEmptyEntries);
                                                    Console.Out.WriteLine("ddddd");
                                                    var sdfas = sdfasd.FirstOrDefault();
                                                    if (null == sdfas)
                                                    {
                                                        continue;
                                                    }
                                                    var sdfa   = sdfas.Replace('.', '_').ToUpperInvariant();
                                                    var safsad = sdafsd[sdfa];
                                                    var sdfsaf = (safsad.GetValue(null) as OpCode?);
                                                    if (null == sdfsaf)
                                                    {
                                                        throw new Exception("gfghgh");
                                                    }
                                                    var sdfdsa = sdfsaf.Value;
                                                    switch (sdfdsa.OperandType)
                                                    {
                                                    case OperandType.InlineBrTarget:
                                                        throw new NotImplementedException();
                                                        break;

                                                    case OperandType.InlineField:
                                                        throw new NotImplementedException();
                                                        break;

                                                    case OperandType.InlineI:
                                                        throw new NotImplementedException();
                                                        break;

                                                    case OperandType.InlineI8:
                                                        throw new NotImplementedException();
                                                        break;

                                                    case OperandType.InlineMethod:
                                                        throw new NotImplementedException();
                                                        break;

                                                    case OperandType.InlineNone:
                                                        ilg.Append(ilg.Create(sdfdsa));
                                                        break;

                                                    case OperandType.InlinePhi:
                                                        throw new NotImplementedException();
                                                        break;

                                                    case OperandType.InlineR:
                                                        throw new NotImplementedException();
                                                        break;

                                                    case OperandType.InlineSig:
                                                        throw new NotImplementedException();
                                                        break;

                                                    case OperandType.InlineString:
                                                        throw new NotImplementedException();
                                                        break;

                                                    case OperandType.InlineSwitch:
                                                        throw new NotImplementedException();
                                                        break;

                                                    case OperandType.InlineTok:
                                                        throw new NotImplementedException();
                                                        break;

                                                    case OperandType.InlineType:
                                                        ilg.Append(ilg.Create(sdfdsa, ts[int.Parse(sdfasd[1].Substring(2))]));
                                                        break;

                                                    case OperandType.InlineVar:
                                                        throw new NotImplementedException();
                                                        break;

                                                    case OperandType.InlineArg:
                                                        throw new NotImplementedException();
                                                        break;

                                                    case OperandType.ShortInlineBrTarget:
                                                        throw new NotImplementedException();
                                                        break;

                                                    case OperandType.ShortInlineI:
                                                        throw new NotImplementedException();
                                                        break;

                                                    case OperandType.ShortInlineR:
                                                        throw new NotImplementedException();
                                                        break;

                                                    case OperandType.ShortInlineVar:
                                                        throw new NotImplementedException();
                                                        break;

                                                    case OperandType.ShortInlineArg:
                                                        throw new NotImplementedException();
                                                        break;

                                                    default:
                                                        throw new Exception("il opcode arg");
                                                    }
                                                }
                                            }
                                            method.CustomAttributes.Remove(sdfsdf);

                                            ++modified;
                                            if (null != ilg)
                                            {
                                                var ignored = 0;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    {
                        if (false)
                        {
                            var typeref = module.GetType(@"UltimateOrb.Utilities.BooleanIntegerModule", false);
                            if (typeref is TypeDefinition type)
                            {
                                var collection = type.Methods;
                                foreach (var method in collection)
                                {
                                    if (@"LessThan" != method.Name)
                                    {
                                        continue;
                                    }
                                    if (!method.HasBody)
                                    {
                                        continue;
                                    }
                                    {
                                        var bd = method.Body;
                                        var f  = method.Parameters[0].ParameterType.Name;
                                        var s  = method.Parameters[1].ParameterType.Name;
                                        if (f != s)
                                        {
                                            continue;
                                        }
                                        var ins = bd.Instructions;
                                        var ilg = (ILProcessor)null;
                                        ilg = bd.GetILProcessor();
                                        var insa = ins.ToArray();
                                        for (var i = 0; insa.Length > i; ++i)
                                        {
                                            ilg.Remove(insa[i]);
                                        }
                                        {
                                            ilg.Append(ilg.Create(OpCodes.Ldarg_0));
                                            ilg.Append(ilg.Create(OpCodes.Ldarg_1));
                                            if (f.ToUpperInvariant().StartsWith("U"))
                                            {
                                                ilg.Append(ilg.Create(OpCodes.Clt_Un));
                                            }
                                            else
                                            {
                                                ilg.Append(ilg.Create(OpCodes.Clt));
                                            }
                                            ilg.Append(ilg.Create(OpCodes.Ret));
                                            ++modified;
                                        }
                                        if (null != ilg)
                                        {
                                            var ignored = 0;
                                        }
                                    }
                                }
                            }
                        }
                        if (false)
                        {
                            var typeref = module.GetType(@"UltimateOrb.Utilities.BooleanIntegerModule", false);
                            if (typeref is TypeDefinition type)
                            {
                                var collection = type.Methods;
                                foreach (var method in collection)
                                {
                                    if (@"LessThanOrEqual" != method.Name)
                                    {
                                        continue;
                                    }
                                    if (!method.HasBody)
                                    {
                                        continue;
                                    }
                                    {
                                        var bd = method.Body;
                                        var f  = method.Parameters[0].ParameterType.Name;
                                        var s  = method.Parameters[1].ParameterType.Name;
                                        if (f != s)
                                        {
                                            continue;
                                        }
                                        var ins = bd.Instructions;
                                        var ilg = (ILProcessor)null;
                                        ilg = bd.GetILProcessor();
                                        var insa = ins.ToArray();
                                        for (var i = 0; insa.Length > i; ++i)
                                        {
                                            ilg.Remove(insa[i]);
                                        }
                                        {
                                            ilg.Append(ilg.Create(OpCodes.Ldarg_0));
                                            ilg.Append(ilg.Create(OpCodes.Ldarg_1));
                                            if (f.ToUpperInvariant().StartsWith("U") || f == "Single" || f == "Double" || f == "float" || f == "double")
                                            {
                                                ilg.Append(ilg.Create(OpCodes.Cgt_Un));
                                            }
                                            else
                                            {
                                                ilg.Append(ilg.Create(OpCodes.Cgt));
                                            }
                                            ilg.Append(ilg.Create(OpCodes.Ldc_I4_0));
                                            ilg.Append(ilg.Create(OpCodes.Ceq));
                                            ilg.Append(ilg.Create(OpCodes.Ret));
                                            ++modified;
                                        }
                                        if (null != ilg)
                                        {
                                            var ignored = 0;
                                        }
                                    }
                                }
                            }
                        }
                        if (false)
                        {
                            var typeref = module.GetType(@"UltimateOrb.Utilities.BooleanIntegerModule", false);
                            if (typeref is TypeDefinition type)
                            {
                                var collection = type.Methods;
                                foreach (var method in collection)
                                {
                                    if (@"GreaterThan" != method.Name)
                                    {
                                        continue;
                                    }
                                    if (!method.HasBody)
                                    {
                                        continue;
                                    }
                                    {
                                        var bd = method.Body;
                                        var f  = method.Parameters[0].ParameterType.Name;
                                        var s  = method.Parameters[1].ParameterType.Name;
                                        if (f != s)
                                        {
                                            continue;
                                        }
                                        var ins = bd.Instructions;
                                        var ilg = (ILProcessor)null;
                                        ilg = bd.GetILProcessor();
                                        var insa = ins.ToArray();
                                        for (var i = 0; insa.Length > i; ++i)
                                        {
                                            ilg.Remove(insa[i]);
                                        }
                                        {
                                            ilg.Append(ilg.Create(OpCodes.Ldarg_0));
                                            ilg.Append(ilg.Create(OpCodes.Ldarg_1));
                                            if (f.ToUpperInvariant().StartsWith("U"))
                                            {
                                                ilg.Append(ilg.Create(OpCodes.Cgt_Un));
                                            }
                                            else
                                            {
                                                ilg.Append(ilg.Create(OpCodes.Cgt));
                                            }
                                            ilg.Append(ilg.Create(OpCodes.Ret));
                                            ++modified;
                                        }
                                        if (null != ilg)
                                        {
                                            var ignored = 0;
                                        }
                                    }
                                }
                            }
                        }
                        if (false)
                        {
                            var typeref = module.GetType(@"UltimateOrb.Utilities.BooleanIntegerModule", false);
                            if (typeref is TypeDefinition type)
                            {
                                var collection = type.Methods;
                                foreach (var method in collection)
                                {
                                    if (@"GreaterThanOrEqual" != method.Name)
                                    {
                                        continue;
                                    }
                                    if (!method.HasBody)
                                    {
                                        continue;
                                    }
                                    {
                                        var bd = method.Body;
                                        var f  = method.Parameters[0].ParameterType.Name;
                                        var s  = method.Parameters[1].ParameterType.Name;
                                        if (f != s)
                                        {
                                            continue;
                                        }
                                        var ins = bd.Instructions;
                                        var ilg = (ILProcessor)null;
                                        ilg = bd.GetILProcessor();
                                        var insa = ins.ToArray();
                                        for (var i = 0; insa.Length > i; ++i)
                                        {
                                            ilg.Remove(insa[i]);
                                        }
                                        {
                                            ilg.Append(ilg.Create(OpCodes.Ldarg_0));
                                            ilg.Append(ilg.Create(OpCodes.Ldarg_1));
                                            if (f.ToUpperInvariant().StartsWith("U") || f == "Single" || f == "Double" || f == "float" || f == "double")
                                            {
                                                ilg.Append(ilg.Create(OpCodes.Clt_Un));
                                            }
                                            else
                                            {
                                                ilg.Append(ilg.Create(OpCodes.Clt));
                                            }
                                            ilg.Append(ilg.Create(OpCodes.Ldc_I4_0));
                                            ilg.Append(ilg.Create(OpCodes.Ceq));
                                            ilg.Append(ilg.Create(OpCodes.Ret));
                                            ++modified;
                                        }
                                        if (null != ilg)
                                        {
                                            var ignored = 0;
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (modified <= 0)
                    {
                        return((int)ExitStatus.RequestFailed);
                    }
                    Console.Out.WriteLine($@"Modified: {modified}.");
                    var sss = (System.Reflection.StrongNameKeyPair)null;
                    try {
                        var keyfile = args?[1];
                        if (null != keyfile)
                        {
                            sss = new System.Reflection.StrongNameKeyPair(File.ReadAllBytes(keyfile));
                        }
                    } catch (Exception) {
                    }

                    Console.Out.Write($@"Writing file: {fileName_Modified}... ");
                    var wp = new WriterParameters()
                    {
                        WriteSymbols = true
                    };
                    assembly.Write(fileName_Modified, wp);
                    Console.Out.WriteLine($@"Done.");
                    File.Replace(fileName_Modified, fileName_Original, fileName_Backup);
                    Console.Out.WriteLine($@"""{fileName_Original}"" -> ""{fileName_Backup}""");
                    Console.Out.WriteLine($@"""{fileName_Modified}"" -> ""{fileName_Original}""");
                    Console.Out.WriteLine(@"Done.");
                    return((int)ExitStatus.OK);
                } catch (Exception ex) {
                    Console.Error.WriteLine(ex);
                    return((int)ExitStatus.RequestFailed);
                }
                break;
            }
            return((int)ExitStatus.UserCanceled);
        }
Esempio n. 9
0
 public StrongNameKeyPair(byte[] keyPairArray)
 {
     this.keyPair = new System.Reflection.StrongNameKeyPair(keyPairArray);
 }
Esempio n. 10
0
 internal StrongNameKeyPair(System.Reflection.StrongNameKeyPair keyPair)
 {
     this.keyPair = keyPair;
 }
Esempio n. 11
0
        private void Rewrite()
        {
            // Specify assembly read and write parameters
            // We want to keep a valid symbols file (pdb or mdb)
            var read_params  = new ReaderParameters();
            var write_params = new WriterParameters();

            read_params.AssemblyResolver = new OpenTKAssemblyResolver();
            read_params.ReadSymbols      = true;
            read_params.ReadWrite        = true;
            write_params.WriteSymbols    = true;

            if (!String.IsNullOrEmpty(Options.StrongNameKey) && File.Exists(Options.StrongNameKey))
            {
                string absoluteKeyFilePath = Path.GetFullPath(Options.StrongNameKey);

                using (var fs = new FileStream(absoluteKeyFilePath, FileMode.Open, FileAccess.Read))
                {
                    var keypair = new System.Reflection.StrongNameKeyPair(fs);
                    write_params.StrongNameKeyPair = keypair;
                }
            }
            else
            {
                Console.Error.WriteLine("No keyfile specified or keyfile missing.");
            }

            if (Options.IsNetStandard)
            {
                DefaultAssemblyResolver resolver = new DefaultAssemblyResolver();
                string searchPath = GetNetstandardRefPath();
                if (!Directory.Exists(searchPath))
                {
                    Console.Error.WriteLine(
                        "Could not locate .NET Standard reference assemblies. This is necessary for binary rewriting to proceed.");
                    return;
                }

                resolver.AddSearchDirectory(searchPath);
                read_params.AssemblyResolver = resolver;
            }

            // Load assembly and process all modules
            try
            {
                using (AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(Options.TargetAssembly, read_params))
                {
                    var rewritten = assembly.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == "RewrittenAttribute");
                    if (rewritten == null)
                    {
                        foreach (var module in assembly.Modules)
                        {
                            foreach (var reference in module.AssemblyReferences)
                            {
                                try
                                {
                                    var resolved = module.AssemblyResolver.Resolve(reference);
                                    if (reference.Name == GetCoreAssemblyName())
                                    {
                                        mscorlib = resolved;
                                    }
                                }
                                catch (Exception e)
                                {
                                    Console.Error.WriteLine(e.ToString());
                                }
                            }
                        }

                        if (mscorlib == null)
                        {
                            Console.Error.WriteLine("Failed to locate " + GetCoreAssemblyName());
                            return;
                        }
                        TypeMarshal = mscorlib.MainModule.GetType("System.Runtime.InteropServices.Marshal");
                        TypeVoid    = mscorlib.MainModule.GetType("System.Void");
                        TypeIntPtr  = mscorlib.MainModule.GetType("System.IntPtr");
                        TypeInt32   = mscorlib.MainModule.GetType("System.Int32");

                        TypeBindingsBase = assembly.Modules.Select(m => m.GetType("OpenTK.BindingsBase")).First();

                        foreach (var module in assembly.Modules)
                        {
                            foreach (var type in module.Types)
                            {
                                Rewrite(type);
                            }
                        }
                    }
                    else
                    {
                        Console.Error.WriteLine("Error: assembly has already been rewritten");
                    }

                    // Save rewritten assembly
                    assembly.Write(write_params);
                }
            }
            catch (InvalidOperationException inex)
            {
                Console.WriteLine("Failed to load the assembly. It may already have been rewritten, and the debug symbols no longer match.");
                Console.WriteLine(inex);
            }
        }
 public System.Reflection.Emit.AssemblyBuilder ConvertTypeLibToAssembly(object typeLib, string asmFileName, int flags, ITypeLibImporterNotifySink notifySink, Byte[] publicKey, System.Reflection.StrongNameKeyPair keyPair, bool unsafeInterfaces)
 {
 }
 public System.Reflection.Emit.AssemblyBuilder ConvertTypeLibToAssembly(object typeLib, string asmFileName, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, Byte[] publicKey, System.Reflection.StrongNameKeyPair keyPair, string asmNamespace, Version asmVersion)
 {
     Contract.Requires(typeLib != null);
     Contract.Requires(asmFileName != null);
     Contract.Requires(notifySink != null);
     Contract.Requires(asmFileName.Length <= 260);
     Contract.Requires((int)((int)flags & 1) == 0 || publicKey != null || keyPair != null);
     return(default(System.Reflection.Emit.AssemblyBuilder));
 }
 public System.Reflection.Emit.AssemblyBuilder ConvertTypeLibToAssembly(Object typeLib, string asmFileName, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, byte[] publicKey, System.Reflection.StrongNameKeyPair keyPair, string asmNamespace, Version asmVersion)
 {
     return(default(System.Reflection.Emit.AssemblyBuilder));
 }
Esempio n. 15
0
 public string GenerateMetaData(string strSrcTypeLib, string outPath, byte[] PublicKey, System.Reflection.StrongNameKeyPair KeyPair)
 {
 }
Esempio n. 16
0
		public StrongNameKeyPair(System.IO.FileStream fs)
		{
			this.keyPair = new System.Reflection.StrongNameKeyPair(fs);
		}
Esempio n. 17
0
        void Rewrite(string file, string keyfile, IEnumerable <string> options)
        {
            // Specify assembly read and write parameters
            // We want to keep a valid symbols file (pdb or mdb)
            var read_params  = new ReaderParameters();
            var write_params = new WriterParameters();
            var pdb          = Path.ChangeExtension(file, "pdb");
            var mdb          = Path.ChangeExtension(file, "mdb");
            ISymbolReaderProvider provider = null;

            if (File.Exists(pdb))
            {
                provider = new Mono.Cecil.Pdb.PdbReaderProvider();
            }
            else if (File.Exists(mdb))
            {
                provider = new Mono.Cecil.Mdb.MdbReaderProvider();
            }
            read_params.SymbolReaderProvider = provider;
            read_params.ReadSymbols          = true;
            write_params.WriteSymbols        = true;

            if (!String.IsNullOrEmpty(keyfile) && File.Exists(keyfile))
            {
                keyfile = Path.GetFullPath(keyfile);
                var fs      = new FileStream(keyfile, FileMode.Open);
                var keypair = new System.Reflection.StrongNameKeyPair(fs);
                fs.Close();
                write_params.StrongNameKeyPair = keypair;
            }
            else
            {
                Console.Error.WriteLine("No keyfile specified or keyfile missing.");
            }

            // Load assembly and process all modules
            var assembly  = AssemblyDefinition.ReadAssembly(file, read_params);
            var rewritten = assembly.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == "RewrittenAttribute");

            if (rewritten == null)
            {
                foreach (var module in assembly.Modules)
                {
                    foreach (var reference in module.AssemblyReferences)
                    {
                        var resolved = module.AssemblyResolver.Resolve(reference);
                        if (reference.Name == "mscorlib")
                        {
                            mscorlib = resolved;
                        }
                    }
                }

                if (mscorlib == null)
                {
                    Console.Error.WriteLine("Failed to locate mscorlib");
                    return;
                }
                TypeMarshal       = mscorlib.MainModule.GetType("System.Runtime.InteropServices.Marshal");
                TypeStringBuilder = mscorlib.MainModule.GetType("System.Text.StringBuilder");
                TypeVoid          = mscorlib.MainModule.GetType("System.Void");
                TypeIntPtr        = mscorlib.MainModule.GetType("System.IntPtr");
                TypeInt32         = mscorlib.MainModule.GetType("System.Int32");

                TypeBindingsBase = assembly.Modules.Select(m => m.GetType("OpenTK.BindingsBase")).First();

                foreach (var module in assembly.Modules)
                {
                    foreach (var type in module.Types)
                    {
                        Rewrite(type, options);
                    }
                }
            }
            else
            {
                Console.Error.WriteLine("Error: assembly has already been rewritten");
            }

            // Save rewritten assembly
            assembly.Write(file, write_params);
        }
Esempio n. 18
0
        private static void InstrumentImpl(IRunExecutorHost host, RunStartParams rsp, Func <DocumentLocation, IEnumerable <DTestCase> > findTest)
        {
            var timeFilter      = rsp.StartTime;
            var solutionRoot    = Path.GetDirectoryName(rsp.Solution.Path.Item);
            var buildOutputRoot = rsp.Solution.BuildRoot.Item;

            Logger.LogInfo(
                "Instrumenting: Time filter - {0}, Build output root - {1}.",
                timeFilter.ToLocalTime(),
                buildOutputRoot);

            System.Reflection.StrongNameKeyPair snKeyPair = null;
            var snKeyFile = Directory.EnumerateFiles(solutionRoot, "*.snk").FirstOrDefault();

            if (snKeyFile != null)
            {
                snKeyPair = new System.Reflection.StrongNameKeyPair(File.ReadAllBytes(snKeyFile));
                Logger.LogInfo("Using strong name from {0}.", snKeyFile);
            }

            var asmResolver = new DefaultAssemblyResolver();

            Array.ForEach(asmResolver.GetSearchDirectories(), asmResolver.RemoveSearchDirectory);
            asmResolver.AddSearchDirectory(buildOutputRoot);
            var readerParams = new ReaderParameters
            {
                AssemblyResolver = asmResolver,
                ReadSymbols      = true,
            };

            string testRunnerPath = Path.GetFullPath(typeof(R4nd0mApps.TddStud10.TestRuntime.Marker).Assembly.Location);
            var    enterSPMD      = from t in ModuleDefinition.ReadModule(testRunnerPath).GetTypes()
                                    where t.Name == "Marker"
                                    from m in t.Methods
                                    where m.Name == "EnterSequencePoint"
                                    select m;

            var exitUTMD = from t in ModuleDefinition.ReadModule(testRunnerPath).GetTypes()
                           where t.Name == "Marker"
                           from m in t.Methods
                           where m.Name == "ExitUnitTest"
                           select m;

            Func <string, string> rebaseDocument = s => PathBuilder.rebaseCodeFilePath(rsp.Solution.Path, rsp.Solution.SnapshotPath, FilePath.NewFilePath(s)).Item;

            Engine.Engine.FindAndExecuteForEachAssembly(
                host,
                buildOutputRoot,
                timeFilter,
                (string assemblyPath) =>
            {
                Logger.LogInfo("Instrumenting {0}.", assemblyPath);

                var assembly = AssemblyDefinition.ReadAssembly(assemblyPath, readerParams);
                var hasSn    = assembly.Name.HasPublicKey;

                /*
                 * IL_0001: ldstr <assemblyId>
                 * IL_0006: ldstr <mdtoken>
                 * IL_000b: ldstr <spid>
                 * IL_000d: call void R4nd0mApps.TddStud10.TestHost.Marker::ExitUnitTest(string, ldstr, ldstr)
                 */
                MethodReference enterSPMR = assembly.MainModule.Import(enterSPMD.First());
                MethodReference exitUTMR  = assembly.MainModule.Import(exitUTMD.First());

                VisitAllTypes(
                    assembly.Modules,
                    (m, t) =>
                {
                    InstrumentType(rsp, findTest, assemblyPath, rebaseDocument, enterSPMR, exitUTMR, m, t);
                });

                var backupAssemblyPath = Path.ChangeExtension(assemblyPath, ".original");
                File.Delete(backupAssemblyPath);
                File.Move(assemblyPath, backupAssemblyPath);
                try
                {
                    assembly.Write(assemblyPath, new WriterParameters {
                        WriteSymbols = true, StrongNameKeyPair = hasSn ? snKeyPair : null
                    });
                }
                catch
                {
                    Logger.LogInfo("Backing up or instrumentation failed. Attempting to revert back changes to {0}.", assemblyPath);
                    File.Delete(assemblyPath);
                    File.Move(backupAssemblyPath, assemblyPath);
                    throw;
                }
            },
                1);
        }
Esempio n. 19
0
 public StrongNameKeyPair(string keyPairContainer)
 {
     this.keyPair = new System.Reflection.StrongNameKeyPair(keyPairContainer);
 }
Esempio n. 20
0
        private void Rewrite(string file, string keyfile, IEnumerable <string> options)
        {
            IEnumerable <string> optionsEnumerated = options as IList <string> ?? options.ToList();

            dllimport = optionsEnumerated.Contains("-dllimport");

            // Specify assembly read and write parameters
            // We want to keep a valid symbols file (pdb or mdb)
            var read_params  = new ReaderParameters();
            var write_params = new WriterParameters();

            read_params.ReadSymbols   = true;
            read_params.ReadWrite     = true;
            write_params.WriteSymbols = true;

            if (!String.IsNullOrEmpty(keyfile) && File.Exists(keyfile))
            {
                keyfile = Path.GetFullPath(keyfile);

                using (var fs = new FileStream(keyfile, FileMode.Open, FileAccess.Read))
                {
                    var keypair = new System.Reflection.StrongNameKeyPair(fs);
                    write_params.StrongNameKeyPair = keypair;
                }
            }
            else
            {
                Console.Error.WriteLine("No keyfile specified or keyfile missing.");
            }

            // Load assembly and process all modules
            try
            {
                using (AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(file, read_params))
                {
                    var rewritten = assembly.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == "RewrittenAttribute");
                    if (rewritten == null)
                    {
                        foreach (var module in assembly.Modules)
                        {
                            foreach (var reference in module.AssemblyReferences)
                            {
                                try
                                {
                                    var resolved = module.AssemblyResolver.Resolve(reference);
                                    if (reference.Name == "mscorlib")
                                    {
                                        mscorlib = resolved;
                                    }
                                }
                                catch (Exception e)
                                {
                                    Console.Error.WriteLine(e.ToString());
                                }
                            }
                        }

                        if (mscorlib == null)
                        {
                            Console.Error.WriteLine("Failed to locate mscorlib");
                            return;
                        }
                        TypeMarshal = mscorlib.MainModule.GetType("System.Runtime.InteropServices.Marshal");
                        TypeVoid    = mscorlib.MainModule.GetType("System.Void");
                        TypeIntPtr  = mscorlib.MainModule.GetType("System.IntPtr");
                        TypeInt32   = mscorlib.MainModule.GetType("System.Int32");

                        TypeBindingsBase = assembly.Modules.Select(m => m.GetType("OpenTK.BindingsBase")).First();

                        foreach (var module in assembly.Modules)
                        {
                            foreach (var type in module.Types)
                            {
                                Rewrite(type, optionsEnumerated);
                            }
                        }
                    }
                    else
                    {
                        Console.Error.WriteLine("Error: assembly has already been rewritten");
                    }

                    // Save rewritten assembly
                    assembly.Write(write_params);
                }
            }
            catch (InvalidOperationException inex)
            {
                Console.WriteLine("Failed to load the assembly. It may already have been rewritten, and the debug symbols no longer match.");
                Console.WriteLine(inex);
            }
        }
Esempio n. 21
0
 public StrongNameKeyPair(System.IO.FileStream fs)
 {
     this.keyPair = new System.Reflection.StrongNameKeyPair(fs);
 }
Esempio n. 22
0
        void Rewrite(string file, string keyfile, IEnumerable<string> options)
        {
            // Specify assembly read and write parameters
            // We want to keep a valid symbols file (pdb or mdb)
            var read_params = new ReaderParameters();
            var write_params = new WriterParameters();
            var pdb = Path.ChangeExtension(file, "pdb");
            var mdb = Path.ChangeExtension(file, "mdb");
            ISymbolReaderProvider provider = null;
            if (File.Exists(pdb))
            {
                provider = new Mono.Cecil.Pdb.PdbReaderProvider();
            }
            else if (File.Exists(mdb))
            {
                provider = new Mono.Cecil.Mdb.MdbReaderProvider();
            }
            read_params.SymbolReaderProvider = provider;
            read_params.ReadSymbols = true;
            write_params.WriteSymbols = true;

            if (!String.IsNullOrEmpty(keyfile) && File.Exists(keyfile))
            {
                keyfile = Path.GetFullPath(keyfile);
                var fs = new FileStream(keyfile, FileMode.Open);
                var keypair = new System.Reflection.StrongNameKeyPair(fs);
                fs.Close();
                write_params.StrongNameKeyPair = keypair;
            }
            else
            {
                Console.Error.WriteLine("No keyfile specified or keyfile missing.");
            }

            // Load assembly and process all modules
            var assembly = AssemblyDefinition.ReadAssembly(file, read_params);
            var rewritten = assembly.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == "RewrittenAttribute");
            if (rewritten == null)
            {
                foreach (var module in assembly.Modules)
                {
                    foreach (var reference in module.AssemblyReferences)
                    {
                        var resolved = module.AssemblyResolver.Resolve(reference);
                        if (reference.Name == "mscorlib")
                        {
                            mscorlib = resolved;
                        }
                    }
                }

                if (mscorlib == null)
                {
                    Console.Error.WriteLine("Failed to locate mscorlib");
                    return;
                }
                TypeMarshal = mscorlib.MainModule.GetType("System.Runtime.InteropServices.Marshal");
                TypeStringBuilder = mscorlib.MainModule.GetType("System.Text.StringBuilder");
                TypeVoid = mscorlib.MainModule.GetType("System.Void");
                TypeIntPtr = mscorlib.MainModule.GetType("System.IntPtr");
                TypeInt32 = mscorlib.MainModule.GetType("System.Int32");

                TypeBindingsBase = assembly.Modules.Select(m => m.GetType("OpenTK.BindingsBase")).First();

                foreach (var module in assembly.Modules)
                {
                    foreach (var type in module.Types)
                    {
                        Rewrite(type, options);
                    }
                }
            }
            else
            {
                Console.Error.WriteLine("Error: assembly has already been rewritten");
            }

            // Save rewritten assembly
            assembly.Write(file, write_params);
        }
Esempio n. 23
0
        private void Rewrite()
        {
            // Specify assembly read and write parameters
            // We want to keep a valid symbols file (pdb or mdb)
            var read_params  = new ReaderParameters();
            var write_params = new WriterParameters();

            var resolver = new OpenTKAssemblyResolver();

            read_params.AssemblyResolver = resolver;
            read_params.ReadSymbols      = true;
            read_params.ReadWrite        = true;
            write_params.WriteSymbols    = true;

            if (File.Exists(Options.TargetAssembly))
            {
                resolver.AddProbingPath(Path.GetDirectoryName(Options.TargetAssembly));
            }

            if (!String.IsNullOrEmpty(Options.StrongNameKey) && File.Exists(Options.StrongNameKey))
            {
                string absoluteKeyFilePath = Path.GetFullPath(Options.StrongNameKey);

                using (var fs = new FileStream(absoluteKeyFilePath, FileMode.Open, FileAccess.Read))
                {
                    var keypair = new System.Reflection.StrongNameKeyPair(fs);
                    write_params.StrongNameKeyPair = keypair;
                }
            }
            else
            {
                Console.Error.WriteLine("No keyfile specified or keyfile missing.");
            }

            // Load assembly and process all modules
            try
            {
                using (AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(Options.TargetAssembly, read_params))
                {
                    var rewritten = assembly.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == "RewrittenAttribute");
                    if (rewritten == null)
                    {
                        var corLib = new AssemblyNameReference("mscorlib", typeof(object).Assembly.GetName().Version);
                        mscorlib = assembly.MainModule.AssemblyResolver.Resolve(corLib);
                        if (mscorlib == null)
                        {
                            Console.Error.WriteLine("Failed to locate mscorlib");
                            return;
                        }
                        TypeMarshal = mscorlib.MainModule.GetType("System.Runtime.InteropServices.Marshal");
                        TypeVoid    = mscorlib.MainModule.GetType("System.Void");
                        TypeIntPtr  = mscorlib.MainModule.GetType("System.IntPtr");
                        TypeInt32   = mscorlib.MainModule.GetType("System.Int32");

                        TypeBindingsBase = assembly.Modules.Select(m => m.GetType("OpenTK.Graphics.BindingsBase")).First();

                        foreach (var module in assembly.Modules)
                        {
                            foreach (var type in module.Types)
                            {
                                Rewrite(type);
                            }
                        }
                    }
                    else
                    {
                        Console.Error.WriteLine("Error: assembly has already been rewritten");
                    }

                    // Save rewritten assembly
                    assembly.Write(write_params);
                }
            }
            catch (InvalidOperationException inex)
            {
                Console.WriteLine("Failed to load the assembly. It may already have been rewritten, and the debug symbols no longer match.");
                Console.WriteLine(inex);
            }
        }
        public static int Main(string[] args)
        {
            for (; null != args;)
            {
                try {
                    var fileName = args?[0];
                    if (null == fileName)
                    {
                        return((int)ExitStatus.UserCanceled);
                    }
                    var dirName       = Path.GetDirectoryName(fileName);
                    var fileNameShort = Path.GetFileNameWithoutExtension(fileName);
                    var fileNameExt   = Path.GetExtension(fileName);

                    var fileName_Original = Path.Combine(dirName, fileNameShort + fileNameExt);
                    var fileName_Modified = Path.Combine(dirName, fileNameShort + @".tmp");
                    var fileName_Backup   = Path.Combine(dirName, fileNameShort + @".bak");
                    var fullpath          = Path.GetFullPath(fileName_Original);
                    var rm = new ReaderParameters();
                    rm.InMemory = true;
                    var assembly = AssemblyDefinition.ReadAssembly(fileName_Original, rm);
                    var module   = assembly.MainModule;
                    var modified = 0;
                    {
                        var typeref = module.GetType(@"UltimateOrb.Cil.Verifiable.SizeOfModule/SizeOf_Typed`1", false);
                        if (typeref is TypeDefinition type)
                        {
                            var tp = type.GenericParameters?[0];
                            if (null != tp)
                            {
                                var collection = type.Methods;
                                foreach (var method in collection)
                                {
                                    if (@"get_Value" != method.Name)
                                    {
                                        continue;
                                    }
                                    if (!method.HasBody)
                                    {
                                        continue;
                                    }
                                    {
                                        var bd  = method.Body;
                                        var ins = bd.Instructions;
                                        if (2 > ins.Count)
                                        {
                                            continue;
                                        }
                                        var ilg  = (ILProcessor)null;
                                        var insa = ins.ToArray();
                                        for (var i = 1; insa.Length > i; ++i)
                                        {
                                            var in1 = insa[i];
                                            if (OpCodes.Throw != in1.OpCode)
                                            {
                                                continue;
                                            }
                                            var in0 = insa[i - 1];
                                            if (OpCodes.Ldnull != in0.OpCode)
                                            {
                                                continue;
                                            }
                                            ilg = bd.GetILProcessor();
                                            ilg.Replace(in0, ilg.Create(OpCodes.Sizeof, tp));
                                            ilg.Replace(in1, ilg.Create(OpCodes.Ret));
                                            ++modified;
                                        }
                                        if (null != ilg)
                                        {
                                            var ignored = 0;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (!UseStaticField)
                    {
                        var typeref = module.GetType(@"UltimateOrb.Cil.Verifiable.SizeOfModule", false);
                        if (typeref is TypeDefinition type)
                        {
                            var collection = type.Methods;
                            foreach (var method in collection)
                            {
                                if (@"SizeOf" != method.Name)
                                {
                                    continue;
                                }
                                var tp = method.GenericParameters?[0];
                                if (!method.HasBody)
                                {
                                    continue;
                                }
                                {
                                    var bd  = method.Body;
                                    var ins = bd.Instructions;
                                    var ilg = (ILProcessor)null;
                                    ilg = bd.GetILProcessor();
                                    var insa = ins.ToArray();
                                    for (var i = 0; insa.Length > i; ++i)
                                    {
                                        ilg.Remove(insa[i]);
                                    }
                                    {
                                        ilg.Append(ilg.Create(OpCodes.Sizeof, tp));
                                        ilg.Append(ilg.Create(OpCodes.Ret));
                                        ++modified;
                                    }
                                    if (null != ilg)
                                    {
                                        var ignored = 0;
                                    }
                                }
                            }
                        }
                    }
                    if (modified <= 0)
                    {
                        return((int)ExitStatus.RequestFailed);
                    }
                    Console.Out.WriteLine($@"Modified: {modified}.");
                    var sss = (System.Reflection.StrongNameKeyPair)null;
                    try {
                        var keyfile = args?[1];
                        if (null != keyfile)
                        {
                            sss = new System.Reflection.StrongNameKeyPair(File.ReadAllBytes(keyfile));
                        }
                    } catch (Exception) {
                    }

                    Console.Out.Write($@"Writing file: {fileName_Modified}... ");
                    var wp = new WriterParameters()
                    {
                    };
                    assembly.Write(fileName_Modified, wp);
                    Console.Out.WriteLine($@"Done.");
                    File.Replace(fileName_Modified, fileName_Original, fileName_Backup);
                    Console.Out.WriteLine($@"""{fileName_Original}"" -> ""{fileName_Backup}""");
                    Console.Out.WriteLine($@"""{fileName_Modified}"" -> ""{fileName_Original}""");
                    Console.Out.WriteLine(@"Done.");
                    return((int)ExitStatus.OK);
                } catch (Exception) {
                    return((int)ExitStatus.RequestFailed);
                }
                break;
            }
            return((int)ExitStatus.UserCanceled);
        }