Exemplo n.º 1
0
        public override void CaseADelegateExp(ADelegateExp node)
        {
            /* Replace delegate<Type>(method)
             * With
             *
             * "method"
             *
             * or
             *
             * "method:reciever"
             */
            AMethodDecl method = finalTrans.data.DelegateCreationMethod[node];
            string d = GetName(method);
            PExp replacer;
            APointerLvalue reciever = finalTrans.data.DelegateRecieveres[node];
            if (reciever != null)
            {
                d += ":";
                AStringConstExp leftSide = new AStringConstExp(new TStringLiteral("\"" + d + "\""));
                replacer = new ABinopExp(leftSide, new APlusBinop(new TPlus("+")), reciever.GetBase());
                finalTrans.data.ExpTypes[leftSide] =
                    finalTrans.data.ExpTypes[replacer] = new ANamedType(new TIdentifier("string"), null);

                if (Util.IsIntPointer(reciever, data.LvalueTypes[reciever], data))
                {

                    ASimpleInvokeExp intToStringInvoke = new ASimpleInvokeExp(new TIdentifier("IntToString"),
                                                                              new ArrayList()
                                                                                  {((ABinopExp) replacer).GetRight()});
                    ((ABinopExp)replacer).SetRight(intToStringInvoke);

                    finalTrans.data.SimpleMethodLinks[intToStringInvoke] =
                        data.Libraries.Methods.First(m => m.GetName().Text == intToStringInvoke.GetName().Text);
                    data.ExpTypes[intToStringInvoke] = new ANamedType(new TIdentifier("string"), null);

                }
            }
            else
            {
                replacer = new AStringConstExp(new TStringLiteral("\"" + d + "\""));
                finalTrans.data.ExpTypes[replacer] = new ANamedType(new TIdentifier("string"), null);
            }
            MoveMethodDeclsOut mover = new MoveMethodDeclsOut("delegateVar", finalTrans.data);
            node.Apply(mover);
            node.ReplaceBy(replacer);
            foreach (PStm stm in mover.NewStatements)
            {
                stm.Apply(this);
            }
        }
 public override void CaseABinopExp(ABinopExp node)
 {
     if (folding)
     {
         node.GetLeft().Apply(this);
         int left = value;
         node.GetRight().Apply(this);
         int right = value;
         if (node.GetBinop() is APlusBinop)
             value = left + right;
         else if (node.GetBinop() is AMinusBinop)
             value = left - right;
         else if (node.GetBinop() is ATimesBinop)
             value = left * right;
         else if (node.GetBinop() is ADivideBinop)
         {
             if (right == 0)
             {
                 errors.Add(new ErrorCollection.Error(((ADivideBinop)node.GetBinop()).GetToken(), LocRM.GetString("ErrorText58")), true);
                 throw new ParserException(null, "SetArrayIndexes.CaseABinopExp");
             }
             value = left / right;
         }
         else if (node.GetBinop() is AModuloBinop)
         {
             if (right == 0)
             {
                 errors.Add(new ErrorCollection.Error(((AModuloBinop)node.GetBinop()).GetToken(), LocRM.GetString("ErrorText58")), true);
                 throw new ParserException(null, "EnviromentChecking.CaseABinopExp");
             }
             value = left % right;
         }
         else if (node.GetBinop() is AAndBinop)
             value = left & right;
         else if (node.GetBinop() is AOrBinop)
             value = left | right;
         else if (node.GetBinop() is AXorBinop)
             value = left ^ right;
         else if (node.GetBinop() is ALBitShiftBinop)
             value = left << right;
         else if (node.GetBinop() is ARBitShiftBinop)
             value = left >> right;
     }
     else
         base.CaseABinopExp(node);
 }
 public override void CaseAArrayLvalue(AArrayLvalue node)
 {
     bool containedLiteral = containsLiteral;
     containsLiteral = false;
     node.GetIndex().Apply(this);
     bool hasLiteral = containsLiteral;
     containsLiteral = containedLiteral;
     PType type = data.ExpTypes[node.GetIndex()];
     if (!hasLiteral && type is ANamedType && ((ANamedType)type).IsPrimitive("byte"))
     {
         AIntConstExp intConst = new AIntConstExp(new TIntegerLiteral("0"));
         ABinopExp binop = new ABinopExp(node.GetIndex(), new APlusBinop(new TPlus("+")), intConst);
         data.ExpTypes[intConst] =
             data.ExpTypes[binop] = new ANamedType(new TIdentifier("int"), null);
         node.SetIndex(binop);
     }
     node.GetBase().Apply(this);
 }
        private AMethodDecl CreateStringDeobfuscator()
        {
            AASourceFile file = (AASourceFile) finalTrans.mainEntry.Parent();

            //Create fields for the string constants
            AStringConstExp emptyStringConst = new AStringConstExp(new TStringLiteral("\"\""));
            AFieldDecl emptyStringField = new AFieldDecl(new APublicVisibilityModifier(), null, new TConst("const"),
                                                         new ANamedType(new TIdentifier("string"), null),
                                                         new TIdentifier("fOobar"), emptyStringConst);
            file.GetDecl().Add(emptyStringField);
            data.Fields.Add(new SharedData.DeclItem<AFieldDecl>(file, emptyStringField));
            AFieldLvalue emptyStringRef1 = new AFieldLvalue(new TIdentifier(emptyStringField.GetName().Text));
            AFieldLvalue emptyStringRef2 = new AFieldLvalue(new TIdentifier(emptyStringField.GetName().Text));
            AFieldLvalue emptyStringRef3 = new AFieldLvalue(new TIdentifier(emptyStringField.GetName().Text));
            ALvalueExp emptyStringRef1Exp = new ALvalueExp(emptyStringRef1);
            ALvalueExp emptyStringRef2Exp = new ALvalueExp(emptyStringRef2);
            ALvalueExp emptyStringRef3Exp = new ALvalueExp(emptyStringRef3);

            AStringConstExp colonStringConst = new AStringConstExp(new TStringLiteral("\":\""));
            AFieldDecl colonStringField = new AFieldDecl(new APublicVisibilityModifier(), null, new TConst("const"),
                                                         new ANamedType(new TIdentifier("string"), null),
                                                         new TIdentifier("foObar"), colonStringConst);
            file.GetDecl().Add(colonStringField);
            data.Fields.Add(new SharedData.DeclItem<AFieldDecl>(file, colonStringField));
            AFieldLvalue colonStringRef = new AFieldLvalue(new TIdentifier(colonStringField.GetName().Text));
            ALvalueExp colonStringRefExp = new ALvalueExp(colonStringRef);

            /*
                string output = "";
                string ch;
                int length = StringLength(s);
                int phase1 = (length - 1)%3;
                int phase2 = (length - 1)%2;
             */

            AALocalDecl stringParam = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                      new ANamedType(new TIdentifier("string"), null),
                                                      new TIdentifier("fo0bar"), emptyStringRef1Exp);
            ALocalLvalue stringParamRef1 = new ALocalLvalue(new TIdentifier(stringParam.GetName().Text));
            ALocalLvalue stringParamRef2 = new ALocalLvalue(new TIdentifier(stringParam.GetName().Text));
            ALocalLvalue stringParamRef3 = new ALocalLvalue(new TIdentifier(stringParam.GetName().Text));
            ALocalLvalue stringParamRef4 = new ALocalLvalue(new TIdentifier(stringParam.GetName().Text));
            ALocalLvalue stringParamRef5 = new ALocalLvalue(new TIdentifier(stringParam.GetName().Text));
            ALocalLvalue stringParamRef6 = new ALocalLvalue(new TIdentifier(stringParam.GetName().Text));
            ALocalLvalue stringParamRef7 = new ALocalLvalue(new TIdentifier(stringParam.GetName().Text));
            ALocalLvalue stringParamRef8 = new ALocalLvalue(new TIdentifier(stringParam.GetName().Text));
            ALvalueExp stringParamRef1Exp = new ALvalueExp(stringParamRef1);
            ALvalueExp stringParamRef2Exp = new ALvalueExp(stringParamRef2);
            ALvalueExp stringParamRef4Exp = new ALvalueExp(stringParamRef4);
            ALvalueExp stringParamRef5Exp = new ALvalueExp(stringParamRef5);
            ALvalueExp stringParamRef7Exp = new ALvalueExp(stringParamRef7);
            ALvalueExp stringParamRef8Exp = new ALvalueExp(stringParamRef8);

            AABlock methodBlock = new AABlock(new ArrayList(), new TRBrace("}"));

            AALocalDecl outputDecl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                     new ANamedType(new TIdentifier("string"), null),
                                                     new TIdentifier("foobar"), emptyStringRef1Exp);
            methodBlock.GetStatements().Add(new ALocalDeclStm(new TSemicolon(";"), outputDecl));
            ALocalLvalue outputRef1 = new ALocalLvalue(new TIdentifier(outputDecl.GetName().Text));
            ALocalLvalue outputRef2 = new ALocalLvalue(new TIdentifier(outputDecl.GetName().Text));
            ALocalLvalue outputRef3 = new ALocalLvalue(new TIdentifier(outputDecl.GetName().Text));
            ALocalLvalue outputRef4 = new ALocalLvalue(new TIdentifier(outputDecl.GetName().Text));
            ALocalLvalue outputRef5 = new ALocalLvalue(new TIdentifier(outputDecl.GetName().Text));
            ALocalLvalue outputRef6 = new ALocalLvalue(new TIdentifier(outputDecl.GetName().Text));
            ALocalLvalue outputRef7 = new ALocalLvalue(new TIdentifier(outputDecl.GetName().Text));
            ALocalLvalue outputRef8 = new ALocalLvalue(new TIdentifier(outputDecl.GetName().Text));
            ALocalLvalue outputRef9 = new ALocalLvalue(new TIdentifier(outputDecl.GetName().Text));
            ALocalLvalue outputRef10 = new ALocalLvalue(new TIdentifier(outputDecl.GetName().Text));
            ALocalLvalue outputRef11 = new ALocalLvalue(new TIdentifier(outputDecl.GetName().Text));
            ALocalLvalue outputRef12 = new ALocalLvalue(new TIdentifier(outputDecl.GetName().Text));
            ALocalLvalue outputRef13 = new ALocalLvalue(new TIdentifier(outputDecl.GetName().Text));
            ALvalueExp outputRef2Exp = new ALvalueExp(outputRef2);
            ALvalueExp outputRef4Exp = new ALvalueExp(outputRef4);
            ALvalueExp outputRef5Exp = new ALvalueExp(outputRef5);
            ALvalueExp outputRef6Exp = new ALvalueExp(outputRef6);
            ALvalueExp outputRef7Exp = new ALvalueExp(outputRef7);
            ALvalueExp outputRef8Exp = new ALvalueExp(outputRef8);
            ALvalueExp outputRef10Exp = new ALvalueExp(outputRef10);
            ALvalueExp outputRef11Exp = new ALvalueExp(outputRef11);
            ALvalueExp outputRef12Exp = new ALvalueExp(outputRef12);
            ALvalueExp outputRef13Exp = new ALvalueExp(outputRef13);

            AALocalDecl chDecl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                     new ANamedType(new TIdentifier("string"), null),
                                                     new TIdentifier("f0obar"), null);
            methodBlock.GetStatements().Add(new ALocalDeclStm(new TSemicolon(";"), chDecl));
            ALocalLvalue chRef1 = new ALocalLvalue(new TIdentifier(chDecl.GetName().Text));
            ALocalLvalue chRef2 = new ALocalLvalue(new TIdentifier(chDecl.GetName().Text));
            ALocalLvalue chRef3 = new ALocalLvalue(new TIdentifier(chDecl.GetName().Text));
            ALocalLvalue chRef4 = new ALocalLvalue(new TIdentifier(chDecl.GetName().Text));
            ALocalLvalue chRef5 = new ALocalLvalue(new TIdentifier(chDecl.GetName().Text));
            ALvalueExp chRef3Exp = new ALvalueExp(chRef3);
            ALvalueExp chRef4Exp = new ALvalueExp(chRef4);
            ALvalueExp chRef5Exp = new ALvalueExp(chRef5);

            ASimpleInvokeExp stringLengthInvoke1 = new ASimpleInvokeExp(new TIdentifier("StringLength"),
                                                                        new ArrayList() { stringParamRef1Exp });
            AALocalDecl lengthDecl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                     new ANamedType(new TIdentifier("int"), null),
                                                     new TIdentifier("f0Obar"), stringLengthInvoke1);
            methodBlock.GetStatements().Add(new ALocalDeclStm(new TSemicolon(";"), lengthDecl));
            ALocalLvalue lengthRef1 = new ALocalLvalue(new TIdentifier(lengthDecl.GetName().Text));
            ALocalLvalue lengthRef2 = new ALocalLvalue(new TIdentifier(lengthDecl.GetName().Text));
            ALocalLvalue lengthRef3 = new ALocalLvalue(new TIdentifier(lengthDecl.GetName().Text));
            ALocalLvalue lengthRef4 = new ALocalLvalue(new TIdentifier(lengthDecl.GetName().Text));
            ALocalLvalue lengthRef5 = new ALocalLvalue(new TIdentifier(lengthDecl.GetName().Text));
            ALocalLvalue lengthRef6 = new ALocalLvalue(new TIdentifier(lengthDecl.GetName().Text));
            ALocalLvalue lengthRef7 = new ALocalLvalue(new TIdentifier(lengthDecl.GetName().Text));
            ALocalLvalue lengthRef8 = new ALocalLvalue(new TIdentifier(lengthDecl.GetName().Text));
            ALvalueExp lengthRef1Exp = new ALvalueExp(lengthRef1);
            ALvalueExp lengthRef2Exp = new ALvalueExp(lengthRef2);
            ALvalueExp lengthRef3Exp = new ALvalueExp(lengthRef3);
            ALvalueExp lengthRef4Exp = new ALvalueExp(lengthRef4);
            ALvalueExp lengthRef5Exp = new ALvalueExp(lengthRef5);
            ALvalueExp lengthRef6Exp = new ALvalueExp(lengthRef6);
            ALvalueExp lengthRef7Exp = new ALvalueExp(lengthRef7);

            AIntConstExp intConstp1Init1 = new AIntConstExp(new TIntegerLiteral("1"));
            AIntConstExp intConstp1Init2 = new AIntConstExp(new TIntegerLiteral("3"));
            ABinopExp binopExpP1InitMinus = new ABinopExp(lengthRef1Exp, new AMinusBinop(new TMinus("-")), intConstp1Init1);
            ABinopExp binopExpP1InitMod = new ABinopExp(binopExpP1InitMinus, new AModuloBinop(new TMod("%")), intConstp1Init2);

            AALocalDecl phase1Decl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                     new ANamedType(new TIdentifier("int"), null),
                                                     new TIdentifier("fO0bar"), binopExpP1InitMod);
            methodBlock.GetStatements().Add(new ALocalDeclStm(new TSemicolon(";"), phase1Decl));
            ALocalLvalue phase1Ref1 = new ALocalLvalue(new TIdentifier(phase1Decl.GetName().Text));
            ALocalLvalue phase1Ref2 = new ALocalLvalue(new TIdentifier(phase1Decl.GetName().Text));
            ALocalLvalue phase1Ref3 = new ALocalLvalue(new TIdentifier(phase1Decl.GetName().Text));
            ALocalLvalue phase1Ref4 = new ALocalLvalue(new TIdentifier(phase1Decl.GetName().Text));
            ALocalLvalue phase1Ref5 = new ALocalLvalue(new TIdentifier(phase1Decl.GetName().Text));
            ALocalLvalue phase1Ref6 = new ALocalLvalue(new TIdentifier(phase1Decl.GetName().Text));
            ALocalLvalue phase1Ref7 = new ALocalLvalue(new TIdentifier(phase1Decl.GetName().Text));
            ALocalLvalue phase1Ref8 = new ALocalLvalue(new TIdentifier(phase1Decl.GetName().Text));
            ALocalLvalue phase1Ref9 = new ALocalLvalue(new TIdentifier(phase1Decl.GetName().Text));
            ALocalLvalue phase1Ref10 = new ALocalLvalue(new TIdentifier(phase1Decl.GetName().Text));
            ALocalLvalue phase1Ref11 = new ALocalLvalue(new TIdentifier(phase1Decl.GetName().Text));
            ALvalueExp phase1Ref1Exp = new ALvalueExp(phase1Ref1);
            ALvalueExp phase1Ref2Exp = new ALvalueExp(phase1Ref2);
            ALvalueExp phase1Ref4Exp = new ALvalueExp(phase1Ref4);
            ALvalueExp phase1Ref5Exp = new ALvalueExp(phase1Ref5);
            ALvalueExp phase1Ref7Exp = new ALvalueExp(phase1Ref7);
            ALvalueExp phase1Ref9Exp = new ALvalueExp(phase1Ref9);
            ALvalueExp phase1Ref10Exp = new ALvalueExp(phase1Ref10);
            ALvalueExp phase1Ref11Exp = new ALvalueExp(phase1Ref11);

            AIntConstExp intConstp2Init1 = new AIntConstExp(new TIntegerLiteral("1"));
            AIntConstExp intConstp2Init2 = new AIntConstExp(new TIntegerLiteral("2"));
            ABinopExp binopExpP2InitMinus = new ABinopExp(lengthRef2Exp, new AMinusBinop(new TMinus("-")), intConstp2Init1);
            ABinopExp binopExpP2InitMod = new ABinopExp(binopExpP2InitMinus, new AModuloBinop(new TMod("%")), intConstp2Init2);

            AALocalDecl phase2Decl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                     new ANamedType(new TIdentifier("int"), null),
                                                     new TIdentifier("carl"), binopExpP2InitMod);
            methodBlock.GetStatements().Add(new ALocalDeclStm(new TSemicolon(";"), phase2Decl));
            ALocalLvalue phase2Ref1 = new ALocalLvalue(new TIdentifier(phase2Decl.GetName().Text));
            ALocalLvalue phase2Ref2 = new ALocalLvalue(new TIdentifier(phase2Decl.GetName().Text));
            ALocalLvalue phase2Ref3 = new ALocalLvalue(new TIdentifier(phase2Decl.GetName().Text));
            ALocalLvalue phase2Ref4 = new ALocalLvalue(new TIdentifier(phase2Decl.GetName().Text));
            ALocalLvalue phase2Ref5 = new ALocalLvalue(new TIdentifier(phase2Decl.GetName().Text));
            ALocalLvalue phase2Ref6 = new ALocalLvalue(new TIdentifier(phase2Decl.GetName().Text));
            ALocalLvalue phase2Ref7 = new ALocalLvalue(new TIdentifier(phase2Decl.GetName().Text));
            ALocalLvalue phase2Ref8 = new ALocalLvalue(new TIdentifier(phase2Decl.GetName().Text));
            ALocalLvalue phase2Ref9 = new ALocalLvalue(new TIdentifier(phase2Decl.GetName().Text));
            ALvalueExp phase2Ref1Exp = new ALvalueExp(phase2Ref1);
            ALvalueExp phase2Ref2Exp = new ALvalueExp(phase2Ref2);
            ALvalueExp phase2Ref4Exp = new ALvalueExp(phase2Ref4);
            ALvalueExp phase2Ref5Exp = new ALvalueExp(phase2Ref5);
            ALvalueExp phase2Ref7Exp = new ALvalueExp(phase2Ref7);
            ALvalueExp phase2Ref9Exp = new ALvalueExp(phase2Ref9);

            /*
                while(length > 0)
                {
                    if(phase2 == 0)
                    {
                        ch = StringSub(s, 1, 1);
                        s = StringReplace(s, "", 1, 1);
                    }
                    else
                    {
                        if(phase2 == 1)
                        {
                            ch = StringSub(s, length, length);
                            s = StringReplace(s, "", length, length);
                        }
                    }

                    if(phase1 == 0)
                    {
                        output = ch + output;
                    }
                    else
                    {
                        if(phase1 == 1)
                        {
                            output = StringSub(output, 1, (StringLength(output) + 1)/2) + ch + StringSub(output, (StringLength(output) + 1)/2 + 1, StringLength(output));
                        }
                        else
                        {
                            output = output + ch;
                        }
                    }
                    phase1 = phase1 - 1;
                    if(phase1 < 0)
                    {
                        phase1 = phase1 + 3;
                    }
                    phase2 = phase2 - 1;
                    if(phase2 < 0)
                    {
                        phase2 = phase2 + 2;
                    }
                    length = StringLength(s);
                }
             */

            AABlock whileBlock = new AABlock(new ArrayList(), new TRBrace("}"));
            AIntConstExp intConstWhileCond = new AIntConstExp(new TIntegerLiteral("0"));
            ABinopExp binopWhileCond = new ABinopExp(lengthRef3Exp, new AGtBinop(new TGt(">")), intConstWhileCond);
            methodBlock.GetStatements().Add(new AWhileStm(new TLParen("("), binopWhileCond,
                                                          new ABlockStm(new TLBrace("{"), whileBlock)));

            /*
                    if(phase2 == 0)
                    {
                        ch = StringSub(s, 1, 1);
                        s = StringReplace(s, "", 1, 1);
                    }
                    else
                    {
                        if(phase2 == 1)
                        {
                            ch = StringSub(s, length, length);
                            s = StringReplace(s, "", length, length);
                        }
                    }
             */
            AIntConstExp intConstIf1Cond = new AIntConstExp(new TIntegerLiteral("0"));
            ABinopExp binopIf1Cond = new ABinopExp(phase2Ref1Exp, new AEqBinop(new TEq("==")), intConstIf1Cond);
            AABlock thenBlock = new AABlock();
            AABlock elseBlock = new AABlock();
            whileBlock.GetStatements().Add(new AIfThenElseStm(new TLParen("("), binopIf1Cond,
                                                              new ABlockStm(new TLBrace("{"), thenBlock),
                                                              new ABlockStm(new TLBrace("{"), elseBlock)));

            //ch = StringSub(s, 1, 1);
            AIntConstExp intConst1 = new AIntConstExp(new TIntegerLiteral("1"));
            AIntConstExp intConst2 = new AIntConstExp(new TIntegerLiteral("1"));
            ASimpleInvokeExp invokeStringSub1 = new ASimpleInvokeExp(new TIdentifier("StringSub"),
                                                           new ArrayList() {stringParamRef2Exp, intConst1, intConst2});
            AAssignmentExp assignment1 = new AAssignmentExp(new TAssign("="), chRef1, invokeStringSub1);
            thenBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), assignment1));

            //s = StringReplace(s, "", 1, 1);
            AIntConstExp intConst3 = new AIntConstExp(new TIntegerLiteral("1"));
            AIntConstExp intConst4 = new AIntConstExp(new TIntegerLiteral("1"));
            ASimpleInvokeExp invokeStringReplace1 = new ASimpleInvokeExp(new TIdentifier("StringReplace"),
                                                           new ArrayList() { stringParamRef4Exp, emptyStringRef2Exp, intConst3, intConst4 });
            AAssignmentExp assignment2 = new AAssignmentExp(new TAssign("="), stringParamRef3, invokeStringReplace1);
            thenBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), assignment2));

            //if(phase2 == 1)
            AIntConstExp intConst5 = new AIntConstExp(new TIntegerLiteral("1"));
            ABinopExp binop1 = new ABinopExp(phase2Ref2Exp, new AEqBinop(new TEq("==")), intConst5);
            thenBlock = new AABlock();
            elseBlock.GetStatements().Add(new AIfThenStm(new TLParen("("), binop1,
                                                         new ABlockStm(new TLBrace("{"), thenBlock)));

            //ch = StringSub(s, length, length);
            ASimpleInvokeExp invokeStringSub2 = new ASimpleInvokeExp(new TIdentifier("StringSub"),
                                                           new ArrayList() { stringParamRef5Exp, lengthRef3Exp, lengthRef4Exp });
            AAssignmentExp assignment3 = new AAssignmentExp(new TAssign("="), chRef2, invokeStringSub2);
            thenBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), assignment3));

            //s = StringReplace(s, "", length, length);
            ASimpleInvokeExp invokeStringReplace2 = new ASimpleInvokeExp(new TIdentifier("StringReplace"),
                                                           new ArrayList() { stringParamRef7Exp, emptyStringRef3Exp, lengthRef5Exp, lengthRef6Exp });
            AAssignmentExp assignment4 = new AAssignmentExp(new TAssign("="), stringParamRef6, invokeStringReplace2);
            thenBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), assignment4));

            //if(phase1 == 0)
            AIntConstExp intConst6 = new AIntConstExp(new TIntegerLiteral("0"));
            ABinopExp binop2 = new ABinopExp(phase1Ref1Exp, new AEqBinop(new TEq("==")), intConst6);
            thenBlock = new AABlock();
            elseBlock = new AABlock();
            whileBlock.GetStatements().Add(new AIfThenElseStm(new TLParen("("), binop2,
                                                              new ABlockStm(new TLBrace("{"), thenBlock),
                                                              new ABlockStm(new TLBrace("{"), elseBlock)));

            //output = ch + output;
            ABinopExp binop3 = new ABinopExp(chRef3Exp, new APlusBinop(new TPlus("+")), outputRef2Exp);
            AAssignmentExp assignment5 = new AAssignmentExp(new TAssign("="), outputRef1, binop3);
            thenBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), assignment5));

            //if(phase1 == 1)
            AABlock cBlock = elseBlock;
            AIntConstExp intConst7 = new AIntConstExp(new TIntegerLiteral("1"));
            ABinopExp binop4 = new ABinopExp(phase1Ref2Exp, new AEqBinop(new TEq("==")), intConst7);
            thenBlock = new AABlock();
            elseBlock = new AABlock();
            cBlock.GetStatements().Add(new AIfThenElseStm(new TLParen("("), binop4,
                                                              new ABlockStm(new TLBrace("{"), thenBlock),
                                                              new ABlockStm(new TLBrace("{"), elseBlock)));

            //output = StringSub(output, 1, (StringLength(output) + 1)/2) + ch + StringSub(output, (StringLength(output) + 1)/2 + 1, StringLength(output));
            AIntConstExp intConst8 = new AIntConstExp(new TIntegerLiteral("1"));
            AIntConstExp intConst9 = new AIntConstExp(new TIntegerLiteral("1"));
            AIntConstExp intConst10 = new AIntConstExp(new TIntegerLiteral("2"));
            AIntConstExp intConst11 = new AIntConstExp(new TIntegerLiteral("1"));
            AIntConstExp intConst12 = new AIntConstExp(new TIntegerLiteral("2"));
            AIntConstExp intConst13 = new AIntConstExp(new TIntegerLiteral("1"));

            ASimpleInvokeExp invokeStringLength1 = new ASimpleInvokeExp(new TIdentifier("StringLength"),
                                                                        new ArrayList() {outputRef5Exp});
            ABinopExp binop5 = new ABinopExp(invokeStringLength1, new APlusBinop(new TPlus("+")), intConst9);
            ABinopExp binop6 = new ABinopExp(binop5, new ADivideBinop(new TDiv("/")), intConst10);

            ASimpleInvokeExp invokeStringSub3 = new ASimpleInvokeExp(new TIdentifier("StringSub"),
                                                           new ArrayList() { outputRef4Exp, intConst8, binop6});

            ABinopExp binop7 = new ABinopExp(invokeStringSub3, new APlusBinop(new TPlus("+")), chRef4Exp);

            ASimpleInvokeExp invokeStringLength2 = new ASimpleInvokeExp(new TIdentifier("StringLength"),
                                                                        new ArrayList() { outputRef7Exp });
            ABinopExp binop8 = new ABinopExp(invokeStringLength2, new APlusBinop(new TPlus("+")), intConst11);
            ABinopExp binop9 = new ABinopExp(binop8, new ADivideBinop(new TDiv("/")), intConst12);
            ABinopExp binop10 = new ABinopExp(binop9, new APlusBinop(new TPlus("+")), intConst13);

            ASimpleInvokeExp invokeStringLength3 = new ASimpleInvokeExp(new TIdentifier("StringLength"),
                                                                        new ArrayList() { outputRef8Exp });

            ASimpleInvokeExp invokeStringSub4 = new ASimpleInvokeExp(new TIdentifier("StringSub"),
                                                           new ArrayList() { outputRef6Exp, binop10, invokeStringLength3 });

            ABinopExp binop11 = new ABinopExp(binop7, new APlusBinop(new TPlus("+")), invokeStringSub4);

            AAssignmentExp assignment6 = new AAssignmentExp(new TAssign("="), outputRef3, binop11);

            thenBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), assignment6));

            //output = output + ch;
            ABinopExp binop12 = new ABinopExp(outputRef10Exp, new APlusBinop(new TPlus("+")), chRef5Exp);
            AAssignmentExp assignment7 = new AAssignmentExp(new TAssign("="), outputRef9, binop12);
            elseBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), assignment7));

            //phase1 = phase1 - 1;
            AIntConstExp intConst14 = new AIntConstExp(new TIntegerLiteral("1"));
            ABinopExp binop13 = new ABinopExp(phase1Ref4Exp, new AMinusBinop(new TMinus("-")), intConst14);
            AAssignmentExp assignment8 = new AAssignmentExp(new TAssign("="), phase1Ref3, binop13);
            whileBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), assignment8));

            //if(phase1 < 0)
            AIntConstExp intConst15 = new AIntConstExp(new TIntegerLiteral("0"));
            ABinopExp binop14 = new ABinopExp(phase1Ref5Exp, new ALtBinop(new TLt("<")), intConst15);
            thenBlock = new AABlock();
            whileBlock.GetStatements().Add(new AIfThenStm(new TLParen("("), binop14,
                                                         new ABlockStm(new TLBrace("{"), thenBlock)));

            //phase1 = phase1 + 3;
            AIntConstExp intConst16 = new AIntConstExp(new TIntegerLiteral("3"));
            ABinopExp binop15 = new ABinopExp(phase1Ref7Exp, new APlusBinop(new TPlus("+")), intConst16);
            AAssignmentExp assignment9 = new AAssignmentExp(new TAssign("="), phase1Ref6, binop15);
            thenBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), assignment9));

            //phase2 = phase2 - 1;
            AIntConstExp intConst17 = new AIntConstExp(new TIntegerLiteral("1"));
            ABinopExp binop16 = new ABinopExp(phase2Ref4Exp, new AMinusBinop(new TMinus("-")), intConst17);
            AAssignmentExp assignment10 = new AAssignmentExp(new TAssign("="), phase2Ref3, binop16);
            whileBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), assignment10));

            //if(phase2 < 0)
            AIntConstExp intConst18 = new AIntConstExp(new TIntegerLiteral("0"));
            ABinopExp binop17 = new ABinopExp(phase2Ref5Exp, new ALtBinop(new TLt("<")), intConst18);
            thenBlock = new AABlock();
            whileBlock.GetStatements().Add(new AIfThenStm(new TLParen("("), binop17,
                                                         new ABlockStm(new TLBrace("{"), thenBlock)));

            //phase2 = phase2 + 2;
            AIntConstExp intConst19 = new AIntConstExp(new TIntegerLiteral("2"));
            ABinopExp binop18 = new ABinopExp(phase2Ref7Exp, new APlusBinop(new TPlus("+")), intConst19);
            AAssignmentExp assignment11 = new AAssignmentExp(new TAssign("="), phase2Ref6, binop18);
            thenBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), assignment11));

            //length = StringLength(s);
            ASimpleInvokeExp invokeStringLength4 = new ASimpleInvokeExp(new TIdentifier("StringLength"),
                                                                        new ArrayList() { stringParamRef8Exp });
            AAssignmentExp assignment12 = new AAssignmentExp(new TAssign("="), lengthRef8, invokeStringLength4);
            whileBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), assignment12));

            /*
                phase1 = StringFind(output, ":", false);
                phase2 = StringToInt(StringSub(output, 1, phase1 - 1));
                return StringSub(output, phase1 + 1, phase2 + phase1);
             */

            ABooleanConstExp boolConst1 = new ABooleanConstExp(new AFalseBool());
            ASimpleInvokeExp invokeStringFind = new ASimpleInvokeExp(new TIdentifier("StringFind"),
                                                                     new ArrayList()
                                                                         {outputRef11Exp, colonStringRefExp, boolConst1});
            AAssignmentExp assignment13 = new AAssignmentExp(new TAssign("="), phase1Ref8, invokeStringFind);
            methodBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), assignment13));

            //phase2 = StringToInt(StringSub(output, 1, phase1 - 1));
            AIntConstExp intConst20 = new AIntConstExp(new TIntegerLiteral("1"));
            AIntConstExp intConst21 = new AIntConstExp(new TIntegerLiteral("1"));
            ABinopExp binop19 = new ABinopExp(phase1Ref9Exp, new AMinusBinop(new TMinus("-")), intConst21);
            ASimpleInvokeExp invokeStringSub5 = new ASimpleInvokeExp(new TIdentifier("StringSub"),
                                                           new ArrayList() { outputRef12Exp, intConst20, binop19});
            ASimpleInvokeExp invokeStringToInt = new ASimpleInvokeExp(new TIdentifier("StringToInt"),
                                                                      new ArrayList() { invokeStringSub5 });
            AAssignmentExp assignment14 = new AAssignmentExp(new TAssign("="), phase2Ref8, invokeStringToInt);
            methodBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), assignment14));

            //return StringSub(output, phase1 + 1, phase2 + phase1);
            AIntConstExp intConst22 = new AIntConstExp(new TIntegerLiteral("1"));
            ABinopExp binop20 = new ABinopExp(phase1Ref10Exp, new APlusBinop(new TPlus("+")), intConst22);
            ABinopExp binop21 = new ABinopExp(phase2Ref9Exp, new APlusBinop(new TPlus("+")), phase1Ref11Exp);
            ASimpleInvokeExp invokeStringSub6 = new ASimpleInvokeExp(new TIdentifier("StringSub"),
                                                           new ArrayList() { outputRef12Exp, binop20, binop21 });
            methodBlock.GetStatements().Add(new AValueReturnStm(new TReturn("return"), invokeStringSub6));

            AMethodDecl method = new AMethodDecl(new APublicVisibilityModifier(), null, null, null, null, null,
                                                 new ANamedType(new TIdentifier("string"), null),
                                                 new TIdentifier("Galaxypp_Deobfuscate"), new ArrayList() {stringParam},
                                                 methodBlock);

            //Fix data refferences.. I got tired here.

            return method;
        }
 private PExp Combine(PExp left, List<string> strings)
 {
     AStringConstExp right = new AStringConstExp(new TStringLiteral("\"" + strings[0] + "\""));
     strings.RemoveAt(0);
     ABinopExp binop = new ABinopExp(left, new APlusBinop(new TPlus("+")), right);
     data.StringsDontJoinRight.Add(right);
     data.ExpTypes[right] =
         data.ExpTypes[binop] = new ANamedType(new TIdentifier("string"), null);
     if (strings.Count > 0)
         return Combine(binop, strings);
     return binop;
 }
        public override void OutABinopExp(ABinopExp node)
        {
            if (node.Parent() is ABinopExp || node.Parent() is AUnopExp)
            {
                AParenExp paren = new AParenExp();
                node.ReplaceBy(paren);
                paren.SetExp(node);

                finalTrans.data.ExpTypes[paren] = finalTrans.data.ExpTypes[node];
            }
            base.OutABinopExp(node);
        }
