Exemplo n.º 1
0
        private CompilerOptimizedSwitchByStringStatement ComposeSwitch(SwitchData data)
        {
            CompilerOptimizedSwitchByStringStatement @switch = new CompilerOptimizedSwitchByStringStatement(data.SwitchExpression, data.SwitchExpressionLoadInstructions);

            foreach (KeyValuePair <Expression, BlockStatement> pair in data.CaseConditionToBlockMap)
            {
                if (pair.Value != null && SwitchHelpers.BlockHasFallThroughSemantics(pair.Value))
                {
                    pair.Value.AddStatement(new BreakSwitchCaseStatement());
                }

                @switch.AddCase(new ConditionCase(pair.Key, pair.Value));
            }

            if (data.HaveDefaultCase)
            {
                if (SwitchHelpers.BlockHasFallThroughSemantics(data.DefaultCase))
                {
                    data.DefaultCase.AddStatement(new BreakSwitchCaseStatement());
                }

                @switch.AddCase(new DefaultCase(data.DefaultCase));
            }

            return(@switch);
        }
Exemplo n.º 2
0
        /// <summary>
        /// 动画进行中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void animationTimer_AnimationIng(object sender, AnimationEventArgs e)
        {
            SwitchData sd = (SwitchData)e.Data;

            if (sd.target_status == SwitchStatus.ON)
            {
                switchSlide.slide_current.X = (float)(sd.slide.slide_prepare.X + (sd.slide.slide_on.X - sd.slide.slide_prepare.X) * e.progressTime);
            }
            else
            {
                switchSlide.slide_current.X = (float)(sd.slide.slide_prepare.X - (sd.slide.slide_prepare.X - sd.slide.slide_off.X) * e.progressTime);
            }
            if (Type == SwitchType.RoundnessIn)
            {
                if (sd.target_status == SwitchStatus.ON)
                {
                    switchSlide.slide_current.Y      = (float)(sd.slide.slide_prepare.Y + (sd.slide.slide_on.Y - sd.slide.slide_prepare.Y) * e.progressTime);
                    switchSlide.slide_current.Width  = (float)(switchSlide.slide_prepare.Width + (sd.slide.slide_on.Width - sd.slide.slide_prepare.Width) * e.progressTime);
                    switchSlide.slide_current.Height = switchSlide.slide_current.Width;
                }
                else
                {
                    switchSlide.slide_current.Y      = (float)(sd.slide.slide_prepare.Y - (sd.slide.slide_prepare.Y - sd.slide.slide_off.Y) * e.progressTime);
                    switchSlide.slide_current.Width  = (float)(switchSlide.slide_prepare.Width - (sd.slide.slide_prepare.Width - sd.slide.slide_off.Width) * e.progressTime);
                    switchSlide.slide_current.Height = switchSlide.slide_current.Width;
                }
            }
            this.Invalidate();
        }
        private bool TryGetSwitchData(IList <Expression> expressions, out SwitchData data)
        {
            data = null;

            if (expressions.Count < 2 ||
                expressions[expressions.Count - 2].CodeNodeType != CodeNodeType.BinaryExpression)
            {
                return(false);
            }

            BinaryExpression binary = expressions[expressions.Count - 2] as BinaryExpression;

            if (!binary.IsAssignmentExpression)
            {
                return(false);
            }

            if (binary.Left.CodeNodeType != CodeNodeType.VariableReferenceExpression ||
                binary.Right.CodeNodeType != CodeNodeType.MethodInvocationExpression)
            {
                return(false);
            }

            MethodInvocationExpression methodInvocation = binary.Right as MethodInvocationExpression;

            if (methodInvocation.MethodExpression.Method.FullName != ComputeStringHashFullName)
            {
                return(false);
            }

            data = new SwitchData((binary.Left as VariableReferenceExpression).Variable, methodInvocation.Arguments[0]);
            return(true);
        }
Exemplo n.º 4
0
        /// <summary>
        ///   <para>SwitchController를 Dictionary에 추가</para>
        /// </summary>
        public void RegisterSwitch(SwitchController switchController)
        {
            if (switchController.IsRegistered)
            {
                return;
            }

            var switchId = switchController.SwitchId;

            if (!_switchDataDic.TryGetValue(switchId, out var switchData))
            {
                //스위치 데이터 생성
                switchData = SwitchData.CreateSwitchData(switchId);
                if (switchData == null)
                {
                    return;
                }

                switchData.Action = switchController.OnSwitch;
                _switchDataDic.Add(switchController.SwitchId, switchData);
            }
            else
            {
                _switchDataDic[switchController.SwitchId].Action += switchController.OnSwitch;
            }

            switchController.IsRegistered = true;

//            AddRequireUpdatingSwitchIdList(switchId);
            switchController.OnSwitch(switchData.CurrentResult);
        }
Exemplo n.º 5
0
 public Switch(GameContext context, SwitchData data, Entity entity, Gear item)
 {
     _data   = data;
     Entity  = entity;
     Item    = item;
     Context = context;
 }
Exemplo n.º 6
0
        public FlowSample(byte[] buffer) : base(buffer)
        {
            SamplingRate    = buffer.ToUInt(16, 4);
            SamplingPool    = buffer.ToUInt(20, 4);
            DroppedPackets  = buffer.ToUInt(24, 4);
            InputInterface  = buffer.ToUInt(28, 4).ToSflowInterface();
            OutputInterface = buffer.ToUInt(32, 4).ToSflowInterface();
            uint records = buffer.ToUInt(36, 4);

            Records = new FlowRecord[records];
            uint recordStartIndex = 40;

            for (uint i = 0; i < Records.Length; i++)
            {
                FlowRecord record       = new FlowRecord(buffer.AsSpan((int)recordStartIndex, (int)Record.HeaderLengthBytes).ToArray());
                int        recordLength = (int)(record.Length + Record.HeaderLengthBytes);
                if (record.Type == RecordType.RawPacketHeader)
                {
                    record = new RawPacketHeader(buffer.AsSpan((int)recordStartIndex, recordLength).ToArray());
                }
                else if (record.Type == RecordType.ExtSwitchData)
                {
                    record = new SwitchData(buffer.AsSpan((int)recordStartIndex, recordLength).ToArray());
                }
                recordStartIndex += (uint)recordLength;
                Records[i]        = record;
            }
        }
