예제 #1
0
		static Expression GenerateExpression(RandomGenerator random, Expression current, int currentDepth, int targetDepth) {
			if (currentDepth == targetDepth || (currentDepth > targetDepth / 3 && random.NextInt32(100) > 85))
				return current;

			switch ((ExpressionOps)random.NextInt32(6)) {
				case ExpressionOps.Add:
					return GenerateExpression(random, current, currentDepth + 1, targetDepth) +
					       GenerateExpression(random, (LiteralExpression)random.NextUInt32(), currentDepth + 1, targetDepth);

				case ExpressionOps.Sub:
					return GenerateExpression(random, current, currentDepth + 1, targetDepth) -
					       GenerateExpression(random, (LiteralExpression)random.NextUInt32(), currentDepth + 1, targetDepth);

				case ExpressionOps.Mul:
					return GenerateExpression(random, current, currentDepth + 1, targetDepth) * (LiteralExpression)(random.NextUInt32() | 1);

				case ExpressionOps.Xor:
					return GenerateExpression(random, current, currentDepth + 1, targetDepth) ^
					       GenerateExpression(random, (LiteralExpression)random.NextUInt32(), currentDepth + 1, targetDepth);

				case ExpressionOps.Not:
					return ~GenerateExpression(random, current, currentDepth + 1, targetDepth);

				case ExpressionOps.Neg:
					return -GenerateExpression(random, current, currentDepth + 1, targetDepth);
			}
			throw new UnreachableException();
		}
예제 #2
0
파일: Swap.cs 프로젝트: EmilZhou/ConfuserEx
		public override void Initialize(RandomGenerator random) {
			if (random.NextInt32(3) == 0)
				Mask = 0xffffffff;
			else
				Mask = random.NextUInt32();
			Key = random.NextUInt32() | 1;
		}
예제 #3
0
        public SharedFactory()
        {
            rndGenerator = new RandomGenerator();

            prefixes = new List<string>
            {
                "http",
                "https",
                "ftp",
                "ftps",
                "sftp",
            };

            suffixes = new List<string>
            {
                "com",
                "edu",
                "org",
                "ca",
                "de",
                "es",
                "fr",
                "it",
                "pl",
                "ir",
                "ro",
                "co.uk",
                "net"
            };
        }
        public int generateRandomNumber()
        {
            if (randomGenerator == null)
                randomGenerator = new RandomGenerator();

            return RandomNumber = randomGenerator.getRandomNumber();
        }
예제 #5
0
        public void TestCalculadora()
        {
            RandomGenerator r = new RandomGenerator();
            var persons = Builder<Person>.CreateListOfSize(tests * tests).
                    All().With(x => x.Age = r.Next(0, 100))
                         .And(x => x.Height = r.Next(90, 180))
                         .And(x => x.Weight = r.Next(10, 90))
                         .And(x => x.IsMan = r.Next())
                         .And(x => x.BMR = r.Next(100, 2000))
                         .And(x => x.Hip = r.Next(20, 60))
                         .And(x => x.Waist = r.Next(20, 60))
                         .And(x => x.Neck = r.Next(10, 30))
                         .Random(15).With(x => x.BMR = 0.0f)
                   .Build();
            foreach (Person p in persons)
            {
                Calculadora c = new Calculadora(p);
                int value = r.Next(-5, 7);
                if (value < 1 || value > 5)
                {
                    Assert.IsFalse(c.seleccionarCalculadora(value.ToString()));
                }
                else
                {
                    Assert.IsTrue(c.seleccionarCalculadora(value.ToString()));
                    if (value == 5)
                        Assert.IsFalse(c.estaActiva);
                }

            }
        }
        public void ShouldDecidePositively()
        {
            var generator = new RandomGenerator(() => 0.2);
            bool decision = generator.Decide(0.3);

            Assert.That(decision, Is.True);
        }
예제 #7
0
        static void Main(string[] args)
        {
            GuessGameEngine gameEngine = new GuessGameEngine();
            RandomGenerator ran = new RandomGenerator();
            ran.StartPoint = 50;
            ran.EndPoint = 100;
            gameEngine.randomGenerator = ran;
            gameEngine.startGame();

            Console.WriteLine("Enter number between 1 - 100");
            while (true)
            {
                int userInput = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine(gameEngine.verifyGuess(userInput));

                if (gameEngine.isGameEnded)
                {
                    Console.WriteLine("Do you want to continue?");
                    var vote = Console.ReadLine().ToString();

                    if (vote.ToLower() == "yes")
                    {
                        Console.WriteLine("Enter number between 1 - 100");
                        gameEngine.restart();
                    }
                    else
                        break;
                }
            }

            Console.ReadKey();
        }
예제 #8
0
		/// <summary>
		///     Initializes a new instance of the <see cref="APIStore" /> class.
		/// </summary>
		/// <param name="context">The working context.</param>
		public APIStore(ConfuserContext context) {
			this.context = context;
			random = context.Registry.GetService<IRandomService>().GetRandomGenerator("APIStore");

			dataStores = new SortedList<int, List<IDataStore>>();
			predicates = new List<IOpaquePredicateDescriptor>();
		}
        public void ShouldDecideNegatively()
        {
            var generator = new RandomGenerator(() => 0.9);
            bool decision = generator.Decide(0.3);

            Assert.That(decision, Is.False);
        }
예제 #10
0
		public CipherGenContext(RandomGenerator random, int dataVarCount) {
			this.random = random;
			Block = new StatementBlock(); // new LoopStatement() { Begin = 0, Limit = 4 };
			dataVars = new Variable[dataVarCount];
			for (int i = 0; i < dataVarCount; i++)
				dataVars[i] = new Variable("v" + i) { Tag = i };
		}
        public void ShouldGiveMiddleValue()
        {
            var generator = new RandomGenerator(() => 0.5);
            double value = generator.Value(3, 7);

            Assert.That(value, Is.InRange(5.0 - Delta, 5.0 + Delta));
        }
예제 #12
0
        /// <summary>
        /// Returns a random person from the test data set.
        /// </summary>
        /// <returns>A random person.</returns>
        public static Person NextPerson()
        {
            var generator = new RandomGenerator();

            var index = generator.NextValue(0, People.Count - 1);

            return People[index];
        }
예제 #13
0
		Tuple<int, int> GetKey(RandomGenerator random, MethodDef init) {
			Tuple<int, int> ret;
			if (!keys.TryGetValue(init, out ret)) {
				int key = random.NextInt32() | 1;
				keys[init] = ret = Tuple.Create(key, (int)MathsUtils.modInv((uint)key));
			}
			return ret;
		}
