예제 #1
0
 /// <summary>
 /// Model of the processor passed as parameter
 /// </summary>
 /// <param name="processor">Processor from which the model is constructed</param>
 public ProcessorModel(Processor processor)
 {
     this.number      = processor.Number;
     this.isStopped   = processor.IsStopped;
     this.dataToRead  = processor.DataToRead;
     this.dataToWrite = processor.DataToWrite;
 }
예제 #2
0
        public IHeapNode FindNode(MemoryAddress address)
        {
            var index = _starts.BinarySearch(address);

            if (index == -1)
            {
                return(null);                // lower than first value
            }
            if (index < 0)
            {
                int closest = ~index - 1;
                if (_nodes[closest].Contains(address))
                {
                    return(_nodes[closest]);
                }
                else
                {
                    if (closest + 1 < _nodes.Length &&
                        _nodes[closest + 1].Contains(address))
                    {
                        return(_nodes[closest + 1]);
                    }
                    else
                    {
                        return(null);
                    }
                }
            }
            else
            {
                return(_nodes[index]);
            }
        }
예제 #3
0
        public void EqualsNull()
        {
            var t_FirstAddress = new MemoryAddress(0);

            t_FirstAddress.Equals(null)
            .Should().BeFalse();
        }
예제 #4
0
        public void EqualsIncorrectType()
        {
            var t_FirstAddress = new MemoryAddress(0);

            t_FirstAddress.Equals(new int())
            .Should().BeFalse();
        }
예제 #5
0
        /// <summary>
        /// 指定のアドレスから、指定の値を順に書き込みます。
        /// </summary>
        /// <param name="address">指定の値を順に書き込むアドレスの値です。</param>
        /// <param name="words">指定のアドレスから書き込む値です。</param>
        internal void WriteRange(MemoryAddress address, IEnumerable <Word> words)
        {
            UInt16 ui16StartAddr            = address.Value;
            IEnumerable <UInt16> ui16Values = words.Select((word) => word.GetAsUnsigned());

            ForEach(ui16StartAddr, ui16Values, Write);
        }
예제 #6
0
 public MemoryFieldSignature(string name, MemoryAddress type, string signature, IEnumerable <MemoryFieldSignaturePointer> pointers, int size)
     : base(name, type, 0, size)
 {
     Signature   = signature;
     Pointers    = pointers;
     Initialized = false;
 }
예제 #7
0
 private static T FirstTextSegmentMatch <T>(string pattern, MemoryAddress start, int count, string label)
 {
     return(CodePattern.Parse(pattern)
            .Matches(_ctx.Text.Start, _ctx.TextBuffer, start, count)
            .First()
            .Read <T>(_ctx.Dump, label));
 }
예제 #8
0
        public void Build_Success()
        {
            Casl2Program subProgram = Casl2Program.MakeForUnitTest(
                "SUB",
                TestUtils.MakeArray(
                    "ADDSUB  START",
                    "        ADDA  GR1,GR2",
                    "        RET",
                    "        END"));
            Casl2Program mainProgram = Casl2Program.MakeForUnitTest(
                "MAIN",
                TestUtils.MakeArray(
                    "MAIN    START",
                    "        CALL  ADDSUB",
                    "        RET",
                    "        END"));
            Casl2Project project = Casl2Project.MakeForUnitTest(subProgram, mainProgram);

            project.Programs.SelectItem(mainProgram);

            MemoryAddress expectedLoadAddress      = MemoryAddress.Zero;
            MemoryAddress expectedExecStartAddress = new MemoryAddress(2);

            Word[] expectedWords = WordTest.MakeArray(
                // Sub
                0x2412,                     //         ADDA  GR1,GR2
                0x8100,                     //         RET
                // Main
                0x8000, 0x0000,             //         CALL  ADDSUB
                0x8100);                    //         RET
            ExecutableModule expected =
                new ExecutableModule(expectedLoadAddress, expectedExecStartAddress, expectedWords);

            CheckBuild(project, expected, "ビルド成功 => 実行可能モジュールが生成される");
        }
