public override void OutAAProgram(AAProgram node)
 {
     if (multipleEntryCandidates.Count > 0)
     {
         finalTrans.errors.Add(new ErrorCollection.Error(multipleEntryCandidates[0], LocRM.GetString("ErrorText1"), multipleEntryCandidates.ToArray()));
     }
 }
            public override void OutAAProgram(AAProgram node)
            {
                //First, analyze methods with no dependancies
                List<AMethodDecl> analyzedMethods = new List<AMethodDecl>();
                while (true)
                {
                    bool processedSomething = false;
                    foreach (KeyValuePair<AMethodDecl, List<AMethodDecl>> pair in dependancies)
                    {
                        AMethodDecl method = pair.Key;
                        if (analyzedMethods.Contains(method))
                            continue;

                        bool hasDependancies = false;
                        foreach (AMethodDecl dependancy in pair.Value)
                        {
                            if (!analyzedMethods.Contains(dependancy))
                            {
                                hasDependancies = true;
                                break;
                            }
                        }
                        if (hasDependancies)
                            continue;
                        processedSomething = true;
                        Analyze(method);
                        analyzedMethods.Add(method);
                    }
                    if (analyzedMethods.Count == dependancies.Count)
                        break;
                    if (processedSomething)
                        continue;
                    //There is a cycle left.
                }
            }
Exemplo n.º 3
0
 public void Parse(AAProgram ast)
 {
     FindNullChecks finder = new FindNullChecks(data);
     ast.Apply(finder);
     ast.Apply(new Phase0(data));
     //ast.Apply(new Phase0(data));
     ast.Apply(new Phase2(data, finder.TypesWithIdentifierArray));
 }
 public static void Parse(AAProgram ast, ErrorCollection errors, SharedData data, out string rootFile)
 {
     FinalTransformations finalTrans = new FinalTransformations(errors, data);
     finalTrans.Apply(ast);
     AASourceFile rootSrcFile = Util.GetAncestor<AASourceFile>(finalTrans.mainEntry);
     if (rootSrcFile == null)
         rootFile = "";
     else
         rootFile = rootSrcFile.GetName().Text + ".galaxy";
 }
 public override void OutAAProgram(AAProgram node)
 {
     //Remove all inits of struct fields
     foreach (AStructDecl str in data.Structs.Select(declItem => declItem.Decl))
     {
         foreach (AALocalDecl localDecl in str.GetLocals().OfType<AALocalDecl>())
         {
             localDecl.SetInit(null);
         }
     }
     base.OutAAProgram(node);
 }
 public override void OutAAProgram(AAProgram node)
 {
     //Link stuff in delegates
        /* foreach (SharedData.DeclItem<AMethodDecl> declItem in data.Delegates)
     {
         //declItem.File.GetDecl().Add(declItem.Decl);
         declItem.Decl.Apply(this);
         //declItem.File.GetDecl().Remove(declItem.Decl);
     }*/
     //Remove typedefs
     foreach (ATypedefDecl decl in data.Typedefs)
     {
         decl.Parent().RemoveChild(decl);
     }
     data.Typedefs.Clear();
     base.OutAAProgram(node);
 }
        public override void CaseAAProgram(AAProgram node)
        {
            /*decls.AddRange(finalTrans.data.Structs.Select(str => str.Decl));
            decls.AddRange(finalTrans.data.Methods.Select(str => str.Decl));
            decls.AddRange(finalTrans.data.Fields.Select(str => str.Decl));
            if (finalTrans.data.Locals.Count > 0)
                decls.AddRange(finalTrans.data.Locals.Select(str => str.Value).Aggregate(Aggregate));
            if (finalTrans.data.Structs.Count > 0)
                decls.AddRange(finalTrans.data.StructFields.Values.Aggregate(Aggregate));*/
            base.CaseAAProgram(node);
            Random rand = new Random();
            while (decls.Count > 0)
            {
                int i = rand.Next(decls.Count);
                Node n = decls[i];
                decls.RemoveAt(i);

                if (n is AFieldDecl)
                {
                    AFieldDecl an = (AFieldDecl) n;
                    an.GetName().Text = nextName;
                }
                else if (n is AMethodDecl)
                {
                    AMethodDecl an = (AMethodDecl)n;
                    if (finalTrans.mainEntry == an || (an.GetTrigger() != null && finalTrans.data.HasUnknownTrigger))
                        continue;
                    an.GetName().Text = nextName;
                }
                else if (n is AALocalDecl)
                {
                    AALocalDecl an = (AALocalDecl)n;
                    an.GetName().Text = nextName;
                }
                else if (n is AStructDecl)
                {
                    AStructDecl an = (AStructDecl)n;
                    an.GetName().Text = nextName;
                }
                NextName();
            }
        }
 public static void Parse(AAProgram ast, FinalTransformations finalTrans)
 {
     /*
      * Should be done in Pointers phase
      * foo == null > foo == "" || !DataTableExists(foo);
      *             | foo == -1 || !inUse[foo] || GetIdentifier(foo) != foo->identifier
      *
      *
      * delete foo > delete foo;
      *              foo = null;
      *
      * foo = null > foo = ""
      *            | foo = -1
      *
      *
      * This phase:
      * Add identifier to all structs and classes that are ever dynamically created
      * At any (*foo), analyze if foo can be null, and if so, create null check.
      *
      * Phase 1: Generate SafeVariablesData for all methods.
      *
      */
 }