Exemplo n.º 7
0
 public virtual void InABinopExp(ABinopExp node)
 {
     DefaultIn(node);
 }
Exemplo n.º 8
0
 public override void CaseABinopExp(ABinopExp node)
 {
     InABinopExp(node);
     if (node.GetRight() != null)
     {
         node.GetRight().Apply(this);
     }
     if (node.GetBinop() != null)
     {
         node.GetBinop().Apply(this);
     }
     if (node.GetLeft() != null)
     {
         node.GetLeft().Apply(this);
     }
     OutABinopExp(node);
 }
Exemplo n.º 9
0
 ArrayList New490()
 {
     ArrayList nodeList = new ArrayList();
     ArrayList nodeArrayList3 = (ArrayList) Pop();
     ArrayList nodeArrayList2 = (ArrayList) Pop();
     ArrayList nodeArrayList1 = (ArrayList) Pop();
     PExp pexpNode2 = (PExp)nodeArrayList1[0];
     TGt tgtNode4 = (TGt)nodeArrayList2[0];
     AGtBinop pbinopNode3 = new AGtBinop (
       tgtNode4
     );
     PExp pexpNode5 = (PExp)nodeArrayList3[0];
     ABinopExp pexpNode1 = new ABinopExp (
       pexpNode2,
       pbinopNode3,
       pexpNode5
     );
     nodeList.Add(pexpNode1);
     return nodeList;
 }
