Example #1
0
        internal static void VerifyModuleMvid(int generation, MetadataReader previousReader, MetadataReader currentReader)
        {
            var previousModule = previousReader.GetModuleDefinition();
            var currentModule  = currentReader.GetModuleDefinition();

            Assert.Equal(previousReader.GetGuid(previousModule.Mvid), currentReader.GetGuid(currentModule.Mvid));

            Assert.Equal(generation - 1, previousModule.Generation);
            Assert.Equal(generation, currentModule.Generation);

            if (generation == 1)
            {
                Assert.True(previousModule.GenerationId.IsNil);
                Assert.True(previousModule.BaseGenerationId.IsNil);

                Assert.False(currentModule.GenerationId.IsNil);
                Assert.True(currentModule.BaseGenerationId.IsNil);
            }
            else
            {
                Assert.False(currentModule.GenerationId.IsNil);
                Assert.False(currentModule.BaseGenerationId.IsNil);

                Assert.Equal(previousReader.GetGuid(previousModule.GenerationId), currentReader.GetGuid(currentModule.BaseGenerationId));
            }

            Assert.NotEqual(default(Guid), currentReader.GetGuid(currentModule.GenerationId));
        }
Example #2
0
        public static void ReadPdbDocuments(string pdbPath)
        {
            // Open Portable PDB file
            using var fs = new FileStream(pdbPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            using MetadataReaderProvider provider = MetadataReaderProvider.FromPortablePdbStream(fs);

            MetadataReader reader = provider.GetMetadataReader();

            // Display information about documents in each MethodDebugInformation table entry
            foreach (MethodDebugInformationHandle h in reader.MethodDebugInformation)
            {
                MethodDebugInformation mdi = reader.GetMethodDebugInformation(h);

                if (mdi.Document.IsNil)
                {
                    continue;
                }

                int token = MetadataTokens.GetToken(h);
                Console.WriteLine($"MethodDebugInformation 0x{token.ToString("X")}");

                Document doc = reader.GetDocument(mdi.Document);
                Console.WriteLine($"File: {ReadDocumentPath(reader, doc)}");
                Guid guidLang = reader.GetGuid(doc.Language);
                Console.WriteLine($"Language: {guidLang}");
                Guid guidHashAlg = reader.GetGuid(doc.HashAlgorithm);
                Console.WriteLine($"Hash algorithm: {guidHashAlg}");
                Console.WriteLine();
            }
        }
Example #3
0
        private unsafe static MetadataBlock GetMetadataBlock(IntPtr ptr, uint size)
        {
            var reader          = new MetadataReader((byte *)ptr, (int)size);
            var moduleDef       = reader.GetModuleDefinition();
            var moduleVersionId = reader.GetGuid(moduleDef.Mvid);
            var generationId    = reader.GetGuid(moduleDef.GenerationId);

            return(new MetadataBlock(moduleVersionId, generationId, ptr, (int)size));
        }
        private IReadOnlyList <SourceLinkMap> GetSourceLinkInformation()
        {
            var sl = (from cdi in _reader.CustomDebugInformation
                      let cd = _reader.GetCustomDebugInformation(cdi)
                               let kind = _reader.GetGuid(cd.Kind)
                                          where kind == SourceLinkGuid
                                          let bl = _reader.GetBlobBytes(cd.Value)
                                                   select Encoding.UTF8.GetString(bl))
                     .FirstOrDefault();

            if (sl != null)
            {
                try
                {
                    /* Some tools, like GitLink generate incorrectly escaped JSON:
                     *
                     * {
                     * "documents": {
                     *  "C:\projects\cefsharp\*": "https://raw.github.com/CefSharp/CefSharp/4f88ad11416e93dde4b52216800efd42ba3b9c8a/*"
                     * }
                     * }
                     *
                     * Catch the exception and try to fix the key
                     */
                    JObject?jobj = null;
                    try
                    {
                        jobj = JObject.Parse(sl);
                    }
                    catch (JsonReaderException e) when(e.Path == "documents")
                    {
                        sl   = sl.Replace(@"\", @"\\");
                        jobj = JObject.Parse(sl);
                    }

                    var docs = (JObject)jobj["documents"];

                    var slis = (from prop in docs.Properties()
                                select new SourceLinkMap
                    {
                        Base = prop.Name.Replace(@"\", @"/"),             // use forward slashes for the url,
                        Location = prop.Value.Value <string>()
                    })
                               .ToList();

                    return(slis);
                }
                catch (JsonReaderException jse)
                {
                    throw new InvalidDataException("SourceLink data could not be parsed", jse);
                }
            }

            return(Array.Empty <SourceLinkMap>());
        }
            private static bool TryGetCustomDebugInformation(
                MetadataReader reader,
                EntityHandle handle,
                Guid kind,
                out CustomDebugInformation customDebugInfo
                )
            {
                var foundAny = false;

                customDebugInfo = default;
                foreach (var infoHandle in reader.GetCustomDebugInformation(handle))
                {
                    var info = reader.GetCustomDebugInformation(infoHandle);
                    var id   = reader.GetGuid(info.Kind);
                    if (id == kind)
                    {
                        if (foundAny)
                        {
                            throw new BadImageFormatException();
                        }

                        customDebugInfo = info;
                        foundAny        = true;
                    }
                }

                return(foundAny);
            }
Example #6
0
 private void CollectMethods(MetadataReader reader)
 {
     foreach (var mh in reader.MethodDebugInformation)
     {
         if (mh.IsNil)
         {
             continue;
         }
         var mdbg = reader.GetMethodDebugInformation(mh);
         if (mdbg.Document.IsNil)
         {
             continue;
         }
         // TODO: maybe we should add more error-checking here...
         var doc      = reader.GetDocument(mdbg.Document);
         var mdh      = mh.ToDefinitionHandle();
         var token    = reader.GetToken(mdh);
         var language = reader.GetGuid(doc.Language);
         // Note that we're lying here by specifying "cpp" as the language when it is C# in reality
         // (this is so we get some syntax-highlighting in Sourcetrail)
         var languageName = language == SymLanguageType.CSharp ? "cpp"
             : language == SymLanguageType.Basic ? "basic" : "c";
         var method = new PdbMethod(token, reader.GetString(doc.Name), languageName);
         foreach (var sph in mdbg.GetSequencePoints())
         {
             if (sph.IsHidden)
             {
                 continue;
             }
             method.AddSequence(sph.Offset, sph.StartLine, sph.StartColumn, sph.EndLine, sph.EndColumn);
         }
         methodsByToken[token] = method;
     }
 }
Example #7
0
 public static ImmutableArray <byte> GetSourceLinkBlob(this MetadataReader reader)
 {
     return((from handle in reader.CustomDebugInformation
             let cdi = reader.GetCustomDebugInformation(handle)
                       where reader.GetGuid(cdi.Kind) == PortableCustomDebugInfoKinds.SourceLink
                       select reader.GetBlobContent(cdi.Value)).Single());
 }
Example #8
0
        public static string GetPDBFileName(string assemblyFile, NuGetFramework framework, string runtimeIdentifier)
        {
            if (IsTargetOsWindows(runtimeIdentifier))
            {
                return(Path.GetFileName(Path.ChangeExtension(assemblyFile, "ni.pdb")));
            }

            if (IsTargetOsLinux(runtimeIdentifier))
            {
                if (framework.Version.Major >= 6)
                {
                    return(Path.GetFileName(Path.ChangeExtension(assemblyFile, "ni.r2rmap")));
                }

                // Legacy perfmap file naming prior to .NET 6
                using (FileStream fs = new FileStream(assemblyFile, FileMode.Open, FileAccess.Read))
                {
                    PEReader       pereader = new PEReader(fs);
                    MetadataReader mdReader = pereader.GetMetadataReader();
                    Guid           mvid     = mdReader.GetGuid(mdReader.GetModuleDefinition().Mvid);

                    return(Path.GetFileName(Path.ChangeExtension(assemblyFile, "ni.{" + mvid + "}.map")));
                }
            }

            return(null);
        }
Example #9
0
        /// <summary>
        /// Unpacks all files stored in a PortablePDB meta-data. The key in the dictionary is the location of a source file
        /// on the build machine. The value is the content of the source file itself.
        /// The function will throw an exception if PortablePDB file is not found or anything else went wrong.
        /// </summary>
        /// <param name="pdbFilePath">Path to PortablePDB file to load source files from.</param>
        public static Dictionary <string, CompressedSourceFile> GetEmbeddedFiles(string pdbFilePath)
        {
            Dictionary <string, CompressedSourceFile> embeddedFiles = new Dictionary <string, CompressedSourceFile>();

            using (FileStream stream = File.OpenRead(pdbFilePath))
                using (MetadataReaderProvider metadataReaderProvider = MetadataReaderProvider.FromPortablePdbStream(stream))
                {
                    MetadataReader metadataReader = metadataReaderProvider.GetMetadataReader();
                    CustomDebugInformationHandleCollection customDebugInformationHandles = metadataReader.CustomDebugInformation;
                    foreach (var customDebugInformationHandle in customDebugInformationHandles)
                    {
                        CustomDebugInformation customDebugInformation = metadataReader.GetCustomDebugInformation(customDebugInformationHandle);
                        if (metadataReader.GetGuid(customDebugInformation.Kind) == EmbeddedSource)
                        {
                            byte[] embeddedSource             = metadataReader.GetBlobBytes(customDebugInformation.Value);
                            Int32  uncompressedSourceFileSize = BitConverter.ToInt32(embeddedSource, 0);
                            if (uncompressedSourceFileSize != 0)
                            {
                                Document document       = metadataReader.GetDocument((DocumentHandle)customDebugInformation.Parent);
                                string   sourceFileName = System.IO.Path.GetFullPath(metadataReader.GetString(document.Name));
                                embeddedFiles.Add(sourceFileName, new CompressedSourceFile(embeddedSource));
                            }
                        }
                    }
                }
            return(embeddedFiles);
        }
Example #10
0
 public static BlobReader GetSingleBlob(Guid infoGuid, MetadataReader pdbReader)
 {
     return((from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition)
             let cdi = pdbReader.GetCustomDebugInformation(cdiHandle)
                       where pdbReader.GetGuid(cdi.Kind) == infoGuid
                       select pdbReader.GetBlobReader(cdi.Value)).Single());
 }
            static CustomDebugInformationKind GetKind(MetadataReader metadata, GuidHandle h)
            {
                if (h.IsNil)
                {
                    return(CustomDebugInformationKind.None);
                }
                var guid = metadata.GetGuid(h);

                if (KnownGuids.StateMachineHoistedLocalScopes == guid)
                {
                    return(CustomDebugInformationKind.StateMachineHoistedLocalScopes);
                }
                if (KnownGuids.DynamicLocalVariables == guid)
                {
                    return(CustomDebugInformationKind.StateMachineHoistedLocalScopes);
                }
                if (KnownGuids.DefaultNamespaces == guid)
                {
                    return(CustomDebugInformationKind.StateMachineHoistedLocalScopes);
                }
                if (KnownGuids.EditAndContinueLocalSlotMap == guid)
                {
                    return(CustomDebugInformationKind.EditAndContinueLocalSlotMap);
                }
                if (KnownGuids.EditAndContinueLambdaAndClosureMap == guid)
                {
                    return(CustomDebugInformationKind.EditAndContinueLambdaAndClosureMap);
                }
                if (KnownGuids.EmbeddedSource == guid)
                {
                    return(CustomDebugInformationKind.EmbeddedSource);
                }
                if (KnownGuids.SourceLink == guid)
                {
                    return(CustomDebugInformationKind.SourceLink);
                }
                if (KnownGuids.MethodSteppingInformation == guid)
                {
                    return(CustomDebugInformationKind.MethodSteppingInformation);
                }
                if (KnownGuids.CompilationOptions == guid)
                {
                    return(CustomDebugInformationKind.CompilationOptions);
                }
                if (KnownGuids.CompilationMetadataReferences == guid)
                {
                    return(CustomDebugInformationKind.CompilationMetadataReferences);
                }
                if (KnownGuids.TupleElementNames == guid)
                {
                    return(CustomDebugInformationKind.TupleElementNames);
                }
                if (KnownGuids.TypeDefinitionDocuments == guid)
                {
                    return(CustomDebugInformationKind.TypeDefinitionDocuments);
                }

                return(CustomDebugInformationKind.Unknown);
            }
Example #12
0
 private static unsafe bool TryGetMetadataBlock(IntPtr ptr, uint size, out MetadataBlock block)
 {
     try
     {
         var reader          = new MetadataReader((byte *)ptr, (int)size);
         var moduleDef       = reader.GetModuleDefinition();
         var moduleVersionId = reader.GetGuid(moduleDef.Mvid);
         var generationId    = reader.GetGuid(moduleDef.GenerationId);
         block = new MetadataBlock(moduleVersionId, generationId, ptr, (int)size);
         return(true);
     }
     catch (BadImageFormatException)
     {
         block = default;
         return(false);
     }
 }
Example #13
0
        private static bool TryMapPortablePdb(Module module, out MetadataReaderProvider metadataReaderProvider)
        {
            metadataReaderProvider = null;
            MetadataReader rd = null;

            try
            {
                metadataReaderProvider = GetMetadataReaderProvider(module);
                rd = metadataReaderProvider?.GetMetadataReader();
            }
            catch (BadImageFormatException ex) when(ex.Message == "Invalid COR20 header signature.")
            {
                TraceSourceLink("no portable PDB found: " + module.FullyQualifiedName);
                // todo figure out a better way to detect if PDB is portable or classic
                // https://github.com/dotnet/corefx/blob/06b1365d9881ed26a921490d7edd2d4e4de35565/src/System.Reflection.Metadata/src/System/Reflection/Metadata/MetadataReader.cs#L185
            }
            if (rd == null)
            {
                metadataReaderProvider?.Dispose();
                metadataReaderProvider = null;
                return(false);
            }

            TraceSourceLink("found portable PDB for: " + module.FullyQualifiedName);

            // https://github.com/dotnet/symreader-portable/blob/d27c08d6015c4716ced790e34233c0219773ab10/src/Microsoft.DiaSymReader.PortablePdb/Utilities/MetadataUtilities.cs
            var sourceLinkHandles = rd
                                    .GetCustomDebugInformation(EntityHandle.ModuleDefinition)
                                    .Where(r => !r.IsNil)
                                    .Select(rd.GetCustomDebugInformation)
                                    .Where(cdi => !cdi.Value.IsNil && rd.GetGuid(cdi.Kind) == SourceLinkId)
                                    .ToList();

            if (sourceLinkHandles.Count == 0)
            {
                metadataReaderProvider?.Dispose();
                metadataReaderProvider = null;
                return(false);
            }
            var sourceLinkHandle = sourceLinkHandles.First();
            var sourceLink       = SourceLink.Deserialize(rd.GetBlobBytes(sourceLinkHandle.Value));

            var hinstance = (long)Marshal.GetHINSTANCE(module);

            foreach (var dh in rd.Documents)
            {
                if (dh.IsNil)
                {
                    continue;
                }
                var doc = rd.GetDocument(dh);

                var file = rd.GetString(doc.Name);
                SourceMappedPaths[Tuple.Create(hinstance, file)] = sourceLink.GetUrl(file);
            }

            return(true);
        }
Example #14
0
        /// <exception cref="BadImageFormatException">Invalid data format.</exception>
        private static void ReadMethodCustomDebugInformation(
            MetadataReader reader,
            MethodDefinitionHandle methodHandle,
            out ImmutableArray <HoistedLocalScopeRecord> hoistedLocalScopes,
            out string defaultNamespace)
        {
            hoistedLocalScopes = ImmutableArray <HoistedLocalScopeRecord> .Empty;

            foreach (var infoHandle in reader.GetCustomDebugInformation(methodHandle))
            {
                var info = reader.GetCustomDebugInformation(infoHandle);
                var id   = reader.GetGuid(info.Kind);
                if (id == PortableCustomDebugInfoKinds.StateMachineHoistedLocalScopes)
                {
                    // only single CDIof this kind is allowed on a method:
                    if (!hoistedLocalScopes.IsEmpty)
                    {
                        throw new BadImageFormatException();
                    }

                    hoistedLocalScopes = DecodeHoistedLocalScopes(reader.GetBlobReader(info.Value));
                }
            }

            // TODO: consider looking this up once per module (not for every method)
            defaultNamespace = null;
            foreach (var infoHandle in reader.GetCustomDebugInformation(EntityHandle.ModuleDefinition))
            {
                var info = reader.GetCustomDebugInformation(infoHandle);
                var id   = reader.GetGuid(info.Kind);
                if (id == PortableCustomDebugInfoKinds.DefaultNamespace)
                {
                    // only single CDI of this kind is allowed on the module:
                    if (defaultNamespace != null)
                    {
                        throw new BadImageFormatException();
                    }

                    var valueReader = reader.GetBlobReader(info.Value);
                    defaultNamespace = valueReader.ReadUTF8(valueReader.Length);
                }
            }

            defaultNamespace = defaultNamespace ?? "";
        }
Example #15
0
 public static bool IsEmbedded(MetadataReader mr, DocumentHandle dh)
 {
     foreach (var cdih in mr.GetCustomDebugInformation(dh))
     {
         var cdi = mr.GetCustomDebugInformation(cdih);
         if (mr.GetGuid(cdi.Kind) == EmbeddedSourceId)
         {
             return(true);
         }
     }
     return(false);
 }
Example #16
0
        public ImmutableArray <SourceDocument> FindSourceDocuments(ISymbol symbol)
        {
            var documentHandles = SymbolSourceDocumentFinder.FindDocumentHandles(symbol, _dllReader, _pdbReader);

            using var _ = ArrayBuilder <SourceDocument> .GetInstance(out var sourceDocuments);

            foreach (var handle in documentHandles)
            {
                var document = _pdbReader.GetDocument(handle);
                var filePath = _pdbReader.GetString(document.Name);

                var hashAlgorithmGuid = _pdbReader.GetGuid(document.HashAlgorithm);
                var hashAlgorithm     = SourceHashAlgorithms.GetSourceHashAlgorithm(hashAlgorithmGuid);
                var checksum          = _pdbReader.GetBlobContent(document.Hash);

                var embeddedText = TryGetEmbeddedSourceText(handle);

                sourceDocuments.Add(new SourceDocument(filePath, hashAlgorithm, checksum, embeddedText));
            }

            return(sourceDocuments.ToImmutable());
        }
        private byte[]? GetSourceLinkBytes()
        {
            if (_reader == null)
            {
                return(null);
            }
            var blobh = default(BlobHandle);

            foreach (var cdih in _reader.GetCustomDebugInformation(EntityHandle.ModuleDefinition))
            {
                var cdi = _reader.GetCustomDebugInformation(cdih);
                if (_reader.GetGuid(cdi.Kind) == SourceLinkId)
                {
                    blobh = cdi.Value;
                }
            }
            if (blobh.IsNil)
            {
                return(Array.Empty <byte>());
            }
            return(_reader.GetBlobBytes(blobh));
        }
Example #18
0
        internal static string GetVisualBasicDefaultNamespace(MetadataReader reader)
        {
            foreach (var cdiHandle in reader.GetCustomDebugInformation(Handle.ModuleDefinition))
            {
                var cdi = reader.GetCustomDebugInformation(cdiHandle);
                if (reader.GetGuid(cdi.Kind) == VbDefaultNamespaceId)
                {
                    return(reader.GetStringUTF8(cdi.Value));
                }
            }

            return(null);
        }
Example #19
0
        internal static BlobHandle GetCustomDebugInformation(this MetadataReader reader, EntityHandle parent, Guid kind)
        {
            foreach (var cdiHandle in reader.GetCustomDebugInformation(parent))
            {
                var cdi = reader.GetCustomDebugInformation(cdiHandle);
                if (reader.GetGuid(cdi.Kind) == kind)
                {
                    // return the first record
                    return(cdi.Value);
                }
            }

            return(default);
Example #20
0
        /// <summary>
        /// Given a path to an assembly, returns its MVID (Module Version ID).
        /// May throw.
        /// </summary>
        /// <exception cref="IOException">If the file at <paramref name="filePath"/> does not exist or cannot be accessed.</exception>
        /// <exception cref="BadImageFormatException">If the file is not an assembly or is somehow corrupted.</exception>
        public static Guid ReadMvid(string filePath)
        {
            Debug.Assert(filePath != null);
            Debug.Assert(PathUtilities.IsAbsolute(filePath));

            using (PEReader reader = new PEReader(FileUtilities.OpenRead(filePath)))
            {
                MetadataReader metadataReader = reader.GetMetadataReader();
                GuidHandle     mvidHandle     = metadataReader.GetModuleDefinition().Mvid;
                Guid           fileMvid       = metadataReader.GetGuid(mvidHandle);

                return(fileMvid);
            }
        }
        private BlobReader GetCustomDebugInformationBlobReader(Guid infoGuid)
        {
            var blobs = from cdiHandle in _metadataReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition)
                        let cdi = _metadataReader.GetCustomDebugInformation(cdiHandle)
                                  where _metadataReader.GetGuid(cdi.Kind) == infoGuid
                                  select _metadataReader.GetBlobReader(cdi.Value);

            if (blobs.Any())
            {
                return(blobs.Single());
            }

            throw new InvalidDataException($"No blob found for {infoGuid}");
        }
Example #22
0
        /// <exception cref="BadImageFormatException">Invalid data format.</exception>
        private static ImmutableArray <bool> ReadDynamicCustomDebugInformation(MetadataReader reader, EntityHandle variableOrConstantHandle)
        {
            foreach (var infoHandle in reader.GetCustomDebugInformation(variableOrConstantHandle))
            {
                var info = reader.GetCustomDebugInformation(infoHandle);
                var id   = reader.GetGuid(info.Kind);
                if (id == PortableCustomDebugInfoKinds.DynamicLocalVariables)
                {
                    return(DecodeDynamicFlags(reader.GetBlobReader(info.Value)));
                }
            }

            return(default(ImmutableArray <bool>));
        }
        private IReadOnlyList <SourceLinkMap> GetSourceLinkInformation()
        {
            var sl = (from cdi in _reader.CustomDebugInformation
                      let cd = _reader.GetCustomDebugInformation(cdi)
                               let kind = _reader.GetGuid(cd.Kind)
                                          where kind == SourceLinkGuid
                                          let bl = _reader.GetBlobBytes(cd.Value)
                                                   select Encoding.UTF8.GetString(bl))
                     .FirstOrDefault();

            if (sl != null)
            {
                try
                {
                    var jobj = JObject.Parse(sl);
                    var docs = (JObject)jobj["documents"];


                    var slis = (from prop in docs.Properties()
                                select new SourceLinkMap
                    {
                        Base = prop.Name,
                        Location = prop.Value.Value <string>()
                    })
                               .ToList();

                    return(slis);
                }
                catch (JsonReaderException jse)
                {
                    throw new InvalidDataException("SourceLink data could not be parsed", jse);
                }
            }

            return(Array.Empty <SourceLinkMap>());
        }
Example #24
0
        private IReadOnlyList <SourceLinkMap> GetSourceLinkInformation()
        {
            var sl = (from cdi in _reader.CustomDebugInformation
                      let cd = _reader.GetCustomDebugInformation(cdi)
                               let kind = _reader.GetGuid(cd.Kind)
                                          where kind == SourceLinkGuid
                                          let bl = _reader.GetBlobBytes(cd.Value)
                                                   select Encoding.UTF8.GetString(bl))
                     .FirstOrDefault();

            var jobj = JObject.Parse(sl);
            var docs = (JObject)jobj["documents"];


            var slis = (from prop in docs.Properties()
                        select new SourceLinkMap
            {
                Base = prop.Name,
                Location = prop.Value.Value <string>()
            })
                       .ToList();

            return(slis);
        }
        private bool HasSourceLinkDebugInformation(MetadataReader pdbReader)
        {
            foreach (var customDebugInfoHandle in pdbReader.CustomDebugInformation)
            {
                var customDebugInfo = pdbReader.GetCustomDebugInformation(customDebugInfoHandle);
                if (pdbReader.GetGuid(customDebugInfo.Kind) == SourceLinkCustomDebugInfoGuid)
                {
                    // var sourceLinkContent = pdbReader.GetBlobBytes(customDebugInfo.Value);
                    // var sourceLinkText = System.Text.Encoding.UTF8.GetString(sourceLinkContent);
                    return(true);
                }
            }

            return(false);
        }
            public override bool TryGetDocumentChecksum(string documentPath, out ImmutableArray <byte> checksum, out Guid algorithmId)
            {
                foreach (var documentHandle in _pdbReader.Documents)
                {
                    var document = _pdbReader.GetDocument(documentHandle);
                    if (_pdbReader.StringComparer.Equals(document.Name, documentPath))
                    {
                        checksum    = _pdbReader.GetBlobContent(document.Hash);
                        algorithmId = _pdbReader.GetGuid(document.HashAlgorithm);
                        return(true);
                    }
                }

                checksum    = default;
                algorithmId = default;
                return(false);
            }
Example #27
0
        public static bool HasSourceLink(this MetadataReader reader)
        {
            foreach (var customDebugInfoHandle in reader.CustomDebugInformation)
            {
                var customDebugInfo = reader.GetCustomDebugInformation(customDebugInfoHandle);
                if (reader.GetGuid(customDebugInfo.Kind) == SourceLinkMagic)
                {
                    //var sourceLinkContent = pdbReader.GetBlobBytes(customDebugInfo.Value);
                    //var sourceLinkText = System.Text.Encoding.UTF8.GetString(sourceLinkContent);

                    //Console.WriteLine("Sourcelink: " + sourceLinkText);
                    return(true);
                }
            }

            return(false);
        }
Example #28
0
 private (bool allDocumentsMatch, string notFoundDocument) MatchDocumentsWithSources(MetadataReader metadataReader)
 {
     foreach (DocumentHandle docHandle in metadataReader.Documents)
     {
         Document document     = metadataReader.GetDocument(docHandle);
         string   docName      = _sourceRootTranslator.ResolveFilePath(metadataReader.GetString(document.Name));
         Guid     languageGuid = metadataReader.GetGuid(document.Language);
         // We verify all docs and return false if not all are present in local
         // We could have false negative if doc is not a source
         // Btw check for all possible extension could be weak approach
         // We exlude from the check the autogenerated source file(i.e. source generators)
         // We exclude special F# construct https://github.com/coverlet-coverage/coverlet/issues/1145
         if (!_fileSystem.Exists(docName) && !docName.EndsWith(".g.cs") &&
             !IsUnknownModuleInFSharpAssembly(languageGuid, docName))
         {
             return(false, docName);
         }
     }
     return(true, string.Empty);
 }
        private static string DedupeReference(string output, string referencePath)
        {
            if (dedupedReferences.ContainsKey(referencePath))
            {
                return(dedupedReferences[referencePath]);
            }
            using var file   = new FileStream(referencePath, FileMode.Open, FileAccess.Read);
            using var reader = new PEReader(file);
            MetadataReader mdReader = reader.GetMetadataReader();
            GuidHandle     handle   = mdReader.GetModuleDefinition().Mvid;
            Guid           mvid     = mdReader.GetGuid(handle);
            string         refPath  = Path.Join(output, "ref", mvid.ToString("N"), Path.GetFileName(referencePath));

            if (!File.Exists(refPath))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(refPath));
                File.Copy(referencePath, refPath);
            }

            return(dedupedReferences[referencePath] = Path.GetRelativePath(output, refPath));
        }
Example #30
0
        private string GetPDBFileName(string assemblyFile)
        {
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                return(Path.GetFileName(Path.ChangeExtension(assemblyFile, "ni.pdb")));
            }

            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                using (FileStream fs = new FileStream(assemblyFile, FileMode.Open, FileAccess.Read))
                {
                    PEReader       pereader = new PEReader(fs);
                    MetadataReader mdReader = pereader.GetMetadataReader();
                    Guid           mvid     = mdReader.GetGuid(mdReader.GetModuleDefinition().Mvid);

                    return(Path.GetFileName(Path.ChangeExtension(assemblyFile, "ni.{" + mvid + "}.map")));
                }
            }

            return(null);
        }