Example #1
0
 /// <summary>
 /// Converts <see cref="IDiaEnumSymbols"/> container to <see cref="IEnumerable{IDiaSymbol}"/>.
 /// </summary>
 /// <param name="container">The container.</param>
 public static IEnumerable <IDiaSymbol> Enum(this IDiaEnumSymbols container)
 {
     foreach (IDiaSymbol symbol in container)
     {
         yield return(symbol);
     }
 }
Example #2
0
        public static ComPtr <IDiaSymbol> GetTypeSymbol(this IDiaSymbol moduleSym, string name)
        {
            IDiaEnumSymbols enumSymbols = null;

            moduleSym.findChildren(SymTagEnum.SymTagUDT, name, 1, out enumSymbols);
            using (ComPtr.Create(enumSymbols)) {
                if (enumSymbols.count > 0)
                {
                    return(ComPtr.Create(enumSymbols.Item(0)));
                }
            }

            moduleSym.findChildren(SymTagEnum.SymTagTypedef, name, 1, out enumSymbols);
            using (ComPtr.Create(enumSymbols)) {
                if (enumSymbols.count > 0)
                {
                    using (var item = ComPtr.Create(enumSymbols.Item(0))) {
                        return(ComPtr.Create(item.Object.type));
                    }
                }

                Debug.Fail("Type symbol '" + name + "' was not found.");
                throw new ArgumentException();
            }
        }
Example #3
0
        void PopulateDataTable(DataTable table, IDiaEnumSymbols symbols)
        {
            table.Rows.Clear();

            table.BeginLoadData();
            foreach (IDiaSymbol sym in symbols)
            {
                if (sym.length > 0 && !HasSymbol(sym.name))
                {
                    SymbolInfo info = new SymbolInfo();
                    info.Set(sym.name, "", sym.length, 0);
                    info.ProcessChildren(sym);

                    long totalPadding = info.CalcTotalPadding();

                    DataRow row        = table.NewRow();
                    string  symbolName = sym.name;
                    row["Symbol"]       = symbolName;
                    row["Size"]         = info.m_size;
                    row["Padding"]      = totalPadding;
                    row["Padding/Size"] = (double)totalPadding / info.m_size;
                    table.Rows.Add(row);

                    m_symbols.Add(info.m_name, info);
                }
            }
            table.EndLoadData();
        }
Example #4
0
        void FuncCollectSym(IDiaSymbol Detail, uint tag, String ModName, String BlockName)
        {
            IDiaEnumSymbols EnumSymbols     = null;
            IDiaSymbol      Symbol          = null;
            List <string>   Args            = new List <string>();
            uint            childrenFetched = 0;

            ForegroundColor = ConsoleColor.Green;

            if (Detail == null || string.IsNullOrWhiteSpace(Detail.name))
            {
                return;
            }

            //WriteLine($"{Detail.undecoratedName} ({Detail.name}) Length: {Detail.length} RVA: {Detail.targetRelativeVirtualAddress} VA: {Detail.targetVirtualAddress}");

            Detail.findChildren(SymTagEnum.SymTagNull, null, 0, out EnumSymbols);
            do
            {
                //EnumSymbols.Next(1, out Symbol, out childrenFetched);
                //if (Symbol == null || string.IsNullOrEmpty(Symbol.name))
                //    continue;

                Symbol = Detail;

                if (Symbol.type != null)
                {
                    Args.Add(Symbol.type.name);
                }
                //else
                //    WriteLine($"{Symbol.undecoratedName} ({Symbol.name}) @ {Symbol.virtualAddress:X} Length: {Symbol.length} ");
            } while (childrenFetched == 1);
        }
Example #5
0
        private IEnumerable <Symbol> CreateChildrenImpl(SymTagEnum symbolTagType, string symbolName, NameSearchOptions searchOptions)
        {
            IDiaEnumSymbols enumSymbols = null;

            try
            {
                _sym.findChildren(symbolTagType, symbolName, (uint)searchOptions, out enumSymbols);
                if (enumSymbols == null)
                {
                    yield break;
                }

                while (true)
                {
                    uint       celt = 0;
                    IDiaSymbol symbol;
                    enumSymbols.Next(1, out symbol, out celt);
                    if (celt != 1)
                    {
                        break;            //No more symbols
                    }
                    yield return(Symbol.Create(symbol));
                }
            }
            finally
            {
                if (enumSymbols != null)
                {
                    Marshal.ReleaseComObject(enumSymbols);
                }
            }
        }
