コード例 #1
0
        private CompileUnit GenInitUnit(Dictionary <string, string> transMap)
        {
            CompileUnit unit = new CompileUnit();

            unit.Name = "il2cppInit";

            CodePrinter prtGC      = new CodePrinter();
            CodePrinter prtInit    = new CodePrinter();
            bool        addedRoots = false;

            foreach (var kv in InitFldsMap)
            {
                unit.ImplDepends.Add(transMap[kv.Key]);

                foreach (var item in kv.Value)
                {
                    if (item.Item2)
                    {
                        prtGC.AppendFormatLine("IL2CPP_ADD_ROOT({0}),", item.Item1);
                        addedRoots = true;
                    }
                    prtInit.AppendFormatLine("{0} = {{}};", item.Item1);
                }
            }

            CodePrinter prtFunc = new CodePrinter();

            prtFunc.AppendLine("void il2cpp_InitVariables()\n{");
            ++prtFunc.Indents;
            if (addedRoots)
            {
                prtFunc.AppendLine("il2cppRootItem roots[] =\n{");
                ++prtFunc.Indents;
                prtFunc.Append(prtGC.ToString());
                --prtFunc.Indents;
                prtFunc.AppendLine("};");
                prtFunc.AppendLine("il2cpp_CommitRoots(roots, sizeof(roots) / sizeof(roots[0]));");
            }
            prtFunc.Append(prtInit.ToString());
            --prtFunc.Indents;
            prtFunc.AppendLine("}");

            unit.ImplCode = prtFunc.ToString();

            return(unit);
        }
コード例 #2
0
        private void GenerateIsType(CodePrinter prtDecl, CodePrinter prtImpl)
        {
            if (CurrType.IsValueType)
            {
                return;
            }

            CodePrinter prt = new CodePrinter();

            prt.AppendFormat("uint8_t istype_{0}(uint32_t typeID)",
                             GenContext.GetTypeName(CurrType));

            string strDecl = prt.ToString() + ";\n";

            prt.AppendLine("\n{");
            ++prt.Indents;

            var derivedRange = new List <TypeX>(CurrType.DerivedTypes);

            derivedRange.Add(CurrType);

            List <TypeX> derTypes = new List <TypeX>();

            foreach (var derTyX in derivedRange)
            {
                // 跳过不分配在堆上的类型
                if (!derTyX.IsInstantiated || derTyX.IsValueType || derTyX.Def.IsInterface)
                {
                    continue;
                }
                derTypes.Add(derTyX);
            }

            if (derTypes.Count > 0)
            {
                prt.AppendLine("switch (typeID)\n{");
                ++prt.Indents;

                derTypes.Sort((lhs, rhs) =>
                              GenContext.GetTypeID(lhs).CompareTo(GenContext.GetTypeID(rhs)));

                foreach (var derTyX in derTypes)
                {
                    prt.AppendFormatLine("// {0}",
                                         derTyX.GetNameKey());
                    prt.AppendFormatLine("case {0}:",
                                         GenContext.GetTypeID(derTyX));
                }

                ++prt.Indents;
                prt.AppendLine("return 1;");
                --prt.Indents;

                --prt.Indents;
                prt.AppendLine("}");
            }

            prt.AppendLine("return 0;");

            --prt.Indents;
            prt.AppendLine("}");

            prtDecl.Append(strDecl);
            prtImpl.Append(prt.ToString());
        }
