예제 #1
0
 public void Setup()
 {
     sw        = new StringWriter();
     formatter = new TextFormatter(sw);
     cf        = new CodeFormatter(formatter);
     m         = new ExpressionEmitter();
 }
예제 #2
0
 public ConditionCodeEliminator(SsaState ssa, IPlatform platform, DecompilerEventListener listener)
 {
     this.ssa      = ssa;
     this.ssaIds   = ssa.Identifiers;
     this.platform = platform;
     this.m        = new ExpressionEmitter();
 }
예제 #3
0
 public OperandRewriter(IntelArchitecture arch, ExpressionEmitter emitter, Frame frame, IRewriterHost host)
 {
     this.arch  = arch;
     this.m     = emitter;
     this.frame = frame;
     this.host  = host;
 }
예제 #4
0
 public OperandRewriter(IntelArchitecture arch, ExpressionEmitter emitter, IStorageBinder binder, IRewriterHost host)
 {
     this.arch   = arch;
     this.m      = emitter;
     this.binder = binder;
     this.host   = host;
 }
예제 #5
0
 public ConditionCodeEliminator(SsaState ssa, IPlatform arch)
 {
     this.ssa      = ssa;
     this.ssaIds   = ssa.Identifiers;
     this.platform = arch;
     this.m        = new ExpressionEmitter();
 }
예제 #6
0
 static Expression RolC(ExpressionEmitter m, Expression e, Expression sh, Expression c)
 {
     var sig = FunctionType.Func(
         new Identifier("", e.DataType, null !),
         new Identifier("e", e.DataType, null !),
         new Identifier("sh", e.DataType, null !),
         new Identifier("c", e.DataType, null !));
     return(m.Fn(new IntrinsicProcedure(IntrinsicProcedure.RolC, false, sig), e, sh, c));
 }
예제 #7
0
        public void Setup()
        {
            arch = new FakeArchitecture();
            sp   = new RegisterStorage("sp", 42, 0, PrimitiveType.Ptr32);
            arch.StackRegister = sp;

            idSp = new Identifier(sp.Name, sp.DataType, sp);
            m    = new ExpressionEmitter();
        }
예제 #8
0
 public TypedExpressionRewriter(Program program)
 {
     this.program   = program;
     this.globals   = program.Globals;
     this.compTypes = new DataTypeComparer();
     this.tcr       = new TypedConstantRewriter(program);
     this.m         = new ExpressionEmitter();
     this.unifier   = new Unifier();
 }
예제 #9
0
 public ConditionCodeEliminator(Program program, SsaState ssa, DecompilerEventListener listener)
 {
     this.ssa      = ssa;
     this.ssaIds   = ssa.Identifiers;
     this.program  = program;
     this.listener = listener;
     this.m        = new ExpressionEmitter();
     this.aliases  = new HashSet <Identifier>();
 }
예제 #10
0
 public TypedExpressionRewriter(Program program, DecompilerEventListener eventListener)
 {
     this.program       = program;
     this.globals       = program.Globals;
     this.eventListener = eventListener;
     this.compTypes     = new DataTypeComparer();
     this.tcr           = new TypedConstantRewriter(program, eventListener);
     this.m             = new ExpressionEmitter();
     this.unifier       = new Unifier();
 }
예제 #11
0
        public void Setup()
        {
            this.m       = new ExpressionEmitter();
            this.store   = new TypeStore();
            this.factory = new TypeFactory();
            var arch     = new FakeArchitecture();
            var platform = new DefaultPlatform(null, arch);

            this.exa = new ExpressionTypeAscender(platform, store, factory);
        }
예제 #12
0
        public void Setup()
        {
            sp   = new RegisterStorage("sp", 42, PrimitiveType.Pointer32);
            arch = new FakeArchitecture();
            arch.StackRegister = sp;

            sce = new FakeProcessorState(arch);

            idSp = new Identifier(sp.Name, sp.DataType, sp);
            m    = new ExpressionEmitter();
        }