Example #6
0
        public static dynamic xStructInfo(
            string PDBFile,
            string Struct,
            long vAddress  = 0,
            long[] memRead = null,
            Func <long, int, byte[]> GetMem            = null,
            Func <long, int, long[]> GetMemLong        = null,
            PropertyChangedEventHandler ExpandoChanged = null
            )
        {
            dynamic         Info        = null;
            IDiaSymbol      Master      = null;
            IDiaEnumSymbols EnumSymbols = null;
            IDiaSession     Session;
            uint            compileFetched = 0;

            var foo = new DiaSource();

            foo.loadDataFromPdb(PDBFile);
            foo.openSession(out Session);
            if (Session == null)
            {
                return(null);
            }

            Session.loadAddress = (ulong)vAddress;

            // 10 is regex
            Session.globalScope.findChildren(
                SymTagEnum.SymTagUDT
                ,
                Struct, 10, out EnumSymbols);
            do
            {
                EnumSymbols.Next(1, out Master, out compileFetched);
                if (Master == null)
                {
                    continue;
                }
#if DEBUGX
                Console.ForegroundColor = ConsoleColor.White;
                WriteLine($"Dumping Type [{Master.name}] Len [{Master.length}]");
#endif
                Info          = new ExpandoObject();
                Info.TypeName = Master.name;
                Info.Length   = Master.length;
                Info.vAddress = vAddress;

                //StructInfo.Add(Master.name, Info); // Tuple.Create<int, int>(0, (int)Master.length));
                xDumpStructs(Info, Master, Master.name, 0, vAddress, memRead, GetMem, GetMemLong, ExpandoChanged);

                if (ExpandoChanged != null)
                {
                    ((INotifyPropertyChanged)Info).PropertyChanged +=
                        new PropertyChangedEventHandler(ExpandoChanged);
                }
            } while (compileFetched == 1);

            return(Info);
        }
Example #7
0
        void ClassCollectSym(IDiaSymbol Detail)
        {
            IDiaEnumSymbols EnumSymbols     = null;
            IDiaSymbol      Symbol          = null;
            List <string>   Args            = new List <string>();
            uint            childrenFetched = 0;

            ForegroundColor = ConsoleColor.Yellow;

            if (Detail == null || string.IsNullOrWhiteSpace(Detail.name))
            {
                return;
            }

            WriteLine($"{Detail.undecoratedName} ({Detail.name}) Length: {Detail.length} RVA: {Detail.targetRelativeVirtualAddress} VA: {Detail.targetVirtualAddress}");

            Detail.findChildren(SymTagEnum.SymTagNull, null, 0, out EnumSymbols);
            do
            {
                EnumSymbols.Next(1, out Symbol, out childrenFetched);
                if (Symbol == null || string.IsNullOrEmpty(Symbol.name))
                {
                    continue;
                }

                if (Symbol.type != null)
                {
                    Args.Add(Symbol.type.name);
                }
                else
                {
                    WriteLine($"{Symbol.undecoratedName} ({Symbol.name}) @ {Symbol.virtualAddress:X} Length: {Symbol.length} ");
                }
            } while (childrenFetched == 1);
        }
Example #8
0
 public LeafMembers(IDiaEnumSymbols symbols)
 {
     _members = new List <LeafMember>();
     foreach (IDiaSymbol symbol in symbols)
     {
         _members.Add(new LeafMember(symbol));
     }
 }
Example #9
0
 public LeafMembers(IDiaEnumSymbols symbols)
 {
     _members = new List<LeafMember>();
     foreach (IDiaSymbol symbol in symbols)
     {
         _members.Add(new LeafMember(symbol));
     }
 }
Example #10
0
 public CStruct CollectStruct(IDiaEnumSymbols symbols)
 {
     LeafMembers allMembers = new LeafMembers(symbols);
     Columns columns = allMembers.CalculateColumns();
     columns.CalculateResetters();
     AnonymousStruct struc = columns.CollectStruct();
     struc.PostProcess();
     struc.SinglizeStructs();
     return (CStruct)struc.ToCType(_translator);
 }
Example #11
0
 public CUnion CollectUnion(IDiaEnumSymbols symbols)
 {
     LeafMembers allMembers = new LeafMembers(symbols);
     Columns columns = allMembers.CalculateColumns();
     columns.CalculateResetters();
     AnonymousUnion union = columns.CollectUnion();
     union.PostProcess();
     union.SinglizeStructs();
     return (CUnion)union.ToCType(_translator);
 }
Example #12
0
        public IList <SourceFileLocation> GetFunctions(string symbolFilterString)
        {
            if (_diaDataSource == null) // Silently return when DIA failed to load
            {
                return(new SourceFileLocation[0]);
            }

            IDiaEnumSymbols diaSymbols = FindFunctionsByRegex(symbolFilterString);

            return(GetSymbolNamesAndAddresses(diaSymbols).Select(ToSourceFileLocation).ToList());
        }