コード例 #3
0
        public CompileUnit Generate()
        {
            CompileUnit unit = new CompileUnit();

            unit.Name = GenContext.GetTypeName(CurrType);

            // 重排字段
            var fields = LayoutFields(out var sfields);

            // 生成类结构
            CodePrinter prtDecl = new CodePrinter();

            if (!CurrType.IsEnumType)
            {
                prtDecl.AppendFormatLine("// {0}", CurrType.GetNameKey());
                var baseType = CurrType.BaseType;

                // 值类型不继承任何基类
                if (CurrType.IsValueType)
                {
                    baseType = null;
                }

                // 接口类型继承 object
                if (baseType == null && CurrType.Def.IsInterface)
                {
                    baseType = GenContext.TypeMgr.GetTypeByName("Object");
                }

                if (baseType != null)
                {
                    string strBaseTypeName = GenContext.GetTypeName(baseType);
                    unit.DeclDepends.Add(strBaseTypeName);

                    prtDecl.AppendFormatLine("struct {0} : {1}",
                                             GenContext.GetTypeName(CurrType),
                                             strBaseTypeName);
                }
                else
                {
                    prtDecl.AppendFormatLine("struct {0}",
                                             GenContext.GetTypeName(CurrType));
                }

                prtDecl.AppendLine("{");
                ++prtDecl.Indents;

                // 生成对象内置字段
                if (CurrType.IsArrayType)
                {
                    var arrayInfo = CurrType.ArrayInfo;
                    if (arrayInfo.IsSZArray)
                    {
                        prtDecl.AppendLine("int32_t Length;");
                    }
                    else
                    {
                        uint rank = arrayInfo.Rank;
                        for (int i = 0; i < rank; ++i)
                        {
                            prtDecl.AppendFormatLine("int32_t LowerBound{0};\nint32_t Size{0};", i);
                        }
                    }
                }
                else
                {
                    string nameKey = CurrType.GetNameKey();
                    if (nameKey == "Object")
                    {
                        prtDecl.AppendLine("uint32_t TypeID;");
                    }
                    else if (nameKey == "System.Array")
                    {
                        prtDecl.AppendLine("int32_t Rank;");
                    }
                }

                // 生成字段
                foreach (var fldX in fields)
                {
                    RefValueTypeDecl(unit, fldX.FieldType);

                    prtDecl.AppendLine("// " + fldX.GetReplacedNameKey());
                    prtDecl.AppendFormatLine("{0} {1};",
                                             GenContext.GetTypeName(fldX.FieldType),
                                             GenContext.GetFieldName(fldX));
                }

                --prtDecl.Indents;
                prtDecl.AppendLine("};");
            }

            CodePrinter prtImpl = new CodePrinter();

            // 生成类型判断函数
            GenerateIsType(prtDecl, prtImpl);

            // 生成静态字段
            foreach (var sfldX in sfields)
            {
                RefValueTypeDecl(unit, sfldX.FieldType);

                string fldDecl = string.Format("{0} {1};",
                                               GenContext.GetTypeName(sfldX.FieldType),
                                               GenContext.GetFieldName(sfldX));

                prtDecl.AppendFormatLine("// {0} -> {1}", sfldX.DeclType.GetNameKey(), sfldX.GetReplacedNameKey());
                prtDecl.AppendLine("extern " + fldDecl);
                prtImpl.AppendLine(fldDecl);
            }

            // 生成方法
            foreach (MethodX metX in CurrType.Methods)
            {
                var metGen = new MethodGenerator(GenContext, metX);
                metGen.Generate();

                prtDecl.AppendFormatLine("// {0} -> {1}", metX.DeclType.GetNameKey(), metX.GetReplacedNameKey());
                prtDecl.Append(metGen.DeclCode);
                unit.DeclDepends.UnionWith(metGen.DeclDepends);

                prtImpl.Append(metGen.ImplCode);
                unit.ImplDepends.UnionWith(metGen.ImplDepends);

                unit.StringDepends.UnionWith(metGen.StringDepends);
            }

            unit.DeclCode = prtDecl.ToString();
            unit.ImplCode = prtImpl.ToString();

            return(unit);
        }