Exemplo n.º 7
0
        private int?CalculateKey(SwitchData switchData)
        {
            var popValue = _instructionEmulator.Peek();

            if (popValue == null || !popValue.IsInt32() || !(popValue as Int32Value).AllBitsValid())
            {
                return(null);
            }

            _instructionEmulator.Pop();
            int num = ((Int32Value)popValue).Value;

            if (switchData is NativeSwitchData)
            {
                var nativeSwitchData = (NativeSwitchData)switchData;
                //var nativeMethod = new X86Method(nativeSwitchData.NativeMethodDef, _blocks.Method.Module as ModuleDefMD); //TODO: Possible null
                //return nativeMethod.Execute(num);
                return((int?)_nativeEmulator.Emulate(nativeSwitchData.NativeMethodDef, num));
            }
            if (switchData is NormalSwitchData)
            {
                var normalSwitchData = (NormalSwitchData)switchData;
                return(num ^ normalSwitchData.Key.Value);
            }
            return(null);
        }
Exemplo n.º 8
0
 private bool DetermineExceptionHandlingStatesFromSwitchData(SwitchData switchBlockInfo)
 {
     V_0 = 0;
     V_1 = switchBlockInfo.get_SwitchBlock().get_Last().get_Previous();
     if (V_1.get_OpCode().get_Code() == 88)
     {
         V_1 = V_1.get_Previous();
         if (!StateMachineUtilities.TryGetOperandOfLdc(V_1, out V_0))
         {
             return(false);
         }
         V_1 = V_1.get_Previous();
     }
     V_2 = switchBlockInfo.get_OrderedCasesArray();
     V_4 = 0;
     while (V_4 < (int)V_2.Length)
     {
         if (this.TryGetExceptionHandler(this.GetActualCase(V_2[V_4]), out V_6))
         {
             if (!this.handlerToStatesMap.ContainsKey(V_6))
             {
                 this.handlerToStatesMap.Add(V_6, new HashSet <int>());
             }
             dummyVar0 = this.handlerToStatesMap.get_Item(V_6).Add(V_4 + V_0);
         }
         V_4 = V_4 + 1;
     }
     return(true);
 }
 public StateMachineCFGCleaner(ControlFlowGraph theCFG, SwitchData controllerSwitchData, InstructionBlock newEntryBlock)
 {
     base();
     this.theCFG = theCFG;
     this.controllerSwitchData = controllerSwitchData;
     this.newEntryBlock        = newEntryBlock;
     return;
 }
        protected override bool ProcessCFG()
        {
            StateMachineDisposeAnalyzer disposeAnalyzer = new StateMachineDisposeAnalyzer(moveNextMethodContext.Method);
            StateControllerRemover      controllerRemover;
            YieldStateMachineVersion    machineVersion = disposeAnalyzer.ProcessDisposeMethod();

            if (machineVersion == YieldStateMachineVersion.V1)
            {
                controllerRemover = new StateControllerRemover(moveNextMethodContext);
            }
            else if (machineVersion == YieldStateMachineVersion.V2)
            {
                controllerRemover = new DisposingStateControllerRemover(moveNextMethodContext, disposeAnalyzer.StateField, disposeAnalyzer.DisposingField);
                StateMachineDoFinallyCheckRemover doFinallyCheckRemover = new StateMachineDoFinallyCheckRemover(moveNextMethodContext);
                if (!doFinallyCheckRemover.MarkFinallyConditionsForRemoval())
                {
                    return(false);
                }
                toBeRemoved.UnionWith(doFinallyCheckRemover.BlocksMarkedForRemoval);
            }
            else
            {
                return(false);
            }

            if (!controllerRemover.RemoveStateMachineController())
            {
                return(false);
            }

            toBeRemoved.UnionWith(controllerRemover.BlocksMarkedForRemoval);

            SwitchData switchData = controllerRemover.SwitchData;
            YieldStateMachineControlFlowRebuilder controlFlowRebuilder =
                new YieldStateMachineControlFlowRebuilder(moveNextMethodContext, switchData, controllerRemover.StateField);

            if (!controlFlowRebuilder.ProcessEndBlocks())
            {
                return(false);
            }

            toBeRemoved.UnionWith(controlFlowRebuilder.BlocksMarkedForRemoval);
            StateMachineCFGCleaner cfgCleaner = new StateMachineCFGCleaner(theCFG, switchData, switchData.OrderedCasesArray[0]);

            if (!cfgCleaner.CleanUpTheCFG(toBeRemoved))
            {
                return(false);
            }

            YieldFieldsInformation fieldsInfo = new YieldFieldsInformation(controllerRemover.StateField,
                                                                           controlFlowRebuilder.CurrentItemField, controlFlowRebuilder.ReturnFlagVariable);

            this.moveNextMethodContext.YieldData =
                new YieldData(machineVersion, controlFlowRebuilder.YieldReturnBlocks,
                              controlFlowRebuilder.YieldBreakBlocks, fieldsInfo, disposeAnalyzer.YieldsExceptionData);
            return(true);
        }
 private bool CreateFakeSwitchData(out SwitchData switchData)
 {
     if (!this.GetMethodEntry(out V_0))
     {
         switchData = null;
         return(false);
     }
     switchData = new SwitchData(null, V_0, new InstructionBlock[0]);
     return(true);
 }