Exemplo n.º 10
0
 ArrayList New487()
 {
     ArrayList nodeList = new ArrayList();
     ArrayList nodeArrayList3 = (ArrayList) Pop();
     ArrayList nodeArrayList2 = (ArrayList) Pop();
     ArrayList nodeArrayList1 = (ArrayList) Pop();
     PExp pexpNode2 = (PExp)nodeArrayList1[0];
     TRBitShift trbitshiftNode4 = (TRBitShift)nodeArrayList2[0];
     ARBitShiftBinop pbinopNode3 = new ARBitShiftBinop (
       trbitshiftNode4
     );
     PExp pexpNode5 = (PExp)nodeArrayList3[0];
     ABinopExp pexpNode1 = new ABinopExp (
       pexpNode2,
       pbinopNode3,
       pexpNode5
     );
     nodeList.Add(pexpNode1);
     return nodeList;
 }
Exemplo n.º 11
0
 ArrayList New484()
 {
     ArrayList nodeList = new ArrayList();
     ArrayList nodeArrayList3 = (ArrayList) Pop();
     ArrayList nodeArrayList2 = (ArrayList) Pop();
     ArrayList nodeArrayList1 = (ArrayList) Pop();
     PExp pexpNode2 = (PExp)nodeArrayList1[0];
     TMinus tminusNode4 = (TMinus)nodeArrayList2[0];
     AMinusBinop pbinopNode3 = new AMinusBinop (
       tminusNode4
     );
     PExp pexpNode5 = (PExp)nodeArrayList3[0];
     ABinopExp pexpNode1 = new ABinopExp (
       pexpNode2,
       pbinopNode3,
       pexpNode5
     );
     nodeList.Add(pexpNode1);
     return nodeList;
 }
Exemplo n.º 12
0
 ArrayList New481()
 {
     ArrayList nodeList = new ArrayList();
     ArrayList nodeArrayList3 = (ArrayList) Pop();
     ArrayList nodeArrayList2 = (ArrayList) Pop();
     ArrayList nodeArrayList1 = (ArrayList) Pop();
     PExp pexpNode2 = (PExp)nodeArrayList1[0];
     TMod tmodNode4 = (TMod)nodeArrayList2[0];
     AModuloBinop pbinopNode3 = new AModuloBinop (
       tmodNode4
     );
     PExp pexpNode5 = (PExp)nodeArrayList3[0];
     ABinopExp pexpNode1 = new ABinopExp (
       pexpNode2,
       pbinopNode3,
       pexpNode5
     );
     nodeList.Add(pexpNode1);
     return nodeList;
 }
Exemplo n.º 13
0
 ArrayList New480()
 {
     ArrayList nodeList = new ArrayList();
     ArrayList nodeArrayList3 = (ArrayList) Pop();
     ArrayList nodeArrayList2 = (ArrayList) Pop();
     ArrayList nodeArrayList1 = (ArrayList) Pop();
     PExp pexpNode2 = (PExp)nodeArrayList1[0];
     TDiv tdivNode4 = (TDiv)nodeArrayList2[0];
     ADivideBinop pbinopNode3 = new ADivideBinop (
       tdivNode4
     );
     PExp pexpNode5 = (PExp)nodeArrayList3[0];
     ABinopExp pexpNode1 = new ABinopExp (
       pexpNode2,
       pbinopNode3,
       pexpNode5
     );
     nodeList.Add(pexpNode1);
     return nodeList;
 }
Exemplo n.º 14
0
 ArrayList New479()
 {
     ArrayList nodeList = new ArrayList();
     ArrayList nodeArrayList3 = (ArrayList) Pop();
     ArrayList nodeArrayList2 = (ArrayList) Pop();
     ArrayList nodeArrayList1 = (ArrayList) Pop();
     PExp pexpNode2 = (PExp)nodeArrayList1[0];
     TStar tstarNode4 = (TStar)nodeArrayList2[0];
     ATimesBinop pbinopNode3 = new ATimesBinop (
       tstarNode4
     );
     PExp pexpNode5 = (PExp)nodeArrayList3[0];
     ABinopExp pexpNode1 = new ABinopExp (
       pexpNode2,
       pbinopNode3,
       pexpNode5
     );
     nodeList.Add(pexpNode1);
     return nodeList;
 }