コード例 #4
0
        public CompileUnit Generate()
        {
            CompileUnit unit = new CompileUnit();

            unit.Name = GenContext.GetTypeName(CurrType, false);

            // 重排字段
            var fields = LayoutFields(out var sfields);

            string nameKey      = CurrType.GetNameKey();
            bool   currIsObject = nameKey == "Object";

            // 生成类结构
            CodePrinter prtDecl = new CodePrinter();

            if (!CurrType.IsEnumType)
            {
                prtDecl.AppendFormatLine("// {0}", nameKey);
                var baseType = CurrType.BaseType;

                // 值类型不继承任何基类
                if (CurrType.IsValueType)
                {
                    baseType = null;
                }

                // 接口类型继承 object
                if (baseType == null && CurrType.Def.IsInterface)
                {
                    baseType = GenContext.TypeMgr.GetTypeByName("Object");
                }

                if (baseType != null)
                {
                    string strBaseTypeName = GenContext.GetTypeName(baseType);
                    unit.DeclDepends.Add(strBaseTypeName);

                    prtDecl.AppendFormatLine("struct {0} : {1}",
                                             GenContext.GetTypeName(CurrType),
                                             strBaseTypeName);
                }
                else
                {
                    prtDecl.AppendFormatLine("struct {0}",
                                             GenContext.GetTypeName(CurrType));
                }

                prtDecl.AppendLine("{");
                ++prtDecl.Indents;

                // 生成对象内置字段
                if (CurrType.IsArrayType)
                {
                    var arrayInfo = CurrType.ArrayInfo;
                    if (!arrayInfo.IsSZArray)
                    {
                        uint rank = arrayInfo.Rank;
                        for (int i = 0; i < rank; ++i)
                        {
                            prtDecl.AppendFormatLine("int32_t LowerBound{0};\nuint32_t Size{0};", i);
                        }
                    }
                }
                else
                {
                    if (currIsObject)
                    {
                        prtDecl.AppendLine("uint32_t TypeID;");
                        prtDecl.AppendLine("uint8_t Flags[4];");
                    }
                    else if (nameKey == "System.Array")
                    {
                        prtDecl.AppendLine("uintptr_t Length;");
                        prtDecl.AppendLine("uint32_t Rank;");
                        prtDecl.AppendLine("uint32_t ElemSize;");
                    }
                }

                bool isExplicitLayout = CurrType.Def.IsExplicitLayout;
                uint classSize        = CurrType.Def.ClassSize;
                bool hasStructSize    = CurrType.Def.HasClassLayout && classSize != 0;
                if (isExplicitLayout || hasStructSize)
                {
                    prtDecl.AppendLine("union\n{");
                    ++prtDecl.Indents;

                    if (!isExplicitLayout && fields.Count != 0)
                    {
                        prtDecl.AppendLine("struct\n{");
                        ++prtDecl.Indents;
                    }
                }

                int fldCounter = 0;

                // 生成字段
                foreach (var fldX in fields)
                {
                    RefValueTypeDecl(unit, fldX.FieldType);

                    bool isFieldExLayout = isExplicitLayout && fldX.Def.FieldOffset != 0;
                    if (isFieldExLayout)
                    {
                        prtDecl.AppendLine("struct\n{");
                        ++prtDecl.Indents;
                        prtDecl.AppendFormatLine("uint8_t padding_{0}[{1}];",
                                                 fldCounter,
                                                 fldX.Def.FieldOffset);
                    }

                    prtDecl.AppendLine("// " + fldX.GetReplacedNameKey());
                    prtDecl.AppendFormatLine("{0} {1};",
                                             GenContext.GetTypeName(fldX.FieldType),
                                             GenContext.GetFieldName(fldX));

                    if (isFieldExLayout)
                    {
                        --prtDecl.Indents;
                        prtDecl.AppendLine("};");
                    }

                    ++fldCounter;
                }

                if (isExplicitLayout || hasStructSize)
                {
                    if (!isExplicitLayout && fields.Count != 0)
                    {
                        --prtDecl.Indents;
                        prtDecl.AppendLine("};");
                    }
                    if (hasStructSize)
                    {
                        prtDecl.AppendFormatLine("uint8_t padding_struct[{0}];",
                                                 classSize);
                    }

                    --prtDecl.Indents;
                    prtDecl.AppendLine("};");
                }

                --prtDecl.Indents;
                prtDecl.AppendLine("};");
            }

            CodePrinter prtImpl = new CodePrinter();

            // 生成类型判断函数
            GenerateIsType(prtDecl, prtImpl, currIsObject);

            // 生成静态字段
            foreach (var sfldX in sfields)
            {
                RefValueTypeDecl(unit, sfldX.FieldType);

                string fldDecl = string.Format("{0} {1};",
                                               GenContext.GetTypeName(sfldX.FieldType),
                                               GenContext.GetFieldName(sfldX));

                prtDecl.AppendFormatLine("// {0} -> {1}", sfldX.DeclType.GetNameKey(), sfldX.GetReplacedNameKey());
                prtDecl.AppendLine("extern " + fldDecl);
                prtImpl.AppendLine(fldDecl);
            }

            // 生成方法
            foreach (MethodX metX in CurrType.Methods)
            {
                var metGen = new MethodGenerator(GenContext, metX);
                metGen.Generate();

                AppendRuntimeFlags(metX, prtDecl);

                prtDecl.AppendFormatLine("// {0}{1}{2} -> {3}",
                                         !metX.Def.HasBody && !metX.Def.IsAbstract ? "extern " : null,
                                         metX.Def.IsInternalCall ? "internalcall " : null,
                                         metX.DeclType.GetNameKey(),
                                         metX.GetReplacedNameKey());

                prtDecl.Append(metGen.DeclCode);
                unit.DeclDepends.UnionWith(metGen.DeclDepends);

                prtImpl.Append(metGen.ImplCode);
                unit.ImplDepends.UnionWith(metGen.ImplDepends);

                unit.StringDepends.UnionWith(metGen.StringDepends);
            }

            unit.DeclCode = prtDecl.ToString();
            unit.ImplCode = prtImpl.ToString();

            return(unit);
        }