예제 #14
0
        /// <summary>
        /// Returns a random male from the test data set.
        /// </summary>
        /// <returns>A random male.</returns>
        public static Person NextMale()
        {
            var generator = new RandomGenerator();

            var index = generator.NextValue(0, Males.Count - 1);

            return Males[index];
        }
        public void IsSupportedThrowsExceptionWithNullTypeTest()
        {
            var target = new RandomGenerator();

            Action action = () => target.IsSupported(null);

            action.ShouldThrow<ArgumentNullException>();
        }
        public void NextValueThrowsExceptionWhenMinimumGreaterThanMaximumTest()
        {
            var target = new RandomGenerator();

            Action action = () => target.NextValue(1, 0);

            action.ShouldThrow<ArgumentOutOfRangeException>();
        }
        public void NextValueThrowsExceptionWithUnsupportedTypeTest()
        {
            var target = new RandomGenerator();

            Action action = () => target.NextValue('C', 'C');

            action.ShouldThrow<NotSupportedException>();
        }
예제 #18
0
 public static void CanGetRandomBool()
 {
     RandomGenerator r = new RandomGenerator(new Random().Next());
     bool[] values = new bool[10];
     for (int i = 0; i < 10; i++)
         values[i] = r.GetBool();
     Assert.That(values, Contains.Item(true));
     Assert.That(values, Contains.Item(false));
 }
        public void ShouldChooseItemRandomly()
        {
            int[] items = { 1, 2, 3 };
            
            var generator = new RandomGenerator(() => 0.4);
            int chosen = generator.Choose(items, 0.5, 1.0, 0.3);

            Assert.That(chosen, Is.EqualTo(2));
        }
예제 #20
0
        public static void RandomShortsAreUnique(short min, short max)
        {
            RandomGenerator r = new RandomGenerator(new Random().Next());
            short[] values = new short[10];
            for (int i = 0; i < 10; i++)
                values[i] = r.GetShort(min, max);

            UniqueValues.Check(values, 8); // Heuristic
        }
예제 #21
0
        public static void RandomBytesAreUnique(byte min, byte max)
        {
            RandomGenerator r = new RandomGenerator(new Random().Next());
            byte[] values = new byte[10];
            for (int i = 0; i < 10; i++)
                values[i] = r.GetByte(min, max);

            UniqueValues.Check(values, 8); // Heuristic
        }
        public void ShouldChooseLastItem()
        {
            int[] items = { 1, 2, 3 };

            var generator = new RandomGenerator(() => 0.99);
            int chosen = generator.Choose(items, 0.5, 1.0, 0.5);

            Assert.That(chosen, Is.EqualTo(3));
        }
예제 #23
0
        public static void RandomIntsAreUnique()
        {
            RandomGenerator r = new RandomGenerator(new Random().Next());
            int[] values = new int[10];
            for (int i = 0; i < 10; i++)
                values[i] = r.GetInt();

            UniqueValues.Check(values, 8); // Heuristic
        }
예제 #24
0
        public static RandomGenerator GetInstance()
        {
            if (Instance == null)
            {
                Instance = new RandomGenerator(0);
            }

            return RandomGenerator.Instance;
        }
        protected override void GivenThat()
        {
            var randomGenerator = new RandomGenerator();

            _expectedX = randomGenerator.Generate<int>();
            _expectedY = randomGenerator.Generate<int>();

            _startCells = Enumerable.Create(new Pair<int, int>(_expectedX, _expectedY), new Pair<int, int>(_expectedX - 1, _expectedY), new Pair<int, int>(_expectedX + 1, _expectedY));
        }
        public void RandomShortsAreUnique(short min, short max)
        {
            RandomGenerator r = new RandomGenerator(new Random().Next());
            short[] values = new short[10];
            for (int i = 0; i < 10; i++)
                values[i] = r.GetShort(min, max);

            Assert.That(values, Is.Unique);
        }
예제 #27
0
    void Start()
    {
        validSize = (timing.Length > variation.Length) ? variation.Length : timing.Length;

        generator = GetComponent<RandomGenerator>();

        // カウンター開始
        StartCoroutine("Counter");
    }
        public void RandomIntsAreUnique(int min, int max)
        {
           RandomGenerator r = new RandomGenerator(new Random().Next());
            int[] values = new int[10];
            for (int i = 0; i < 10; i++)
                values[i] = r.GetInt(min,max);

            Assert.That(values, Is.Unique);
        }
예제 #29
0
		public override void Initialize(RandomGenerator random) {
			InverseKey = mul(transpose4(GenerateUnimodularMatrix(random)), GenerateUnimodularMatrix(random));

			var cof = new uint[4, 4];
			for (int i = 0; i < 4; i++)
				for (int j = 0; j < 4; j++)
					cof[i, j] = cofactor4(InverseKey, i, j);
			Key = transpose4(cof);
		}
        public void RandomBytesAreUnique(byte min, byte max)
        {
            RandomGenerator r = new RandomGenerator(new Random().Next());
            byte[] values = new byte[10];
            for (int i = 0; i < 10; i++)
                values[i] = r.GetByte();

            Assert.That(values, Is.Unique);
        }
예제 #31
0
 public static SampleAppUrlPathData RandomSampleAppUrlPath() =>
 SampleAppUrlPaths.AllPaths[RandomGenerator.GetInstance().Next(0, SampleAppUrlPaths.AllPaths.Count)];