Exemplo n.º 15
0
        private AMethodDecl GetStringPointerMethod()
        {
            if (GetStringPointerPartMethod != null)
                return GetStringPointerPartMethod;
            /*
             *  string GetPointerPart(string delegate)
             *  {
             *      return StringSub(delegate, StringFind(delegate, ":", false) + 1, StringLength(delegate));
             *  }
             */

            AASourceFile sourceFile = Util.GetAncestor<AASourceFile>(finalTrans.mainEntry);
            AALocalDecl delegateFormal = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                         new ANamedType(new TIdentifier("string"), null),
                                                         new TIdentifier("delegate"), null);
            ALocalLvalue delegateRef1 = new ALocalLvalue(new TIdentifier("delegate"));
            ALocalLvalue delegateRef2 = new ALocalLvalue(new TIdentifier("delegate"));
            ALocalLvalue delegateRef3 = new ALocalLvalue(new TIdentifier("delegate"));
            ALvalueExp delegateRef1Exp = new ALvalueExp(delegateRef1);
            ALvalueExp delegateRef2Exp = new ALvalueExp(delegateRef2);
            ALvalueExp delegateRef3Exp = new ALvalueExp(delegateRef3);

            AStringConstExp stringConst = new AStringConstExp(new TStringLiteral("\":\""));
            ABooleanConstExp booleanConst = new ABooleanConstExp(new AFalseBool());
            ASimpleInvokeExp stringFindInvoke = new ASimpleInvokeExp(new TIdentifier("StringFind"), new ArrayList(){delegateRef2Exp, stringConst, booleanConst});
            AIntConstExp intConst = new AIntConstExp(new TIntegerLiteral("1"));
            ABinopExp binop = new ABinopExp(stringFindInvoke, new APlusBinop(new TPlus("+")), intConst);

            ASimpleInvokeExp stringLengthInvoke = new ASimpleInvokeExp(new TIdentifier("StringLength"), new ArrayList() { delegateRef3Exp });

            ASimpleInvokeExp stringSubInvoke = new ASimpleInvokeExp(new TIdentifier("StringSub"), new ArrayList(){delegateRef1Exp, binop, stringLengthInvoke});

            GetStringPointerPartMethod = new AMethodDecl(new APublicVisibilityModifier(), null, null, null, null, null,
                                                 new ANamedType(new TIdentifier("string"), null),
                                                 new TIdentifier("GetPointerPart", finalTrans.data.LineCounts[sourceFile] + 1, 1), new ArrayList() {delegateFormal},
                                                 new AABlock(
                                                     new ArrayList()
                                                         {new AValueReturnStm(new TReturn("return"), stringSubInvoke)},
                                                     new TRBrace("}")));
            sourceFile.GetDecl().Add(GetStringPointerPartMethod);
            data.Methods.Add(new SharedData.DeclItem<AMethodDecl>(sourceFile, GetStringPointerPartMethod));

            finalTrans.data.LocalLinks[delegateRef1] =
                finalTrans.data.LocalLinks[delegateRef2] =
                finalTrans.data.LocalLinks[delegateRef3] = delegateFormal;
            finalTrans.data.LvalueTypes[delegateRef1] =
                finalTrans.data.LvalueTypes[delegateRef2] =
                finalTrans.data.LvalueTypes[delegateRef3] =
                finalTrans.data.ExpTypes[delegateRef1Exp] =
                finalTrans.data.ExpTypes[delegateRef2Exp] =
                finalTrans.data.ExpTypes[delegateRef3Exp] =
                finalTrans.data.ExpTypes[stringConst] =
                finalTrans.data.ExpTypes[stringSubInvoke] = new ANamedType(new TIdentifier("string"), null);
            finalTrans.data.ExpTypes[booleanConst] = new ANamedType(new TIdentifier("bool"), null);
            finalTrans.data.ExpTypes[intConst] =
                finalTrans.data.ExpTypes[binop] =
                finalTrans.data.ExpTypes[stringFindInvoke] =
                finalTrans.data.ExpTypes[stringLengthInvoke] = new ANamedType(new TIdentifier("int"), null);

            finalTrans.data.SimpleMethodLinks[stringFindInvoke] =
                finalTrans.data.Libraries.Methods.First(m => m.GetName().Text == stringFindInvoke.GetName().Text);
            finalTrans.data.SimpleMethodLinks[stringLengthInvoke] =
                finalTrans.data.Libraries.Methods.First(m => m.GetName().Text == stringLengthInvoke.GetName().Text);
            finalTrans.data.SimpleMethodLinks[stringSubInvoke] =
                finalTrans.data.Libraries.Methods.First(m => m.GetName().Text == stringSubInvoke.GetName().Text);

            return GetStringPointerPartMethod;
        }
Exemplo n.º 16
0
        public override void OutACastExp(ACastExp node)
        {
            string toType = ((AAName)((ANamedType) node.GetType()).GetName()).AsString();
            string fromType;
            PType fromPType = data.ExpTypes[node.GetExp()];
            AStructDecl toEnum = null;
            AStructDecl fromEnum = null;

            if (data.StructTypeLinks.ContainsKey((ANamedType)node.GetType()))
            {
                AStructDecl str = data.StructTypeLinks[(ANamedType)node.GetType()];
                if (data.Enums.ContainsKey(str))
                    toEnum = str;
            }
            if (fromPType is ANamedType)
            {
                fromType = ((AAName)((ANamedType)fromPType).GetName()).AsString();
                //Namespace ignored
                if (data.StructTypeLinks.ContainsKey((ANamedType) fromPType))
                {
                    AStructDecl str = data.StructTypeLinks[(ANamedType) fromPType];
                    if (data.Enums.ContainsKey(str))
                        fromEnum = str;
                }
            }
            else
            {
                errors.Add(new ErrorCollection.Error(node.GetToken(), currentSourceFile, LocRM.GetString("ErrorText121")));
                throw new ParserException(node.GetToken(), "Invalid cast");
            }

            if (toEnum != null && (fromType == "int" || fromType == "byte"))
            {
                ANamedType type = new ANamedType(new TIdentifier(toEnum.GetName().Text), null);
                data.StructTypeLinks[type] = toEnum;
                data.ExpTypes[node.GetExp()] = type;
                node.ReplaceBy(node.GetExp());
                return;
            }

            if (fromEnum != null && (toType == "int" || toType == "byte"))
            {
                int enumDefinitions = 0;
                foreach (PLocalDecl local in fromEnum.GetLocals())
                {
                    if (local is AALocalDecl)
                        enumDefinitions++;
                }
                string typeName = enumDefinitions > 255 ? "int" : "byte";
                ANamedType type = new ANamedType(new TIdentifier(typeName), null);
                data.ExpTypes[node.GetExp()] = new ANamedType(new TIdentifier(typeName), null);
                node.ReplaceBy(node.GetExp());
                return;
            }

            if (fromEnum != null && toType == "string")
            {
                AMethodDecl targetMethod = data.StructMethods[fromEnum][0];
                ASimpleInvokeExp invokeExp = new ASimpleInvokeExp(new TIdentifier("toString"), new ArrayList(){node.GetExp()});
                data.SimpleMethodLinks[invokeExp] = targetMethod;
                data.ExpTypes[invokeExp] = targetMethod.GetReturnType();
                node.ReplaceBy(invokeExp);
                return;
            }

            ASimpleInvokeExp replacementMethod = null;
            switch (toType)
            {
                case "string":
                    switch (fromType)
                    {
                        case "wave":
                            replacementMethod = new ASimpleInvokeExp(new TIdentifier("AIWaveToString"), new ArrayList{node.GetExp()});
                            break;
                        case "fixed"://Implicit
                            AFieldLvalue precisionArg = new AFieldLvalue(new TIdentifier("c_fixedPrecisionAny"));
                            ALvalueExp exp = new ALvalueExp(precisionArg);
                            data.FieldLinks[precisionArg] =
                                data.Libraries.Fields.First(field => field.GetName().Text == precisionArg.GetName().Text);
                            replacementMethod = new ASimpleInvokeExp(new TIdentifier("FixedToString"), new ArrayList { node.GetExp(), exp});
                            break;
                        case "int"://Implicit
                        case "byte"://Implicit
                            replacementMethod = new ASimpleInvokeExp(new TIdentifier("IntToString"), new ArrayList { node.GetExp()});
                            break;
                        case "bool"://Implicit
                            replacementMethod = new ASimpleInvokeExp(new TIdentifier("libNtve_gf_ConvertBooleanToString"), new ArrayList { node.GetExp() });
                            break;
                        case "color"://Implicit
                            replacementMethod = new ASimpleInvokeExp(new TIdentifier("libNtve_gf_ConvertColorToString"), new ArrayList { node.GetExp() });
                            break;
                    }
                    break;
                case "text":
                    switch (fromType)
                    {
                        case "wave":
                            replacementMethod = new ASimpleInvokeExp(new TIdentifier("AIWaveToText"), new ArrayList { node.GetExp() });
                            break;
                        case "fixed"://Implicit
                            AFieldLvalue precisionArg = new AFieldLvalue(new TIdentifier("c_fixedPrecisionAny"));
                            ALvalueExp exp = new ALvalueExp(precisionArg);
                            data.FieldLinks[precisionArg] =
                                data.Libraries.Fields.First(field => field.GetName().Text == precisionArg.GetName().Text);
                            replacementMethod = new ASimpleInvokeExp(new TIdentifier("FixedToText"), new ArrayList { node.GetExp(), exp });
                            break;
                        case "int"://Implicit
                        case "byte":
                            replacementMethod = new ASimpleInvokeExp(new TIdentifier("IntToText"), new ArrayList { node.GetExp() });
                            break;
                        case "bool"://Implicit
                            replacementMethod = new ASimpleInvokeExp(new TIdentifier("libNtve_gf_ConvertBooleanToText"), new ArrayList { node.GetExp() });
                            break;
                        case "string"://Implicit
                            replacementMethod = new ASimpleInvokeExp(new TIdentifier("StringToText"), new ArrayList { node.GetExp() });
                            break;
                    }
                    break;
                case "int":
                    switch (fromType)
                    {
                        case "bool":
                            replacementMethod = new ASimpleInvokeExp(new TIdentifier("BoolToInt"), new ArrayList {node.GetExp()});
                            break;
                        case "fixed":
                            replacementMethod = new ASimpleInvokeExp(new TIdentifier("FixedToInt"), new ArrayList { node.GetExp() });
                            break;
                        case "string":
                            replacementMethod = new ASimpleInvokeExp(new TIdentifier("StringToInt"), new ArrayList { node.GetExp() });
                            break;
                    }
                    break;
                case "fixed":
                    switch (fromType)
                    {
                        case "int"://Already implicit
                            replacementMethod = new ASimpleInvokeExp(new TIdentifier("IntToFixed"), new ArrayList { node.GetExp() });
                            break;
                        case "string":
                            replacementMethod = new ASimpleInvokeExp(new TIdentifier("StringToFixed"), new ArrayList { node.GetExp() });
                            break;
                    }
                    break;
                case "bool":
                    switch (fromType)
                    {
                        case "int":
                        case "byte":
                        case "fixed":
                            //Replace by
                            //exp != 0
                            AIntConstExp zero = new AIntConstExp(new TIntegerLiteral("0"));
                            ABinopExp binop = new ABinopExp(node.GetExp(), new ANeBinop(new TNeq("!=")), zero);
                            node.ReplaceBy(binop);

                            binop.Apply(this);
                            return;
                    }
                    break;
            }

            if (replacementMethod == null)
            {
                errors.Add(new ErrorCollection.Error(node.GetToken(), currentSourceFile, LocRM.GetString("ErrorText122") + fromType + LocRM.GetString("ErrorText123") + toType));
                throw new ParserException(node.GetToken(), LocRM.GetString("ErrorText121"));
            }

            data.SimpleMethodLinks[replacementMethod] =
                data.Libraries.Methods.First(method => method.GetName().Text == replacementMethod.GetName().Text);
            data.ExpTypes[replacementMethod] = data.SimpleMethodLinks[replacementMethod].GetReturnType();
            node.ReplaceBy(replacementMethod);
            for (int i = 1; i < replacementMethod.GetArgs().Count; i++)
            {
                ((Node)replacementMethod.GetArgs()[i]).Apply(this);
            }
        }
Exemplo n.º 17
0
        public override void OutAIncDecExp(AIncDecExp node)
        {
            PIncDecOp op = node.GetIncDecOp();
            if (!Util.HasAncestor<AABlock>(node))
            {
                Token token = null;
                if (op is APostDecIncDecOp)
                    token = ((APostDecIncDecOp) op).GetToken();
                else if (op is APreDecIncDecOp)
                    token = ((APreDecIncDecOp)op).GetToken();
                else if (op is APostIncIncDecOp)
                    token = ((APostIncIncDecOp)op).GetToken();
                else if (op is APreIncIncDecOp)
                    token = ((APreIncIncDecOp)op).GetToken();
                errors.Add(new ErrorCollection.Error(token, LocRM.GetString("ErrorText114")));
                throw new ParserException(token, "TypeChecking.OutAIncDecExp");
            }

            bool plus = op is APreIncIncDecOp || op is APostIncIncDecOp;
            if (op is APreIncIncDecOp || op is APreDecIncDecOp || node.Parent() is AExpStm)
            {//++i, --i, i++; or i--;
                //Replace with assignment
                //<exp>++ => <exp> + 1
                //(... foo = <exp> ...)++ => (... foo = <exp> ...) = (... foo ...) + 1
                //(... foo++ ...)++ => (... foo++ ...) = (... foo ...) + 1

                PLvalue clone = Util.MakeClone(node.GetLvalue(), data);
                clone.Apply(new AssignFixup(data));
                PBinop binop;
                if (plus)
                {
                    binop = new APlusBinop(new TPlus("+"));
                }
                else
                {
                    binop = new AMinusBinop(new TMinus("-"));
                }
                ABinopExp addExp = new ABinopExp(new ALvalueExp(clone), binop, new AIntConstExp(new TIntegerLiteral("1")));
                AAssignmentExp exp = new AAssignmentExp(new TAssign("="), node.GetLvalue(), addExp);
                node.ReplaceBy(exp);
                exp.Apply(this);
                return;
            }
            {//i++ or i--
                //Make a new local so
                //int newLocal = i;
                //++i;
                //...newLocal...;
                PLvalue lvalueClone = Util.MakeClone(node.GetLvalue(), data);
                PExp exp = new ALvalueExp(Util.MakeClone(node.GetLvalue(), data));
                data.ExpTypes[exp] = data.LvalueTypes[node.GetLvalue()];
                AALocalDecl localDecl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, Util.MakeClone(data.LvalueTypes[node.GetLvalue()], data), new TIdentifier("incDecVar"), exp);
                ALocalDeclStm localDeclStm = new ALocalDeclStm(new TSemicolon(";"), localDecl);

                node.SetIncDecOp(plus
                                     ? (PIncDecOp) new APreIncIncDecOp(new TPlusPlus("++"))
                                     : new APreDecIncDecOp(new TMinusMinus("--")));

                ALocalLvalue lvalue = new ALocalLvalue(new TIdentifier(localDecl.GetName().Text));
                exp = new ALvalueExp(lvalue);
                data.ExpTypes[exp] = data.LvalueTypes[lvalue] = data.LvalueTypes[node.GetLvalue()];
                data.LocalLinks[lvalue] = localDecl;

                PStm pStm = Util.GetAncestor<PStm>(node);
                node.ReplaceBy(exp);
                PStm nodeStm = new AExpStm(new TSemicolon(";"), node);

                AABlock block = (AABlock) pStm.Parent();

                block.GetStatements().Insert(block.GetStatements().IndexOf(pStm), localDeclStm);
                block.GetStatements().Insert(block.GetStatements().IndexOf(pStm), nodeStm);
                localDeclStm.Apply(this);
                nodeStm.Apply(this);
                exp.Apply(this);

                if (pStm is AWhileStm && Util.IsAncestor(exp, ((AWhileStm)pStm).GetCondition()))
                {
                    AWhileStm aStm = (AWhileStm)pStm;
                    //Insert
                    // newLocal = i
                    // ++i
                    //Before each continue in the while, and at the end.

                    //Add continue statement, if not present
                    block = (AABlock)((ABlockStm)aStm.GetBody()).GetBlock();
                    if (block.GetStatements().Count == 0 || !(block.GetStatements()[block.GetStatements().Count - 1] is AContinueStm))
                        block.GetStatements().Add(new AContinueStm(new TContinue("continue")));

                    //Get all continue statements in the while
                    ContinueFinder finder = new ContinueFinder();
                    block.Apply(finder);
                    foreach (AContinueStm continueStm in finder.Continues)
                    {
                        PLvalue nodeLvalue1 = Util.MakeClone(lvalueClone, data);
                        PExp nodeLvalue1Exp = new ALvalueExp(nodeLvalue1);
                        PLvalue nodeLvalue2 = Util.MakeClone(lvalueClone, data);
                        ALocalLvalue newLocalLvalue = new ALocalLvalue(new TIdentifier("newLocal"));
                        data.LocalLinks[newLocalLvalue] = localDecl;
                        AAssignmentExp assignment = new AAssignmentExp(new TAssign("="), newLocalLvalue, nodeLvalue1Exp);
                        PStm assignmentStm = new AExpStm(new TSemicolon(";"), assignment);

                        AIncDecExp newIncDecExp = new AIncDecExp(nodeLvalue2, plus
                                                                                  ? (PIncDecOp)
                                                                                    new APreIncIncDecOp(
                                                                                        new TPlusPlus("++"))
                                                                                  : new APreDecIncDecOp(
                                                                                        new TMinusMinus("--")));
                        PStm newIncDecExpStm = new AExpStm(new TSemicolon(";"), newIncDecExp);

                        block = (AABlock)continueStm.Parent();
                        block.GetStatements().Insert(block.GetStatements().IndexOf(continueStm), assignmentStm);
                        block.GetStatements().Insert(block.GetStatements().IndexOf(continueStm), newIncDecExpStm);

                        assignment.Apply(this);
                        newIncDecExp.Apply(this);
                    }
                }
                return;
            }
        }