コード例 #5
0
ファイル: TypeGenerator.cs プロジェクト: xushenghan/il2cpp
        private void GenerateCompileUnits()
        {
            List <TypeCppCode> codeSorter = new List <TypeCppCode>(CodeMap.Values);

            // 构建类型代码依赖关联
            foreach (var cppCode in codeSorter)
            {
                foreach (string typeName in cppCode.DeclDependNames)
                {
                    if (GetCodeFromMap(typeName, out var typeCode))
                    {
                        cppCode.DeclDependTypes.Add(typeCode);
                    }
                }
                cppCode.DeclDependNames = null;

                foreach (string typeName in cppCode.ImplDependNames)
                {
                    if (GetCodeFromMap(typeName, out var typeCode))
                    {
                        cppCode.ImplDependTypes.Add(typeCode);
                    }
                }
                cppCode.ImplDependNames = null;
            }
            CodeMap.Clear();

            // 统计依赖计数
            foreach (var cppCode in codeSorter)
            {
                // 预生成排序索引
                cppCode.GetSortedID();

                foreach (var typeCode in cppCode.DeclDependTypes)
                {
                    ++typeCode.DependCounter;
                }

                foreach (var typeCode in cppCode.ImplDependTypes)
                {
                    ++typeCode.DependCounter;
                }
            }

            // 排序代码
            codeSorter.Sort((x, y) =>
            {
                int cmp = x.GetSortedID().CompareTo(y.GetSortedID());
                if (cmp == 0)
                {
                    cmp = y.DependCounter.CompareTo(x.DependCounter);
                }
                return(cmp);
            });

            // 划分编译单元
            foreach (var cppCode in codeSorter)
            {
                var unit = GetCompileUnit();
                unit.AddCode(cppCode);
                cppCode.CompileUnit = unit;
            }

            StringGen.GenDefineCode(
                100,
                out var strSplitMap,
                out var strCodeMap,
                out string strTypeDefs);

            // 生成代码
            HashSet <string> dependSet = new HashSet <string>();

            foreach (var unit in CompileUnits)
            {
                // 防止包含自身
                dependSet.Add(unit.Name);

                unit.DeclCode.Append("#pragma once\n");
                unit.DeclCode.Append("#include \"il2cpp.h\"\n");

                foreach (var cppCode in unit.CodeList)
                {
                    // 生成头文件依赖包含
                    foreach (var typeCode in cppCode.DeclDependTypes)
                    {
                        string unitName = typeCode.CompileUnit.Name;
                        if (!dependSet.Contains(unitName))
                        {
                            dependSet.Add(unitName);
                            unit.DeclCode.AppendFormat("#include \"{0}.h\"\n",
                                                       unitName);
                        }
                    }
                }
                foreach (var cppCode in unit.CodeList)
                {
                    // 拼接声明代码
                    unit.DeclCode.Append(cppCode.DeclCode);
                    cppCode.DeclCode        = null;
                    cppCode.DeclDependTypes = null;
                }

                foreach (var cppCode in unit.CodeList)
                {
                    // 生成源文件依赖包含
                    foreach (var typeCode in cppCode.ImplDependTypes)
                    {
                        string unitName = typeCode.CompileUnit.Name;
                        if (!dependSet.Contains(unitName))
                        {
                            dependSet.Add(unitName);
                            unit.ImplCode.AppendFormat("#include \"{0}.h\"\n",
                                                       unitName);
                        }
                    }

                    // 生成字符串包含
                    if (strSplitMap != null &&
                        cppCode.DependStrings.Count > 0)
                    {
                        HashSet <int> strUnitSet = new HashSet <int>();
                        foreach (string str in cppCode.DependStrings)
                        {
                            strUnitSet.Add(strSplitMap[str]);
                        }
                        cppCode.DependStrings = null;

                        foreach (var strUnitId in strUnitSet)
                        {
                            string strUnit = "StringUnit_" + strUnitId;
                            unit.ImplCode.AppendFormat("#include \"{0}.h\"\n",
                                                       strUnit);
                        }
                    }
                }
                foreach (var cppCode in unit.CodeList)
                {
                    // 拼接实现代码
                    unit.ImplCode.Append(cppCode.ImplCode);
                    cppCode.ImplCode        = null;
                    cppCode.ImplDependTypes = null;
                }

                // 如果包含内容则追加头文件
                if (unit.ImplCode.Length > 0)
                {
                    unit.ImplCode.Insert(0, string.Format("#include \"{0}.h\"\n", unit.Name));
                }

                unit.CodeList = null;
                dependSet.Clear();
            }

            if (strTypeDefs.Length > 0)
            {
                foreach (var item in strCodeMap)
                {
                    var strUnit = new CppCompileUnit("StringUnit_" + item.Key);
                    CompileUnits.Add(strUnit);
                    strUnit.DeclCode.Append("#pragma once\n");
                    strUnit.DeclCode.Append("#include \"StringTypes.h\"\n");
                    strUnit.DeclCode.Append(item.Value);
                }

                var strTypeDefUnit = new CppCompileUnit("StringTypes");
                CompileUnits.Add(strTypeDefUnit);
                strTypeDefUnit.DeclCode.Append("#pragma once\n");
                strTypeDefUnit.DeclCode.Append("#include \"il2cpp.h\"\n");
                strTypeDefUnit.DeclCode.Append(strTypeDefs);
            }

            // 添加初始化静态变量的函数
            if (StaticInitBody.Length > 0)
            {
                var firstUnit = CompileUnits[0];

                string initDecl = "void il2cpp_InitStaticVars()";
                firstUnit.DeclCode.Append(initDecl + ";\n");

                CodePrinter staticInitPrt = new CodePrinter();
                staticInitPrt.Append(StaticInitDecl.ToString());
                staticInitPrt.Append(initDecl);
                staticInitPrt.AppendLine("\n{");
                ++staticInitPrt.Indents;
                staticInitPrt.Append(StaticInitBody.ToString());
                --staticInitPrt.Indents;
                staticInitPrt.AppendLine("}");

                firstUnit.ImplCode.Append(staticInitPrt);
            }
        }
