Beispiel #1
0
 public IRType PresolveType(TypeDefData pTypeDefData)
 {
     if (pTypeDefData == null)
     {
         throw new ArgumentNullException("pTypeDefData");
     }
     return(AssemblyFileLookup[pTypeDefData.CLIFile].Types[pTypeDefData.TableIndex]);
 }
Beispiel #2
0
        internal void LoadStage2()
        {
            Console.WriteLine("================================================== Stage 2: {0} ==================================================", File.ReferenceName);

            for (int typeIndex = 0; typeIndex < Types.Count; ++typeIndex)
            {
                IRType      type        = Types[typeIndex];
                TypeDefData typeDefData = File.TypeDefTable[typeIndex];
                if (typeDefData.Extends.Type != TypeDefRefOrSpecIndex.TypeDefRefOrSpecType.TypeDef || typeDefData.Extends.TypeDef != null)
                {
                    type.BaseType = AppDomain.PresolveType(typeDefData.Extends);
                }
                for (int fieldIndex = 0; fieldIndex < type.Fields.Count; ++fieldIndex)
                {
                    IRField field = type.Fields[fieldIndex];
                    field.Type = AppDomain.PresolveType(typeDefData.FieldList[fieldIndex].ExpandedSignature);
                    if (field.Type == null)
                    {
                        throw new Exception();
                    }
                }
            }
            for (int methodIndex = 0; methodIndex < Methods.Count; ++methodIndex)
            {
                IRMethod      method        = Methods[methodIndex];
                MethodDefData methodDefData = File.MethodDefTable[methodIndex];
                var           mGenParams    = File.GenericParamTable.Where(gp => gp.Owner.Type == TypeOrMethodDefIndex.TypeOrMethodDefType.MethodDef && gp.Owner.MethodDef == methodDefData).ToList();
                for (int i = 0; i < mGenParams.Count; i++)
                {
                    method.GenericParameters.Add(IRType.GetMVarPlaceholder(mGenParams[i].Number));
                }
                method.ReturnType = AppDomain.PresolveType(methodDefData.ExpandedSignature.RetType);
                for (int parameterIndex = 0; parameterIndex < method.Parameters.Count; ++parameterIndex)
                {
                    IRParameter parameter = method.Parameters[parameterIndex];
                    parameter.Type = AppDomain.PresolveType(methodDefData.ExpandedSignature.Params[parameterIndex]);
                }
                for (int localIndex = 0; localIndex < method.Locals.Count; ++localIndex)
                {
                    IRLocal local = method.Locals[localIndex];
                    local.Type = AppDomain.PresolveType(methodDefData.Body.ExpandedLocalVarSignature.LocalVars[localIndex]);
                }
            }
            for (int methodIndex = 0; methodIndex < Methods.Count; ++methodIndex)
            {
                IRMethod      method        = Methods[methodIndex];
                MethodDefData methodDefData = File.MethodDefTable[methodIndex];
                if (methodDefData.ExpandedSignature.HasThis && !methodDefData.ExpandedSignature.ExplicitThis)
                {
                    IRParameter implicitThis = new IRParameter(this);
                    implicitThis.ParentMethod = method;
                    implicitThis.Type         = method.ParentType.IsValueType ? AppDomain.GetPointerType(method.ParentType) : method.ParentType;
                    method.Parameters.Insert(0, implicitThis);
                }
            }
        }