예제 #32
0
        public void HandleInject(AntiTamperProtection parent, ConfuserContext context, ProtectionParameters parameters)
        {
            this.context = context;
            random       = context.Registry.GetService <IRandomService>().GetRandomGenerator(parent.FullId);
            z            = random.NextUInt32();
            x            = random.NextUInt32();
            c            = random.NextUInt32();
            v            = random.NextUInt32();
            name1        = random.NextUInt32() & 0x7f7f7f7f;
            name2        = random.NextUInt32() & 0x7f7f7f7f;
            key          = random.NextUInt32();

            fieldLayout = new byte[6];
            for (var i = 0; i < 6; i++)
            {
                var index = random.NextInt32(0, 6);
                while (fieldLayout[index] != 0)
                {
                    index = random.NextInt32(0, 6);
                }

                fieldLayout[index] = (byte)i;
            }

            switch (parameters.GetParameter(context, context.CurrentModule, "key", Mode.Normal))
            {
            case Mode.Normal:
                deriver = new NormalDeriver();
                break;

            case Mode.Dynamic:
                deriver = new DynamicDeriver();
                break;

            default:
                throw new UnreachableException();
            }
            deriver.Init(context, random);

            var rt       = context.Registry.GetService <IRuntimeService>();
            var initType = rt.GetRuntimeType("Confuser.Runtime.AntiTamperJIT");
            var defs     = InjectHelper.Inject(initType, context.CurrentModule.GlobalType, context.CurrentModule);

            initMethod = defs.OfType <MethodDef>().Single(method => method.Name == "Initialize");

            initMethod.Body.SimplifyMacros(initMethod.Parameters);
            var instrs = initMethod.Body.Instructions.ToList();

            for (var i = 0; i < instrs.Count; i++)
            {
                var instr = instrs[i];
                if (instr.OpCode == OpCodes.Ldtoken)
                {
                    instr.Operand = context.CurrentModule.GlobalType;
                }
                else if (instr.OpCode == OpCodes.Call)
                {
                    var method = (IMethod)instr.Operand;
                    if (method.DeclaringType.Name == "Mutation" &&
                        method.Name == "Crypt")
                    {
                        var ldDst = instrs[i - 2];
                        var ldSrc = instrs[i - 1];
                        Debug.Assert(ldDst.OpCode == OpCodes.Ldloc && ldSrc.OpCode == OpCodes.Ldloc);
                        instrs.RemoveAt(i);
                        instrs.RemoveAt(i - 1);
                        instrs.RemoveAt(i - 2);
                        instrs.InsertRange(i - 2, deriver.EmitDerivation(initMethod, context, (Local)ldDst.Operand, (Local)ldSrc.Operand));
                    }
                }
            }
            initMethod.Body.Instructions.Clear();
            foreach (var instr in instrs)
            {
                initMethod.Body.Instructions.Add(instr);
            }

            MutationHelper.InjectKeys(initMethod,
                                      new[] { 0, 1, 2, 3, 4 },
                                      new[] { (int)(name1 * name2), (int)z, (int)x, (int)c, (int)v });

            var name   = context.Registry.GetService <INameService>();
            var marker = context.Registry.GetService <IMarkerService>();

            cctor = context.CurrentModule.GlobalType.FindStaticConstructor();

            cctorRepl = new MethodDefUser(name.RandomName(), MethodSig.CreateStatic(context.CurrentModule.CorLibTypes.Void))
            {
                IsStatic = true,
                Access   = MethodAttributes.CompilerControlled,
                Body     = new CilBody()
            };
            cctorRepl.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
            context.CurrentModule.GlobalType.Methods.Add(cctorRepl);
            name.MarkHelper(cctorRepl, marker, parent);

            MutationHelper.InjectKeys(defs.OfType <MethodDef>().Single(method => method.Name == "HookHandler"),
                                      new[] { 0 }, new[] { (int)key });
            foreach (var def in defs)
            {
                if (def.Name == "MethodData")
                {
                    var dataType = (TypeDef)def;
                    var fields   = dataType.Fields.ToArray();
                    var layout   = fieldLayout.Clone() as byte[];
                    Array.Sort(layout, fields);
                    for (byte j = 0; j < 6; j++)
                    {
                        layout[j] = j;
                    }

                    Array.Sort(fieldLayout, layout);
                    fieldLayout = layout;
                    dataType.Fields.Clear();
                    foreach (var f in fields)
                    {
                        dataType.Fields.Add(f);
                    }
                }
                name.MarkHelper(def, marker, parent);
                if (def is MethodDef)
                {
                    parent.ExcludeMethod(context, (MethodDef)def);
                }
            }
            parent.ExcludeMethod(context, cctor);
        }
예제 #33
0
 public int GetSeed()
 {
     return(RandomGenerator.GetCurrentSeed());
 }
예제 #34
0
 public IReadOnlyList <Sample> AllPlasmaProteinOntogenyFactorForStrictBiggerThanPMA(string parameterName, OriginData originData, RandomGenerator randomGenerator = null)
 {
     return(AllOntogenyFactorForStrictBiggerThanPMA(forMolecule(originData, SupportedProteins[parameterName]), originData, CoreConstants.Groups.ONTOGENY_PLASMA, randomGenerator));
 }
예제 #35
0
        public double OntogenyFactorFor(Ontogeny ontogeny, string containerName, double?age, double?gestationalAge, RandomGenerator randomGenerator)
        {
            var allOntogenies = AllValuesFor(ontogeny, containerName);

            if (!allOntogenies.Any())
            {
                return(CoreConstants.DEFAULT_ONTOGENY_FACTOR);
            }

            var factorRetriever = ontogenyFactorRetriever(randomGenerator, allOntogenies);

            return(_interpolation.Interpolate(allOntogenies.Select(x => new Sample(x.PostmenstrualAge, factorRetriever(x))), postmenstrualAgeInYearsFor(age, gestationalAge)));
        }
예제 #36
0
 private double getOrganVolumeForIndividual(IMuSigma muSigma, RandomGenerator randomGenerator)
 {
     return(muSigma.GenerateRandomValueForIndividual(randomGenerator));
 }
 public void RandomlyMoveItemsAscending() => CollectionTestHelpers.RandomlyMoveItems(l => l.ActiveOrderBy(o => o.Property), l => l.OrderBy(o => o.Property), () => new IntegerTestClass()
 {
     Property = RandomGenerator.GenerateRandomInteger()
 });
예제 #38
0
        /**
         * 生成随机串,随机串包含字母或数字
         * @return 随机串
         */
        public static string GenerateNonceStr()
        {
            RandomGenerator randomGenerator = new RandomGenerator();

            return(randomGenerator.GetRandomUInt().ToString());
        }
예제 #39
0
        private void TestTwoWithRandomOperations(Func <IActiveList <int>, IActiveList <int>, IActiveSet <int> > operation, Func <IReadOnlyList <int>, IReadOnlyList <int>, IEnumerable <int> > linqOperation)
        {
            RandomGenerator.ResetRandomGenerator();

            var list1 = new ObservableList <int>();

            foreach (var value in RandomGenerator.GenerateRandomIntegerList(100, 0, 50))
            {
                list1.Add(list1.Count, value);
            }

            var list2 = new ObservableList <int>();

            foreach (var value in RandomGenerator.GenerateRandomIntegerList(100, 0, 50))
            {
                list2.Add(list2.Count, value);
            }

            var set = operation.Invoke(list1, list2);

            IActiveValue <bool> sut;

            if (set is IActiveSetList <int> setList)
            {
                sut = setList.ActiveSetContains(25);
            }
            else
            {
                sut = (set as IActiveLookup <int, int>).ActiveSetContains(25);
            }

            foreach (var value in Enumerable.Range(0, 1000))
            {
                switch (list1.Count > 0 ? RandomGenerator.GenerateRandomInteger(0, 4) : 0)
                {
                case 0:
                    list1.Add(RandomGenerator.GenerateRandomInteger(0, list1.Count), RandomGenerator.GenerateRandomInteger(0, 50));
                    break;

                case 1:
                    list1.Remove(RandomGenerator.GenerateRandomInteger(0, list1.Count));
                    break;

                case 2:
                    list1.Replace(RandomGenerator.GenerateRandomInteger(0, list1.Count), RandomGenerator.GenerateRandomInteger(0, 50));
                    break;

                case 3:
                    list1.Move(RandomGenerator.GenerateRandomInteger(0, list1.Count), RandomGenerator.GenerateRandomInteger(0, list1.Count));
                    break;
                }
                switch (list2.Count > 0 ? RandomGenerator.GenerateRandomInteger(0, 4) : 0)
                {
                case 0:
                    list2.Add(RandomGenerator.GenerateRandomInteger(0, list2.Count), RandomGenerator.GenerateRandomInteger(0, 50));
                    break;

                case 1:
                    list2.Remove(RandomGenerator.GenerateRandomInteger(0, list2.Count));
                    break;

                case 2:
                    list2.Replace(RandomGenerator.GenerateRandomInteger(0, list2.Count), RandomGenerator.GenerateRandomInteger(0, 50));
                    break;

                case 3:
                    list2.Move(RandomGenerator.GenerateRandomInteger(0, list2.Count), RandomGenerator.GenerateRandomInteger(0, list2.Count));
                    break;
                }
                Assert.Equal(sut.Value, linqOperation.Invoke(list1, list2).Contains(25));
            }
        }