コード例 #6
0
ファイル: TypeGenerator.cs プロジェクト: xushenghan/il2cpp
        private TypeCppCode GenDeclCode(TypeX currType)
        {
            CodePrinter prt = new CodePrinter();

            // 构造类型注释
            prt.AppendFormatLine("// {0}",
                                 currType.PrettyName());

            // 构造类型结构体代码
            string typeName;
            string baseTypeName = null;

            if (currType.BaseType != null &&
                !currType.Def.IsValueType)
            {
                baseTypeName = currType.BaseType.GetCppName();
                typeName     = currType.GetCppName();
                prt.AppendFormatLine("struct {0} : {1}\n{{",
                                     typeName,
                                     baseTypeName);
            }
            else if (currType.Def.ToTypeSig().IsObjectSig())
            {
                typeName = currType.GetCppName();
                prt.AppendFormatLine("struct {0} : il2cppObject\n{{",
                                     typeName);
            }
            else
            {
                Debug.Assert(
                    currType.Def.IsValueType ||
                    currType.Def.IsInterface);

                typeName = currType.GetCppName();
                prt.AppendFormatLine("struct {0}\n{{",
                                     typeName);
            }

            // 添加代码映射
            TypeCppCode cppCode = new TypeCppCode(typeName);

            CodeMap.Add(typeName, cppCode);

            // 添加基类型依赖
            if (baseTypeName != null)
            {
                cppCode.DeclDependNames.Add(baseTypeName);
            }

            ++prt.Indents;

            // 构造结构体成员
            List <FieldX> staticFields = new List <FieldX>();

            foreach (var fldX in currType.Fields)
            {
                if (fldX.Def.IsStatic)
                {
                    staticFields.Add(fldX);
                    continue;
                }

                string fieldTypeName = fldX.FieldType.GetCppName(TypeMgr);
                prt.AppendFormatLine("// {0}\n{1} {2};",
                                     fldX.PrettyName(),
                                     fieldTypeName,
                                     fldX.GetCppName());

                // 添加字段类型依赖
                if (fldX.FieldType.IsValueType)
                {
                    cppCode.DeclDependNames.Add(fieldTypeName);
                }
            }

            --prt.Indents;
            prt.AppendLine("};");

            // 构造装箱类型
            if (currType.Def.IsValueType)
            {
                prt.AppendFormatLine("struct box_{0} : il2cppObject\n{{",
                                     typeName);
                ++prt.Indents;

                prt.AppendFormatLine("{0} value;",
                                     currType.ToTypeSig().GetCppName(TypeMgr));

                --prt.Indents;
                prt.AppendLine("};");
            }

            // 构造静态字段全局变量
            StringBuilder sbImpl = new StringBuilder();

            foreach (var sfldX in staticFields)
            {
                string sfldTypeName   = sfldX.FieldType.GetCppName(TypeMgr);
                string sfldCppName    = sfldX.GetCppName();
                string sfldPrettyName = sfldX.PrettyName(true);
                string sfldDef        = string.Format("{0} {1};\n",
                                                      sfldTypeName,
                                                      sfldCppName);

                prt.AppendFormat("// {0}\nextern {1}",
                                 sfldPrettyName,
                                 sfldDef);

                sbImpl.AppendFormat("// {0}\n{1}",
                                    sfldPrettyName,
                                    sfldDef);

                StaticInitDecl.Append("extern " + sfldDef);

                StaticInitBody.AppendFormat("{0} = {1};\n",
                                            sfldCppName,
                                            sfldX.FieldType.GetInitValue(TypeMgr));

                // 添加字段类型依赖
                if (sfldX.FieldType.IsValueType)
                {
                    cppCode.DeclDependNames.Add(sfldTypeName);
                    cppCode.ImplDependNames.Add(sfldTypeName);
                }
            }

            // 静态构造函数防止多次调用的标记
            if (currType.CctorMethod != null)
            {
                string onceName = string.Format("onceflag_{0}",
                                                typeName);
                string onceDef = string.Format("int8_t {0};\n",
                                               onceName);

                string locktidName = string.Format("locktid_{0}",
                                                   typeName);
                string locktidDef = string.Format("uintptr_t {0};\n",
                                                  locktidName);

                prt.Append("extern " + onceDef);
                prt.Append("extern " + locktidDef);

                sbImpl.Append(onceDef);
                sbImpl.Append(locktidDef);

                StaticInitDecl.Append("extern " + onceDef);
                StaticInitDecl.Append("extern " + locktidDef);

                StaticInitBody.AppendFormat("{0} = 0;\n",
                                            onceName);
                StaticInitBody.AppendFormat("{0} = 0;\n",
                                            locktidName);
            }

            cppCode.DeclCode.Append(prt);
            cppCode.ImplCode.Append(sbImpl);

            return(cppCode);
        }