Beispiel #3
0
        /* NOT USED: Type Definition Arrays will now be handled in the same manner as non-array type definition declarations
         * /// <summary>
         * /// TODO
         * /// </summary>
         * /// <param name="strTypeDefAry"></param>
         * /// <returns></returns>
         * public object[] ExtractTypeDefArrayData(string strTypeDefAry)
         * {
         *  try
         *  {
         *      CHeaderDataSet.tblTypeDefsDataTable dtTypeDefs = m_dsHeaderData.tblTypeDefs;
         *
         *      object[] aryTypeDefAryVarData = null;
         *
         *      string strAnalyze = strTypeDefAry.Trim();
         *      strAnalyze = strAnalyze.Replace("typedef", "").Replace(";", "").Trim();
         *
         *      string[] aryTypeDefAryStr = strAnalyze.Split(' ');
         *
         *      //Extract TypeDef Variable Name
         *      string strTypeDefName = aryTypeDefAryStr[0];
         *
         *      //Extract Typedef Array Declaration Name and Total Number of elements in the array.
         *      int iTotalAryElements = ExtractorUtils.CalculateFieldElements(aryTypeDefAryStr[aryTypeDefAryStr.Length - 1]);
         *      string strTypeDefAryName = aryTypeDefAryStr[aryTypeDefAryStr.Length - 1].Split('[')[0].Trim();
         *
         *      //Set the number of bytes associated with the array type definition which will then be linked to the array typedef declaration name.
         *      //The number of bytes will be calculated by multiplying the number of bytes associated with the primitive derived type definition associated
         *      //with the array type definition.
         *      CHeaderDataSet.tblTypeDefsRow rowTypeDef = dtTypeDefs.FindByTypeDefName(strTypeDefName);
         *
         *      if (rowTypeDef == null)
         *          return null;
         *
         *      int iSrcTypeDefBytes = rowTypeDef.DataSize;
         *      int iDataSizeBytes = iTotalAryElements * iSrcTypeDefBytes;
         *
         *      aryTypeDefAryVarData = new object[] { strTypeDefAryName, strTypeDefName, iTotalAryElements, iDataSizeBytes };
         *
         *      return aryTypeDefAryVarData;
         *  }
         *  catch (Exception err)
         *  {
         *      ErrorHandler.ShowErrorMessage(err, "Error in ExtractTypeDefArrayData function of TypeExtractor class.");
         *      return null;
         *  }
         * }
         */

        #endregion

        #region Enumeration Extraction Functions

        /// <summary>
        /// Examines an enumeration declaration and extracts the appropriate information about the definition into a TypeDefData data object.  Once
        /// the appropriate data is extracted from the enumeration string supplied to the function, the data can be loaded into the appropriate data table
        /// and have their data types be identified in declared variables in structures.
        /// </summary>
        /// <param name="strEnumDef"></param>
        /// <returns></returns>
        public TypeDefData ExtractEnumData(string strEnumDef)
        {
            try
            {
                TypeDefData tdEnum = null;

                string[] aryEnumDefStr = null;
                string   strEnumName   = "";

                if (strEnumDef.StartsWith("enum"))
                {
                    strEnumDef    = strEnumDef.Replace("enum", "").Trim();
                    aryEnumDefStr = strEnumDef.Split('{');
                    strEnumName   = aryEnumDefStr[0].Trim();
                }
                else
                {
                    aryEnumDefStr = strEnumDef.Split('}');

                    //Extract Enumeration Typedef Declaration Name
                    strEnumName = aryEnumDefStr[aryEnumDefStr.Length - 1];
                    strEnumName = strEnumName.Replace(";", "").Trim();
                }//end if

                int iTotalElements = 1;

                //If the enumeration is declared as an array, then the total number of elements in the array and data size of the enumeration array
                //will be calculated.  The data size of an enumeration will be the data size of enumerations on the system multiplied by the number
                //of elements in the array.
                if (strEnumName.Contains('[') && strEnumName.Contains(']'))
                {
                    iTotalElements = ExtractorUtils.CalculateFieldElements(strEnumName);
                    strEnumName    = strEnumName.Split('[')[0].Trim();
                }//end if

                tdEnum = new TypeDefData()
                {
                    TypeDefName = strEnumName, Elements = iTotalElements, DataSize = EnumSizeBytes * iTotalElements
                };

                return(tdEnum);
            }
            catch (Exception err)
            {
                ErrorHandler.ShowErrorMessage(err, "Error in ExtractEnumData function of TypeExtractor class.");
                return(null);
            }
        }