Exemplo n.º 9
0
 public static void Parse(AAProgram ast, ErrorCollection errors, SharedData data)
 {
     ast.Apply(new Weeder(errors, data));
 }
Exemplo n.º 10
0
        public static void Apply(AAProgram ast, FinalTransformations finalTrans)
        {
            //Build list of file dependacies
            Phase1 phase1 = new Phase1(finalTrans);
            ast.Apply(phase1);
            var dependancies = phase1.dependancies;
            if (dependancies.Keys.Count == 0) return;
            AASourceFile root = Util.GetAncestor<AASourceFile>(finalTrans.mainEntry) ??
                                dependancies.Keys.FirstOrDefault(file => !file.GetName().Text.Contains("\\")) ??
                                dependancies.Keys.First(file => true);

            //Remove files unreachable from root
            //On second thought, dont. there might be static refferences the other way which needs to be included
            /*{
                List<AASourceFile> reachable = GetReachable(root, dependancies);
                AASourceFile[] keys = new AASourceFile[dependancies.Count];
                dependancies.Keys.CopyTo(keys, 0);
                foreach (AASourceFile key in keys)
                {
                    if (!reachable.Contains(key))
                        dependancies.Remove(key);
                }
            }*/

            //Push common depancies up
            /*
             * root -> (item1 -> (item3), item2 -> (item4 -> (item3)))
             *
             * root -> (item3, item1, item2 -> (item4))
             */

            //Add unreachable to the root
            while (true)
            {
                List<AASourceFile> reachable = new List<AASourceFile>();
                GetReachable(root, dependancies, ref reachable);
                if (reachable.Count == dependancies.Count + (reachable.Contains(null) ? 1 : 0)) break;
                AASourceFile[] keys = new AASourceFile[dependancies.Count];
                dependancies.Keys.CopyTo(keys, 0);
                foreach (AASourceFile key in keys)
                {
                    if (!reachable.Contains(key))
                    {
                        AASourceFile k = key;
                        //See if you can find another unreachable file which need this file
                        Dictionary<AASourceFile, int> decendantCounts = new Dictionary<AASourceFile, int>();
                        decendantCounts.Add(k, CountDecendants(k, dependancies, new List<AASourceFile>()));
                        while (true)
                        {
                            AASourceFile file = null;
                            foreach (KeyValuePair<AASourceFile, List<AASourceFile>> dependancy in dependancies)
                            {
                                if (decendantCounts.ContainsKey(dependancy.Key))
                                    continue;
                                if (!dependancy.Value.Contains(k))
                                    continue;
                                file = dependancy.Key;
                                break;
                            }

                            //AASourceFile file = dependancies.FirstOrDefault(item => item.Value.Contains(k)).Key;
                            if (file == null) break;
                            decendantCounts.Add(file, CountDecendants(file, dependancies, new List<AASourceFile>()));
                            k = file;
                        }
                        foreach (KeyValuePair<AASourceFile, int> decendantItem in decendantCounts)
                        {
                            if (decendantItem.Value > decendantCounts[k])
                                k = decendantItem.Key;
                        }

                        dependancies[root].Add(k);
                        break;
                    }
                }
            }
            //It is moved down here because cycles are not removed in unreachable
            RemoveCycles(root, dependancies, new List<AASourceFile> { root });

            //Convert to tree to make it easier
            List<Item> allItems = new List<Item>();
            IncludeItem rootIncludeItem = MakeTree(root, dependancies, allItems, null);
            bool[] removed = new bool[allItems.Count];
            for (int i = 0; i < removed.Length; i++)
                removed[i] = false;
            int removedCount = 0;

            //Ensure that each include is only included one place
            for (int i = 0; i < allItems.Count; i++)
            {
                if (removed[i])
                    continue;

                IncludeItem item1 = (IncludeItem)allItems[i];
                for (int j = i + 1; j < allItems.Count; j++)
                {
                    if (removed[j])
                        continue;
                    IncludeItem item2 = (IncludeItem)allItems[j];

                    if (item1.Current == item2.Current)
                    {
                        List<Item> path1 = item1.Path;
                        List<Item> path2 = item2.Path;

                        for (int k = 0; k < Math.Min(path1.Count, path2.Count); k++)
                        {
                            if (path1[k] != path2[k])
                            {

                                int insertAt = Math.Min(path1[k - 1].Children.IndexOf(path1[k]),
                                                        path2[k - 1].Children.IndexOf(path2[k]));

                                item1.Parent.Children.Remove(item1);
                                LinkedList<IncludeItem> toRemove = new LinkedList<IncludeItem>();
                                toRemove.AddLast(item2);
                                while (toRemove.Count > 0)
                                {
                                    IncludeItem item = toRemove.First.Value;
                                    toRemove.RemoveFirst();
                                    item.Parent.Children.Remove(item);
                                    //allItems.Remove(item);
                                    removedCount++;
                                    removed[item.ListIndex] = true;
                                    foreach (IncludeItem child in item.Children)
                                    {
                                        toRemove.AddLast(child);
                                    }
                                }
                                //j--;

                                path1[k - 1].Children.Insert(insertAt, item1);
                                item1.Parent = path1[k - 1];

                                break;
                            }
                        }
                    }
                }
            }

            List<Item> newAllItems = new List<Item>(allItems.Count - removedCount);
            for (int i = 0; i < allItems.Count; i++)
                if (!removed[i])
                    newAllItems.Add(allItems[i]);
            allItems = newAllItems;

            //Move the null node to nr [0]
            foreach (IncludeItem item in allItems)
            {
                if (item.Current == null)
                {
                    int itemIndex = item.Parent.Children.IndexOf(item);
                    Item item0 = item.Parent.Children[0];
                    item.Parent.Children[0] = item;
                    item.Parent.Children[itemIndex] = item0;
                    break;
                }
            }

            //Insert method decls and move structs & fields up as needed
            ast.Apply(new Phase2(finalTrans, allItems));

            //Insert the headers in the files

            if (Options.Compiler.OneOutputFile)
            {
                //for (int i = 0; i < allItems.Count; i++)
                int i = 0;
                while (allItems.Count > 0)
                {
                    if (allItems[i] is IncludeItem)
                    {
                        IncludeItem includeItem = (IncludeItem) allItems[i];
                        //Dont want the standard lib
                        if (includeItem.Current == null)
                        {
                            i++;
                            continue;
                        }
                        //If it has children with children, then pick another first
                        if (includeItem.Children.Any(child => child.Children.Count > 0))
                        {
                            i++;
                            continue;
                        }
                        if (includeItem.Children.Count == 0)
                        {
                            if (includeItem.Parent == null)
                                break;
                            i++;
                            continue;
                        }
                        i = 0;
                        //Put all children into this
                        while (includeItem.Children.Count > 0)
                        {
                            int childNr = includeItem.Children.Count - 1;
                            allItems.Remove(includeItem.Children[childNr]);
                            if (includeItem.Children[childNr] is FieldItem)
                            {
                                FieldItem aItem = (FieldItem)includeItem.Children[childNr];
                                Node node = aItem.FieldDecl;
                                node.Parent().RemoveChild(node);
                                includeItem.Current.GetDecl().Insert(0, node);
                            }
                            else if (includeItem.Children[childNr] is StructItem)
                            {
                                StructItem aItem = (StructItem)includeItem.Children[childNr];
                                Node node = aItem.StructDecl;
                                node.Parent().RemoveChild(node);
                                includeItem.Current.GetDecl().Insert(0, node);
                            }
                            else if (includeItem.Children[childNr] is MethodDeclItem)
                            {
                                MethodDeclItem aItem = (MethodDeclItem)includeItem.Children[childNr];
                                AMethodDecl aNode = new AMethodDecl();
                                if (aItem.RealDecl.GetStatic() != null) aNode.SetStatic(new TStatic("static"));
                                aNode.SetReturnType(Util.MakeClone(aItem.RealDecl.GetReturnType(), finalTrans.data));
                                aNode.SetName(new TIdentifier(aItem.RealDecl.GetName().Text));
                                foreach (AALocalDecl formal in aItem.RealDecl.GetFormals())
                                {
                                    AALocalDecl clone = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, Util.MakeClone(formal.GetType(), finalTrans.data), new TIdentifier(formal.GetName().Text), null);
                                    aNode.GetFormals().Add(clone);
                                }
                                includeItem.Current.GetDecl().Insert(0, aNode);
                            }
                            else if (includeItem.Children[childNr] is IncludeItem)
                            {
                                IncludeItem aChild = (IncludeItem)includeItem.Children[childNr];
                                if (aChild.Current == null)
                                {
                                    AIncludeDecl node = new AIncludeDecl(new TInclude("include"),
                                                        new TStringLiteral("\"TriggerLibs/NativeLib\""));
                                    includeItem.Current.GetDecl().Insert(0, node);
                                }
                                else
                                {
                                    PDecl[] decls = new PDecl[aChild.Current.GetDecl().Count];
                                    aChild.Current.GetDecl().CopyTo(decls, 0);
                                    for (int k = decls.Length - 1; k >= 0; k--)
                                    {
                                        includeItem.Current.GetDecl().Insert(0, decls[k]);
                                    }
                                    aChild.Current.Parent().RemoveChild(aChild.Current);
                                    //i = -1;
                                }
                            }
                            includeItem.Children.RemoveAt(childNr);
                        }
                    }
                }
            }
            else
                foreach (IncludeItem includeItem in allItems.OfType<IncludeItem>())
                {
                    for (int i = includeItem.Children.Count - 1; i >= 0; i--)
                    {
                        Node node;
                        if (includeItem.Children[i] is IncludeItem)
                        {
                            IncludeItem aItem = (IncludeItem) includeItem.Children[i];
                            node = new AIncludeDecl(new TInclude("include"),
                                                    new TStringLiteral("\"" + (aItem.Current == null ? "TriggerLibs/NativeLib" : aItem.Current.GetName().Text.Replace("\\", "/")) + "\""));
                            if (aItem.Current == null && finalTrans.mainEntry != null)
                            {
                                //Search for user defined initlib
                                bool foundInvoke = false;
                                foreach (ASimpleInvokeExp invokeExp in finalTrans.data.SimpleMethodLinks.Keys)
                                {
                                    if(invokeExp.GetName().Text == "libNtve_InitLib" && invokeExp.GetArgs().Count == 0)
                                    {
                                        /*finalTrans.errors.Add(new ErrorCollection.Error(invokeExp.GetName(),
                                                                                        Util.GetAncestor<AASourceFile>(
                                                                                            invokeExp),
                                                                                        "You are invoking libNtve_InitLib() yourself somewhere. It will not be auto inserted.",
                                                                                        true));*/
                                        foundInvoke = true;
                                        break;
                                    }
                                }

                                if (!foundInvoke)
                                {
                                    //Init the lib
                                    ASimpleInvokeExp initExp = new ASimpleInvokeExp();
                                    initExp.SetName(new TIdentifier("libNtve_InitLib"));
                                    finalTrans.data.ExpTypes[initExp] = new AVoidType(new TVoid("void"));
                                    foreach (AMethodDecl method in finalTrans.data.Libraries.Methods)
                                    {
                                        if (method.GetName().Text == "libNtve_InitLib" && method.GetFormals().Count == 0)
                                        {
                                            finalTrans.data.SimpleMethodLinks[initExp] = method;
                                        }
                                    }
                                    AABlock block = (AABlock) finalTrans.mainEntry.GetBlock();
                                    block.GetStatements().Insert(0, new AExpStm(new TSemicolon(";"), initExp));
                                }
                            }
                        }
                        else if (includeItem.Children[i] is FieldItem)
                        {
                            FieldItem aItem = (FieldItem)includeItem.Children[i];
                            node = aItem.FieldDecl;
                            node.Parent().RemoveChild(node);
                        }
                        else if (includeItem.Children[i] is StructItem)
                        {
                            StructItem aItem = (StructItem)includeItem.Children[i];
                            node = aItem.StructDecl;
                            node.Parent().RemoveChild(node);
                        }
                        else if (includeItem.Children[i] is MethodDeclItem)
                        {
                            MethodDeclItem aItem = (MethodDeclItem)includeItem.Children[i];
                            AMethodDecl aNode = new AMethodDecl();
                            if (aItem.RealDecl.GetStatic() != null) aNode.SetStatic(new TStatic("static"));
                            aNode.SetReturnType(Util.MakeClone(aItem.RealDecl.GetReturnType(), finalTrans.data));
                            aNode.SetName(new TIdentifier(aItem.RealDecl.GetName().Text));
                            foreach (AALocalDecl formal in aItem.RealDecl.GetFormals())
                            {
                                AALocalDecl clone = new AALocalDecl(new APublicVisibilityModifier(), null, null, null, null, Util.MakeClone(formal.GetType(), finalTrans.data), new TIdentifier(formal.GetName().Text), null);
                                aNode.GetFormals().Add(clone);
                            }
                            node = aNode;
                        }
                        else
                            throw new Exception("FixIncludes.Apply: Unexpected item type");

                        includeItem.Current.GetDecl().Insert(0, node);
                    }
                }
        }