コード例 #7
0
ファイル: TypeGenerator.cs プロジェクト: xubingyue/il2cpp
        private void GenIsTypeFunc(CodePrinter prtDecl, CodePrinter prtImpl, bool currIsObject)
        {
            if (CurrType.IsValueType || !CurrType.NeedGenIsType)
            {
                return;
            }

            CodePrinter prt = new CodePrinter();

            prt.AppendFormat("uint8_t {0}(uint32_t typeID)",
                             GenContext.GetIsTypeFuncName(CurrType));

            string strDecl = prt.ToString() + ";\n";

            prt.AppendLine("\n{");
            ++prt.Indents;

            var derivedRange = new List <TypeX>(CurrType.DerivedTypes);

            derivedRange.Add(CurrType);

            var derivedEnumTypes = CurrType.UnBoxedType?.DerivedEnumTypes;

            if (derivedEnumTypes != null)
            {
                derivedRange.AddRange(derivedEnumTypes);
            }

            List <TypeX> derTypes = new List <TypeX>();

            foreach (var derTyX in derivedRange)
            {
                // 跳过不分配在堆上的类型
                if (!derTyX.IsInstantiated || derTyX.Def.IsInterface)
                {
                    continue;
                }
                // 如果当前类型是 object, 则跳过值类型
                if (currIsObject && derTyX.IsValueType)
                {
                    continue;
                }
                derTypes.Add(derTyX);
            }

            if (derTypes.Count > 0)
            {
                prt.AppendLine("switch (typeID)\n{");
                ++prt.Indents;

                derTypes.Sort((lhs, rhs) =>
                              GenContext.GetTypeID(lhs).CompareTo(GenContext.GetTypeID(rhs)));

                foreach (var derTyX in derTypes)
                {
                    prt.AppendFormatLine("// {0}",
                                         Helper.EscapeString(derTyX.GetNameKey()));
                    prt.AppendFormatLine("case {0}:",
                                         GenContext.GetTypeID(derTyX));
                }

                ++prt.Indents;
                prt.AppendLine("return 1;");
                --prt.Indents;

                --prt.Indents;
                prt.AppendLine("}");
            }

            prt.AppendLine("return 0;");

            --prt.Indents;
            prt.AppendLine("}");

            prtDecl.Append(strDecl);
            prtImpl.Append(prt.ToString());
        }