Exemplo n.º 18
0
 ArrayList New495()
 {
     ArrayList nodeList = new ArrayList();
     ArrayList nodeArrayList3 = (ArrayList) Pop();
     ArrayList nodeArrayList2 = (ArrayList) Pop();
     ArrayList nodeArrayList1 = (ArrayList) Pop();
     PExp pexpNode2 = (PExp)nodeArrayList1[0];
     TNeq tneqNode4 = (TNeq)nodeArrayList2[0];
     ANeBinop pbinopNode3 = new ANeBinop (
       tneqNode4
     );
     PExp pexpNode5 = (PExp)nodeArrayList3[0];
     ABinopExp pexpNode1 = new ABinopExp (
       pexpNode2,
       pbinopNode3,
       pexpNode5
     );
     nodeList.Add(pexpNode1);
     return nodeList;
 }
Exemplo n.º 19
0
 public override void OutASAssignmentExp(ASAssignmentExp node)
 {
     AAssignmentExp replacer = null;
     PAssignop assignop = node.GetAssignop();
     Token token = null;
     PBinop binop = null;
     if (assignop is AAddAssignop)
     {
         token = ((AAddAssignop)assignop).GetToken();
         binop = new APlusBinop(new TPlus("+", token.Line, token.Pos));
     }
     else if (assignop is ASubAssignop)
     {
         token = ((ASubAssignop)assignop).GetToken();
         binop = new AMinusBinop(new TMinus("-", token.Line, token.Pos));
     }
     else if (assignop is AMulAssignop)
     {
         token = ((AMulAssignop)assignop).GetToken();
         binop = new ATimesBinop(new TStar("*", token.Line, token.Pos));
     }
     else if (assignop is ADivAssignop)
     {
         token = ((ADivAssignop)assignop).GetToken();
         binop = new ADivideBinop(new TDiv("/", token.Line, token.Pos));
     }
     else if (assignop is AModAssignop)
     {
         token = ((AModAssignop)assignop).GetToken();
         binop = new AModuloBinop(new TMod("%", token.Line, token.Pos));
     }
     else// if (assignop is AAssignAssignop)
     {
         token = ((AAssignAssignop)assignop).GetToken();
     }
     PExp rightSide;
     if (binop != null)
         rightSide = new ABinopExp(new ALvalueExp((PLvalue)node.GetLvalue().Clone()),
                                             binop,
                                             (PExp)node.GetExp().Clone());
     else
         rightSide = (PExp)node.GetExp().Clone();
     replacer = new AAssignmentExp(new TAssign("=", token.Line, token.Pos), (PLvalue)node.GetLvalue().Clone(), rightSide);
     node.ReplaceBy(replacer);
     replacer.Apply(this);
 }
Exemplo n.º 20
0
 ArrayList New499()
 {
     ArrayList nodeList = new ArrayList();
     ArrayList nodeArrayList3 = (ArrayList) Pop();
     ArrayList nodeArrayList2 = (ArrayList) Pop();
     ArrayList nodeArrayList1 = (ArrayList) Pop();
     PExp pexpNode2 = (PExp)nodeArrayList1[0];
     TXor txorNode4 = (TXor)nodeArrayList2[0];
     AXorBinop pbinopNode3 = new AXorBinop (
       txorNode4
     );
     PExp pexpNode5 = (PExp)nodeArrayList3[0];
     ABinopExp pexpNode1 = new ABinopExp (
       pexpNode2,
       pbinopNode3,
       pexpNode5
     );
     nodeList.Add(pexpNode1);
     return nodeList;
 }
Exemplo n.º 21
0
 public virtual void CaseABinopExp(ABinopExp node)
 {
     DefaultCase(node);
 }
Exemplo n.º 22
0
 ArrayList New503()
 {
     ArrayList nodeList = new ArrayList();
     ArrayList nodeArrayList3 = (ArrayList) Pop();
     ArrayList nodeArrayList2 = (ArrayList) Pop();
     ArrayList nodeArrayList1 = (ArrayList) Pop();
     PExp pexpNode2 = (PExp)nodeArrayList1[0];
     TAndAnd tandandNode4 = (TAndAnd)nodeArrayList2[0];
     ALazyAndBinop pbinopNode3 = new ALazyAndBinop (
       tandandNode4
     );
     PExp pexpNode5 = (PExp)nodeArrayList3[0];
     ABinopExp pexpNode1 = new ABinopExp (
       pexpNode2,
       pbinopNode3,
       pexpNode5
     );
     nodeList.Add(pexpNode1);
     return nodeList;
 }
Exemplo n.º 23
0
 public virtual void OutABinopExp(ABinopExp node)
 {
     DefaultOut(node);
 }
Exemplo n.º 24
0
 ArrayList New505()
 {
     ArrayList nodeList = new ArrayList();
     ArrayList nodeArrayList3 = (ArrayList) Pop();
     ArrayList nodeArrayList2 = (ArrayList) Pop();
     ArrayList nodeArrayList1 = (ArrayList) Pop();
     PExp pexpNode2 = (PExp)nodeArrayList1[0];
     TOrOr tororNode4 = (TOrOr)nodeArrayList2[0];
     ALazyOrBinop pbinopNode3 = new ALazyOrBinop (
       tororNode4
     );
     PExp pexpNode5 = (PExp)nodeArrayList3[0];
     ABinopExp pexpNode1 = new ABinopExp (
       pexpNode2,
       pbinopNode3,
       pexpNode5
     );
     nodeList.Add(pexpNode1);
     return nodeList;
 }
        //Join string + string to string
        public override void CaseABinopExp(ABinopExp node)
        {
            if (node.GetBinop() is APlusBinop)
            {
                PType type = data.ExpTypes[node];
                if (type is ANamedType && ((ANamedType)type).IsPrimitive("string"))
                {
                    PExp other = null;
                    if (node.GetLeft() is ANullExp)
                        other = node.GetRight();
                    if (node.GetRight() is ANullExp)
                        other = node.GetLeft();
                    if (other != null)
                    {
                        node.ReplaceBy(other);
                        other.Apply(this);
                        return;
                    }
                }

                //Case (string + string)
                if (node.GetLeft() is AStringConstExp && node.GetRight() is AStringConstExp)
                {
                    AStringConstExp left = (AStringConstExp) node.GetLeft();
                    AStringConstExp right = (AStringConstExp) node.GetRight();

                    if (!IsJoinAllowed(left.GetStringLiteral().Text, right.GetStringLiteral().Text))
                    {
                        base.CaseABinopExp(node);
                        return;
                    }
                    left.GetStringLiteral().Text = left.GetStringLiteral().Text.Substring(0,
                                                                                          left.GetStringLiteral().Text.
                                                                                              Length - 1);
                    left.GetStringLiteral().Text += right.GetStringLiteral().Text.Substring(1);
                    node.ReplaceBy(left);
                    CaseAStringConstExp(left);
                    return;
                }
                //Case (<exp> + string) + string
                if (node.GetLeft() is ABinopExp && node.GetRight() is AStringConstExp)
                {
                    ABinopExp leftBinop = (ABinopExp) node.GetLeft();
                    if (leftBinop.GetBinop() is APlusBinop && leftBinop.GetRight() is AStringConstExp)
                    {
                        AStringConstExp left = (AStringConstExp) leftBinop.GetRight();
                        AStringConstExp right = (AStringConstExp) node.GetRight();
                        if (!IsJoinAllowed(left.GetStringLiteral().Text, right.GetStringLiteral().Text))
                        {
                            base.CaseABinopExp(node);
                            return;
                        }
                        left.GetStringLiteral().Text = left.GetStringLiteral().Text.Substring(0,
                                                                                              left.GetStringLiteral().
                                                                                                  Text.
                                                                                                  Length - 1);
                        left.GetStringLiteral().Text += right.GetStringLiteral().Text.Substring(1);
                        node.ReplaceBy(leftBinop);
                        CaseABinopExp(leftBinop);
                        return;
                    }
                }
                //Case string + (string + <exp>)
                //Case (<exp> + string) + (string + <exp>)

            }
            //Case (int + int)
            /*if (node.GetLeft() is AIntConstExp && node.GetRight() is AIntConstExp)
            {
                AIntConstExp left = (AIntConstExp) node.GetLeft();
                AIntConstExp right = (AIntConstExp) node.GetRight();

                int a = int.Parse(left.GetIntegerLiteral().Text);
                int b = int.Parse(right.GetIntegerLiteral().Text);

                if (node.GetBinop() is APlusBinop)
                {
                    a += b;
                }
                else if (node.GetBinop() is AMinusBinop)
                {
                    a -= b;
                }
                else if (node.GetBinop() is ATimesBinop)
                {
                    a *= b;
                }
                else if (node.GetBinop() is ADivideBinop)
                {
                    if (b == 0)
                    {
                        base.CaseABinopExp(node);
                        return;
                    }
                    a /= b;
                }
                else
                {
                    base.CaseABinopExp(node);
                    return;
                }

                left.GetIntegerLiteral().Text = a.ToString();
                node.ReplaceBy(left);
                left.Apply(this);
                return;
            }
            //Case (<exp> + int) + int
            if (node.GetLeft() is ABinopExp && node.GetRight() is AIntConstExp && (node.GetBinop() is APlusBinop || node.GetBinop() is AMinusBinop))
            {
                ABinopExp leftBinop = (ABinopExp) node.GetLeft();
                PType leftType = data.ExpTypes[leftBinop];
                if (leftBinop.GetRight() is AIntConstExp && leftType is ANamedType && ((ANamedType) leftType).GetName().Text == "int" &&
                     (leftBinop.GetBinop() is APlusBinop || leftBinop.GetBinop() is AMinusBinop))
                {
                    AIntConstExp left = (AIntConstExp)leftBinop.GetRight();
                    AIntConstExp right = (AIntConstExp)node.GetRight();
                    int a = int.Parse(left.GetIntegerLiteral().Text);
                    int b = int.Parse(right.GetIntegerLiteral().Text);

                    if (node.GetBinop() is APlusBinop)
                    {
                        if (leftBinop.GetBinop() is APlusBinop)
                        {
                            //(<exp> + int) + int
                            int c = a + b;
                            //Test for overflow
                            if (a > 0 && b > 0 && (c < a || c < b) ||
                                a < 0 && b < 0 && (c > a || c > b))
                            {
                                //Don't add them
                                base.CaseABinopExp(node);
                                return;
                            }
                            if (c < 0)
                            {
                                //Change binop to <exp> - c
                                if (c != int.MinValue)
                                {
                                    c = -c;
                                    leftBinop.SetBinop(new AMinusBinop(new TMinus("-")));
                                }
                            }
                            //Replace node with leftbinop
                            left.GetIntegerLiteral().Text = c.ToString();
                            node.ReplaceBy(leftBinop);
                            leftBinop.Apply(this);
                            return;
                        }
                        else
                        {
                            //(<exp> - int) + int
                            int c = b - a;
                            //Test for overflow
                            if (a < 0 && b > 0 && (c < a || c < b) ||
                                a > 0 && b < 0 && (c > a || c > b))
                            {
                                //Don't add them
                                base.CaseABinopExp(node);
                                return;
                            }
                            if (c > 0 || c == int.MinValue)
                            {
                                //Change binop to <exp> + c
                                leftBinop.SetBinop(new APlusBinop(new TPlus("+")));

                            }
                            else
                                c = -c;
                            //Replace node with leftbinop
                            left.GetIntegerLiteral().Text = c.ToString();
                            node.ReplaceBy(leftBinop);
                            leftBinop.Apply(this);
                            return;
                        }
                    }
                    else
                    {
                        if (leftBinop.GetBinop() is APlusBinop)
                        {
                            //(<exp> + int) - int
                            //ALso need to consider <exp> in the other position, and int on the other side of the binop
                            //Make a more general algorithm
                        }
                        else
                        {

                        }
                    }
                }
            }*/
            base.CaseABinopExp(node);
        }
Exemplo n.º 26
0
        public override void CaseABinopExp(ABinopExp node)
        {
            if (!foldIntegerConstants)
            {
                base.CaseABinopExp(node);
                return;
            }

            CheckValidConstExp(node.GetLeft());
            CheckValidConstExp(node.GetRight());
            node.GetLeft().Apply(this);
            int left = integerConstant;
            node.GetBinop().Apply(this);
            node.GetRight().Apply(this);
            int right = integerConstant;

            if (node.GetBinop() is APlusBinop)
                integerConstant = left + right;
            else if (node.GetBinop() is AMinusBinop)
                integerConstant = left - right;
            else if (node.GetBinop() is ATimesBinop)
                integerConstant = left * right;
            else if (node.GetBinop() is ADivideBinop)
            {
                if (right == 0)
                {
                    errors.Add(new ErrorCollection.Error(((ADivideBinop)node.GetBinop()).GetToken(), currentSourceFile, LocRM.GetString("ErrorText58"), false), true);
                    throw new ParserException(null, "EnviromentChecking.CaseABinopExp");
                }
                integerConstant = left / right;
            }
            else if (node.GetBinop() is AModuloBinop)
            {
                if (right == 0)
                {
                    errors.Add(new ErrorCollection.Error(((AModuloBinop)node.GetBinop()).GetToken(), currentSourceFile, LocRM.GetString("ErrorText58"), false), true);
                    throw new ParserException(null, "EnviromentChecking.CaseABinopExp");
                }
                integerConstant = left % right;
            }
            else if (node.GetBinop() is AAndBinop)
                integerConstant = left & right;
            else if (node.GetBinop() is AOrBinop)
                integerConstant = left | right;
            else if (node.GetBinop() is AXorBinop)
                integerConstant = left ^ right;
            else if (node.GetBinop() is ALBitShiftBinop)
                integerConstant = left << right;
            else if (node.GetBinop() is ARBitShiftBinop)
                integerConstant = left >> right;
        }