예제 #13
0
 public TypedExpressionRewriter(Program prog)
 {
     this.prog      = prog;
     this.platform  = prog.Platform;
     this.store     = prog.TypeStore;
     this.globals   = prog.Globals;
     this.compTypes = new DataTypeComparer();
     this.tcr       = new TypedConstantRewriter(prog);
     this.m         = new ExpressionEmitter();
     this.unifier   = new Unifier();
 }
예제 #14
0
 public void Setup()
 {
     this.m       = new ExpressionEmitter();
     this.store   = new TypeStore();
     this.factory = new TypeFactory();
     this.arch    = new FakeArchitecture();
     this.program = new Program {
         Architecture = arch, Platform = new DefaultPlatform(null, arch)
     };
     this.exa = new ExpressionTypeAscender(program, store, factory);
     this.exd = new ExpressionTypeDescender(program, store, factory);
     store.EnsureExpressionTypeVariable(factory, program.Globals, "globals_t");
 }
예제 #15
0
        public void Setup()
        {
            this.m       = new ExpressionEmitter();
            this.store   = new TypeStore();
            this.factory = new TypeFactory();
            var arch     = new FakeArchitecture(new ServiceContainer());
            var platform = new DefaultPlatform(null, arch);

            program = new Program {
                Architecture = arch, Platform = platform
            };
            this.exa = new ExpressionTypeAscender(program, store, factory);
        }
예제 #16
0
        public static string ExpressionResult(Expression exp, string result)
        {
            var emitter  = new ExpressionEmitter(exp, result);
            var emitterG = emitter.GenerateCode(dict);

            if (emitterG == null)
            {
                errors = true;
                return("");
            }

            return(emitterG);
        }
예제 #17
0
 public IndirectCallRewriter(
     Program program,
     SsaState ssa,
     DecompilerEventListener eventListener)
 {
     this.program          = program;
     this.proc             = ssa.Procedure;
     this.ssa              = ssa;
     this.asc              = new IndirectCallTypeAscender(program);
     this.expander         = new IndirectCallExpander(ssa);
     this.ssaIdTransformer = new SsaIdentifierTransformer(ssa);
     this.eventListener    = eventListener;
     this.m = new ExpressionEmitter();
 }
예제 #18
0
        private readonly int                decodingPathNumber; // For use debugging

        internal PreparedILBody(
            Label label,
            ExpressionEmitter emitter,
            int uniqueCodeBlockIndex,
            ICodeInformation code,
            int decodingPathNumber)
        {
            this.Label   = label;
            this.Emitter = emitter;
            this.UniqueCodeBlockIndex = uniqueCodeBlockIndex;
            this.Code = code;

            this.decodingPathNumber = decodingPathNumber;
        }
예제 #19
0
 public TrashedRegisterFinder(
     Program program,
     IEnumerable <Procedure> procedures,
     ProgramDataFlow flow,
     DecompilerEventListener eventListener)
 {
     this.program       = program;
     this.procedures    = procedures;
     this.flow          = flow;
     this.eventListener = eventListener ?? NullDecompilerEventListener.Instance;
     this.worklist      = new WorkList <Block>();
     this.visited       = new HashSet <Block>();
     this.ecomp         = new ExpressionValueComparer();
     this.m             = new ExpressionEmitter();
 }
