/// <summary>
        /// Disables encryption on the given disk volume.
        /// </summary>
        /// <param name="volumeType">The disk volume.</param>
        /// <return>An observable that emits the decryption status.</return>
        ///GENMHASH:B980B0A762D67885E3B127392FD42890:A65E5C07D8DA37A2AB5EC199276933B9
        internal async Task <Microsoft.Azure.Management.Compute.Fluent.IDiskVolumeEncryptionMonitor> DisableEncryptionAsync(DiskVolumeType volumeType, CancellationToken cancellationToken = default(CancellationToken))
        {
            EnableDisableEncryptConfig encryptConfig = new DisableEncryptConfig(volumeType);

            await ValidateBeforeDecryptAsync(volumeType, cancellationToken);

            // Update the encryption extension if already installed
            //
            IVirtualMachine virtualMachine = await UpdateEncryptionExtensionAsync(encryptConfig, cancellationToken);

            if (virtualMachine == null)
            {
                // If encryption extension is not then install it
                //
                virtualMachine = await InstallEncryptionExtensionAsync(encryptConfig, cancellationToken);
            }
            // Validate and retrieve the encryption extension status
            //
            string status = await RetrieveEncryptionExtensionStatusStringAsync(ERROR_ENCRYPTION_EXTENSION_STATUS_IS_EMPTY, cancellationToken);

            // Update the VM's OS profile by marking encryption disabled
            //
            virtualMachine = await UpdateVMStorageProfileAsync(encryptConfig, cancellationToken);

            // Gets the encryption status
            //
            return(await GetDiskVolumeEncryptDecryptStatusAsync(virtualMachine, cancellationToken));
        }
Esempio n. 2
0
        public VirtualMachine(
            string subscriptionId,
            IVirtualMachine virtualMachine,
            ILogger logger,
            IEnumerable <Setting> settings,
            NotificationDelay notificationDelay,
            ResourceGroup resourceGroup,
            LocationTZ timezone,
            DateTime timeNowUtc
            )
        {
            this.subscriptionId    = subscriptionId;
            this.virtualMachine    = virtualMachine;
            this.logger            = logger;
            this.settings          = settings;
            this.notificationDelay = notificationDelay;
            this.resourceGroup     = resourceGroup;
            this.timezones         = timezone.GetAll();
            this.timeNowUtc        = timeNowUtc;

            // Using the settings, set the start and stop time for the vm
            startTime = settings.First(s => s.name == "vm_start").value;
            stopTime  = settings.First(s => s.name == "vm_stop").value;

            SetPowerState();
        }