Exemplo n.º 12
0
 public YieldStateMachineControlFlowRebuilder(MethodSpecificContext moveNextMethodContext, SwitchData controllerSwitchData, FieldDefinition stateField)
 {
     this.yieldBreaks  = new HashSet <InstructionBlock>();
     this.yieldReturns = new HashSet <InstructionBlock>();
     this.toBeRemoved  = new HashSet <InstructionBlock>();
     base();
     this.moveNextMethodContext = moveNextMethodContext;
     this.switchData            = controllerSwitchData;
     this.stateField            = stateField;
     return;
 }
Exemplo n.º 13
0
        /// <summary>
        /// Creates a fake switch data for the CFG cleaner.
        /// </summary>
        /// <remarks>
        /// In async methods without await there is no state controller blocks. In these cases switch data cannot be created by the state controller remover.
        /// Thats why we create a fake switch data which contains only the default case, which will later become the entry of the method.
        /// </remarks>
        /// <returns></returns>
        private bool CreateFakeSwitchData(out SwitchData switchData)
        {
            InstructionBlock defaultCase;

            if (!GetMethodEntry(out defaultCase))
            {
                switchData = null;
                return(false);
            }

            switchData = new SwitchData(null, defaultCase, new InstructionBlock[0]);
            return(true);
        }
Exemplo n.º 14
0
        private void CreateSwitchConstruct(CFGBlockLogicalConstruct switchBlock, ILogicalConstruct parentConstruct,
                                           SwitchData switchData, DominatorTree dominatorTree)
        {
            List <KeyValuePair <CFGBlockLogicalConstruct, List <int> > >    cfgSuccessorToLabelsMap           = GetOrderedCFGSuccessorToLabelsMap(switchData);
            Dictionary <ILogicalConstruct, HashSet <ISingleEntrySubGraph> > validCaseEntryToDominatedNodesMap = GetValidCases(dominatorTree, switchBlock);

            List <CaseLogicalConstruct> orderedCaseConstructs = new List <CaseLogicalConstruct>();
            PairList <List <int>, CFGBlockLogicalConstruct> labelsToCFGSuccessorsList = new PairList <List <int>, CFGBlockLogicalConstruct>();

            foreach (KeyValuePair <CFGBlockLogicalConstruct, List <int> > cfgSuccessorToLabelsPair in cfgSuccessorToLabelsMap)
            {
                ILogicalConstruct successor;
                HashSet <ISingleEntrySubGraph> dominatedNodes;
                if (LogicalFlowUtilities.TryGetParentConstructWithGivenParent(cfgSuccessorToLabelsPair.Key, parentConstruct, out successor) &&
                    validCaseEntryToDominatedNodesMap.TryGetValue(successor, out dominatedNodes))
                {
                    CaseLogicalConstruct newCaseConstruct = new CaseLogicalConstruct(successor);
                    newCaseConstruct.CaseNumbers.AddRange(cfgSuccessorToLabelsPair.Value);
                    newCaseConstruct.Body.UnionWith(dominatedNodes.Cast <ILogicalConstruct>());
                    newCaseConstruct.AttachCaseConstructToGraph();
                    orderedCaseConstructs.Add(newCaseConstruct);
                }
                else
                {
                    labelsToCFGSuccessorsList.Add(cfgSuccessorToLabelsPair.Value, cfgSuccessorToLabelsPair.Key);
                }
            }

            CaseLogicalConstruct           defaultCase         = null;
            CFGBlockLogicalConstruct       defaultCFGSuccessor = GetCFGLogicalConstructFromBlock(switchData.DefaultCase);
            ILogicalConstruct              defaultSuccessor;
            HashSet <ISingleEntrySubGraph> defaultCaseNodes;

            if (LogicalFlowUtilities.TryGetParentConstructWithGivenParent(defaultCFGSuccessor, parentConstruct, out defaultSuccessor) &&
                validCaseEntryToDominatedNodesMap.TryGetValue(defaultSuccessor, out defaultCaseNodes))
            {
                defaultCase = new CaseLogicalConstruct(defaultSuccessor);
                if (HasSuccessors(defaultCaseNodes))
                {
                    defaultCase.Body.UnionWith(defaultCaseNodes.Cast <ILogicalConstruct>());
                }
                defaultCase.AttachCaseConstructToGraph();
            }

            SwitchLogicalConstruct theSwitch = SwitchLogicalConstruct.GroupInSwitchConstruct(switchBlock, orderedCaseConstructs, labelsToCFGSuccessorsList, defaultCase, defaultCFGSuccessor);

            UpdateDominatorTree(dominatorTree, theSwitch);
        }
Exemplo n.º 15
0
 public void Load(SwitchData data)
 {
     /* (int i = 0; i < ports.Count; i++)
      * {
      *  ports[i].Load(data.ports[i]);
      * }
      * macTable = data.mactable;*/
     numFEPorts = data.numFEPorts;
     numGPorts  = data.numGPorts;
     vlans      = data.vlanmaps;
     //update vlans
     for (int i = 0; i < ports.Count; i++)
     {
         ports[i].ChangeVLAN(vlans[i]);
     }
 }
Exemplo n.º 16
0
        private int?CalculateSwitchCaseIndex(Block block, SwitchData switchData, int key)
        {
            if (switchData is NativeSwitchData)
            {
                _instructionEmulator.Push(new Int32Value(key));
                _instructionEmulator.Emulate(block.Instructions, block.SwitchData.IsKeyHardCoded ? 2 : 1, block.Instructions.Count - 1);

                var popValue = _instructionEmulator.Peek();
                _instructionEmulator.Pop();
                return(((Int32Value)popValue).Value);
            }
            if (switchData is NormalSwitchData)
            {
                var normalSwitchData = (NormalSwitchData)switchData;
                return(key % normalSwitchData.DivisionKey);
            }
            return(null);
        }