예제 #20
0
        public void Setup()
        {
            program = new Program();
            program.Architecture = new FakeArchitecture(new ServiceContainer());
            program.Platform     = new DefaultPlatform(program.Architecture.Services, program.Architecture);
            store   = program.TypeStore;
            factory = program.TypeFactory;
            globals = program.Globals;
            StructureType point = new StructureType("Point", 0)
            {
                Fields =
                {
                    { 0, PrimitiveType.Word32, null },
                    { 4, PrimitiveType.Word32, null }
                }
            };
            TypeVariable     tvPoint = store.CreateTypeVariable(factory);
            EquivalenceClass eq      = new EquivalenceClass(tvPoint)
            {
                DataType = point
            };

            tvPoint.DataType = eq;
            ptrPoint         = new Pointer(eq, 32);

            UnionType u = new UnionType("RealInt", null)
            {
                Alternatives =
                {
                    new UnionAlternative("w", PrimitiveType.Word32, 0),
                    new UnionAlternative("r", PrimitiveType.Real32, 1),
                }
            };
            TypeVariable tvUnion = store.CreateTypeVariable(factory);

            eq = new EquivalenceClass(tvUnion)
            {
                DataType = u
            };
            tvUnion.DataType = eq;
            ptrUnion         = new Pointer(eq, 32);

            ptrInt  = new Pointer(PrimitiveType.Int32, 32);
            ptrWord = new Pointer(PrimitiveType.Word32, 32);
            m       = new ExpressionEmitter();
        }
예제 #21
0
        public void DynLink_LP32_weirdness()
        {
            var memText = new ByteMemoryArea(Address.Ptr64(0x00123400), new byte[100]);
            var memGot  = new ByteMemoryArea(Address.Ptr64(0x00200000), new byte[100]);
            var wr      = new LeImageWriter(memGot.Bytes);

            wr.WriteLeUInt32(0x00300000);
            wr.WriteLeUInt32(0x00300004);
            var arch = new FakeArchitecture64(new ServiceContainer());
            //var arch = new Mock<IProcessorArchitecture>();
            //arch.Setup(a => a.Endianness).Returns(EndianServices.Little);
            //arch.Setup(a => a.Name).Returns("fakeArch");
            //arch.Setup(a => a.PointerType).Returns(PrimitiveType.Ptr64);
            //arch.Setup(a => a.MakeAddressFromConstant(
            //    It.IsAny<Constant>(),
            //    It.IsAny<bool>())).Returns((Constant c, bool b) =>
            //        Address.Ptr64(c.ToUInt32()));
            var project = new Project();
            var sc      = new ServiceContainer();
            var program = new Program
            {
                Architecture = arch,
                Platform     = new DefaultPlatform(sc, arch),
                SegmentMap   = new SegmentMap(memGot.BaseAddress,
                                              new ImageSegment(".text", memText, AccessMode.ReadExecute),
                                              new ImageSegment(".got", memGot, AccessMode.Read)),
            };

            program.ImportReferences.Add(
                Address.Ptr32(0x00200000),
                new NamedImportReference(
                    Address.Ptr32(0x00200000), null, "my_global_var", SymbolType.Data));

            var dynlink = new DynamicLinker(project, program, new FakeDecompilerEventListener());

            var m     = new ExpressionEmitter();
            var addr  = Address.Ptr64(0x00123000);
            var proc  = program.EnsureProcedure(program.Architecture, addr, "foo_proc");
            var block = new Block(proc, addr, "foo");
            var stm   = new Statement(0x00123400, new Store(m.Word64(0x00123400), Constant.Real32(1.0F)), block);

            var result = dynlink.ResolveToImportedValue(stm, Constant.Word32(0x00200000));

            Assert.AreEqual("0x300000<64>", result.ToString());     //$LIT: pointer? p64?
        }