예제 #40
0
 public double PlasmaProteinOntogenyFactor(string protein, OriginData originData, RandomGenerator randomGenerator = null)
 {
     return(PlasmaProteinOntogenyFactor(protein, originData.Age, originData.GestationalAge, originData.Species.Name, randomGenerator));
 }
 public void RandomlyChangePropertyValuesDescending() => CollectionTestHelpers.RandomlyChangePropertyValues(l => l.ActiveOrderBy(o => o.Property, ListSortDirection.Descending), l => l.OrderByDescending(o => o.Property), () => new IntegerTestClass()
 {
     Property = RandomGenerator.GenerateRandomInteger()
 }, o => o.Property = RandomGenerator.GenerateRandomInteger());
 public void ResetWithRandomItemsDescending() => CollectionTestHelpers.ResetWithRandomItems(l => l.ActiveOrderBy(o => o.Property, ListSortDirection.Descending), l => l.OrderByDescending(o => o.Property), () => new IntegerTestClass()
 {
     Property = RandomGenerator.GenerateRandomInteger()
 });
 /// <summary>
 /// 初始化一个<see cref="ChineseAddressRandomizer"/>类型的实例
 /// </summary>
 /// <param name="options">地址配置</param>
 public ChineseAddressRandomizer(ChineseAddressFieldOptions options) : base(options)
 {
     _generator = new RandomGenerator();
 }
예제 #44
0
 public Sr25519Base(SchnorrkelSettings settings)
 {
     _rng = settings.RandomGenerator;
 }
예제 #45
0
 private void Picker_ValueChanged(object sender, NumberPicker.ValueChangeEventArgs e)
 {
     txtChoosNum.Text = RandomGenerator.GetLongNumber(e.NewVal);
 }
예제 #46
0
        public void HandleInject(AntiTamperProtection parent, ConfuserContext context, ProtectionParameters parameters)
        {
            random = context.Registry.GetService <IRandomService>().GetRandomGenerator(parent.FullId);
            z      = random.NextUInt32();
            x      = random.NextUInt32();
            c      = random.NextUInt32();
            v      = random.NextUInt32();
            name1  = random.NextUInt32() & 0x7f7f7f7f;
            name2  = random.NextUInt32() & 0x7f7f7f7f;

            switch (parameters.GetParameter(context, context.CurrentModule, "key", Mode.Normal))
            {
            case Mode.Normal:
                deriver = new NormalDeriver();
                break;

            case Mode.Dynamic:
                deriver = new DynamicDeriver();
                break;

            default:
                throw new UnreachableException();
            }
            deriver.Init(context, random);

            var     rt       = context.Registry.GetService <IRuntimeService>();
            TypeDef initType = rt.GetRuntimeType("Confuser.Runtime.AntiTamperNormal");
            IEnumerable <IDnlibDef> members = InjectHelper.Inject(initType, context.CurrentModule.GlobalType, context.CurrentModule);
            var initMethod = (MethodDef)members.Single(m => m.Name == "Initialize");

            initMethod.Body.SimplifyMacros(initMethod.Parameters);
            List <Instruction> instrs = initMethod.Body.Instructions.ToList();

            for (int i = 0; i < instrs.Count; i++)
            {
                Instruction instr = instrs[i];
                if (instr.OpCode == OpCodes.Ldtoken)
                {
                    instr.Operand = context.CurrentModule.GlobalType;
                }
                else if (instr.OpCode == OpCodes.Call)
                {
                    var method = (IMethod)instr.Operand;
                    if (method.DeclaringType.Name == "Mutation" &&
                        method.Name == "Crypt")
                    {
                        Instruction ldDst = instrs[i - 2];
                        Instruction ldSrc = instrs[i - 1];
                        Debug.Assert(ldDst.OpCode == OpCodes.Ldloc && ldSrc.OpCode == OpCodes.Ldloc);
                        instrs.RemoveAt(i);
                        instrs.RemoveAt(i - 1);
                        instrs.RemoveAt(i - 2);
                        instrs.InsertRange(i - 2, deriver.EmitDerivation(initMethod, context, (Local)ldDst.Operand, (Local)ldSrc.Operand));
                    }
                }
            }
            initMethod.Body.Instructions.Clear();
            foreach (Instruction instr in instrs)
            {
                initMethod.Body.Instructions.Add(instr);
            }

            MutationHelper.InjectKeys(initMethod,
                                      new[] { 0, 2, 4, 6, 8 },
                                      new[] { (int)(name1 * name2), (int)z, (int)x, (int)c, (int)v });

            var name   = context.Registry.GetService <INameService>();
            var marker = context.Registry.GetService <IMarkerService>();

            foreach (IDnlibDef def in members)
            {
                name.MarkHelper(def, marker, parent);
                if (def is MethodDef)
                {
                    parent.ExcludeMethod(context, (MethodDef)def);
                }
            }

            MethodDef cctor = context.CurrentModule.GlobalType.FindStaticConstructor();

            cctor.Body.Instructions.Insert(0, Instruction.Create(OpCodes.Call, initMethod));

            parent.ExcludeMethod(context, cctor);
        }
예제 #47
0
        public void Randomize(Individual individual, IParameter weightParameter, double?minWeight, double?maxWeight, IEnumerable <IParameter> allIndividualParameters, RandomGenerator randomGenerator)
        {
            _minWeight       = minWeight;
            _maxWeight       = maxWeight;
            _weightParameter = weightParameter;

            try
            {
                if (individual.IsAgeDependent)
                {
                    distributeParameterFor(individual, randomGenerator, randomizeAgeDependentVolumes);
                }
                else
                {
                    distributeParameterFor(individual, randomGenerator, randomizeWeightAndScaleVolumes);
                }

                randomizeDistributedParameterIn(individual, randomGenerator);
            }
            finally
            {
                _weightParameter = null;
            }
        }
 protected override void Context()
 {
     _randomGenerator = new RandomGenerator();
     sut = new UniformDistribution(10, 14);
 }
예제 #49
0
 private double getOrganVolumeForPopulation(IMuSigma muSigma, RandomGenerator randomGenerator)
 {
     return(muSigma.GenerateRandomValueForPopulation(randomGenerator));
 }
예제 #50
0
        public IReadOnlyList <Sample> AllOntogenyFactorForStrictBiggerThanPMA(Ontogeny ontogeny, OriginData originData, string containerName, RandomGenerator randomGenerator = null)
        {
            Start();

            if (ontogeny.IsUndefined())
            {
                return(new List <Sample>());
            }

            var pma       = postmenstrualAgeInYearsFor(originData);
            var gaInYears = inYears(originData.GestationalAge.GetValueOrDefault(CoreConstants.NOT_PRETERM_GESTATIONAL_AGE_IN_WEEKS));

            var ontogenies = AllValuesFor(ontogeny, containerName).Where(x => x.PostmenstrualAge > pma).ToList();

            if (!ontogenies.Any())
            {
                return(new List <Sample>());
            }

            var factorRetriever = ontogenyFactorRetriever(randomGenerator, ontogenies);

            return(ontogenies.Select(x => new Sample(x.PostmenstrualAge - gaInYears, factorRetriever(x))).ToList());
        }