Example #13
0
        public CStruct CollectStruct(IDiaEnumSymbols symbols)
        {
            LeafMembers allMembers = new LeafMembers(symbols);
            Columns     columns    = allMembers.CalculateColumns();

            columns.CalculateResetters();
            AnonymousStruct struc = columns.CollectStruct();

            struc.PostProcess();
            struc.SinglizeStructs();
            return((CStruct)struc.ToCType(_translator));
        }
Example #14
0
        public CUnion CollectUnion(IDiaEnumSymbols symbols)
        {
            LeafMembers allMembers = new LeafMembers(symbols);
            Columns     columns    = allMembers.CalculateColumns();

            columns.CalculateResetters();
            AnonymousUnion union = columns.CollectUnion();

            union.PostProcess();
            union.SinglizeStructs();
            return((CUnion)union.ToCType(_translator));
        }
Example #15
0
        void PopulateDataTable(DataTable table, IDiaEnumSymbols symbols, BackgroundWorker LoadingWorker)
        {
            int TotalSymbolCount = symbols.count;
            int CurSymIndex      = 0;

            string msg = String.Format("Loading {0} symbols...", TotalSymbolCount);

            Console.WriteLine(msg);
            LoadingWorker?.ReportProgress(0, msg);

            System.Diagnostics.Stopwatch watch = new Stopwatch();
            watch.Start();

            table.BeginLoadData();
            foreach (IDiaSymbol sym in symbols)
            {
                if (sym.length > 0 && !HasSymbol(sym.name))
                {
                    CruncherSymbol info = new CruncherSymbol(sym.name, "", sym.length, 0);
                    info.ProcessChildren(sym);

                    long totalPadding = info.CalcTotalPadding();

                    DataRow row        = table.NewRow();
                    string  symbolName = sym.name;
                    row["Symbol"]       = symbolName;
                    row["Size"]         = info.Size;
                    row["Padding"]      = totalPadding;
                    row["Padding/Size"] = (double)totalPadding / info.Size;
                    table.Rows.Add(row);

                    m_SymbolMap.Add(info.Name, info);

                    // Report progress to loading bar
                    int percentProgress = (int)Math.Round((double)(100 * CurSymIndex++) / TotalSymbolCount);
                    percentProgress = Math.Max(Math.Min(percentProgress, 99), 1);
                    LoadingWorker?.ReportProgress(percentProgress, String.Format("Adding symbol {0} of {1}", CurSymIndex, TotalSymbolCount));
                }
            }
            table.EndLoadData();
            watch.Stop();

            // Format and display the TimeSpan value.
            TimeSpan ts          = watch.Elapsed;
            string   elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
                                                 ts.Hours, ts.Minutes, ts.Seconds,
                                                 ts.Milliseconds / 10);
            string CompleteMessage = String.Format("Finished processing {0} symbols in {1}", TotalSymbolCount, elapsedTime);

            Console.WriteLine(CompleteMessage);
            LoadingWorker?.ReportProgress(100, CompleteMessage);
        }
Example #16
0
        /// <summary>
        /// Perform full symbol walk scanning for a struct/member position and length
        ///
        /// TODO: make safe for type collisions in other pdb's
        /// </summary>
        /// <param name="PDBFile">d:\dev\symbols\ntkrnlmp.pdb\DD08DD42692B43F199A079D60E79D2171\ntkrnlmp.pdb</param>
        /// <param name="Struct">_EPROCESS</param>
        /// <param name="Member">Pcb.DirectoryTableBase</param>
        /// <returns>Tuple of Position & Length </returns>

        public Tuple <int, int> StructMemberInfo(string PDBFile, string Struct, string Member)
        {
            IDiaSession     Session;
            IDiaSymbol      Master         = null;
            IDiaEnumSymbols EnumSymbols    = null;
            uint            compileFetched = 0;

            var result = from symx in StructInfo
                         where symx.Key.EndsWith(Member)
                         select symx;

            if (result.Count() > 0)
            {
                return(result.First().Value);
            }

            var foo = new DiaSource();

            foo.loadDataFromPdb(PDBFile);
            foo.openSession(out Session);
            if (Session == null)
            {
                return(null);
            }

            Session.findChildren(Session.globalScope, SymTagEnum.SymTagNull, Struct, 0, out EnumSymbols);
            do
            {
                EnumSymbols.Next(1, out Master, out compileFetched);
                if (Master == null)
                {
                    continue;
                }
#if DEBUGX
                Console.ForegroundColor = ConsoleColor.White;
                WriteLine($"Dumping Type [{Master.name}] Len [{Master.length}]");
#endif
                if (!StructInfo.ContainsKey(Master.name))
                {
                    StructInfo.Add(Master.name, Tuple.Create <int, int>(0, (int)Master.length));
                }

                DumpStructs(Master, Master.name, Struct, 0);
            } while (compileFetched == 1);

            var resultx = (from symx in StructInfo
                           where symx.Key.EndsWith(Member)
                           select symx).FirstOrDefault();

            return(resultx.Value);
        }