예제 #22
0
        public void Setup()
        {
            store   = new TypeStore();
            factory = new TypeFactory();
            globals = new Identifier("globals", PrimitiveType.Word32, null);
            StructureType point = new StructureType("Point", 0)
            {
                Fields =
                {
                    { 0, PrimitiveType.Word32, null },
                    { 4, PrimitiveType.Word32, null }
                }
            };
            TypeVariable     tvPoint = store.CreateTypeVariable(factory);
            EquivalenceClass eq      = new EquivalenceClass(tvPoint)
            {
                DataType = point
            };

            tvPoint.DataType = eq;
            ptrPoint         = new Pointer(eq, 32);

            UnionType u = new UnionType("RealInt", null)
            {
                Alternatives =
                {
                    new UnionAlternative("w", PrimitiveType.Word32, 0),
                    new UnionAlternative("r", PrimitiveType.Real32, 1),
                }
            };
            TypeVariable tvUnion = store.CreateTypeVariable(factory);

            eq = new EquivalenceClass(tvUnion)
            {
                DataType = u
            };
            tvUnion.DataType = eq;
            ptrUnion         = new Pointer(eq, 32);

            ptrInt  = new Pointer(PrimitiveType.Int32, 32);
            ptrWord = new Pointer(PrimitiveType.Word32, 32);
            m       = new ExpressionEmitter();
        }
예제 #23
0
        public void ApplySignatureToProcedure(Address addr, ProcedureSignature sig, Procedure proc)
        {
            proc.Signature = sig;

            int i       = 0;
            var stmts   = proc.EntryBlock.Succ[0].Statements;
            var linAddr = addr.ToLinear();
            var m       = new ExpressionEmitter();

            foreach (var param in sig.Parameters)
            {
                var starg = param.Storage as StackArgumentStorage;
                if (starg != null)
                {
                    proc.Frame.EnsureStackArgument(
                        starg.StackOffset + sig.ReturnAddressOnStack,
                        param.DataType,
                        param.Name);
                    var fp = proc.Frame.FramePointer;
                    stmts.Insert(i, linAddr, new Store(
                                     m.Load(param.DataType, m.IAdd(fp, sig.ReturnAddressOnStack + starg.StackOffset)),
                                     param));
                }
                else
                {
                    var paramId = proc.Frame.EnsureIdentifier(param.Storage);
                    paramId.DataType = param.DataType;

                    // Need to take an extra step with parameters being passed
                    // in a register. It's perfectly possible for a user to
                    // create a variable which they want to call 'r2' but which
                    // the calling convention of the machine wants to call 'r1'.
                    // To avoid this, we create a temporary identifier for
                    // the formal parameter, and inject an copy statement in the
                    // entry block that moves the parameter value into the
                    // register.
                    stmts.Insert(i, linAddr, NewMethod(param, paramId));
                }
                ++i;
            }
        }
예제 #24
0
        public void ApplySignatureToProcedure(Address addr, FunctionType sig, Procedure proc)
        {
            proc.Signature = sig;
            // The copy instructions have to happen before any of the
            // "real" code, so they have to live in the entry block.
            var stmts = proc.EntryBlock.Statements;
            int i     = stmts.Count;

            var linAddr = addr.ToLinear();
            var m       = new ExpressionEmitter();

            foreach (var param in sig.Parameters !)
            {
                if (param.Storage is StackArgumentStorage starg)
                {
                    proc.Frame.EnsureStackArgument(
                        starg.StackOffset,
                        param.DataType,
                        param.Name);
                    var fp = proc.Frame.FramePointer;
                    stmts.Insert(i, linAddr, new Store(
                                     m.Mem(param.DataType, m.IAdd(fp, starg.StackOffset)),
                                     param));
                }
                else
                {
                    var paramId = proc.Frame.EnsureIdentifier(param.Storage);

                    // Need to take an extra step with parameters being passed
                    // in a register. It's perfectly possible for a user to
                    // create a variable which they want to call 'r2' but which
                    // the calling convention of the machine wants to call 'r1'.
                    // To avoid this, we create a temporary identifier for
                    // the formal parameter, and inject an copy statement in the
                    // entry block that moves the parameter value into the
                    // register.
                    stmts.Insert(i, linAddr, new Assignment(param, paramId));
                }
                ++i;
            }
        }