예제 #51
0
 public double OntogenyFactorFor(Ontogeny ontogeny, string containerName, OriginData originData, RandomGenerator randomGenerator = null)
 {
     return(OntogenyFactorFor(ontogeny, containerName, originData.Age, originData.GestationalAge, randomGenerator));
 }
예제 #52
0
 public override void Initialize(RandomGenerator random)
 {
     Operation = (CryptoBinOps)random.NextInt32(3);
 }
예제 #53
0
        public Span(
            string name,
            string type,
            string parentId,
            string traceId,
            Transaction enclosingTransaction,
            IPayloadSender payloadSender,
            IApmLogger logger,
            ICurrentExecutionSegmentsContainer currentExecutionSegmentsContainer,
            IApmServerInfo apmServerInfo,
            Span parentSpan = null,
            InstrumentationFlag instrumentationFlag = InstrumentationFlag.None,
            bool captureStackTraceOnStart           = false
            )
        {
            InstrumentationFlag = instrumentationFlag;
            Timestamp           = TimeUtils.TimestampNow();
            Id      = RandomGenerator.GenerateRandomBytesAsString(new byte[8]);
            _logger = logger?.Scoped($"{nameof(Span)}.{Id}");

            _payloadSender = payloadSender;
            _currentExecutionSegmentsContainer = currentExecutionSegmentsContainer;
            _parentSpan           = parentSpan;
            _enclosingTransaction = enclosingTransaction;
            _apmServerInfo        = apmServerInfo;
            Name = name;
            Type = type;

            ParentId = parentId;
            TraceId  = traceId;

            if (IsSampled)
            {
                SampleRate = enclosingTransaction.SampleRate;
                // Started and dropped spans should be counted only for sampled transactions
                if (enclosingTransaction.SpanCount.IncrementTotal() > ConfigSnapshot.TransactionMaxSpans &&
                    ConfigSnapshot.TransactionMaxSpans >= 0)
                {
                    _isDropped = true;
                    enclosingTransaction.SpanCount.IncrementDropped();
                }
                else
                {
                    enclosingTransaction.SpanCount.IncrementStarted();

                    // In some cases capturing the stacktrace in End() results in a stack trace which is not very useful.
                    // In such cases we capture the stacktrace on span start.
                    // These are typically async calls - e.g. capturing stacktrace for outgoing HTTP requests in the
                    // System.Net.Http.HttpRequestOut.Stop
                    // diagnostic source event produces a stack trace that does not contain the caller method in user code - therefore we
                    // capture the stacktrace is .Start
                    if (captureStackTraceOnStart && ConfigSnapshot.StackTraceLimit != 0 && ConfigSnapshot.SpanFramesMinDurationInMilliseconds != 0)
                    {
                        RawStackTrace = new StackTrace(true);
                    }
                }
            }
            else
            {
                SampleRate = 0;
            }

            _currentExecutionSegmentsContainer.CurrentSpan = this;

            _logger.Trace()
            ?.Log("New Span instance created: {Span}. Start time: {Time} (as timestamp: {Timestamp}). Parent span: {Span}",
                  this, TimeUtils.FormatTimestampForLog(Timestamp), Timestamp, _parentSpan);
        }
예제 #54
0
 public void SetSeed(int seed)
 {
     RandomGenerator.ResetSeed(seed);
 }
예제 #55
0
        public double PlasmaProteinOntogenyFactor(string protein, double?age, double?gestationalAge, string species, RandomGenerator randomGenerator)
        {
            var ontogeny = allFor(species).FindByName(protein) ?? new NullOntogeny();

            return(OntogenyFactorFor(ontogeny, CoreConstants.Groups.ONTOGENY_PLASMA, age, gestationalAge, randomGenerator));
        }