Example #17
0
        public List <Tuple <String, ulong, ulong> > MatchSyms(String Match, String PDBFile, ulong LoadAddr = 0)
        {
            List <Tuple <String, ulong, ulong> > rv = new List <Tuple <string, ulong, ulong> >();
            IDiaSession     Session;
            IDiaEnumSymbols EnumSymbols    = null;
            IDiaSymbol      Master         = null;
            uint            compileFetched = 0;

            var foo = new DiaSource();

            foo.loadDataFromPdb(PDBFile);
            foo.openSession(out Session);
            if (Session == null)
            {
                return(rv);
            }
            // 10 is regex
            Session.globalScope.findChildren(SymTagEnum.SymTagNull, Match, 10, out EnumSymbols);

            if (Session == null)
            {
                return(rv);
            }

            Session.loadAddress = LoadAddr;

            var GlobalScope = Session.globalScope;

            var tot = EnumSymbols.count;

            do
            {
                EnumSymbols.Next(1, out Master, out compileFetched);
                if (Master == null)
                {
                    continue;
                }

                var len = Master.length;

                rv.Add(Tuple.Create <String, ulong, ulong>(Master.name, Master.virtualAddress, len));
#if DEBUGX
                ForegroundColor = ConsoleColor.White;
                WriteLine($"Name = [{Master.name}] VA = {Master.virtualAddress}");
#endif
            } while (compileFetched == 1);

            return(rv);
        }
Example #18
0
        public DiaFile(String pdbFile, String dllFile)
        {
            m_dsc = GetDiaSourceClass();
            string pdbPath = System.IO.Path.GetDirectoryName(pdbFile);

            // Open the PDB file, validating it matches the supplied DLL file
            DiaLoadCallback loadCallback = new DiaLoadCallback();

            try
            {
                m_dsc.loadDataForExe(dllFile, pdbPath, loadCallback);
            }
            catch (System.Exception diaEx)
            {
                // Provide additional diagnostics context and rethrow
                string       msg   = "ERROR from DIA loading PDB for specified DLL";
                COMException comEx = diaEx as COMException;
                if (comEx != null)
                {
                    if (Enum.IsDefined(typeof(DiaHResults), comEx.ErrorCode))
                    {
                        // This is a DIA-specific error code,
                        DiaHResults hr = (DiaHResults)comEx.ErrorCode;
                        msg += ": " + hr.ToString();

                        // Additional clarification for the common case of the DLL not matching the PDB
                        if (hr == DiaHResults.E_PDB_NOT_FOUND)
                        {
                            msg +=
                                " - The specified PDB file does not match the specified DLL file";
                        }
                    }
                }
                throw new ApplicationException(msg, diaEx);
            }

            // Save the path of the PDB file actually loaded
            Debug.Assert(loadCallback.LoadedPdbPath != null, "Didn't get PDB load callback");
            m_loadedPdbPath = loadCallback.LoadedPdbPath;

            // Also use DIA to get the debug directory entry in the DLL referring
            // to the PDB, and save it's timestamp comparison at runtime.
            m_debugTimestamp = loadCallback.DebugTimeDateStamp;
            Debug.Assert(m_debugTimestamp != 0, "Didn't find debug directory entry");

            m_dsc.openSession(out m_session);
            m_global      = new DiaSymbol(m_session.globalScope);
            m_publicsEnum = null;
        }
        private IDiaEnumSymbols FindFunctionsByRegex(string pattern)
        {
            IDiaEnumSymbols result = null;

            try
            {
                _diaSession.globalScope.findChildren(SymTagEnum.SymTagFunction, pattern, (uint)NameSearchOptions.NsfRegularExpression, out result);
            }
            catch (NotImplementedException)
            {
                // https://developercommunity.visualstudio.com/content/problem/4631/dia-sdk-still-doesnt-support-debugfastlink.html
                _logger.LogWarning("In order to get source locations for your tests, please ensure to generate *full* PDBs for your test executables.");
                _logger.LogWarning("Use linker option /DEBUG:FULL (VS2017) or /DEBUG (VS2015 and older) - do not use /DEBUG:FASTLINK!");
            }
            return(result);
        }
        private IDiaEnumSymbols FindFunctionsByRegex(string pattern)
        {
            IDiaEnumSymbols result = null;

            try
            {
                _diaSession.globalScope.findChildren(SymTagEnum.SymTagFunction, pattern, (uint)NameSearchOptions.NsfRegularExpression, out result);
            }
            catch (NotImplementedException)
            {
                // https://developercommunity.visualstudio.com/content/problem/4631/dia-sdk-still-doesnt-support-debugfastlink.html
                _logger.LogWarning(Resources.GenerateFullPDBMessage);
                _logger.LogWarning(Resources.UseLinkerOption);
            }
            return(result);
        }