Beispiel #4
0
        internal void LoadStage1()
        {
            Console.WriteLine("================================================== Stage 1: {0} ==================================================", File.ReferenceName);
            foreach (TypeDefData typeDefData in File.TypeDefTable)
            {
                Types.Add(new IRType(this));
            }
            foreach (FieldData fieldData in File.FieldTable)
            {
                Fields.Add(new IRField(this));
            }
            foreach (MethodDefData methodDefData in File.MethodDefTable)
            {
                Methods.Add(new IRMethod(this));
            }

            for (int typeIndex = 0; typeIndex < Types.Count; ++typeIndex)
            {
                IRType      type        = Types[typeIndex];
                TypeDefData typeDefData = File.TypeDefTable[typeIndex];

                type.Namespace = typeDefData.TypeNamespace;
                type.Name      = typeDefData.TypeName;
                var genParams = File.GenericParamTable.Where(gp => gp.Owner.Type == TypeOrMethodDefIndex.TypeOrMethodDefType.TypeDef && gp.Owner.TypeDef == typeDefData).ToList();
                for (int i = 0; i < genParams.Count; i++)
                {
                    type.GenericParameters.Add(IRType.GetVarPlaceholder(genParams[i].Number));
                }

                foreach (FieldData fieldData in typeDefData.FieldList)
                {
                    IRField field = Fields[fieldData.TableIndex];
                    field.Name       = fieldData.Name;
                    field.ParentType = type;
                    type.Fields.Add(field);
                }
                foreach (MethodDefData methodDefData in typeDefData.MethodList)
                {
                    IRMethod method = Methods[methodDefData.TableIndex];
                    method.Name       = methodDefData.Name;
                    method.ParentType = type;
                    method.IsStatic   = (methodDefData.Flags & MethodAttributes.Static) == MethodAttributes.Static;
                    type.Methods.Add(method);

                    foreach (ParamData paramData in methodDefData.ParamList)
                    {
                        IRParameter parameter = new IRParameter(this);
                        parameter.ParentMethod = method;
                        method.Parameters.Add(parameter);
                    }

                    if (methodDefData.Body != null && methodDefData.Body.ExpandedLocalVarSignature != null)
                    {
                        method.MaximumStackDepth = methodDefData.Body.MaxStack;
                        foreach (SigLocalVar sigLocalVar in methodDefData.Body.ExpandedLocalVarSignature.LocalVars)
                        {
                            IRLocal local = new IRLocal(this);
                            local.ParentMethod = method;
                            local.Index        = (uint)method.Locals.Count;
                            method.Locals.Add(local);
                        }
                    }
                }
            }
            for (int typeIndex = 0; typeIndex < Types.Count; ++typeIndex)
            {
                IRType      type        = Types[typeIndex];
                TypeDefData typeDefData = File.TypeDefTable[typeIndex];

                foreach (TypeDefData nestedTypeDefData in typeDefData.NestedClassList)
                {
                    IRType nestedType = Types[nestedTypeDefData.TableIndex];
                    nestedType.Namespace = type.Namespace + "." + type.Name;
                    type.NestedTypes.Add(nestedType);
                }
            }
            if (CORLibrary)
            {
                AppDomain.CacheCORTypes(this);
            }
        }