Exemplo n.º 11
0
 public virtual void OutAAProgram(AAProgram node)
 {
     DefaultOut(node);
 }
Exemplo n.º 12
0
 public virtual void InAAProgram(AAProgram node)
 {
     DefaultIn(node);
 }
 public override void InAAProgram(AAProgram node)
 {
     LocalChecker.CalculateMethodModify(node, data, out methodCount);
 }
 public override void CaseAAProgram(AAProgram node)
 {
     if (Options.Compiler.ObfuscateStrings)
         base.CaseAAProgram(node);
 }
Exemplo n.º 15
0
 internal SourceFiles_Cast(AAProgram obj)
 {
     this.obj = obj;
 }
Exemplo n.º 16
0
        public override void OutAAProgram(AAProgram node)
        {
            foreach (var pair in Refferences)
            {
                if (structsWithGenerics.Contains(pair.Key) && pair.Value.Count > 0)
                    needAnotherPass = true;
            }
            foreach (var pair in Refferences)
            {
                AStructDecl str = pair.Key;
                if (!copies.ContainsKey(str))
                    copies[str] = new List<List<PType>>();
                IList declList;
                Node parent = str.Parent();
                if (parent is AASourceFile)
                    declList = ((AASourceFile)parent).GetDecl();
                else
                    declList = ((ANamespaceDecl)parent).GetDecl();
                //AASourceFile pFile = (AASourceFile) str.Parent();
                foreach (AGenericType refference in pair.Value)
                {

                    AStructDecl clone = null;
                    bool addList = true;
                    foreach (List<PType> list in copies[str])
                    {
                        bool listEqual = true;
                        for (int i = 0; i < list.Count; i++)
                        {
                            if (!Util.TypesEqual(list[i], (PType) refference.GetGenericTypes()[i], data))
                            {
                                listEqual = false;
                                break;
                            }
                        }
                        if (listEqual)
                        {
                            addList = false;
                            clone = clones[list];
                            break;
                        }
                    }
                    if (addList)
                    {
                        List<PType> list = new List<PType>();
                        foreach (PType type in refference.GetGenericTypes())
                        {
                            list.Add(type);
                        }
                        copies[str].Add(list);

                        clone = (AStructDecl)str.Clone();
                        declList.Insert(declList.IndexOf(str), clone);

                        clone.Apply(new EnviromentBuilding(errors, data));
                        clone.Apply(new EnviromentChecking(errors, data, false));
                        clone.Apply(new LinkNamedTypes(errors, data));
                        /*
                        data.Structs.Add(new SharedData.DeclItem<AStructDecl>(pFile, clone));
                        data.StructFields[clone] = new List<AALocalDecl>();
                        data.StructMethods[clone] = new List<AMethodDecl>();
                        data.StructProperties[clone] = new List<APropertyDecl>();
                        data.StructConstructors[clone] = new List<AConstructorDecl>();
                        foreach (PLocalDecl localDecl in clone.GetLocals())
                        {
                            if (localDecl is AALocalDecl)
                            {
                                data.StructFields[clone].Add((AALocalDecl)localDecl);
                            }
                            else
                            {
                                PDecl decl = ((ADeclLocalDecl) localDecl).GetDecl();
                                if (decl is AMethodDecl)
                                {
                                    data.StructMethods[clone].Add((AMethodDecl) decl);
                                }
                                else if (decl is APropertyDecl)
                                {
                                    data.StructProperties[clone].Add((APropertyDecl)decl);
                                }
                                else
                                {
                                    data.StructConstructors[clone].Add((AConstructorDecl) decl);
                                }
                            }
                        }*/

                        clones[list] = clone;

                        clone.setGenericVars(new ArrayList());

                        FixGenericLinks.Parse(str, clone, list, data);
                        clone.GetName().Text = Util.TypeToIdentifierString(refference);
                    }
                    //Change refference to clone
                    ANamedType baseRef = (ANamedType) refference.GetBase();
                    List<string> cloneNs = Util.GetFullNamespace(clone);
                    cloneNs.Add(clone.GetName().Text);
                    AAName aName = (AAName) baseRef.GetName();
                    aName.GetIdentifier().Clear();
                    foreach (var n in cloneNs)
                    {
                        aName.GetIdentifier().Add(new TIdentifier(n));
                    }
                    data.StructTypeLinks[baseRef] = clone;
                    refference.ReplaceBy(baseRef);
                }

                if (!needAnotherPass)
                    parent.RemoveChild(str);
            }
            if (needAnotherPass)
            {
                Refferences.Clear();
                structsWithGenerics.Clear();
                needAnotherPass = false;
                CaseAAProgram(node);
            }
        }
 public override void OutAAProgram(AAProgram node)
 {
     List<ALocalLvalue> deleteUs = new List<ALocalLvalue>();
     foreach (KeyValuePair<ALocalLvalue, AALocalDecl> pair in finalTrans.data.LocalLinks)
     {
         if (!Util.HasAncestor<AAProgram>(pair.Key))
             deleteUs.Add(pair.Key);
     }
     foreach (ALocalLvalue lvalue in deleteUs)
     {
         finalTrans.data.LocalLinks.Remove(lvalue);
     }
 }