Example #21
0
        /// <summary>
        /// Converts <see cref="IDiaEnumSymbols"/> container to <see cref="IEnumerable{IDiaSymbol}"/>.
        /// </summary>
        /// <param name="container">The container.</param>
        public static IEnumerable <IDiaSymbol> Enum(this IDiaEnumSymbols container)
        {
            IDiaSymbol[] tempSymbols = new IDiaSymbol[1];
            container.Reset();
            while (true)
            {
                uint count;

                container.Next((uint)tempSymbols.Length, tempSymbols, out count);
                if (count == 0)
                {
                    break;
                }
                yield return(tempSymbols[0]);
            }
        }
        /// From given symbol enumeration, extract name, section, offset and length
        private IList <NativeSourceFileLocation> GetSymbolNamesAndAddresses(IDiaEnumSymbols diaSymbols)
        {
            var locations = new List <NativeSourceFileLocation>();

            foreach (IDiaSymbol diaSymbol in diaSymbols)
            {
                locations.Add(new NativeSourceFileLocation()
                {
                    Symbol         = diaSymbol.name,
                    AddressSection = diaSymbol.addressSection,
                    AddressOffset  = diaSymbol.addressOffset,
                    Length         = (uint)diaSymbol.length
                });
            }
            return(locations);
        }
Example #23
0
    private DiaSymbol GetValidPublicSymbolEntry(String name)
    {
        IDiaEnumSymbols e = df.FindPublicSymbols(name);

        if (e.count != 1)
        {
            return(null);
        }
        else
        {
            IDiaSymbol s;
            UInt32     celt;

            e.Next(1, out s, out celt);
            return(new DiaSymbol(s));
        }
    }
Example #24
0
        /// <summary>
        /// Gets the stack frame locals.
        /// </summary>
        /// <param name="block">The block.</param>
        /// <param name="relativeAddress">The relative address or uint.MaxValue if only first children are desired.</param>
        /// <param name="variables">The variables.</param>
        /// <param name="frame">The frame.</param>
        /// <param name="module">The module.</param>
        /// <param name="arguments">if set to <c>true</c> only arguments will be returned.</param>
        private static void GetFrameLocals(IDiaSymbol block, uint relativeAddress, List <Variable> variables, StackFrame frame, Module module, bool arguments)
        {
            IEnumerable <IDiaSymbol> symbols;

            if (relativeAddress != uint.MaxValue)
            {
                IDiaEnumSymbols symbolsEnum = block.findChildrenExByRVA(SymTagEnum.Null, null, 0, relativeAddress);

                symbols = symbolsEnum.Enum();
            }
            else
            {
                symbols = block.GetChildren(SymTagEnum.Data);
            }

            foreach (var symbol in symbols)
            {
                SymTagEnum tag = symbol.symTag;

                if (tag == SymTagEnum.Data)
                {
                    DataKind symbolDataKind = symbol.dataKind;

                    if ((arguments && symbolDataKind != DataKind.Param) || symbol.locationType == LocationType.Null)
                    {
                        continue;
                    }
                }
                else if (tag != SymTagEnum.FunctionArgType || !arguments)
                {
                    continue;
                }

                CodeType codeType     = module.TypesById[symbol.typeId];
                ulong    address      = ResolveAddress(module.Process, symbol, frame.FrameContext);
                var      variableName = symbol.name;

                variables.Add(Variable.CreateNoCast(codeType, address, variableName, variableName));
            }
        }
Example #25
0
        public dynamic xStructInfo(string PDBFile, string Struct, long[] memRead = null)
        {
            dynamic         Info        = null;
            IDiaSymbol      Master      = null;
            IDiaEnumSymbols EnumSymbols = null;
            IDiaSession     Session;
            uint            compileFetched = 0;

            var foo = new DiaSource();

            foo.loadDataFromPdb(PDBFile);
            foo.openSession(out Session);
            if (Session == null)
            {
                return(null);
            }
            // 10 is regex
            Session.globalScope.findChildren(SymTagEnum.SymTagNull, Struct, 10, out EnumSymbols);
            do
            {
                EnumSymbols.Next(1, out Master, out compileFetched);
                if (Master == null)
                {
                    continue;
                }
#if DEBUGX
                Console.ForegroundColor = ConsoleColor.White;
                WriteLine($"Dumping Type [{Master.name}] Len [{Master.length}]");
#endif
                Info          = new ExpandoObject();
                Info.TypeName = Master.name;
                Info.Length   = Master.length;
                //StructInfo.Add(Master.name, Info); // Tuple.Create<int, int>(0, (int)Master.length));

                xDumpStructs(Info, Master, Master.name, 0, memRead);
            } while (compileFetched == 1);

            return(Info);
        }