コード例 #8
0
ファイル: TypeGenerator.cs プロジェクト: xubingyue/il2cpp
        public CompileUnit Generate()
        {
            CompileUnit unit        = new CompileUnit();
            string      strTypeName = GenContext.GetTypeName(CurrType, false);

            unit.Name = strTypeName;

            // 重排字段
            var fields = LayoutFields(out var sfields);

            string nameKey      = CurrType.GetNameKey();
            bool   currIsObject = nameKey == "Object";

            // 生成类结构
            CodePrinter prtDecl = new CodePrinter();

            if (!CurrType.IsEnumType)
            {
                prtDecl.AppendFormatLine("// {0}", Helper.EscapeString(nameKey));

                ushort packSize = CurrType.Def.HasClassLayout ? CurrType.Def.PackingSize : (ushort)0;
                if (packSize > 2 && !Helper.IsPowerOfTwo(packSize))
                {
                    throw new TypeLoadException();
                }

                if (packSize != 0)
                {
                    prtDecl.AppendLine("#if defined(IL2CPP_MSVC_LIKE)");
                    prtDecl.AppendFormatLine("#pragma pack(push, {0})", packSize);
                    prtDecl.AppendLine("#endif");
                }

                var baseType = CurrType.BaseType;

                // 值类型不继承任何基类
                if (CurrType.IsValueType)
                {
                    baseType = null;
                }

                // 接口类型继承 object
                if (baseType == null && CurrType.Def.IsInterface)
                {
                    baseType = GenContext.GetTypeByName("Object");
                }

                if (baseType != null)
                {
                    string strBaseTypeName = GenContext.GetTypeName(baseType);
                    unit.DeclDepends.Add(strBaseTypeName);

                    prtDecl.AppendFormatLine("struct {0} : {1}",
                                             strTypeName,
                                             strBaseTypeName);
                }
                else
                {
                    prtDecl.AppendFormatLine("struct {0}",
                                             strTypeName);
                }

                prtDecl.AppendLine("{");
                ++prtDecl.Indents;

                // 生成对象内置字段
                if (CurrType.IsArrayType)
                {
                    var arrayInfo = CurrType.ArrayInfo;
                    if (!arrayInfo.IsSZArray)
                    {
                        uint rank = arrayInfo.Rank;
                        for (int i = 0; i < rank; ++i)
                        {
                            prtDecl.AppendFormatLine("int32_t LowerBound{0};\nuint32_t Size{0};", i);
                        }
                    }
                }
                else
                {
                    if (currIsObject)
                    {
                        prtDecl.AppendLine("uint32_t TypeID;");
                        prtDecl.AppendLine("uint8_t Flags[4];");
                    }
                    else if (nameKey == "System.Array")
                    {
                        prtDecl.AppendLine("uint32_t Length;");
                        prtDecl.AppendLine("uint32_t ElemSize : 24;");
                        prtDecl.AppendLine("uint32_t Rank : 8;");
                    }
                }

                bool isExplicitLayout = CurrType.Def.IsExplicitLayout;
                uint classSize        = CurrType.Def.ClassSize;
                bool hasStructSize    = CurrType.Def.HasClassLayout && classSize != 0;
                if (isExplicitLayout || hasStructSize)
                {
                    prtDecl.AppendLine("union\n{");
                    ++prtDecl.Indents;

                    if (!isExplicitLayout && fields.Count != 0)
                    {
                        prtDecl.AppendLine("struct\n{");
                        ++prtDecl.Indents;
                    }
                }

                int fldCounter = 0;

                // 生成字段
                foreach (var fldX in fields)
                {
                    RefValueTypeDecl(unit, fldX.FieldType);

                    bool isFieldExLayout = isExplicitLayout && fldX.Def.FieldOffset != 0;
                    if (isFieldExLayout)
                    {
                        prtDecl.AppendLine("struct\n{");
                        ++prtDecl.Indents;
                        prtDecl.AppendFormatLine("uint8_t padding_{0}[{1}];",
                                                 fldCounter,
                                                 fldX.Def.FieldOffset);
                    }

                    prtDecl.AppendLine("// " + fldX.GetReplacedNameKey());
                    prtDecl.AppendFormatLine("{0} {1};",
                                             GenContext.GetTypeName(fldX.FieldType),
                                             GenContext.GetFieldName(fldX));

                    if (isFieldExLayout)
                    {
                        --prtDecl.Indents;
                        prtDecl.AppendLine("};");
                    }

                    ++fldCounter;
                }

                if (isExplicitLayout || hasStructSize)
                {
                    if (!isExplicitLayout && fields.Count != 0)
                    {
                        --prtDecl.Indents;
                        prtDecl.AppendLine("};");
                    }
                    if (hasStructSize)
                    {
                        prtDecl.AppendFormatLine("uint8_t padding_struct[{0}];",
                                                 classSize);
                    }

                    --prtDecl.Indents;
                    prtDecl.AppendLine("};");
                }

                --prtDecl.Indents;

                if (packSize != 0)
                {
                    prtDecl.AppendFormatLine("}} IL2CPP_PACKED_TAIL({0});",
                                             packSize);
                }
                else
                {
                    prtDecl.AppendLine("};");
                }

                if (packSize != 0)
                {
                    prtDecl.AppendLine("#if defined(IL2CPP_MSVC_LIKE)");
                    prtDecl.AppendLine("#pragma pack(pop)");
                    prtDecl.AppendLine("#endif");
                }
            }

            CodePrinter prtImpl = new CodePrinter();

            // 生成静态字段
            foreach (var sfldX in sfields)
            {
                RefValueTypeDecl(unit, sfldX.FieldType);

                string sfldName = GenContext.GetFieldName(sfldX);
                string fldDecl  = string.Format("{0} {1};",
                                                GenContext.GetTypeName(sfldX.FieldType),
                                                sfldName);

                prtDecl.AppendFormatLine("// {0} -> {1}",
                                         Helper.EscapeString(sfldX.DeclType.GetNameKey()),
                                         Helper.EscapeString(sfldX.GetReplacedNameKey()));
                prtDecl.AppendLine("extern " + fldDecl);
                prtImpl.AppendLine(fldDecl);

                bool hasRef = GenContext.IsRefOrContainsRef(GenContext.GetTypeBySig(sfldX.FieldType));
                GenContext.AddStaticField(strTypeName, sfldName, hasRef);
            }

            // 生成类型判断函数
            GenIsTypeFunc(prtDecl, prtImpl, currIsObject);

            // 生成方法
            foreach (MethodX metX in CurrType.Methods)
            {
                var metGen = new MethodGenerator(GenContext, metX);
                metGen.Generate();

                AppendRuntimeFlags(metX, prtDecl);

                prtDecl.AppendFormatLine("// {0}{1}{2} -> {3}",
                                         Helper.IsExtern(metX.Def) ? "extern " : null,
                                         metX.Def.IsInternalCall ? "internalcall " : null,
                                         Helper.EscapeString(metX.DeclType.GetNameKey()),
                                         Helper.EscapeString(metX.GetReplacedNameKey()));

                prtDecl.Append(metGen.DeclCode);
                unit.DeclDepends.UnionWith(metGen.DeclDepends);

                prtImpl.Append(metGen.ImplCode);
                unit.ImplDepends.UnionWith(metGen.ImplDepends);

                unit.StringDepends.UnionWith(metGen.StringDepends);
            }

            GenerateMetadata(prtDecl, prtImpl);

            unit.DeclCode = prtDecl.ToString();
            unit.ImplCode = prtImpl.ToString();

            return(unit);
        }