예제 #56
0
        /// <summary>
        /// Returns a random number from the distribution; bypasses the internal state.
        /// </summary>
        public double NextDouble(double alpha, double lambda)
        {
            /// <summary>****************************************************************
            ///                                                               ///
            ///    Gamma Distribution - Acceptance Rejection combined with    ///
            ///                         Acceptance Complement                 ///
            ///                                                               ///
            ///*****************************************************************
            ///                                                               ///
            /// FUNCTION:    - gds samples a random number from the standard  ///
            ///                gamma distribution with parameter  a > 0d      ///
            ///                Acceptance Rejection  gs  for  a < 1 ,         ///
            ///                Acceptance Complement gd  for  a >= 1 d        ///
            /// REFERENCES:  - J.Hd Ahrens, Ud Dieter (1974): Computer methods///
            ///                for sampling from gamma, beta, Poisson and     ///
            ///                binomial distributions, Computing 12, 223-246d ///
            ///              - J.Hd Ahrens, Ud Dieter (1982): Generating gamma///
            ///                variates by a modified rejection technique,    ///
            ///                Communications of the ACM 25, 47-54d           ///
            /// SUBPROGRAMS: - drand(seed) ..d (0,1)-Uniform generator with   ///
            ///                unsigned long int///seed                    ///
            ///              - NORMAL(seed) ..d Normal generator N(0,1)d      ///
            ///                                                               ///
            ///****************************************************************/// </summary>
            double a = alpha;
            double aa = -1.0, aaa = -1.0,
                   b = 0.0, c = 0.0, d = 0.0, e, r, s = 0.0, si = 0.0, ss = 0.0, q0 = 0.0,
                   q1 = 0.0416666664, q2 = 0.0208333723, q3 = 0.0079849875,
                   q4 = 0.0015746717, q5 = -0.0003349403, q6 = 0.0003340332,
                   q7 = 0.0006053049, q8 = -0.0004701849, q9 = 0.0001710320,
                   a1 = 0.333333333, a2 = -0.249999949, a3 = 0.199999867,
                   a4 = -0.166677482, a5 = 0.142873973, a6 = -0.124385581,
                   a7 = 0.110368310, a8 = -0.112750886, a9 = 0.104089866,
                   e1 = 1.000000000, e2 = 0.499999994, e3 = 0.166666848,
                   e4 = 0.041664508, e5 = 0.008345522, e6 = 0.001353826,
                   e7 = 0.000247453;

            double gds, p, q, t, sign_u, u, v, w, x;
            double v1, v2, v12;

            // Check for invalid input values

            if (a <= 0.0)
            {
                throw new ArgumentException();
            }
            if (lambda <= 0.0)
            {
                new ArgumentException();
            }

            if (a < 1.0)
            {                                // CASE A: Acceptance rejection algorithm gs
                b = 1.0 + 0.36788794412 * a; // Step 1
                for (; ;)
                {
                    p = b * RandomGenerator.Raw();
                    if (p <= 1.0)
                    {                       // Step 2d Case gds <= 1
                        gds = System.Math.Exp(System.Math.Log(p) / a);
                        if (System.Math.Log(RandomGenerator.Raw()) <= -gds)
                        {
                            return(gds / lambda);
                        }
                    }
                    else
                    {                                // Step 3d Case gds > 1
                        gds = -System.Math.Log((b - p) / a);
                        if (System.Math.Log(RandomGenerator.Raw()) <= ((a - 1.0) * System.Math.Log(gds)))
                        {
                            return(gds / lambda);
                        }
                    }
                }
            }

            else
            {        // CASE B: Acceptance complement algorithm gd (gaussian distribution, box muller transformation)
                if (a != aa)
                {    // Step 1d Preparations
                    aa = a;
                    ss = a - 0.5;
                    s  = System.Math.Sqrt(ss);
                    d  = 5.656854249 - 12.0 * s;
                }
                // Step 2d Normal deviate
                do
                {
                    v1  = 2.0 * RandomGenerator.Raw() - 1.0;
                    v2  = 2.0 * RandomGenerator.Raw() - 1.0;
                    v12 = v1 * v1 + v2 * v2;
                } while (v12 > 1.0);
                t   = v1 * System.Math.Sqrt(-2.0 * System.Math.Log(v12) / v12);
                x   = s + 0.5 * t;
                gds = x * x;
                if (t >= 0.0)
                {
                    return(gds / lambda);                 // Immediate acceptance
                }
                u = RandomGenerator.Raw();                // Step 3d Uniform random number
                if (d * u <= t * t * t)
                {
                    return(gds / lambda);                      // Squeeze acceptance
                }
                if (a != aaa)
                {                           // Step 4d Set-up for hat case
                    aaa = a;
                    r   = 1.0 / a;
                    q0  = ((((((((q9 * r + q8) * r + q7) * r + q6) * r + q5) * r + q4) *
                             r + q3) * r + q2) * r + q1) * r;
                    if (a > 3.686)
                    {
                        if (a > 13.022)
                        {
                            b  = 1.77;
                            si = 0.75;
                            c  = 0.1515 / s;
                        }
                        else
                        {
                            b  = 1.654 + 0.0076 * ss;
                            si = 1.68 / s + 0.275;
                            c  = 0.062 / s + 0.024;
                        }
                    }
                    else
                    {
                        b  = 0.463 + s - 0.178 * ss;
                        si = 1.235;
                        c  = 0.195 / s - 0.079 + 0.016 * s;
                    }
                }
                if (x > 0.0)
                {                        // Step 5d Calculation of q
                    v = t / (s + s);     // Step 6.
                    if (System.Math.Abs(v) > 0.25)
                    {
                        q = q0 - s * t + 0.25 * t * t + (ss + ss) * System.Math.Log(1.0 + v);
                    }
                    else
                    {
                        q = q0 + 0.5 * t * t * ((((((((a9 * v + a8) * v + a7) * v + a6) *
                                                    v + a5) * v + a4) * v + a3) * v + a2) * v + a1) * v;
                    }                                 // Step 7d Quotient acceptance
                    if (System.Math.Log(1.0 - u) <= q)
                    {
                        return(gds / lambda);
                    }
                }

                for (; ;)
                {                             // Step 8d Double exponential deviate t
                    do
                    {
                        e      = -System.Math.Log(RandomGenerator.Raw());
                        u      = RandomGenerator.Raw();
                        u      = u + u - 1.0;
                        sign_u = (u > 0) ? 1.0 : -1.0;
                        t      = b + (e * si) * sign_u;
                    } while (t <= -0.71874483771719); // Step 9d Rejection of t
                    v = t / (s + s);                  // Step 10d New q(t)
                    if (System.Math.Abs(v) > 0.25)
                    {
                        q = q0 - s * t + 0.25 * t * t + (ss + ss) * System.Math.Log(1.0 + v);
                    }
                    else
                    {
                        q = q0 + 0.5 * t * t * ((((((((a9 * v + a8) * v + a7) * v + a6) *
                                                    v + a5) * v + a4) * v + a3) * v + a2) * v + a1) * v;
                    }
                    if (q <= 0.0)
                    {
                        continue;                     // Step 11.
                    }
                    if (q > 0.5)
                    {
                        w = System.Math.Exp(q) - 1.0;
                    }
                    else
                    {
                        w = ((((((e7 * q + e6) * q + e5) * q + e4) * q + e3) * q + e2) *
                             q + e1) * q;
                    }                                 // Step 12d Hat acceptance
                    if (c * u * sign_u <= w * System.Math.Exp(e - 0.5 * t * t))
                    {
                        x = s + 0.5 * t;
                        return(x * x / lambda);
                    }
                }
            }
        }
예제 #57
0
        //private int _powerLevel;


        public Laptop(UdpServer model, Player player, Position position, int laptopLenght)
        {
            _timeLeft        = 30;
            _position        = position;
            _affectedFields  = new List <Int32>();
            _toDrop          = new List <int>();
            _owner           = player;
            _randomGenerator = new RandomGenerator();
            Remove           = false;

            var positions       = new List <Position>();
            var toDropPositions = new List <Position>();

            positions.Add(_position);

            bool lockedRight = false;
            bool lockedLeft  = false;
            bool lockedUp    = false;
            bool lockedDown  = false;



            for (int i = 0; i <= laptopLenght; i++)
            {
                Position newPosition = position;

                if (position.Column + i < UdpServer.NumberOfColumns)
                {
                    newPosition = new Position {
                        Column = _position.Column + i, Row = _position.Row
                    };
                    if (model.GameBoard[newPosition.FieldIndex()].Type != FieldType.unbreakable && lockedRight == false)
                    {
                        positions.Add(newPosition);
                        if (model.GameBoard[newPosition.FieldIndex()].Type == FieldType.firewall)
                        {
                            toDropPositions.Add(newPosition);
                            lockedRight = true;
                        }
                    }
                    else
                    {
                        lockedRight = true;
                    }
                }

                if (position.Column - i >= 0)
                {
                    newPosition = new Position {
                        Column = _position.Column - i, Row = _position.Row
                    };
                    if (model.GameBoard[newPosition.FieldIndex()].Type != FieldType.unbreakable && lockedLeft != true)
                    {
                        positions.Add(newPosition);
                        if (model.GameBoard[newPosition.FieldIndex()].Type == FieldType.firewall)
                        {
                            toDropPositions.Add(newPosition);
                            lockedLeft = true;
                        }
                    }
                    else
                    {
                        lockedLeft = true;
                    }
                }

                if (position.Row + i < UdpServer.NumberOfRows)
                {
                    newPosition = new Position {
                        Column = _position.Column, Row = _position.Row + i
                    };
                    if (model.GameBoard[newPosition.FieldIndex()].Type != FieldType.unbreakable && lockedDown == false)
                    {
                        positions.Add(newPosition);
                        if (model.GameBoard[newPosition.FieldIndex()].Type == FieldType.firewall)
                        {
                            toDropPositions.Add(newPosition);
                            lockedDown = true;
                        }
                    }
                    else
                    {
                        lockedDown = true;
                    }
                }

                if (position.Row - i >= 0)
                {
                    newPosition = new Position {
                        Column = _position.Column, Row = _position.Row - i
                    };
                    if (model.GameBoard[newPosition.FieldIndex()].Type != FieldType.unbreakable && lockedUp == false)
                    {
                        positions.Add(newPosition);
                        if (model.GameBoard[newPosition.FieldIndex()].Type == FieldType.firewall)
                        {
                            toDropPositions.Add(newPosition);
                            lockedUp = true;
                        }
                    }
                    else
                    {
                        lockedUp = true;
                    }
                }
            }

            foreach (var p in positions)
            {
                _affectedFields.Add(p.FieldIndex());
            }

            foreach (var tdp in toDropPositions)
            {
                if (_randomGenerator.DropOrNotDrop())
                {
                    _toDrop.Add(tdp.FieldIndex());
                }
            }
        }