Example #26
0
        void DumpStructs(IDiaSymbol Master, string preName, string Search, int CurrOffset)
        {
            IDiaSymbol      Sub            = null;
            IDiaEnumSymbols Enum2          = null;
            uint            compileFetched = 0;

            Master.findChildren(SymTagEnum.SymTagNull, null, 0, out Enum2);
            do
            {
                if (Enum2 == null)
                {
                    break;
                }

                Enum2.Next(1, out Sub, out compileFetched);
                if (Sub == null)
                {
                    continue;
                }

                var sType    = Sub.type;
                var typeName = sType.name;
                var currName = $"{preName}.{Sub.name}";
                int Pos      = CurrOffset + Sub.offset;

#if DEBUGX
                ForegroundColor = ConsoleColor.Cyan;
                WriteLine($"Pos = [{Pos}] Name = [{currName}] Len [{sType.length}], Type [{typeName}]");
#endif
                if (!StructInfo.ContainsKey(currName))
                {
                    StructInfo.Add(currName, Tuple.Create <int, int>(Pos, (int)sType.length));
                }
                DumpStructs(sType, currName, typeName, Pos);
            } while (compileFetched == 1);
        }
Example #27
0
    public DiaFile(String pdbFile, String dllFile)
    {
        m_dsc = new DiaSourceClass();
        string pdbPath = System.IO.Path.GetDirectoryName(pdbFile);

        // Open the PDB file, validating it matches the supplied DLL file
        DiaLoadCallback loadCallback = new DiaLoadCallback();
        try
        {
            m_dsc.loadDataForExe(dllFile, pdbPath, loadCallback);
        }
        catch (System.Exception diaEx)
        {
            // Provide additional diagnostics context and rethrow
            string msg = "ERROR from DIA loading PDB for specified DLL";
            COMException comEx = diaEx as COMException;
            if (comEx != null)
            {
                if (Enum.IsDefined(typeof(DiaHResults), comEx.ErrorCode))
                {
                    // This is a DIA-specific error code,
                    DiaHResults hr = (DiaHResults)comEx.ErrorCode;
                    msg += ": " + hr.ToString();

                    // Additional clarification for the common case of the DLL not matching the PDB
                    if (hr == DiaHResults.E_PDB_NOT_FOUND)
                    {
                        msg += " - The specified PDB file does not match the specified DLL file";
                    }
                }
            }
            throw new ApplicationException(msg, diaEx);
        }

        // Save the path of the PDB file actually loaded
        Debug.Assert(loadCallback.LoadedPdbPath != null, "Didn't get PDB load callback");
        m_loadedPdbPath = loadCallback.LoadedPdbPath;

        // Also use DIA to get the debug directory entry in the DLL referring
        // to the PDB, and save it's timestamp comparison at runtime.
        m_debugTimestamp = loadCallback.DebugTimeDateStamp;
        Debug.Assert(m_debugTimestamp != 0, "Didn't find debug directory entry");

        m_dsc.openSession(out m_session);
        m_global = new DiaSymbol(m_session.globalScope);
        m_publicsEnum = null;
    }