예제 #9
0
        private static bool Init()
        {
            if (IsProcessNullCheck())
            {
                Dispose();
            }

            var processes = Process.GetProcessesByName("A Dance of Fire and Ice");

            if (!(processes.Length > 0))
            {
                return(false);
            }

            try
            {
                TargetProcess = processes[0];
                MS            = new MemoryScanner(p => p.ProcessName == TargetProcess.ProcessName);

                //FrameAddress = new MemoryAddress(new IntPtr(0x1E52CFC38B0), null);
                FrameAddress = new MemoryAddress(GetModuleBaseAddress("UnityPlayer.dll") + 0x017EEDD0, new int[] { 0x3D8, 0x0, 0x578, 0xE30 });
                //FrameAddress = new MemoryAddress(GetModuleBaseAddress("UnityPlayer.dll") + 0x0173E000, new int[] { 0x0, 0x20, 0x118 });

                IsPauseAddress = new MemoryAddress(GetModuleBaseAddress("UnityPlayer.dll") + 0x0179C458, new int[] { 0x170, 0x18, 0x18, 0x94 });
                InputOffset    = new MemoryAddress(GetModuleBaseAddress("UnityPlayer.dll") + 0x01731010, new int[] { 0x270, 0x10, 0xA50, 0x70, 0x7C0 });
                return(true);
            }
            catch
            {
                return(false);
            }
        }