Exemplo n.º 18
0
 public override void OutAAProgram(AAProgram node)
 {
     List<AMethodDecl> checkedMethods = new List<AMethodDecl>();
     List<AMethodDecl> path = new List<AMethodDecl>();
     //Check that we dont have an inline method cycle
     foreach (KeyValuePair<AMethodDecl, List<AMethodDecl>> inlineMethodCall in InlineMethodCalls)
     {
         CheckInlineMethod(inlineMethodCall.Key, checkedMethods, path);
     }
     //Check that we dont have a struct dependancy cycle
     List<AStructDecl> checkedStructs = new List<AStructDecl>();
     List<AStructDecl> structPath = new List<AStructDecl>();
     foreach (KeyValuePair<AStructDecl, List<AStructDecl>> structDepandancy in StructDepandancies)
     {
         CheckStructDependancies(structDepandancy.Key, checkedStructs, structPath);
     }
 }
Exemplo n.º 19
0
 public static void Parse(AAProgram ast, ErrorCollection errors, SharedData data)
 {
     ast.Apply(new TypeChecking(errors, data));
 }
 public static void Parse(AAProgram ast, ErrorCollection errors, SharedData data)
 {
     ast.Apply(new EnviromentBuilding(errors, data));
 }
 public static void Parse(AAProgram ast, ErrorCollection errors, SharedData data, DirectoryInfo outputDir)
 {
     ast.Apply(new CodeGeneration(errors, data, outputDir));
 }