Example #28
0
        private bool ProcessSymbol(Symbol s)
        {
            _accessBlock.Clear();
            List <string>         variablesBlock = new List <string>(); // used for global variables
            List <FunctionRecord> entries        = new List <FunctionRecord>();
            string structureName = s.Name;

            // unnamed is a special case and I want the function names to be in the same form as the others i.e. _FUNCTION_NAME
            if (structureName.StartsWith("<unnamed-"))
            {
                structureName = structureName.Replace("<unnamed-", "_UNNAMED_");
                structureName = structureName.TrimEnd(new char[] { '>' });
            }
            // just make sure it hasn't been done already
            if (_doneList.Contains(structureName))
            {
                return(true);
            }
            // create the top of the source file
            AddToBody("#region " + structureName, 1);
            variablesBlock.Add("private Byte[] _StructureData;");
            variablesBlock.Add("private int _BufferOffset;");
            // start a new manifest file
            CreateNewManifest((int)s.Length);
            // get the symbol children
            IDiaEnumSymbols children = s.TryChildren();
            // process each child
            FunctionRecord fr;

            Debug.WriteLine("PROCESSING: " + structureName);
            foreach (IDiaSymbol child in children)
            {
                fr = ProcessChild(child);
                entries.Add(fr);
            }
            foreach (FunctionRecord entry in entries)
            {
                if (_enumList.Contains(entry.symbolType))
                {
                    entry.isFoundInEnumList = true;
                }
                if (!entry.isBuiltinType && structureName != entry.type && !_doneList.Contains(entry.type) && !_todoList.Contains(entry.type) && !entry.type.StartsWith("_UNNAMED"))
                {
                    if (entry.isArray)
                    {
                        _todoList.Add(entry.arrayType);
                        Debug.WriteLine("Adding: " + entry.arrayType);
                    }
                    else
                    {
                        _todoList.Add(entry.type);
                        Debug.WriteLine("Adding: " + entry.type);
                    }
                }
            }
            string[] manifestParts = TidyManifest(structureName);
            // write out the body
            AddToBody(" ", 0);
            AddToBody("public class " + structureName, 1);
            AddToBody("{", 1);
            foreach (string a in variablesBlock)
            {
                AddToBody(a, 2);
            }
            AddToBody("public " + structureName + "(Byte[] Buffer, int PartitionOffset)", 2);
            AddToBody("{", 2);
            AddToBody("_StructureData = Buffer;", 3);
            AddToBody("_BufferOffset = PartitionOffset;", 3);
            AddToBody("}", 2);
            AddToBody("public int MxStructureSize { get { return " + s.Length.ToString() + "; } }", 2);

            AddToBody("public string manifest", 2);
            AddToBody("{", 2);
            AddToBody("get", 3);
            AddToBody("{", 3);
            AddToBody("return @\"(", 4);
            foreach (string line in manifestParts)
            {
                AddToBody(line, 4);
            }
            AddToBody(")\";", 4);
            AddToBody("}", 3);
            AddToBody("}", 2);

            foreach (String a in _accessBlock)
            {
                AddToBody(a, 2);
            }

            AddToBody("}", 1);
            AddToBody("#endregion", 1);

            _doneList.Add(structureName);
            return(true);
        }
Example #29
0
 void IDiaSymbol.findChildren(SymTagEnum symTag, string name, uint compareFlags, out IDiaEnumSymbols ppResult)
 {
     ppResult = new EnumSymbols(CV, EnumSymType.Sym, Master);
     return;
 }
Example #30
0
 public void Clone(out IDiaEnumSymbols ppenum)
 {
     ppenum = new EnumSymbols(CV, eType, Current) as IDiaEnumSymbols;
     return;
 }
Example #31
0
        void IDiaSession.findChildren(IDiaSymbol parent, SymTagEnum symTag, string name, uint compareFlags, out IDiaEnumSymbols ppResult)
        {
            dynamic typ = null;

            if (!Dia3.StructCache.ContainsKey(name))
            {
                var json      = SymAPI.TypeDef(name, CV);
                var converter = new Newtonsoft.Json.Converters.ExpandoObjectConverter();
                var obj       = JsonConvert.DeserializeObject <List <ExpandoObject> >(json.Result, converter);
                // we access just the first object back
                Dia3.StructCache.TryAdd(name, obj.First());
            }
            Dia3.StructCache.TryGetValue(name, out typ);

            ppResult = new EnumSymbols(CV, EnumSymType.Sym, typ);
            return;
        }
Example #32
0
 public void findChildren(SymTagEnum symTag, string name, uint compareFlags, out IDiaEnumSymbols ppResult)
 {
     throw new NotImplementedException();
 }
Example #33
0
        void PopulateDataTable(DataTable table, IDiaEnumSymbols symbols)
        {
            ulong cacheLineSize = GetCacheLineSize();
            table.Rows.Clear();

            foreach (IDiaSymbol sym in symbols)
            {
                if (sym.length > 0 && !HasSymbol(sym.name))
                {
                    SymbolInfo info = new SymbolInfo();
                    info.Set(sym.name, "", sym.length, 0);
                    info.ProcessChildren(sym);

                    long totalPadding = info.CalcTotalPadding();

                    DataRow row = table.NewRow();
                    string symbolName = sym.name;
                    row["Symbol"] = symbolName;
                    row["Size"] = info.m_size;
                    row["Padding"] = totalPadding;
                    row["Padding/Size"] = (double)totalPadding / info.m_size;
                    table.Rows.Add(row);

                    m_symbols.Add(info.m_name, info);
                }
            }
        }
 /// From given symbol enumeration, extract name, section, offset and length
 private IList<NativeSourceFileLocation> GetSymbolNamesAndAddresses(IDiaEnumSymbols diaSymbols)
 {
     var locations = new List<NativeSourceFileLocation>();
     foreach (IDiaSymbol diaSymbol in diaSymbols)
     {
         locations.Add(new NativeSourceFileLocation()
         {
             Symbol = diaSymbol.name,
             AddressSection = diaSymbol.addressSection,
             AddressOffset = diaSymbol.addressOffset,
             Length = (uint)diaSymbol.length
         });
     }
     return locations;
 }