예제 #25
0
        private TextViewModel GenerateSimulatedHllCode()
        {
            var code   = new List <AbsynStatement>();
            var ase    = new Structure.AbsynStatementEmitter(code);
            var m      = new ExpressionEmitter();
            var a_id   = new Identifier("a", PrimitiveType.Int32, null);
            var sum_id = new Identifier("sum", PrimitiveType.Int32, null);

            ase.EmitAssign(a_id, Constant.Int32(10));
            ase.EmitAssign(sum_id, Constant.Int32(0));

            var tsf = new TextSpanFormatter();
            var fmt = new AbsynCodeFormatter(tsf);

            fmt.InnerFormatter.UseTabs = false;
            foreach (var stm in code)
            {
                stm.Accept(fmt);
            }
            return(tsf.GetModel());
        }
예제 #26
0
 public ExpressionSimplifier(SegmentMap segmentMap, EvaluationContext ctx, DecompilerEventListener listener)
 {
     this.segmentMap              = segmentMap ?? throw new ArgumentNullException(nameof(SegmentMap));
     this.ctx                     = ctx;
     this.cmp                     = new ExpressionValueComparer();
     this.m                       = new ExpressionEmitter();
     this.unifier                 = new Unifier();
     this.add2ids                 = new AddTwoIdsRule(ctx);
     this.addEcc                  = new Add_e_c_cRule(ctx);
     this.addMici                 = new Add_mul_id_c_id_Rule(ctx);
     this.idConst                 = new IdConstant(ctx, unifier, listener);
     this.idCopyPropagation       = new IdCopyPropagationRule(ctx);
     this.idBinIdc                = new IdBinIdc_Rule(ctx);
     this.sliceConst              = new SliceConstant_Rule();
     this.sliceMem                = new SliceMem_Rule();
     this.sliceSegPtr             = new SliceSegmentedPointer_Rule(ctx);
     this.negSub                  = new NegSub_Rule();
     this.constConstBin           = new ConstConstBin_Rule();
     this.shAdd                   = new Shl_add_Rule(ctx);
     this.shMul                   = new Shl_mul_e_Rule(ctx);
     this.shiftShift              = new ShiftShift_c_c_Rule(ctx);
     this.mpsRule                 = new Mps_Constant_Rule(ctx);
     this.sliceShift              = new SliceShift(ctx);
     this.binopWithSelf           = new BinOpWithSelf_Rule();
     this.constDiv                = new ConstDivisionImplementedByMultiplication(ctx);
     this.idProcConstRule         = new IdProcConstRule(ctx);
     this.convertConvertRule      = new ConvertConvertRule(ctx);
     this.distributedConvert      = new DistributedConversionRule();
     this.distributedCast         = new DistributedCastRule();
     this.distributedSlice        = new DistributedSliceRule();
     this.mkSeqFromSlicesRule     = new MkSeqFromSlices_Rule(ctx);
     this.constOnLeft             = new ComparisonConstOnLeft();
     this.sliceSeq                = new SliceSequence(ctx);
     this.sliceConvert            = new SliceConvert();
     this.logicalNotFollowedByNeg = new LogicalNotFollowedByNegRule();
     this.logicalNotFromBorrow    = new LogicalNotFromArithmeticSequenceRule();
     this.unaryNegEqZero          = new UnaryNegEqZeroRule();
     this.scaledIndexRule         = new ScaledIndexRule(ctx);
 }
 public StackPointerBackpropagator(SsaState ssa, DecompilerEventListener listener)
 {
     this.ssa      = ssa;
     this.m        = new ExpressionEmitter();
     this.listener = listener;
 }