Exemplo n.º 17
0
    public SwitchData Save()
    {
        SwitchData data = new SwitchData();

        if (vlans.Count != 0)
        {
            vlans.Clear();
        }

        for (int i = 0; i < ports.Count; i++)
        {
            vlans.Add(ports[i].link.vlan);
        }
        data.numGPorts  = numGPorts;
        data.numFEPorts = numFEPorts;
        data.vlanmaps   = vlans;
        return(data);
    }
    // Use this for initialization
    void Start()
    {
#if UNITY_EDITOR
        //json test file path
        string path = Application.streamingAssetsPath + "/switchTest.json";

        //read in file and store json text
        StreamReader jsonString = new StreamReader(new FileStream(path, FileMode.Open));

        //deserialize jsonString and store key-values in new instance of SwitchTelemtry
        SwitchData switchData = new SwitchData();

        switchData = JsonUtility.FromJson <SwitchData>(jsonString.ReadToEnd());

        switchData.printSet();

        jsonString.Dispose();
#endif
    }
Exemplo n.º 19
0
        private bool TryGetSwitchData(IfElseIfStatement node, out SwitchData data)
        {
            data = new SwitchData();

            foreach (KeyValuePair <Expression, BlockStatement> pair in node.ConditionBlocks)
            {
                if (!TryMatchCondition(pair.Key, pair.Value, data))
                {
                    return(false);
                }
            }

            if (node.Else != null)
            {
                data.DefaultCase = node.Else;
            }

            return(true);
        }
        /// <summary>
        /// Creates the controller switch data using the information gathered during the traversal of the state controller blocks.
        /// </summary>
        private void CreateControllerSwitchData()
        {
            int index = GetIndexOfLastNonNullElement(stateToStartBlock);

            InstructionBlock[] finalCasesArray = new InstructionBlock[++index];
            //Trim the excess elements of the cases array.
            for (int i = 0; i < index; i++)
            {
                if (stateToStartBlock[i] == null)
                {
                    finalCasesArray[i] = defaultStateEntry;
                }
                else
                {
                    finalCasesArray[i] = stateToStartBlock[i];
                }
            }

            this.switchData = new SwitchData(null, defaultStateEntry, finalCasesArray);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Process each switch block to determine which cases lead to try/finally constructs.
        /// </summary>
        /// <param name="switchBlockInfo"></param>
        private bool DetermineExceptionHandlingStatesFromSwitchData(SwitchData switchBlockInfo)
        {
            //Since the first try/finally that this switch covers can start at state 20, the complier will optimize this by subtracting 20 from the value of
            //the state field.
            int         stateOffset        = 0;
            Instruction currentInstruction = switchBlockInfo.SwitchBlock.Last.Previous;

            if (currentInstruction.OpCode.Code == Code.Sub)
            {
                currentInstruction = currentInstruction.Previous;
                if (!StateMachineUtilities.TryGetOperandOfLdc(currentInstruction, out stateOffset))
                {
                    return(false);
                }

                currentInstruction = currentInstruction.Previous;
            }

            InstructionBlock[] orderedCases = switchBlockInfo.OrderedCasesArray;
            for (int i = 0; i < orderedCases.Length; i++)
            {
                InstructionBlock currentCase = GetActualCase(orderedCases[i]);

                ExceptionHandler theHandler;
                if (!TryGetExceptionHandler(currentCase, out theHandler))
                {
                    continue;
                }

                //We've found an exception handler.

                if (!this.handlerToStatesMap.ContainsKey(theHandler))
                {
                    this.handlerToStatesMap.Add(theHandler, new HashSet <int>());
                }

                this.handlerToStatesMap[theHandler].Add(i + stateOffset);
            }

            return(true);
        }
Exemplo n.º 22
0
        /// <summary>
        /// There are 2 types is conditions:
        /// - Simple condition - that's when the condition is composed from unary expression with "None" operator
        ///   containing a binary expression with the actual string comparison.
        /// - Complex condition - that's when there are 2 or more simple conditions OR'd in binary expressions.
        ///   If we have 3 or more conditions, the complex ones will be always at the left hand side, e.g.
        ///                         Binary
        ///             Binary---------|---------Unary
        ///     Binary-----|-----Unary
        /// Unary--|--Unary
        /// </summary>
        private bool TryMatchCondition(Expression condition, BlockStatement block, SwitchData data)
        {
            if (condition.CodeNodeType != CodeNodeType.UnaryExpression &&
                condition.CodeNodeType != CodeNodeType.BinaryExpression)
            {
                return(false);
            }

            BinaryExpression binary;

            if (condition.CodeNodeType == CodeNodeType.BinaryExpression)
            {
                binary = condition as BinaryExpression;
                if (binary.Operator == BinaryOperator.LogicalOr)
                {
                    // Basically a DFS, which will result in traversing the unary expressions in left to right order.
                    if (TryMatchCondition(binary.Left, null, data) &&
                        TryMatchCondition(binary.Right, null, data))
                    {
                        // If this is the top BinaryExpression of the complex condition
                        if (block != null)
                        {
                            // We replace the last condition with one with the block for the complex condition.
                            int        lastIndex     = data.CaseConditionToBlockMap.Count - 1;
                            Expression lastCondition = data.CaseConditionToBlockMap[lastIndex].Key;
                            data.CaseConditionToBlockMap[lastIndex] = new KeyValuePair <Expression, BlockStatement>(lastCondition, block);
                        }

                        return(true);
                    }

                    return(false);
                }
            }
            else
            {
                UnaryExpression unary = condition as UnaryExpression;
                if (unary.Operator != UnaryOperator.None ||
                    unary.Operand.CodeNodeType != CodeNodeType.BinaryExpression)
                {
                    return(false);
                }

                binary = unary.Operand as BinaryExpression;
            }

            if (binary.Right.CodeNodeType != CodeNodeType.LiteralExpression ||
                binary.Operator != BinaryOperator.ValueEquality)
            {
                return(false);
            }

            LiteralExpression literal = binary.Right as LiteralExpression;

            if (condition.CodeNodeType == CodeNodeType.UnaryExpression &&
                literal.ExpressionType.FullName != "System.String")
            {
                return(false);
            }
            else if (condition.CodeNodeType == CodeNodeType.BinaryExpression &&
                     (literal.ExpressionType.FullName != "System.Object" ||
                      literal.Value != null))
            {
                return(false);
            }

            if (data.SwitchExpression == null)
            {
                data.SwitchExpression = binary.Left;
            }
            else if (!data.SwitchExpression.Equals(binary.Left))
            {
                return(false);
            }
            else
            {
                data.SwitchExpressionLoadInstructions.Add(binary.Left.UnderlyingSameMethodInstructions.First().Offset);
            }

            data.CaseConditionToBlockMap.Add(new KeyValuePair <Expression, BlockStatement>(literal, block));

            return(true);
        }
Exemplo n.º 23
0
 public YieldStateMachineControlFlowRebuilder(MethodSpecificContext moveNextMethodContext, SwitchData controllerSwitchData, FieldDefinition stateField)
 {
     this.moveNextMethodContext = moveNextMethodContext;
     this.switchData            = controllerSwitchData;
     this.stateField            = stateField;
 }
Exemplo n.º 24
0
        private PairList <CFGBlockLogicalConstruct, List <int> > GetOrderedCFGSuccessorToLabelsMap(SwitchData switchData)
        {
            //Ugly but effective. Sorry
            PairList <CFGBlockLogicalConstruct, List <int> > result = new PairList <CFGBlockLogicalConstruct, List <int> >();
            Dictionary <InstructionBlock, KeyValuePair <int, List <int> > > blockSuccessorToResultPositionMap =
                new Dictionary <InstructionBlock, KeyValuePair <int, List <int> > >();

            for (int i = 0; i < switchData.OrderedCasesArray.Length; i++)
            {
                InstructionBlock instructionBlock = switchData.OrderedCasesArray[i];
                if (instructionBlock != switchData.DefaultCase)
                {
                    KeyValuePair <int, List <int> > positionToLabelListPair;
                    if (!blockSuccessorToResultPositionMap.TryGetValue(instructionBlock, out positionToLabelListPair))
                    {
                        positionToLabelListPair = new KeyValuePair <int, List <int> >(result.Count, new List <int>());

                        result.Add(GetCFGLogicalConstructFromBlock(instructionBlock), positionToLabelListPair.Value);

                        blockSuccessorToResultPositionMap.Add(instructionBlock, positionToLabelListPair);
                    }
                    positionToLabelListPair.Value.Add(i);
                }
            }

            return(result);
        }
        /// <summary>
        /// Removes the chain of blocks that represents the state machine controller.
        /// </summary>
        /// <remarks>
        /// The idea is to remove the chain and to create a fake switch data that represents the state machine controller.
        /// </remarks>
        protected bool RemoveControllerChain()
        {
            Queue <InstructionBlock> controllerTraversalQueue = InitializeTheTraversalQueue();

            while (controllerTraversalQueue.Count > 0)
            {
                InstructionBlock initialBlock = controllerTraversalQueue.Dequeue();
                InstructionBlock currentBlock = initialBlock;
                int stateNumber;
                StateMachineControllerType controllerType;
                while (IsStateMachineControllerBlock(ref currentBlock, out controllerType, out stateNumber))
                {
                    switch (controllerType)
                    {
                    case StateMachineControllerType.Switch:
                    {
                        InstructionBlock   actualSuccessor;
                        SwitchData         switchData       = theCFG.SwitchBlocksInformation[currentBlock];
                        InstructionBlock[] switchCasesArray = switchData.OrderedCasesArray;
                        for (int i = 0; i < switchCasesArray.Length; i++)
                        {
                            if (toBeRemoved.Contains(switchCasesArray[i]))
                            {
                                continue;
                            }


                            switch (TryGetStateEntry(switchCasesArray[i], out actualSuccessor))
                            {
                            case ControllerTraversalSearchResult.FoundStateEntry:
                                stateToStartBlock[i + stateNumber] = actualSuccessor;
                                break;

                            case ControllerTraversalSearchResult.FoundControllerCandidate:
                                stateToStartBlock[i + stateNumber] = actualSuccessor;
                                controllerTraversalQueue.Enqueue(actualSuccessor);
                                break;

                            case ControllerTraversalSearchResult.PatternFailed:
                                return(false);
                            }
                        }

                        controllerTraversalQueue.Enqueue(SkipBranchChain(switchData.DefaultCase));
                        break;
                    }

                    case StateMachineControllerType.Condition:
                    {
                        InstructionBlock actualSuccessor;
                        switch (TryGetStateEntry(currentBlock.Successors[0], out actualSuccessor))
                        {
                        case ControllerTraversalSearchResult.FoundStateEntry:
                            stateToStartBlock[stateNumber] = actualSuccessor;
                            break;

                        case ControllerTraversalSearchResult.FoundControllerCandidate:
                            stateToStartBlock[stateNumber] = actualSuccessor;
                            controllerTraversalQueue.Enqueue(actualSuccessor);
                            break;

                        case ControllerTraversalSearchResult.PatternFailed:
                            return(false);
                        }
                        break;
                    }

                    case StateMachineControllerType.NegativeCondition:
                    {
                        InstructionBlock actualSuccessor;
                        int successorIndex = 1;
                        if (stateNumber == -1)
                        {
                            stateNumber    = 0;
                            successorIndex = 0;
                        }

                        switch (TryGetStateEntry(currentBlock.Successors[successorIndex], out actualSuccessor))
                        {
                        case ControllerTraversalSearchResult.FoundStateEntry:
                        case ControllerTraversalSearchResult.FoundControllerCandidate:
                            stateToStartBlock[stateNumber] = actualSuccessor;
                            break;

                        case ControllerTraversalSearchResult.PatternFailed:
                            return(false);
                        }
                        break;
                    }
                    }

                    toBeRemoved.Add(currentBlock);
                    if (controllerType == StateMachineControllerType.NegativeCondition)
                    {
                        currentBlock = currentBlock.Successors[0];
                    }
                    else
                    {
                        currentBlock = currentBlock.Successors[currentBlock.Successors.Length - 1];
                    }

                    currentBlock = SkipBranchChain(currentBlock);
                }

                if (defaultStateEntry == null)
                {
                    defaultStateEntry = currentBlock;
                }

                ReattachDefaultSuccessor(initialBlock, currentBlock); //Redirect the predecessors of the first controller block to it's default successor

                while (controllerTraversalQueue.Count > 0 && toBeRemoved.Contains(controllerTraversalQueue.Peek()))
                {
                    controllerTraversalQueue.Dequeue();
                }
            }

            if (toBeRemoved.Count == 0)
            {
                return(false);
            }

            CreateControllerSwitchData();
            return(true);
        }
Exemplo n.º 26
0
        public Iso8583Message ProcessMessage(Iso8583Message message, SourceNode sourceNode)
        {
            var    field41    = message.Fields[41].Value.ToString();
            var    terminalID = field41.Substring(1, field41.Length - 1);
            string cardBIN    = message.Fields[2].Value.ToString().Substring(0, 6);

            Console.WriteLine("Processing ...");
            if (!terminalID.Equals(IsoMessageFieldDefinitions.TERMINAL_ID.ToString()))
            {
                Console.WriteLine("THIS IS A NOT-ON-US TRANSACTION");
            }
            else
            {
                if (cardBIN.Equals(IsoMessageFieldDefinitions.INSTITUTION_BIN.ToString()))
                {
                    Console.WriteLine("THIS IS AN ON-US TRANSACTION");
                }
                else
                {
                    Console.WriteLine("THIS IS A REMOTE-ON-US TRANSACTION");
                }
            }
            if (message.MessageTypeIdentifier != 420)
            {
                message = AddOriginalDataElement(message);
            }
            //            SourceNode sourceNode = new EntityLogic<SourceNode>().GetByID(sourceID);
            bool returnMsg;

            message = CheckMessageType(message, sourceNode, out returnMsg);

            if (returnMsg == true)
            {
                return(message);
            }

            Iso8583Message responseMessage;
            string         expiryDate = message.Fields[14].Value.ToString();
            DateTime       cardExpiry = ParseDate(expiryDate);

            if (cardExpiry < DateTime.Now)
            {
                //expired card
                responseMessage = SetResponseMessage(message, "54");
                new TransactionLogProcessing().LogTransaction(responseMessage);
                return(responseMessage);
            }

            Console.WriteLine("Getting TrxCode ...");
            string transactionTypeCode = message.Fields[3].Value.ToString().Substring(0, 2);

            Console.WriteLine("Getting Amount ...");
            double amount = ConvertIsoAmountToDouble(message.Fields[4].Value.ToString());

            if (transactionTypeCode != "31" && amount <= 0)
            {
                responseMessage = SetResponseMessage(message, "13");
                new TransactionLogProcessing().LogTransaction(responseMessage);
                return(responseMessage);
            }

            // GETTING ROUTE

            Console.WriteLine("Getting BIN ...");
//            string cardBIN = message.Fields[2].Value.ToString().Substring(0, 6);

            Console.WriteLine("Getting Route ...");
            Route route = new RouteLogic().GetRouteByBIN(cardBIN);

            if (route == null)
            {
                responseMessage = SetResponseMessage(message, "15");
                new TransactionLogProcessing().LogTransaction(responseMessage);
                return(responseMessage);
            }

            if (route.SinkNode == null || route.SinkNode.Status == "In-active")
            {
                Console.WriteLine("Sink Node is null");
                responseMessage = SetResponseMessage(message, "91");
                new TransactionLogProcessing().LogTransaction(responseMessage);
                return(responseMessage);
            }

            //GETTING SCHEME

            Scheme scheme;

            try

            {
                Console.WriteLine("Getting Scheme ...");
                scheme = SwitchData.GetSchemeByRoute(route, transactionTypeCode);
            }
            catch (Exception e)
            {
                responseMessage = SetResponseMessage(message, "06");
                new TransactionLogProcessing().LogTransaction(responseMessage);
                return(responseMessage);
            }

            if (scheme == null)
            {
                responseMessage = SetResponseMessage(message, "58");
                new TransactionLogProcessing().LogTransaction(responseMessage);
                //new TransactionLogLogic().LogMessage(responseMessage);
                return(responseMessage);
            }

            Console.WriteLine("Getting TrxType ...");
            TransactionType transactionType = new TransactionTypeLogic().GetTransactionTypebyCode(transactionTypeCode);

            Console.WriteLine("Getting Channel ...");
            string channelCode = message.Fields[41].Value.ToString().Substring(0, 1);

            Channel channel = new ChannelLogic().GetChannelByCode(channelCode);

            Fee fee = GetFee(transactionType, channel, scheme);

            if (fee == null)
            {
                responseMessage = SetResponseMessage(message, "58");
                new TransactionLogProcessing().LogTransaction(responseMessage);
                return(responseMessage);
            }

            double?fees = CalculateFee(fee, amount);

            message = SetFee(message, fees);

            //BY NOW ALL CHECKS HAVE BEEN DONE , TIME TO SEND TO SINK NODE

            bool needReversal = false;

            Console.WriteLine("Routing To Destination ...");
            responseMessage = RouteToDestination(message, route.SinkNode, out needReversal);


            return(responseMessage);
        }
        private void MarkOptimizationAndCaseBlocks(InstructionBlock block, SwitchData data)
        {
            Queue <InstructionBlock> queue   = new Queue <InstructionBlock>();
            HashSet <int>            visited = new HashSet <int>();

            foreach (InstructionBlock successor in block.Successors)
            {
                queue.Enqueue(successor);
            }

            while (queue.Count > 0)
            {
                InstructionBlock current = queue.Dequeue();
                visited.Add(current.First.Offset);

                if (IsOptimizationBlock(this.blockExpressions[current.First.Offset], data.OptimizationVariable))
                {
                    // The first successor of an optimization block is either another optimization block
                    // or case block. Either case we want to enqueue it.
                    InstructionBlock firstSuccessor = current.Successors[0];
                    if (!visited.Contains(firstSuccessor.First.Offset))
                    {
                        queue.Enqueue(firstSuccessor);
                    }

                    // The second (and last) successor of an optimization block can be unconditional jump.
                    // In that case we need to first remove it. Then we examine the new last successor of
                    // the optimization block.
                    InstructionBlock lastSuccessor = MarkSecondSuccessorForRemovalIfItIsUnconditionalJump(current);

                    // We enqueue the last successor of an optimization block only if it's another optimization block.
                    // This is done, because if we have an optimization block, which last successor is jump to the
                    // switch's next statement (the first statement after the actual switch) and this next statement
                    // have the same structure as the case blocks, this will cause unexpected behavior and wrong decompilation.
                    if (!visited.Contains(lastSuccessor.First.Offset) &&
                        IsOptimizationBlock(this.blockExpressions[current.First.Offset], data.OptimizationVariable))
                    {
                        queue.Enqueue(lastSuccessor);
                    }

                    blocksToBeRemoved.Add(current.First.Offset);
                }
                else if (IsCaseBlock(this.blockExpressions[current.First.Offset], data.SwitchExpression) ||
                         IsNullCaseBlock(this.blockExpressions[current.First.Offset], data.SwitchExpression))
                {
                    switchBlocksToCasesMap[block.First.Offset].Add(current.First.Offset);

                    InstructionBlock secondSuccessor = current.Successors[1];
                    if (IsEmptyStringCaseBlock(this.blockExpressions[secondSuccessor.First.Offset], data.SwitchExpression))
                    {
                        // The first successor is jump to the next/default statement, so we merge the current block with
                        // its second successor, which contains the lenght check. The first successor of the current block
                        // and the second successor of current block's second successor are exactly the same block. In this
                        // case it will be marked for removal by the MarkSecondSuccessorForRemovalIfItIsUnconditionalJump
                        // invocation below, so there is no need for us to mark it here.
                        current.Last       = secondSuccessor.Last;
                        current.Successors = secondSuccessor.Successors;

                        // We change the someExpr == null binary expression, so it became someExpr == "".
                        BinaryExpression binary = this.blockExpressions[current.First.Offset][0] as BinaryExpression;
                        binary.Right = new LiteralExpression("", this.methodContext.Method.Module.TypeSystem, null);

                        // Preserve the instructions from the second block as instructions of the binary expression.
                        IEnumerable <Instruction> secondSuccessorInstructions = this.blockExpressions[secondSuccessor.First.Offset][0].UnderlyingSameMethodInstructions;
                        binary = binary.CloneAndAttachInstructions(secondSuccessorInstructions) as BinaryExpression;

                        // Wrap the binary expression in unary with operator "None", because it should have the exact
                        // same structure as the normal cases in order next steps of switch by string building to work.
                        this.blockExpressions[current.First.Offset][0] = new UnaryExpression(UnaryOperator.None, binary, null);

                        this.blocksToBeRemoved.Add(secondSuccessor.First.Offset);
                    }

                    // If the second successor of the case block is unconditional jump we want to remove it.
                    // This is done, because later we take all case blocks and connect them one to each other.
                    // All case blocks can have different unconditional jump block used to jump the the next statement
                    // (the statement after the switch statement). Later we connect all the case blocks in a chain
                    // and we want to be sure that there is only one way to go the next statement, and that there are
                    // no unreachable unconditional jump blocks.
                    MarkSecondSuccessorForRemovalIfItIsUnconditionalJump(current);
                }
            }
        }
Exemplo n.º 28
0
        /// <summary>
        /// Process each switch block to determine which cases lead to try/finally constructs.
        /// </summary>
        /// <remarks>
        /// E.g.: If the cases from 3 to 5 lead to the same try/finally construct then there is a try/finally construct in the MoveNext method
        /// that covers states 3, 4 and 5.
        /// </remarks>
        /// <param name="switchBlockInfo"></param>
        private bool DetermineExceptionHandlingIntervalsFromSwitchData(SwitchData switchBlockInfo)
        {
            //Since the first try/finally that this switch covers can start at state 20, the complier will optimize this by subtracting 20 from the value of
            //the state field.
            int         stateOffset        = 0;
            Instruction currentInstruction = switchBlockInfo.SwitchBlock.Last.Previous;

            if (currentInstruction.OpCode.Code == Code.Sub)
            {
                currentInstruction = currentInstruction.Previous;
                if (!StateMachineUtilities.TryGetOperandOfLdc(currentInstruction, out stateOffset))
                {
                    return(false);
                }

                currentInstruction = currentInstruction.Previous;
            }

            //The switch instruction block usually looks like this:
            //
            //ldarg.0 <- this
            //ldfld stateField
            //stloc.0
            //ldloc.0                  <- currentInstruction
            //(ldc.i4 stateOffset)
            //(sub)
            //switch ....
            currentInstruction = currentInstruction.Previous.Previous;
            if (currentInstruction.OpCode.Code != Code.Ldfld || !(currentInstruction.Operand is FieldReference) ||
                !CheckAndSaveStateField(currentInstruction.Operand as FieldReference))
            {
                //sanity check - the state field used by the Dispose method should be the same as the field used by the MoveNext method
                return(false);
            }

            //The algorithm works with the presumption that a try/finally construct contains a consecutive sequence of states.
            InstructionBlock[] orderedCases = switchBlockInfo.OrderedCasesArray;
            InstructionBlock   currentBlock = null;
            int intervalStart = -1;
            int intervalEnd   = -1;
            ExceptionHandler exceptionHandler = null;

            for (int i = 0; i < orderedCases.Length; i++)
            {
                InstructionBlock currentCase = GetActualCase(orderedCases[i]);

                if (currentBlock != null && currentCase == currentBlock) //Current block will be null, if we still haven't found an exception handler.
                {
                    intervalEnd = i + stateOffset;
                    continue;
                }

                ExceptionHandler theHandler;
                if (!TryGetExceptionHandler(currentCase, out theHandler))
                {
                    //There are cases where a state is never reached (i.e. the state field is never assigned this state number).
                    //This can create holes in the exception handlers, but since the states are never reached we can add them to the handler.
                    //(We work with the assumption that if state 3 and state 6 are handled by the same try/finally construct and 4 and 5 are not handled by
                    //any exception handler, then 4 and 5 are unreachable. True in general, but obfuscation can break this assumption.)
                    continue;
                }

                //We've found an exception handler.

                if (currentBlock != null) //If currentBlock != null, then currentBlock != currentCase. This means that we have found a new exception
                //handler, so we must store the data for the old one.
                {
                    if (!TryCreateYieldExceptionHandler(intervalStart, intervalEnd, exceptionHandler))
                    {
                        return(false);
                    }
                }
                else //Otherwise this is the first handler found for the switch block.
                {
                    currentBlock = currentCase;
                }

                intervalStart    = i + stateOffset;
                exceptionHandler = theHandler;
            }

            return(currentBlock == null ||
                   TryCreateYieldExceptionHandler(intervalStart, intervalEnd, exceptionHandler)); //Store the data for the last found exception handler.
        }
Exemplo n.º 29
0
 private void CreateSwitchConstruct(CFGBlockLogicalConstruct switchBlock, ILogicalConstruct parentConstruct, SwitchData switchData, DominatorTree dominatorTree)
 {
     stackVariable2 = this.GetOrderedCFGSuccessorToLabelsMap(switchData);
     V_0            = this.GetValidCases(dominatorTree, switchBlock);
     V_1            = new List <CaseLogicalConstruct>();
     V_2            = new PairList <List <int>, CFGBlockLogicalConstruct>();
     V_8            = stackVariable2.GetEnumerator();
     try
     {
         while (V_8.MoveNext())
         {
             V_9 = V_8.get_Current();
             if (!LogicalFlowUtilities.TryGetParentConstructWithGivenParent(V_9.get_Key(), parentConstruct, out V_10) || !V_0.TryGetValue(V_10, out V_11))
             {
                 V_2.Add(V_9.get_Value(), V_9.get_Key());
             }
             else
             {
                 V_12 = new CaseLogicalConstruct(V_10);
                 V_12.get_CaseNumbers().AddRange(V_9.get_Value());
                 V_12.get_Body().UnionWith(V_11.Cast <ILogicalConstruct>());
                 V_12.AttachCaseConstructToGraph();
                 V_1.Add(V_12);
             }
         }
     }
     finally
     {
         ((IDisposable)V_8).Dispose();
     }
     V_3 = null;
     V_4 = this.GetCFGLogicalConstructFromBlock(switchData.get_DefaultCase());
     if (LogicalFlowUtilities.TryGetParentConstructWithGivenParent(V_4, parentConstruct, out V_5) && V_0.TryGetValue(V_5, out V_6))
     {
         V_3 = new CaseLogicalConstruct(V_5);
         if (this.HasSuccessors(V_6))
         {
             V_3.get_Body().UnionWith(V_6.Cast <ILogicalConstruct>());
         }
         V_3.AttachCaseConstructToGraph();
     }
     V_7 = SwitchLogicalConstruct.GroupInSwitchConstruct(switchBlock, V_1, V_2, V_3, V_4);
     this.UpdateDominatorTree(dominatorTree, V_7);
     return;
 }
Exemplo n.º 30
0
 private PairList <CFGBlockLogicalConstruct, List <int> > GetOrderedCFGSuccessorToLabelsMap(SwitchData switchData)
 {
     V_0 = new PairList <CFGBlockLogicalConstruct, List <int> >();
     V_1 = new Dictionary <InstructionBlock, KeyValuePair <int, List <int> > >();
     V_2 = 0;
     while (V_2 < (int)switchData.get_OrderedCasesArray().Length)
     {
         V_3 = switchData.get_OrderedCasesArray()[V_2];
         if (InstructionBlock.op_Inequality(V_3, switchData.get_DefaultCase()))
         {
             if (!V_1.TryGetValue(V_3, out V_4))
             {
                 V_4 = new KeyValuePair <int, List <int> >(V_0.get_Count(), new List <int>());
                 V_0.Add(this.GetCFGLogicalConstructFromBlock(V_3), V_4.get_Value());
                 V_1.Add(V_3, V_4);
             }
             V_4.get_Value().Add(V_2);
         }
         V_2 = V_2 + 1;
     }
     return(V_0);
 }