Exemplo n.º 22
0
 public override void InAAProgram(AAProgram node)
 {
     node.Apply(new BlockFixer(data));
 }
        public override void OutAAProgram(AAProgram node)
        {
            foreach (KeyValuePair<AArrayLengthLvalue, AArrayTempType> pair in data.ArrayLengthTypes)
            {
                AIntConstExp intConst = new AIntConstExp(new TIntegerLiteral(pair.Value.GetIntDim().Text));
                data.ExpTypes[intConst] = new ANamedType(new TIdentifier("int"), null);
                ALvalueExp exp = Util.GetAncestor<ALvalueExp>(pair.Key);
                exp.ReplaceBy(intConst);
            }

            base.OutAAProgram(node);
        }
        public override void InAAProgram(AAProgram node)
        {
            return;
            //Check that there are not two diffrent definitions with same name, in same namespace

            for (int i = 0; i < node.GetSourceFiles().Count; i++)
            {
                for (int j = i; j < node.GetSourceFiles().Count; j++)
                {
                    AASourceFile file1 = (AASourceFile) node.GetSourceFiles()[i];
                    AASourceFile file2 = (AASourceFile) node.GetSourceFiles()[j];

                    Check(new List<IList>() {file1.GetDecl()}, new List<IList>() {file2.GetDecl()});
                }
            }
        }
        public override void OutAAProgram(AAProgram node)
        {
            List<IDecl> decls = new List<IDecl>(this.decls.Count);
            decls.AddRange(this.decls);
            bool changes;
            do
            {
                decls.Sort(Compare);
                changes = false;

                for (int i = 0; i < decls.Count; i++ )
                {
                    int j = i + 1;
                    for (; j < decls.Count; j++)
                    {
                        if (Compare(decls[i], decls[j]) != 0)
                            break;
                    }
                    if (j - i > 1)
                    {//The same from i to j-1
                        bool sameType = true;
                        for (int k = i + 1; k < j; k++)
                            if (decls[i].GetType() != decls[k].GetType())
                            {
                                //We have diffrent types. Add letter
                                sameType = false;
                                for (k = i; k < j; k++)
                                    decls[k].AddStandardLetter();
                                break;
                            }
                        //Now, add numbers if they are still the same
                        if (sameType)
                        {
                            for (int k = i; k < j; k++)
                            {
                                decls[k].Name += k - i + 1;
                            }
                        }
                        i = j - 1;
                        changes = true;
                    }
                }

            } while (changes);

            List<IDecl> localDecls = new List<IDecl>(this.localDecls.Count);
            localDecls.AddRange(this.localDecls);
            do
            {
                localDecls.Sort(Compare);
                changes = false;

                for (int i = 0; i < localDecls.Count; i++)
                {
                    int j = i + 1;
                    for (; j < localDecls.Count; j++)
                    {
                        if (Compare(localDecls[i], localDecls[j]) != 0)
                            break;
                    }
                    if (j - i > 1)
                    {//The same from i to j-1

                        bool sameType = true;
                        for (int k = i + 1; k < j; k++)
                            if (localDecls[i].GetType() != localDecls[k].GetType())
                            {
                                //We have diffrent types. Add letter
                                sameType = false;
                                for (k = i; k < j; k++)
                                    localDecls[k].AddStandardLetter();
                                break;
                            }
                        //Now, add numbers if they are still the same
                        if (sameType)
                        {
                            for (int k = i; k < j; k++)
                            {
                                localDecls[k].Name += k - i + 1;
                            }
                        }
                        i = j - 1;
                        changes = true;
                    }
                }

            } while (changes);
        }