예제 #58
0
        private int ApplyPackageDD(string filePath, int phraseLen, bool removeSus, string rampPath, string cfgPath, out string consoleOutput, bool overWrite = false, bool keepLog = false)
        {
            int            result = 0; // Ends normally with no error
            DLCPackageData packageData;

            consoleOutput = String.Empty;

            try
            {
                using (var psarcOld = new PsarcPackager())
                    packageData = psarcOld.ReadPackage(filePath);
            }
            catch (Exception ex)
            {
                consoleOutput = "Error Reading : " + filePath + Environment.NewLine + ex.Message;
                return(-1); // Read Error
            }

            var ddcFilePath = GenerateDdcFilePath(filePath);

            // Update arrangement song info
            foreach (Arrangement arr in packageData.Arrangements)
            {
                if (chkGenArrIds.Checked)
                {
                    // generate new AggregateGraph
                    arr.SongFile = new RocksmithToolkitLib.DLCPackage.AggregateGraph.SongFile()
                    {
                        File = ""
                    };

                    // generate new Arrangement IDs
                    arr.Id       = IdGenerator.Guid();
                    arr.MasterId = RandomGenerator.NextInt();
                }

                // skip vocal and showlight arrangements
                if (arr.ArrangementType == ArrangementType.Vocal || arr.ArrangementType == ArrangementType.ShowLight)
                {
                    continue;
                }

                // validate existing SongInfo
                var songXml = Song2014.LoadFromFile(arr.SongXml.File);
                songXml.AlbumYear      = packageData.SongInfo.SongYear.ToString().GetValidYear();
                songXml.ArtistName     = packageData.SongInfo.Artist.GetValidAtaSpaceName();
                songXml.Title          = packageData.SongInfo.SongDisplayName.GetValidAtaSpaceName();
                songXml.AlbumName      = packageData.SongInfo.Album.GetValidAtaSpaceName();
                songXml.ArtistNameSort = packageData.SongInfo.ArtistSort.GetValidSortableName();
                songXml.SongNameSort   = packageData.SongInfo.SongDisplayNameSort.GetValidSortableName();
                songXml.AlbumNameSort  = packageData.SongInfo.AlbumSort.GetValidSortableName();
                songXml.AverageTempo   = Convert.ToSingle(packageData.SongInfo.AverageTempo.ToString().GetValidTempo());

                // write updated xml arrangement
                using (var stream = File.Open(arr.SongXml.File, FileMode.Create))
                    songXml.Serialize(stream, false);

                // restore arrangment comments
                Song2014.WriteXmlComments(arr.SongXml.File, arr.XmlComments);

                // apply DD to xml arrangments... 0 = Ends normally with no error
                result = ApplyDD(arr.SongXml.File, phraseLen, removeSus, rampPath, cfgPath, out consoleOutput, true, keepLog);
                if (result == 1) // Ends with system error
                {
                    consoleOutput = "DDC System Error: " + Environment.NewLine +
                                    "Arrangment file: " + Path.GetFileName(arr.SongXml.File) + Environment.NewLine +
                                    "CDLC file: " + filePath;
                    return(result);
                }

                if (result == 2) // Ends with application error
                {
                    consoleOutput = "DDC Application Error: " + Environment.NewLine +
                                    "Arrangment file: " + Path.GetFileName(arr.SongXml.File) + Environment.NewLine +
                                    "CDLC file: " + filePath;
                    return(result);
                }

                if (keepLog)
                {
                    var unpackedDir = Path.GetDirectoryName(Path.GetDirectoryName(arr.SongXml.File));
                    var logFiles    = Directory.EnumerateFiles(unpackedDir, "*.log", SearchOption.AllDirectories);
                    var clogDir     = Path.Combine(Path.GetDirectoryName(ddcFilePath), "DDC_Log");
                    var plogDir     = Path.Combine(clogDir, Path.GetFileNameWithoutExtension(ddcFilePath).StripPlatformEndName().Replace("_DD", "").Replace("_NDD", ""));

                    if (!Directory.Exists(clogDir))
                    {
                        Directory.CreateDirectory(clogDir);
                    }

                    DirectoryExtension.SafeDelete(plogDir);
                    Directory.CreateDirectory(plogDir);

                    foreach (var logFile in logFiles)
                    {
                        File.Copy(logFile, Path.Combine(plogDir, Path.GetFileName(logFile)));
                    }
                }

                // put arrangment comments in correct order
                Song2014.WriteXmlComments(arr.SongXml.File);
            }

            if (chkGenArrIds.Checked)
            {
                // add comment to ToolkitInfo to identify CDLC
                var arrIdComment = packageData.PackageComment;
                if (String.IsNullOrEmpty(arrIdComment))
                {
                    arrIdComment = TKI_ARRID;
                }
                else if (!arrIdComment.Contains(TKI_ARRID))
                {
                    arrIdComment = arrIdComment + " " + TKI_ARRID;
                }

                packageData.PackageComment = arrIdComment;
            }

            // add comment to ToolkitInfo to identify CDLC
            var remasterComment = packageData.PackageComment;

            if (String.IsNullOrEmpty(remasterComment))
            {
                remasterComment = TKI_REMASTER;
            }
            else if (!remasterComment.Contains(TKI_REMASTER))
            {
                remasterComment = remasterComment + " " + TKI_REMASTER;
            }

            packageData.PackageComment = remasterComment;

            // add default package version if missing
            if (String.IsNullOrEmpty(packageData.PackageVersion))
            {
                packageData.PackageVersion = "1";
            }
            else
            {
                packageData.PackageVersion = packageData.PackageVersion.GetValidVersion();
            }

            // validate packageData (important)
            packageData.Name = packageData.Name.GetValidKey(); // DLC Key

            try
            {
                // let's not bug user with this ... they should know what they are doing, right?
                //if (File.Exists(ddcFilePath) && !overWrite)
                //    if (MessageBox.Show("Are you sure to overwrite file? " + Path.GetFileName(ddcFilePath), MESSAGEBOX_CAPTION, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                //        return result;

                // regenerates the SNG with the repair and repackages
                using (var psarcNew = new PsarcPackager(true))
                    psarcNew.WritePackage(ddcFilePath, packageData, filePath);
            }
            catch (Exception ex)
            {
                consoleOutput = "Error Writing: " + filePath + Environment.NewLine + ex.Message;
                result        = -2; // Write Error
            }

            return(result);
        }