Esempio n. 3
0
        public static void RegisterTo(IVirtualMachine vm)
        {
            var jumpMachine = new JumpMachine(vm.Instructions);

            vm.RegisterCommand('[', b => jumpMachine.OnBrace(b));
            vm.RegisterCommand(']', b => jumpMachine.OnBrace(b));
        }
        async Task DecorateWithNetworkProperties(IVirtualMachine vm, VmExtendedDto vmDto, CancellationToken cancellationToken)
        {
            var primaryNic = await _azure.NetworkInterfaces.GetByIdAsync(vm.PrimaryNetworkInterfaceId, cancellationToken);

            vmDto.PrivateIp = primaryNic.PrimaryPrivateIP;

            try
            {
                if (primaryNic.PrimaryIPConfiguration != null)
                {
                    var pip = await _azure.PublicIPAddresses.GetByIdAsync(primaryNic.PrimaryIPConfiguration.PublicIPAddressId, cancellationToken);

                    if (pip != null)
                    {
                        vmDto.PublicIp = pip.IPAddress;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, $"Unable to fetch public IP settings for VM {vm.Name}");
            }

            vmDto.NICs.Add(CreateNicDto(primaryNic));

            foreach (var curNic in vm.NetworkInterfaceIds)
            {
                vmDto.NICs.Add(await CreateNicDto(curNic, cancellationToken));
            }
        }
        public static void InjectMembers(this IVirtualMachine virtualMachine, GamePatch gamePatch, Type type)
        {
            if (((AvailableSinceAttribute)Attribute.GetCustomAttribute(type, typeof(AvailableSinceAttribute)))?.AvailableSince > gamePatch)
            {
                return;
            }

            foreach (var member in type.GetMembers())
            {
                if (((AvailableSinceAttribute)Attribute.GetCustomAttribute(member, typeof(AvailableSinceAttribute)))?.AvailableSince > gamePatch)
                {
                    continue;
                }

                if (member.DeclaringType == type)
                {
                    if (member is FieldInfo field)
                    {
                        virtualMachine.InjectField(field);
                    }
                    else if (member is MethodInfo method)
                    {
                        virtualMachine.InjectMethod(method);
                    }
                }
            }
        }
Esempio n. 6
0
        public static void RegisterTo(IVirtualMachine vm)
        {
            var pogoStick = new PogoStick(vm.Instructions);

            vm.RegisterCommand('[', b => pogoStick.OnBrace(b));
            vm.RegisterCommand(']', b => pogoStick.OnBrace(b));
        }
        public static void RegisterTo(IVirtualMachine vm)
        {
            var halfLoops = new Stack <Loop>();

            startLoops = new Dictionary <int, Loop>();
            endLoops   = new Dictionary <int, Loop>();
            for (int position = 0; position < vm.Instructions.Length; position++)
            {
                if (vm.Instructions[position] == '[')
                {
                    halfLoops.Push(new Loop(position));
                }
                else if (vm.Instructions[position] == ']')
                {
                    var loop = halfLoops.Pop();
                    loop.End = position;
                    startLoops.Add(loop.Start, loop);
                    endLoops.Add(loop.End, loop);
                }
            }
            vm.RegisterCommand('[', b => {
                if (vm.Memory[vm.MemoryPointer] == 0)
                {
                    vm.InstructionPointer = startLoops[vm.InstructionPointer].End;
                }
            });
            vm.RegisterCommand(']', b => {
                if (vm.Memory[vm.MemoryPointer] != 0)
                {
                    vm.InstructionPointer = endLoops[vm.InstructionPointer].Start;
                }
            });
        }
Esempio n. 8
0
 public static void Constants(IVirtualMachine vm)
 {
     foreach (var chars in constant)
     {
         vm.RegisterCommand(chars, machine => machine.Memory[machine.MemoryPointer] = (byte)chars);
     }
 }
Esempio n. 9
0
        /// <summary>
        /// Disables encryption on the given disk volume.
        /// </summary>
        /// <param name="volumeType">The disk volume.</param>
        /// <return>An observable that emits the decryption status.</return>
        ///GENMHASH:B980B0A762D67885E3B127392FD42890:A65E5C07D8DA37A2AB5EC199276933B9
        internal async Task <Microsoft.Azure.Management.Compute.Fluent.IDiskVolumeEncryptionMonitor> DisableEncryptionAsync(DiskVolumeType volumeType, CancellationToken cancellationToken = default(CancellationToken))
        {
            var encryptConfig = EncryptionSettings.CreateDisable(volumeType);

            await ValidateBeforeDecryptAsync(volumeType, cancellationToken);

            // Update the encryption extension if already installed
            //
            IVirtualMachineExtension extension = await GetEncryptionExtensionInstalledInVMAsync(cancellationToken);

            IVirtualMachine virtualMachine = await UpdateEncryptionExtensionAsync(encryptConfig, extension, cancellationToken);

            bool isNoAAD = EncryptionExtensionIdentifier.IsNoAADVersion(osType, extension.VersionName);

            if (virtualMachine != null && !isNoAAD)
            {
                // Validate and retrieve the encryption extension status
                //
                string status = await RetrieveEncryptionExtensionStatusStringAsync(ERROR_ENCRYPTION_EXTENSION_STATUS_IS_EMPTY, cancellationToken);

                // Update the VM's OS profile by marking encryption disabled
                //
                virtualMachine = await UpdateVMStorageProfileAsync(encryptConfig, cancellationToken);
            }
            // Gets the encryption status
            //
            return(await GetDiskVolumeEncryptDecryptStatusAsync(virtualMachine, isNoAAD, cancellationToken));
        }
        // Сдвинуть указатель памяти вправо/влево на 1 байт
        private static void RegisterRigthSNLefthift(IVirtualMachine vm)
        {
            vm.RegisterCommand('>', vMachine =>
            {
                // Если указатель памяти указывает на последнюю ячейку памяти, то ставим его в начало
                if (vMachine.MemoryPointer + 1 == vMachine.Memory.Length)
                {
                    vMachine.MemoryPointer = 0;
                }
                else
                {
                    vMachine.MemoryPointer++;
                }
            });

            vm.RegisterCommand('<', vMachine =>
            {
                if (vMachine.MemoryPointer == 0) // Аналогично сдвигу вправо
                {
                    vMachine.MemoryPointer = vMachine.Memory.Length - 1;
                }
                else
                {
                    vMachine.MemoryPointer--;
                }
            });
        }
        /// <summary>Convert the Virtual machine to virtual machine crawler response entity.</summary>
        /// <param name="virtualMachine">The virtual machine.</param>
        /// <param name="partitionKey">The partition key for the virtaul machine entity.</param>
        /// <param name="vmGroup">Vm group name.</param>
        /// <returns></returns>
        public static VirtualMachineCrawlerResponse ConvertToVirtualMachineEntity(IVirtualMachine virtualMachine, string partitionKey, string vmGroup = "")
        {
            var virtualMachineCrawlerResponseEntity = new VirtualMachineCrawlerResponse(partitionKey,
                                                                                        virtualMachine.Id.Replace(Delimeters.ForwardSlash, Delimeters.Exclamatory))
            {
                RegionName        = virtualMachine.RegionName,
                ResourceGroupName = virtualMachine.ResourceGroupName,
                ResourceName      = virtualMachine.Name,
                AvailabilitySetId = virtualMachine.AvailabilitySetId,
                ResourceType      = virtualMachine.Type,
                AvailabilityZone  = virtualMachine.AvailabilityZones.Count > 0 ?
                                    int.Parse(virtualMachine.AvailabilityZones.FirstOrDefault().Value) : 0,
                VirtualMachineGroup = string.IsNullOrWhiteSpace(vmGroup) ? VirtualMachineGroup.VirtualMachines.ToString() : vmGroup,
                State = virtualMachine.PowerState?.Value
            };

            if (virtualMachine.InstanceView?.PlatformUpdateDomain > 0)
            {
                virtualMachineCrawlerResponseEntity.UpdateDomain = virtualMachine.InstanceView.PlatformUpdateDomain;
            }
            if (virtualMachine.InstanceView?.PlatformFaultDomain > 0)
            {
                virtualMachineCrawlerResponseEntity.FaultDomain = virtualMachine.InstanceView.PlatformFaultDomain;
            }

            return(virtualMachineCrawlerResponseEntity);
        }
Esempio n. 12
0
        /// <summary>Perform the Chaos Operation</summary>
        /// <param name="actionType">Action type</param>
        /// <param name="virtualMachine">Virtual Machine</param>
        /// <param name="scheduledRules">Event activity entity</param>
        /// <returns></returns>
        private static void PerformChaosOnVirtualMachine(string action, IVirtualMachine virtualMachine, ScheduledRules scheduledRules, bool enableRollback)
        {
            ActionType actionType;

            if (!Enum.TryParse(action, out actionType))
            {
                return;
            }

            switch (actionType)
            {
            case ActionType.Start:
                virtualMachine.StartAsync();
                break;

            case ActionType.PowerOff:
            case ActionType.Stop:
                virtualMachine.PowerOffAsync();
                break;

            case ActionType.Restart:
                virtualMachine.RestartAsync();
                break;
            }

            if (enableRollback)
            {
                scheduledRules.RollbackExecutionStatus = Status.Executing.ToString();
            }
            else
            {
                scheduledRules.ExecutionStatus = Status.Executing.ToString();
            }
        }
Esempio n. 13
0
        public IVirtualMachine GetVMFromAzure(string _vmId)
        {
            IVirtualMachine machine = null;

            using (CADContext context = new CADContext())
            {
                try
                {
                    IAzure      azure;
                    VM          vm   = context.VMs.FirstOrDefault(v => v.VMId == _vmId);
                    Application apps = context.Applications.FirstOrDefault(app => app.AppId == vm.ApplicationId);
                    azure   = GetAzureConnection(apps);
                    machine = azure.VirtualMachines.List().FirstOrDefault(v => v.VMId == _vmId);
                }
                catch (Exception ex)
                {
                    Log log = new Log();
                    log.name      = ex.ToString();
                    log.timestamp = DateTime.UtcNow;
                    context.Logs.Add(log);
                    context.SaveChanges();
                }
            }
            return(machine);
        }
        // Увеличение/уменьшение байта памяти, на который указывает указатель
        private static void RegisterIncNDec(IVirtualMachine vm)
        {
            vm.RegisterCommand('+', vMachine =>
            {
                // Если значение байта максимально, то при увеличении значение становится 0
                if (vMachine.Memory[vMachine.MemoryPointer] == 255)
                {
                    vMachine.Memory[vMachine.MemoryPointer] = 0;
                }
                else
                {
                    vMachine.Memory[vMachine.MemoryPointer]++;
                }
            });

            vm.RegisterCommand('-', vMachine =>
            {
                if (vMachine.Memory[vMachine.MemoryPointer] == 0) // Аналогично инкрименту
                {
                    vMachine.Memory[vMachine.MemoryPointer] = 255;
                }
                else
                {
                    vMachine.Memory[vMachine.MemoryPointer]--;
                }
            });
        }
Esempio n. 15
0
        /**
         * It creates a new Azure virtual machine and it instantiate a Java Docker client.
         * @param azure - instance of Azure
         * @param rgName - name of the Azure resource group to be used when creating a virtual machine
         * @param region - region to be used when creating a virtual machine
         * @return an instance of DockerClient
         */
        public static DockerClient FromNewDockerVM(IAzure azure, String rgName, Region region)
        {
            string dockerVMName     = SdkContext.RandomResourceName("dockervm", 15);
            string publicIPDnsLabel = SdkContext.RandomResourceName("pip", 10);
            string vmUserName       = "******";
            string vmPassword       = "******";

            // Could not find a Docker environment; presume that there is no local Docker engine running and
            //    attempt to configure a Docker engine running inside a new Azure virtual machine
            Utilities.Log("Creating an Azure virtual machine running Docker");

            IVirtualMachine dockerVM = azure.VirtualMachines.Define(dockerVMName)
                                       .WithRegion(region)
                                       .WithExistingResourceGroup(rgName)
                                       .WithNewPrimaryNetwork("10.0.0.0/28")
                                       .WithPrimaryPrivateIPAddressDynamic()
                                       .WithNewPrimaryPublicIPAddress(publicIPDnsLabel)
                                       .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                       .WithRootUsername(vmUserName)
                                       .WithRootPassword(vmPassword)
                                       .WithSize(VirtualMachineSizeTypes.StandardD2V2)
                                       .Create();

            Utilities.Log("Created Azure Virtual Machine: " + dockerVM.Id);

            // Get the IP of the Docker host
            INicIPConfiguration nicIPConfiguration = dockerVM.GetPrimaryNetworkInterface().PrimaryIPConfiguration;
            IPublicIPAddress    publicIp           = nicIPConfiguration.GetPublicIPAddress();
            string dockerHostIP = publicIp.IPAddress;

            DockerClient dockerClient = InstallDocker(dockerHostIP, vmUserName, vmPassword);

            return(dockerClient);
        }
Esempio n. 16
0
 public TypeProvider(IVirtualMachine virtualMachine)
 {
     this.virtualMachine = virtualMachine;
     this.virtualMachine.AssemblyLoaded += OnAssemblyLoaded;
     this.virtualMachine.AssemblyUnloaded += OnAssemblyUnloaded;
     this.virtualMachine.TypeLoaded += OnTypeLoaded;
 }
        public void GlobalSetup()
        {
            TrieStore      trieStore = new(new MemDb(), new OneLoggerLogManager(NullLogger.Instance));
            IKeyValueStore codeDb    = new MemDb();

            _stateProvider = new StateProvider(trieStore, codeDb, new OneLoggerLogManager(NullLogger.Instance));
            _stateProvider.CreateAccount(Address.Zero, 1000.Ether());
            _stateProvider.Commit(_spec);

            _storageProvider = new StorageProvider(trieStore, _stateProvider, new OneLoggerLogManager(NullLogger.Instance));

            _worldState = new WorldState(_stateProvider, _storageProvider);
            Console.WriteLine(MuirGlacier.Instance);
            _virtualMachine = new VirtualMachine(_blockhashProvider, MainnetSpecProvider.Instance, new OneLoggerLogManager(NullLogger.Instance));

            _environment = new ExecutionEnvironment
            {
                ExecutingAccount   = Address.Zero,
                CodeSource         = Address.Zero,
                Caller             = Address.Zero,
                CodeInfo           = new CodeInfo(Bytecode),
                Value              = 0,
                TransferValue      = 0,
                TxExecutionContext = new TxExecutionContext(_header, Address.Zero, 0)
            };

            _evmState = new EvmState(100_000_000L, _environment, ExecutionType.Transaction, true, _worldState.TakeSnapshot(), false);
        }
 // Добавление констант
 private static void RegisterConstants(IVirtualMachine vm)
 {
     foreach (var c in consts)
     {
         vm.RegisterCommand(c, vMachine => vMachine.Memory[vMachine.MemoryPointer] = (byte)c);
     }
 }
        /// <summary>
        /// Enables encryption.
        /// </summary>
        /// <param name="encryptionSettings">The settings to be used for encryption extension.</param>
        /// <param name="">The Windows or Linux encryption settings.</param>
        /// <return>An observable that emits the encryption status.</return>
        ///GENMHASH:FB7DBA27A41CC76685F21AB0A9729C82:D88D73A86520940C4EA57E9CEEA1516F
        internal async Task <IDiskVolumeEncryptionMonitor> EnableEncryptionAsync <T>(VirtualMachineEncryptionConfiguration <T> encryptionSettings,
                                                                                     CancellationToken cancellationToken = default(CancellationToken)) where T : VirtualMachineEncryptionConfiguration <T>
        {
            var encryptConfig = new EnableEncryptConfig <T>(encryptionSettings);
            // Update the encryption extension if already installed
            //
            IVirtualMachine virtualMachine = await UpdateEncryptionExtensionAsync(encryptConfig, cancellationToken);

            if (virtualMachine == null)
            {
                // If encryption extension is not installed then install it
                //
                virtualMachine = await InstallEncryptionExtensionAsync(encryptConfig, cancellationToken);
            }
            // Retrieve the encryption key URL after extension install or update
            //
            string keyVaultSecretUrl = await RetrieveEncryptionExtensionStatusStringAsync(ERROR_EXPECTED_KEY_VAULT_URL_NOT_FOUND, cancellationToken);

            // Update the VM's OS Disk (in storage profile) with the encryption metadata
            //
            virtualMachine = await UpdateVMStorageProfileAsync(encryptConfig, keyVaultSecretUrl, cancellationToken);

            // Gets the encryption status
            //
            return(await GetDiskVolumeEncryptDecryptStatusAsync(virtualMachine, cancellationToken));
        }
Esempio n. 20
0
        public void GlobalSetup()
        {
            ISnapshotableDb codeDb      = new StateDb();
            ISnapshotableDb stateDb     = new StateDb();
            IDb             blockInfoDb = new MemDb(10, 5);

            ISpecProvider specProvider = MainNetSpecProvider.Instance;
            IReleaseSpec  spec         = MainNetSpecProvider.Instance.GenesisSpec;

            StateProvider stateProvider = new StateProvider(stateDb, codeDb, LimboLogs.Instance);

            stateProvider.CreateAccount(Address.Zero, 1000.Ether());
            stateProvider.Commit(spec);

            StorageProvider storageProvider = new StorageProvider(stateDb, stateProvider, LimboLogs.Instance);
            StateReader     stateReader     = new StateReader(stateDb, codeDb, LimboLogs.Instance);

            ChainLevelInfoRepository chainLevelInfoRepository = new ChainLevelInfoRepository(blockInfoDb);
            BlockTree blockTree = new BlockTree(new MemDb(), new MemDb(), blockInfoDb, chainLevelInfoRepository, specProvider, NullTxPool.Instance, LimboLogs.Instance);

            _blockhashProvider = new BlockhashProvider(blockTree, LimboLogs.Instance);
            _virtualMachine    = new VirtualMachine(stateProvider, storageProvider, _blockhashProvider, specProvider, LimboLogs.Instance);

            Block genesisBlock = Build.A.Block.Genesis.TestObject;

            blockTree.SuggestBlock(genesisBlock);

            Block block1 = Build.A.Block.WithParent(genesisBlock).WithNumber(1).TestObject;

            blockTree.SuggestBlock(block1);

            TransactionProcessor transactionProcessor
                = new TransactionProcessor(MainNetSpecProvider.Instance, stateProvider, storageProvider, _virtualMachine, LimboLogs.Instance);

            BlockProcessor blockProcessor = new BlockProcessor(specProvider, AlwaysValidBlockValidator.Instance, new RewardCalculator(specProvider), transactionProcessor,
                                                               stateDb, codeDb, new MemDb(), stateProvider, storageProvider, NullTxPool.Instance, NullReceiptStorage.Instance, LimboLogs.Instance);

            BlockchainProcessor blockchainProcessor = new BlockchainProcessor(
                blockTree,
                blockProcessor,
                new TxSignaturesRecoveryStep(new EthereumEcdsa(specProvider, LimboLogs.Instance), NullTxPool.Instance, LimboLogs.Instance),
                LimboLogs.Instance,
                false,
                false);

            blockchainProcessor.Process(genesisBlock, ProcessingOptions.None, NullBlockTracer.Instance);
            blockchainProcessor.Process(block1, ProcessingOptions.None, NullBlockTracer.Instance);

            BlockchainBridge bridge = new BlockchainBridge(
                stateReader,
                stateProvider,
                storageProvider,
                blockTree,
                NullTxPool.Instance,
                NullReceiptStorage.Instance,
                NullFilterStore.Instance,
                NullFilterManager.Instance, new DevWallet(new WalletConfig(), LimboLogs.Instance), transactionProcessor, new EthereumEcdsa(MainNetSpecProvider.Instance, LimboLogs.Instance));

            _ethModule = new EthModule(LimboLogs.Instance, bridge);
        }
        public void CanEnableWithImplicitStorageOnManagedVMCreation()
        {
            using (var context = FluentMockContext.Start(GetType().FullName))
            {
                string rgName     = TestUtilities.GenerateName("vmbdtest");
                string regionName = "eastus";
                string vmName     = "javavm";

                var             azure          = TestHelper.CreateRollupClient();
                IVirtualMachine virtualMachine = azure.VirtualMachines
                                                 .Define(vmName)
                                                 .WithRegion(regionName)
                                                 .WithNewResourceGroup(rgName)
                                                 .WithNewPrimaryNetwork("10.0.0.0/28")
                                                 .WithPrimaryPrivateIPAddressDynamic()
                                                 .WithoutPrimaryPublicIPAddress()
                                                 .WithPopularLinuxImage(KnownLinuxVirtualMachineImage.UbuntuServer16_04_Lts)
                                                 .WithRootUsername("Foo12")
                                                 .WithRootPassword("abc!@#F0orL")
                                                 .WithBootDiagnostics()
                                                 .Create();

                Assert.NotNull(virtualMachine);
                Assert.True(virtualMachine.IsBootDiagnosticsEnabled);
                Assert.NotNull(virtualMachine.BootDiagnosticsStorageUri);
            }
        }
Esempio n. 22
0
 public VirtualMachineControl(IVirtualMachine machine)
 {
     DataContext = this;
     InitializeComponent();
     Machine         = machine;
     VMAction.Click += VMAction_Click;
 }
        public static string GetManagementLink(IVirtualMachine machine)
        {
            string portalUrl = CombineUris(PortalUrlBase, machine.Id);
            string aTag      = $"<a href=\"{portalUrl}\">Manage</a>";

            return(aTag);
        }
        public static void RegisterTo(IVirtualMachine vm)
        {
            var indexOfBrackets = new Stack <int>();
            var startBrackets   = new Dictionary <int, int>();
            var endBrackets     = new Dictionary <int, int>();

            for (int i = 0; i < vm.Instructions.Length; i++)
            {
                if (vm.Instructions[i] == '[')
                {
                    indexOfBrackets.Push(i);
                }
                else if (vm.Instructions[i] == ']')
                {
                    startBrackets[i] = indexOfBrackets.Peek();
                    endBrackets[indexOfBrackets.Pop()] = i;
                }
            }

            vm.RegisterCommand('[', b => {
                if (vm.Memory[vm.MemoryPointer] == 0)
                {
                    vm.InstructionPointer = endBrackets[vm.InstructionPointer];
                }
            });
            vm.RegisterCommand(']', b => vm.InstructionPointer = startBrackets[vm.InstructionPointer] - 1);
        }
Esempio n. 25
0
        public static void RegisterTo(IVirtualMachine vm)
        {
            var indexOfSquareBrackets = new Stack <int>();
            var squareBracketsDict    = new Dictionary <int, int>();

            for (int i = 0; i < vm.Instructions.Length; i++)
            {
                if (vm.Instructions[i] == '[')
                {
                    indexOfSquareBrackets.Push(i);
                }
                if (vm.Instructions[i] == ']')
                {
                    var tempIndex = indexOfSquareBrackets.Pop();
                    squareBracketsDict.Add(tempIndex, i);
                    squareBracketsDict.Add(i, tempIndex);
                }
            }
            vm.RegisterCommand('[', virtMachine =>
            {
                if (vm.Memory[vm.MemoryPointer] == 0)
                {
                    vm.InstructionPointer = squareBracketsDict[vm.InstructionPointer];
                }
            });
            vm.RegisterCommand(']', virtMachine =>
            {
                if (vm.Memory[vm.MemoryPointer] != 0)
                {
                    vm.InstructionPointer = squareBracketsDict[vm.InstructionPointer];
                }
            });
        }
Esempio n. 26
0
 public static void WriteAllSymbols(IVirtualMachine vm)
 {
     foreach (var symbol in allSymbols)
     {
         vm.RegisterCommand(symbol, machine => machine.Memory[machine.MemoryPointer] = (byte)symbol);
     }
 }
Esempio n. 27
0
 public TypeProvider(IVirtualMachine virtualMachine)
 {
     this.virtualMachine = virtualMachine;
     this.virtualMachine.AssemblyLoaded   += OnAssemblyLoaded;
     this.virtualMachine.AssemblyUnloaded += OnAssemblyUnloaded;
     this.virtualMachine.TypeLoaded       += OnTypeLoaded;
 }
Esempio n. 28
0
        public void Run(IVirtualMachine Runtime, int[] args, char[] types)
        {
            if (types[0] != 0)
            {
                throw new VMException(VMFault.InvalidArgs);
            }
            int memoryAddr;

            if (types[1] == 0)
            {
                memoryAddr = Runtime.Read(args[1]);
            }
            else
            {
                memoryAddr = args[1];
            }

            int offset = args[2];

            if (types[2] == 0)
            {
                offset = Runtime.Read(args[2]);
            }

            Runtime.Write(args[0], Runtime.Read(memoryAddr + offset));
        }
        private void CreateStepRequests()
        {
            IVirtualMachine      virtualMachine = _thread.GetVirtualMachine();
            IEventRequestManager manager        = virtualMachine.GetEventRequestManager();

            /*
             * THE ORDER OF THESE MUST MATCH THE LOOKUP IN GetStepRequest!
             */

            // step into
            _stepRequests.Add(manager.CreateStepRequest(_thread, StepSize.Instruction, StepDepth.Into));
            _stepRequests.Add(manager.CreateStepRequest(_thread, StepSize.Line, StepDepth.Into));
            _stepRequests.Add(manager.CreateStepRequest(_thread, StepSize.Statement, StepDepth.Into));

            // step out
            _stepRequests.Add(manager.CreateStepRequest(_thread, StepSize.Instruction, StepDepth.Out));
            _stepRequests.Add(manager.CreateStepRequest(_thread, StepSize.Line, StepDepth.Out));
            _stepRequests.Add(manager.CreateStepRequest(_thread, StepSize.Statement, StepDepth.Out));

            // step over
            _stepRequests.Add(manager.CreateStepRequest(_thread, StepSize.Instruction, StepDepth.Over));
            _stepRequests.Add(manager.CreateStepRequest(_thread, StepSize.Line, StepDepth.Over));
            _stepRequests.Add(manager.CreateStepRequest(_thread, StepSize.Statement, StepDepth.Over));

            foreach (var request in _stepRequests)
            {
                request.SuspendPolicy = SuspendPolicy.All;
            }
        }
Esempio n. 30
0
        public void GlobalSetup()
        {
            ByteCode = Bytes.FromHexString(Environment.GetEnvironmentVariable("NETH.BENCHMARK.BYTECODE"));
            Console.WriteLine($"Running benchmark for bytecode {ByteCode?.ToHexString()}");
            IDb             codeDb  = new StateDb();
            ISnapshotableDb stateDb = new StateDb();

            _stateProvider = new StateProvider(stateDb, codeDb, LimboLogs.Instance);
            _stateProvider.CreateAccount(Address.Zero, 1000.Ether());
            _stateProvider.Commit(_spec);

            _storageProvider = new StorageProvider(stateDb, _stateProvider, LimboLogs.Instance);
            _virtualMachine  = new VirtualMachine(_stateProvider, _storageProvider, _blockhashProvider, MainnetSpecProvider.Instance, LimboLogs.Instance);

            _environment = new ExecutionEnvironment();
            _environment.ExecutingAccount = Address.Zero;
            _environment.CodeSource       = Address.Zero;
            _environment.Originator       = Address.Zero;
            _environment.Sender           = Address.Zero;
            _environment.CodeInfo         = new CodeInfo(ByteCode);
            _environment.GasPrice         = 0;
            _environment.Value            = 0;
            _environment.TransferValue    = 0;
            _environment.CurrentBlock     = _header;

            _evmState = new EvmState(long.MaxValue, _environment, ExecutionType.Transaction, true, false);
        }
        public static void RegisterTo(IVirtualMachine vm, Func <int> read, Action <char> write)
        {
            // Вывести байт памяти, на который указывает указатель, преобразовав в символ согласно ASCII
            vm.RegisterCommand('.', b => { write(Convert.ToChar(b.Memory[b.MemoryPointer])); });
            // Увеличить байт памяти, на который указывает указатель
            vm.RegisterCommand('+', b => { b.Memory[b.MemoryPointer] = Convert.ToByte((b.Memory[b.MemoryPointer] + 1) & 0xFF); });
            // Уменьшить байт памяти, на который указывает указатель
            vm.RegisterCommand('-', b => { b.Memory[b.MemoryPointer] = Convert.ToByte((b.Memory[b.MemoryPointer] + 255) & 0xFF); });
            // Ввести символ и сохранить его ASCII-код в байт памяти, на который указывает указатель
            vm.RegisterCommand(',', b => { b.Memory[b.MemoryPointer] = Convert.ToByte(read()); });
            // Сдвинуть указатель памяти вправо на 1 байт
            vm.RegisterCommand('>', b => { b.MemoryPointer = (b.MemoryPointer + 1) % b.Memory.Length; });
            // Сдвинуть указатель памяти влево на 1 байт
            vm.RegisterCommand('<', b =>
            {
                b.MemoryPointer = (b.MemoryPointer + b.Memory.Length - 1) % b.Memory.Length;
            });
            // сохранить ASCII-код этого символа в байт памяти, на который указывает указатель
            const string literals = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

            for (var ix = 0; ix < literals.Length; ix++)
            {
                var literal = literals[ix];
                vm.RegisterCommand(literal, b => { b.Memory[b.MemoryPointer] = Convert.ToByte(literal); });
            }
        }
Esempio n. 32
0
        public DebuggerSession(IVirtualMachine vm, ITypeProvider typeProvider,
			IExecutionProvider executionProvider, IThreadProvider threadProvider,
			IBreakpointProvider breakpointProvider)
        {
            this.typeProvider = typeProvider;
            this.executionProvider = executionProvider;
            this.threadProvider = threadProvider;
            this.breakpointProvider = breakpointProvider;
            this.vm = vm;
        }
Esempio n. 33
0
        public DebuggerSession(IVirtualMachine virtualMachine,
			IExecutionProvider executionProvider, ITypeProvider typeProvider,
			IThreadProvider threadProvider, IBreakpointProvider breakpointProvider)
        {
            VM = virtualMachine;
            ExecutionProvider = executionProvider;
            ThreadProvider = threadProvider;
            TypeProvider = typeProvider;
            BreakpointProvider = breakpointProvider;
        }
Esempio n. 34
0
 public ExecutionProvider(IVirtualMachine vm)
 {
     this.vm = vm;
     this.vm.VMSuspended += VMSuspended;
     this.vm.Stepped += OnStepped;
     this.vm.ThreadStarted += OnThreadStarted;
     this.vm.BreakpointHit += OnBreakpointHit;
     currentLocation = null;
     currentThread = null;
     running = true;
 }
Esempio n. 35
0
        public DebuggerSession(IVirtualMachine vm, ITypeProvider typeProvider,
			IExecutionProvider executionProvider, IThreadProvider threadProvider,
			IBreakpointProvider breakpointProvider)
        {
            this.typeProvider = typeProvider;
            this.executionProvider = executionProvider;
            this.threadProvider = threadProvider;
            this.breakpointProvider = breakpointProvider;
            this.vm = vm;

            LogProvider.Debug += s => LogOnDebug (s);
            LogProvider.Error += s => LogOnError (s);
        }
 private IVirtualMachine CreateVirtualMachine()
 {
     return _virtualMachine = new SphereVirtualMachine( _vmWareVirtualMachine );
 }
Esempio n. 37
0
        internal void InitializeDebuggerChannel(JavaDebugEngine debugEngine, IDebugEventCallback2 callback)
        {
            Contract.Requires<ArgumentNullException>(debugEngine != null, "debugEngine");
            Contract.Requires<ArgumentNullException>(callback != null, "callback");

            _debugEngine = debugEngine;
            _callback = callback;

            var connector = new LocalDebuggingAttachingConnector();

            Dictionary<string, IConnectorArgument> arguments = new Dictionary<string, IConnectorArgument>();

            string argumentName = "pid";
            IConnectorIntegerArgument defaultArgument = (IConnectorIntegerArgument)connector.DefaultArguments[argumentName];
            IConnectorIntegerArgument argument = new ConnectorIntegerArgument(defaultArgument, (int)_process.GetPhysicalProcessId().dwProcessId);
            arguments.Add(argumentName, argument);

            argumentName = "sourcePaths";
            IConnectorStringArgument defaultPathsArgument = (IConnectorStringArgument)connector.DefaultArguments[argumentName];
            List<string> sourcePaths = GetSourcePaths();
            IConnectorStringArgument stringArgument = new ConnectorStringArgument(defaultPathsArgument, string.Join(";", sourcePaths));
            arguments.Add(argumentName, stringArgument);

            connector.AttachComplete += HandleAttachComplete;
            _virtualMachine = connector.Attach(arguments);

            IVirtualMachineEvents events = _virtualMachine.GetEventQueue() as IVirtualMachineEvents;
            if (events != null)
            {
                events.VirtualMachineStart += HandleVirtualMachineStart;
                events.VirtualMachineDeath += HandleVirtualMachineDeath;
                events.SingleStep += HandleSingleStep;
                events.Breakpoint += HandleBreakpoint;
                events.MethodEntry += HandleMethodEntry;
                events.MethodExit += HandleMethodExit;
                events.MonitorContendedEnter += HandleMonitorContendedEnter;
                events.MonitorContendedEntered += HandleMonitorContendedEntered;
                events.MonitorContendedWait += HandleMonitorContendedWait;
                events.MonitorContendedWaited += HandleMonitorContendedWaited;
                events.Exception += HandleException;
                events.ThreadStart += HandleThreadStart;
                events.ThreadDeath += HandleThreadDeath;
                events.ClassPrepare += HandleClassPrepare;
                events.ClassUnload += HandleClassUnload;
                events.FieldAccess += HandleFieldAccess;
                events.FieldModification += HandleFieldModification;
            }
        }
 public CreateVirtualMachineService(IVirtualMachine ivm)
 {
 }
 public VirtualMachineIsNotReadyException( IVirtualMachine virtualMachine, string message ):base(message)
 {
     VirtualMachine = virtualMachine;
 }
Esempio n. 40
0
 public void SetUp()
 {
     _vm = SetupVirtualMachineRunning (CompileSimpleProgram ());
 }
Esempio n. 41
0
 public Shell(IVirtualMachine virtualMachine)
 {
     if (virtualMachine == null) throw new ArgumentNullException("virtualMachine");
     VirtualMachine = virtualMachine;
 }
 public RegisteredVirtualMachineService(string imagePathName)
 {
     GetVirtualHost();
     VM = virtualHost.Open(imagePathName);
 }
Esempio n. 43
0
 public void Destroy(IVirtualMachine vm)
 {
     ((Regulus.Framework.ILaunched)vm).Shutdown();
 }
Esempio n. 44
0
 /// <summary>
 /// A constructor for the system environment.
 /// </summary>
 /// <param name="vm"></param>
 public SystemEnvironment(IVirtualMachine vm = null)
 {
     VirtualMachine = vm;
     Bind(Time, "time", null, new { time = new[] { "datetime", "date", "now" } });
     Bind(Exit, "exit", null, new { exit = new[] { "quit" } });
 }
Esempio n. 45
0
        private void Stop()
        {
            AddText("Stopping...");
            Terminating = true;

            SetEnabled(false, StopButton);
            SetEnabled(true, BreakOnStartCheckBox);
            SetEnabled(true, StartButton);

            if (theVM != null && theVM.PoweredOn)
            {
                AddText("Stopping VM...");

                theVM.PowerOff();
                theVM = null;
            }
            if (TheDebugger != null)
            {
                AddText(string.Format("Stopped debugger : {0}", TheDebugger.Stop()));
                TheDebugger = null;
            }

            AddText("Stopped.");
            AddText("");
        }
Esempio n. 46
0
 public ExecutionProvider(IVirtualMachine virtualMachine)
 {
     this.virtualMachine = virtualMachine;
     this.virtualMachine.VMSuspended += VMSuspended;
 }
Esempio n. 47
0
 private static void SetEventProperties(DebugEvent debugEvent, IEventRequest request, SuspendPolicy suspendPolicy, IVirtualMachine virtualMachine, IThreadReference thread, bool manualResume)
 {
     Contract.Requires<ArgumentNullException>(debugEvent != null, "debugEvent");
     debugEvent.Properties.AddProperty(typeof(IEventRequest), request);
     debugEvent.Properties.AddProperty(typeof(SuspendPolicy), suspendPolicy);
     debugEvent.Properties.AddProperty(typeof(IVirtualMachine), virtualMachine);
     debugEvent.Properties.AddProperty(typeof(IThreadReference), thread);
     debugEvent.Properties.AddProperty("ManualResume", manualResume);
 }
Esempio n. 48
0
 public ThreadProvider(IVirtualMachine vm, IExecutionProvider executionProvider)
 {
     this.vm = vm;
     this.executionProvider = executionProvider;
     executionProvider.Suspended += Suspended;
 }