예제 #28
0
파일: statement.cs 프로젝트: tgiphil/mono
		public override bool Resolve (BlockContext ec)
		{
			if (!ec.IsUnsafe){
				Expression.UnsafeError (ec, loc);
				return false;
			}
			
			TypeExpr texpr = type.ResolveAsContextualType (ec, false);
			if (texpr == null) {
				if (type is VarExpr)
					ec.Report.Error (821, type.Location, "A fixed statement cannot use an implicitly typed local variable");

				return false;
			}

			expr_type = texpr.Type;

			data = new Emitter [declarators.Count];

			if (!expr_type.IsPointer){
				ec.Report.Error (209, loc, "The type of locals declared in a fixed statement must be a pointer type");
				return false;
			}
			
			int i = 0;
			foreach (var p in declarators){
				LocalInfo vi = p.Key;
				Expression e = p.Value;
				
				vi.VariableInfo.SetAssigned (ec);
				vi.SetReadOnlyContext (LocalInfo.ReadOnlyContext.Fixed);

				//
				// The rules for the possible declarators are pretty wise,
				// but the production on the grammar is more concise.
				//
				// So we have to enforce these rules here.
				//
				// We do not resolve before doing the case 1 test,
				// because the grammar is explicit in that the token &
				// is present, so we need to test for this particular case.
				//

				if (e is Cast){
					ec.Report.Error (254, loc, "The right hand side of a fixed statement assignment may not be a cast expression");
					return false;
				}

				using (ec.Set (ResolveContext.Options.FixedInitializerScope)) {
					e = e.Resolve (ec);
				}

				if (e == null)
					return false;

				//
				// Case 2: Array
				//
				if (e.Type.IsArray){
					TypeSpec array_type = TypeManager.GetElementType (e.Type);
					
					//
					// Provided that array_type is unmanaged,
					//
					if (!TypeManager.VerifyUnmanaged (ec.Compiler, array_type, loc))
						return false;

					//
					// and T* is implicitly convertible to the
					// pointer type given in the fixed statement.
					//
					ArrayPtr array_ptr = new ArrayPtr (e, array_type, loc);
					
					Expression converted = Convert.ImplicitConversionRequired (
						ec, array_ptr, vi.VariableType, loc);
					if (converted == null)
						return false;
					
					//
					// fixed (T* e_ptr = (e == null || e.Length == 0) ? null : converted [0])
					//
					converted = new Conditional (new BooleanExpression (new Binary (Binary.Operator.LogicalOr,
						new Binary (Binary.Operator.Equality, e, new NullLiteral (loc), loc),
						new Binary (Binary.Operator.Equality, new MemberAccess (e, "Length"), new IntConstant (0, loc), loc), loc)),
							new NullPointer (loc),
							converted, loc);

					converted = converted.Resolve (ec);					

					data [i] = new ExpressionEmitter (converted, vi);
					i++;

					continue;
				}

				//
				// Case 3: string
				//
				if (e.Type == TypeManager.string_type){
					data [i] = new StringEmitter (e, vi, loc).Resolve (ec);
					i++;
					continue;
				}

				// Case 4: fixed buffer
				if (e is FixedBufferPtr) {
					data [i++] = new ExpressionEmitter (e, vi);
					continue;
				}

				//
				// Case 1: & object.
				//
				Unary u = e as Unary;
				if (u != null && u.Oper == Unary.Operator.AddressOf) {
					IVariableReference vr = u.Expr as IVariableReference;
					if (vr == null || !vr.IsFixed) {
						data [i] = new ExpressionEmitter (e, vi);
					}
				}

				if (data [i++] == null)
					ec.Report.Error (213, vi.Location, "You cannot use the fixed statement to take the address of an already fixed expression");

				e = Convert.ImplicitConversionRequired (ec, e, expr_type, loc);
			}

			ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
			bool ok = statement.Resolve (ec);
			bool flow_unreachable = ec.EndFlowBranching ();
			has_ret = flow_unreachable;

			return ok;
		}
예제 #29
0
 public ConstDivisionImplementedByMultiplication(SsaState ssa)
 {
     this.ssa = ssa;
     this.m   = new ExpressionEmitter();
 }
예제 #30
0
 public void Setup()
 {
     m = new ExpressionEmitter();
 }
예제 #31
0
파일: SsaMutator.cs 프로젝트: claunia/reko
 public SsaMutator(SsaState ssa)
 {
     this.ssa = ssa;
     this.m   = new ExpressionEmitter();
 }