예제 #59
0
        private void PackModules(ConfuserContext context, CompressorContext compCtx, ModuleDef stubModule, ICompressionService comp, RandomGenerator random)
        {
            var maxLen  = 0;
            var modules = new Dictionary <string, byte[]>();

            for (var i = 0; i < context.OutputModules.Count; i++)
            {
                if (i == compCtx.ModuleIndex)
                {
                    continue;
                }

                var id = GetId(context.Modules[i].Assembly);
                modules.Add(id, context.OutputModules[i]);

                var strLen = Encoding.UTF8.GetByteCount(id);
                if (strLen > maxLen)
                {
                    maxLen = strLen;
                }
            }
            foreach (var extModule in context.ExternalModules)
            {
                var name = GetId(extModule).ToUpperInvariant();
                modules.Add(name, extModule);

                var strLen = Encoding.UTF8.GetByteCount(name);
                if (strLen > maxLen)
                {
                    maxLen = strLen;
                }
            }

            var key = random.NextBytes(4 + maxLen);

            key[0] = (byte)(compCtx.EntryPointToken >> 0);
            key[1] = (byte)(compCtx.EntryPointToken >> 8);
            key[2] = (byte)(compCtx.EntryPointToken >> 16);
            key[3] = (byte)(compCtx.EntryPointToken >> 24);
            for (var i = 4; i < key.Length; i++) // no zero bytes
            {
                key[i] |= 1;
            }
            compCtx.KeySig = key;

            var moduleIndex = 0;

            foreach (var entry in modules)
            {
                var name = Encoding.UTF8.GetBytes(entry.Key);
                for (var i = 0; i < name.Length; i++)
                {
                    name[i] *= key[i + 4];
                }

                uint state = 0x6fff61;
                foreach (var chr in name)
                {
                    state = state * 0x5e3f1f + chr;
                }
                var encrypted = compCtx.Encrypt(comp, entry.Value, state, progress =>
                {
                    progress = (progress + moduleIndex) / modules.Count;
                    context.Logger.Progress((int)(progress * 10000), 10000);
                });
                context.CheckCancellation();

                var resource = new EmbeddedResource(Convert.ToBase64String(name), encrypted, ManifestResourceAttributes.Private);
                stubModule.Resources.Add(resource);
                moduleIndex++;
            }
            context.Logger.EndProgress();
        }
예제 #60
0
        void InjectStub(DotProtectContext context, CompressorContext compCtx, ProtectionParameters parameters, ModuleDef stubModule)
        {
            var             rt     = context.Registry.GetService <IRuntimeService>();
            RandomGenerator random = context.Registry.GetService <IRandomService>().GetRandomGenerator(Id);
            var             comp   = context.Registry.GetService <ICompressionService>();

            var rtType = rt.GetRuntimeType(compCtx.CompatMode ? "DotProtect.Runtime.CompressorCompat" : "DotProtect.Runtime.Compressor");
            IEnumerable <IDnlibDef> defs = InjectHelper.Inject(rtType, stubModule.GlobalType, stubModule);

            switch (parameters.GetParameter(context, context.CurrentModule, "key", Mode.Normal))
            {
            case Mode.Normal:
                compCtx.Deriver = new NormalDeriver();
                break;

            case Mode.Dynamic:
                compCtx.Deriver = new DynamicDeriver();
                break;

            default:
                throw new UnreachableException();
            }
            compCtx.Deriver.Init(context, random);

            context.Logger.Debug("Encrypting modules...");

            // Main
            MethodDef entryPoint = defs.OfType <MethodDef>().Single(method => method.Name == "Main");

            stubModule.EntryPoint = entryPoint;

            if (compCtx.EntryPoint.HasAttribute("System.STAThreadAttribute"))
            {
                var attrType = stubModule.CorLibTypes.GetTypeRef("System", "STAThreadAttribute");
                var ctorSig  = MethodSig.CreateInstance(stubModule.CorLibTypes.Void);
                entryPoint.CustomAttributes.Add(new CustomAttribute(
                                                    new MemberRefUser(stubModule, ".ctor", ctorSig, attrType)));
            }
            else if (compCtx.EntryPoint.HasAttribute("System.MTAThreadAttribute"))
            {
                var attrType = stubModule.CorLibTypes.GetTypeRef("System", "MTAThreadAttribute");
                var ctorSig  = MethodSig.CreateInstance(stubModule.CorLibTypes.Void);
                entryPoint.CustomAttributes.Add(new CustomAttribute(
                                                    new MemberRefUser(stubModule, ".ctor", ctorSig, attrType)));
            }

            uint seed = random.NextUInt32();

            compCtx.OriginModule = context.OutputModules[compCtx.ModuleIndex];

            byte[] encryptedModule = compCtx.Encrypt(comp, compCtx.OriginModule, seed,
                                                     progress => context.Logger.Progress((int)(progress * 10000), 10000));
            context.Logger.EndProgress();
            context.CheckCancellation();

            compCtx.EncryptedModule = encryptedModule;

            MutationHelper.InjectKeys(entryPoint,
                                      new[] { 0, 1 },
                                      new[] { encryptedModule.Length >> 2, (int)seed });
            InjectData(stubModule, entryPoint, encryptedModule);

            // Decrypt
            MethodDef decrypter = defs.OfType <MethodDef>().Single(method => method.Name == "Decrypt");

            decrypter.Body.SimplifyMacros(decrypter.Parameters);
            List <Instruction> instrs = decrypter.Body.Instructions.ToList();

            for (int i = 0; i < instrs.Count; i++)
            {
                Instruction instr = instrs[i];
                if (instr.OpCode == OpCodes.Call)
                {
                    var method = (IMethod)instr.Operand;
                    if (method.DeclaringType.Name == "Mutation" &&
                        method.Name == "Crypt")
                    {
                        Instruction ldDst = instrs[i - 2];
                        Instruction ldSrc = instrs[i - 1];
                        Debug.Assert(ldDst.OpCode == OpCodes.Ldloc && ldSrc.OpCode == OpCodes.Ldloc);
                        instrs.RemoveAt(i);
                        instrs.RemoveAt(i - 1);
                        instrs.RemoveAt(i - 2);
                        instrs.InsertRange(i - 2, compCtx.Deriver.EmitDerivation(decrypter, context, (Local)ldDst.Operand, (Local)ldSrc.Operand));
                    }
                    else if (method.DeclaringType.Name == "Lzma" &&
                             method.Name == "Decompress")
                    {
                        MethodDef decomp = comp.GetRuntimeDecompressor(stubModule, member => { });
                        instr.Operand = decomp;
                    }
                }
            }
            decrypter.Body.Instructions.Clear();
            foreach (Instruction instr in instrs)
            {
                decrypter.Body.Instructions.Add(instr);
            }

            // Pack modules
            PackModules(context, compCtx, stubModule, comp, random);
        }