Beispiel #5
0
        /// <summary>
        /// Examines a type definition declaration and extracts the appropriate information about the definition into a TypeDefData data object.  The
        /// ExtractTypeDefData function will be used to extract type defintions derived from primitive data types and other type definitions,
        /// pointers (including functions) and enumerations.  Union and Structure type definitions will be extracted using the ExtractStructData function
        /// of the StructExtractor class instead.  Once the appropriate data is extracted from the type definition string supplied to the function, the data
        ///  can be loaded into the appropriate data table and have their data types be identified in declared variables in structures.
        /// </summary>
        /// <param name="strTypeDef"></param>
        /// <returns></returns>
        public TypeDefData ExtractTypeDefData(string strTypeDef)
        {
            try
            {
                TypeDefData tdTypeDef = new TypeDefData();

                //Checks to see if the type definition is defined as an array and verifies that the array contains only numeric values.  If
                //non-numeric values are presented in the type definition array declaration, they are first converted to their numeric equivalents
                //before proceeding with extracting the type definition declaration.
                if (!strTypeDef.StartsWith("typedef enum") && !strTypeDef.StartsWith("enum"))
                {
                    if (strTypeDef.Contains('[') && strTypeDef.Contains(']'))
                    {
                        if (!ExtractorUtils.IsNumericArray(strTypeDef))
                        {
                            strTypeDef = ExtractorUtils.ConvertNonNumericElements(m_HeaderAccess, strTypeDef);
                        }
                    }//end if

                    string strAnalyze = strTypeDef.Trim();
                    strAnalyze = strAnalyze.Replace("typedef", "").Replace(";", "").Replace("\n", "").Trim();

                    string[] aryTypeDefStr = strAnalyze.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                    //Extract Primitive C++ Data Type Name
                    string strTypeDefDataType = "";

                    for (int i = 0; i < aryTypeDefStr.Length - 1; i++)
                    {
                        strTypeDefDataType += aryTypeDefStr[i] + " ";
                    }

                    strTypeDefDataType = strTypeDefDataType.TrimEnd();

                    //Extract Typedef Declaration Name
                    string strTypeDefName = aryTypeDefStr[aryTypeDefStr.Length - 1];

                    //Set the number of bytes associated with the primitive C++ data type which will then be linked to the typedef declaration name.
                    int iDataSizeBytes = 0;

                    if (!strTypeDefDataType.Contains("*") && !strTypeDefName.Contains("*"))
                    {
                        if (DataAccess.PrimDataTypes.IsPrimitiveDataType(strTypeDefDataType))
                        {
                            //Locates the associated primitive data type associated with the type definition and set the data size of the type definition, according
                            //to the data type.
                            switch (strTypeDefDataType)
                            {
                            case "RMascii":
                            case "RMbool":
                            case "RMuint8":
                            case "RMint8":
                            case "char":
                            case "unsigned char":
                            case "signed char":
                            case "bool":
                                iDataSizeBytes = 1;
                                break;

                            case "RMuint16":
                            case "RMint16":
                            case "short":
                            case "short int":
                            case "unsigned short":
                            case "unsigned short int":
                            case "signed short":
                            case "signed short int":
                            case "wchar_t":
                                iDataSizeBytes = 2;
                                break;

                            case "RMuint32":
                            case "RMint32":
                            case "RMnewOperatorSize":
                            case "int":
                            case "unsigned int":
                            case "signed int":
                            case "long":
                            case "long int":
                            case "signed long":
                            case "signed long int":
                            case "unsigned long":
                            case "unsigned long int":
                            case "float":
                                iDataSizeBytes = 4;
                                break;

                            case "RMint64":
                            case "RMuint64":
                            case "RMreal":
                            case "long long":
                            case "unsigned long long":
                            case "double":
                            case "long double":
                                iDataSizeBytes = 8;
                                break;
                            }
                            ; //end switch
                        }
                        else
                        {
                            //If the data type of the type definition is associated with another type definition, then the type definition will be located and the
                            //data size of the type definition which is the associated data type of the type definition will be assigned to the type definition being
                            //extracted.
                            CHeaderDataSet.tblTypeDefsRow rowTypeDef = m_HeaderAccess.GetTypeDef(strTypeDefDataType);

                            if (rowTypeDef == null)
                            {
                                return(null);
                            }

                            iDataSizeBytes = rowTypeDef.DataSize;
                        }//end if
                    }
                    else
                    {
                        if (strTypeDefName.Contains('*'))
                        {
                            strTypeDefName = strTypeDefName.Replace("*", "");
                        }

                        //Pointers variables will always be set to the pre-defined size of the pointer length on the operating system, which is preset in the
                        //program's settings by the user.
                        iDataSizeBytes = PointerSizeBytes;
                    }//end if

                    int iTotalElements = 1;

                    //If the type definition is declared as an array, then the total number of elements in the array and data size of the type definition array
                    //will be calculated.  The data size of a type definition will be the data size of the data type associated with the type definition multiplied
                    //by the number of elements in the array.
                    if (strTypeDefName.Contains('[') && strTypeDefName.Contains(']'))
                    {
                        iTotalElements = ExtractorUtils.CalculateFieldElements(strTypeDefName);
                        strTypeDefName = strTypeDefName.Split('[')[0].Trim();
                    }//end if

                    tdTypeDef.TypeDefName = strTypeDefName;
                    tdTypeDef.Elements    = iTotalElements;
                    tdTypeDef.DataSize    = iDataSizeBytes * iTotalElements;
                }
                else
                {
                    //Enumerations and Enumeration TypeDefs handled by ExtractEnumData function.
                    tdTypeDef = ExtractEnumData(strTypeDef);
                }//end if

                return(tdTypeDef);
            }
            catch (Exception err)
            {
                ErrorHandler.ShowErrorMessage(err, "Error in ExtractTypeDefData function of TypeExtractor class.");
                return(null);
            }
        }