Example #35
0
        private IDiaSymbol GetMethodSymbol(IDiaSymbol typeSymbol, string methodName)
        {
            ValidateArg.NotNull(typeSymbol, "typeSymbol");
            ValidateArg.NotNullOrEmpty(methodName, "methodName");

            IDiaEnumSymbols enumSymbols  = null;
            IDiaSymbol      methodSymbol = null;
            Dictionary <string, IDiaSymbol> methodSymbolsForType;

            try
            {
                typeSymbol.GetName(out string symbolName);
                if (this.methodSymbols.ContainsKey(symbolName))
                {
                    methodSymbolsForType = this.methodSymbols[symbolName];
                    if (methodSymbolsForType.ContainsKey(methodName))
                    {
                        return(methodSymbolsForType[methodName]);
                    }
                }
                else
                {
                    methodSymbolsForType           = new Dictionary <string, IDiaSymbol>();
                    this.methodSymbols[symbolName] = methodSymbolsForType;
                }

                typeSymbol.FindChildren(SymTagEnum.SymTagFunction, methodName, 0, out enumSymbols);

                enumSymbols.GetNext(1, out methodSymbol, out uint celtFetched);

#if DEBUG
                if (methodSymbol == null)
                {
                    IDiaEnumSymbols enumAllSymbols = null;
                    try
                    {
                        typeSymbol.FindChildren(SymTagEnum.SymTagFunction, null, 0, out enumAllSymbols);
                        List <string> children = new List <string>();

                        while (true)
                        {
                            enumAllSymbols.GetNext(1, out IDiaSymbol childSymbol, out uint fetchedCount);
                            if (fetchedCount == 0 || childSymbol == null)
                            {
                                break;
                            }

                            childSymbol.GetName(out string childSymbolName);
                            children.Add(childSymbolName);
                            ReleaseComObject(ref childSymbol);
                        }

                        Debug.Assert(children.Count > 0);
                    }
                    finally
                    {
                        ReleaseComObject(ref enumAllSymbols);
                    }
                }
#endif
            }
            finally
            {
                ReleaseComObject(ref enumSymbols);
            }

            if (methodSymbol != null)
            {
                methodSymbolsForType[methodName] = methodSymbol;
            }

            return(methodSymbol);
        }
Example #36
0
        private IDiaSymbol GetTypeSymbol(string typeName, SymTagEnum symTag)
        {
            ValidateArg.NotNullOrEmpty(typeName, "typeName");

            IDiaEnumSymbols enumSymbols = null;
            IDiaSymbol      typeSymbol  = null;
            IDiaSymbol      global      = null;

            try
            {
                typeName = typeName.Replace('+', '.');
                if (this.typeSymbols.ContainsKey(typeName))
                {
                    return(this.typeSymbols[typeName]);
                }

                this.session.GetGlobalScope(out global);
                global.FindChildren(symTag, typeName, 0, out enumSymbols);

                enumSymbols.GetNext(1, out typeSymbol, out uint celt);

#if DEBUG
                if (typeSymbol == null)
                {
                    IDiaEnumSymbols enumAllSymbols = null;
                    try
                    {
                        global.FindChildren(symTag, null, 0, out enumAllSymbols);
                        List <string> children = new List <string>();

                        while (true)
                        {
                            enumAllSymbols.GetNext(1, out IDiaSymbol childSymbol, out uint fetchedCount);
                            if (fetchedCount == 0 || childSymbol == null)
                            {
                                break;
                            }

                            childSymbol.GetName(out var childSymbolName);
                            children.Add(childSymbolName);
                            ReleaseComObject(ref childSymbol);
                        }

                        Debug.Assert(children.Count > 0);
                    }
                    finally
                    {
                        ReleaseComObject(ref enumAllSymbols);
                    }
                }
#endif
            }
            finally
            {
                ReleaseComObject(ref enumSymbols);
                ReleaseComObject(ref global);
            }

            if (typeSymbol != null)
            {
                this.typeSymbols[typeName] = typeSymbol;
            }

            return(typeSymbol);
        }
Example #37
0
 public CUnion TranslateUnion2(IDiaEnumSymbols symbols)
 {
     return new Collector(this).CollectUnion(symbols);
 }
Example #38
0
 public CStruct TranslateStruct2(IDiaEnumSymbols symbols)
 {
     return new Collector(this).CollectStruct(symbols);
 }