Exemplo n.º 27
0
        public override void CaseASwitchStm(ASwitchStm node)
        {
            node.GetTest().Apply(this);

            AALocalDecl fallThroughDecl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                          new ANamedType(new TIdentifier("bool"), null),
                                                          new TIdentifier(MakeUniqueLocalName(node, "switchFallThrough")),
                                                          new ABooleanConstExp(new AFalseBool()));
            AALocalDecl continueDecl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                          new ANamedType(new TIdentifier("bool"), null),
                                                          new TIdentifier(MakeUniqueLocalName(node, "switchContinue")),
                                                          new ABooleanConstExp(new ATrueBool()));

            AALocalDecl testVar = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                          Util.MakeClone(data.ExpTypes[node.GetTest()], data),
                                                          new TIdentifier(MakeUniqueLocalName(node, "switchTestVar")),
                                                          node.GetTest());

            AABlock bigBlock = new AABlock();
            //AABlock previousBlock = bigBlock;
            if (node.GetCases().Count > 0)
            {
                List<SwitchCaseData> switchCaseDatas = new List<SwitchCaseData>();
                //Join cases without a body
                for (int i = node.GetCases().Count - 1; i >= 0; i--)
                {
                    ASwitchCaseStm caseStm = (ASwitchCaseStm) node.GetCases()[i];
                    SwitchCaseData caseData = new SwitchCaseData();
                    caseData.Block = (AABlock) caseStm.GetBlock();
                    if (caseStm.GetType() is ACaseSwitchCaseType)
                        caseData.Tests.Add(((ACaseSwitchCaseType)caseStm.GetType()).GetExp());
                    else
                        caseData.ContainsDefault = true;

                    caseData.IsLast = switchCaseDatas.Count == 0;

                    if (switchCaseDatas.Count == 0 || caseData.Block.GetStatements().Count > 0)
                    {
                        switchCaseDatas.Insert(0, caseData);
                        continue;
                    }
                    switchCaseDatas[0].Tests.AddRange(caseData.Tests);
                }
                for (int i = switchCaseDatas.Count - 1; i >= 0; i--)
                {
                    switchCaseDatas[i].ContainsFallthrough = CanFallthrough(switchCaseDatas[i].Block, out switchCaseDatas[i].HasBreaks, out switchCaseDatas[i].RequiresWhile);
                    if (i == switchCaseDatas.Count - 1)
                        continue;

                    switchCaseDatas[i + 1].TargetForFallThrough = switchCaseDatas[i].ContainsFallthrough;
                    switchCaseDatas[i].RequiresContinue = !switchCaseDatas[i].ContainsFallthrough &&
                                                          (switchCaseDatas[i + 1].RequiresContinue ||
                                                           switchCaseDatas[i + 1].ContainsFallthrough);
                }

                AABlock previousBlock = bigBlock;
                //Make code for specific case
                foreach (SwitchCaseData switchCase in switchCaseDatas)
                {
                    List<PExp> tests = new List<PExp>();
                    AABlock nextBlock;
                    if (switchCase.TargetForFallThrough)
                    {//Add if (continueSwitch) {}
                        ALocalLvalue lvalue = new ALocalLvalue(new TIdentifier(continueDecl.GetName().Text));
                        ALvalueExp test = new ALvalueExp(lvalue);
                        nextBlock = new AABlock();
                        AIfThenStm ifStm = new AIfThenStm(new TLParen("("), test, new ABlockStm(new TLBrace("{"), nextBlock));
                        previousBlock.GetStatements().Add(ifStm);
                        previousBlock = nextBlock;

                        data.LocalLinks[lvalue] = continueDecl;
                        data.LvalueTypes[lvalue] = data.ExpTypes[test] = continueDecl.GetType();

                        //First test in next if: if (fallThrough || ...
                        lvalue = new ALocalLvalue(new TIdentifier(fallThroughDecl.GetName().Text));
                        test = new ALvalueExp(lvalue);
                        tests.Add(test);

                        data.LocalLinks[lvalue] = fallThroughDecl;
                        data.LvalueTypes[lvalue] = data.ExpTypes[test] = fallThroughDecl.GetType();
                    }
                    //Make code for the test in the if
                    foreach (PExp exp in switchCase.Tests)
                    {
                        ALocalLvalue leftSide = new ALocalLvalue(new TIdentifier(testVar.GetName().Text));
                        ALvalueExp lvalueExp = new ALvalueExp(leftSide);
                        ABinopExp test = new ABinopExp(lvalueExp, new AEqBinop(new TEq("==")), exp);
                        tests.Add(test);

                        data.LocalLinks[leftSide] = testVar;
                        data.LvalueTypes[leftSide] = data.ExpTypes[lvalueExp] = testVar.GetType();
                        data.ExpTypes[test] = new ANamedType(new TIdentifier("bool"), null);
                    }

                    if (switchCase.ContainsDefault)
                    {
                        ABooleanConstExp test = new ABooleanConstExp(new ATrueBool());
                        tests.Add(test);

                        data.ExpTypes[test] = new ANamedType(new TIdentifier("bool"), null);
                    }

                    PExp finalTest = tests[0];
                    tests.RemoveAt(0);
                    foreach (PExp exp in tests)
                    {
                        finalTest = new ABinopExp(finalTest, new ALazyOrBinop(new TOrOr("||")), exp);

                        data.ExpTypes[finalTest] = new ANamedType(new TIdentifier("bool"), null);
                    }

                    //Transform breaks into assignments

                    //If we can fallthrough, and there are breaks, encase in a while stm
                    AABlock testBlock = switchCase.Block;
                    if (switchCase.RequiresWhile)
                    {
                        AABlock newBlock = new AABlock();
                        PExp whileTest = new ABooleanConstExp(new ATrueBool());
                        AWhileStm whileStm = new AWhileStm(new TLParen("("), whileTest, new ABlockStm(new TLBrace("{"), switchCase.Block));
                        newBlock.GetStatements().Add(whileStm);
                        switchCase.Block = newBlock;
                    }

                    TransformBreaks(testBlock, switchCase, continueDecl, fallThroughDecl);

                    if (switchCase.ContainsFallthrough && !switchCase.TargetForFallThrough)
                    {//Add fallthrough = true;
                        ALocalLvalue lvalue = new ALocalLvalue(new TIdentifier(fallThroughDecl.GetName().Text));
                        ABooleanConstExp rightSide = new ABooleanConstExp(new ATrueBool());
                        AAssignmentExp assignment = new AAssignmentExp(new TAssign("="), lvalue, rightSide);
                        testBlock.GetStatements().Add(new AExpStm(new TSemicolon(";"), assignment));

                        data.LocalLinks[lvalue] = fallThroughDecl;
                        data.LvalueTypes[lvalue] = data.ExpTypes[rightSide] = data.ExpTypes[assignment] = fallThroughDecl.GetType();
                    }

                    if (switchCase.RequiresWhile)
                    {//Add break at the end of the while
                        testBlock.GetStatements().Add(new ABreakStm(new TBreak("break")));
                    }

                    //Make if
                    PStm finalIfStm;
                    if (finalTest is ABooleanConstExp)
                    {//Final if is if(true). dont add it.
                        finalIfStm = new ABlockStm(new TLBrace("{"), switchCase.Block);
                        nextBlock = new AABlock();
                    }
                    else if (switchCase.IsLast || switchCase.ContainsFallthrough)
                    {//One armed if
                        finalIfStm = new AIfThenStm(new TLParen("("), finalTest,
                                                    new ABlockStm(new TLBrace("{"), switchCase.Block));
                        nextBlock = bigBlock;
                    }
                    else
                    {//Two armed if
                        nextBlock = new AABlock();
                        finalIfStm = new AIfThenElseStm(new TLParen("("), finalTest,
                                                        new ABlockStm(new TLBrace("{"), switchCase.Block),
                                                        new ABlockStm(new TLBrace("{"), nextBlock));
                    }

                    previousBlock.GetStatements().Add(finalIfStm);
                    previousBlock = nextBlock;
                }

                //If needed, add fallThroughDecl and continueDecl
                data.Locals.Add(bigBlock, new List<AALocalDecl>());
                if (data.LocalLinks.Values.Contains(fallThroughDecl))
                {
                    bigBlock.GetStatements().Insert(0, new ALocalDeclStm(new TSemicolon(";"), fallThroughDecl));
                    data.Locals[bigBlock].Add(fallThroughDecl);
                }
                if (data.LocalLinks.Values.Contains(continueDecl))
                {
                    bigBlock.GetStatements().Insert(0, new ALocalDeclStm(new TSemicolon(";"), continueDecl));
                    data.Locals[bigBlock].Add(continueDecl);
                }
                bigBlock.GetStatements().Insert(0, new ALocalDeclStm(new TSemicolon(";"), testVar));
                data.Locals[bigBlock].Add(testVar);

                node.ReplaceBy(new ABlockStm(new TLBrace("{"), bigBlock));
                bigBlock.Apply(this);
            }
        }