Beispiel #6
0
        /*OBSOLETE: Header Files will be loaded and parsed in the Parse button click event handler.
         * /// <summary>
         * /// Loads the data of all the header files set in the header file names textbox into the HeaderDeclareParser object in the form,
         * /// which will then make the header data files available for parsing and extracting their type definition and structure data.
         * /// </summary>
         * /// <param name="sender"></param>
         * /// <param name="e"></param>
         * private void btnLoadHeaderFiles_Click(object sender, EventArgs e)
         * {
         *  try
         *  {
         *      DateTime datStart = DateTime.Now;
         *
         *      if (txtHeaderFileNames.Text.Trim() == "")
         *      {
         *          MessageBox.Show("No header files set to be loaded!", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
         *          return;
         *      }//end if
         *
         *      m_Parser.ClearHeaderData();
         *
         *      string[] aryHeaderFileNames = txtHeaderFileNames.Text.
         *                                                      Split(new string[] { "\r\n", ",", ";" }, StringSplitOptions.RemoveEmptyEntries)
         *                                                      .Select(filename => filename.Trim())
         *                                                      .Where(filename => File.Exists(filename))
         *                                                      .ToArray();
         *
         *      foreach (string strHeaderFileName in aryHeaderFileNames)
         *      {
         *          m_Parser.AppendHeaderFromFile(strHeaderFileName);
         *      }//next strHeaderFileName
         *
         *      btnParse.Enabled = true;
         *
         *      TimeSpan tsElapsed = DateTime.Now.Subtract(datStart);
         *
         *      MessageBox.Show("Header files loaded into CHeaderDeclareParser object!  The header files can now be parsed.", "Headers Loaded",
         *                                  MessageBoxButtons.OK, MessageBoxIcon.Information);
         *
         *      if (chbShowHdrLoadTime.Checked)
         *          MessageBox.Show("Header Data File Loading Time: " + tsElapsed.TotalSeconds.ToString() + " seconds");
         *  }
         *  catch (Exception err)
         *  {
         *      ErrorHandler.ShowErrorMessage(err, "Error in btnLoadHeaderFiles_Click function of frmCHeaderExtract form.");
         *  }
         * }
         */

        #endregion

        #region Header Parsing and Extraction Functions, Event Handlers

        /// <summary>
        /// When the Parse button is clicked, all header data files will be loaded into the HeaderDeclareParser object of the form and then
        /// will be parsed and have the desired information extracted from the file into data objects.   The parser will extract all type definition,
        /// enumerations, structure and union information from the file and load them into their associated data objects in the data tables of a
        /// CHeaderDataSet data object.   Once all the data in the header data file (or set of files) is parsed, the extracted data can be
        /// queried and displayed in the form or extracted to other data file formats.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnParse_Click(object sender, EventArgs e)
        {
            try
            {
                DateTime datStartTime = DateTime.Now;

                if (!LoadHeaderFiles())
                {
                    return;
                }

                this.Cursor = Cursors.WaitCursor;

                m_Parser.CurrentPos = 0;

                m_HeaderAccess.TypeDefsTable.Rows.Clear();
                m_HeaderAccess.StructuresTable.Rows.Clear();
                m_HeaderAccess.FieldsTable.Rows.Clear();

                TypeExtractor.PointerSizeBytes = Convert.ToInt32(txtPointerSize.Text);
                TypeExtractor.EnumSizeBytes    = Convert.ToInt32(txtEnumSize.Text);

                StructExtractor.PointerSizeBytes = Convert.ToInt32(txtPointerSize.Text);
                StructExtractor.EnumSizeBytes    = Convert.ToInt32(txtEnumSize.Text);

                do
                {
                    if (m_Parser.IsTypeDef())
                    {
                        string      strTypeDef = m_Parser.GetTypeDef();
                        TypeDefData tdData     = m_typeExt.ExtractTypeDefData(strTypeDef);

                        if (tdData != null)
                        {
                            m_HeaderAccess.AddTypeDefRow(tdData);
                        }
                    }
                    else if (m_Parser.IsEnum())
                    {
                        string      strEnum = m_Parser.GetEnum();
                        TypeDefData tdEnum  = m_typeExt.ExtractEnumData(strEnum);

                        if (tdEnum != null)
                        {
                            m_HeaderAccess.AddTypeDefRow(tdEnum);
                        }
                    }
                    else if (m_Parser.IsStruct())
                    {
                        string     strStruct = m_Parser.GetStructure();
                        StructData sdData    = m_structExt.ExtractStructData(strStruct);

                        if (sdData != null)
                        {
                            m_HeaderAccess.AddStructRow(sdData);
                            m_HeaderAccess.AddFieldRows(sdData.Fields);
                        }//end if
                    }
                    else
                    {
                        m_Parser.MoveNextItem();
                    }//end if
                } while (!m_Parser.EndOfFile);

                TimeSpan tsElapsed = DateTime.Now.Subtract(datStartTime);

                //Once the parsing operation completes successfully, all the structures/unions extracted from the header files will be initially
                //queried and loaded in the form.
                rbQryDisplayAll.Checked = true;
                btnQuery_Click(btnQuery, EventArgs.Empty);

                this.Cursor = Cursors.Default;
                MessageBox.Show("Header File Parsing Completed!", "Complete", MessageBoxButtons.OK, MessageBoxIcon.Information);

                if (chbShowParseTime.Checked)
                {
                    MessageBox.Show("Parsing Time: " + tsElapsed.TotalSeconds.ToString() + " seconds");
                }
            }
            catch (Exception err)
            {
                this.Cursor = Cursors.Default;
                ErrorHandler.ShowErrorMessage(err, "Error in btnParse_Click function of frmCHeaderExtract form.");
            }
        }