Exemplo n.º 26
0
 public override void CaseAAProgram(AAProgram node)
 {
     InAAProgram(node);
     {
         Object[] temp = new Object[node.GetSourceFiles().Count];
         node.GetSourceFiles().CopyTo(temp, 0);
         for (int i = temp.Length - 1; i >= 0; i--)
         {
             ((PSourceFile)temp[i]).Apply(this);
         }
     }
     OutAAProgram(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.º 28
0
 public virtual void CaseAAProgram(AAProgram node)
 {
     DefaultCase(node);
 }
Exemplo n.º 29
0
        public static void CalculateMethodModify(AAProgram ast, SharedData data, out int methodCount)
        {
            //Calculate what global variables all methods might modify.
            methodData.Clear();

            GetDependancies dependancies = new GetDependancies(data);
            ast.Apply(dependancies);
            methodCount = dependancies.UsedMethods.Count;

            while (dependancies.UsedMethods.Count > 0)
            {
                LinkedList<AMethodDecl> modified = new LinkedList<AMethodDecl>();
                foreach (var pair in dependancies.UsedMethods)
                {
                    AMethodDecl method = pair.Key;
                    List<AMethodDecl> usedMethods = pair.Value;

                    ModifyData modifyData = new ModifyData();
                    foreach (AFieldDecl fieldDecl in dependancies.ReadFields[method])
                    {
                        modifyData.Add(fieldDecl, true, false);
                    }
                    foreach (AFieldDecl fieldDecl in dependancies.WrittenFields[method])
                    {
                        modifyData.Add(fieldDecl, false, true);
                    }
                    bool skip = false;
                    foreach (AMethodDecl usedMethod in usedMethods)
                    {
                        ModifyData usedData = GetModifyData(usedMethod);
                        if (usedData == null)
                        {
                            skip = true;
                            break;
                        }
                        modifyData.Union(usedData);
                    }
                    if (skip)
                        continue;
                    methodData[method] = modifyData;
                    modified.AddLast(method);
                }
                foreach (AMethodDecl decl in modified)
                {
                    dependancies.UsedMethods.Remove(decl);
                    dependancies.ReadFields.Remove(decl);
                    dependancies.WrittenFields.Remove(decl);
                }
                if (modified.Count == 0)
                {//The rest is in a circular dependancy
                    foreach (var pair in dependancies.UsedMethods)
                    {
                        AMethodDecl method = pair.Key;

                        ModifyData modifyData = new ModifyData();

                        Update(method, new List<AMethodDecl>(), modifyData, dependancies.UsedMethods, dependancies.ReadFields, dependancies.WrittenFields);

                        methodData[method] = modifyData;
                        modified.AddLast(method);
                    }
                    dependancies.UsedMethods.Clear();
                }
            }
        }
Exemplo n.º 30
0
 public override void OutAAProgram(AAProgram node)
 {
     foreach (ANamedType type in finalTrans.data.DelegateTypeLinks.Keys)
     {
         type.SetPrimitive("string");
     }
     base.OutAAProgram(node);
 }