Exemplo n.º 28
0
        public override void OutABinopExp(ABinopExp node)
        {
            PBinop binop = node.GetBinop();
            PExp left = node.GetLeft();
            PType leftType = data.ExpTypes[left];
            string leftTypeString = Util.TypeToString(leftType);
            PExp right = node.GetRight();
            PType rightType = data.ExpTypes[right];
            string rightTypeString = Util.TypeToString(rightType);

            bool wasDefined = false;
            Token token = null;
            while (true)
            {
                if (binop is APlusBinop)
                {
                    token = ((APlusBinop) binop).GetToken();
                    //Check that types are okay for +
                    if (!new[] {"int", "fixed", "string", "text", "byte", "point"}.Any(c => c == leftTypeString))
                    {
                        errors.Add(new ErrorCollection.Error(token, currentSourceFile,
                                                             LocRM.GetString("ErrorText103") + leftTypeString));
                        throw new ParserException(null, null);
                    }
                    if (!new[] {"int", "fixed", "string", "text", "byte", "point"}.Any(c => c == rightTypeString))
                    {
                        errors.Add(new ErrorCollection.Error(token, currentSourceFile,
                                                             LocRM.GetString("ErrorText103") + rightTypeString));
                        throw new ParserException(null, null);
                    }
                    //If you are using string or text, both sides must be same type
                    if ((leftTypeString == "string" && rightTypeString != "string") ||
                        (leftTypeString == "text" && rightTypeString != "text") ||
                        (leftTypeString == "point" && rightTypeString != "point") ||
                        (rightTypeString == "string" && leftTypeString != "string") ||
                        (rightTypeString == "text" && leftTypeString != "text") ||
                        (rightTypeString == "point" && leftTypeString != "point"))
                    {
                        if (ImplicitAssignable(leftType, rightType))
                        {
                            ANamedType namedTo = (ANamedType) rightType;
                            ACastExp cast = new ACastExp(new TLParen("("),
                                                         new ANamedType(
                                                             new TIdentifier(((AAName) namedTo.GetName()).AsString()),
                                                             null), node.GetLeft());
                            node.SetLeft(cast);
                            OutACastExp(cast);
                            leftType = rightType;
                        }
                        else if (ImplicitAssignable(rightType, leftType))
                        {
                            ANamedType namedTo = (ANamedType) leftType;
                            ACastExp cast = new ACastExp(new TLParen("("),
                                                         new ANamedType(
                                                             new TIdentifier(((AAName) namedTo.GetName()).AsString()),
                                                             null), node.GetRight());
                            node.SetRight(cast);
                            OutACastExp(cast);
                            rightType = leftType;
                        }
                        else
                        {
                            //Not valid
                            break;
                        }
                    }
                    wasDefined = true;
                    PType type = leftType;
                    if (rightTypeString == "fixed")
                        type = rightType;
                    data.ExpTypes[node] = type;
                }
                else if (binop is AMinusBinop || binop is ATimesBinop || binop is ADivideBinop || binop is AModuloBinop)
                {
                    token = null;
                    if (binop is AMinusBinop) token = ((AMinusBinop) binop).GetToken();
                    else if (binop is ATimesBinop) token = ((ATimesBinop) binop).GetToken();
                    else if (binop is ADivideBinop) token = ((ADivideBinop) binop).GetToken();
                    else if (binop is AModuloBinop) token = ((AModuloBinop) binop).GetToken();

                    //Check that types are okay for whatever
                    if (!new[] {"int", "fixed", "byte", "point"}.Any(c => c == leftTypeString))
                    {
                        //Not valid
                        break;
                    }
                    if (!new[] {"int", "fixed", "byte", "point"}.Any(c => c == rightTypeString))
                    {
                        //Not valid
                        break;
                    }
                    if ((leftTypeString == "point" || rightTypeString == "point") &&
                        !(leftTypeString == "point" && rightTypeString == "point" && binop is AMinusBinop))
                    {
                        //Not valid
                        break;
                    }
                    wasDefined = true;
                    PType type = leftType;
                    if (rightTypeString == "fixed")
                        type = rightType;
                    if (rightTypeString == "int" && leftTypeString == "byte")
                        type = rightType;
                    data.ExpTypes[node] = type;
                }
                else if (binop is AEqBinop || binop is ANeBinop || binop is ALtBinop || binop is ALeBinop ||
                         binop is AGtBinop || binop is AGeBinop)
                {
                    token = null;
                    if (binop is AEqBinop) token = ((AEqBinop) binop).GetToken();
                    else if (binop is ANeBinop) token = ((ANeBinop) binop).GetToken();
                    else if (binop is ALtBinop) token = ((ALtBinop) binop).GetToken();
                    else if (binop is ALeBinop) token = ((ALeBinop) binop).GetToken();
                    else if (binop is AGtBinop) token = ((AGtBinop) binop).GetToken();
                    else if (binop is AGeBinop) token = ((AGeBinop) binop).GetToken();

                    //Unless types are int and fixed, they must be the same type, or null and a nullable type
                    if (leftTypeString == "void" || rightTypeString == "void" ||
                        !(
                             GalaxyKeywords.NullablePrimitives.words.Any(s => s == leftTypeString) &&
                             rightTypeString == "null" ||
                             leftTypeString == "null" &&
                             GalaxyKeywords.NullablePrimitives.words.Any(s => s == rightTypeString) ||
                             (leftTypeString == "int" || leftTypeString == "fixed" || leftTypeString == "byte") &&
                             (rightTypeString == "int" || rightTypeString == "fixed" || rightTypeString == "byte") ||
                             leftTypeString == rightTypeString && !(IsDynamic(leftType) || IsDynamic(rightType)) ||
                             (binop is AEqBinop || binop is ANeBinop) &&
                             (
                                 leftTypeString == rightTypeString ||
                                 leftTypeString == "null" && IsDynamic(rightType) ||
                                 IsDynamic(leftType) && rightTypeString == "null" ||
                                 Util.TypesEqual(leftType, rightType, data)
                             ) ||
                             leftType is ANamedType && data.DelegateTypeLinks.ContainsKey((ANamedType) leftType) &&
                             (rightTypeString == "null" ||
                              rightType is ANamedType && data.DelegateTypeLinks.ContainsKey((ANamedType) rightType)) ||
                             rightType is ANamedType && data.DelegateTypeLinks.ContainsKey((ANamedType) rightType) &&
                             leftTypeString == "null"
                         )
                        )
                    {

                        //Not valid
                        break;

                    }
                    wasDefined = true;
                    data.ExpTypes[node] = new ANamedType(new TIdentifier("bool"), null);
                }
                else if (binop is AAndBinop || binop is AOrBinop || binop is AXorBinop || binop is ALBitShiftBinop ||
                         binop is ARBitShiftBinop)
                {
                    token = null;
                    if (binop is AAndBinop) token = ((AAndBinop) binop).GetToken();
                    else if (binop is AOrBinop) token = ((AOrBinop) binop).GetToken();
                    else if (binop is AXorBinop) token = ((AXorBinop) binop).GetToken();
                    else if (binop is ALBitShiftBinop) token = ((ALBitShiftBinop) binop).GetToken();
                    else if (binop is ARBitShiftBinop) token = ((ARBitShiftBinop) binop).GetToken();

                    if (
                        !((leftTypeString == "int" || leftTypeString == "byte") &&
                          (rightTypeString == "int" || rightTypeString == "byte") &&
                          (binop is ALBitShiftBinop || binop is ARBitShiftBinop ||
                           leftTypeString == rightTypeString)))
                    {
                        if (rightTypeString == "int" && leftTypeString == "byte" && left is AIntConstExp)
                        {
                            data.ExpTypes[left] =
                                leftType = new ANamedType(new TIdentifier("int"), null);
                            leftTypeString = "int";
                        }
                        else if (leftTypeString == "int" && rightTypeString == "byte" && right is AIntConstExp)
                        {
                            data.ExpTypes[right] =
                                rightType = new ANamedType(new TIdentifier("int"), null);
                            rightTypeString = "int";
                        }
                        else
                        {
                            //Not valid
                            break;
                        }
                    }
                    wasDefined = true;
                    data.ExpTypes[node] = leftType;
                    if (rightTypeString == "int")
                        data.ExpTypes[node] = rightType;
                }
                else if (binop is ALazyAndBinop || binop is ALazyOrBinop)
                {
                    token = null;
                    if (binop is ALazyAndBinop) token = ((ALazyAndBinop) binop).GetToken();
                    else if (binop is ALazyOrBinop) token = ((ALazyOrBinop) binop).GetToken();

                    if (leftTypeString != "bool" || rightTypeString != "bool")
                    {

                        errors.Add(new ErrorCollection.Error(token, currentSourceFile,
                                                             token.Text + LocRM.GetString("ErrorText104") +
                                                             token.Text +
                                                             " bool). Got (" +
                                                             leftTypeString + " " + token.Text + " " +
                                                             rightTypeString + ")"));
                        throw new ParserException(null, null);
                    }
                    wasDefined = true;
                    data.ExpTypes[node] = leftType;
                }
                else
                    throw new Exception("Unexpected binop (This should never happen)");
                break;
            }

            List<AMethodDecl> possibleOperators = new List<AMethodDecl>();
            List<IList> visibleDecls = Util.GetVisibleDecls(node, true);
            List<string> currentNamespace = Util.GetFullNamespace(node);
            AASourceFile currentFile = Util.GetAncestor<AASourceFile>(node);
            foreach (IList declList in visibleDecls)
            {
                bool sameNS = false;
                bool sameFile = false;
                if (declList.Count > 0)
                {
                    sameNS = Util.NamespacesEquals(currentNamespace, Util.GetFullNamespace((PDecl) declList[0]));
                    sameFile = currentFile == Util.GetAncestor<AASourceFile>((PDecl) declList[0]);
                }
                foreach (PDecl decl in declList)
                {
                    if (decl is AMethodDecl)
                    {
                        AMethodDecl method = (AMethodDecl) decl;
                        if (method.GetName().Text == token.Text)
                        {
                            if (method.GetVisibilityModifier() is APrivateVisibilityModifier && !sameNS)
                                continue;
                            if (method.GetStatic() != null && !sameFile)
                                continue;
                            //Check that parameters are assignable
                            bool add = true;
                            bool matchImplicit = false;
                            List<PType> argTypes = new List<PType>(){leftType, rightType};
                            for (int i = 0; i < argTypes.Count; i++)
                            {
                                PType argType = argTypes[i];
                                AALocalDecl formal = (AALocalDecl)method.GetFormals()[i];
                                PType formalType = formal.GetType();
                                if (formal.GetOut() != null && !Assignable(formalType, argType)
                                    ||
                                    formal.GetRef() != null &&
                                    !(Assignable(argType, formalType) && Assignable(formalType, argType))
                                    ||
                                    formal.GetOut() == null && formal.GetRef() == null &&
                                    !Assignable(argType, formalType))
                                {
                                    add = false;
                                    if (formal.GetOut() == null && formal.GetRef() == null &&
                                        ImplicitAssignable(argType, formalType))
                                    {
                                        matchImplicit = true;
                                    }
                                    else
                                    {
                                        matchImplicit = false;
                                        break;
                                    }
                                }
                            }
                            if (!add && !matchImplicit)
                                continue;
                            if (add)
                                possibleOperators.Add(method);
                        }
                    }
                }
            }

            if (possibleOperators.Count == 0 && !wasDefined)
            {
                errors.Add(new ErrorCollection.Error(token, LocRM.GetString("ErrorText105") + leftTypeString + " " + token.Text + " " + rightTypeString + ")"));
                throw new ParserException(token, "TypeChecking.OutABinopExp");
            }

            if (possibleOperators.Count + (wasDefined ? 1 : 0) > 1)
            {
                List<ErrorCollection.Error> subErrors = new List<ErrorCollection.Error>();
                foreach (AMethodDecl method in possibleOperators)
                {
                    subErrors.Add(new ErrorCollection.Error(method.GetName(), LocRM.GetString("ErrorText106")));
                }
                if (wasDefined)
                    subErrors.Add(new ErrorCollection.Error(token, LocRM.GetString("ErrorText107") + token.Text));
                errors.Add(new ErrorCollection.Error(token, LocRM.GetString("ErrorText108") + leftTypeString + " " + token.Text + " " + rightTypeString + LocRM.GetString("ErrorText109"), false, subErrors.ToArray()));
                throw new ParserException(token, "TypeChecking.OutABinopExp");
            }

            if (wasDefined)
                return;

            AMethodDecl op = possibleOperators[0];
            ASimpleInvokeExp replacer = new ASimpleInvokeExp(new TIdentifier(op.GetName().Text), new ArrayList(){node.GetLeft(), node.GetRight()});
            node.ReplaceBy(replacer);
            data.SimpleMethodLinks[replacer] = op;
            data.ExpTypes[replacer] = op.GetReturnType();

            //base.OutABinopExp(node);
        }
        public override void OutAAProgram(AAProgram node)
        {
            if (strings.Count == 0)
                return;

            //Obfuscate all strings
            List<string> obfuscated = new List<string>();
            foreach (AStringConstExp stringConstExp in strings)
            {
                TStringLiteral token = stringConstExp.GetStringLiteral();
                string s = token.Text.Substring(1, token.Text.Length - 2);
                obfuscated.Add(Obfuscate(s));
            }

            //Set invokes instead of string constants, and move varaiabes down
            List<AFieldDecl> ignoredFields = new List<AFieldDecl>();
            List<AFieldDecl> moveFieldsIn = new List<AFieldDecl>();
            Dictionary<AFieldDecl, AMethodDecl> fieldMethods = new Dictionary<AFieldDecl, AMethodDecl>();
            for (int i = 0; i < strings.Count; i++)
            {
                AStringConstExp stringExp = strings[i];
                Token token = stringExp.GetStringLiteral();
                bool inDeobfuscator = Util.GetAncestor<AMethodDecl>(stringExp) == finalTrans.data.DeobfuscateMethod;

                if (inDeobfuscator)
                {
                    AFieldDecl field = finalTrans.data.UnobfuscatedStrings[stringExp];

                    AStringConstExp newStringConst = new AStringConstExp(stringExp.GetStringLiteral());

                    field.SetInit(newStringConst);

                    AFieldLvalue fieldRef = new AFieldLvalue(new TIdentifier(field.GetName().Text, token.Line, token.Pos));
                    finalTrans.data.FieldLinks[fieldRef] = field;

                    stringExp.ReplaceBy(new ALvalueExp(fieldRef));
                }
                else
                {
                    AFieldDecl field;
                    if (!finalTrans.data.ObfuscatedStrings.ContainsKey(stringExp))
                    {
                        int line = -finalTrans.data.ObfuscatedStrings.Count - 1;
                        field = new AFieldDecl(new APublicVisibilityModifier(), null, new TConst("const", line, 0),
                                                new ANamedType(new TIdentifier("string", line, 1), null),
                                                new TIdentifier("Galaxy_pp_stringO" +
                                                                finalTrans.data.ObfuscatedStrings.Count), null);
                        //If the strings are the same - point them to same field
                        bool newField = true;
                        foreach (AStringConstExp oldStringConstExp in finalTrans.data.ObfuscatedStrings.Keys)
                        {
                            if (stringExp.GetStringLiteral().Text == oldStringConstExp.GetStringLiteral().Text)
                            {
                                field = finalTrans.data.ObfuscatedStrings[oldStringConstExp];
                                newField = false;
                                break;
                            }
                        }
                        if (newField)
                        {
                            AASourceFile file = (AASourceFile)finalTrans.data.DeobfuscateMethod.Parent();
                            file.GetDecl().Insert(file.GetDecl().IndexOf(finalTrans.data.DeobfuscateMethod) + 1, field);

                            finalTrans.data.Fields.Add(new SharedData.DeclItem<AFieldDecl>(file, field));
                        }
                        finalTrans.data.ObfuscatedStrings.Add(stringExp, field);

                    }
                    field = finalTrans.data.ObfuscatedStrings[stringExp];
                    string obfuscatedString = obfuscated[i];

                    ASimpleInvokeExp invoke = new ASimpleInvokeExp();
                    invoke.SetName(new TIdentifier(finalTrans.data.DeobfuscateMethod.GetName().Text,
                                                   stringExp.GetStringLiteral().Line,
                                                   stringExp.GetStringLiteral().Pos));

                    AStringConstExp newStringConst =
                        new AStringConstExp(new TStringLiteral("\"" + obfuscatedString + "\""));
                    invoke.GetArgs().Add(newStringConst);
                    finalTrans.data.SimpleMethodLinks[invoke] = finalTrans.data.DeobfuscateMethod;

                    if (Util.GetAncestor<PStm>(stringExp) == null && false)
                    {
                        ignoredFields.Add(field);
                        /*if (Util.GetAncestor<ASimpleInvokeExp>(stringExp) == null)
                            stringExp.ReplaceBy(invoke);*/
                        //Add obfuscate call to this location);
                        continue;
                        /*ASimpleInvokeExp invoke = new ASimpleInvokeExp();
                        invoke.SetName(new TIdentifier(finalTrans.data.DeobfuscateMethod.GetName().Text,
                                                       stringExp.GetStringLiteral().Line,
                                                       stringExp.GetStringLiteral().Pos));

                        AStringConstExp newStringConst =
                            new AStringConstExp(new TStringLiteral("\"" + obfuscatedString + "\""));
                        invoke.GetArgs().Add(newStringConst);
                        stringExp.ReplaceBy(invoke);

                        finalTrans.data.SimpleMethodLinks[invoke] = finalTrans.data.DeobfuscateMethod;
                        continue;*/
                    }

                    if (field.GetInit() == null)
                    {
                        /*field.SetInit(invoke);
                        field.SetConst(null);*/

                        if (
                            stringExp.GetStringLiteral().Text.Remove(0, 1).Substring(0,
                                                                                     stringExp.GetStringLiteral().Text.
                                                                                         Length - 2) == "")
                        {
                            //Make method
                            /*
                                string <field>Method()
                                {
                                    return "";
                                }
                             *
                             */
                            ANullExp nullExp = new ANullExp();

                            field.SetInit(nullExp);
                            field.SetConst(null);

                            AStringConstExp stringConst = new AStringConstExp(new TStringLiteral("\"\""));
                            AMethodDecl method = new AMethodDecl(new APublicVisibilityModifier(), null, null, null, null, null,
                                                                 new ANamedType(new TIdentifier("string"), null),
                                                                 new TIdentifier("Get" + field.GetName()),
                                                                 new ArrayList(),
                                                                 new AABlock(
                                                                     new ArrayList()
                                                                         {
                                                                             new AValueReturnStm(new TReturn("return"),
                                                                                                 stringConst)
                                                                         },
                                                                     new TRBrace("}")));

                            AASourceFile pFile = (AASourceFile)field.Parent();
                            pFile.GetDecl().Insert(pFile.GetDecl().IndexOf(field) + 1, method);
                            finalTrans.data.ExpTypes[stringConst] = new ANamedType(new TIdentifier("string"), null);
                            finalTrans.data.ExpTypes[nullExp] = new ANamedType(new TIdentifier("null"), null);

                            fieldMethods[field] = method;
                        }
                        else
                        {
                            //Make method
                            /*
                                string <field>Method()
                                {
                                    if (field == null)
                                    {
                                        field = Invoke;
                                    }
                                    if (field == null)
                                    {
                                        return Invoke;
                                    }
                                    return field;
                                }
                             */

                            ANullExp nullExp1 = new ANullExp();

                            field.SetInit(nullExp1);
                            field.SetConst(null);

                            ANullExp nullExp2 = new ANullExp();
                            AFieldLvalue fieldRef1 = new AFieldLvalue(new TIdentifier(field.GetName().Text));
                            AFieldLvalue fieldRef2 = new AFieldLvalue(new TIdentifier(field.GetName().Text));
                            AFieldLvalue fieldRef3 = new AFieldLvalue(new TIdentifier(field.GetName().Text));
                            ALvalueExp fieldRef1Exp = new ALvalueExp(fieldRef1);
                            ALvalueExp fieldRef3Exp = new ALvalueExp(fieldRef3);
                            ABinopExp binop1 = new ABinopExp(fieldRef1Exp, new AEqBinop(new TEq("==")), nullExp2);
                            AAssignmentExp assignment = new AAssignmentExp(new TAssign("="), fieldRef2, invoke);

                            AIfThenStm ifStm1 = new AIfThenStm(new TLParen("("), binop1,
                                                              new ABlockStm(new TLBrace("{"),
                                                                            new AABlock(
                                                                                new ArrayList()
                                                                                    {
                                                                                        new AExpStm(new TSemicolon(";"),
                                                                                                    assignment)
                                                                                    },
                                                                                new TRBrace("}"))));

                            /*ANullExp nullExp3 = new ANullExp();
                            AFieldLvalue fieldRef4 = new AFieldLvalue(new TIdentifier(field.GetName().Text));
                            ALvalueExp fieldRef4Exp = new ALvalueExp(fieldRef4);
                            AStringConstExp invokeArgClone =
                                new AStringConstExp(new TStringLiteral("\"" + obfuscatedString + "\""));
                            ASimpleInvokeExp invokeClone = new ASimpleInvokeExp(new TIdentifier(invoke.GetName().Text),
                                                                                new ArrayList() { invokeArgClone });
                            finalTrans.data.SimpleMethodLinks[invokeClone] = finalTrans.data.DeobfuscateMethod;
                            ABinopExp binop2 = new ABinopExp(fieldRef4Exp, new AEqBinop(new TEq("==")), nullExp3);

                            AIfThenStm ifStm2 = new AIfThenStm(new TLParen("("), binop2,
                                                              new ABlockStm(new TLBrace("{"),
                                                                            new AABlock(
                                                                                new ArrayList()
                                                                                    {
                                                                                        new AValueReturnStm(new TReturn("return"), invokeClone)
                                                                                    },
                                                                                new TRBrace("}"))));*/

                            AMethodDecl method = new AMethodDecl(new APublicVisibilityModifier(), null, null, null, null, null,
                                                                 new ANamedType(new TIdentifier("string"), null),
                                                                 new TIdentifier("Get" + field.GetName()),
                                                                 new ArrayList(),
                                                                 new AABlock(
                                                                     new ArrayList()
                                                                         {
                                                                             ifStm1,
                                                                             //ifStm2,
                                                                             new AValueReturnStm(new TReturn("return"),
                                                                                                 fieldRef3Exp)
                                                                         },
                                                                     new TRBrace("}")));
                            AASourceFile pFile = (AASourceFile) field.Parent();
                            pFile.GetDecl().Insert(pFile.GetDecl().IndexOf(field) + 1, method);

                            finalTrans.data.FieldLinks[fieldRef1] =
                                finalTrans.data.FieldLinks[fieldRef2] =
                                finalTrans.data.FieldLinks[fieldRef3] =
                                /*finalTrans.data.FieldLinks[fieldRef4] = */field;
                            finalTrans.data.LvalueTypes[fieldRef1] =
                                finalTrans.data.LvalueTypes[fieldRef2] =
                                finalTrans.data.LvalueTypes[fieldRef3] =
                                //finalTrans.data.LvalueTypes[fieldRef4] =
                                finalTrans.data.ExpTypes[fieldRef1Exp] =
                                finalTrans.data.ExpTypes[fieldRef3Exp] =
                                //finalTrans.data.ExpTypes[fieldRef4Exp] =
                                finalTrans.data.ExpTypes[assignment] = field.GetType();

                            finalTrans.data.ExpTypes[nullExp1] =
                                finalTrans.data.ExpTypes[nullExp2] =
                                /*finalTrans.data.ExpTypes[nullExp3] =*/ new ANamedType(new TIdentifier("null"), null);
                            finalTrans.data.ExpTypes[binop1] =
                                /*finalTrans.data.ExpTypes[binop2] = */new ANamedType(new TIdentifier("bool"), null);

                            fieldMethods[field] = method;
                        }

                        /* AFieldLvalue fieldRef = new AFieldLvalue(new TIdentifier(field.GetName().Text, token.Line, token.Pos));
                         finalTrans.data.FieldLinks[fieldRef] = field;*/

                        //stringExp.ReplaceBy(new ALvalueExp(fieldRef));
                    }
                    ASimpleInvokeExp invoke2 =
                            new ASimpleInvokeExp(new TIdentifier(fieldMethods[field].GetName().Text), new ArrayList());
                    finalTrans.data.SimpleMethodLinks[invoke2] = fieldMethods[field];
                    stringExp.ReplaceBy(invoke2);

                    //If we are in a field, move it in
                    if (Util.GetAncestor<AFieldDecl>(invoke2) != null)
                        moveFieldsIn.Add(Util.GetAncestor<AFieldDecl>(invoke2));
                }
            }

            foreach (AFieldDecl field in finalTrans.data.ObfuscationFields)
            {
                if (field.GetInit() == null && field.Parent() != null)
                {
                    field.Parent().RemoveChild(field);
                }
            }

            //A constant field, or a field used by a constant field cannot be moved in
            List<AFieldDecl> constantFields = new List<AFieldDecl>();
            foreach (SharedData.DeclItem<AFieldDecl> field in finalTrans.data.Fields)
            {
                if (field.Decl.GetConst() != null)
                    constantFields.Add(field.Decl);
            }
            for (int i = 0; i < constantFields.Count; i++)
            {
                GetFieldLvalues lvalues = new GetFieldLvalues();
                constantFields[i].Apply(lvalues);
                foreach (AFieldLvalue lvalue in lvalues.Lvalues)
                {
                    AFieldDecl field = finalTrans.data.FieldLinks[lvalue];
                    if (!constantFields.Contains(field))
                        constantFields.Add(field);
                }
            }
            moveFieldsIn.RemoveAll(constantFields.Contains);
            Dictionary<AFieldDecl, List<AFieldDecl>> dependancies = new Dictionary<AFieldDecl, List<AFieldDecl>>();
            //Order the fields so any dependancies are instansiated first
            foreach (AFieldDecl field in moveFieldsIn)
            {
                dependancies.Add(field, new List<AFieldDecl>());
                GetFieldLvalues lvalues = new GetFieldLvalues();
                field.Apply(lvalues);
                foreach (AFieldLvalue lvalue in lvalues.Lvalues)
                {
                    AFieldDecl dependancy = finalTrans.data.FieldLinks[lvalue];
                    if (!dependancies[field].Contains(dependancy))
                        dependancies[field].Add(dependancy);
                }
            }
            List<PStm> newStatements = new List<PStm>();
            while (dependancies.Keys.Count > 0)
            {
                AFieldDecl field = dependancies.FirstOrDefault(f1 => f1.Value.Count == 0).Key ??
                                   dependancies.Keys.First(f => true);

                AFieldLvalue fieldRef = new AFieldLvalue(new TIdentifier(field.GetName().Text));
                AAssignmentExp assignment = new AAssignmentExp(new TAssign("="), fieldRef, field.GetInit());
                field.SetInit(null);

                newStatements.Add(new AExpStm(new TSemicolon(";"), assignment));

                finalTrans.data.FieldLinks[fieldRef] = field;
                finalTrans.data.LvalueTypes[fieldRef] =
                    finalTrans.data.ExpTypes[assignment] = field.GetType();

                foreach (KeyValuePair<AFieldDecl, List<AFieldDecl>> dependancy in dependancies)
                {
                    if (dependancy.Value.Contains(field))
                        dependancy.Value.Remove(field);
                }

                dependancies.Remove(field);
            }
            AABlock initBody = (AABlock) finalTrans.mainEntry.GetBlock();
            for (int i = newStatements.Count - 1; i >= 0; i--)
            {
                initBody.GetStatements().Insert(0, newStatements[i]);
            }
        }