예제 #10
0
        public void OperatorEqualsNull()
        {
            var t_Address = new MemoryAddress(0);

            (t_Address == null)
            .Should().BeFalse();
        }
        public void ResolveAddressFor()
        {
            Label           definedLabel        = new Label("DEF");
            MemoryAddress   definedLabelAddress = new MemoryAddress(0x1234);
            LabelDefinition labelDef            =
                LabelDefinition.MakeForUnitTest(definedLabel, MemoryOffset.Zero, definedLabelAddress);

            m_labelTable.RegisterForUnitTest(labelDef);
            CheckResolveAddressFor(
                definedLabel, true, definedLabelAddress,
                "プログラム内で定義されたラベル => 成功、そのラベルのアドレスが返される");

            EntryPoint entryPoint = EntryPointTest.Make("EXESTRT", "ENTRY", 0xfedc);

            m_entryPointTable.Register(entryPoint);
            CheckResolveAddressFor(
                entryPoint.EntryLabel, true, entryPoint.ExecStartAddress,
                "プログラムの入口名 => 成功、そのプログラムの実行開始アドレスが返される");

            Label         undefinedLabel = new Label("UNDEF");
            MemoryAddress DontCare       = MemoryAddress.Zero;

            CheckResolveAddressFor(
                undefinedLabel, false, DontCare,
                "未定義のラベル => 例外");
        }
        public static IEnumerable <MemoryAddress> Decode(BitMask mask, MemoryAddress memoryAddress)
        {
            var floatingAddress = mask.Overwrite(memoryAddress);

            var decodingAddress = new List <string>
            {
                string.Empty
            };

            foreach (var bit in floatingAddress)
            {
                var assignBit = bit == 'X' ? '0' : bit;

                for (var i = 0; i < decodingAddress.Count; i++)
                {
                    decodingAddress[i] += assignBit;
                }

                if (bit != 'X')
                {
                    continue;
                }

                foreach (var decodingResult in decodingAddress.ToList())
                {
                    decodingAddress.Add(decodingResult[..^ 1] + '1');
예제 #13
0
            public FluentWriter MM(MemoryAddress destinationAddress, MemoryAddress sourceAddress)
            {
                var instruction = new Instruction(_opCode).Destination(destinationAddress).Source(sourceAddress);

                _parent._codeStream.Add(instruction);
                return(_parent);
            }
예제 #14
0
            FluentWriter IFluentSourceInstructionWriter.M(MemoryAddress memoryAddress)
            {
                var instruction = new Instruction(_opCode).Destination(memoryAddress);

                _parent._codeStream.Add(instruction);
                return(_parent);
            }
 /// <summary>Constructor.</summary>
 /// <param name="targetIORef">
 ///    A reference to the <see cref="Target"/> object that will be used to read the target process' memory space.
 ///    This <see cref="Target"/> MUST be attached to a process, as it will be used in this constructor method to read the process'
 ///    memory and keep a snapshot of the original bytes at the given 'branchPoint' for restoring their values,
 ///    whenever <see cref="MemoryAlterationX86BranchInstruction.SetEnabled{TMemoryAlterationID, TCodeCave, TVariable}(Injector{TMemoryAlterationID, TCodeCave, TVariable}, bool)"/> is called
 ///    to deactivate a memory alteration.
 /// </param>
 /// <param name="branchPoint">The address of the instruction(s) that will be replaced by the branching instruction.</param>
 /// <param name="branchTarget">The address where the branching instruction will make the target application's code flow to.</param>
 /// <param name="instructionType">The type of branching instruction to be generated.</param>
 /// <param name="instructionSize">The size of the instruction(s) that will be replaced with the generated instruction (and some NOP instructions, whenever paddings are necessary).</param>
 public MemoryAlterationX86BranchInstruction(Target targetIORef, MemoryAddress branchPoint, MemoryAddress branchTarget,
                                             EX86BranchInstructionType instructionType, int instructionSize)
     : base(targetIORef, branchPoint, instructionSize)
 {
     m_instructionType = instructionType;
     m_branchTarget    = branchTarget;
 }
예제 #16
0
        public void EqualsSameInstance()
        {
            var t_FirstAddress = new MemoryAddress(0);

            t_FirstAddress.Equals(t_FirstAddress)
            .Should().BeTrue();
        }
예제 #17
0
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(TagName);

            if (Dimensions > 0)
            {
                sb.Append("[");
                sb.Append(Dimension1Size);
                if (Dimensions > 1)
                {
                    sb.Append(",");
                    sb.Append(Dimension2Size);
                }

                if (Dimensions > 2)
                {
                    sb.Append(",");
                    sb.Append(Dimension3Size);
                }
                sb.Append("]");
            }

            sb.Append((IsStructure ? " (Structure)" : "(Not a Structure)"));
            sb.Append(" Memory Address: " + MemoryAddress.ToString("X8"));

            return(sb.ToString());
        }
예제 #18
0
        public void OperatorEqualsSameInstance()
        {
            var t_Address = new MemoryAddress(0);

            (t_Address == t_Address)
            .Should().BeTrue();
        }
예제 #19
0
 protected internal override void WriteAt(Memory memory, MemoryAddress address, MemoryValue value)
 {
     foreach (var decodedMemoryAddress in MemoryAddressDecoder.Decode(memory.BitMask, address))
     {
         memory.values[decodedMemoryAddress.Position] = value;
     }
 }
예제 #20
0
 /// <summary>
 /// Empty model
 /// </summary>
 public ProcessorModel()
 {
     this.isStopped   = false;
     this.number      = 0;
     this.dataToRead  = new MemoryAddress();
     this.dataToWrite = new MemoryAddress();
 }
예제 #21
0
파일: ApiCatalogs.cs 프로젝트: 0xCM/z0
        public static Index <ApiCatalogEntry> rebase(MemoryAddress @base, ReadOnlySpan <ApiMember> members)
        {
            var dst = alloc <ApiCatalogEntry>(members.Length);

            rebase(@base, members, dst);
            return(dst);
        }
예제 #22
0
 public MemoryFieldSignature(string name, MemoryAddress type, string signature, IEnumerable <int> pointers, int size)
     : base(name, type, 0, size)
 {
     Signature   = signature;
     Pointers    = pointers.Select(pointer => new MemoryFieldSignaturePointer(pointer, false)).ToList();
     Initialized = false;
 }
예제 #23
0
        private void CheckAssignAbsAddress(
            UInt16 relOffsetValue, UInt16 baseAddressValue,
            Boolean success, UInt16 expectedAbsAddressValue, String message)
        {
            Label           label  = new Label("LBL001");
            LabelDefinition target = new LabelDefinition(label);

            MemoryOffset relOffset = new MemoryOffset(relOffsetValue);

            target.SetRelOffset(relOffset);

            MemoryAddress baseAddress = new MemoryAddress(baseAddressValue);

            try
            {
                target.AssignAbsAddress(baseAddress);
                Assert.IsTrue(success, message);

                MemoryAddress expectedAbsAddress = new MemoryAddress(expectedAbsAddressValue);
                MemoryAddress actualAbsAddress   = target.AbsAddress;
                MemoryAddressTest.Check(expectedAbsAddress, actualAbsAddress, message);
            }
            catch (Casl2SimulatorException)
            {
                Assert.IsFalse(success, message);
            }
        }
예제 #24
0
        public ReadToWritePrimitive(
            MemoryAccessParameter controlledParameter,
            MemoryAddress controlledAddress,
            Expression <Func <SimulationContext, bool> > constraints = null,
            GetNextViolationDelegate nextViolation       = null,
            PrimitiveTransitionSuccessDelegate onSuccess = null
            )
            : base(
                ExploitationPrimitiveType.ReadToWrite,
                name: String.Format("read content from '{0}' that is used as '{1}' of write", controlledAddress, controlledParameter),
                readAddress: controlledAddress
                )
        {
            this.ControlledParameter = controlledParameter;
            this.ControlledAddress   = controlledAddress;

            this.NextViolationDelegate = (context) =>
            {
                Violation v = context.CurrentViolation.NewTransitiveViolation(
                    MemoryAccessMethod.Write,
                    String.Format("write via content derived from '{0}'", controlledAddress)
                    );

                InheritParameterState(context.CurrentViolation, v);

                context.AttackerFavorsAssumeTrue(AssumptionName.CanTriggerMemoryWrite);

                return(v);
            };

            Update(constraints, nextViolation, onSuccess);
        }
예제 #25
0
        public CodeExecutionPrimitive(
            string name = "execute code",
            MemoryAddress codeExecutionAddress = null,
            Expression <Func <SimulationContext, bool> > constraints = null,
            GetNextViolationDelegate nextViolation       = null,
            PrimitiveTransitionSuccessDelegate onSuccess = null
            )
            : base(ExploitationPrimitiveType.ExecuteToExecute, "code_execution", name)
        {
            this.CodeExecutionAddress = codeExecutionAddress;

            this.ConstraintList.Add(
                (context) =>
                (
                    (context.AttackerFavorsEqual(context.CurrentViolation.Method, MemoryAccessMethod.Execute) == true)

                    &&

                    (context.AttackerFavorsEqual(context.CurrentViolation.Address, this.CodeExecutionAddress) == true)

                    &&

                    (context.CanFindAddress(this.CodeExecutionAddress) == true)

                    &&

                    (context.CanExecuteMemoryAtAddress(this.CodeExecutionAddress) == true)
                )
                );

            Update(constraints, nextViolation, onSuccess);
        }
예제 #26
0
 /// <summary>
 /// Model built from separately passed parameters
 /// </summary>
 /// <param name="number">Processor number</param>
 /// <param name="isStopped">Whether or not processor is stopped</param>
 /// <param name="dataToRead">Current processor read request</param>
 /// <param name="dataToWrite">Current processor write request</param>
 public ProcessorModel(int number, bool isStopped, MemoryAddress dataToRead, MemoryAddress dataToWrite)
 {
     this.number      = number;
     this.isStopped   = isStopped;
     this.dataToRead  = dataToRead;
     this.dataToWrite = dataToWrite;
 }
예제 #27
0
        public InitializeDestinationContentPrimitive(
            string name = "initialize content at destination address of write",
            MemoryAddress destinationAddress           = null,
            MemoryAccessParameterState newContentState = MemoryAccessParameterState.Controlled,
            Expression <Func <SimulationContext, bool> > constraints = null,
            PrimitiveTransitionSuccessDelegate onSuccess             = null
            )
            : base(ExploitationPrimitiveType.Identity, "initialize_destination_content", name)
        {
            this.DestinationAddress = destinationAddress;
            this.NewContentState    = newContentState;

            this.ConstraintList.Add(
                (context) =>
                (
                    (context.Global.AssumeContentInitializationPossible == false)

                    &&

                    (context.AttackerFavorsEqual(context.CurrentViolation.Method, MemoryAccessMethod.Write) == true)

                    &&

                    (
                        (context.AttackerFavorsEqual(context.CurrentViolation.ContentDstState, MemoryAccessParameterState.Uninitialized) == true)

                        ||

                        (context.AttackerFavorsEqual(context.CurrentViolation.ContentDstState, MemoryAccessParameterState.Unknown) == true)
                    )

                    &&

                    (context.AttackerFavorsEqual(context.CurrentViolation.Address, this.DestinationAddress) == true)

                    &&

                    (context.CanCorruptMemoryAtAddress(this.DestinationAddress) == true)
                )
                );

            this.NextViolationDelegate = (context) =>
            {
                Violation v = context.CurrentViolation.CloneViolation();

                v.ContentDstState = this.NewContentState;

                v.Address = this.DestinationAddress;

                return(v);
            };

            this.OnSuccess += onSuccess;

            if (constraints != null)
            {
                this.ConstraintList.Add(constraints);
            }
        }
예제 #28
0
 public override dynamic Run(dynamic data)
 {
     if (TickCount < 2)
     {
         if (TickCount == 0)
         {
             value      = data;
             DataToRead = new MemoryAddress("MatrixB", column + num * size);
             return(null);
         }
         else
         {
             DataToWrite = new MemoryAddress("temp" + clusterNumber.ToString(), num);
             DataToRead  = new MemoryAddress("temp" + clusterNumber.ToString(), num);
             return(value * data);
         }
     }
     else
     {
         if (num + (int)Math.Pow(2, TickCount - 3) < size)
         {
             sum += data;
         }
         // If first processor should work
         if ((int)Math.Pow(2, TickCount - 2) < size)
         {
             // If any other processor should work
             if (num % Math.Pow(2, TickCount - 1) == 0)
             {
                 if (num + (int)Math.Pow(2, TickCount - 2) < size)
                 {
                     this.DataToRead = new MemoryAddress("temp" + clusterNumber.ToString(),
                                                         num + (int)Math.Pow(2, TickCount - 2));
                 }
                 else
                 {
                     this.DataToRead = new MemoryAddress();
                 }
                 this.DataToWrite = new MemoryAddress("temp" + clusterNumber.ToString(), num);
                 return(sum);
             }
             else
             {
                 Stop();
                 this.DataToWrite = new MemoryAddress();
                 return(sum);
             }
         }
         else
         {
             if (num == 0)
             {
                 DataToWrite = new MemoryAddress("MatrixC", clusterNumber);
             }
             Stop();
             return(sum);
         }
     }
 }
예제 #29
0
파일: RAM.cs 프로젝트: sdzxwxlsj/lsjutil
 public ushort GetWord(MemoryAddress address)
 {
     if (address.Value + 1 <= ram.Length)
     {
         return (ushort)(ram[address.Value] << 8 + ram[address.Value + 1]);
     }
     throw new IndexOutOfRangeException();
 }
예제 #30
0
        internal static EntryPoint Make(String execStartName, String entryName, UInt16 execStartAddressValue)
        {
            EntryPoint    entryPoint       = Make(execStartName, entryName);
            MemoryAddress execStartAddress = new MemoryAddress(execStartAddressValue);

            entryPoint.SetExecStartAddressForUnitTest(execStartAddress);
            return(entryPoint);
        }
예제 #31
0
파일: RAM.cs 프로젝트: sdzxwxlsj/lsjutil
 public byte GetByte(MemoryAddress address)
 {
     if (address.Value <= ram.Length)
     {
         return ram[address.Value];
     }
     throw new IndexOutOfRangeException();
 }
예제 #32
0
파일: RAM.cs 프로젝트: sdzxwxlsj/lsjutil
 public void SetByte(MemoryAddress address, byte x)
 {
     if (address.Value <= ram.Length)
     {
         ram[address.Value] = x;
     }
     throw new IndexOutOfRangeException();
 }
예제 #33
0
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="address">
        /// The memory address for the comparison.
        /// </param>
        /// <param name="comparison">
        /// The value to which the memory address is compared.
        /// </param>
        /// <param name="trueValue">
        /// The resultant value, if the comparison is true.
        /// </param>
        public AutoTrackAddressBool(MemoryAddress address, byte comparison, int trueValue)
        {
            _address    = address ?? throw new ArgumentNullException(nameof(address));
            _comparison = comparison;
            _trueValue  = trueValue;

            _address.PropertyChanged += OnMemoryChanged;
        }
예제 #34
0
파일: RAM.cs 프로젝트: sdzxwxlsj/lsjutil
 public void SetWord(MemoryAddress address, ushort x)
 {
     if (address.Value + 1 <= ram.Length)
     {
         ram[address.Value] = (byte)(x >> 8);
         ram[address.Value + 1] = (byte)(x);
     }
     throw new IndexOutOfRangeException();
 }
예제 #35
0
 void MOV(MemoryAddress address, ushort x)
 {
     this.machine.RAM.SetWord(address,x);
 }
예제 #36
0
 void MOV(eRegister16 a ,MemoryAddress address)
 {
     MOV(a, this.machine.RAM.GetWord(address));
 }
예제 #37
0
 public FluentWriter RM(Register destination, MemoryAddress sourceAddress)
 {
     var instruction = new Instruction(_opCode).Destination(destination).Source(sourceAddress);
     _parent._codeStream.Add(instruction);
     return _parent;
 }
예제 #38
0
 public FluentWriter MU(MemoryAddress destinationAddress, uint value)
 {
     var instruction = new Instruction(_opCode).Destination(destinationAddress).Source(value);
     _parent._codeStream.Add(instruction);
     return _parent;
 }
예제 #39
0
 FluentWriter IFluentSourceInstructionWriter.M(MemoryAddress memoryAddress)
 {
     var instruction = new Instruction(_opCode).Destination(memoryAddress);
     _parent._codeStream.Add(instruction);
     return _parent;
 }
예제 #40
0
 void MOV(eRegister8 a, MemoryAddress address)
 {
     MOV(a, this.machine.RAM.GetByte(address));
 }
예제 #41
0
 private byte[] ReadAddress(MemoryAddress addess, int size)
 {
     IntPtr processHandle = Win32.OpenProcess(Win32.ProcessAccessFlags.VMRead, false, _process.Id);
     int bytesRead = 0;
     byte[] buffer = new byte[size];
     Win32.ReadProcessMemory((int)processHandle, (int)addess, buffer, buffer.Length, ref bytesRead);
     //ulong result = Misc.ConvertoToULong(buffer);
     return buffer;
 }
예제 #42
0
        void MOV(MemoryAddress address, eRegister16 x)
        {
            switch (x)
            {
                case eRegister16.AX:
                    MOV(address, AX);
                    break;
                case eRegister16.BX:
                    MOV(address, BX);
                    break;
                case eRegister16.CX:
                    MOV(address, CX);
                    break;
                case eRegister16.DX:
                    MOV(address, DX);
                    break;
                case eRegister16.DI:
                    MOV(address, DI);
                    break;
                case eRegister16.SI:
                    MOV(address, SI);
                    break;
                case eRegister16.BP:
                    MOV(address, BP);
                    break;
                case eRegister16.SP:
                    MOV(address, SP);
                    break;
                case eRegister16.DS:
                    MOV(address, DS);
                    break;
                case eRegister16.SS:
                    MOV(address, SS);
                    break;
                case eRegister16.ES:
                    MOV(address, ES);
                    break;
                case eRegister16.CS:
                    MOV(address, CS);
                    break;

                default:
                    throw new InvalidOperationException();
            }
        }
예제 #43
0
 void MOV(MemoryAddress address, byte x)
 {
     this.machine.RAM.SetByte(address, x);
 }