Exemplo n.º 30
0
        private AMethodDecl GetMethodMethod()
        {
            if (GetMethodPartMethod != null)
                return GetMethodPartMethod;
            /*
                string GetMethodPart(string delegate)
                {
                    int i = StringFind(delegate, ":", false);
                    if (i == -1)
                    {
                        return delegate;
                    }
                    return StringSub(delegate, 1, i - 1);
                }
             */
            AASourceFile sourceFile = Util.GetAncestor<AASourceFile>(finalTrans.mainEntry);

            AALocalDecl delegateFormal = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null,
                                                         new ANamedType(new TIdentifier("string"), null),
                                                         new TIdentifier("delegate"), null);
            ALocalLvalue delegateRef1 = new ALocalLvalue(new TIdentifier("delegate"));
            ALocalLvalue delegateRef2 = new ALocalLvalue(new TIdentifier("delegate"));
            ALocalLvalue delegateRef3 = new ALocalLvalue(new TIdentifier("delegate"));
            ALvalueExp delegateRef1Exp = new ALvalueExp(delegateRef1);
            ALvalueExp delegateRef2Exp = new ALvalueExp(delegateRef2);
            ALvalueExp delegateRef3Exp = new ALvalueExp(delegateRef3);

            AStringConstExp stringConst = new AStringConstExp(new TStringLiteral("\":\""));
            ABooleanConstExp booleanConst = new ABooleanConstExp(new AFalseBool());
            AIntConstExp intConst1 = new AIntConstExp(new TIntegerLiteral("-1"));
            AIntConstExp intConst2 = new AIntConstExp(new TIntegerLiteral("1"));
            AIntConstExp intConst3 = new AIntConstExp(new TIntegerLiteral("1"));

            ASimpleInvokeExp stringFindInvoke = new ASimpleInvokeExp(new TIdentifier("StringFind"),
                                                                     new ArrayList()
                                                                         {delegateRef1Exp, stringConst, booleanConst});
            AALocalDecl iDecl = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, new ANamedType(new TIdentifier("int"), null),
                                                new TIdentifier("i"), stringFindInvoke);
            ALocalLvalue iRef1 = new ALocalLvalue(new TIdentifier("i"));
            ALocalLvalue iRef2 = new ALocalLvalue(new TIdentifier("i"));
            ALvalueExp iRef1Exp = new ALvalueExp(iRef1);
            ALvalueExp iRef2Exp = new ALvalueExp(iRef2);

            ABinopExp binop1 = new ABinopExp(iRef1Exp, new AEqBinop(new TEq("==")), intConst1);
            AIfThenStm ifThen = new AIfThenStm(new TLParen("("), binop1,
                                               new ABlockStm(new TLBrace("{"),
                                                             new AABlock(
                                                                 new ArrayList()
                                                                     {
                                                                         new AValueReturnStm(new TReturn("return"),
                                                                                             delegateRef2Exp)
                                                                     },
                                                                 new TRBrace("}"))));

            ABinopExp binop2 = new ABinopExp(iRef2Exp, new AMinusBinop(new TMinus("-")), intConst3);
            ASimpleInvokeExp stringSubInvoke = new ASimpleInvokeExp(new TIdentifier("StringSub"),
                                                                    new ArrayList() {delegateRef3Exp, intConst2, binop2});

            GetMethodPartMethod = new AMethodDecl(new APublicVisibilityModifier(), null, null, null, null, null,
                                                  new ANamedType(new TIdentifier("string"), null),
                                                  new TIdentifier("GetMethodPart", finalTrans.data.LineCounts[sourceFile] + 1, 1), new ArrayList() { delegateFormal },
                                                  new AABlock(
                                                      new ArrayList()
                                                          {
                                                              new ALocalDeclStm(new TSemicolon(";"), iDecl),
                                                              ifThen,
                                                              new AValueReturnStm(new TReturn("return"), stringSubInvoke)
                                                          },
                                                      new TRBrace("}")));
            sourceFile.GetDecl().Add(GetMethodPartMethod);

            finalTrans.data.LocalLinks[delegateRef1] =
                finalTrans.data.LocalLinks[delegateRef2] =
                finalTrans.data.LocalLinks[delegateRef3] = delegateFormal;
            finalTrans.data.LocalLinks[iRef1] =
                finalTrans.data.LocalLinks[iRef2] = iDecl;
            finalTrans.data.LvalueTypes[delegateRef1] =
                finalTrans.data.LvalueTypes[delegateRef2] =
                finalTrans.data.LvalueTypes[delegateRef3] =
                finalTrans.data.ExpTypes[delegateRef1Exp] =
                finalTrans.data.ExpTypes[delegateRef2Exp] =
                finalTrans.data.ExpTypes[delegateRef3Exp] =
                finalTrans.data.ExpTypes[stringConst] =
                finalTrans.data.ExpTypes[stringSubInvoke] = new ANamedType(new TIdentifier("string"), null);
            finalTrans.data.LvalueTypes[iRef1] =
                finalTrans.data.LvalueTypes[iRef2] =
                finalTrans.data.ExpTypes[iRef1Exp] =
                finalTrans.data.ExpTypes[iRef2Exp] =
                finalTrans.data.ExpTypes[stringFindInvoke] =
                finalTrans.data.ExpTypes[intConst1] =
                finalTrans.data.ExpTypes[intConst2] =
                finalTrans.data.ExpTypes[intConst3] =
                finalTrans.data.ExpTypes[binop2] = new ANamedType(new TIdentifier("int"), null);
            finalTrans.data.ExpTypes[booleanConst] =
                finalTrans.data.ExpTypes[binop1] = new ANamedType(new TIdentifier("bool"), null);

            finalTrans.data.SimpleMethodLinks[stringFindInvoke] =
                finalTrans.data.Libraries.Methods.First(m => m.GetName().Text == stringFindInvoke.GetName().Text);
            finalTrans.data.SimpleMethodLinks[stringSubInvoke] =
                finalTrans.data.Libraries.Methods.First(m => m.GetName().Text == stringSubInvoke.GetName().Text);

            return GetMethodPartMethod;
        }